• 【花书笔记|PyTorch版】手动学深度学习7:模型选择、欠拟合和过拟合


    2022.11.10
    
    • 1

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

    4.4.1. 训练误差和泛化误差

    • 训练误差(training error)是指, 模型在训练数据集上计算得到的误差。
    • 泛化误差(generalization error)是指, 模型应用在同样从原始样本的分布中抽取的无限多数据样本时,模型误差的期望。

    参考:https://zhuanlan.zhihu.com/p/561167184

    4.4.2. 模型选择

    就是设计模型结构、训练集、测试集等等

    在这里插入图片描述

    • 欠拟合:就是训练不到位,训练误差较大
    • 过拟合:就是训练的太多了,过分同训练数据一致,那么整体泛化能力就差了,也就是在测试集预测的反而误差比较大,也就是泛化误差比较大。

    4.4.3 训练数据集大小

    • 通常,如果训练数据集中样本过少,特别是比模型参数数量更少时,如意发生过拟合。

    • 如果数据量小的,可以用K折交叉验证;数据量足够就不需要

      原始训练数据被分成个K不重叠的子集。 然后执行K次模型训练和验证,每次在K-1个子集上进行训练, 并在剩余的一个子集(在该轮中没有用于训练的子集)上进行验证。 最后,通过对K次实验的结果取平均来估计训练和验证误差

    4.4.4 多项式回归

    就是用多项式 ,来描绘出 过拟合和欠拟合图像

    y = 5 + 1.2 x − 3.4 x 2 2 ! + 5.6 x 3 3 ! + ϵ   w h e r e   ϵ ∽ N ( 0 , 0. 1 2 ) y=5+1.2x-3.4\frac{x^2}{2!}+5.6\frac{x^3}{3!}+\epsilon \ where \ \epsilon \backsim N(0,0.1^2) y=5+1.2x3.42!x2+5.63!x3+ϵ where ϵN(0,0.12)

    • ϵ是噪声,服从均值0标准差0.1正态分布

    1、引入包

    import math
    import numpy as np
    import torch
    from torch import nn
    from d2l import torch as d2l
    
    • 1
    • 2
    • 3
    • 4
    • 5

    2、设置阶数、训练测试集的大小、初始化w

    # 多项式的最大阶数 确定w向量的维度(1,20)
    max_degree = 20
    # 训练和测试数据集大小
    n_train, n_test = 100, 100  
    # 分配大量的空间 np.zeros是创建为0的向量 
    true_w = np.zeros(max_degree)  
    true_w[0:4] = np.array([5, 1.2, -3.4, 5.6])
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    设置参数w,前四项如式子,后面为0

    3、生成相应特征
    poly_features记录不同阶数的x

    # 生成(200,1)的特征
    features = np.random.normal(size=(n_train + n_test, 1))
    # 将生成的特征打乱
    np.random.shuffle(features)
    
    • 1
    • 2
    • 3
    • 4

    在这里插入图片描述

    正态分布随机抽:
    https://blog.csdn.net/wzy628810/article/details/103807829

    
    # poly_features 生成(200,20)的向量
    # np.arange(max_degree).reshape(1, -1)表示x的次数
    # poly_features存放的是features经过次方的数据
    poly_features = np.power(features, np.arange(max_degree).reshape(1, -1))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • np.arange(max_degree).reshape(1, -1) 变成 二维了

    在这里插入图片描述

    • pow()看不出来有什么作用

    在这里插入图片描述

    • 羊老羊讲解
      features 是生成的(200,1)的数据,相当如输入的X
      poly_features是记录不同阶数的x。它是200个数据(200,1)和指数1,2,…20 power后,(200,20)。
      每一排是一个数据,0次到19次的值;一共200

    4、生成真实labels

    # math.gamma()表示的是伽玛函数
    for i in range(max_degree):
        poly_features[:, i] /= math.gamma(i + 1)  # gamma(n)=(n-1)!
    
    • 1
    • 2
    • 3

    实现的就是 x n ( n − 1 ) ! \frac{x^n}{(n-1)!} (n1)!xn

    # np.dot表示矩阵的乘法 poly_features(200,20)true_w(1,20)
    labels = np.dot(poly_features, true_w) 
    # 参数scale表示正态分布的标准差,这里相当于来个一个bias
    labels += np.random.normal(scale=0.1, size=labels.shape)
    
    • 1
    • 2
    • 3
    • 4

    labels实现的式子前半部分
    np.random.normal(scale=0.1, size=labels.shape) 是噪音ϵ
    加到一起,式子完成!

    5、获取相应数据

    # NumPy ndarray转换为tensor
    # 用了for 一一对应的转换
    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]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    在这里插入图片描述

    • 都已经转换成了tensor
    • 一个数据20阶,这里有两个数据,计算出来两个y

    6、定义损失函数

     def evaluate_loss(net, data_iter, loss):  #@save
        """评估给定数据集上模型的损失"""
        # d2l.Accumulator(2)创建两个单位,存放总loss和单位数量
        # 损失的总和,样本数量
        metric = d2l.Accumulator(2)  
        # 传入数据data_iter
        for X, y in data_iter:
            # out为预测y的值
            out = net(X)
            # y是真实的y的值
            y = y.reshape(out.shape)
            # 根据定义的loss函数计算损失
            l = loss(out, y)
            # l.sum()总损失 l.numel()相等于总共l的数量
            metric.add(l.sum(), l.numel())
        return metric[0] / metric[1]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    7 训练模型

    # 传入训练特征,测试特征,训练标签,测试标签,迭代次数
    # 最重要的部分
    def train(train_features, test_features, train_labels, test_labels,
              num_epochs=400):
        # 定义loss为nn.MSELoss(reduction='none') 即均方损失函数
        loss = nn.MSELoss(reduction='none')
        # 输入的形状为train.features的列数
        input_shape = train_features.shape[-1]
        # 不设置偏置,因为我们已经在多项式中实现了它
        # nn.Linear表示定义为线性模型
        # 表示一个形状(input_shape,1)
        net = nn.Sequential(nn.Linear(input_shape, 1, bias=False))
        # 选择小批量大小
        batch_size = min(10, train_labels.shape[0])
        # d2l.load_array传入相应的数据
        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)
        # 选择SGD小批量梯度优化器去更新w和b
        trainer = torch.optim.SGD(net.parameters(), lr=0.01)
        # d2l.Animator动画显示训练和验证集损失情况
        animator = d2l.Animator(xlabel='epoch', ylabel='loss', yscale='log',
                                xlim=[1, num_epochs], ylim=[1e-3, 1e2],
                                legend=['train', 'test'])
        # 依次迭代训练,num_epochs=400
        for epoch in range(num_epochs):
            # d2l.train_epoch_ch3表示迭代一次
            d2l.train_epoch_ch3(net, train_iter, loss, trainer)
            # 每迭代20次画一个图
            if epoch == 0 or (epoch + 1) % 20 == 0:
                animator.add(epoch + 1, (evaluate_loss(net, train_iter, loss),
                                         evaluate_loss(net, test_iter, loss)))
        # 默认w的输出方式
        print('weight:', net[0].weight.data.numpy())
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    8 结果

    • 取4个维度训练 相对正常的结果
    # 从多项式特征中选择前4个维度,即1,x,x^2/2!,x^3/3!
    # n_train为100,一半测试集一半训练集
    train(poly_features[:n_train, :4], poly_features[n_train:, :4],
          labels[:n_train], labels[n_train:])
    
    • 1
    • 2
    • 3
    • 4

    在这里插入图片描述

    • 取2个维度训练 相对正常的结果
    # 从多项式特征中选择前2个维度,即1和x
    train(poly_features[:n_train, :2], poly_features[n_train:, :2],
          labels[:n_train], labels[n_train:])
    
    • 1
    • 2
    • 3

    在这里插入图片描述
    欠拟合了,模型太简单了,训练的不够

    • 取所有维度进行训练
    # 从多项式特征中选取所有维度
    train(poly_features[:n_train, :], poly_features[n_train:, :],
          labels[:n_train], labels[n_train:], num_epochs=1500)
    
    • 1
    • 2
    • 3

    在这里插入图片描述

    过拟合了,在300左右已经降到最低了,本来系数应该都是0的,因为模型过度复杂,噪音也放大了,反而让test训练误差有点增多的意思

  • 相关阅读:
    redis常用命令
    c# 反射专题—————— 介绍一下是什么是反射[ 一]
    使用Docker Compose运行Elasticsearch
    python gui(六)全局设定
    vue2 中store 使用
    java基于springboot+vue协同过滤算法的音乐推荐系统
    Educational Codeforces Round 108 (Rated for Div. 2) C. Berland Regional
    【游戏开发】快来听听我与口袋方舟的故事吧
    Vue3语法糖setup(二)
    滴答定时器
  • 原文地址:https://blog.csdn.net/wistonty11/article/details/127795551