训练误差:模型在训练数据上的误差
泛化误差:模型在新数据上的误差
训练数据集:训练模型参数
验证数据集:一个用来评估模型好坏的数据集,选择模型超参数
测试数据集:只使用一次的数据集
模型容量:拟合各种函数的能力
低容量的模型难以拟合训练数据,高容量的模型可以记住所有训练数据
深度学习的核心:在模型足够大的情况下,通过各种手段来控制模型容量,进而降低泛化误差。
很难在不同的种类算法之间比较模型容量
给定一个模型种类,将有两个主要因素:参数的个数,参数值的选择范围
对于一个分类模型,VC维等于一个最大数据集的大小,不管如何给定标号,都存在一个模型来对它及进行完美分类。VC维提供为什么一个模型好的理论依据,可以衡量训练误差和泛化误差之间的间隔,在深度学习中的使用是不常见的。
数据的复杂度有多个重要因素:样本个数、每个样本的元素个数、时间空间结构、多样性等。
模型容量需要匹配数据复杂度,否则可能导致欠拟合和过拟合,统计机器学习提供数学工具来衡量模型复杂度,实际中一般依靠观察训练误差和验证误差。
代码实现
# 通过多项式拟合来交互的探索模型选怎、欠拟合和过拟合的现象
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)
labels = np.dot(poly_features,true_w)
labels += np.random.normal(scale=0.1,size=labels.shape)
# 查看数据
true_w,features,poly_features,labels=[torch.tensor(x,dtype=torch.float32) for x in [true_w,fetures,poly_features,labels]]
features[:2],poly_features[:2,:],labels[:2]
运行结果:
(tensor([[-0.5888],
[ 0.0810]]),
tensor([[ 1.0000e+00, 1.6245e+00, 1.3196e+00, 7.1456e-01, 2.9021e-01,
9.4290e-02, 2.5529e-02, 5.9248e-03, 1.2031e-03, 2.1717e-04,
3.5280e-05, 5.2103e-06, 7.0536e-07, 8.8145e-08, 1.0228e-08,
1.1077e-09, 1.1247e-10, 1.0748e-11, 9.7002e-13, 8.2939e-14],
[ 1.0000e+00, -2.1660e-01, 2.3459e-02, -1.6937e-03, 9.1718e-05,
-3.9733e-06, 1.4344e-07, -4.4385e-09, 1.2017e-10, -2.8923e-12,
6.2648e-14, -1.2336e-15, 2.2267e-17, -3.7101e-19, 5.7402e-21,
-8.2890e-23, 1.1221e-24, -1.4298e-26, 1.7205e-28, -1.9614e-30]]),
tensor([6.3544, 4.6742]))
# 实现一个函数来评估模型在给定数据集上的损失
def evaluate_loss(net,data_iter,loss):
"""评估给定数据集上模型的损失"""
metric = d2l.Accumulator(2)
for X,y in data_iter:
out=net(X)
# y和输出的形状保持一致
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())
train(poly_features[:n_train,:4],poly_features[n_train:,:4],labels[:n_train],labels[n_train:])
# 只给数据的一部分:欠拟合
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)