李沐d2l(六)---模型选择
一、模型选择
训练误差:模型在训练数据上的误差 泛化误差:模型在新数据上的误差 验证数据集:用来评估模型好坏的数据集 测试数据集:只用一次的数据集 K-则交叉验证:在没有足够多数据使用时,可以将训练数据分割成K块,在i = (1,2,… ,k)的循环中,依次想把第i块作为验证数据集,其余的作为训练数据集,最后再报告K个验证集误差的平均。
二、过拟合和欠拟合
模型容量:拟合各种函数的能力;低容量的模型难以拟合训练数据;高容量的模型可以记住所有的训练数据。 下图左边的模型容量就比较低,只能拟合出一条直线,而右边的高容量模型却过于复杂,把噪声都拟合进去了。
模型容量的影响
VC维等于一个最大数据集的大小,不管如何给定标号,都存在一个模型俩对它进行完美的分类。 支持N维输入的感知机的VC维是N + 1,一些多层感知机的VC维O(NLog2 N)
三、代码实现
使用下列三阶多项式来生成训练和测试数据的标签
import math import numpy as np import torch from torch import nn from d2l import torch as d2l import os os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE" 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)) 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) # 查看前两个样本 true_w, features, poly_features, labels = [ torch.tensor(x, dtype=torch.float32) for x in [true_w, features, poly_features, labels]] # print(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() 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:]) d2l.plt.show() weight: [[ 4.982289 1.1968644 -3.388561 5.612971 ]]
现在来看欠拟合的情况,只给出两个特征,可以看到最后的误差非常大。
train(poly_features[:n_train, :2], poly_features[n_train:, :2], labels[:n_train], labels[n_train:]) weight: [[3.3086548 5.039875 ]]
再来看过拟合,相当于把整个数据都给出来(一大部分噪音也被给出),而一些数据会对结果产生误导性。可以看到train和test之间的gap有明显的增加。
上一篇:
通过多线程提高代码的执行效率例子
下一篇:
温控系统设计——过冲问题解决方案