1、涉及语句 import d2lzh1981 as d2l

数据1 :

d2lzh1981

链接:https://pan.baidu.com/s/1LyaZ84Q4M75GLOO-ZPvPoA

提取码:cf8s

2、FashionMNIST2065数据集

涉及语句

batch_size = 256

train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size,root=’/home/kesci/input/FashionMNIST2065’)

数据2 : 为方便,可把数据直接下载下来。

为使用需

1)保持数据文件夹的路径把数据拷贝到jupyter notebook路径下

2)修改 home路径前加点 ,即’./home/kesci/input/FashionMNIST2065’)。

3)修改d2lzh1981文件下的utils.py 的load_data_fashion_mnist() 方法。为

torchvision.datasets.FashionMNIST(root=root, train=True, download=False, transform=transform)

FashionMNIST2065

链接:https://pan.baidu.com/s/1MLhOsusr5hqPn8sik1bUqw

提取码:v0l8**

10

过拟合、欠拟合及其解决方案

  1. 过拟合、欠拟合的概念
  2. 权重衰减
  3. 丢弃法

    下载地址:下载

    https://download.csdn.net/download/xiuyu1860/12156306

模型选择、过拟合和欠拟合

训练误差和泛化误差

在解释上述现象之前,我们需要区分训练误差(training error)和泛化误差(generalization error)。通俗来讲,前者指模型在训练数据集上表现出的误差,后者指模型在任意一个测试数据样本上表现出的误差的期望,并常常通过测试数据集上的误差来近似。计算训练误差和泛化误差可以使用之前介绍过的损失函数,例如线性回归用到的平方损失函数和softmax回归用到的交叉熵损失函数。

机器学习模型应关注降低泛化误差。

模型选择

验证数据集

从严格意义上讲,测试集只能在所有超参数和模型参数选定后使用一次。不可以使用测试数据选择模型,如调参。由于无法从训练误差估计泛化误差,因此也不应只依赖训练数据选择模型。鉴于此,我们可以预留一部分在训练数据集和测试数据集以外的数据来进行模型选择。这部分数据被称为验证数据集,简称验证集(validation set)。例如,我们可以从给定的训练集中随机选取一小部分作为验证集,而将剩余部分作为真正的训练集。

K折交叉验证

由于验证数据集不参与模型训练,当训练数据不够用时,预留大量的验证数据显得太奢侈。一种改善的方法是K折交叉验证(K-fold cross-validation)。在K折交叉验证中,我们把原始训练数据集分割成K个不重合的子数据集,然后我们做K次模型训练和验证。每一次,我们使用一个子数据集验证模型,并使用其他K-1个子数据集来训练模型。在这K次训练和验证中,每次用来验证模型的子数据集都不同。最后,我们对这K次训练误差和验证误差分别求平均。

过拟合和欠拟合

接下来,我们将探究模型训练中经常出现的两类典型问题:

  • 一类是模型无法得到较低的训练误差,我们将这一现象称作欠拟合(underfitting);
  • 另一类是模型的训练误差远小于它在测试数据集上的误差,我们称该现象为过拟合(overfitting)。

    在实践中,我们要尽可能同时应对欠拟合和过拟合。虽然有很多因素可能导致这两种拟合问题,在这里我们重点讨论两个因素:模型复杂度和训练数据集大小。

模型复杂度

为了解释模型复杂度,我们以多项式函数拟合为例。给定一个由标量数据特征xxx和对应的标量标签yyy组成的训练数据集,多项式函数拟合的目标是找一个KKK阶多项式函数

y^=b+∑k=1Kxkwk
\hat{y} = b + \sum_{k=1}^K x^k w_k
y^​=b+k=1∑K​xkwk​

来近似 yyy。在上式中,wkw_kwk​是模型的权重参数,bbb是偏差参数。与线性回归相同,多项式函数拟合也使用平方损失函数。特别地,一阶多项式函数拟合又叫线性函数拟合。

