3.2

激活函数详解

为什么需要激活函数

激活函数为神经网络引入非线性,使其能够学习复杂的模式。如果没有激活函数,多层神经网络就等价于单层线性模型。

常用激活函数

Sigmoid 函数

σ(x) = 1 / (1 + e^(-x))

特点:输出范围 (0, 1),常用于二分类输出层

缺点:梯度消失、输出不以零为中心

Tanh 函数

tanh(x) = (e^x - e^(-x)) / (e^x + e^(-x))

特点:输出范围 (-1, 1),零中心

缺点:仍存在梯度消失问题

ReLU 函数

ReLU(x) = max(0, x)

特点:计算简单、收敛快、缓解梯度消失

缺点:可能出现"神经元死亡"

Leaky ReLU

LeakyReLU(x) = max(0.01x, x)

特点:解决 ReLU 的神经元死亡问题

优势:负值也有梯度

PyTorch 中的激活函数

import torch
import torch.nn as nn

# 创建输入张量
x = torch.tensor([-2.0, -1.0, 0.0, 1.0, 2.0])

# Sigmoid
sigmoid = nn.Sigmoid()
print("Sigmoid:", sigmoid(x))
# tensor([0.1192, 0.2689, 0.5000, 0.7311, 0.8808])

# Tanh
tanh = nn.Tanh()
print("Tanh:", tanh(x))
# tensor([-0.9640, -0.7616, 0.0000, 0.7616, 0.9640])

# ReLU
relu = nn.ReLU()
print("ReLU:", relu(x))
# tensor([0., 0., 0., 1., 2.])

# Leaky ReLU
leaky_relu = nn.LeakyReLU(negative_slope=0.01)
print("Leaky ReLU:", leaky_relu(x))
# tensor([-0.0200, -0.0100, 0.0000, 1.0000, 2.0000])

# Softmax (用于多分类输出层)
softmax = nn.Softmax(dim=0)
print("Softmax:", softmax(x))
# tensor([0.0116, 0.0316, 0.0861, 0.2341, 0.6366])

如何选择激活函数

层类型 推荐激活函数 原因
隐藏层 ReLU 或 Leaky ReLU 计算快速、训练稳定
二分类输出层 Sigmoid 输出范围 (0, 1),表示概率
多分类输出层 Softmax 输出概率分布,和为 1
回归输出层 无(线性) 输出任意实数值

激活函数的可视化

绘制激活函数曲线

import torch
import matplotlib.pyplot as plt
import numpy as np

x = torch.linspace(-5, 5, 100)

# 计算各种激活函数
sigmoid = torch.sigmoid(x)
tanh = torch.tanh(x)
relu = torch.relu(x)
leaky_relu = torch.nn.functional.leaky_relu(x, negative_slope=0.1)

# 绘图
plt.figure(figsize=(12, 4))

plt.subplot(1, 4, 1)
plt.plot(x.numpy(), sigmoid.numpy())
plt.title('Sigmoid')
plt.grid(True)

plt.subplot(1, 4, 2)
plt.plot(x.numpy(), tanh.numpy())
plt.title('Tanh')
plt.grid(True)

plt.subplot(1, 4, 3)
plt.plot(x.numpy(), relu.numpy())
plt.title('ReLU')
plt.grid(True)

plt.subplot(1, 4, 4)
plt.plot(x.numpy(), leaky_relu.numpy())
plt.title('Leaky ReLU')
plt.grid(True)

plt.tight_layout()
plt.show()

✏️ 课堂练习

在深度神经网络的隐藏层中,最常用的激活函数是?