李沐动手学深度学习代码标注----4.4模型的选择

自己在学习的时候标注的,分享出来让大家学习时能够快速理解代码的意思,

                                                               如有标注不足之处,敬请指正!

import math
import matplotlib.pyplot as plt
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))
np.random.shuffle(features)#随机打乱
poly_features = np.power(features, np.arange(max_degree).reshape(1, -1))#计算x的y次方
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)
'模拟噪音'
#模拟噪音,从正态分布中‘’‘’‘{loc是分布的均值,scale是分布的标准差}
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]]

features[:2], poly_features[:2, :], labels[:2]






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)
    #优化函数SGD
    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())






'验证数据量的复杂程度对模型的复杂程度的比较'
# 从多项式特征中选择前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:])
d2l.plt.show()


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


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



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

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

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

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

你可能感兴趣的:(李沐动手学深度学习,深度学习,python,机器学习)