残差神经网络
残差神经网络(Residual Network, ResNet)通过跳跃连接缓解深层网络训练困难。它不是直接学习目标映射
概念详解
普通网络层希望学习:
残差块改写为:
因此输出为:
当最优映射接近恒等映射时,只需要让
梯度推导
设残差块输出:
损失为
其中
应用代码
python
import torch
from torch import nn
class ResidualBlock(nn.Module):
def __init__(self, dim):
super().__init__()
self.net = nn.Sequential(
nn.Linear(dim, dim),
nn.ReLU(),
nn.Linear(dim, dim)
)
self.act = nn.ReLU()
def forward(self, x):
return self.act(x + self.net(x))
block = ResidualBlock(dim=16)
x = torch.randn(8, 16)
y = block(x)
print(y.shape)小结
残差连接让深层网络更容易优化。Transformer、U-Net、扩散模型中的很多模块也大量使用残差结构。