首页 > 解决方案 > 在 Keras 中使用嵌入层和 LSTM 作为输入的 3 维数组

问题描述

嘿伙计们,我已经建立了一个有效的 LSTM 模型,现在我正在尝试(不成功)添加一个嵌入层作为第一层。

这个解决方案对我不起作用。在提问之前我还阅读了这些问题 :Keras 输入解释:input_shape、units、batch_size、dim 等了解 Keras LSTMskeras 示例

我的输入是由 27 个字母组成的语言字符的单热编码(1 和 0)。我选择将每个单词表示为 10 个字符的序列。每个单词的输入大小是(10,27),我有 465 个,所以X_train.shape (465,10,27)我也有一个大小标签y_train.shape (465,1)。我的目标是训练一个模型,同时构建一个字符嵌入。

现在这是编译和拟合的模型。

main_input = Input(shape=(10, 27))
rnn = Bidirectional(LSTM(5))
x = rnn(main_input)
de = Dense(1, activation='sigmoid')(x)
model = Model(inputs = main_input, outputs = de)
model.compile(loss='binary_crossentropy',optimizer='adam')
model.fit(X_train, y_train, epochs=10, batch_size=1, verbose=1)

添加嵌入层后:

main_input = Input(shape=(10, 27))
emb = Embedding(input_dim=2, output_dim = 10)(main_input)
rnn = Bidirectional(LSTM(5))
x = rnn(emb)
de = Dense(1, activation='sigmoid')(x)
model = Model(inputs = main_input, outputs = de)
model.compile(loss='binary_crossentropy',optimizer='adam')
model.fit(X_train, y_train, epochs=10, batch_size=1, verbose=1)

输出:ValueError:输入 0 与双向 31 层不兼容:预期 ndim=3,发现 ndim=4

如何修复输出形状?您的想法将不胜感激。

标签: tensorflowkeraslstmword-embedding

解决方案


我的输入是由 27 个字母组成的语言字符的单热编码(1 和 0)。

您不应该将 one-hot-encoding 传递给Embedding. Embedding层将整数索引映射到 n 维向量。因此,您应该直接传入 pre-one-hotted 索引。

即,在你有一个单一的输入之前[[0, 1, 0], [1, 0, 0], [0, 0, 1]],它是从一组整数创建的,比如[1, 0, 2]. 而不是传递(10, 27)one-hotted 向量,而是传递 的原始向量(10,)

main_input = Input(shape=(10,)) # only pass in the indexes
emb = Embedding(input_dim=27, output_dim = 10)(main_input) # vocab size is 27
rnn = Bidirectional(LSTM(5))
x = rnn(emb)
de = Dense(1, activation='sigmoid')(x)
model = Model(inputs = main_input, outputs = de)
model.compile(loss='binary_crossentropy',optimizer='adam')
model.fit(X_train, y_train, epochs=10, batch_size=1, verbose=1)

推荐阅读