关于RNN模型参数的解释,可以参看RNN参数解释
  ###仅为自己练习,没有其他用途

 1 import torch
from torch import nn
import numpy as np
import matplotlib.pyplot as plt # torch.manual_seed(1) # reproducible # Hyper Parameters
TIME_STEP = 10 # rnn time step
INPUT_SIZE = 1 # rnn input size
LR = 0.02 # learning rate # show data
steps = np.linspace(0, np.pi*2, 100, dtype=np.float32) # float32 for converting torch FloatTensor
x_np = np.sin(steps)
y_np = np.cos(steps)
plt.plot(steps, y_np, 'r-', label='target (cos)')
plt.plot(steps, x_np, 'b-', label='input (sin)')
plt.legend(loc='best')
plt.show() class RNN(nn.Module):
def __init__(self):
super(RNN, self).__init__() self.rnn = nn.RNN(
input_size=INPUT_SIZE,
hidden_size=32, # rnn hidden unit
num_layers=1, # number of rnn layer
batch_first=True, # input & output will has batch size as 1s dimension. e.g. (batch, time_step, input_size)
)
self.out = nn.Linear(32, 1) def forward(self, x, h_state):
# x (batch, time_step, input_size)
# h_state (n_layers, batch, hidden_size)
# r_out (batch, time_step, hidden_size)
r_out, h_state = self.rnn(x, h_state) outs = [] # save all predictions
for time_step in range(r_out.size(1)): # calculate output for each time step
outs.append(self.out(r_out[:, time_step, :]))
return torch.stack(outs, dim=1), h_state # instead, for simplicity, you can replace above codes by follows
# r_out = r_out.view(-1, 32)
# outs = self.out(r_out)
# outs = outs.view(-1, TIME_STEP, 1)
# return outs, h_state # or even simpler, since nn.Linear can accept inputs of any dimension
# and returns outputs with same dimension except for the last
# outs = self.out(r_out)
# return outs rnn = RNN()
print(rnn) optimizer = torch.optim.Adam(rnn.parameters(), lr=LR) # optimize all cnn parameters
loss_func = nn.MSELoss() h_state = None # for initial hidden state plt.figure(1, figsize=(12, 5))
plt.ion() # continuously plot for step in range(100):
start, end = step * np.pi, (step+1)*np.pi # time range
# use sin predicts cos
steps = np.linspace(start, end, TIME_STEP, dtype=np.float32, endpoint=False) # float32 for converting torch FloatTensor
x_np = np.sin(steps)
y_np = np.cos(steps) x = torch.from_numpy(x_np[np.newaxis, :, np.newaxis]) # shape (batch, time_step, input_size)
y = torch.from_numpy(y_np[np.newaxis, :, np.newaxis]) prediction, h_state = rnn(x, h_state) # rnn output
# !! next step is important !!
h_state = h_state.data # repack the hidden state, break the connection from last iteration loss = loss_func(prediction, y) # calculate loss
optimizer.zero_grad() # clear gradients for this training step
loss.backward() # backpropagation, compute gradients
optimizer.step() # apply gradients # plotting
plt.plot(steps, y_np.flatten(), 'r-')
plt.plot(steps, prediction.data.numpy().flatten(), 'b-')
plt.draw(); plt.pause(0.05) plt.ioff()
plt.show()

最新文章

  1. 使用SQLServer同义词和SQL邮件,解决发布订阅中订阅库丢失数据的问题
  2. linux下cp覆盖原so文件时引起的段错误原因确定
  3. hibernate_Restrictions用法
  4. Rails : css或js文件无法成功预编译或调用jquery类插件时预编译问题
  5. Unity开发 资源准备
  6. python中get、post数据
  7. 操作符重载.xml
  8. cuda中时间用法
  9. 1002 Fire Net
  10. RegisterHotKey注册热键,然后响应WM_HOTKEY消息
  11. Java中容器的两种初始化方式比较
  12. POJ 1182 食物链 -- 解题报告
  13. 第二章——机器学习项目完整案例(End-to-End Machine Learning Project)
  14. VS中拒绝在if语句中赋值 (转)
  15. day09内存管理
  16. Linux umask
  17. 2017-2018-2 20155303『网络对抗技术』Exp4:恶意代码分析
  18. tornado请求头/状态码/接口 笔记
  19. 摘:用ADO操作数据库的方法步骤
  20. 关于font-size对垂直居中影响的问题

热门文章

  1. php配置xdebug插件,断点调试
  2. VMware Workstation CentOS7 Linux 学习之路(1)--系统安装
  3. Ubuntu 设置中文输入法
  4. matplotlib 折线图
  5. es7中数组如何判断元素是否存在
  6. Ninject 初步 -Getting Started with Ninject 精通ASP-NET-MVC-5-弗瑞曼 Listing 6-10
  7. 20200104模拟赛 问题A 图样
  8. 《即时消息技术剖析与实战》学习笔记8——IM系统如何保证长连接的可用性:心跳机制
  9. 机器学习-TensorFlow应用之classification和ROC curve
  10. 看看AQS阻塞队列和条件队列