用例子與代碼詳解LSTM層的輸入輸出,以Keras爲例

先附上代碼:

from keras import Sequential
from keras.layers import LSTM

model = Sequential()
model.add(LSTM(64))  #64表示input_dim,即每個時間步輸入的向量的維度

#輸入爲2個句子,即2個樣本,Batchsize=2,3個時間步,每個時間步的輸入是64維,如X0,
# 注意:每個時間步不一定只輸入一個單詞,如一個單詞的維度爲32,那麼這個時間步就是輸入了兩個單詞,即Word0和word1共同構成了X0
input_array = np.random.randint(10, size=(2,3,64))

model.compile('rmsprop', 'mse')
output_array = model.predict(input_array)
print(output_array.shape)
assert output_array.shape == (2,64)

然後附上圖解:

注:如果是Bidirectional(LSTM())則輸出維度會變成(batch_size,128)

參考資料(如果對於上述例子感覺迷惑,建議閱讀參考資料後再回顧一遍):

https://keras.io/zh/layers/recurrent/#lstm

https://www.jianshu.com/p/c66369cfa0c7

如有其他疑問,歡迎留言交流。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章