PyTorch 常用非线性激活函数详解
-
首先,简单复习下什么是梯度:梯度是偏微分的集合
- 举例说明:对于 z = y 2 − x 2 : ∇ z = ( ∂ z ∂ x , ∂ z ∂ y ) = ( 2 x , 2 y ) z = y^2-x^2: \nabla z= (\frac{\partial z}{\partial x}, \frac{\partial z}{\partial y}) = (2x, 2y) z=y2−x2:∇z=(∂x∂z,∂y∂z)=(2x,2y)
-
获取极小值
minima的方法核心: θ t + 1 = θ t − α ∇ f ( θ t ) \theta_{t+1}=\theta_t-\alpha\nabla f(\theta_t) θt+1=θt−α∇f(θt)
本文总结了深度学习中常见的几种激活函数,包括 Sigmoid, Tanh, ReLU, Softmax
1. Sigmoid
-
【
torch.sigmoid(x)】
Sigmoid ( x ) = 1 1 + e − x \text{Sigmoid}(x)=\frac{1}{1+e^{-x}} Sigmoid(x)=1+e−x1

- 优点:连续可导,常用作二分类输出层
- 缺点:在
|x|非常大时饱和(函数会变得很平),对x的微小改变会变得不敏感;在反向传播时,梯度趋近 0 → 容易出现 梯度消失,从而无法完成深层网络训练 - PyTorch 使用:对应类
torch.nn.Sigmoidimport torch import torch.nn as nn # 1) 准备输入 x = torch.linspace(-5, 5, 10) # 2.1) 使用方法一 out1 = torch.sigmoid(x) # 函数式 # 2.2) 使用方法二 layer = nn.Sigmoid() # 模块式 out2 = layer(x)
2. Tanh
- 【
torch.tanh(x)】 sigmoid 经过缩放平移获得
Tanh ( x ) = e x − e − x e x + e − x \text{Tanh}(x) = \frac{e^x-e^{-x}}{e^x+e^{-x}} Tanh(x)=ex+e−xex−e−x
- 优点:同 sigmoid 且均值是0 (更有利于优化)
- 缺点:仍存在
饱和问题 - PyTorch 使用:对应类
torch.nn.Tanh(layer = torch.nn.Tanh(), layer(x) )import torch import torch.nn as nn # 1) 准备输入 x = torch.linspace(-5, 5, 10) # 2.1) 使用方法一 out1 = torch.tanh(x) # 函数式 # 2.2) 使用方法二 layer = nn.Tanh() # 模块形式 out2 = layer(x)
3. ReLU
-
【
torch.relu(x)】
ReLU ( x ) = max ( 0 , x ) \text{ReLU}(x)=\max(0,x) ReLU(x)=max(0,x)

- 优点:高效;在x>0区域上,不会出现梯度饱和、梯度消失
- 缺点:
Dead ReLU Problem(在x<0时,梯度为0:这个神经元及之后的神经元梯度永远为0,不再对任何数据有所响应,导致相应参数永远不会被更新) - PyTorch 使用:对应类
torch.nn.ReLU(layer = torch.nn.ReLU(), layer(x) )import torch import torch.nn as nn # 1) 准备输入 x = torch.linspace(-5, 5, 10) # 2.1) 使用方法一 out1 = torch.relu(x) # 函数式 # 2.2) 使用方法二 layer = nn.ReLU() # 模块形式 out2 = layer(x)
4. Softmax
-
【
torch.softmax(x)】softmax 可以用作输出层 (如多分类)
Softmax ( x i ) = e x i ∑ j e x j \text{Softmax}(x_i) = \frac{e^{x_i}}{\sum_j e^{x_j}} Softmax(xi)=∑jexjexi

- 优点:将向量转为概率分布(所有元素 ∈ (0,1),且和为 1),常用于 多分类输出层
- 缺点:对极端值敏感;在某个输入过大时,分布可能过于“尖锐”
- PyTorch 使用:
import torch import torch.nn as nn # 1) 准备输入 x = torch.randn(2, 5) # 假设 batch=2, 类别=5 # 2.1) 使用方法一 out1 = torch.softmax(x, dim=1) # 函数式 # 2.2) 使用方法二 layer = nn.Softmax(dim=1) # 模块形式 out2 = layer(x)
总结
- Sigmoid:二分类常用,但易梯度消失
- Tanh:输出均值为 0,比 Sigmoid 更优,但仍有饱和问题
- ReLU:最常用,简单高效,但存在 Dead ReLU
- Softmax:多分类输出层常用,结果可解释为概率分布
1295



被折叠的 条评论
为什么被折叠?



