我正在尝试制作一个适用于数字 f32 和 f64 的 sigmoid 函数。
此代码出现错误 - 在当前范围内未找到类型 & T
的名为 exp
的方法。
我想我知道为什么会这样,我想向编译器解释数字将是 F32 和 F64,但我不知道如何解释。对不起我的英语。
pub trait Activation<T> {
fn compute(&self,input:&Vec<T>) -> Vec<T>;
}
pub struct Sigmoid {}
impl Sigmoid {
pub fn new() -> Sigmoid {
Sigmoid{}
}
}
impl<T> Activation<T> for Sigmoid {
fn compute(&self, input: &Vec<T>) -> Vec<> {
let mut out:Vec<T> = vec![];
for (i,v) in input.iter().enumerate() {
let mut z = *v.exp() ;
out.push(z);
}
out
}
}
最佳答案
看起来你可以使用 num_traits 箱子:
use num_traits::float::Float;
pub trait Activation<T: Float> {
fn compute(&self, input: &Vec<T>) -> Vec<T>;
}
pub struct Sigmoid {}
impl Sigmoid {
pub fn new() -> Sigmoid {
Sigmoid {}
}
}
impl<T> Activation<T> for Sigmoid
where T: Float {
fn compute(&self, input: &Vec<T>) -> Vec<T> {
let mut out: Vec<T> = vec![];
for (_, v) in input.iter().enumerate() {
let z = v.exp();
out.push(z);
}
out
}
}
你也可以在没有 num crate 的情况下实现它,但它有点丑陋:
pub trait LocalFloat {
fn exp(self) -> Self;
}
impl LocalFloat for f32 {
fn exp(self) -> Self {
f32::exp(self)
}
}
impl LocalFloat for f64 {
fn exp(self) -> Self {
f64::exp(self)
}
}
pub trait Activation<T: LocalFloat> {
fn compute(&self, input: &Vec<T>) -> Vec<T>;
}
pub struct Sigmoid {}
impl Sigmoid {
pub fn new() -> Sigmoid {
Sigmoid {}
}
}
impl<T> Activation<T> for Sigmoid
where T: LocalFloat + Copy {
fn compute(&self, input: &Vec<T>) -> Vec<T> {
let mut out: Vec<T> = vec![];
for (_, v) in input.iter().enumerate() {
let z = v.exp();
out.push(z);
}
out
}
}
关于rust - 如何限制 Activation bar 以便我可以使用类型 <T> 的 exp () 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58987875/