Softmax与SoftmaxWithLoss原理及代码详解

2024-08-24 18:08

本文主要是介绍Softmax与SoftmaxWithLoss原理及代码详解,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一直对softmax的反向传播的caffe代码看不懂,最近在朱神的数学理论支撑下给我详解了它的数学公式,才豁然开朗

SoftmaxWithLoss的由来

SoftmaxWithLoss也被称为交叉熵loss。
回忆一下交叉熵的公式, H(p,q)=jpjlogqj H ( p , q ) = − ∑ j p j log ⁡ q j ,其中向量 p p 是原始的分布,这里指的是 ground-truth label,具体是 One-hot 编码结果。q则是模型预测的输出,且 qj=efjjefj q j = e f j ∑ j e f j ,由于 p p 是one-hot向量,里面一堆的零只有 label 那项会保留下来,即H(p,q)=plabellogqlabel=logqlabel=eflabeljefj

再考虑交叉熵,因为 H(p,q)=H(p)+DKL(pq) H ( p , q ) = H ( p ) + D K L ( p ‖ q ) ( 交叉熵= KL散度 + 熵),而 H(p)=0 H ( p ) = 0 ,所以最小化交叉熵,其实就是最小化 KLKL 散度,也就是想让两个分布尽量相同。

上面是信息论的角度来看 Softmax,其实也可以用概率的角度来解释,即把结果看做是对每个类别预测分类的概率值, p(yi|xi;W)=efyijefj p ( y i | x i ; W ) = e f y i ∑ j e f j ,因为有归一化的步骤,所以可以看做合法的概率值。

Softmax

公式推导:

softmax

// top_diff是下一层传过来的梯度,bottom_diff是该层往前反传的梯度
// top_data是该层输出到下一层的结果
template <typename Dtype>
void SoftmaxLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,const vector<bool>& propagate_down,const vector<Blob<Dtype>*>& bottom) {const Dtype* top_diff = top[0]->cpu_diff();const Dtype* top_data = top[0]->cpu_data();Dtype* bottom_diff = bottom[0]->mutable_cpu_diff();Dtype* scale_data = scale_.mutable_cpu_data();int channels = top[0]->shape(softmax_axis_);int dim = top[0]->count() / outer_num_;// bottom_diff = top_diff而top_diff是dloss/da(见我手写的公式推导) shape: Cx1caffe_copy(top[0]->count(), top_diff, bottom_diff);for (int i = 0; i < outer_num_; ++i) {// compute dot(top_diff, top_data) and subtract them from the bottom diff// dloss/da和a的内积(见我手写的公式推导),scale_data保存了该内积for (int k = 0; k < inner_num_; ++k) {scale_data[k] = caffe_cpu_strided_dot<Dtype>(channels,bottom_diff + i * dim + k, inner_num_,top_data + i * dim + k, inner_num_);}// subtraction// sum_multiplier_.cpu_data()由Reshape函数定义了该向量,shape: C×1,值都为1// 作用是把dloss/da和a的内积这个标量变成Cx1的行向量// bottom_diff = -1*sum_multiplier_.cpu_data()*scale_data+bottom_diff 大括号里的减法caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans, channels, inner_num_, 1,-1., sum_multiplier_.cpu_data(), scale_data, 1., bottom_diff + i * dim);}// elementwise multiplication// 大括号外的对应元素相乘caffe_mul(top[0]->count(), bottom_diff, top_data, bottom_diff);
}

SoftmaxWithLoss

公式推导:

softmaxwithloss

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();// 梯度全部设为: ak(见我手写的公式推导)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]);// 设置ignor_label的地方,梯度设为0if (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 {// 在k==y的地方把梯度改为: ak-1(见我手写的公式推导)bottom_diff[i * dim + label_value * inner_num_ + j] -= 1;++count;}}}// Scale gradientDtype loss_weight = top[0]->cpu_diff()[0] /get_normalizer(normalization_, count);caffe_scal(prob_.count(), loss_weight, bottom_diff);}
}

Softmax注意点

Softmax前传时有求指数的操作,如果z很小或者很大,很容易发生float/double的上溢和下溢。这个问题其实也是有解决办法的,caffe源码中求 exponential 之前将z的每一个元素减去z分量中的最大值。这样求 exponential 的时候会碰到的最大的数就是 0 了,不会发生 overflow 的问题,但是如果其他数原本是正常范围,现在全部被减去了一个非常大的数,于是都变成了绝对值非常大的负数,所以全部都会发生 underflow,但是 underflow 的时候得到的是 0,这其实是非常 meaningful 的近似值,而且后续的计算也不会出现奇怪的 NaN。

详情参考这篇博客Softmax vs. Softmax-Loss: Numerical Stability

