机器学习:模型选择、欠拟合和过拟合

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

# y = 5 + 1.2x - 3.4*(x^2/2!) + 5.6*(x^3/3!) + E  where E 属于N(0,0.1^2)
max_degree = 20  # 特征为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])  # 就前面4个是有值的,后面全是0,就是噪音了

# 生成了一个形状为(n_train + n_test, 1)的数组,其中的元素都是从正态分布中随机抽取的。这就是我们的原始特征。
features = np.random.normal(size=(n_train + n_test, 1))

# 将features数组的元素随机打乱。
np.random.shuffle(features)

# 生成了多项式特征。
# 使用np.arange(max_degree)生成一个从0到max_degree-1的数组,然后使用reshape(1, -1)将其变形为一个列向量。
# 接着,使用np.power函数将原始特征features的每一个元素都提升到这个列向量中的每一个元素所代表的次幂,
# 从而得到多项式特征。
poly_features = np.power(features, np.arange(max_degree).reshape(1, -1))

for i in range(max_degree):  # 对每一个多项式特征进行归一化。
    # 在循环中,这行代码将第i个多项式特征的每一个元素都除以math.gamma(i + 1)。
    # 这是为了使得每个多项式特征的期望值为0。但是,当i=0时,这会导致除以0的错误,因为math.gamma(1)返回的是0。
    poly_features[:, i] /= math.gamma(i + 1)

# 使用np.dot函数计算多项式特征poly_features和权重向量true_w的点积,从而生成标签。
labels = np.dot(poly_features, true_w)

# 向生成的标签添加一些正态分布的噪音,其中噪音的标准差为0.1。
labels += np.random.normal(scale=0.1, size=labels.shape)

true_w, features, poly_features, labels = [
    torch.tensor(x, dtype=torch.float32)
    for x in [true_w, features, poly_features, labels]
]

# print(features[:2], '\n', poly_features[:2, :], '\n', labels[:2])


# 实现一个函数来评估模型再给定数据集上的损失
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())  # 将当前批次的损失总和(l.sum())和损失元素的数量(l.numel())添加到 metric 对象中。
    return metric[0] / metric[1]  # 返回整个数据集的平均损失,即所有批次的损失总和除以所有损失元素的数量。


# 定义训练函数
def train(train_features, test_features, train_labels, test_labels, num_epochs=400):
    loss = nn.MSELoss()
    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())


train(poly_features[:n_train, :4], poly_features[n_train:, :4], labels[:n_train], labels[n_train:])

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值