pytorch循环神经网络实现回归预测代码

更新时间:2023-06-17 04:09:24 阅读: 评论:0

pytorch循环神经⽹络实现回归预测代码pytorch循环神经⽹络实现回归预测
学习视频:莫烦python
# RNN for classification
暮鼓晨钟import torch
import numpy as np
as nn
import torch.utils.data as Data
import matplotlib.pyplot as plt
import torchvision
#hyper parameters
TIME_STEP=10    #run time step
INPUT_SIZE=1
LR=0.02  #learning rate
# t=np.linspace(0,np.pi*2,100,dtype=float)  #from zero to pi*2, and one hundred point there
# x=np.sin(t)
# s(t)
# plt.plot(t,x,'r-',label='input (sin)')
# plt.plot(t,y,'b-',label='target (cos)')
# plt.legend(loc='best')
# plt.show()
class RNN_Net(nn.Module):
def__init__(lf):
super(RNN_Net,lf).__init__()
<=nn.RNN(
input_size=INPUT_SIZE,
hidden_size=32,
num_layers=1,
batch_first=True,
)
lf.out=nn.Linear(32,1)
def forward(lf,x,h_state):
项目总结报告
祖国的发展r_out,h_(x,h_state)
outs=[]
别说抱歉for time_step in range(r_out.size(1)):
outs.append(lf.out(r_out[:,time_step,:]))
return torch.stack(outs,dim=1),h_state  # the type of return data is torch, and the return data also include h_state
rnn=RNN_Net()
# print(rnn)
optimizer=torch.optim.Adam(rnn.parameters(),lr=LR)
loss_func=nn.MSELoss()
plt.ion()
h_state=None
for step in range (60):
start,end=step*np.pi,(step+1)*np.pi
#using sin predicts cos
steps=np.linspace(start,end,TIME_STEP,dtype=np.float32)
x_np=np.sin(steps)牛仔裤配什么上衣好看
y_s(steps)
x=torch.from_numpy(x_waxis,:,np.newaxis]) # np.newaxis means increa a dim
y=torch.from_numpy(y_waxis,:,np.newaxis])
predition,h_state=rnn(x,h_state) #the first h_state is None
h_state=h_state.data  #
loss=loss_func(predition,y)
<_grad()
loss.backward()
幻灯片大小
optimizer.step()
白雪公主故事plt.plot(steps,y_np,'r-')
plt.plot(steps,predition.detach().numpy().flatten(),'b-')  #flatten() 展平维度
plt.draw()
plt.pau(0.05)
莲藕炖鸡plt.ioff()
plt.show()

本文发布于:2023-06-17 04:09:24,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/fan/89/1041961.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:祖国   总结报告   实现   神经
相关文章
留言与评论(共有 0 条评论)
   
验证码:
推荐文章
排行榜
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图