LSTM網絡中各層解讀


https://towardsdatascience.com/reading-between-the-layers-lstm-network-7956ad192e58

 

構建深度神經網絡最關鍵的部分之一是——當數據流經不同的層時,要對其有一個清晰的視圖,這些層經歷了維度的變化、形狀的改變、扁平化和重新塑造……

 

 

 

 LSTM Network Architecture for Sentiment Analysis

每層解讀:

0) 把單詞變為tokens

1)embedding 把每個token變成特定大小的embedding

2)LSTM 由隱藏狀態維度和層數決定

3)全連接層

4)激活函數

5)輸出

 

數據:使用IMDB電影評論的數據集;

對數據進行了預處理,使得batch_size=50, 序列長度為200

1 dataiter = iter(train_loader)
2 x, y = dataiter.next()
3 x = x.type(torch.LongTensor)
4 print ('X is', x)
5 print ('Shape of X and y are :', x.shape, y.shape)

 

 

 

從X的形狀可以看出,X是一個張量,為50行(=batch size)和200列(=sequence length)。

這個X將作為嵌入層的輸入

  • Embedding layer :


使用torch.nn.Embedding模塊作嵌入。它需要兩個參數:詞匯表大小和嵌入的維數

1 from torch import nn
2 vocab_size = len(words)
3 embedding_dim = 30
4 embeds = nn.Embedding(vocab_size, embedding_dim)
5 print ('Embedding layer is ', embeds)
6 print ('Embedding layer weights ', embeds.weight.shape)

 

 

 

1 embeds_out = embeds(x)
2 print ('Embedding layer output shape', embeds_out.shape)
3 print ('Embedding layer output ', embeds_out)

 

 

 

 從嵌入層的輸出可以看出,它作為嵌入權值的結果創建了一個三維張量。現在它有50行,200列和30個嵌入維,也就是說,在我們的審查中,我們為每個標記化的單詞添加了嵌入維。該數據現在將進入LSTM層

  • LSTM Layer :

在定義LSTM層時,我們保持Batch First = True和隱藏單元的數量= 512。

1 # initializing the hidden state to 0
2 hidden=None
3 lstm = nn.LSTM(input_size=embedding_dim, hidden_size=512, num_layers=1, batch_first=True)
4 lstm_out, h = lstm(embeds_out, hidden)
5 print ('LSTM layer output shape', lstm_out.shape)
6 print ('LSTM layer output ', lstm_out)

 

 

 通過查看LSTM層的輸出,我們可以看到張量現在有50行,200列和512個LSTM節點。接下來,該數據被提取到全連接層

  • Fully Connected Layer :


對於全連通層,輸入特征數= LSTM中隱藏單元數。輸出大小= 1,因為我們只有二進制結果(1/0;正和負)

1 fc = nn.Linear(in_features=512, out_features=1)
2 fc_out = fc(lstm_out.contiguous().view(-1, 512))
3 print ('FC layer output shape', fc_out.shape)
4 print ('FC layer output ', fc_out)

注意,在將lstm輸出放入fc層之前,必須將其壓平。

1 fc = nn.Linear(in_features=512, out_features=1)
2 fc_out = fc(lstm_out.contiguous().view(-1, 512))
3 print ('FC layer output shape', fc_out.shape)
4 print ('FC layer output ', fc_out)

 

 

  • Sigmoid Activation Layer :


這只是為了將所有的輸出值從完全連接的層轉換為0到1之間的值

1 sigm = nn.Sigmoid()
2 sigm_out = sigm(fc_out)
3 print ('Sigmoid layer output shape', sigm_out.shape)
4 print ('Sigmoid layer output ', sigm_out)

 

 

  • Final Output :

這包括兩個步驟:首先,重塑輸出,使rows = batch大小

1 batch_size = x.shape[0]
2 out = sigm_out.view(batch_size, -1)
3 print ('Output layer output shape', out.shape)
4 print ('Output layer output ', out)

 

 第二,正如我們在網絡體系結構中看到的那樣——我們只希望在最后一個序列之后進行輸出(在最后一個時間步之后)

 1 print ('Final sentiment prediction, ', out[:,-1]) 

 

 這些輸出來自未經訓練的網絡,因此這些值可能還不表示任何內容。這只是為了說明,我們將使用這些知識來正確定義模型。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM