深度学习基础 过拟合 欠拟合 及展示代码

1.模型的选择

误差相关

训练误差:模型再训练数据上的误差

泛化误差:模型再新数据上的误差

举例:训练误差相当于平时学生做模拟卷子的分数,泛化误差相当于高考时考试的分数

训练误差好的模型泛化误差不一定好

数据集

验证数据集:一个评估模型好坏的数据集(通常用来调整参数)

例:拿出50%训练数据

验证数据集不能与训练数据有交叉

测试数据集:只用一次的数据集(测试模型真正水平)

K-则交叉验证(本片并没有使用)

如果拿出一把数据用来训练,一半用来验证太浪费数据

算法:将数据分为k块

从1到k遍历,取遍历到的块为验证数据集,剩下为训练数据集,误差为k的损失的平均0

2.过拟合和欠拟合

过拟合是指在机器学习中,模型在训练集上表现较好,但在测试集或实际应用中表现较差的现象

欠拟合是指模型不能在训练集上获得足够低的误差。

打比方就是过拟合记住了所有问题的答案有一定做题能力,但其他题就不会做了,而欠拟合是储备知识不足题都做不出来

 

通俗地讲,模型的容量是指它拟合各种函数的能力 

下图是模型容量与数据复杂程度对于模型拟合的影响

 

模型容量与误差之间的关系 

 

 3代码实验

引入

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

数据的生成

生成100含有20个参数的向量做训练数据(100,20),前5个为有效参数其余为噪音,生成100做测试数据(100,20)

以及生成计算结果(100,1)打乱放入迭代器

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])#定义真实的权重,剩下16个是噪音
features = np.random.normal(size=(n_train + n_test, 1))#生成200个数据x   (1,200)
np.random.shuffle(features)#打乱x
poly_features = np.power(features, np.arange(max_degree).reshape(1, -1))#-1指让系统自动计算第二维度的容量   power为幂运算  可以是  (12)**(12)得到对应位置   (1)**(12)得到(12)  1分别去幂运算12个数
for i in range(max_degree):
    poly_features[:, i] /= math.gamma(i + 1) # gamma计算阶乘
# labels的维度:(n_train+n_test,)
labels = np.dot(poly_features, true_w)#计算出y
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]]

计算平均损失

def evaluate_loss(net, data_iter, loss): #平均损失
    """评估给定数据集上模型的损失"""
    metric = d2l.Accumulator(2) # 损失的总和,样本数量
    for X, y in data_iter:
        out = net(X) # (bathsize,zidingyi)->(batchsize,1)
        # 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)
        for X,y in train_iter:#训练模型
            shuchu=net(X)
            l=loss(shuchu,y)
            trainer.zero_grad()
            l.backward()
            trainer.step()
        if epoch == 0 or (epoch + 1) % 20 == 0:#每训练20次 测试一遍损失
            animator.add(epoch + 1, (evaluate_loss(net, train_iter, loss),
            evaluate_loss(net, test_iter, loss)))
    d2l.plt.show()
    print('weight:', net[0].weight.data.numpy())

测试

1.正常的拟合

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

只传入前5个有用的参数

 发现可以较好的拟合

2.欠拟合

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

只取前两个参数进行训练

损失值都比较高,无法有效拟合

3.过拟合 

train(poly_features[:n_train, :], poly_features[n_train:, :],
labels[:n_train], labels[n_train:],num_epochs=1000)

将前20个参数都学了进去,包括噪音

 发生的过拟合

总代码

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])#定义真实的权重,剩下16个是噪音
features = np.random.normal(size=(n_train + n_test, 1))#生成200个数据x   (1,200)
np.random.shuffle(features)#打乱x
poly_features = np.power(features, np.arange(max_degree).reshape(1, -1))#-1指让系统自动计算第二维度的容量   power为幂运算  可以是  (12)**(12)得到对应位置   (1)**(12)得到(12)  1分别去幂运算12个数
for i in range(max_degree):
    poly_features[:, i] /= math.gamma(i + 1) # gamma计算阶乘
# labels的维度:(n_train+n_test,)
labels = np.dot(poly_features, true_w)#计算出y
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]]
def evaluate_loss(net, data_iter, loss): #平均损失
    """评估给定数据集上模型的损失"""
    metric = d2l.Accumulator(2) # 损失的总和,样本数量
    for X, y in data_iter:
        out = net(X) # (bathsize,zidingyi)->(batchsize,1)
        # 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)
        for X,y in train_iter:#训练模型
            shuchu=net(X)
            l=loss(shuchu,y)
            trainer.zero_grad()
            l.backward()
            trainer.step()
        if epoch == 0 or (epoch + 1) % 20 == 0:#每训练20次 测试一遍损失
            animator.add(epoch + 1, (evaluate_loss(net, train_iter, loss),
            evaluate_loss(net, test_iter, loss)))
    d2l.plt.show()
    print('weight:', net[0].weight.data.numpy())
# train(poly_features[:n_train, :4], poly_features[n_train:, :4],
# labels[:n_train], labels[n_train:])
# 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=1000)

参考自《动手学深度学习

过拟合(overfitting)和欠拟合(underfitting)出现原因及如何避免方案-CSDN博客

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值