【笔记】动手学深度学习-模型选择,拟合

模型选择

验证数据集:用来评估模型好坏的数据集。例如:拿出50%的训练数据。验证数据集没有参加训练,所以可以在一定程度上参数选择好坏。不要跟训练数据混在一起(常犯错误)。

测试数据集:只用一次的数据集,不能用来调参。例如:未来的考试

而我们在代码中写的test_data一般指的是验证数据集,测试数据集应该是新找的。

但是通常情况下我们是没有那么多数据来验证,所以提出了

k-折交叉验证:

        将数据分为k块

        Fori=1....K

                使用第i块作为验证数据集,其余的作为训练数据

        报告K个验证集误差的平均

即每次在K块数据中选择一个作为测试数据集,其余为训练数据集。

常用:K=5或10

过拟合和欠拟合

模型容量 应该匹配数据复杂度,否则就会出现过拟合和欠拟合。

下图分别是欠拟合、合适、和过拟合。

模型容量指的是拟合各种函数的能力:低容量模型难以拟合训练数据,高容量模型可以记住所有训练数据。如图:

泛化误差就是真正的误差

训练误差指的是对于训练数据的误差,当误差特别特别小时,就过拟合了

代码

本次例子用于验证下面这个式子

 

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]) #生成真实值,前面的4项参数是有值的,后面的都是噪音


'''另外加入一点噪音'''
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))
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)



# 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):  #传入网络,数据,损失函数
    metric = d2l.Accumulator(2)  # 损失的总和, 样本数量
    for X, y in data_iter: #每次从data_iter里面拿出一组数据
        out = net(X)
        y = y.reshape(out.shape) 
        l = loss(out, y) #根据计算出的out和y来求loss
        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()
    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:])

# 从多项式特征中选择前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)

-

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值