import math
import numpy as np
import torch
from torch import nn
import commfuncs
# step 1: 生成数据集(x,y)
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]) # 示例给定
features = np.random.normal(size=(n_train + n_test, 1)) # 随机生成x
# 默认标准正态 def normal(loc=0.0, scale=1.0, size=None)
# print(features.shape)
# print(features[:5])
np.random.shuffle(features) # 随机打乱数据
# 开始逐步算y
poly_features = np.power(features, np.arange(max_degree).reshape(1, -1)) # broadcasting
# print(poly_features[:5,:])
# print(poly_features.shape) # (200,20)
'''
broadcasting
x = np.array([[1], [2], [3]])
y = np.array([1, 2, 3])
z = np.power(x, y)
[[ 1^1 1^2 1^3]
[ 2^1 2^2 2^3]
[ 3^1 3^2 3^3]]
'''
for i in range(max_degree):
poly_features[:, i] /= math.gamma(i+1) # gamma(n) = (n-1)!
labels = np.dot(poly_features, true_w) # (200,20) (20,1)
labels += np.random.normal(scale=0.1, size=labels.shape) # 算出y了
# print(labels[:5])
# print(labels.shape)
# 转化数据类型 从数组到tensor
true_w, features, poly_features, labels = [torch.tensor(x, dtype=torch.float32) for x in
[true_w, features, poly_features, labels]]
# step 2: 对模型进行训练和测试
def evaluate_loss(net, data_iter, loss):
metric = commfuncs.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()) # 累加当轮的损失函数值+用到的样本个数
print("l.numel()",l.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] # -1 最后一个参数
# print(train_features.shape) # 100,4
# print(train_features.shape[-1]) # 4
net = nn.Sequential(nn.Linear(input_shape, 1, bias=False)) # 一层 输入input_shape个 输出1个
batch_size = min(10, train_labels.shape[0])
train_iter = commfuncs.load_array((train_features, train_labels.reshape(-1, 1)), batch_size) # 数据迭代器
test_iter = commfuncs.load_array((test_features, test_labels.reshape(-1, 1)), batch_size, is_train=False)
trainer = torch.optim.SGD(net.parameters(), lr=0.01) # 优化算法
for epoch in range(num_epochs):
commfuncs.train_epoch_ch3(net, train_iter, loss, trainer)
print(f'epoch {epoch + 1}, train loss {evaluate_loss(net, train_iter, loss): f}, '
f'test loss {evaluate_loss(net, test_iter, loss): f}')
print('weight:', net[0].weight.data.numpy())
# 三阶多项式函数拟合
train(poly_features[:n_train, :4], poly_features[n_train:, :4], labels[:n_train], labels[n_train:])
# underfitting
train(poly_features[:n_train, :2], poly_features[n_train:, :2], labels[:n_train], labels[n_train:])
# 模型太简单了没学会模式
# overfitting
train(poly_features[:n_train, :], poly_features[n_train:, :], labels[:n_train], labels[n_train:], num_epochs=1500)
# 在数据集相同的情况下 模型越复杂月容易过拟合