当前位置:   article > 正文

动手学深度学习(Pytorch版)代码实践 -深度学习基础-09过拟合与欠拟合

动手学深度学习(Pytorch版)代码实践 -深度学习基础-09过拟合与欠拟合

09过拟合与欠拟合

#通过多项式拟合来探索过拟合和欠拟合
#欠拟合是指模型无法继续减少训练误差。
#过拟合是指训练误差远小于验证误差。
import math
import numpy as np
import torch
from torch import nn
from d2l import torch as d2l
import liliPytorch as lp

#生成数据集
max_degree = 20 #多项式的最大阶数
n_train, n_test = 100,100 #训练和测试数据集大小

#生成真实的多项式权重
true_w = np.zeros(max_degree) #创建一个长度为20的零数组,用于存储多项式的权重。
true_w[0:4] = np.array([5,1.2,-3.4,5.6])

#生成200*1个特征数据,服从标准正态分布。
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))
"""
np.arange(max_degree) 生成一个包含从 0 到 19的数组
np.arange(max_degree).reshape(1, -1) 将上述数组转换为一个形状为 (1, max_degree) 的二维数组
即[0, 1, 2, ..., 19]

np.power(features, np.arange(max_degree).reshape(1, -1)) 
使用 NumPy 的 power 函数对 features 进行逐元素的指数计算。

features 是一个形状为 (200, 1) 的数组,
那么 features 中的每个元素都会与 [0, 1, 2, ..., 19] 分别进行幂运算,
生成一个新的形状为 (200, 20) 的数组。
"""

for i in range(max_degree):
    #math.gamma(n) 是 Gamma 函数,用于计算 (n-1)!
    #将poly_features 矩阵第 i 列的每个元素都除以 i!
    poly_features[:,i] /= math.gamma(i + 1)


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]]

def evaluate_loss(net, data_iter, loss):  #@save
    """评估给定数据集上模型的损失"""
    metric = d2l.Accumulator(2)  # 损失的总和,样本数量
    #按批次返回输入特征 X 和对应的真实标签 y。
    for X, y in data_iter:
        out = net(X)
        y = y.reshape(out.shape)
        #计算模型输出 out 与真实标签 y 之间的损失 l。
        l = loss(out, y)
        metric.add(l.sum(), l.numel())
        #l.sum():计算当前批次损失的总和。
        #l.numel():计算当前批次中元素(样本)的数量。
    return metric[0] / metric[1]

def train(train_features, test_features, train_labels, test_labels,num_epochs=400):
    #均方误差损失函数
    #reduce='none',这意味着损失不会在计算时自动求和或取平均,而是返回每个样本的损失。
    loss = nn.MSELoss(reduce='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):
        lp.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: [[ 5.008241   1.2082175 -3.3981295  5.5975304]]
"""
poly_features[:n_train, :4]:从多项式特征矩阵中提取前 n_train 个样本(训练集),并只使用前 4 个特征。
poly_features[n_train:, :4]:从多项式特征矩阵中提取从 n_train 开始的样本(测试集),并只使用前 4 个特征。
labels[:n_train]:从标签数据中提取前 n_train 个样本的标签(训练集标签)。
labels[n_train:]:从标签数据中提取从 n_train 开始的样本的标签(测试集标签)
"""

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


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

d2l.plt.show() 
  • 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
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117

运行结果:

正态:
在这里插入图片描述

欠拟合:
在这里插入图片描述

过拟合:
在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Guff_9hys/article/detail/735867
推荐阅读
相关标签
  

闽ICP备14008679号