RNN回归
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()
运行结果为:
用正弦曲线去拟合余弦曲线
RNN回归的更多相关文章
- 循环神经网络LSTM RNN回归:sin曲线预测
摘要:本篇文章将分享循环神经网络LSTM RNN如何实现回归预测. 本文分享自华为云社区<[Python人工智能] 十四.循环神经网络LSTM RNN回归案例之sin曲线预测 丨[百变AI秀]& ...
- TF之RNN:matplotlib动态演示之基于顺序的RNN回归案例实现高效学习逐步逼近余弦曲线—Jason niu
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt BATCH_START = 0 TIME_STEP ...
- TF之RNN:TensorBoard可视化之基于顺序的RNN回归案例实现蓝色正弦虚线预测红色余弦实线—Jason niu
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt BATCH_START = 0 TIME_STEP ...
- 对比学习用 Keras 搭建 CNN RNN 等常用神经网络
Keras 是一个兼容 Theano 和 Tensorflow 的神经网络高级包, 用他来组件一个神经网络更加快速, 几条语句就搞定了. 而且广泛的兼容性能使 Keras 在 Windows 和 Ma ...
- Tensorflow实战第十一课(RNN Regression 回归例子 )
本节我们会使用RNN来进行回归训练(Regression),会继续使用自己创建的sin曲线预测一条cos曲线. 首先我们需要先确定RNN的各种参数: import tensorflow as tf i ...
- TensorFlow从入门到理解(五):你的第一个循环神经网络RNN(回归例子)
运行代码: import tensorflow as tf import numpy as np import matplotlib.pyplot as plt BATCH_START = 0 TIM ...
- lecture7-序列模型及递归神经网络RNN
Hinton 第七课 .这里先说下RNN有recurrent neural network 和 recursive neural network两种,是不一样的,前者指的是一种人工神经网络,后者指的是 ...
- lecture7-序列模型及递归神经网络RNN(转载)
Hinton 第七课 .这里先说下RNN有recurrent neural network 和 recursive neural network两种,是不一样的,前者指的是一种人工神经网络,后者指的是 ...
- 递归神经网络(RNN,Recurrent Neural Networks)和反向传播的指南 A guide to recurrent neural networks and backpropagation(转载)
摘要 这篇文章提供了一个关于递归神经网络中某些概念的指南.与前馈网络不同,RNN可能非常敏感,并且适合于过去的输入(be adapted to past inputs).反向传播学习(backprop ...
随机推荐
- 解决 golang unrecognized import path "golang.org/x" 之类错误的一种尝试
如果使用的开发IDE是goland,那么 打开 FILE -> setting -> Go Modules 选项 ,在proxy 选项上填写 "https://goproxy.i ...
- Python selenium —— 一定要会用selenium的等待,三种等待方式解读
发现太多人不会用等待了,博主今天实在是忍不住要给大家讲讲等待的必要性. 很多人在群里问,这个下拉框定位不到.那个弹出框定位不到…各种定位不到,其实大多数情况下就是两种问题:1 有frame,2 没有加 ...
- 安装maven,并配置eclipse
平台 ubuntu 18.04 + Java 8 下载并安装Maven 下载页面:http://maven.apache.org/download.cgi 我这里使用写博客是最新的版本3.6.1,选择 ...
- Vjudge Code
Stylus @-moz-document url-prefix("https://cn.vjudge.net/"), url-prefix("https://vjudg ...
- bs4模块
1.导入模块 from bs4 import BeautifulSoup 2.创建对象 Beautiful Soup支持Python标准库中的HTML解析器,还支持一些第三方的解析器,如果我们不安装它 ...
- 「译」图解 ArrayBuffers 和 SharedArrayBuffers
作者:Lin Clark 译者:Cody Chan 原帖链接:A cartoon intro to ArrayBuffers and SharedArrayBuffers 这是图解 SharedArr ...
- [leetcode] 5.Longest Palindromic Substring-2
想了很多方法 搞轴对称,算对称轴,偶数都高出了一堆0.5在那加加减减,最后发现在移轴之前可能就返回了. class Solution: def longestPalindrome(self, s: s ...
- Django中ORM介绍
Object Relational Mapping(ORM) ORM介绍 ORM概念 对象关系映射(Object Relational Mapping,简称ORM)模式是一种为了解决面向对象与关系数据 ...
- Nginx-反向代理实现
Nginx 反向代理操作案例 Nginx反向代理的组件模块 upstream模块介绍->点我< http_proxy_module模块介绍->点我< 环境准备 1)四台服务器都 ...
- nuxt npm run dev 报错Solution to the "Error: listen EADDRINUSE 127.0.0.1:8080"
Solution to the "Error: listen EADDRINUSE 127.0.0.1:8080" Hello, Just sharing a solution t ...