给定训练数据集,模型复杂度和误差之间的关系:

训练数据集大小

影响欠拟合和过拟合的另一个重要因素是训练数据集的大小。一般来说,如果训练数据集中样本数过少,特别是比模型参数数量(按元素计)更少时,过拟合更容易发生。此外,泛化误差不会随训练数据集里样本数量增加而增大。因此,在计算资源允许的范围之内,我们通常希望训练数据集大一些,特别是在模型复杂度较高时,例如层数较多的深度学习模型。

多项式函数拟合实验

%matplotlib inline
import torch
import numpy as np
import sys
sys.path.append("/home/kesci/input")
import d2lzh1981 as d2l
print(torch.__version__)
1.3.0

初始化模型参数

n_train, n_test, true_w, true_b = 100, 100, [1.2, -3.4, 5.6], 5
features = torch.randn((n_train + n_test, 1))
poly_features = torch.cat((features, torch.pow(features, 2), torch.pow(features, 3)), 1)
labels = (true_w[0] * poly_features[:, 0] + true_w[1] * poly_features[:, 1]
+ true_w[2] * poly_features[:, 2] + true_b)
labels += torch.tensor(np.random.normal(0, 0.01, size=labels.size()), dtype=torch.float)
features[:2], poly_features[:2], labels[:2]
(tensor([[1.0065],
[0.4447]]), tensor([[1.0065, 1.0131, 1.0197],
[0.4447, 0.1977, 0.0879]]), tensor([8.4715, 5.3434]))

定义、训练和测试模型

def semilogy(x_vals, y_vals, x_label, y_label, x2_vals=None, y2_vals=None,
legend=None, figsize=(3.5, 2.5)):
# d2l.set_figsize(figsize)
d2l.plt.xlabel(x_label)
d2l.plt.ylabel(y_label)
d2l.plt.semilogy(x_vals, y_vals)
if x2_vals and y2_vals:
d2l.plt.semilogy(x2_vals, y2_vals, linestyle=':')
d2l.plt.legend(legend)
num_epochs, loss = 100, torch.nn.MSELoss()

def fit_and_plot(train_features, test_features, train_labels, test_labels):
# 初始化网络模型
net = torch.nn.Linear(train_features.shape[-1], 1)
# 通过Linear文档可知,pytorch已经将参数初始化了,所以我们这里就不手动初始化了 # 设置批量大小
batch_size = min(10, train_labels.shape[0])
dataset = torch.utils.data.TensorDataset(train_features, train_labels) # 设置数据集
train_iter = torch.utils.data.DataLoader(dataset, batch_size, shuffle=True) # 设置获取数据方式 optimizer = torch.optim.SGD(net.parameters(), lr=0.01) # 设置优化函数,使用的是随机梯度下降优化
train_ls, test_ls = [], []
for _ in range(num_epochs):
for X, y in train_iter: # 取一个批量的数据
l = loss(net(X), y.view(-1, 1)) # 输入到网络中计算输出,并和标签比较求得损失函数
optimizer.zero_grad() # 梯度清零,防止梯度累加干扰优化
l.backward() # 求梯度
optimizer.step() # 迭代优化函数,进行参数优化
train_labels = train_labels.view(-1, 1)
test_labels = test_labels.view(-1, 1)
train_ls.append(loss(net(train_features), train_labels).item()) # 将训练损失保存到train_ls中
test_ls.append(loss(net(test_features), test_labels).item()) # 将测试损失保存到test_ls中
print('final epoch: train loss', train_ls[-1], 'test loss', test_ls[-1])
semilogy(range(1, num_epochs + 1), train_ls, 'epochs', 'loss',
range(1, num_epochs + 1), test_ls, ['train', 'test'])
print('weight:', net.weight.data,
'\nbias:', net.bias.data)

三阶多项式函数拟合(正常)

