![](/img/trans.png)
[英]logits and labels must have the same first dimension, got logits shape [3662,5] and labels shape [18310]
[英]How to solve “logits and labels must have the same first dimension” error
我正在為基於單詞的 NLP 嘗試不同的神經網絡架構。
到目前為止,我已經在本教程的指導下使用了 GRU 的雙向、嵌入式和模型: https://towardsdatascience.com/language-translation-with-rnns-d84d43b40571 ,一切都很好。 但是,當我嘗試使用 LSTM 時,我收到一條錯誤消息:
logits 和 labels 必須具有相同的第一維,得到 logits 形狀 [32,186] 和標簽形狀 [4704]
我該如何解決這個問題?
我的源和目標數據集由 7200 個例句組成。 它們是 integer 標記和嵌入的。 源數據集被后填充以匹配目標數據集的長度。
這是我的 model 和相關代碼:
lstm_model = Sequential()
lstm_model.add(Embedding(src_vocab_size, 128, input_length=X.shape[1], input_shape=X.shape[1:]))
lstm_model.add(LSTM(128, return_sequences=False, dropout=0.1, recurrent_dropout=0.1))
lstm_model.add(Dense(128, activation='relu'))
lstm_model.add(Dropout(0.5))
lstm_model.add((Dense(target_vocab_size, activation='softmax')))
lstm_model.compile(optimizer=Adam(0.002), loss='sparse_categorical_crossentropy', metrics=['accuracy'])
history = lstm_model.fit(X, Y, batch_size = 32, callbacks=CALLBACK, epochs = 100, validation_split = 0.25) #At this line the error is raised!
隨着形狀:
我已經在這里查看過類似的問題並嘗試添加 Reshape 圖層
simple_lstm_model.add(Reshape((-1,)))
但這只會導致以下錯誤:
“TypeError:__int__ 返回非 int(類型 NoneType)”
這真的很奇怪,因為我對所有模型都以相同的方式預處理數據集,並且除了上述之外它工作得很好。
在調用 LSTM 構造函數時,您應該有return_sequences=True
和return_state=False
。
在您的代碼段中,LSTM 僅返回其最后一個 state,而不是每個輸入嵌入的狀態序列。 理論上,您可以從錯誤消息中發現它:
logits 和 labels 必須具有相同的第一維,得到 logits 形狀 [32,186] 和標簽形狀 [4704]
logits 應該是三維的:批量大小 × 序列長度 × 類數。 序列的長度是 147,實際上是 32 × 147 = 4704(標簽數)。 這可能告訴你序列的長度消失了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.