本周主要是复习偏微分方程数值解的考试,完成了机器学习模型的选择,欠拟合和过拟合的学习。
在机器学习过程中模型在训练集上更准确时,但在测试集上不一定准确。这是因为误差分为在训练集上的训练误差(training error)和测试集上的泛化误差(generalization error),所以机器学习模型应关注降低泛化误差。
一、模型选择
1.1相关概念
1.训练误差(training error):模型在训练数据上的误差。
2.泛化误差(generalization error):模型在新数据上的误差。
3.验证数据集:一个用来评估模型好坏的数据集。一般从训练集中选取一部分作为验证集其余的作为训练集。
4.测试数据集:只用一次的数据集。但在实际应用中由于数据获取不易,仍然会多次使用。
1.2K折交叉验证(K-fold cross-validation)
由于验证数据集不参与模型训练,所以当训练数据不够用时,预留大量的验证数据就不太合理,一种改善的方法就是K折交叉验证。我们把原始训练数据被分成K个不重叠的⼦集。然后执⾏K次模型训练和验证, 每次在K − 1个⼦集上进⾏训练,并在剩余的⼀个⼦集(在该轮中没有⽤于训练的⼦集)上进⾏验证。最后, 通过对K次实验的结果取平均来估计训练和验证误差。
算法过程:将训练数据分割成K块,
for i = 1,....K.
使用第i块作为验证数据集,其余的作为训练数据集。
报告K个验证集误差的平均。
常用:K=5或10.
二、过拟合和欠拟合
2.1⽋拟合(underfitting):模型无法得到较低的训练误差。
2.2过拟合(overfitting):模型的训练误差远小于它在测试数据集上的误差。
2.3模型复杂度:
以多项式函数拟合为例,给定由单个特征𝑥和对应实数标签𝑦组成的训练数据,我们试图找到下面的𝑑d阶多项式来估计标签𝑦。
这是一个线性回归问题,我们的特征是𝑥的幂给出的,模型的权重是𝑤𝑖给出的,偏置是𝑤0给出的。高阶多项式函数比低阶多项式函数复杂得多。高阶多项式的参数较多,模型函数的选择范围较广。因此在固定训练数据集的情况下,高阶多项式函数相对于低阶多项式的训练误差应该始终更低(最坏也是相等)。给定训练数据集,模型复杂度和误差之间的关系如下图所示,如果模型复杂度过低,容易出现欠拟合,但复杂度过高,又容易出现过拟合。
2.4训练数据集的大小:
影响过拟合和欠拟合的一个重要因素就是训练数据集的大小,一般来说训练数据集中的样本越少,我们就越有可能(且更严重地)遇到过拟合。随着训练数据量的增加,泛化误差通常会减小。因此,在计算资源允许的范围内,通常希望训练数据集大一些,特别是在模型复杂度较高的时候。
三、多项式拟合代码
我们用以下的三阶多项式函数来生成训练和测试数据的标签。
3.1生成数据集
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)
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(n)` = (n-1)!
# `labels`的维度
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=
d2l.float32) for x in [true_w, features, poly_features, labels]]
3.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()
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())
3.3使用三阶多项式拟合:
# 从多项式特征中选择前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:])
结果:
因为它与数据生成函数的阶数相同,所以其效果良好,能有效的降低误差并且学习到的模型参数也接近真实值。
3.4欠拟合实验
# 从多项式特征中选择前2个维度,即 1, x
train(poly_features[:n_train, :2], poly_features[n_train:, :2],
labels[:n_train], labels[n_train:])
可以看出训练误差只在一开始下降后,之后基本没有下降了,在完成训练后误差仍然很大。
3.5过拟合实验
# 只选取两个样本实验
train(poly_features[:2, :4], poly_features[n_train:, :4],
labels[:2], labels[n_train:], num_epochs=400)
可以看到,在训练样本不足的情况下,即使使用和数据模型相同的三阶多项式模型,会出现过拟合现象,训练误差较低但测试误差很高。