fit_and_plot(poly_features[:n_train, :], poly_features[n_train:, :], labels[:n_train], labels[n_train:])
final epoch: train loss 0.00013102585216984153 test loss 0.00014579357230104506
weight: tensor([[ 1.2092, -3.3994, 5.5965]])
bias: tensor([5.0003])

线性函数拟合(欠拟合)

fit_and_plot(features[:n_train, :], features[n_train:, :], labels[:n_train], labels[n_train:])
final epoch: train loss 56.10523986816406 test loss 203.95297241210938
weight: tensor([[12.9553]])
bias: tensor([1.8765])

训练样本不足(过拟合)

fit_and_plot(poly_features[0:2, :], poly_features[n_train:, :], labels[0:2], labels[n_train:])
final epoch: train loss 0.30480968952178955 test loss 336.5728759765625
weight: tensor([[2.4363, 1.9240, 1.2780]])
bias: tensor([3.0333])

权重衰减

方法

权重衰减等价于 L2L_2L2​ 范数正则化(regularization)。正则化通过为模型损失函数添加惩罚项使学出的模型参数值较小,是应对过拟合的常用手段。

L2 范数正则化(regularization)

L2L_2L2​范数正则化在模型原损失函数基础上添加L2L_2L2​范数惩罚项,从而得到训练所需要最小化的函数。L2L_2L2​范数惩罚项指的是模型权重参数每个元素的平方和与一个正的常数的乘积。以线性回归中的线性回归损失函数为例

ℓ(w1,w2,b)=1n∑i=1n12(x1(i)w1+x2(i)w2+b−y(i))2
\ell(w_1, w_2, b) = \frac{1}{n} \sum_{i=1}^n \frac{1}{2}\left(x_1^{(i)} w_1 + x_2^{(i)} w_2 + b - y^{(i)}\right)^2
ℓ(w1​,w2​,b)=n1​i=1∑n​21​(x1(i)​w1​+x2(i)​w2​+b−y(i))2

其中w1,w2w_1, w_2w1​,w2​是权重参数,bbb是偏差参数,样本iii的输入为x1(i),x2(i)x_1^{(i)}, x_2^{(i)}x1(i)​,x2(i)​,标签为y(i)y^{(i)}y(i),样本数为nnn。将权重参数用向量w=[w1,w2]\boldsymbol{w} = [w_1, w_2]w=[w1​,w2​]表示,带有L2L_2L2​范数惩罚项的新损失函数为

ℓ(w1,w2,b)+λ2n∣w∣2,
\ell(w_1, w_2, b) + \frac{\lambda}{2n} |\boldsymbol{w}|^2,
ℓ(w1​,w2​,b)+2nλ​∣w∣2,

其中超参数λ>0\lambda > 0λ>0。当权重参数均为0时,惩罚项最小。当λ\lambdaλ较大时,惩罚项在损失函数中的比重较大,这通常会使学到的权重参数的元素较接近0。当λ\lambdaλ设为0时,惩罚项完全不起作用。上式中L2L_2L2​范数平方∣w∣2|\boldsymbol{w}|^2∣w∣2展开后得到w12+w22w_1^2 + w_2^2w12​+w22​。

有了L2L_2L2​范数惩罚项后,在小批量随机梯度下降中,我们将线性回归一节中权重w1w_1w1​和w2w_2w2​的迭代方式更改为

