嵌入层

时间:2018-06-16 09:11:20

标签: python keras

我一直在尝试在Keras中实现LSTM几个小时(使用带有嵌入层的顺序模型,两个LSTM层和一个密集层),但我最终得到了不同的错误消息。

据我所知,问题是嵌入层的输出有两个维度而不是三个,因为我在添加第二个LSTM图层时得到这个值错误(ValueError: Input 0 is incompatible with layer lstm_2: expected ndim=3, found ndim=2),我得到了错误assert len(input_shape) >= 3 AssertionError当我删除添加第二个LSTM图层的行时(这意味着密集图层具有相同的问题)。

在我调用模型的“train”方法之前发生了这些错误。

我的代码在这里。

from keras.models import Sequential
from keras.layers import Dense, Activation
from keras.layers import LSTM
from keras.layers import Embedding
from keras.layers import TimeDistributed
from keras.preprocessing import text
from keras.preprocessing.sequence import pad_sequences

# The data in X was preprocessed using Keras' built in pad_sequences.
# Before preprocessing, it consisted of plain lists of integers (which
# were just integers wit a one-to-one map to plain words as strings)

X = pad_sequences(X)

model = Sequential()
model.add(Embedding(batch_size=32, input_dim=len(filtered_vocabulary)+1, output_dim=256, input_length=38))
model.add(LSTM(128))
model.add(LSTM(128)) # error occurs in this line
model.add(TimeDistributed(Dense(len(filtered_vocabulary)+1, activation="softmax")))

model.compile(optimizer = "rmsprop", loss="categorical_crossentropy", metrics=["accuracy"])
model.fit(X, X, epochs=60, batch_size=32)

如果你们中的任何人能帮助我,我会很高兴。

1 个答案:

答案 0 :(得分:0)

发生错误是因为第一个LSTM图层仅返回 last 输出,因为您尚未在LSTM图层中指定return_sequences=True。这看起来像一个多输出设置,因此您需要使用该参数在每个时间步返回LSTM输出

为了清楚起见,没有return_sequences=True形状为(None, 128);形状为(None, 38, 128)

相关问题