您好,登錄后才能下訂單哦!
如何進行LSTM總結(jié)及sin與cos擬合應(yīng)用,相信很多沒有經(jīng)驗的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。
一、LSTM總結(jié)
RNN在實際應(yīng)用中,無法處理無關(guān)的信息,很難處理長距離的依賴。LSTM思路,在原始RNN的隱藏層只有一個狀態(tài)h,它對短期的輸入非常敏感,那么,我們再增加一個狀態(tài)c, 它來保存長期的狀態(tài)。其結(jié)構(gòu)如下:
與RNN比較,
定義LSTM類如下:
class RNN(nn.Module): def __init__(self): super(RNN, self).__init__() self.rnn = nn.LSTM( input_size=INPUT_SIZE, hidden_size=32, num_layers=1, batch_first=True ) self.out = nn.Linear(32, 1) def forward(self, x, h_state, c_state): r_out, (h_state, c_state) = self.rnn(x, (h_state, c_state)) out = self.out(r_out).squeeze() return out, h_state, c_state
改進GRU版本: (Gated Recurrent Unit)
二、sin與cos擬合應(yīng)用
import torch from torch import nn import numpy as np import matplotlib.pyplot as plt TIME_STEP = 10 INPUT_SIZE = 1 learning_rate = 0.001 class RNN(nn.Module): def __init__(self): super(RNN, self).__init__() self.rnn = nn.LSTM( input_size=INPUT_SIZE, hidden_size=32, num_layers=1, batch_first=True ) self.out = nn.Linear(32, 1) def forward(self, x, h_state, c_state): r_out, (h_state, c_state) = self.rnn(x, (h_state, c_state)) out = self.out(r_out).squeeze() return out, h_state, c_state rnn = RNN() criterion = nn.MSELoss() optimizer = torch.optim.Adam(rnn.parameters(), lr=learning_rate) h_state = torch.randn(1, 1, 32) c_state = torch.randn(1, 1, 32) plt.figure(1, figsize=(12, 5)) plt.ion() for step in range(100): start, end = step * np.pi, (step + 1) * np.pi steps = np.linspace(start, end, TIME_STEP, dtype=np.float32, endpoint=False) x_np = np.sin(steps) # x_np.shape: 10 y_np = np.cos(steps) # y_np.shape: 10 x = torch.from_numpy(x_np[np.newaxis, :, np.newaxis]) y = torch.from_numpy(y_np) prediction, h_state, c_state = rnn(x, h_state, c_state) h_state = h_state.data c_state = c_state.data loss = criterion(prediction, y) optimizer.zero_grad() loss.backward() optimizer.step() plt.plot(steps, y_np.flatten(), 'r-') plt.plot(steps, prediction.data.numpy().flatten(), 'b-') plt.draw() plt.pause(.05) plt.ioff() plt.show()
看完上述內(nèi)容,你們掌握如何進行LSTM總結(jié)及sin與cos擬合應(yīng)用的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(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)容。