caffe代码分析(1)

caff中的softmaxlayer前向传播公式如下[在这里插入图片描述]在这里插入图片描述
代码Forward_cpu分析如下:

void SoftmaxLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
    const vector<Blob<Dtype>*>& top) {
  const Dtype* bottom_data = bottom[0]->cpu_data(); //获取bottom层数据 假设bottom_data维数为100×10,展开维度为1000
  Dtype* top_data = top[0]->mutable_cpu_data(); //获取top层数据指针
  Dtype* scale_data = scale_.mutable_cpu_data();//获取scale层指针,其实作用为中间变量
  int channels = bottom[0]->shape(softmax_axis_);//获取bottom数据的列数
  int dim = bottom[0]->count() / outer_num_;// 获取bottom数据行数
  caffe_copy(bottom[0]->count(), bottom_data, top_data);//将bottom_data数据复制给top_data
  // We need to subtract the max to avoid numerical issues, compute the exp,
  // and then normalize.
  for (int i = 0; i < outer_num_; ++i) {
    // initialize scale_data to the first plane
    caffe_copy(inner_num_, bottom_data + i * dim, scale_data);
    for (int j = 0; j < channels; j++) {
      for (int k = 0; k < inner_num_; k++) {
        scale_data[k] = std::max(scale_data[k],
            bottom_data[i * dim + j * inner_num_ + k]);  //获取bottom_data中每一行最大数值
      }
    }
    // subtraction
    caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans, channels, inner_num_,
        1, -1., sum_multiplier_.cpu_data(), scale_data, 1., top_data);//将bottom_data中每一行数据减去对应行中的最大值,后赋值给top_data
    // exponentiation
    caffe_exp<Dtype>(dim, top_data, top_data);//对top_data一行每一个数采用exp指数函数计算获取数值
    // sum after exp
    caffe_cpu_gemv<Dtype>(CblasTrans, channels, inner_num_, 1.,
        top_data, sum_multiplier_.cpu_data(), 0., scale_data);//对top_data每一行进行求和
    // division
    for (int j = 0; j < channels; j++) {
      caffe_div(inner_num_, top_data, scale_data, top_data);//将top_data的每一个数除以对应行的总和
      top_data += inner_num_;// 地址加1,变换成下一个数的地址
    }
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值