关于python:LSTM:lstm_1层的输入0与层不兼容:预期ndim=3,发现ndim=2(reshaping input)
LSTM: Input 0 of layer lstm_1 is incompatible with the layer: expected ndim=3, found ndim=2 (reshaping input)
我想根据 Robert Frost 的诗歌创作诗歌。
我已经预处理了我的数据集:
|
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
max_sentence_len = max(len(l) for l in corpus_int)
input_seq = np.array(tf.keras.preprocessing.sequence.pad_sequences(corpus_int,padding = 'pre',truncating = 'pre',maxlen = max_sentence_len)) predictors array([[ 0, 0, 0, ..., 10, 5, 544], label array([[0, 0, 0, ..., 0, 0, 0], |
之后,我使用编码器 - 解码器架构构建了我的模型:
|
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
class seq2seq(tf.keras.Model):
def __init__(self,max_sequence_len,total_words): super(seq2seq,self).__init__() self.max_sequence_len = max_sequence_len self.total_words = total_words self.input_len = self.max_sequence_len - 1 #Encoder #decoder #Dense layer and output: def call(self,inputs): #Decoding: return output_dense model = seq2seq(max_sequence_len = max_sentence_len,total_words = total_words) |
但最后我得到以下错误:
|
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
ValueError Traceback (most recent call last)
<ipython-input-4-1c349573302d> in <module>() 37 model = seq2seq(max_sequence_len = max_sentence_len,total_words = total_words) 38 model.compile(optimizer = tf.keras.optimizers.RMSprop(lr=0.0001),loss='categorical_crossentropy', metrics=['accuracy']) ---> 39 model.fit(predictors,label,epochs=5, batch_size=128) 8 frames ValueError: in converted code: <ipython-input-4-1c349573302d>:27 call * ValueError: Input 0 of layer lstm_1 is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: [None, 300] |
我明白,问题出在输入形状中(正如在帖子中回答的那样,预期 ndim=3,发现 ndim=2)。
但我不知道我应该如何为 tensorflow 2.0 重塑我的数据。
你能帮我解决这个问题吗?
相关讨论
- 如果您共享完整的错误跟踪,这会有所帮助
- @OverLordGoldDragon 已编辑。请看一下。
- 错误很好,但是您确定您提供的代码是您使用的代码吗?我很惊讶它完全可以编译——这些层甚至没有连接。对于您的问题,使用基于类的模型定义似乎是一种过度杀伤力——无论如何,问题是不可重现的。在此处查看参考实现
- @OverLordGoldDragon 是的,我确定
- 我非常怀疑它 - 但试一试,分享你的完整代码,也许它会改变一些东西。
- @OverLordGoldDragon 已更正,现在图层已连接。
问题的根源在于
的使用
-
True --> 返回每个输入时间步的输出。 LSTM 维度为20 ,输入形状为(32, 100, 40) ,输出形状为(32, 100, 20) == (batch_size, timesteps, lstm_units) -
False --> 返回最后一个时间步的输出,使用所有时间步计算:(32, 1, 20)
默认情况下,层将压缩尺寸为 1 - 所以
|
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
class seq2seq(tf.keras.Model):
def __init__(self,max_sequence_len,total_words): super(seq2seq,self).__init__() self.max_sequence_len = max_sequence_len self.total_words = total_words self.input_len = self.max_sequence_len - 1 #Encoder #decoder #Dense layer and output: def call(self,inputs): #Decoding: return output_dense |