← Back to Index
Research & Engineering Archive

D2L 4.4 Model Selection, Underfitting, and Overfitting

By Jingnan Huang · April 15, 2024 · 2313 Words

深度学习的目的是发现Pattern,即做到模型的Generalization 泛化

原因很简单:当我们将来部署该模型时,模型需要判断从未见过的患者。 只有当模型真正发现了一种泛化模式时,才会作出有效的预测

困难在于,当我们训练模型时,我们只能访问数据中的小部分样本。 最大的公开图像数据集包含大约一百万张图像。 而在大部分时候,我们只能从数千或数万个数据样本中学习。 在大型医院系统中,我们可能会访问数十万份医疗记录。 当我们使用有限的样本时,可能会遇到这样的问题: 当收集到更多的数据时,会发现之前找到的明显关系并不成立。

Overfitting 过拟合
#

Regularization 正则化
#

4.4.1 训练误差和泛化误差
#

Training Error 训练误差
#

Generalization Error 泛化误差
#

4.4.1.1 统计学习理论
#

4.4.1.2 模型复杂性
#

Early Stopping 早停
#

4.4.2 模型选择
#

4.4.2.1 验证集
#

训练集,验证集,测试集分别是什么_训练集 验证集 测试集-CSDN博客

Training Set 训练集
#

Validation Set 验证集
#

z

Test Set 测试集
#

4.4.2.2 K-Fold Cross-Validation K折交叉验证
#

过程描述
#

4.4.3 欠拟合还是过拟合?
#

4.4.3.1 模型复杂性
#

![[Pasted image 20240615153938.png]]

Lost 损失
#

Variance 方差
#

4.4.3.2 数据集大小
#

4.4.4 多项式回归
#

4.4.4.1 生成数据集
#

![[Pasted image 20240616094316.png]]

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)  # 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):  #@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)
    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()

欠拟合
#

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