学习笔记: 源码 multinomial_logistic_loss_layer.cpp 略晓

MultinomialLogisticLossLayer

对数损失函数: L = -log(P(Y|X))

softmax 的损失函数如下:


在处理分类问题的时候,当前一层输出了每一类的概率,那么则可以利用 MultinomialLogisticLossLayer 来计算 loss。

1. forward()
template <typename Dtype>
void MultinomialLogisticLossLayer<Dtype>::Forward_cpu(
...
  Dtype loss = 0;
  for (int i = 0; i < num; ++i) {
    int label = static_cast<int>(bottom_label[i]);
    Dtype prob = std::max(
        bottom_data[i * dim + label], Dtype(kLOG_THRESHOLD)); //kLOG_THRESHOLD = 1e-20;
    loss -= log(prob);  // 累加
  }
  top[0]->mutable_cpu_data()[0] = loss / num;  // 再求平均
}

2. backward()
template <typename Dtype>
void MultinomialLogisticLossLayer<Dtype>::Backward_cpu(
    const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down,
    const vector<Blob<Dtype>*>& bottom) {
...
    caffe_set(bottom[0]->count(), Dtype(0), bottom_diff);  //除了 label 对应的bottom 项,其余bottom_diff 为 0  
    const Dtype scale = - top[0]->cpu_diff()[0] / num; // 此处top_diff = loss weight = 1, 则scale = -1/N
    for (int i = 0; i < num; ++i) {
      int label = static_cast<int>(bottom_label[i]);
      Dtype prob = std::max(
          bottom_data[i * dim + label], Dtype(kLOG_THRESHOLD));
      bottom_diff[i * dim + label] = scale / prob;
} } }

假设输入为a, 输出为 z. 前向和后向公式分别如下:

其中 有N个样本,K个类别。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值