首页 > 解决方案 > 如何在 Keras 中为 Bi-LSTM 准备 2D 形状

问题描述

我有一个已经压缩的词向量的 2D numpy 矩阵(来自 DataFrame)(我使用了最大池技术,正在尝试将 logres 与 bi-LSTM 方法进行比较),但我不知道如何准备它在 keras 模型中使用它。

我知道 Bi-LSTM 模型需要 3D 张量,并尝试了谷歌搜索解决方案,但找不到有效的解决方案。

这就是我现在所拥有的:

# Set model parameters
epochs = 4
batch_size = 32
input_shape = (1, 10235, 3072)

# Create the model
model = Sequential()
model.add(Bidirectional(LSTM(64, return_sequences = True, input_shape = input_shape)))
model.add(Dropout(0.5))
model.add(Dense(1, activation = 'sigmoid'))

# Try using different optimizers and different optimizer configs
model.compile('adam', 'binary_crossentropy', metrics = ['accuracy'])

# Fit the training set over the model and correct on the validation set
model.fit(inputs['X_train'], inputs['y_train'],
            batch_size = batch_size,
            epochs = epochs,
            validation_data = [inputs['X_validation'], inputs['y_validation']])

# Get score over the test set
return model.evaluate(inputs['X_test'], inputs['y_test'])

我目前收到以下错误:

ValueError: Input 0 is incompatible with layer bidirectional_23: expected ndim=3, found ndim=2

inputs['X_train']我的训练数据 ( )的形状是(10235, 3072)

非常感谢!

标签: pythonkeraslstmbidirectional

解决方案


我通过执行以下操作使其与回复的建议一起工作:

  1. 删除return_sequence = True
  2. 对 X 集应用以下变换:np.reshape(inputs[dataset], (inputs[dataset].shape[0], inputs[dataset].shape[1], 1))
  3. 将 LSTM 层的输入形状更改(10235, 3072, 1)为 的形状X_train

推荐阅读