关于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()

pytorch之 RNN regression的更多相关文章

  1. pytorch实现rnn并且对mnist进行分类

    1.RNN简介 rnn,相比很多人都已经听腻,但是真正用代码操练起来,其中还是有很多细节值得琢磨. 虽然大家都在说,我还是要强调一次,rnn实际上是处理的是序列问题,与之形成对比的是cnn,cnn不能 ...

  2. pytorch之 RNN 参数解释

    上次通过pytorch实现了RNN模型,简易的完成了使用RNN完成mnist的手写数字识别,但是里面的参数有点不了解,所以对问题进行总结归纳来解决. 总述:第一次看到这个函数时,脑袋有点懵,总结了下总 ...

  3. Tensorflow实战第十一课(RNN Regression 回归例子 )

    本节我们会使用RNN来进行回归训练(Regression),会继续使用自己创建的sin曲线预测一条cos曲线. 首先我们需要先确定RNN的各种参数: import tensorflow as tf i ...

  4. Task3.PyTorch实现Logistic regression

    1.PyTorch基础实现代码 import torch from torch.autograd import Variable torch.manual_seed(2) x_data = Varia ...

  5. pytorch之 RNN classifier

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

  6. pytorch中如何处理RNN输入变长序列padding

    一.为什么RNN需要处理变长输入 假设我们有情感分析的例子,对每句话进行一个感情级别的分类,主体流程大概是下图所示: 思路比较简单,但是当我们进行batch个训练数据一起计算的时候,我们会遇到多个训练 ...

  7. Pytorch基础——使用 RNN 生成简单序列

    一.介绍 内容 使用 RNN 进行序列预测 今天我们就从一个基本的使用 RNN 生成简单序列的例子中,来窥探神经网络生成符号序列的秘密. 我们首先让神经网络模型学习形如 0^n 1^n 形式的上下文无 ...

  8. 【深度学习】Pytorch 学习笔记

    目录 Pytorch Leture 05: Linear Rregression in the Pytorch Way Logistic Regression 逻辑回归 - 二分类 Lecture07 ...

  9. 吐血整理:PyTorch项目代码与资源列表 | 资源下载

    http://www.sohu.com/a/164171974_741733   本文收集了大量基于 PyTorch 实现的代码链接,其中有适用于深度学习新手的“入门指导系列”,也有适用于老司机的论文 ...

随机推荐

  1. 【DPDK】【ring】从DPDK的ring来看无锁队列的实现

    [前言] 队列是众多数据结构中最常见的一种之一.曾经有人和我说过这么一句话,叫做“程序等于数据结构+算法”.因此在设计模块.写代码时,队列常常作为一个很常见的结构出现在模块设计中.DPDK不仅是一个加 ...

  2. jQuery, 文本框获得焦点后, placeholder提示文字消失

    文本框获得焦点后, 提示文字消失, 基于jQuery, 兼容性: html5 //所有文本框获得焦点后, 提示文字消失 $('body').on('focus', 'input[placeholder ...

  3. Java多线程的创建(二)

    前言: 虽然java的API中说创建多线程的方式只有两种(There are two ways to create a new thread of execution),分别是继承Thread类创建和 ...

  4. ASP.NET 开源导入导出库Magicodes.IE 导出Pdf教程

    基础教程之导出Pdf收据 说明 本教程主要说明如何使用Magicodes.IE.Pdf完成Pdf收据导出 要点 导出PDF数据 自定义PDF模板 导出单据 如何批量导出单据 导出特性 PdfExpor ...

  5. vue引用外部JS的两种种方案

    前言 肯定会遇到没有npm化的库 自己写的js 方法 在Vue中该怎么引用呢 第一种 如果库是es6写的 就可以用import 引入 比如我自己写的http 封装接口的方法 就可以这样子导入哦 第二种 ...

  6. mongdb角色的授权

    开启cmd窗口切换到cd D:\programs\mongoDB\bin D:\programs\mongoDB\bin>mongo MongoDB shell version v3.4.6 c ...

  7. pandas时间序列常用操作

    目录 一.时间序列是什么 二.时间序列的选取 三.时间序列的生成 四.时间序列的偏移量 五.时间前移或后移 五.时区处理 六.时期及算术运算 七.频率转换 一.时间序列是什么 时间序列在多个时间点观察 ...

  8. javaWeb传收参数方式总结

    有时候,我真会被传参搞得头晕,这样传要怎么接收,那样传又要怎么接收? get可以json吗?什么是json方式提交?等等问题,已困扰我许久 所以,在此想做个总结,整理一下思绪,不再为传收参烦恼!如有错 ...

  9. Docker 安装 Elasticsearch+kibana

    1 下载镜像 docker pull elasticsearch:7.4.1 docker pull kibana:7.4.1 拉取的镜像如下: 2 创建network 创建一个网络,名字任意取,使得 ...

  10. Redhat下如何查看nvidia显卡的工作状况

    安装完毕nvidia显卡驱动后,可以使用命令来查看显卡的工作状况,命令如下: nvidia-smi 输入上述命令后,显示界面如下 安装nvidia显卡驱动的步骤,请参照驱动安装cuda和cudnn.