·  阅读 100

# 3.1. 模型选择、欠拟合和过拟合

## 3.1.3. 欠拟合和过拟合

### 3.1.3.1. 模型复杂度

y^=b+∑k=1Kxkwky^=b+∑k=1Kxkwk

## 3.1.4. 多项式函数拟合实验

``````In [1]:

``````%matplotlib inline
import d2lzh as d2l
from mxnet import autograd, gluon, nd
from mxnet.gluon import data as gdata, loss as gloss, nn

### 3.1.4.1. 生成数据集

y=1.2x−3.4x2+5.6x3+5+ϵ,y=1.2x−3.4x2+5.6x3+5+ϵ,

``````In [2]:

``````n_train, n_test, true_w, true_b = 100, 100, [1.2, -3.4, 5.6], 5
features = nd.random.normal(shape=(n_train + n_test, 1))
poly_features = nd.concat(features, nd.power(features, 2),
nd.power(features, 3))
labels = (true_w[0] * poly_features[:, 0] + true_w[1] * poly_features[:, 1]
+ true_w[2] * poly_features[:, 2] + true_b)
labels += nd.random.normal(scale=0.1, shape=labels.shape)

``````In [3]:

``````features[:2], poly_features[:2], labels[:2]

``````Out[3]:

``````(
[[2.2122064]
[0.7740038]]
<NDArray 2x1 @cpu(0)>,
[[ 2.2122064   4.893857   10.826221  ]
[ 0.7740038   0.5990819   0.46369165]]
<NDArray 2x3 @cpu(0)>,
[51.674885   6.3585763]
<NDArray 2 @cpu(0)>)

### 3.1.4.2. 定义、训练和测试模型

``````In [4]:

``````# 本函数已保存在d2lzh包中方便以后使用
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)

``````In [5]:

``````num_epochs, loss = 100, gloss.L2Loss()

def fit_and_plot(train_features, test_features, train_labels, test_labels):
net = nn.Sequential()
net.initialize()
batch_size = min(10, train_labels.shape[0])
train_features, train_labels), batch_size, shuffle=True)
trainer = gluon.Trainer(net.collect_params(), 'sgd',
{'learning_rate': 0.01})
train_ls, test_ls = [], []
for _ in range(num_epochs):
for X, y in train_iter:
l = loss(net(X), y)
l.backward()
trainer.step(batch_size)
train_ls.append(loss(net(train_features),
train_labels).mean().asscalar())
test_ls.append(loss(net(test_features),
test_labels).mean().asscalar())
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[0].weight.data().asnumpy(),
'\nbias:', net[0].bias.data().asnumpy())

### 3.1.4.3. 三阶多项式函数拟合（正常）

``````In [6]:

``````fit_and_plot(poly_features[:n_train, :], poly_features[n_train:, :],
labels[:n_train], labels[n_train:])

``````final epoch: train loss 0.0067995964 test loss 0.010894175
weight: [[ 1.319636  -3.3645654  5.5645313]]
bias: [4.9527817]

### 3.1.4.4. 线性函数拟合（欠拟合）

``````In [7]:

``````fit_and_plot(features[:n_train, :], features[n_train:, :], labels[:n_train],
labels[n_train:])

``````final epoch: train loss 43.99766 test loss 160.84781
weight: [[15.548418]]
bias: [2.2836545]

### 3.1.4.5. 训练样本不足（过拟合）

``````In [8]:

``````fit_and_plot(poly_features[0:2, :], poly_features[n_train:, :], labels[0:2],
labels[n_train:])

``````final epoch: train loss 0.4027369 test loss 103.314186
weight: [[1.3872364 1.9376589 3.5085924]]
bias: [1.2312856]

## 3.1.5. 小结

• 由于无法从训练误差估计泛化误差，一味地降低训练误差并不意味着泛化误差一定会降低。机器学习模型应关注降低泛化误差。
• 可以使用验证数据集来进行模型选择。
• 欠拟合指模型无法得到较低的训练误差，过拟合指模型的训练误差远小于它在测试数据集上的误差。
• 应选择复杂度合适的模型并避免使用过少的训练样本。