2--模型选择 过拟合 欠拟合

2.1 模型选择、过拟合、欠拟合

        在评估几个候选模型后选择最终的模型的过程叫做模型选择。有时需要进行比较的模型在本质上是完全不同的(比如,决策树与线性模型),有时需要比较不同的超参数设置下的同一类模型。为了确定候选模型中的最佳模型,通常会使用验证集。

        验证集区别于测试集,验证集用来查看模型表现的情况,可以在验证集上进行参数的调整以达到最好的效果,而测试集只能用一次,是模型没有见过的数据,在测试集上能表现该模型真实的性能以及泛化性。

        当数据集较少无法提供合适验证集的时候,可以使用K折交叉验证。即原始训练数据被分成K个不重叠的子集。然后执行K次模型训练和验证,每次在K−1个子集上进行训练,并在剩余的一个子集(在该轮中没有用于训练的子集)上进行验证。 最后,通过对K次实验的结果取平均来估计训练和验证误差。这里可以直接使用得到的k个模型均值,或者确定好超参数后在用所有数据训练一次,或者就选择表现最好的那个模型直接使用。

        欠拟合:训练误差和验证误差都很严重,它们之间仅有一点差距。即模型不够复杂,学到的东西很少。

        过拟合:训练误差明显低于验证误差。即模型学得太好了,把一些不重要的特征也学到了。

2.2 代码展示

!pip install git+https://github.com/d2l-ai/d2l-zh@release  # installing d2l
! pip install matplotlib==3.0.0

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

max_degree = 20
n_train, n_test = 100, 100
true_w = np.zeros(max_degree)
true_w[: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的n次方
for i in range(max_degree):
  poly_features[:,i] /= math.gamma(i+1)#生成多项式
labels = np.dot(poly_features,true_w)
labels += np.random.normal(scale=0.1, size=labels.shape)#添加噪音

#将numpy转化为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:
    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)
    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:])


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

正常拟合结果: 在训练集和验证集上的损失都在400轮后降低到0.01左右

 

 

欠拟合结果: 可以看到,在两个数据集上最后达到的效果是远远不如正常结果的,这里最后的损失大概是10左右,是比较大的。

  

过拟合结果: 可以看出在1500轮后,在验证集上的损失是大于训练集的。

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值