tensorflow - 在 Keras 中使用嵌入层和 LSTM 作为输入的 3 维数组
问题描述
嘿伙计们,我已经建立了一个有效的 LSTM 模型,现在我正在尝试(不成功)添加一个嵌入层作为第一层。
这个解决方案对我不起作用。在提问之前我还阅读了这些问题 :Keras 输入解释:input_shape、units、batch_size、dim 等, 了解 Keras LSTMs和keras 示例。
我的输入是由 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
如何修复输出形状?您的想法将不胜感激。
解决方案
我的输入是由 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)
推荐阅读
- reactjs - React JS:找出组件是否在上下文提供者中
- jquery - jquery option select filter by other option select
- webgl - 具有两种纹理的立方体
- c++ - 具有非 POD 对象的 GLib 异步队列
- python - 是否可以将 .exe 文件转换为 .py?
- javascript - Ionic 3:播放 Icecast/Shoutcast 音频流
- ios - iOS - 表面检测
- scikit-learn - 了解 ROC 曲线
- xaml - Xamarin 表单 xaml 绑定在 iOS 中失败,但在 Android 中有效
- python - Pygame中的白框