import math
import numpy as np
import torch
from torch import nn
from d2l import torch as d2l
#生成数据集
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])
#噪声项服从均值为0且标准差为0.1的正态分布.
#在优化的过程中,我们通常希望避免非常大的梯度值或损失值。这就是我们将特征调整为gamma的原因,可以避免很大的带来的特别大的指数值
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) #gamma(n) = (n-1)!
#labels的维度:(n_train + n_test,)
labels = np.dot(poly_features,true_w)
labels += np.random.normal(scale=0.1,size=labels.shape)
#存储在poly_features中的单项式由gamma函数重新缩放,从生成的数据集中查看一下前2个样本,第一个值是与偏置相对应的常量特征。
#NumPy ndarray转换为tensor
true_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]
#对模型进行训练和测试
#实现一个函数来评估模型在给定数据集上的损失。
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)
I = loss(out,y)
metric.add(I.sum(),I.numel())
return metric[0] / metric[1]
#定义训练函数
def train(train_features,test_features,train_labels,test_labels,num_epochs=400):
loss = nn.MSELoss(reduction='none')
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())
#三阶多项式函数拟合(正常)
#首先使用三阶多项式函数,它与数据生成函数的阶数相同。结果表明,该模型能有效降低训练损失和测试损失。学习到的模型参数也接近真实值
## 从多项式特征中选择前4个维度,即1,x,x^2/2!,x^3/3!
train(poly_features[:n_train,:4],poly_features[n_train:,:4],
labels[:n_train],labels[n_train:])
d2l.plt.show()
weight: [[ 5.014977 1.2570255 -3.4122806 5.4952126]]
#线性函数拟合(欠拟合)
#线性函数拟合,减少该模型的训练损失相对困难。在最后一个迭代周期完成后,训练损失仍然很高。
#当用来拟合非线性模式(如这里的三阶多项式函数)时,线性模型容易欠拟合。
#从多项式特征中选择前2个维度,即1和x
train(poly_features[:n_train,:2],poly_features[n_train:,:2],
labels[:n_train],labels[n_train:])
d2l.plt.show()
weight: [[3.3760684 3.340304 ]]
#高阶多项式函数拟合(过拟合)
#没有足够的数据用于学到高阶系数应该具有接近于零的值。过于复杂的模型会轻易受到训练数据中噪声的影响。
# 虽然训练损失可以有效地降低,但测试损失仍然很高。
#从多项式特征中选取所有维度
train(poly_features[:n_train, :], poly_features[n_train:, :],
labels[:n_train], labels[n_train:], num_epochs=1500)
weight: [[ 4.9825454 1.2999343 -3.3884344 5.125409 -0.08730704 1.2174056
0.43766126 0.25185174 0.13421033 0.17221996 0.15894955 -0.04748236
-0.07315657 -0.12668477 0.18594444 -0.13069476 -0.04506584 -0.14766978
0.14226449 0.09253487]]