李沐深度学习记录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)
相关推荐
大熊背3 分钟前
图像处理专业书籍以及网络资源总结
人工智能·算法·microsoft
江理不变情10 分钟前
图像质量对比感悟
c++·人工智能
张较瘦_2 小时前
[论文阅读] 人工智能 + 软件工程 | 需求获取访谈中LLM生成跟进问题研究:来龙去脉与创新突破
论文阅读·人工智能
一 铭3 小时前
AI领域新趋势:从提示(Prompt)工程到上下文(Context)工程
人工智能·语言模型·大模型·llm·prompt
麻雀无能为力7 小时前
CAU数据挖掘实验 表分析数据插件
人工智能·数据挖掘·中国农业大学
时序之心7 小时前
时空数据挖掘五大革新方向详解篇!
人工智能·数据挖掘·论文·时间序列
.30-06Springfield7 小时前
人工智能概念之七:集成学习思想(Bagging、Boosting、Stacking)
人工智能·算法·机器学习·集成学习
说私域8 小时前
基于开源AI智能名片链动2+1模式S2B2C商城小程序的超级文化符号构建路径研究
人工智能·小程序·开源
永洪科技8 小时前
永洪科技荣获商业智能品牌影响力奖,全力打造”AI+决策”引擎
大数据·人工智能·科技·数据分析·数据可视化·bi
shangyingying_18 小时前
关于小波降噪、小波增强、小波去雾的原理区分
人工智能·深度学习·计算机视觉