文章标题

caffe Layer 源码分三个文件,hpp、cpp、cu.
SoftmaxLoss的数学公式参考 caffe层解读系列-softmax_loss

其实SoftmaxLossLayer(下面简称SL)封装了一个SoftmaxLayer(下面简称S)为他完成一部分计算,我们可以看到:

  1. LayerSetUp时:
    创建了S(SoftmaxLayer)对象;SL的输入bottom[0] (一般是fc层的结果) 直接作为S的输入;S的输出定义为prob_。
  2. ReShape为输出申请内存和改变维度时,调用S层ReShape为prob_申请内存并改变维度,
    因为SL的输出是一个数字(scalar),在父类LossLayer中的ReShape中已申请了内存。
  3. Forward时,调用S层的Forward计算出prob_,再根据prob_和label计算出loss(SL_top[0]),
    如果有第二个输出SL_top[1]的话,它是ShareData(prob_)的,所以不需要申请新内存。
SL_bottom[0] -- S_bottom --> S_top(prob_) --|--> SL_top[1] (如果有第二个输出的话)
                                            |--> SL_top[0]
SL_bottom[1](label)                     ----|

{caffe_master}/src/caffe/layers/softmax_loss_layer.cpp

namespace caffe {
/**
1. 调用父类函数
2. 创建一个SoftmaxLayer,

   这里也可以看到一个Layer的创建主要过程是下面几个步骤:
   a. 工厂模式创建, 需要对应层的param对象
   b. SetUp该层的bottom和top数据对象
3. 解析并处理该层需要的param。
   param的定义在caffe.proto中,protobuf会根据该文件生成相应的参数类,
   参数解析的工作由该类完成,所以我们使用时可以直接看到对应的属性。
*/
template <typename Dtype>
void SoftmaxWithLossLayer<Dtype>::LayerSetUp(
    const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) {
  LossLayer<Dtype>::LayerSetUp(bottom, top);
  LayerParameter softmax_param(this->layer_param_);
  softmax_param.set_type("Softmax");
  softmax_layer_ = LayerRegistry<Dtype>::CreateLayer(softmax_param);
  softmax_bottom_vec_.clear();
  softmax_bottom_vec_.push_back(bottom[0]);
  softmax_top_vec_.clear();
  softmax_top_vec_.push_back(&prob_);
  softmax_layer_->SetUp(softmax_bottom_vec_, softmax_top_vec_);

  has_ignore_label_ =
    this->layer_param_.loss_param().has_ignore_label();
  if (has_ignore_label_) {
    ignore_label_ = this->layer_param_.loss_param().ignore_label();
  }
  if (!this->layer_param_.loss_param().has_normalization() &&
      this->layer_param_.loss_param().has_normalize()) {
    normalization_ = this->layer_param_.loss_param().normalize() ?
                     LossParameter_NormalizationMode_VALID :
                     LossParameter_NormalizationMode_BATCH_SIZE;
  } else {
    normalization_ = this->layer_param_.loss_param().normalization();
  }
}

/**
Layer需要ReShape的时候只有:输入的bottom数据的shape改变了,对应的top的shape也要跟着变。
或者第一次调用时用于给top申请内存,因为该函数还有申请内存的作用。
注意reshape只能为top里的每一个输出分配内存,而不能改变top里输出的个数,这个应该是创建该layer的时候就被定义的。
1. 调用父类函数
2. 调用S的ReShape函数
3. reshape的合理性检查 (CanonicalAxisIndex将负数通过加上count获取对应的正数索引)
   对于分类问题,softmax_axis_默认为1,也就是channel(以为SL层的上一层一般是fc层(n,c,1,1)),channel每一维都是相应类的概率
   这里的outer_num_=n,inner_num_=1*1=1
4. 改变该层需要改变的输出的shape
*/
template <typename Dtype>
void SoftmaxWithLossLayer<Dtype>::Reshape(
    const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) {
  LossLayer<Dtype>::Reshape(bottom, top);
  softmax_layer_->Reshape(softmax_bottom_vec_, softmax_top_vec_);
  softmax_axis_ =
      bottom[0]->CanonicalAxisIndex(this->layer_param_.softmax_param().axis());
  outer_num_ = bottom[0]->count(0, softmax_axis_);
  inner_num_ = bottom[0]->count(softmax_axis_ + 1);
  CHECK_EQ(outer_num_ * inner_num_, bottom[1]->count())
      << "Number of labels must match number of predictions; "
      << "e.g., if softmax axis == 1 and prediction shape is (N, C, H, W), "
      << "label count (number of labels) must be N*H*W, "
      << "with integer values in {0, 1, ..., C-1}.";
  if (top.size() >= 2) {
    // softmax output
    top[1]->ReshapeLike(*bottom[0]);
  }
}

/**
根据参数选择正则化方法
*/
template <typename Dtype>
Dtype SoftmaxWithLossLayer<Dtype>::get_normalizer(
    LossParameter_NormalizationMode normalization_mode, int valid_count) {
  Dtype normalizer;
  switch (normalization_mode) {
    case LossParameter_NormalizationMode_FULL:
      normalizer = Dtype(outer_num_ * inner_num_);
      break;
    case LossParameter_NormalizationMode_VALID:
      if (valid_count == -1) {
        normalizer = Dtype(outer_num_ * inner_num_);
      } else {
        normalizer = Dtype(valid_count);
      }
      break;
    case LossParameter_NormalizationMode_BATCH_SIZE:
      normalizer = Dtype(outer_num_);
      break;
    case LossParameter_NormalizationMode_NONE:
      normalizer = Dtype(1);
      break;
    default:
      LOG(FATAL) << "Unknown normalization mode: "
          << LossParameter_NormalizationMode_Name(normalization_mode);
  }
  // Some users will have no labels for some examples in order to 'turn off' a
  // particular loss in a multi-task setup. The max prevents NaNs in that case.
  return std::max(Dtype(1.0), normalizer);
}

/**
调用S层的Forward计算出prob_,再根据prob_和label计算出loss(SL_top[0]).
outer_num_ = n, inner_num_ = 1
*/
template <typename Dtype>
void SoftmaxWithLossLayer<Dtype>::Forward_cpu(
    const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) {
  // The forward pass computes the softmax prob values.
  softmax_layer_->Forward(softmax_bottom_vec_, softmax_top_vec_);
  const Dtype* prob_data = prob_.cpu_data();
  const Dtype* label = bottom[1]->cpu_data();
  int dim = prob_.count() / outer_num_;
  int count = 0;
  Dtype loss = 0;
  for (int i = 0; i < outer_num_; ++i) {
    for (int j = 0; j < inner_num_; j++) {
      const int label_value = static_cast<int>(label[i * inner_num_ + j]);
      if (has_ignore_label_ && label_value == ignore_label_) {
        continue;
      }
      DCHECK_GE(label_value, 0);
      DCHECK_LT(label_value, prob_.shape(softmax_axis_));
      loss -= log(std::max(prob_data[i * dim + label_value * inner_num_ + j],
                           Dtype(FLT_MIN)));
      ++count;
    }
  }
  top[0]->mutable_cpu_data()[0] = loss / get_normalizer(normalization_, count);
  if (top.size() == 2) {
    top[1]->ShareData(prob_);
  }
}

/**
根据上面链接中SL的公式, S层其实是激活函数,先指数再归一化 p 。由于减掉一个常数,导数不变,
所以这里推导数时不减 max(x[1...C]), x[1...c]是SL的上一层(fc层)的输出
p[i] = e^x[i] (i=1...C);  p[i] = p[i]/sum(P[1...C])
SL的loss计算公式为:
loss = -log(p[l]) (l为lable对应的类别号)
可以求导得到回传倒上一层(fc层)各节点的误差:
loss(x[i])' = p[i] (i!=l)
loss(x[l])' = p[l] - 1
*/
template <typename Dtype>
void SoftmaxWithLossLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
    const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {
  if (propagate_down[1]) {
    LOG(FATAL) << this->type()
               << " Layer cannot backpropagate to label inputs.";
  }
  if (propagate_down[0]) {
    Dtype* bottom_diff = bottom[0]->mutable_cpu_diff();
    const Dtype* prob_data = prob_.cpu_data();
    caffe_copy(prob_.count(), prob_data, bottom_diff);
    const Dtype* label = bottom[1]->cpu_data();
    int dim = prob_.count() / outer_num_;
    int count = 0;
    for (int i = 0; i < outer_num_; ++i) {
      for (int j = 0; j < inner_num_; ++j) {
        const int label_value = static_cast<int>(label[i * inner_num_ + j]);
        if (has_ignore_label_ && label_value == ignore_label_) {
          for (int c = 0; c < bottom[0]->shape(softmax_axis_); ++c) {
            bottom_diff[i * dim + c * inner_num_ + j] = 0;
          }
        } else {
          bottom_diff[i * dim + label_value * inner_num_ + j] -= 1;
          ++count;
        }
      }
    }
    // Scale gradient
    Dtype loss_weight = top[0]->cpu_diff()[0] /
                        get_normalizer(normalization_, count);
    caffe_scal(prob_.count(), loss_weight, bottom_diff);
  }
}

#ifdef CPU_ONLY
STUB_GPU(SoftmaxWithLossLayer);
#endif

INSTANTIATE_CLASS(SoftmaxWithLossLayer);
REGISTER_LAYER_CLASS(SoftmaxWithLoss);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值