【问题标题】:How to get a 2D shape ready for a Bi-LSTM in Keras如何在 Keras 中为 Bi-LSTM 准备 2D 形状
【发布时间】:2019-05-20 13:18:11
【问题描述】:

我有一个已经压缩的词向量的 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)

非常感谢!

【问题讨论】:

  • 使用 inputs['X_test'].apply(lambda x: np.reshape(x, (1, 10235, 3072)))
  • @BenjaminBreton 感谢您的快速回复!我已经尝试过了,但现在我遇到了以下错误:ValueError: Error when checking target: expected dense_29 to have 3 dimensions, but got array with shape (10235, 1)
  • 你不应该有 return_sequence=True 除非你想预测每个序列元素的一个值,在这种情况下,Dense 应该是 时间分布

标签: python keras lstm bidirectional


【解决方案1】:

我已通过执行以下操作使其符合回复的建议:

  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的形状。

【讨论】:

    猜你喜欢
    • 2019-02-03
    • 1970-01-01
    • 1970-01-01
    • 2018-09-24
    • 2016-07-05
    • 2018-02-27
    • 2017-12-12
    • 2019-01-20
    • 1970-01-01
    相关资源
    最近更新 更多