神经网络基础概念
约 1443 字大约 5 分钟
neural-networkdeep-learning
2025-08-28
神经网络是深度学习的基石,其核心思想源于对生物神经元的数学建模。本文系统介绍感知机、激活函数、前向/反向传播、梯度下降、损失函数以及关键正则化技术。
感知机(Perceptron)
感知机是最简单的神经网络单元,接收多个输入,经过加权求和与激活函数后输出结果。
import torch
import torch.nn as nn
# 单个感知机
class Perceptron(nn.Module):
def __init__(self, input_dim):
super().__init__()
self.linear = nn.Linear(input_dim, 1)
self.activation = nn.Sigmoid()
def forward(self, x):
return self.activation(self.linear(x))
# 使用
model = Perceptron(input_dim=3)
x = torch.tensor([1.0, 2.0, 3.0])
output = model(x)多层感知机(MLP)通过堆叠多个感知机层解决了单层感知机无法处理非线性可分问题(如 XOR)的局限。
激活函数
激活函数引入非线性,使网络能拟合复杂的映射关系。
ReLU(Rectified Linear Unit)
ReLU 定义为 f(x) = max(0, x)。优点是计算简单、缓解梯度消失。缺点是存在"死神经元"问题(输入恒负时梯度为 0)。变体包括 Leaky ReLU 和 PReLU。
Sigmoid
Sigmoid 将输入映射到 (0, 1) 区间,常用于二分类输出层。缺点是梯度消失严重、输出非零中心化。
Tanh
Tanh 将输入映射到 (-1, 1) 区间,解决了 Sigmoid 非零中心化的问题,但仍存在梯度消失。
GELU(Gaussian Error Linear Unit)
GELU 是 BERT、GPT 等 Transformer 模型的标准激活函数,提供了平滑的非线性。其定义为输入 x 乘以标准正态分布的累积分布函数值。
# PyTorch 中使用各种激活函数
relu = nn.ReLU()
sigmoid = nn.Sigmoid()
tanh = nn.Tanh()
gelu = nn.GELU()
# 在模型中组合使用
class MLP(nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim):
super().__init__()
self.fc1 = nn.Linear(input_dim, hidden_dim)
self.fc2 = nn.Linear(hidden_dim, output_dim)
self.gelu = nn.GELU()
def forward(self, x):
x = self.gelu(self.fc1(x))
return self.fc2(x)前向传播与反向传播
前向传播按层顺序计算每一层的输出,最终得到预测值和损失。反向传播利用链式法则从损失函数出发,逐层反向计算每个参数的梯度。
# PyTorch 自动微分示例
x = torch.randn(32, 10) # batch_size=32, features=10
y = torch.randint(0, 2, (32, 1)).float()
model = MLP(10, 64, 1)
criterion = nn.BCEWithLogitsLoss()
# 前向传播
output = model(x)
loss = criterion(output, y)
# 反向传播(自动计算梯度)
loss.backward()
# 查看梯度
print(model.fc1.weight.grad.shape) # torch.Size([64, 10])梯度下降优化器
SGD(随机梯度下降)
最基础的优化器,每次用一个 mini-batch 估计梯度并更新参数。可加入动量(Momentum)来加速收敛并抑制震荡。
Adam
结合了 Momentum(一阶矩估计)和 RMSProp(二阶矩估计),自适应调整每个参数的学习率。
AdamW
在 Adam 基础上将权重衰减(weight decay)从梯度更新中解耦,是目前训练 Transformer 的标准优化器。
# 常用优化器对比
optimizer_sgd = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.9)
optimizer_adam = torch.optim.Adam(model.parameters(), lr=1e-3, betas=(0.9, 0.999))
optimizer_adamw = torch.optim.AdamW(model.parameters(), lr=1e-4, weight_decay=0.01)
# 学习率调度器
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer_adamw, T_max=100)
# 训练循环
for epoch in range(100):
optimizer_adamw.zero_grad()
output = model(x)
loss = criterion(output, y)
loss.backward()
optimizer_adamw.step()
scheduler.step()损失函数
| 损失函数 | 适用场景 | PyTorch 类 |
|---|---|---|
| MSE | 回归 | nn.MSELoss() |
| CrossEntropy | 多分类 | nn.CrossEntropyLoss() |
| BCEWithLogits | 二分类 | nn.BCEWithLogitsLoss() |
| Huber Loss | 鲁棒回归 | nn.HuberLoss() |
| CTC Loss | 序列对齐 | nn.CTCLoss() |
Batch Normalization
BN 在每个 mini-batch 上对每个特征维度做归一化,加速训练并起到轻微正则化效果。
class ConvBlock(nn.Module):
def __init__(self, in_channels, out_channels):
super().__init__()
self.conv = nn.Conv2d(in_channels, out_channels, 3, padding=1)
self.bn = nn.BatchNorm2d(out_channels)
self.relu = nn.ReLU()
def forward(self, x):
return self.relu(self.bn(self.conv(x)))注意事项:推理时使用训练阶段积累的 running mean/var;batch size 过小时效果不佳,可改用 Layer Normalization 或 Group Normalization。
Dropout
训练时以概率 p 随机将神经元输出置零,防止网络对特定神经元产生过度依赖,是最常用的正则化手段之一。
class RegularizedMLP(nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim, dropout_rate=0.5):
super().__init__()
self.net = nn.Sequential(
nn.Linear(input_dim, hidden_dim),
nn.ReLU(),
nn.Dropout(dropout_rate),
nn.Linear(hidden_dim, hidden_dim),
nn.ReLU(),
nn.Dropout(dropout_rate),
nn.Linear(hidden_dim, output_dim)
)
def forward(self, x):
return self.net(x)
# 训练/推理模式切换
model = RegularizedMLP(784, 256, 10)
model.train() # 启用 Dropout
model.eval() # 禁用 Dropout完整训练示例
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, TensorDataset
# 构建数据集
X_train = torch.randn(1000, 20)
y_train = torch.randint(0, 5, (1000,))
dataset = TensorDataset(X_train, y_train)
loader = DataLoader(dataset, batch_size=64, shuffle=True)
# 模型定义
model = nn.Sequential(
nn.Linear(20, 128),
nn.BatchNorm1d(128),
nn.GELU(),
nn.Dropout(0.3),
nn.Linear(128, 64),
nn.BatchNorm1d(64),
nn.GELU(),
nn.Dropout(0.3),
nn.Linear(64, 5)
)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.01)
# 训练循环
for epoch in range(50):
model.train()
total_loss = 0
for batch_x, batch_y in loader:
optimizer.zero_grad()
pred = model(batch_x)
loss = criterion(pred, batch_y)
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
optimizer.step()
total_loss += loss.item()
if (epoch + 1) % 10 == 0:
print(f"Epoch {epoch+1}, Loss: {total_loss/len(loader):.4f}")总结
神经网络的核心要素包括:网络架构设计(层数、宽度)、激活函数选择、损失函数匹配任务类型、优化器调参(学习率、weight decay)、以及正则化策略(BN、Dropout、梯度裁剪)。掌握这些基础概念是理解 Transformer、CNN、GAN 等高级架构的前提。
贡献者
更新日志
9f6c2-feat: organize wiki content and refresh site setup于