3.11 模型选择、欠拟合和过拟合
3.11.1 训练误差和泛化误差
训练误差:模型在训练数据集上表现出的误差
泛化误差:模型在任一测试数据样本上表现出的误差的期望
机器学习模型应关注降低泛化误差
3.11.2 模型选择
验证数据集 训练数据集合和测试数据集之外的数据
k折交叉验证 2.1 把训练数据集分割成k个不重合的子数据集,然后做k次模型训练和验证 2.2 每一次,使用一个子数据集验证模型,使用其他k-1个子数据集来训练模型 2.3 在这k次训练和验证中,每一次用来验证模型的子数据集都不同。 2.4 对这k次训练误差和验证误差分别求平均。
3.11.3 欠拟合和过拟合
欠拟合:模型无法得到较低的训练误差
过拟合:模型的训练误差远小于它在测试数据集上的误差
给定数据集,如果模型复杂度过低,很容易出现欠拟合;
给定数据集,如果模型复杂度过高,很容易出现过拟合。
泛化误差不会随训练数据集中的样本数量增加而增大。
3.11.4 多项式函数拟合实验
% matplotlib inline
import d2lzh as d2l
from mxnet import autograd, gluon, nd
from mxnet. gluon import data as gdata, loss as gloss, nn
1. 生成数据集
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)
features[ : 2 ] , poly_features[ : 2 ] , labels[ : 2 ]
output:
( [ [ - 0.24919763 ]
[ - 1.2863069 ] ]
< NDArray 2x1 @cpu( 0 ) > ,
[ [ - 0.24919763 0.06209946 - 0.01547504 ]
[ - 1.2863069 1.6545854 - 2.1283045 ] ]
< NDArray 2x3 @cpu( 0 ) > ,
[ 4.4988413 - 14.094537 ]
< NDArray 2 @cpu( 0 ) > )
2. 定义、训练模型
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 , gloss. L2Loss( )
def fit_and_plot ( train_features, test_features, train_labels, test_labels) :
net = nn. Sequential( )
net. add( nn. Dense( 1 ) )
net. initial