2.1 模型选择、过拟合、欠拟合
在评估几个候选模型后选择最终的模型的过程叫做模型选择。有时需要进行比较的模型在本质上是完全不同的(比如,决策树与线性模型),有时需要比较不同的超参数设置下的同一类模型。为了确定候选模型中的最佳模型,通常会使用验证集。
验证集区别于测试集,验证集用来查看模型表现的情况,可以在验证集上进行参数的调整以达到最好的效果,而测试集只能用一次,是模型没有见过的数据,在测试集上能表现该模型真实的性能以及泛化性。
当数据集较少无法提供合适验证集的时候,可以使用K折交叉验证。即原始训练数据被分成K个不重叠的子集。然后执行K次模型训练和验证,每次在K−1个子集上进行训练,并在剩余的一个子集(在该轮中没有用于训练的子集)上进行验证。 最后,通过对K次实验的结果取平均来估计训练和验证误差。这里可以直接使用得到的k个模型均值,或者确定好超参数后在用所有数据训练一次,或者就选择表现最好的那个模型直接使用。
欠拟合:训练误差和验证误差都很严重,它们之间仅有一点差距。即模型不够复杂,学到的东西很少。
过拟合:训练误差明显低于验证误差。即模型学得太好了,把一些不重要的特征也学到了。
2.2 代码展示
!pip install git+https://github.com/d2l-ai/d2l-zh@release # installing d2l
! pip install matplotlib==3.0.0
import torch
from torch import nn
import math
import numpy as np
from d2l import torch as d2l
max_degree = 20
n_train, n_test = 100, 100
true_w = np.zeros(max_degree)
true_w[:4] = np.array([5, 1.2, -3.4, 5.6])
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))#计算x的n次方
for i in range(max_degree):
poly_features[:,i] /= math.gamma(i+1)#生成多项式
labels = np.dot(poly_features,true_w)
labels += np.random.normal(scale=0.1, size=labels.shape)#添加噪音
#将numpy转化为tensor
true_w, features, poly_features, labels = [torch.tensor(x,dtype=torch.float32) for x in [true_w, features, poly_features, labels]]
#features[:2], poly_features[:2,:], labels[:2]
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]
# 不设置偏置,因为我们已经在多项式中实现了它
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('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:])
# 从多项式特征中选择前2个维度,即1和x 欠拟合
train(poly_features[:n_train, :2], poly_features[n_train:, :2],
labels[:n_train], labels[n_train:])
# 从多项式特征中选取所有维度 过拟合
train(poly_features[:n_train, :], poly_features[n_train:, :],
labels[:n_train], labels[n_train:], num_epochs=1500)
正常拟合结果: 在训练集和验证集上的损失都在400轮后降低到0.01左右
欠拟合结果: 可以看到,在两个数据集上最后达到的效果是远远不如正常结果的,这里最后的损失大概是10左右,是比较大的。
过拟合结果: 可以看出在1500轮后,在验证集上的损失是大于训练集的。