目录
1.模型选择
我们关心的是泛化误差
5和10是多少次训练,数据很多就选小一点
2.过拟合和欠拟合
低就是简单模型,比如线性模型,高就是复杂模型,比如多层感知机。
假设中等数据集固定,常用的调参策略有先从最简单的模型逐步过渡到复杂的模型。泛化误差先降后升是因为模型过于关注细节导致真的拿新的数据训练被无关的细节困扰住了。泛化误差和训练误差中间的距离常用来衡量模型欠拟合和过拟合的程度。最优泛化误差就是寻泛化误差的低点同时不要把泛化误差和训练误差之间的距离弄得特别大,但是,有时我们为了降低泛化误差不得不承受一定的过拟合。过拟合本质上不是一件很坏的事情,首先模型容量要够,其次再去控制他的容量。在模型容量足够大的前提下,再通过各种手段控制模型容量,使得最后能得到泛化误差往下降。
2维输入的感知机,就是输入的特征有2个
3.代码
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 # 训练和测试数据集大小
#用100个训练样本和验证样本
true_w = np.zeros(max_degree) # 分配大量的空间
#长为20的w
true_w[0:4] = np.array([5, 1.2, -3.4, 5.6])
#后面剩余15项全是0的噪声项
features = np.random.normal(size=(n_train + n_test, 1))
#从标准正态分布中抽取200个随机值,features形状200*1
np.random.shuffle(features)
#打乱
poly_features = np.power(features, np.arange(max_degree).reshape(1, -1))
#np.power(a,b),若b为单个数字,则对a各个元素分别求b次方。若b为数组,其列数要与a相同,
#并求相应的次方。np.arange返回一个有终点和起点的固定步长的排列(可理解为一个等差数组)
#在这里的意思是生成一个形状为1*20的序列。features(200*1)np.arange(1*20)。
#poly_features (200*20)
for i in range(max_degree):
#i是0-19
poly_features[:, i] /= math.gamma(i + 1) # gamma(n)=(n-1)!
#poly_features的所有行取出来,拿出第i列,代表每一个x的次方项。poly_features形状是200*20。
#算分母的阶层
# labels的维度:(n_train+n_test,)
labels = np.dot(poly_features, true_w)
#poly_features(200*20)点乘true_w(1*20),np.dot要求前面的行等于后面的列,并且可以自动转置,
#因此labels(200*1)
labels += np.random.normal(scale=0.1, size=labels.shape)
#加点从标准差为0.1的正态分布中取出的噪声
# NumPy ndarray转换为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]
#展示以下features(200*1)的0-2行, poly_features(200*20)的0-2行,所有列,
#labels(200*1)的第0-2行
"""对模型进行训练和测试"""
#实现一个函数来评估模型在给定数据集上的损失
def evaluate_loss(net, data_iter, loss): #@save
"""评估给定数据集上模型的损失"""
metric = d2l.Accumulator(2) # 损失的总和,样本数量
# metric=[0.0,0.0]
for X, y in data_iter:
out = net(X)
#把X放到net里面得到一个输出
y = y.reshape(out.shape)
#把y弄成和输出一样的形状
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')
#算均方损失,reduction='none'返回每个样本的独立损失值
input_shape = train_features.shape[-1]
#输入等于train_features的最后一维的大小
# 不设置偏置,因为我们已经在多项式中实现了它
net = nn.Sequential(nn.Linear(input_shape, 1, bias=False))
#网络模型为线性层,输入为input_shape,输出为1
batch_size = min(10, train_labels.shape[0])
#批量大小取10和train_labels形状大小第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:])
#poly_features(200*20),labels(200*1),n_train=100,取出前100个特征和标签,
#取出后100个特征和标签
#结果输出:weight: [[ 5.000446 1.1925726 -3.3994446 5.613429 ]]
#权重和我们设置的权重还是比较相似的,而且出来的图片没有太多的过拟合,最后的损失都降到了0.01
"""线性函数拟合(欠拟合)"""
# 从多项式特征中选择前2个维度,即1和x
train(poly_features[:n_train, :2], poly_features[n_train:, :2],
labels[:n_train], labels[n_train:])
#结果输出:weight: [[3.2520251] [3.8255486]]
#损失非常高,根本就没降,没有训练好模型,因为数据给的很少
#取出前2项作为特征
"""高阶多项式函数拟合(过拟合)"""
# 从多项式特征中选取所有维度
train(poly_features[:n_train, :], poly_features[n_train:, :],
labels[:n_train], labels[n_train:], num_epochs=1500)
"""结果输出:weight: [[ 4.990251 ]
[ 1.2706137 ]
[-3.3405976 ]
[ 5.1611915 ]
[-0.21923827]
[ 1.3674685 ]
[ 0.5580076 ]
[ 0.6122327 ]
[-0.2809331 ]
[ 0.16498628]
[ 0.02497598]
[-0.3946727 ]
[-0.25850204]
[ 0.1591375 ]
[-0.01723303]
[ 0.04925743]
[-0.00524987]
[ 0.3699218 ]
[-0.1588985 ]
[ 0.10174304]]"""
#模型不变的情况下,数据给的更多,把本来为0的噪音都学到了
三阶多项式函数拟合(正常)
线性函数拟合(欠拟合)
高阶多项式函数拟合(过拟合)
虽然训练损失可以有效地降低,但测试损失仍然很高。
结论:怎么控制模型的容量呢?一是把模型变得比较小,就是里面的参数比较少,第二是使得每个参数选择的值的范围比较小。