课程ppt

image.png
image.png
对见过的数据建模,也称自回归模型
image.png

引入潜变量ht来表示过去信息,ht = f(x1,x2,…,xt-1)
xt = p(xt|ht)

模型1:
x’ 和前一个时间的x和潜变量h’有关
模型2:
h’和前一个时间的x和前一个时间的潜变量h有关

image.png
总结:

  • 时序模型中,当前数据跟之前观察到的数据相关
  • 自回归模型使用自身过去数据来预测未来
  • 马尔可夫模型假设当前只跟最近少数数据相关,从而简化模型
  • 潜变量模型使用潜变量来概括历史信息

part-3_1.pdf

代码

labels = x[tau:].reshape((-1, 1))
这里-1是指未设定行数,程序随机分配,所以这里-1表示任一正整数
所以reshape(-1,1)表示(任意行,1列)
image.png

  1. import torch
  2. from torch import nn
  3. from d2l import torch as d2l
  4. # 序列模型
  5. # 使用正弦函数和一些可加性噪声来生成序列数据,时间步为1,2,..., 1000
  6. T = 1000
  7. time = torch.arange(1,T+1,dtype=torch.float32)
  8. x = torch.sin(0.01*time)+torch.normal(0,0.2,(T,))
  9. d2l.plot(time,[x],'time','x',xlim=[1,1000],figsize=(6,3))
  10. tau = 4
  11. features = torch.zeros((T - tau, tau))
  12. for i in range(tau):
  13. features[:, i] = x[i:T - tau + i]
  14. labels = x[tau:].reshape((-1, 1))
  15. batch_size, n_train = 16, 600
  16. train_iter = d2l.load_array((features[:n_train], labels[:n_train]),
  17. batch_size, is_train=True)
  18. ### 使用一个相当简单的结构:只是一个拥有两个全连接层的多层感知机
  19. def init_weights(m):
  20. if type(m) == nn.Linear:
  21. nn.init.xavier_uniform_(m.weight)
  22. def get_net():
  23. net = nn.Sequential(nn.Linear(4,10),nn.ReLU(),nn.Linear(10,1))
  24. net.apply(init_weights)
  25. return net
  26. loss = nn.MSELoss()
  27. def train(net,train_iter,loss,epochs,lr):
  28. trainer = torch.optim.Adam(net.parameters(),lr)
  29. for epoch in range(epochs):
  30. for X,y in train_iter:
  31. trainer.zero_grad() #梯度设为0
  32. l = loss(net(X),y)
  33. l.backward()
  34. trainer.step()
  35. print(f'epoch {epoch+1},'
  36. f'loss {d2l.evaluate_loss(net,train_iter,loss)}')
  37. net = get_net()
  38. train(net,train_iter,loss,5,0.01)
  39. ### 模型预测下一个时间步
  40. onestep_preds = net(features)
  41. d2l.plot(
  42. [time,time[tau:]],
  43. [x.detach().numpy(),onestep_preds.detach().numpy()],
  44. 'time','x',
  45. legend=['data','1-step preds'],
  46. xlim=[1,1000],figsize=(6,3)
  47. )