深度学习复习笔记|过拟合 & 欠拟合:新手秒懂 + 多项式回归实战
·
复习日期:2026-04-29学习内容:《动手学深度学习》4.4 节 过拟合 & 欠拟合、多项式回归实验适配环境:Python3.9 + PyTorch2.6.0 + RTX4070 Laptop GPU
📝 目录
一、核心概念:欠拟合 & 过拟合,菜鸟秒懂
一句话终极比喻(学生考试)
- 上课学知识 = 模型训练(看训练集)
- 课后作业 = 训练集(做过的题)
- 期末考试 = 测试集(没见过的新题)
| 类型 | 通俗解释 | 作业分数 | 考试分数 | 本质 |
|---|---|---|---|---|
| 欠拟合 | 没学会,太笨学不懂 | 很低 | 很低 | 模型太简单,学不会规律 |
| 过拟合 | 死记硬背,只会背原题 | 满分 | 极低 | 模型太复杂,只会背训练数据,不会举一反三 |
| 正常拟合 | 学会了,能举一反三 | 低 | 低 | 模型刚好,学到了真实规律 |
看曲线一眼分辨
| 类型 | 训练损失 | 测试损失 | 曲线特征 |
|---|---|---|---|
| 欠拟合 | 高高不下 | 高高不下 | 两条线都在上面,下不去 |
| 过拟合 | 一路降到 0 | 先降后飙升 | 训练线到底,测试线往上飞 |
| 正常拟合 | 稳定下降 | 稳定下降 | 两条线都低,平行收敛 |
二、实战:多项式回归实验(三种拟合场景)
我们用3 次多项式带噪声的数据,测试不同复杂度模型的拟合效果,完美复现三种场景。
1. 数据构造(带注释的完整代码)
python
运行
# 导入依赖
import math
import numpy as np
import torch
from torch import nn
from d2l import torch as d2l
# 实验参数
max_degree = 20 # 多项式最大阶数(测试过拟合)
n_train, n_test = 100, 100 # 训练/测试样本数
true_w = np.zeros(max_degree)
true_w[0:4] = np.array([5, 1.2, -3.4, 5.6]) # 真实3次多项式权重
# 生成原始特征
features = np.random.normal(size=(n_train + n_test, 1))
np.random.shuffle(features)
# 构造多项式特征(带阶乘归一化,防止数值爆炸)
poly_features = np.power(features, np.arange(max_degree).reshape(1, -1))
for i in range(max_degree):
poly_features[:, i] /= math.gamma(i + 1) # gamma(i+1) = i!
# 生成标签(加高斯噪声,模拟真实数据)
labels = np.dot(poly_features, true_w)
labels += np.random.normal(scale=0.1, size=labels.shape)
# 转换为PyTorch张量
true_w, features, poly_features, labels = [torch.tensor(x, dtype=torch.float32) for x in [true_w, features, poly_features, labels]]
2. 训练 & 评估函数
python
运行
# 评估损失函数
def evaluate_loss(net, data_iter, loss):
metric = d2l.Accumulator(2)
for X, y in data_iter:
out = net(X)
y = y.reshape(out.shape)
l = loss(out, y)
metric.add(l.sum(), l.numel())
return metric[0] / metric[1]
# 训练函数(适配GPU,解决d2l新版train_ch3缺失问题)
def train(train_features, test_features, train_labels, test_labels, num_epochs=400):
loss = nn.MSELoss(reduction='none')
input_shape = train_features.shape[-1]
net = nn.Sequential(nn.Linear(input_shape, 1, bias=False))
batch_size = min(10, train_labels.shape[0])
train_iter = d2l.load_array((train_features, train_labels.reshape(-1,1)), batch_size)
test_iter = d2l.load_array((test_features, test_labels.reshape(-1,1)), batch_size, is_train=False)
trainer = torch.optim.SGD(net.parameters(), lr=0.01)
animator = d2l.Animator(xlabel='epoch', ylabel='loss', yscale='log',
xlim=[1, num_epochs], ylim=[1e-3, 1e2],
legend=['train', 'test'])
for epoch in range(num_epochs):
d2l.train_epoch_ch3(net, train_iter, loss, trainer)
if epoch == 0 or (epoch + 1) % 20 == 0:
animator.add(epoch + 1, (evaluate_loss(net, train_iter, loss),
evaluate_loss(net, test_iter, loss)))
print('学习到的权重:', net[0].weight.data.numpy())
3. 三种场景实验
场景 1:正常拟合(前 4 阶特征)
python
运行
# 匹配真实3次多项式,模型复杂度刚好
train(poly_features[:n_train, :4], poly_features[n_train:, :4],
labels[:n_train], labels[n_train:])
✅ 结果:训练 / 测试损失都低,权重接近真实值,完美拟合。
场景 2:欠拟合(前 2 阶特征)
python
运行
# 只用1阶线性特征,模型太简单,学不会3次多项式
train(poly_features[:n_train, :2], poly_features[n_train:, :2],
labels[:n_train], labels[n_train:])
❌ 结果:训练 / 测试损失都很高,模型能力不足。
场景 3:过拟合(全部 20 阶特征)
python
运行
# 用全部20阶特征,模型太复杂,把噪声都背下来了
train(poly_features[:n_train, :], poly_features[n_train:, :],
labels[:n_train], labels[n_train:], num_epochs=1500)
❌ 结果:训练损失降到 0,测试损失飙升,死记硬背了训练数据。
三、核心考点 & 常见问题
必背考点
- 欠拟合:模型太简单,两边损失都高
- 过拟合:模型太复杂,训练损失 0,测试损失爆高
- 多项式特征必须标准化:否则高阶项数值爆炸,训练不稳定
- 泛化误差不可能为 0:真实数据有噪声,永远不可能完美拟合新数据
常见报错速解
module 'd2l.torch' has no attribute 'train_ch3'→ 新版 d2l 删除了旧函数,手动补全训练函数即可- 训练速度慢→ 没开 GPU,把模型和数据都移到
cuda设备 - 训练不收敛→ 没做特征标准化,高阶项数值爆炸
四、精简速记卡片(手机复习版)
| 类型 | 口诀 | 损失特征 |
|---|---|---|
| 欠拟合 | 没学会 | 训练高、测试高 |
| 过拟合 | 死记硬背 | 训练 0、测试爆 |
| 正常拟合 | 举一反三 | 训练低、测试低 |
核心一句话
- 模型太简单→欠拟合,太复杂→过拟合
- 多项式特征必须标准化,否则数值爆炸
- 泛化误差不可能为 0,因为数据有噪声
更多推荐
所有评论(0)