《动手学深度学习》模型选择、欠拟合和过拟合(李沐)

4.4. 模型选择、欠拟合和过拟合(4.多层感知机)
代码学习笔记(含详细代码注释)
4.4.4. 多项式回归
通过多项式拟合来探索模型选择、欠拟合和过拟合过程

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

4.4.4.1. 生成数据集
在这里插入图片描述
噪声项服从均值为0且标准差为0.1的正态分布。 在优化的过程中,我们通常希望避免非常大的梯度值或损失值。 这就是我们将特征从“x的i次方”调整为“x的i次方除以i的阶乘”的原因。

# 多项式的最大阶数
max_degree = 20
# 训练和测试数据集大小
n_train, n_test = 100, 100
# 分配足够的空间
# 保证满足最大阶数时需要的w的数量
true_w = np.zeros(max_degree)
#生成真实值,前面的4项参数是有值的,后面的都是噪音
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进行重新排列,改变自身序列
np.random.shuffle(features)
# reshape(n,-1)转化成n行;reshape(-1,n)转化成n列
# np.arange(max_degree).reshape(1, -1)依次生成max_degree个自然数:0,1,2,3..,并且以1行max_degree列的数组形式显示
# power(x, y) 函数,计算 x 的 y 次方
# 所以poly_features为我们求得的x的i次方(0=<i<=19),矩阵形式为:200*20(n_train+n_test,max_degree)
poly_features = np.power(features,np.arange(max_degree).reshape(1, -1))
for i in range(max_degree):
    # gamma(n)=(n-1)!
    # poly_features[:,i]表示取其中的第i列
    # 第i列除以i!(i的阶乘)
    poly_features[:,i] /= math.gamma(i + 1)

# np.dot(),进行运算时,会首先将后面一项进行自动转置操作,之后再进行乘法运算,结果为(n_train+n_test)阶向量
# labels的维度:(n_train+n_test,)
labels = np.dot(poly_features, true_w)
# 加上噪声项,噪声项服从均值为0且标准差为0.1的正态分布
labels += np.random.normal(scale=0.1,size=labels.shape)

np.random.shuffle(x) :在原数组上进行,改变自身序列,无返回值。
np.random.permutation(x) :不在原数组上进行,返回新的数组,不改变自身数组。

# NumPy ndarray转换为tensor
true_w, features, poly_features, labels = [torch.tensor(x, dtype=
    torch.float32) for x in [true_w, features, poly_features, labels]]

# 输出经过切片产生的参数
print(features[:2],poly_features[:2, :], labels[:2])
# features[:2], poly_features[:2, :], labels[:2]

从生成的数据集中查看一下前2个样本, 第一个值是与偏置相对应的常量特征。

4.4.4.2. 对模型进行训练和测试

def evaluate_loss(net, data_iter, loss):
    """评估给定数据集上模型的损失"""
    # 损失的总和,样本数量,Accumulator(n)函数在之前的章节出现过
    metric = d2l.Accumulator(2)
    for X,y in data_iter:
        # 即y_hat
        out = net(X)
        y = y.reshape(out.shape)
        # 根据计算出的out和y来求loss
        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')
    # 取矩阵的列数
    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_labels转换成一列
    # 训练数据集中选出batch_size的数据
    train_iter = d2l.load_array((train_features, train_labels.reshape(-1,1)), batch_size)
    # 测试数据集中选出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)
        # 每20个epoch绘制更新一次图表
        if epoch == 0 or (epoch + 1) % 20 ==0:
            animator.add(epoch + 1,(evaluate_loss(net, train_iter, loss),
                                    evaluate_loss(net, test_iter, loss)))
    # 输出训练更新后的weight值
    print('weight:', net[0].weight.data.numpy())

shape[-1]代表最后一个维度,如在二维张量里,shape[-1]表示列数。
矩阵:
shape[0]读取矩阵的行数。
shape[1]读取矩阵的列数。
图片:
shape[0]图片的高。
shape[1]图片的宽。
shape[2]图片的通道数(chanel)。
reshape[-1,n]:转换成n列。
reshape[n,-1]:转换成n行。

4.4.4.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:])

训练结果:
weight1

F1

4.4.4.4. 线性函数拟合(欠拟合)
再看看线性函数拟合,减少该模型的训练损失相对困难。 在最后一个迭代周期完成后,训练损失仍然很高。 当用来拟合非线性模式(如这里的三阶多项式函数)时,线性模型容易欠拟合。

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

训练结果:

weight2

F2

4.4.4.5. 高阶多项式函数拟合(过拟合)
在这种情况下,没有足够的数据用于学到高阶系数应该具有接近于零的值。 因此,这个过于复杂的模型会轻易受到训练数据中噪声的影响。 虽然训练损失可以有效地降低,但测试损失仍然很高。 结果表明,复杂模型对数据造成了过拟合。

# 从多项式特征中选取所有维度
train(poly_features[:n_train, :], poly_features[n_train:, :],
      labels[:n_train], labels[n_train:], num_epochs=1500)

训练结果:
weight3
F3
4.4.5. 小结
1.欠拟合是指模型无法继续减少训练误差。过拟合是指训练误差远小于验证误差。

2.由于不能基于训练误差来估计泛化误差,因此简单地最小化训练误差并不一定意味着泛化误差的减小。机器学习模型需要注意防止过拟合,即防止泛化误差过大。

3.验证集可以用于模型选择,但不能过于随意地使用它。

4.我们应该选择一个复杂度适当的模型,避免使用数量不足的训练样本。

参考链接:
【Numpy】中np.random.shuffle()与np.random.permutation()的用法和区别
《动手学习深度学习》
Python的reshape的用法
np.dot()函数的用法详解
Python中的shape[0]、shape[1]和shape[-1]分别是什么意思

  • 10
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值