我正在为基于单词的 NLP 尝试不同的神经网络架构。
到目前为止,我已经在本教程的指导下使用了双向、嵌入式和带有 GRU 的模型:https://towardsdatascience.com/language-translation-with-rnns-d84d43b40571一切都很顺利。 然而,当我尝试使用 LSTM 时,我收到一条错误消息:
logits and labels must have the same first dimension, got logits shape [32,186] and labels shape [4704]
我该如何解决这个问题?
我的源数据集和目标数据集包含 7200 个例句。它们是整数标记化和嵌入的。源数据集经过后填充以匹配目标数据集的长度。
这是我的模型和相关代码:
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!
形状:
- X.shape = (7200, 147)
- Y.shape = (7200, 147, 1)
- src_vocab_size = 188
- target_vocab_size = 186
我已经在这里看过类似的问题并尝试添加 reshape 图层
simple_lstm_model.add(Reshape((-1,)))
但这只会导致以下错误:
"TypeError: __int__ returned non-int (type NoneType)"
这真的很奇怪,因为我对所有模型都以相同的方式预处理数据集,并且除了上述之外它工作得很好。
最佳答案
在调用 LSTM 构造函数时,您应该使用 return_sequences=True
和 return_state=False
。
在您的代码片段中,LSTM 仅返回其最后状态,而不是每个输入嵌入的状态序列。理论上,您可以从错误消息中发现它:
logits and labels must have the same first dimension, got logits shape [32,186] and labels shape [4704]
logits 应该是三维的:批量大小 × 序列长度 × 类数。序列的长度是 147,实际上是 32 × 147 = 4704(标签的数量)。这可能告诉您序列消失的长度。
关于python-3.x - 如何解决 "logits and labels must have the same first dimension"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58543163/