w1←(1−ηλ∣B∣)w1−η∣B∣∑i∈Bx1(i)(x1(i)w1+x2(i)w2+b−y(i)),w2←(1−ηλ∣B∣)w2−η∣B∣∑i∈Bx2(i)(x1(i)w1+x2(i)w2+b−y(i)).
\begin{aligned} w_1 &\leftarrow \left(1- \frac{\eta\lambda}{|\mathcal{B}|} \right)w_1 - \frac{\eta}{|\mathcal{B}|} \sum_{i \in \mathcal{B}}x_1^{(i)} \left(x_1^{(i)} w_1 + x_2^{(i)} w_2 + b - y^{(i)}\right),\\ w_2 &\leftarrow \left(1- \frac{\eta\lambda}{|\mathcal{B}|} \right)w_2 - \frac{\eta}{|\mathcal{B}|} \sum_{i \in \mathcal{B}}x_2^{(i)} \left(x_1^{(i)} w_1 + x_2^{(i)} w_2 + b - y^{(i)}\right). \end{aligned}
w1​w2​​←(1−∣B∣ηλ​)w1​−∣B∣η​i∈B∑​x1(i)​(x1(i)​w1​+x2(i)​w2​+b−y(i)),←(1−∣B∣ηλ​)w2​−∣B∣η​i∈B∑​x2(i)​(x1(i)​w1​+x2(i)​w2​+b−y(i)).​

可见,L2L_2L2​范数正则化令权重w1w_1w1​和w2w_2w2​先自乘小于1的数,再减去不含惩罚项的梯度。因此,L2L_2L2​范数正则化又叫权重衰减。权重衰减通过惩罚绝对值较大的模型参数为需要学习的模型增加了限制,这可能对过拟合有效。

高维线性回归实验从零开始的实现

下面,我们以高维线性回归为例来引入一个过拟合问题,并使用权重衰减来应对过拟合。设数据样本特征的维度为ppp。对于训练数据集和测试数据集中特征为x1,x2,…,xpx_1, x_2, \ldots, x_px1​,x2​,…,xp​的任一样本,我们使用如下的线性函数来生成该样本的标签:

y=0.05+∑i=1p0.01xi+ϵ
y = 0.05 + \sum_{i = 1}^p 0.01x_i + \epsilon
y=0.05+i=1∑p​0.01xi​+ϵ

其中噪声项ϵ\epsilonϵ服从均值为0、标准差为0.01的正态分布。为了较容易地观察过拟合,我们考虑高维线性回归问题,如设维度p=200p=200p=200;同时,我们特意把训练数据集的样本数设低,如20。

%matplotlib inline
import torch
import torch.nn as nn
import numpy as np
import sys
sys.path.append("/home/kesci/input")
import d2lzh1981 as d2l print(torch.__version__)
1.3.0

初始化模型参数

与前面观察过拟合和欠拟合现象的时候相似,在这里不再解释。

n_train, n_test, num_inputs = 20, 100, 200
true_w, true_b = torch.ones(num_inputs, 1) * 0.01, 0.05 features = torch.randn((n_train + n_test, num_inputs))
labels = torch.matmul(features, true_w) + true_b
labels += torch.tensor(np.random.normal(0, 0.01, size=labels.size()), dtype=torch.float)
train_features, test_features = features[:n_train, :], features[n_train:, :]
train_labels, test_labels = labels[:n_train], labels[n_train:]
# 定义参数初始化函数,初始化模型参数并且附上梯度
def init_params():
w = torch.randn((num_inputs, 1), requires_grad=True)
b = torch.zeros(1, requires_grad=True)
return [w, b]

定义L2范数惩罚项

def l2_penalty(w):
return (w**2).sum() / 2

定义训练和测试

batch_size, num_epochs, lr = 1, 100, 0.003
net, loss = d2l.linreg, d2l.squared_loss dataset = torch.utils.data.TensorDataset(train_features, train_labels)
train_iter = torch.utils.data.DataLoader(dataset, batch_size, shuffle=True) def fit_and_plot(lambd):
w, b = init_params()
train_ls, test_ls = [], []
for _ in range(num_epochs):
for X, y in train_iter:
# 添加了L2范数惩罚项
l = loss(net(X, w, b), y) + lambd * l2_penalty(w)
l = l.sum() if w.grad is not None:
w.grad.data.zero_()
b.grad.data.zero_()
l.backward()
d2l.sgd([w, b], lr, batch_size)
train_ls.append(loss(net(train_features, w, b), train_labels).mean().item())
test_ls.append(loss(net(test_features, w, b), test_labels).mean().item())
d2l.semilogy(range(1, num_epochs + 1), train_ls, 'epochs', 'loss',
range(1, num_epochs + 1), test_ls, ['train', 'test'])
print('L2 norm of w:', w.norm().item())

