app开发者平台在数字化时代的重要性与发展趋势解析
647
2022-11-18
动手深度学习4月11日
模型选择、欠拟合和过拟合
import mathimport numpy as npimport torchfrom torch import nnfrom d2l import torch as
生成数据集
max_degree = 20n_train, n_test = 100, 100true_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)
看一下前两个样本
# NumPy ndarray转换为tensortrue_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]
(tensor([[-0.4808], [-1.2272]]), tensor([[ 1.0000e+00, -4.8082e-01, 1.1560e-01, -1.8527e-02, 2.2270e-03, -2.1416e-04, 1.7162e-05, -1.1789e-06, 7.0853e-08, -3.7853e-09, 1.8201e-10, -7.9557e-12, 3.1877e-13, -1.1790e-14, 4.0493e-16, -1.2980e-17, 3.9006e-19, -1.1032e-20, 2.9470e-22, -7.4579e-24], [ 1.0000e+00, -1.2272e+00, 7.5305e-01, -3.0805e-01, 9.4514e-02, -2.3198e-02, 4.7449e-03, -8.3187e-04, 1.2761e-04, -1.7401e-05, 2.1355e-06, -2.3825e-07, 2.4366e-08, -2.3002e-09, 2.0163e-10, -1.6497e-11, 1.2653e-12, -9.1344e-14, 6.2278e-15, -4.0226e-16]]), tensor([ 3.9838, -0.8609]))
实现一个函数来评估模型在给定数据集上的损失
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() 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:])
weight: [[ 5.0135717 1.3508536 -3.4156091 5.128729 ]]
线性函数拟合(欠拟合)
# 从多项式特征中选择前2个维度,即 1, xtrain(poly_features[:n_train, :2], poly_features[n_train:, :2], labels[:n_train], labels[n_train:])
weight: [[3.7977045 3.2206762]]
高阶多项式函数拟合(过拟合)
# Pick all the dimensions from the polynomial featurestrain(poly_features[:n_train, :], poly_features[n_train:, :], labels[:n_train], labels[n_train:], num_epochs=1500)
weight: [[ 4.9865603 1.2511449 -3.2733696 5.3045583 -0.50323266 1.0441713 0.10415662 0.03293074 -0.20018525 -0.07525058 0.13166684 -0.01062546 0.07663539 0.06715228 0.1376793 -0.20864992 -0.1013298 -0.1149036 -0.05261741 0.17634636]]
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~