当前位置:网站首页>神经网络入门之模型选择(PyTorch)
神经网络入门之模型选择(PyTorch)
2022-07-03 09:27:00 【-素心向暖】
文章目录
模型选择
训练误差和泛化误差
- 训练误差:模型在训练数据上的误差
- 泛化误差:模型在新数据上的误差
- 例子:根据模考成绩来预测未来考试分数
- 在过去的考试中表现很好(训练误差)不代表未来考试一定很好(泛化误差)
- 学生 A 通过背书在模考中拿到很好成绩
- 学生 B 知道答案后面的原因
验证数据集和测试数据集
- 验证数据集:一个用来评估模型好坏的数据集
- 例如拿出50%的训练数据
- 不要跟训练数据混在一起(常犯错误)
- 测试数据集:只用一次的数据集。例如
- 未来的考试
- 我出价的房子的实际成交价
- 用在 Kaggle 私有排行版中的数据集
- 因为验证数据集没有参与训练,一定程度上可以反映模型超参数选择的好坏
- 验证数据集和训练数据及一定不能混在一起
K-则交叉验证
- 在没有足够多数据时使用(这是常态)
- 算法:
- 将训练数据分割成 K 快
- For i =1,…,K
- 使用第 i 块作为验证数据集,其余的作为训练数据集
- 报告 K 个验证数据集误差的平均
- 常用:K=5 或 10
validation dataset 测试数据集
总结
- 训练数据集:训练模型参数
- 验证数据集:选择模型超参数
- 非大数据集上通常使用 k-折交叉验证
k-折交叉验证(k-fold cross-validation)
分成K份,做K次,每次留一份做验证,剩下的作为训练集
来通过K折的平均误差来判断超参数的好坏
过拟合和欠拟合


capacity 容量,也可以理解为能力
模型容量
- 拟合各种函数的能力
- 低容量的模型难以拟合训练数据
- 高容量的模型可以记住所有的训练数据
模型容量的选择
高阶多项式函数比低阶多项式函数复杂得多。 高阶多项式的参数较多,模型函数的选择范围较广。 因此在固定训练数据集的情况下, 高阶多项式函数相对于低阶多项式的训练误差应该始终更低(最坏也是相等)。 事实上,当数据样本包含了 x x x的不同值时, 函数阶数等于数据样本数量的多项式函数可以完美拟合训练集。
估计模型容量
- 难以在不同的种类算法之间比较
- 例如树模型和神经网络
- 给定一个模型种类,将有两个主要参数
- 参数的个数
- 参数值的选择范围

线性模型的参数个数是 d+1 ,1是参数的偏移
VC维
- 统计学习理论的一个核心思想
- 对于一个分类模型,VC等于一个最大的数据集的大小,不管如何给定标号,都存在一个模型来对它进行完美分类
林轩田这块讲得很好(vc dimension),<<机器学习基石>>
线性分类器的VC维
2维输入的感知机,VC维=3
- 能够分类任何三个点,但不是4个(xor)


- 能够分类任何三个点,但不是4个(xor)
支持 N 维输入的感知机的 VC 维是 N+1
一些多层感知机的 VC 维 O ( N l o g 2 N ) O(N log_2N) O(Nlog2N)
2为输入感知机意思是,输入特征是2,输出是1
VC维的用处
- 提供为什么一个模型好的理论依据
- 它可以衡量训练误差和泛化误差之间的间隔
- 但深度学习中很少使用
- 衡量不是很准确
- 计算深度学习模型的 VC 维很困难
数据复杂度
- 多个重要因素
- 样本个数
- 每个样本的元素个数
- 时间、空间结构
- 多样性