观察过拟合

fit_and_plot(lambd=0)
L2 norm of w: 13.291242599487305

使用权重衰减

fit_and_plot(lambd=3)
L2 norm of w: 0.04461875185370445

简洁实现

def fit_and_plot_pytorch(wd):
# 对权重参数衰减。权重名称一般是以weight结尾
net = nn.Linear(num_inputs, 1)
nn.init.normal_(net.weight, mean=0, std=1)
nn.init.normal_(net.bias, mean=0, std=1)
optimizer_w = torch.optim.SGD(params=[net.weight], lr=lr, weight_decay=wd) # 对权重参数衰减
optimizer_b = torch.optim.SGD(params=[net.bias], lr=lr) # 不对偏差参数衰减 train_ls, test_ls = [], []
for _ in range(num_epochs):
for X, y in train_iter:
l = loss(net(X), y).mean()
optimizer_w.zero_grad()
optimizer_b.zero_grad() l.backward() # 对两个optimizer实例分别调用step函数,从而分别更新权重和偏差
optimizer_w.step()
optimizer_b.step()
train_ls.append(loss(net(train_features), train_labels).mean().item())
test_ls.append(loss(net(test_features), test_labels).mean().item())
d2l.semilogy(range(1, num_epochs + 1), train_ls, 'epochs', 'loss',
range(1, num_epochs + 1), test_ls, ['train', 'test'])
print('L2 norm of w:', net.weight.data.norm().item())
fit_and_plot_pytorch(0)
L2 norm of w: 14.70448112487793

fit_and_plot_pytorch(3)
L2 norm of w: 0.0769280269742012

丢弃法

多层感知机中神经网络图描述了一个单隐藏层的多层感知机。其中输入个数为4,隐藏单元个数为5,且隐藏单元hih_ihi​(i=1,…,5i=1, \ldots, 5i=1,…,5)的计算表达式为

hi=ϕ(x1w1i+x2w2i+x3w3i+x4w4i+bi)
h_i = \phi\left(x_1 w_{1i} + x_2 w_{2i} + x_3 w_{3i} + x_4 w_{4i} + b_i\right)
hi​=ϕ(x1​w1i​+x2​w2i​+x3​w3i​+x4​w4i​+bi​)

这里ϕ\phiϕ是激活函数,x1,…,x4x_1, \ldots, x_4x1​,…,x4​是输入,隐藏单元iii的权重参数为w1i,…,w4iw_{1i}, \ldots, w_{4i}w1i​,…,w4i​,偏差参数为bib_ibi​。当对该隐藏层使用丢弃法时,该层的隐藏单元将有一定概率被丢弃掉。设丢弃概率为ppp,那么有ppp的概率hih_ihi​会被清零,有1−p1-p1−p的概率hih_ihi​会除以1−p1-p1−p做拉伸。丢弃概率是丢弃法的超参数。具体来说,设随机变量ξi\xi_iξi​为0和1的概率分别为ppp和1−p1-p1−p。使用丢弃法时我们计算新的隐藏单元hi′h_i'hi′​

hi′=ξi1−phi
h_i' = \frac{\xi_i}{1-p} h_i
hi′​=1−pξi​​hi​

由于E(ξi)=1−pE(\xi_i) = 1-pE(ξi​)=1−p,因此

