caffe2中Loss层解析-以一个简单的loss函数为例

此为caffe里比较简单的sigmoid函数的定义,位于
your path/src/caffe/layers/sigmoid_layer.cpp

#include <cmath>
#include <vector>

#include "caffe/layers/sigmoid_layer.hpp"

namespace caffe 
{

template <typename Dtype>
inline Dtype sigmoid(Dtype x) 
{
	return 1. / (1. + exp(-x));
}

template <typename Dtype>
void SigmoidLayer<Dtype>::Forward_cpu(
const vector<Blob<Dtype>*>& bottom,const vector<Blob<Dtype>*>& top) 
{
	//bottom[0]->cpu_data()为前一层传入的激活值
	const Dtype* bottom_data = bottom[0]->cpu_data();
	//top[0]->mutable_cpu_data()拿到了传到前一层的数值所存的地址
	Dtype* top_data = top[0]->mutable_cpu_data();
	const int count = bottom[0]->count();
	//把要输入下一层的激活值进行赋值
	for (int i = 0; i < count; ++i) 
    {
        top_data[i] = sigmoid(bottom_data[i]);
    }
}

template <typename Dtype>
void SigmoidLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
    const vector<bool>& propagate_down,const vector<Blob<Dtype>*>& bottom) 
{
	/*现在为反向传播,所以现在是有top输入,输出到bottom*/
    if (propagate_down[0]) 
    {
        const Dtype* top_data = top[0]->cpu_data();
        //top[0]->cpu_diff()此为后一层神经元反向传播时计算出的梯度值
        const Dtype* top_diff = top[0]->cpu_diff();
        //同样是取到了存放输出梯度值的地址
        Dtype* bottom_diff = bottom[0]->mutable_cpu_diff();
        //count为输出梯度值的数量
        const int count = bottom[0]->count();
        //对所有的梯度值赋值
        for (int i = 0; i < count; ++i) 
	    {
            const Dtype sigmoid_x = top_data[i];
            bottom_diff[i] = top_diff[i] * sigmoid_x * (1. - sigmoid_x);
        }
    } 
}

#ifdef CPU_ONLY
STUB_GPU(SigmoidLayer);
#endif

INSTANTIATE_CLASS(SigmoidLayer);


}  // namespace caffe
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值