import torch
from torch import nn
import numpy as np
import matplotlib.pyplot as plt # 超参数
# 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() # 定义神经网络
# 对每一个 r_out 都得放到 Linear 中去计算出预测的 output, 所以能用一个 for loop 来循环计算.
class RNN(nn.Module):
def __init__(self):
super(RNN, self).__init__() # 继承 __init__ 功能 self.rnn = nn.RNN( # 一个普通的 RNN
input_size=INPUT_SIZE,
hidden_size=32, # rnn hidden unit 32个神经元
num_layers=1, # number of rnn layer # 有几层 RNN layers
batch_first=True, # input & output will has batch size as 1s dimension. e.g. (batch, time_step, input_size) # input & output 会是以 batch size 为第一维度的特征集 e.g. (batch, time_step, input_size)
)
self.out = nn.Linear(32, 1) def forward(self, x, h_state): # 因为 hidden state 是连续的, 所以要一直传递这一个 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) # h_state 也要作为 RNN 的一个输入 outs = [] # save all predictions # 保存所有时间点的预测值
for time_step in range(r_out.size(1)): # calculate output for each time step # 对每一个时间点计算 output
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()

pytorch1.0实现RNN for Regression的更多相关文章

  1. 用pytorch1.0快速搭建简单的神经网络

    用pytorch1.0搭建简单的神经网络 import torch import torch.nn.functional as F # 包含激励函数 # 建立神经网络 # 先定义所有的层属性(__in ...

  2. pytorch1.0 用torch script导出模型

    python的易上手和pytorch的动态图特性,使得pytorch在学术研究中越来越受欢迎,但在生产环境,碍于python的GIL等特性,可能达不到高并发.低延迟的要求,存在需要用c++接口的情况. ...

  3. pytorch-1.0 踩坑记录

    参加百度的一个竞赛,官方要求把提交的代码测试环境pyorch1.0,于是将自己计算机pytorch升级到1.0. 在ubuntu下用conda install pytorch 命令安装时,效果很差,解 ...

  4. windows10 安装 Anaconda 并配置 pytorch1.0

    官网下载Anaconda安装包,按步骤安装即可安装完后,打开DOS,或Anaconda自带的Anaconda Prompt终端查看Anaconda已安装的安装包C:\Users\jiangshan&g ...

  5. pytorch1.0实现RNN-LSTM for Classification

    import torch from torch import nn import torchvision.datasets as dsets import torchvision.transforms ...

  6. pytorch1.0进行Optimizer 优化器对比

    pytorch1.0进行Optimizer 优化器对比 import torch import torch.utils.data as Data # Torch 中提供了一种帮助整理数据结构的工具, ...

  7. pytorch1.0批训练神经网络

    pytorch1.0批训练神经网络 import torch import torch.utils.data as Data # Torch 中提供了一种帮助整理数据结构的工具, 叫做 DataLoa ...

  8. pytorch1.0神经网络保存、提取、加载

    pytorch1.0网络保存.提取.加载 import torch import torch.nn.functional as F # 包含激励函数 import matplotlib.pyplot ...

  9. 用pytorch1.0搭建简单的神经网络:进行多分类分析

    用pytorch1.0搭建简单的神经网络:进行多分类分析 import torch import torch.nn.functional as F # 包含激励函数 import matplotlib ...

随机推荐

  1. Java RabbitMQ配置和使用,基于SpringBoot

    package rabbitmq.demo; import com.rabbitmq.client.AMQP; import org.junit.Test; import org.junit.runn ...

  2. 【洛谷】P1275 魔板(暴力&思维)

    题目描述 有这样一种魔板:它是一个长方形的面板,被划分成n行m列的n*m个方格.每个方格内有一个小灯泡,灯泡的状态有两种(亮或暗).我们可以通过若干操作使魔板从一个状态改变为另一个状态.操作的方式有两 ...

  3. SpringMVC的处理器全局异常处理类

    SpringMVC的处理器全局异常处理类 package com.huawei.utils; import org.springframework.web.servlet.HandlerExcepti ...

  4. 和小哥哥一起刷洛谷(5) 图论之深度优先搜索DFS

    关于dfs dfs伪代码: void dfs(s){ for(int i=0;i<s的出度;i++){ if(used[i]为真) continue; used[i]=1; dfs(i); } ...

  5. 覆盖elementui样式

    前台以表格形式展示后台数据,图片或视频点击后弹出框播放,用el-dialog实现. 希望播放视频的时候不显示dialog的背景那些. 尝试 scoped 无果 <style lang=" ...

  6. python 输出‘\xe8\xb4\x9d\xe8\xb4\x9d’, ‘\xe6\x99\xb6\xe6\x99\xb6’, ‘\xe6\xac\xa2\xe6\xac\xa2’]

    如上代码块,结果输出为: [‘\xe8\xb4\x9d\xe8\xb4\x9d’, ‘\xe6\x99\xb6\xe6\x99\xb6’, ‘\xe6\xac\xa2\xe6\xac\xa2’] 北京 ...

  7. input标签type="file"上传文件的css样式

    <!doctype html> <html> <head> <meta charset="utf-8"> <title> ...

  8. 《Linux设备驱动程序》第三版 scull编译 Ubuntu18.04

    0 准备工作. 0.0 系统环境:Ubuntu18.04.1 amd64. 0.1 安装必要软件包 1 sudo apt install build-essential bison flex libs ...

  9. 深入理解JS中&&和||

    写了这么多JS,才发现JS的语法既是属于C语系的,又与一般C语系的编程语言某些地方有很大区别,其中&&和||就是其中一例. C语系中的&&和|| C语系的&&a ...

  10. redis删除多个键

    DEL命令的参数不支持通配符,但我们可以结合Linux的管道和xargs命令自己实现删除所有符合规则的键.比如要删除所有以“user:”开头的键,就可以执行redis-cli KEYS "u ...