【动手学深度学习】(五)模型选择、过拟合、欠拟合

发布于:2023-12-04 ⋅ 阅读:(154) ⋅ 点赞:(0)

一、模型选择

1.训练误差和泛化误差

  • 训练误差:模型在训练数据上的误差
  • 泛化误差:模型在新数据上的误差
    ex:根据摸底考试成绩来预测未来考试分数
  • 在过去的考试中表现很好(训练误差)不代表未来考试一定会好(泛化误差)
  • 学生A通过背书在摸底考中拿到很好的成绩
  • 学生B知道答案后面的原因

2.验证数据集和测试数据集

  • 验证数据集:一个用来评估模型好坏的数据集
    • 例如拿出50%的训练数据
    • 不要跟训练数据混在一起
  • 测试数据集:只用一次的数据集。例如:
    • 未来的考试
    • 我出价的房子的实际成交价
    • 用在Kaggle私有排行榜中的数据集

3.K则交叉验证

在没有足够多的数据时通常会使用K则交叉验证
将训练数据集分割成K块
for i = 1,…k
使用第i块作为验证数据集,其余作为训练数据集
报告K个验证集误差的平均
ex:假设k=3
在这里插入图片描述

通常k取5或10
总结:

  • 训练数据集:训练模型参数
  • 验证数据集:选择模型超参数
  • 非大数据集上通常使用k-折交叉验证

二、过拟合和欠拟合

在这里插入图片描述

1.模型容量

  • 拟合各种函数的能力
  • 低容量的模型难以拟合训练数据
  • 高容量的模型可以记住所有的训练数据

2.模型容量的影响

在这里插入图片描述

3.估计模型容量

  • 难以在不同的种类算法之间比较
    • 例如树模型和神经网络
  • 给定一个模型种类,将有两个主要因素
    • 参数的个数
    • 参数值的选择范围

4.VC维[了解]

  • 统计学习理论的一个核心思想
  • 对于一个分类模型,VC等于一个最大的数据集的大小,不管如何给定标号,都存在一个模型来对它进行完美分类

5.线性分类器的VC维[了解]

  • 2维输入的感知机,VC维=3
    • 能够分类任何三个点,但不是4个(xor)
      在这里插入图片描述
      下面这种一根直线是不够的,需要曲线
      在这里插入图片描述
  • 支持N维输入的感知机的VC维是N+1
  • 一些多层感知机的VC维O(NlogN)

6.VC维的用处[了解]

  • 提供为什么一个模型好的理论依据
    • 它可以衡量训练误差和泛化误差之间的间隔
  • 但深度学习中很少使用
    • 衡量不是很准确
    • 计算深度学习模型的VC维很困难

7.数据复杂度

  • 多个重要因素
    • 样本个数
    • 每个样本的元素个数
    • 时间、空间结构
    • 多样性

三、代码

1.多项式回归

通过多项式拟合探索上述概念
1.导入相关包

import math
import numpy as np
import torch
from torch import nn
from d2l import torch as d2l

2.使用三阶多项式来生成训练和测试数据的标签

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]) # 设置前4项的真实系数值
# 生成服从正态分布的随机特征值
features = np.random.normal(size=(n_train + n_test, 1))
# print(features)
# 打乱顺序
np.random.shuffle(features)
# 生成多项式特征矩阵,将特征值按照阶数的幂进行展开
poly_features = np.power(features, np.arange(max_degree).reshape(1, -1))
# print(poly_features)
# 除以阶数的阶乘
for i in range(max_degree):
    poly_features[:,i] /= math.gamma(i + 1)
#     labels的维度:(n_train+n_test,)
# 计算多项式回归的预测值
labels = np.dot(poly_features, true_w)
# 添加服从正态分布的随机噪声
labels += np.random.normal(scale=0.1, size=labels.shape)
# print(labels)
# print(features.shape)
# print(poly_features.shape)

3.查看

# 查看前两个样本
# 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]

(tensor([[0.4634],
[1.5931]]),
tensor([[1.0000e+00, 4.6337e-01, 1.0735e-01, 1.6581e-02, 1.9208e-03, 1.7801e-04,
1.3747e-05, 9.0999e-07, 5.2707e-08, 2.7136e-09, 1.2574e-10, 5.2967e-12,
2.0453e-13, 7.2900e-15, 2.4128e-16, 7.4534e-18, 2.1585e-19, 5.8835e-21,
1.5146e-22, 3.6937e-24],
[1.0000e+00, 1.5931e+00, 1.2690e+00, 6.7385e-01, 2.6838e-01, 8.5509e-02,
2.2704e-02, 5.1670e-03, 1.0289e-03, 1.8213e-04, 2.9015e-05, 4.2021e-06,
5.5786e-07, 6.8363e-08, 7.7791e-09, 8.2618e-10, 8.2261e-11, 7.7087e-12,
6.8226e-13, 5.7205e-14]]),
tensor([5.3120, 6.4268]))

4.实现一个函数来评估模型在给定数据集上的损失

def evaluate_loss(net, data_iter, loss):
    """评估给定数据集上模型的损失"""
    metric = d2l.Accumulator(2)  # 累积损失的总和,样本数量
    for X, y in data_iter:
#         模型预测输出结果
        out = net(X)
#     调整标签的形状,确保其与out形状一致
        y = y.reshape(out.shape)
#     计算模型预测好真实标签之间的损失
        l = loss(out, y)
        metric.add(l.sum(), l.numel())
#   平均损失 = 损失总和 / 样本数量
    return metric[0] / metric[1]

5.训练函数

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())

6.三阶多项式函数拟合(正态)

# 从多项式特征中选择前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: [[ 4.9997916 1.1968371 -3.415553 5.615472 ]]
在这里插入图片描述

# 欠拟合(只选择前两个维度)
train(poly_features[:n_train, : 2], poly_features[n_train:, :2],
     labels[:n_train], labels[n_train:])

weight: [[2.9557896 4.5860257]]
在这里插入图片描述

# 高阶多项式(过拟合)
train(poly_features[:n_train, :], poly_features[n_train:, :],
     labels[:n_train], labels[n_train:])

weight: [[ 4.902475 1.4078288 -3.0424712 4.8212714 -0.7548129 1.40631
-0.2779794 0.03954406 0.03519901 0.10875289 0.05778362 -0.21782693
0.03080553 0.13967657 -0.05706897 0.16317466 0.1380277 -0.03208227
0.11803454 -0.03070892]]
在这里插入图片描述

【相关总结】

np.power()

power(x, y) 函数,计算 x 的 y 次方,x和y可以为数字或数组

  • 均为数字
import numpy as np

x = 2
y = 3
result = np.power(x,y)
print(result)

8

# 均为列表
x = [1, 2]
y = [3, 4]
result = np.power(x,y)
print(result)

# [1**3,2**4]


x1 = np.array([[1, 2],[3, 4]])
x2 = np.array([[1, 2],[3, 4]])
result = np.power(x1,x2) 
print(result)
# ([1**1, 2**2],
#  [3**3, 4**4])

[ 1 16]
[[ 1 4]
[ 27 256]]

# 列表和数字
x = [1, 2, 3]
y = 2
result = np.power(x, y)
print(result)

# 数字和列表
result = np.power(y, x)
print(result)

[1 4 9]
[2 4 8]