c++ - ReLU函数在C++上的实现

标签 c++ relu

我实际上正在研究 CNN,我正在使用 Sigmoid 作为激活函数,但我想使用 ReLU。

我已经使用 Eigen 为 ReLU 实现了一个代码,但它似乎不起作用,你能帮帮我吗?

这是我的代码:

Matrix ReLu(const Matrix & x){

    Matrix A;
    for( int i = 0; i< x.rows(); ++i )
    for (int j=0; i< x.cols(); j++) {
        if (x(i,j) <= 0){
            A(i,j)=(0.0);
        }
        else A(i,j)=(x(i,j));
    }
    return std::move(A.matrix());
}

Matrix ReLu_deriv (const Matrix& y) {
    Matrix B;
    for( int i = 0; i < y.rows(); ++i )
    for (int j=0; i < y.cols() ; j++)
    {
        {
        if (y(i,j) <= 0.0){
            B(i,j)=(0.0);
        }
        else B(i,j)=(1.0);
    }
    return std::move(B.matrix());
}

错误是:

> /usr/include/eigen3/Eigen/src/Core/DenseCoeffsBase.h :365 : Eigen::DenseCoeffsBase<Derived,
> 1>::Scalar& Eigen::DenseCoeffsBase<Derived,
> 1>::operator()(Eigen::Index, Eigen::Index) [with Derived =
> Eigen::Matrix<double, -1, -1>; Eigen::DenseCoeffsBase<Derived,
> 1>::Scalar = double; Eigen::Index = long int]:  l'assertion « row >= 0
> && row < rows() && col >= 0 && col < cols() » a échoué.

最佳答案

您需要先正确初始化您的临时矩阵:

Matrix ReLu(const Matrix & x){

    Matrix A(x.rows(), x.cols());
    for( int i = 0; i< x.rows(); ++i )
    for (int j=0; j< x.cols(); ++j) {
        if (x(i,j) <= 0){
            A(i,j)=(0.0);
        }
        else A(i,j)=(x(i,j));
    }
    return std::move(A.matrix());
}

Matrix ReLu_deriv (const Matrix& y) {
    Matrix B(y.rows(), y.cols());
    for( int i = 0; i < y.rows(); ++i )
    for (int j=0; j < y.cols() ; ++j)
    {
        if (y(i,j) <= 0.0){
            B(i,j)=(0.0);
        }
        else B(i,j)=(1.0);
    }
    return std::move(B.matrix());
}

关于c++ - ReLU函数在C++上的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51209644/

相关文章:

c++ - 如何在 C++ 中获取二维动态字符串数组的维度?

c++ - 在 for 循环中使用数组 - C++

numpy - 如何使用 Numpy 函数实现泄漏的 relu

python - 神经网络类型错误: unsupported operand type(s) for +=: 'Dense' and 'str'

c++ - 读取文件时cmake设置路径

c++ - 为什么嵌套的构造函数调用不编译?

c# - 使用 AutoGen FFmpeg 库在 MP4 中同步音频/视频

neural-network - 反向传播中的 ReLU 导数

python - 当使用 .clamp 而不是 torch.relu 时,Pytorch Autograd 会给出不同的渐变