动手学深度学习之模型选择&过拟合欠拟合

模型选择

训练误差和泛化误差

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

验证数据集和测试数据集

  • 验证数据集:一个用来评估模型好坏的数据集
    • 例如拿出50%的训练数据
    • 不要跟训练数据混在一起
  • 测试数据集:只用一次的数据集。例如:
    • 未来的考试
    • 我出价的房子的实际成交价
    • 我在kaggle私有排行榜中的数据集
  • k-折交叉验证
    • 在没有足够多数据时使用
    • 算法:
      • 将训练数据分割称为k块
      • For i=1,…, K。使用第i块作为验证数据集,其余的作为训练数据集
      • 报告K个验证集误差的平均
    • 常用:k=5或10

总结

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

过拟合和欠拟合

模型容量

  • 拟合各种函数的能力
  • 低容量的模型难以你和训练数据
  • 高容量的模型可以记住所有的训练数据
    在这里插入图片描述

估计模型容量

  • 难以在不同种类算法之间比较
    • 例如树模型和神经网络
  • 给定一个模型种类,将有两个主要因素
    • 参数的个数
    • 参数值的选择范围
      [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-jZ4OtIO9-1627904937109)(attachment:image-3.png)]

VC维

  • 统计学系理论的一个核心思想。
  • 对于一个分类模型,VC等于一个最大的数据集的大小,不管如何给丁标号,都存在一个模型来对它进行完美分类。
线形分类器的vc维
  • 2维输入的感知机,VC维=3
    • 能够分类任何三个点,但不是4个
  • 支持N维输入的感知机的VC维是N+1
  • 一些多层感知机的VC维 O ( N l o g 2 N ) O(Nlog_2N) O(Nlog2N)
  • VC维的用处
    • 提供为什么一个模型好的理论依据
      • 可以衡量训练误差和泛化误差之间的间隔
    • 但深度学习中很少使用
      • 衡量不是很准确
      • 计算深度学习模型的VC维很困难

数据复杂度

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

总结

  • 模型容量需要匹配数据复杂度,否则可能导致欠拟合和过拟合
  • 统计机器学习提供数学工具来衡量模型复杂度
  • 实际中一般靠观察训练误差和验证误差

模型选择、欠拟合和过拟合

通过多项式拟合来交互地探索这些概念

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

使用以下三阶多项式来生成训练和测试数据的标签 y = 5 + 1.2 x − 3.4 x 2 2 ! + 5.6 x 3 3 ! + ε ε   N ( 0 , 0. 1 2 ) y=5+1.2x-3.4\frac{x^2}{2!}+5.6\frac{x^3}{3!}+\varepsilon \qquad \varepsilon ~ N(0, 0.1^2) y=5+1.2x3.42!x2+5.63!x3+εε N(0,0.12)

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`的维度: (`n_train` + `n_test`,)
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=torch.float32)
    for x in [true_w, features, poly_features, labels]]

features[:2], poly_features[:2, :], labels[:2]
(tensor([[0.3874],
         [1.6652]]),
 tensor([[1.0000e+00, 3.8744e-01, 7.5056e-02, 9.6933e-03, 9.3890e-04, 7.2754e-05,
          4.6980e-06, 2.6003e-07, 1.2593e-08, 5.4213e-10, 2.1005e-11, 7.3983e-13,
          2.3887e-14, 7.1190e-16, 1.9702e-17, 5.0888e-19, 1.2323e-20, 2.8084e-22,
          6.0450e-24, 1.2327e-25],
         [1.0000e+00, 1.6652e+00, 1.3864e+00, 7.6956e-01, 3.2036e-01, 1.0669e-01,
          2.9611e-02, 7.0440e-03, 1.4662e-03, 2.7128e-04, 4.5173e-05, 6.8383e-06,
          9.4892e-07, 1.2155e-07, 1.4457e-08, 1.6049e-09, 1.6703e-10, 1.6361e-11,
          1.5136e-12, 1.3265e-13]]),
 tensor([5.3903, 6.4085]))

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

def evaluate_loss(net, data_iter, loss):  #@save
    """评估给定数据集上模型的损失。"""
    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())

三阶多项式和桉树拟合(正态)

# 从多项式特征中选择前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.991678   1.2089298 -3.4061375  5.5837603]]

在这里插入图片描述

# 从多项式特征中选择前2个维度,即 1, x
train(poly_features[:n_train, :2], poly_features[n_train:, :2],
      labels[:n_train], labels[n_train:])
weight: [[3.192375  4.2441025]]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tSeBiWxD-1627904937112)(output_12_1.svg)]

# 从多项式特征中选取所有维度
train(poly_features[:n_train, :], poly_features[n_train:, :],
      labels[:n_train], labels[n_train:], num_epochs=1500)
weight: [[ 5.0044866   1.316284   -3.4279313   5.1354914   0.01587025  0.9727597
   0.21220675 -0.07566912  0.08088465 -0.06732125 -0.19916393 -0.1721122
   0.1289137   0.06824628  0.16578138  0.13244942 -0.08216301  0.02891229
  -0.14450851  0.18875384]]

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值