霜庭小筑

4.4 通过多项式拟合来探索过拟合与欠拟合

4.4 通过多项式拟合来探索过拟合与欠拟合

  • 生成数据集

我们将使用以下三阶多项式生成训练和测试数据:

y=5+1.2x−3.4x22!+5.6x33!+ϵ where ϵ∼N(0,0.12)y=5+1.2x-3.4{x^2\over2!}+5.6{x^3\over3!}+\epsilon\ where\ \epsilon\sim\mathcal{N}(0,0.1^2)

噪声项 ϵ\epsilon 服从均值为0且标准差为0.1的正态分布。在优化的过程中,我们通常希望避免非常大的梯度值或损失值。所以我们将特征从 xix^i 调整为 xii!\frac{x^i}{i!},避免 ii 带来的很大的指数值。

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])
features = np.random.normal(size=(n_train + n_test,1))
np.random.shuffle(features)
# np.random.normal的位置参数loc=0.0,scale=1.0定义了正态分布
poly_features = np.power(features, np.arange(max_degree).reshape(1, -1))
# np.power(a,b)返回幂指数a^b
# 这里是(200,1)^(1,20)=(200,20)
#即对(200, 1)的x,分别进行0次方、1次方...19次方的计算
for i in range(max_degree):
poly_features[:, i] /= math.gamma(i+1) # gamma(n) = (n-1)!
# labels的维度: (n_train + n_test, )
labels = np.dot(poly_features, true_w)
labels += np.random.normal(scale=0.1, size=labels.shape)
# NumPy ndarray转换为tensor
true_w, features, poly_features, labels = [torch.tensor(x, dtype=torch.float32)
for x in [true_w, features, poly_features, labels]]
  • 训练和测试
    首先实现一个函数来评估模型在给定数据集上的损失。
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]

现在定义训练函数。

def train(train_features, test_features, train_labels, test_labels,
num_epochs=400):
loss = nn.MSELoss(reduction='none') # 损失不求平均
input_shape = train_features.shape[-1]
# 输入数据的维数,线性模型是4阶,欠拟合<4,过拟合>4
# 不设置偏置,因为我们已经在多项式中实现了它
net = nn.Sequential(nn.Linear(input_shape, 1, bias=False))
batch_size = min(10, train_labels.shape[0])
# 把labels与features统一维度
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('weight:', net[0].weight.data.numpy())
  • 三阶多项式函数拟合(正常)
# 从多项式特征中选择前4个维度,即1, x, x^2/2!, x^3/3!
train(poly_features[:n_train, :4], poly_features[n_train:, :4],
labels[:n_train], labels[n_train:])
weight: [[ 5.0153017 1.2179098 -3.404573 5.573755 ]]

svg

还是悄悄地去d2l库里把缺的这些方法补上了…

  • 线性函数拟合(欠拟合)
# 从多项式特征中选择前2个维度,即1和x
train(poly_features[:n_train, :2], poly_features[n_train:, :2],
labels[:n_train], labels[n_train:])
weight: [[3.2892962 4.308353 ]]

svg

  • 高阶多项式函数拟合(过拟合)
    这个过于复杂的模型会轻易受到训练数据中噪声的影响。 虽然训练损失可以有效地降低,但测试损失仍然很高。
# 从多项式特征中选取所有维度
train(poly_features[:n_train, :], poly_features[n_train:, :],
labels[:n_train], labels[n_train:], num_epochs=1500)
weight: [[ 5.025822 1.2772155 -3.4720984 5.2113256 0.19187188 1.153992
0.07611543 -0.11197536 0.02289135 0.20176187 0.19850163 -0.00605978
-0.05850415 -0.20288932 -0.1583567 -0.09409655 0.07946095 0.04951369
0.12990662 -0.04490566]]

svg

本文由 kaikaikk 原创,发布于 ; 转载请保留原文链接: https://kaikaikk.com/posts/d2l-4-4-overfitting-underfitting/