总结
- 模型容量需要匹配数据复杂度,否则可能导致欠拟合和过拟合
- 统计机器学习提供数学工具来衡量模型复杂度
- 实际中一般靠观察训练误差和验证误差
代码
多项式回归
通过多项式拟合来探索这些概念
import math
import numpy as np
import torch
from torch import nn
from d2l import torch as d2l
生成数据集
给定,我们将使用以下三阶多项式来生成训练和测试数据的标签:
噪声项 ϵ \epsilon ϵ服从均值为0且标准差为0.1的正态分布。 在优化的过程中,我们通常希望避免非常大的梯度值或损失值。 这就是我们将特征从 x i x^i xi调整为 x i i ! {x^i \over i!} i!xi的原因, 这样可以避免很大的带来的特别大的指数值。 我们将为训练集和测试集各生成100个样本。
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)
同样,存储在poly_features中的单项式由gamma函数重新缩放,其中 Γ ( n ) = ( n − 1 ) ! \Gamma(n)=(n-1)! Γ(n)=(n−1)!。 从生成的数据集中查看一下前2个样本, 第一个值是与偏置相对应的常量特征。
# 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())
三阶多项式函数拟合(正常)
我们将首先使用三阶多项式函数,它与数据生成函数的阶数相同。 结果表明,该模型能有效降低训练损失和测试损失。 学习到的模型参数也接近真实值 w = [ 5 , 1.2 , − 3.4 , 5.6 ] w=[5, 1.2, -3.4, 5.6] w=[5,1.2,−3.4,5.6]。
# 从多项式特征中选择前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:])
weight: [[ 5.0008 1.2447366 -3.4524488 5.443078]]
线性函数拟合(欠拟合)
让我们再看看线性函数拟合,减少该模型的训练损失相对困难。 在最后一个迭代周期完成后,训练损失仍然很高。 当用来拟合非线性模式(如这里的三阶多项式函数)时,线性模型容易欠拟合。
# 从多项式特征中选择前2个维度,即1和x
train(poly_features[:n_train, :2], poly_features[n_train:, :2],
labels[:n_train], labels[n_train:])
weight: [[3.4807658 3.1861916]]
损失根本就没怎么降
高阶多项式函数拟合(过拟合)
现在,让我们尝试使用一个阶数过高的多项式来训练模型。 在这种情况下,没有足够的数据用于学到高阶系数应该具有接近于零的值。 因此,这个过于复杂的模型会轻易受到训练数据中噪声的影响。 虽然训练损失可以有效地降低,但测试损失仍然很高。 结果表明,复杂模型对数据造成了过拟合。
# 从多项式特征中选取所有维度
train(poly_features[:n_train, :], poly_features[n_train:, :],
labels[:n_train], labels[n_train:], num_epochs=1500)


可以看到后面W本来应该都是0的,都被赋予了值
QA
时间序列上的数据,训练集和验证集可能会有自相关性,这时候应该怎么处理?
切一块,不能从中间取一块模型参数和超参数不一样吗?
模型参数是指W和b
超参数,例如是选线性模型还是多层感知机。如果是多层感知机,是选多少层,每层多大,训练的时候学习率是多少。模型参数以外,所有我们要来设计的,都是超参数。如何有效设计超参数,是不是只能搜索?最好用的搜索是贝叶斯方法还是网格、随机?
超参数的设计靠自己的经验。
可以每次随机选择一个模型,然后遍历出其中最好的一个。
边栏推荐
- Hands on deep learning pytorch version exercise solution - 2.4 calculus
- Numpy Foundation
- Raspberry pie 4B installs yolov5 to achieve real-time target detection
- 2.1 Dynamic programming and case study: Jack‘s car rental
- 20220604数学:x的平方根
- Inverse code of string (Jilin University postgraduate entrance examination question)
- 20220531 Mathematics: Happy numbers
- 侯捷——STL源码剖析 笔记
- 3.2 Off-Policy Monte Carlo Methods & case study: Blackjack of off-Policy Evaluation
- Notes - regular expressions
猜你喜欢

Timo background management system

CV learning notes - BP neural network training example (including detailed calculation process and formula derivation)

Boston house price forecast (tensorflow2.9 practice)

High imitation bosom friend manke comic app

One click generate traffic password (exaggerated advertisement title)

Hands on deep learning pytorch version exercise solution - 2.5 automatic differentiation

CV learning notes - Stereo Vision (point cloud model, spin image, 3D reconstruction)

LeetCode - 5 最长回文子串

3.1 Monte Carlo Methods & case study: Blackjack of on-Policy Evaluation
![[C question set] of Ⅵ](/img/49/eb31cd26f7efbc4d57f17dc1321092.jpg)
[C question set] of Ⅵ
随机推荐
LeetCode - 1172 餐盘栈 (设计 - List + 小顶堆 + 栈))
Model evaluation and selection
CV learning notes - deep learning
Notes - regular expressions
一个30岁的测试员无比挣扎的故事,连躺平都是奢望
Leetcode刷题---283
20220605数学:两数相除
Leetcode - 705 design hash set (Design)
一步教你溯源【钓鱼邮件】的IP地址
Convolutional neural network (CNN) learning notes (own understanding + own code) - deep learning
Leetcode刷题---44
Basic use and actual combat sharing of crash tool
Powshell's set location: unable to find a solution to the problem of accepting actual parameters
OpenCV Error: Assertion failed (size.width>0 && size.height>0) in imshow
Rewrite Boston house price forecast task (using paddlepaddlepaddle)
Secure in mysql8.0 under Windows_ file_ Priv is null solution
Leetcode-513:找树的左下角值
Leetcode刷题---832
What useful materials have I learned from when installing QT
Hands on deep learning pytorch version exercise solution - 2.3 linear algebra