LSTM 參數
input_size:輸入維數 hidden_size:輸出維數 num_layers:LSTM層數,默認是1 bias:True 或者 False,決定是否使用bias, False則b_h=0. 默認為True batch_first:True 或者 False,因為nn.lstm()接受的數據輸入是(序列長度,batch,輸入維數),這和我們cnn輸入的方式不太一致,所以使用batch_first,我們可以將輸入變成(batch,序列長度,輸入維數) dropout:表示除了最后一層之外都引入一個dropout bidirectional:表示雙向LSTM,也就是序列從左往右算一次,從右往左又算一次,這樣就可以兩倍的輸出
輸入
– input (seq_len, batch_size, input_size)
– h_0 (num_layers * num_directions, batch_size, hidden_size)
– c_0 (num_layers * num_directions, batch_size, hidden_size)
輸出
– output (seq_len, batch_size, num_directions * hidden_size)
– h_n (num_layers * num_directions, batch_size, hidden_size)
– c_n (num_layers * num_directions, batch_size, hidden_size)
【注】如果batch_first = True,則output (batch_size, seq_len, num_directions * hidden_size),而h_n和c_n的維度不會改變
根據上面這張圖可以分析LSTM返回的三個值 output、h_n 和 c_n 的維度:
— h_n:只返回最后一個時間步的隱藏層輸出,第$i$層會輸出$h_{n}^{(i)}$,所以第一維為num_layers * num_directions,第二維的維度為batch_size,第三位就是$h$本身的維度大小,即hidden_size。
— c_n:$c_n$的維度同$h_n$。
—output:返回每個時間步的隱藏層輸出,所以第一維為seq_len,第二維的維度為batch_size,第三維就是hidden_size,雙向的話拼接起來就是2*hidden_size,所以就是num_directions * hidden_size。
由於 h_n 和 output 都包含了最后一個時間步的隱藏層輸出,所以$output[-1,:,:] = h_n[-1,:,:]$。
【注】如果batch_first=True,則 $output[:,-1,:] = h_n[-1,:,:]$
import torch import torch.nn as nn rnn = nn.LSTM(input_size=4, hidden_size=6, num_layers=1) input = torch.randn(3, 2, 4) # batch=2, seq_len=3, input_size=4 output, (hn, cn) = rnn(input) # 如果h0和c0未給出,則默認為0 print(output.shape, hn.shape, cn.shape) print(output[-1, :, :]) print(hn[-1, :, :])
參考: