![](/img/trans.png)
[英]Create an LSTM layer with Attention in Keras for multi-label text classification neural network
[英]Dimensionality Error when using Bidirectional LSTM with an embedding layer, on multi-label classification
我試圖使用雙向LSTM將文本數據(句子)分類為某些類。 我以其中的3個為例。 我遵循了multilabel-classification-post,即“使用Sigmoid激活輸出層”,“使用binary_crossentropy進行損失函數”。 我使用了一個嵌入層(大小為300的單詞向量)。 我的句子被填充和截斷,因此每個句子有100個標記。 這是我的模型的代碼:
model = Sequential()
embedding_layer = Embedding(6695,
300,
weights=[embedding_matrix],
input_length=100,
trainable=True)
model.add(embedding_layer)
model.add(Bidirectional(LSTM(32,
return_sequences=False)))
model.add(Dense(3,
activation='sigmoid'))
model.compile(loss='binary_crossentropy',
optimizer='rmsprop',
metrics=['acc'])
print("model fitting - Bidirectional LSTM")
model.summary()
x= model.fit(X_train, y_train,
batch_size=256,
epochs=6,
validation_data=(X_val, y_val),
shuffle = True,
verbose = 1
)
這是模型摘要,這是預期的結果: 在此處輸入圖像描述
但是,我收到此錯誤:
Traceback (most recent call last):
File "/Users/master/Documents/Deep Learning/Learning Keras/reveiw_classification.py", line 159, in <module>
verbose = 1
File "/Users/master/.pyenv/versions/ENV4/lib/python3.6/site-packages/keras/engine/training.py", line 955, in fit
batch_size=batch_size)
File "/Users/master/.pyenv/versions/ENV4/lib/python3.6/site-packages/keras/engine/training.py", line 792, in _standardize_user_data
exception_prefix='target')
File "/Users/master/.pyenv/versions/ENV4/lib/python3.6/site-packages/keras/engine/training_utils.py", line 136, in standardize_input_data
str(data_shape))
ValueError: Error when checking target: expected dense_1 to have shape (3,) but got array with shape (100,)
我不需要LSTM返回隱藏狀態輸出的序列,我只需要最后一個輸出。 我以為我在LSTM中使用了return_sequences = False,因此輸出應具有維度1,然后具有32個單位的雙向LSTM將具有輸出維度(None,64),如模型摘要中所示。 但是為什么它說期望density_1具有形狀(3,)但卻得到形狀(100,)的數組呢? 有人可以幫我嗎?
看起來您的目標y_train
實際上是句子,而不是例如標簽[1, 0, 1]
y_train
的向量。 錯誤不是關於模型,而是您傳遞的數據。
y_train
應該是一個2D形狀的數組(num_samples, 3)
因此對於每個樣本(句子),您都有3個標簽的向量目標 。 X_train
類似於(num_samples, 100)
,它是長度為100的句子作為您的輸入。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.