E(hi′)=E(ξi)1−phi=hi
E(h_i') = \frac{E(\xi_i)}{1-p}h_i = h_i
E(hi′​)=1−pE(ξi​)​hi​=hi​

即丢弃法不改变其输入的期望值。让我们对之前多层感知机的神经网络中的隐藏层使用丢弃法,一种可能的结果如图所示,其中h2h_2h2​和h5h_5h5​被清零。这时输出值的计算不再依赖h2h_2h2​和h5h_5h5​,在反向传播时,与这两个隐藏单元相关的权重的梯度均为0。由于在训练中隐藏层神经元的丢弃是随机的,即h1,…,h5h_1, \ldots, h_5h1​,…,h5​都有可能被清零,输出层的计算无法过度依赖h1,…,h5h_1, \ldots, h_5h1​,…,h5​中的任一个,从而在训练模型时起到正则化的作用,并可以用来应对过拟合。在测试模型时,我们为了拿到更加确定性的结果,一般不使用丢弃法

丢弃法从零开始的实现

%matplotlib inline
import torch
import torch.nn as nn
import numpy as np
import sys
sys.path.append("/home/kesci/input")
import d2lzh1981 as d2l print(torch.__version__)
1.3.0
def dropout(X, drop_prob):
X = X.float()
assert 0 <= drop_prob <= 1
keep_prob = 1 - drop_prob
# 这种情况下把全部元素都丢弃
if keep_prob == 0:
return torch.zeros_like(X)
mask = (torch.rand(X.shape) < keep_prob).float() return mask * X / keep_prob
X = torch.arange(16).view(2, 8)
dropout(X, 0)
tensor([[ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.],
[ 8., 9., 10., 11., 12., 13., 14., 15.]])
dropout(X, 0.5)
tensor([[ 0.,  2.,  4.,  0.,  0.,  0.,  0., 14.],
[16., 0., 20., 0., 24., 0., 0., 30.]])
dropout(X, 1.0)
tensor([[0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0.]])
# 参数的初始化
num_inputs, num_outputs, num_hiddens1, num_hiddens2 = 784, 10, 256, 256 W1 = torch.tensor(np.random.normal(0, 0.01, size=(num_inputs, num_hiddens1)), dtype=torch.float, requires_grad=True)
b1 = torch.zeros(num_hiddens1, requires_grad=True)
W2 = torch.tensor(np.random.normal(0, 0.01, size=(num_hiddens1, num_hiddens2)), dtype=torch.float, requires_grad=True)
b2 = torch.zeros(num_hiddens2, requires_grad=True)
W3 = torch.tensor(np.random.normal(0, 0.01, size=(num_hiddens2, num_outputs)), dtype=torch.float, requires_grad=True)
b3 = torch.zeros(num_outputs, requires_grad=True) params = [W1, b1, W2, b2, W3, b3]
drop_prob1, drop_prob2 = 0.2, 0.5

def net(X, is_training=True):
X = X.view(-1, num_inputs)
H1 = (torch.matmul(X, W1) + b1).relu()
if is_training: # 只在训练模型时使用丢弃法
H1 = dropout(H1, drop_prob1) # 在第一层全连接后添加丢弃层
H2 = (torch.matmul(H1, W2) + b2).relu()
if is_training:
H2 = dropout(H2, drop_prob2) # 在第二层全连接后添加丢弃层
return torch.matmul(H2, W3) + b3
def evaluate_accuracy(data_iter, net):
acc_sum, n = 0.0, 0
for X, y in data_iter:
if isinstance(net, torch.nn.Module):
net.eval() # 评估模式, 这会关闭dropout
acc_sum += (net(X).argmax(dim=1) == y).float().sum().item()
net.train() # 改回训练模式
else: # 自定义的模型
if('is_training' in net.__code__.co_varnames): # 如果有is_training这个参数
# 将is_training设置成False
acc_sum += (net(X, is_training=False).argmax(dim=1) == y).float().sum().item()
else:
acc_sum += (net(X).argmax(dim=1) == y).float().sum().item()
n += y.shape[0]
return acc_sum / n
num_epochs, lr, batch_size = 5, 100.0, 256  # 这里的学习率设置的很大,原因与之前相同。
loss = torch.nn.CrossEntropyLoss()
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size, root='/home/kesci/input/FashionMNIST2065')
d2l.train_ch3(
net,
train_iter,
test_iter,
loss,
num_epochs,
batch_size,
params,
lr)
epoch 1, loss 0.0045, train acc 0.548, test acc 0.763
epoch 2, loss 0.0023, train acc 0.783, test acc 0.773
epoch 3, loss 0.0019, train acc 0.821, test acc 0.830
epoch 4, loss 0.0017, train acc 0.841, test acc 0.822
epoch 5, loss 0.0016, train acc 0.846, test acc 0.848

