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

相关文章

C++11范围for初始化列表auto decltype详解

《C++11范围for初始化列表autodecltype详解》C++11引入auto类型推导、decltype类型推断、统一列表初始化、范围for循环及智能指针,提升代码简洁性、类型安全与资源管理效... 目录C++11新特性1. 自动类型推导auto1.1 基本语法2. decltype3. 列表初始化3

Spring Security 单点登录与自动登录机制的实现原理

《SpringSecurity单点登录与自动登录机制的实现原理》本文探讨SpringSecurity实现单点登录(SSO)与自动登录机制,涵盖JWT跨系统认证、RememberMe持久化Token... 目录一、核心概念解析1.1 单点登录(SSO)1.2 自动登录(Remember Me)二、代码分析三、

SQL Server 中的 WITH (NOLOCK) 示例详解

《SQLServer中的WITH(NOLOCK)示例详解》SQLServer中的WITH(NOLOCK)是一种表提示,等同于READUNCOMMITTED隔离级别,允许查询在不获取共享锁的情... 目录SQL Server 中的 WITH (NOLOCK) 详解一、WITH (NOLOCK) 的本质二、工作

springboot自定义注解RateLimiter限流注解技术文档详解

《springboot自定义注解RateLimiter限流注解技术文档详解》文章介绍了限流技术的概念、作用及实现方式,通过SpringAOP拦截方法、缓存存储计数器,结合注解、枚举、异常类等核心组件,... 目录什么是限流系统架构核心组件详解1. 限流注解 (@RateLimiter)2. 限流类型枚举 (

Java Thread中join方法使用举例详解

《JavaThread中join方法使用举例详解》JavaThread中join()方法主要是让调用改方法的thread完成run方法里面的东西后,在执行join()方法后面的代码,这篇文章主要介绍... 目录前言1.join()方法的定义和作用2.join()方法的三个重载版本3.join()方法的工作原

Spring AI使用tool Calling和MCP的示例详解

《SpringAI使用toolCalling和MCP的示例详解》SpringAI1.0.0.M6引入ToolCalling与MCP协议,提升AI与工具交互的扩展性与标准化,支持信息检索、行动执行等... 目录深入探索 Spring AI聊天接口示例Function CallingMCPSTDIOSSE结束语

C语言进阶(预处理命令详解)

《C语言进阶(预处理命令详解)》文章讲解了宏定义规范、头文件包含方式及条件编译应用,强调带参宏需加括号避免计算错误,头文件应声明函数原型以便主函数调用,条件编译通过宏定义控制代码编译,适用于测试与模块... 目录1.宏定义1.1不带参宏1.2带参宏2.头文件的包含2.1头文件中的内容2.2工程结构3.条件编

PyTorch中的词嵌入层(nn.Embedding)详解与实战应用示例

《PyTorch中的词嵌入层(nn.Embedding)详解与实战应用示例》词嵌入解决NLP维度灾难,捕捉语义关系,PyTorch的nn.Embedding模块提供灵活实现,支持参数配置、预训练及变长... 目录一、词嵌入(Word Embedding)简介为什么需要词嵌入?二、PyTorch中的nn.Em

Python Web框架Flask、Streamlit、FastAPI示例详解

《PythonWeb框架Flask、Streamlit、FastAPI示例详解》本文对比分析了Flask、Streamlit和FastAPI三大PythonWeb框架:Flask轻量灵活适合传统应用... 目录概述Flask详解Flask简介安装和基础配置核心概念路由和视图模板系统数据库集成实际示例Stre

Spring Bean初始化及@PostConstruc执行顺序示例详解

《SpringBean初始化及@PostConstruc执行顺序示例详解》本文给大家介绍SpringBean初始化及@PostConstruc执行顺序,本文通过实例代码给大家介绍的非常详细,对大家的... 目录1. Bean初始化执行顺序2. 成员变量初始化顺序2.1 普通Java类(非Spring环境)(