当前位置:网站首页>李沐d2l(六)---模型选择
李沐d2l(六)---模型选择
2022-07-26 08:57:00 【madkeyboard】
一、模型选择
训练误差:模型在训练数据上的误差
泛化误差:模型在新数据上的误差
验证数据集:用来评估模型好坏的数据集
测试数据集:只用一次的数据集
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有明显的增加。
边栏推荐
- 合工大苍穹战队视觉组培训Day6——传统视觉,图像处理
- Day06 homework - skill question 7
- 高数 | 武爷『经典系列』每日一题思路及易错点总结
- Self review ideas of probability theory
- tcp 解决short write问题
- 【final关键字的使用】
- 机器学习中的概率模型
- Recurrence of SQL injection vulnerability in the foreground of a 60 terminal security management system
- day06 作业---技能题7
- Uni app simple mall production
猜你喜欢
sklearn 机器学习基础(线性回归、欠拟合、过拟合、岭回归、模型加载保存)
ES6模块化导入导出)(实现页面嵌套)
数据库操作技能7
Day06 homework - skill question 6
day06 作业---技能题7
idea快捷键 alt实现整列操作
[eslint] Failed to load parser ‘@typescript-eslint/parser‘ declared in ‘package. json » eslint-confi
Nuxt - 项目打包部署及上线到服务器流程(SSR 服务端渲染)
C Entry series (31) -- operator overloading
正则表达式:判断是否符合USD格式
随机推荐
zsh: command not found: nvm
What are the differences in the performance of different usages such as count (*), count (primary key ID), count (field) and count (1)? That's more efficient
Cve-2021-21975 VMware SSRF vulnerability recurrence
Ansible important components (playbook)
[recommended collection] summary of MySQL 30000 word essence - partitions, tables, databases and master-slave replication (V)
Pan micro e-cology8 foreground SQL injection POC
unity简易消息机制
day06 作业--技能题6
Espressif plays with the compilation environment
Nuxt - 项目打包部署及上线到服务器流程(SSR 服务端渲染)
[recommended collection] MySQL 30000 word essence summary - query and transaction (III)
2022年上海市安全员C证考试试题及模拟考试
Matlab 绘制阴影误差图
Okaleido上线聚变Mining模式,OKA通证当下产出的唯一方式
The idea shortcut key ALT realizes the whole column operation
at、crontab
Database operation topic 1
Typescript snowflake primary key generator
本地缓存
Ueditot_ JSP SSRF vulnerability recurrence