template <typename Dtype>
void SoftmaxLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,const vector<Blob<Dtype>*>& top) {const Dtype* bottom_data = bottom[0]->cpu_data();Dtype* top_data = top[0]->mutable_cpu_data();Dtype* scale_data = scale_.mutable_cpu_data();int channels = bottom[0]->shape(softmax_axis_);int dim = bottom[0]->count() / outer_num_;caffe_copy(bottom[0]->count(), 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// 计算z分量中的最大值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]);}}// subtractioncaffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans, channels, inner_num_,1, -1., sum_multiplier_.cpu_data(), scale_data, 1., top_data);// exponentiationcaffe_exp<Dtype>(dim, top_data, top_data);// sum after expcaffe_cpu_gemv<Dtype>(CblasTrans, channels, inner_num_, 1.,top_data, sum_multiplier_.cpu_data(), 0., scale_data);// divisionfor (int j = 0; j < channels; j++) {caffe_div(inner_num_, top_data, scale_data, top_data);top_data += inner_num_;}}
}

参考博客

  • 深度学习笔记8:softmax层的实现
  • Caffe Softmax层的实现原理?
  • cs231n 课程作业 Assignment 1
  • pytorch loss function 总结
  • 微调的回答: 为什么交叉熵(cross-entropy)可以用于计算代价?

这篇关于Softmax与SoftmaxWithLoss原理及代码详解的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1103211

相关文章

Debezium 与 Apache Kafka 的集成方式步骤详解

《Debezium与ApacheKafka的集成方式步骤详解》本文详细介绍了如何将Debezium与ApacheKafka集成,包括集成概述、步骤、注意事项等,通过KafkaConnect,D... 目录一、集成概述二、集成步骤1. 准备 Kafka 环境2. 配置 Kafka Connect3. 安装 D

Java中ArrayList和LinkedList有什么区别举例详解

《Java中ArrayList和LinkedList有什么区别举例详解》:本文主要介绍Java中ArrayList和LinkedList区别的相关资料,包括数据结构特性、核心操作性能、内存与GC影... 目录一、底层数据结构二、核心操作性能对比三、内存与 GC 影响四、扩容机制五、线程安全与并发方案六、工程

Java调用DeepSeek API的最佳实践及详细代码示例

《Java调用DeepSeekAPI的最佳实践及详细代码示例》:本文主要介绍如何使用Java调用DeepSeekAPI,包括获取API密钥、添加HTTP客户端依赖、创建HTTP请求、处理响应、... 目录1. 获取API密钥2. 添加HTTP客户端依赖3. 创建HTTP请求4. 处理响应5. 错误处理6.

Spring Cloud LoadBalancer 负载均衡详解

《SpringCloudLoadBalancer负载均衡详解》本文介绍了如何在SpringCloud中使用SpringCloudLoadBalancer实现客户端负载均衡,并详细讲解了轮询策略和... 目录1. 在 idea 上运行多个服务2. 问题引入3. 负载均衡4. Spring Cloud Load

Springboot中分析SQL性能的两种方式详解

《Springboot中分析SQL性能的两种方式详解》文章介绍了SQL性能分析的两种方式:MyBatis-Plus性能分析插件和p6spy框架,MyBatis-Plus插件配置简单,适用于开发和测试环... 目录SQL性能分析的两种方式:功能介绍实现方式:实现步骤:SQL性能分析的两种方式:功能介绍记录

在 Spring Boot 中使用 @Autowired和 @Bean注解的示例详解

《在SpringBoot中使用@Autowired和@Bean注解的示例详解》本文通过一个示例演示了如何在SpringBoot中使用@Autowired和@Bean注解进行依赖注入和Bean... 目录在 Spring Boot 中使用 @Autowired 和 @Bean 注解示例背景1. 定义 Stud

使用 sql-research-assistant进行 SQL 数据库研究的实战指南(代码实现演示)

《使用sql-research-assistant进行SQL数据库研究的实战指南(代码实现演示)》本文介绍了sql-research-assistant工具,该工具基于LangChain框架,集... 目录技术背景介绍核心原理解析代码实现演示安装和配置项目集成LangSmith 配置(可选)启动服务应用场景

如何通过海康威视设备网络SDK进行Java二次开发摄像头车牌识别详解

《如何通过海康威视设备网络SDK进行Java二次开发摄像头车牌识别详解》:本文主要介绍如何通过海康威视设备网络SDK进行Java二次开发摄像头车牌识别的相关资料,描述了如何使用海康威视设备网络SD... 目录前言开发流程问题和解决方案dll库加载不到的问题老旧版本sdk不兼容的问题关键实现流程总结前言作为

SQL 中多表查询的常见连接方式详解

《SQL中多表查询的常见连接方式详解》本文介绍SQL中多表查询的常见连接方式,包括内连接(INNERJOIN)、左连接(LEFTJOIN)、右连接(RIGHTJOIN)、全外连接(FULLOUTER... 目录一、连接类型图表(ASCII 形式)二、前置代码(创建示例表)三、连接方式代码示例1. 内连接(I

Python中顺序结构和循环结构示例代码

《Python中顺序结构和循环结构示例代码》:本文主要介绍Python中的条件语句和循环语句,条件语句用于根据条件执行不同的代码块,循环语句用于重复执行一段代码,文章还详细说明了range函数的使... 目录一、条件语句(1)条件语句的定义(2)条件语句的语法(a)单分支 if(b)双分支 if-else(