import torch
from torch import nn
from d2l import torch as d2l
import os
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
# 51 序列模型
T = 1000 # 总共产生1000个点
time = d2l.arange(1, T + 1, dtype=d2l.float32)
x = d2l.sin(0.01 * time) + d2l.normal(0, 0.2, (T,)) # 正弦加噪音
# 0是正态分布的均值,0.2是标准差,控制噪声的强度。(T,)指定了噪声张量的形状,与时间time张量的形状相同(使用逗号来表示元组)
d2l.plot(time, [x], 'time', 'x', xlim=[1, 1000], figsize=(6, 3))
d2l.plt.show()
tau = 4
features = d2l.zeros((T - tau, tau)) # 每四个数据作为特征,第五个作为标签,不断构造这样的数据形成数据集
for i in range(tau):
features[:, i] = x[i: T - tau + i] # 每个样本对应该时刻开始四个特征
labels = d2l.reshape(x[tau:], (-1, 1))
batch_size, n_train = 16, 600
# 只有前n_train个样本用于训练
train_iter = d2l.load_array((features[:n_train], labels[:n_train]),batch_size, is_train=True)
# 初始化网络权重的函数
def init_weights(m):
if type(m) == nn.Linear:
nn.init.xavier_uniform_(m.weight)
# 一个简单的多层感知机
def get_net():
net = nn.Sequential(nn.Linear(4, 10),
nn.ReLU(),
nn.Linear(10, 1))
net.apply(init_weights)
return net
# 平方损失。注意:MSELoss计算平方误差时不带系数1/2
loss = nn.MSELoss(reduction='none')
# 训练模型
def train(net, train_iter, loss, epochs, lr):
trainer = torch.optim.Adam(net.parameters(), lr) # 定义优化器
for epoch in range(epochs):
for X, y in train_iter:
trainer.zero_grad()
l = loss(net(X), y) # 前向传播计算损失
l.sum().backward() # 反向传播求梯度
trainer.step() # 更新模型参数
print(f'epoch {epoch + 1}, '
f'loss: {d2l.evaluate_loss(net, train_iter, loss):f}')
net = get_net() # 创建神经网络模型
train(net, train_iter, loss, 5, 0.01) # 训练模型
# 预测
onestep_preds = net(features)
d2l.plot([time, time[tau:]],
[d2l.numpy(x), d2l.numpy(onestep_preds)], 'time',
'x', legend=['data', '1-step preds'], xlim=[1, 1000],
figsize=(6, 3))
d2l.plt.show()
multistep_preds = d2l.zeros(T) # 初始化多步预测结果的张量
multistep_preds[: n_train + tau] = x[: n_train + tau] # 将已知的真实数据赋值给多步预测结果
for i in range(n_train + tau, T):
multistep_preds[i] = net(d2l.reshape(multistep_preds[i - tau: i], (1, -1)))
d2l.plot([time, time[tau:], time[n_train + tau:]],
[d2l.numpy(x), d2l.numpy(onestep_preds),
d2l.numpy(multistep_preds[n_train + tau:])], 'time',
'x', legend=['data', '1-step preds', 'multistep preds'],
xlim=[1, 1000], figsize=(6, 3))
d2l.plt.show()
max_steps = 64 # 最大步长
features = d2l.zeros((T - tau - max_steps + 1, tau + max_steps)) # 初始化特征张量
# 列i(i<tau)是来自x的观测,其时间步从(i)到(i+T-tau-max_steps+1)
for i in range(tau):
features[:, i] = x[i: i + T - tau - max_steps + 1]
# 列i(i>=tau)是来自(i-tau+1)步的预测,其时间步从(i)到(i+T-tau-max_steps+1)
for i in range(tau, tau + max_steps):
features[:, i] = d2l.reshape(net(features[:, i - tau: i]), -1)
steps = (1, 4, 16, 64)
d2l.plot([time[tau + i - 1: T - max_steps + i] for i in steps],
[d2l.numpy(features[:, tau + i - 1]) for i in steps], 'time', 'x',
legend=[f'{i}-step preds' for i in steps], xlim=[5, 1000],
figsize=(6, 3))
d2l.plt.show()
51 序列模型
最新推荐文章于 2024-07-15 15:37:59 发布