rust - 如何限制 Activation bar 以便我可以使用类型 <T> 的 exp () 函数?

标签 rust

我正在尝试制作一个适用于数字 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/

相关文章:

rust - 如何从 Rust 中的成员函数返回泛型类型

rust - 如何仅为具有特定项的迭代器实现迭代器适配器?

rust - 像 `n * 10^p`一样准确计算 `f64::from_str`吗?

rust - 如何调试外部库中的崩溃

nested - 无需移动即可访问嵌套结构

recursion - 递归结构错误生命周期(无法为函数调用中的生命周期参数推断适当的生命周期... [E0495])

rust - 我如何在稳定的 Rust 中使用 std::collections::BitSet?

rust - 有什么理由不对不迭代一系列事物的迭代器使用 DoubleEndedIterator 吗?

macros - 如何在 Rust 宏中匹配 "mut"?

rust - 我如何写入 Rust 中的内存映射地址?