RNN基礎:
『cs231n』作業3問題1選講_通過代碼理解RNN&圖像標注訓練
TensorFlow RNN:
對於torch中的RNN相關類,有原始和原始Cell之分,其中RNN和RNNCell層的區別在於前者一次能夠處理整個序列,而后者一次只處理序列中一個時間點的數據,前者封裝更完備更易於使用,后者更具靈活性。實際上RNN層的一種后端實現方式就是調用RNNCell來實現的。
一、nn.RNN
import torch as t from torch import nn from torch.autograd import Variable as V layer = 1 t.manual_seed(1000) # 3句話,每句話2個字,每個字4維矢量 # batch為3,step為2,每個元素4維 input = V(t.randn(2,3,4)) # 1層,輸出(隱藏)神經元3維,輸入神經元4維 # 1層,3隱藏神經元,每個元素4維 lstm = nn.LSTM(4,3,layer) # 初始狀態:1層,batch為3,隱藏神經元3 h0 = V(t.randn(layer,3,3)) c0 = V(t.randn(layer,3,3)) out, hn = lstm(input,(h0,c0)) print(out, hn)
二、nn.RNNCell
import torch as t
from torch import nn
from torch.autograd import Variable as V
t.manual_seed(1000)
# batch為3,step為2,每個元素4維
input = V(t.randn(2,3,4))
# Cell只能是1層,3隱藏神經元,每個元素4維
lstm = nn.LSTMCell(4,3)
# 初始狀態:1層,batch為3,隱藏神經元3
hx = V(t.randn(3,3))
cx = V(t.randn(3,3))
out = []
# 每個step提取各個batch的四個維度
for i_ in input:
print(i_.shape)
hx, cx = lstm(i_,(hx,cx))
out.append(hx)
t.stack(out)
三、nn.Embedding
embedding將標量表示的字符(所以是LongTensor)轉換成矢量,這里給出一個模擬:將標量詞embedding后送入rnn轉換一下維度。
import torch as t
from torch import nn
from torch.autograd import Variable as V
# 5個詞,每個詞使用4維向量表示
embedding = nn.Embedding(5, 4)
# 使用預訓練好的詞向量初始化
embedding.weight.data = t.arange(0, 20).view(5, 4) # 大小對應nn.Embedding(5, 4)
# embedding將標量表示的字符(所以是LongTensor)轉換成矢量
# 實際輸入詞原始向量需要是LongTensor格式
input = V(t.arange(3, 0, -1)).long()
# 1個batch,3個step,4維矢量
input = embedding(input).unsqueeze(1)
print("embedding后:",input.size())
# 1層,3隱藏神經元(輸出元素4維度),每個元素4維
layer = 1
lstm = nn.LSTM(4, 3, layer)
# 初始狀態:1層,batch為3,隱藏神經元3
h0 = V(t.randn(layer, 3, 3))
c0 = V(t.randn(layer, 3, 3))
out, hn = lstm(input, (h0, c0))
print("LSTM輸出:",out.size())
