溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

pytorch-RNN進行回歸曲線預測方式

發(fā)布時間:2020-09-11 03:29:15 來源:腳本之家 閱讀:428 作者:馬飛飛 欄目:開發(fā)技術(shù)

任務

通過輸入的sin曲線與預測出對應的cos曲線

#初始加載包 和定義參數(shù)
import torch
from torch import nn
import numpy as np
import matplotlib.pyplot as plt
 
torch.manual_seed(1) #為了可復現(xiàn)
 
#超參數(shù)設定
TIME_SETP=10
INPUT_SIZE=1
LR=0.02
DOWNLoad_MNIST=True

定義RNN網(wǎng)絡結(jié)構(gòu)

from torch.autograd import Variable
class RNN(nn.Module):
  def __init__(self):
    #在這個函數(shù)中,兩步走,先init,再逐步定義層結(jié)構(gòu)
    super(RNN,self).__init__()
    
    self.rnn=nn.RNN(  #定義32隱層的rnn結(jié)構(gòu)
     input_size=1,  
     hidden_size=32, #隱層有32個記憶體
     num_layers=1,   #隱層層數(shù)是1
     batch_first=True 
    )
    
    self.out=nn.Linear(32,1) #32個記憶體對應一個輸出
  
  def forward(self,x,h_state):
    #前向過程,獲取 rnn網(wǎng)絡輸出r_put(注意這里r_out并不是最后輸出,最后要經(jīng)過全連接層) 和 記憶體情況h_state
    r_out,h_state=self.rnn(x,h_state)    
    outs=[]#獲取所有時間點下得到的預測值
    for time_step in range(r_out.size(1)): #將記憶rnn層的輸出傳到全連接層來得到最終輸出。 這樣每個輸入對應一個輸出,所以會有長度為10的輸出
      outs.append(self.out(r_out[:,time_step,:]))
    return torch.stack(outs,dim=1),h_state #將10個數(shù) 通過stack方式壓縮在一起
 
rnn=RNN()
print('RNN的網(wǎng)絡體系結(jié)構(gòu)為:',rnn)

pytorch-RNN進行回歸曲線預測方式

創(chuàng)建數(shù)據(jù)集及網(wǎng)絡訓練

以sin曲線為特征,以cos曲線為標簽進行網(wǎng)絡的訓練

#定義優(yōu)化器和 損失函數(shù)
optimizer=torch.optim.Adam(rnn.parameters(),lr=LR)
loss_fun=nn.MSELoss()
h_state=None #記錄的隱藏層狀態(tài),記住這就是記憶體,初始時候為空,之后每次后面的都會使用到前面的記憶,自動生成全0的
       #這樣加入記憶信息后,每次都會在之前的記憶矩陣基礎上再進行新的訓練,初始是全0的形式。
#啟動訓練,這里假定訓練的批次為100次
 
 
plt.ion() #可以設定持續(xù)不斷的繪圖,但是在這里看還是間斷的,這是jupyter的問題
for step in range(100):
  #我們以一個π為一個時間步  定義數(shù)據(jù),
  start,end=step*np.pi,(step+1)*np.pi
  
  steps=np.linspace(start,end,10,dtype=np.float32) #注意這里的10并不是間隔為10,而是將數(shù)按范圍分成10等分了
  
  x_np=np.sin(steps)
  y_np=np.cos(steps)
  #將numpy類型轉(zhuǎn)成torch類型  *****當需要 求梯度時,一個 op 的兩個輸入都必須是要 Variable,輸入的一定要variable包下
  x=Variable(torch.from_numpy(x_np[np.newaxis,:,np.newaxis]))#增加兩個維度,是三維的數(shù)據(jù)。
  y=Variable(torch.from_numpy(y_np[np.newaxis,:,np.newaxis]))
  
  #將每個時間步上的10個值 輸入到rnn獲得結(jié)果   這里rnn會自動執(zhí)行forward前向過程. 這里輸入時10個,輸出也是10個,傳遞的是一個長度為32的記憶體
  predition,h_state=rnn(x,h_state)
  
  #更新新的中間狀態(tài)
  h_state=Variable(h_state.data)  #擦,這點一定要從新包裝
  loss=loss_fun(predition,y)
  #print('loss:',loss)
  optimizer.zero_grad()
  loss.backward()
  optimizer.step()
  
  
  # plotting  畫圖,這里先平展了 flatten,這樣就是得到一個數(shù)組,更加直接
  
  plt.plot(steps, y_np.flatten(), 'r-')
  plt.plot(steps, predition.data.numpy().flatten(), 'b-')
  #plt.draw(); 
  plt.pause(0.05)
 
plt.ioff() #關(guān)閉交互模式
plt.show()

pytorch-RNN進行回歸曲線預測方式

以上這篇pytorch-RNN進行回歸曲線預測方式就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持億速云。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI