• 模型选择、过拟合与欠拟合(多层感知机)


    多项式回归

    拟合问题是机器学习、深度学习中必须仔细理解的问题,我们现在可以通过多项式拟合来探索这些概念。

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

    生成数据集

    给定 x x x,我们将使用以下三阶多项式来生成训练和测试数据的标签:

    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 \quad where \quad \epsilon -- N(0,0.1^{2}) y=5+1.2x3.42!x2+5.63!x3+ϵwhereϵN(0,0.12)

    噪声项 ϵ \epsilon ϵ 服从均值为0且标准差为0.1的正态分布。 在优化的过程中,我们通常希望避免非常大的梯度值或损失值。 这就是我们将特征从 x i x^i xi 调整为 x i i ! \frac{x^i}{i!} i!xi 的原因, 这样可以避免很大的 i i i 带来的特别大的指数值。 我们将为训练集和测试集各生成100个样本。

    max_degree = 20                                         #多项式的最大阶数
    n_train, n_test = 100, 100                              #训练数据和测试数据的大小
    true_w = np.zeros(max_degree)                           #初始化权重参数w,均为0
    true_w[:4] = np.array([5, 1.2, -3.4, 5.6])              #参数w的取值
    
    
    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))        #对每个样本求1到20次幂
    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)                          #作点积运算,求结果y
    labels += np.random.normal(scale=0.1, size=labels.shape)        #加上一个偏置项epsilon
    
    labels.shape                                            #查看结果的形状
    
    (200,)
    

    同样,存储在poly_features中的单项式由gamma函数重新缩放, 其中 Γ ( n ) = ( n − 1 ) ! \Gamma (n) = (n-1)! Γ(n)=(n1)! 。 从生成的数据集中查看一下前2个样本, 第一个值是与偏置相对应的常量特征。

    #numpy ndarray转换为tensor
    #返回tensor形式的权重w,初始化数据集features,poly_features次幂与阶乘,结果集labels
    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[0:2], labels[0:2]
    
    (tensor([[ 0.0312],
             [-0.4075]]),
     tensor([[ 1.0000e+00,  3.1213e-02,  4.8712e-04,  5.0681e-06,  3.9547e-08,
               2.4688e-10,  1.2843e-12,  5.7266e-15,  2.2343e-17,  7.7486e-20,
               2.4186e-22,  6.8627e-25,  1.7850e-27,  4.2858e-30,  9.5552e-33,
               1.9883e-35,  3.8788e-38,  7.1215e-41,  1.2331e-43,  0.0000e+00],
             [ 1.0000e+00, -4.0750e-01,  8.3029e-02, -1.1278e-02,  1.1490e-03,
              -9.3641e-05,  6.3599e-06, -3.7024e-07,  1.8859e-08, -8.5390e-10,
               3.4797e-11, -1.2891e-12,  4.3775e-14, -1.3722e-15,  3.9940e-17,
              -1.0850e-18,  2.7635e-20, -6.6243e-22,  1.4997e-23, -3.2164e-25]]),
     tensor([5.0869, 4.1027]))
    

    对模型进行训练和测试

    首先让我们实现一个函数来评估模型在给定数据集上的损失。

    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(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())
        
    '
    运行

    三阶多项式函数拟合(正常)

    我们将首先使用三阶多项式函数,它与数据生成函数的阶数相同。 结果表明,该模型能有效降低训练损失和测试损失。 学习到的模型参数也接近真实值 w = [ 5 , 1.2 , − 3.4 , 5.6 ] w = [5, 1.2, -3.4, 5.6] w=[5,1.2,3.4,5.6]

    train(poly_features[:n_train, :4], poly_features[n_train:,:4],
         labels[:n_train], labels[n_train:])
    
    weight: [[ 4.997768   1.2584422 -3.40202    5.4872117]]
    

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

    线性函数拟合(欠拟合)

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

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

    在这里插入图片描述

    高阶多项式函数拟合(过拟合)

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

    # 从多项式特征中选择全部维度
    train(poly_features[:n_train, :max_degree], poly_features[n_train:, :max_degree], labels[:n_train], labels[n_train:])
    
    weight: [[ 4.921398    1.5011595  -2.9819698   4.4635773  -1.5328755   1.013793
      -0.36828652  0.06206623  0.12625365  0.15865426  0.15550074  0.05320771
      -0.0568059   0.19734485  0.10793436 -0.14808226 -0.14550243  0.04152694
      -0.13646026  0.15658265]]
    

    在这里插入图片描述

    小结

    欠拟合是指模型无法继续减少训练误差。过拟合是指训练误差远小于验证误差。

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

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

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

  • 相关阅读:
    [运维工具]ubuntu下迁移home目录至新的分区教程详解
    什么情况下使用微服务?
    基于人工智能的智能化指挥决策和控制
    点云平面拟合新国标怎么应对?
    c++ 结构体
    Redis环境配置
    艾美捷内毒素水平<0.1 EU/mg的卵清蛋白(OVA)
    软件项目管理--任务分解
    【Java 数据结构】单链表与OJ题
    Web3j 继承StaticStruct的类所有属性必须为Public <DynamicArray<StaticStruct>>
  • 原文地址:https://blog.csdn.net/weixin_43479947/article/details/127094871