李沐深度学习记录3:11模型选择、欠拟合和过拟合

通过多项式拟合探索欠拟合与过拟合

python 复制代码
import math
import numpy as np
import torch
from torch import nn
from d2l import torch as d2l

#生成数据集
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))#生成均值为0,标准差为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)  #加上噪声

#分别对应常数系数、x值、x的次方再除以阶乘、算得的y值
true_w,features,poly_features,labels=[torch.tensor(x,dtype=torch.float32) for x in [true_w,features,poly_features,labels]]
true_w[:2],features[:2],poly_features[:2,:],labels[:2]
python 复制代码
#实现函数评估模型损失
def evaluate_loss(net,data_iter,loss):
    '''评估给定数据集上模型的损失'''
    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]

#from torch.utils import data

#定义训练函数
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])
    #print(train_labels.shape)   [100]
    #print(train_labels.shape[0])   100
    #print(batch_size)   10
    train_iter = d2l.load_array((train_features, train_labels.reshape(-1,1)),
                                batch_size)
    #等价于以下两行代码
#     train_dataset=data.TensorDataset(train_features,train_labels.reshape(-1,1))
#     train_iter=data.DataLoader(train_dataset,batch_size,shuffle=True)
    
    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:   #每20个epoch训练迭代周期,评估一次模型损失(包括训练集和测试集),画一次数据点
            animator.add(epoch + 1, (evaluate_loss(net, train_iter, loss),  #评估训练数据集上模型损失
                                     evaluate_loss(net, test_iter, loss)))  #评估测试数据集上模型损失
    print('weight:', net[0].weight.data.numpy())  #输出最终模型的参数权重
python 复制代码
#使用三阶多项式拟合,与数据生成函数的阶数相同(正常)
# 从多项式特征中选择前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:])
python 复制代码
#使用线性函数拟合非线性函数(这里是三阶多项式函数),线性模型很容易欠拟合
# 从多项式特征中选择前2个维度,即1和x
train(poly_features[:n_train, :2], poly_features[n_train:, :2],
      labels[:n_train], labels[n_train:])
python 复制代码
#使用一个阶数过高的复杂多项式模型来训练会造成过拟合。在这种情况下,没有足够的数据用于学到高阶系数应该具有接近于零的值。 因此,这个过于复杂的模型会轻易受到训练数据中噪声的影响。 虽然训练损失可以有效地降低,但测试损失仍然很高。 
# 从多项式特征中选取所有维度
train(poly_features[:n_train, :], poly_features[n_train:, :],
      labels[:n_train], labels[n_train:], num_epochs=1500)
相关推荐
奈斯。zs2 分钟前
yjs08——矩阵、数组的运算
人工智能·python·线性代数·矩阵·numpy
Melody20502 分钟前
tensorflow-dataset 内网下载 指定目录
人工智能·python·tensorflow
DisonTangor35 分钟前
阿里通义千问开源Qwen2.5系列模型:Qwen2-VL-72B媲美GPT-4
人工智能·计算机视觉
豆浩宇35 分钟前
Halcon OCR检测 免训练版
c++·人工智能·opencv·算法·计算机视觉·ocr
LLSU1339 分钟前
聚星文社AI软件小说推文软件
人工智能
JackieZhengChina42 分钟前
吴泳铭:AI最大的想象力不在手机屏幕,而是改变物理世界
人工智能·智能手机
ShuQiHere43 分钟前
【ShuQiHere】 探索数据挖掘的世界:从概念到应用
人工智能·数据挖掘
嵌入式杂谈44 分钟前
OpenCV计算机视觉:探索图片处理的多种操作
人工智能·opencv·计算机视觉
时光追逐者1 小时前
分享6个.NET开源的AI和LLM相关项目框架
人工智能·microsoft·ai·c#·.net·.netcore
东隆科技1 小时前
PicoQuant公司:探索铜铟镓硒(CIGS)太阳能电池技术,引领绿色能源革新
人工智能·能源