简洁实现

net = nn.Sequential(
d2l.FlattenLayer(),
nn.Linear(num_inputs, num_hiddens1),
nn.ReLU(),
nn.Dropout(drop_prob1),
nn.Linear(num_hiddens1, num_hiddens2),
nn.ReLU(),
nn.Dropout(drop_prob2),
nn.Linear(num_hiddens2, 10)
) for param in net.parameters():
nn.init.normal_(param, mean=0, std=0.01)
optimizer = torch.optim.SGD(net.parameters(), lr=0.5)
d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, batch_size, None, None, optimizer)
epoch 1, loss 0.0046, train acc 0.542, test acc 0.731
epoch 2, loss 0.0023, train acc 0.781, test acc 0.742
epoch 3, loss 0.0019, train acc 0.823, test acc 0.821

总结

  • 欠拟合现象:模型无法达到一个较低的误差

  • 过拟合现象:训练误差较低但是泛化误差依然较高,二者相差较大

L7过拟合欠拟合及其解决方案的更多相关文章

  1. 动手学习Pytorch(4)--过拟合欠拟合及其解决方案

    过拟合.欠拟合及其解决方案 过拟合.欠拟合的概念 权重衰减 丢弃法   模型选择.过拟合和欠拟合 训练误差和泛化误差 在解释上述现象之前,我们需要区分训练误差(training error)和泛化误差 ...

  2. L13过拟合欠拟合及其解决方案

    过拟合.欠拟合及其解决方案 过拟合.欠拟合的概念 权重衰减 丢弃法 模型选择.过拟合和欠拟合 训练误差和泛化误差 在解释上述现象之前,我们需要区分训练误差(training error)和泛化误差(g ...

  3. 过拟合/欠拟合&logistic回归等总结(Ng第二课)

    昨天学习完了Ng的第二课,总结如下: 过拟合:欠拟合: 参数学习算法:非参数学习算法 局部加权回归 KD tree 最小二乘 中心极限定律 感知器算法 sigmod函数 梯度下降/梯度上升 二元分类 ...

  4. [DeeplearningAI笔记]改善深层神经网络1.1_1.3深度学习使用层面_偏差/方差/欠拟合/过拟合/训练集/验证集/测试集

    觉得有用的话,欢迎一起讨论相互学习~Follow Me 1.1 训练/开发/测试集 对于一个数据集而言,可以将一个数据集分为三个部分,一部分作为训练集,一部分作为简单交叉验证集(dev)有时候也成为验 ...

  5. 过拟合VS欠拟合、偏差VS方差

    1. 过拟合 欠拟合 过拟合:在训练集(training set)上表现好,但是在测试集上效果差,也就是说在已知的数据集合中非常好,但是在添加一些新的数据进来训练效果就会差很多,造成这样的原因是考虑影 ...

  6. 局部加权回归、欠拟合、过拟合(Locally Weighted Linear Regression、Underfitting、Overfitting)

    欠拟合.过拟合 如下图中三个拟合模型.第一个是一个线性模型,对训练数据拟合不够好,损失函数取值较大.如图中第二个模型,如果我们在线性模型上加一个新特征项,拟合结果就会好一些.图中第三个是一个包含5阶多 ...

  7. 第三集 欠拟合与过拟合的概念、局部加权回归、logistic回归、感知器算法

    课程大纲 欠拟合的概念(非正式):数据中某些非常明显的模式没有成功的被拟合出来.如图所示,更适合这组数据的应该是而不是一条直线. 过拟合的概念(非正式):算法拟合出的结果仅仅反映了所给的特定数据的特质 ...

  8. TensorFlow从1到2(八)过拟合和欠拟合的优化

    <从锅炉工到AI专家(6)>一文中,我们把神经网络模型降维,简单的在二维空间中介绍了过拟合和欠拟合的现象和解决方法.但是因为条件所限,在该文中我们只介绍了理论,并没有实际观察现象和应对. ...

  9. 斯坦福大学公开课机器学习: advice for applying machine learning - evaluatin a phpothesis(怎么评估学习算法得到的假设以及如何防止过拟合或欠拟合)

    怎样评价我们的学习算法得到的假设以及如何防止过拟合和欠拟合的问题. 当我们确定学习算法的参数时,我们考虑的是选择参数来使训练误差最小化.有人认为,得到一个很小的训练误差一定是一件好事.但其实,仅仅是因 ...

随机推荐

  1. 如何获取主键返回值(MySQL、Oracle)

    添加用户.返回主键 --场景:在执行新增用户sql后,service层返回新增用户的主键值(与mybatis一起使用) insert into user(username, sex, birthday ...

  2. 李瑞红201771010111《面向对象程序设计(java)》第四周学习总结

    实验四:类与对象的定义及使用 第一部分:理论知识学习 1.类与对象概念 (1)类是构造对象的模板或蓝图,由类构造对象的过程称为创建类的实例.   (2)对象:即数据,对象有三个特性,行为.状态.标识. ...

  3. TensorFlow 多元线性回归【波士顿房价】

    1数据读取 1.1数据集解读 1.2引入包 %matplotlib notebook import tensorflow as tf import matplotlib.pyplot as plt i ...

  4. P5020 货币系统 题解

    原题链接 简要题意: 求一个长度最小的货币系统与给出的货币系统等价.求这个货币系统的长度.等价的定义详见题目,不再赘述. 本文可能用到一些集合论,请放心食用. 算法一 \(n=2\) 时,只需判断两个 ...

  5. NLP interview

    2019-08-26 17:19:58 1)聊实习项目 2)代码题,二维数组中的查找某个target 3)讲一些最能体现创新能力的工作,而不是一些工程上的实现 4)讲论文可以从哪些方面做创新点,文本生 ...

  6. Redis 缓存更新一致性

    当执行写操作后,需要保证从缓存读取到的数据与数据库中持久化的数据是一致的,因此需要对缓存进行更新. 因为涉及到数据库和缓存两步操作,难以保证更新的原子性. 在设计更新策略时,我们需要考虑多个方面的问题 ...

  7. Windows下用Python你会几种copy文件的方法?

    1. [代码]1. os.system ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 import os import temp ...

  8. 力软敏捷框架7.0.6 葡萄城报表升级到ar14版本

    忙了两天终于搞定升级到ar14版本,坑无数,终于算全部解决,在这里做一个小结. 1.第一步去掉框架中原本集成的ar13部分(吐槽一下应该是对12的集成). 首先去掉licenses.licx文件. 然 ...

  9. 使用Keras进行深度学习:(二)CNN讲解及实践

    欢迎大家关注我们的网站和系列教程:http://www.tensorflownews.com/,学习更多的机器学习.深度学习的知识! 现今最主流的处理图像数据的技术当属深度神经网络了,尤其是卷积神经网 ...

  10. 【Pytest05】全网最全最新的Pytest框架之用例分组执行

    一.Fixture用例分组运行常用于冒烟测试,分模块运行等 pytest.ini配置文件中增加分组参数markers来实现用例分组,如: markers = g1:组一 smoke:冒烟测试 pyte ...