【问题标题】:Conv2D + LSTM network giving errorsConv2D + LSTM 网络给出错误
【发布时间】:2019-06-08 12:18:31
【问题描述】:

我有一个名为 charMatrixList 的矩阵列表,长度为 40744。我将此列表转换为 numpy 数组,形状变为 (40744,32,30)。这个 numpy 数组作为输入传递给神经网络。

当作为输入传递到 LSTM 层时,我得到的错误与 Conv2D 层输出的形状有关。

from keras.models import Sequential 
from keras.layers import Embedding,LSTM,Flatten,Conv2D,Reshape
import numpy as np


def phase22(charMatrixList ):
    model = Sequential()
    model.add(Conv2D(32, (3, 3), strides=(1,1) , padding="same",               activation="relu",input_shape=(40744,32,30)))
    model.add(LSTM(16, return_sequences=True))
    model.add(LSTM(16, return_sequences=True))
    model.add(Flatten())
    model.compile('rmsprop', 'mse')
    input_array = charMatrixList
    model.compile('rmsprop', 'mse')
    output_array = model.predict(input_array)
    return output_array

p2out = phase22(charMatrixList)

我收到以下错误:

Traceback (most recent call last):

  File "<ipython-input-56-f615f91b6704>", line 1, in <module>
    p2out = phase22(np.array(charMatrixList) )

  File "<ipython-input-55-9a4fd292a04f>", line 4, in phase22
    model.add(LSTM(16, return_sequences=True))

  File "C:\Users\Kishore\Anaconda3\lib\site-packages\keras\engine\sequential.py", line 185, in add
    output_tensor = layer(self.outputs[0])

  File "C:\Users\Kishore\Anaconda3\lib\site-packages\keras\layers\recurrent.py", line 500, in __call__
    return super(RNN, self).__call__(inputs, **kwargs)

  File "C:\Users\Kishore\Anaconda3\lib\site-packages\keras\engine\base_layer.py", line 414, in __call__
    self.assert_input_compatibility(inputs)

  File "C:\Users\Kishore\Anaconda3\lib\site-packages\keras\engine\base_layer.py", line 311, in assert_input_compatibility
    str(K.ndim(x)))

ValueError: Input 0 is incompatible with layer lstm_11: expected ndim=3, found ndim=4

【问题讨论】:

    标签: keras conv-neural-network lstm


    【解决方案1】:

    Keras 在定义输入大小时忽略了第一个维度,因为这只是训练示例的数量 m。 Keras 能够使用任何 m,因此它只关心实际的输入尺寸。这就是为什么 Kears 将 (40744,32,30) 视为 4 个维度。

    我对您输入的维度感到困惑,40744 是训练示例的数量吗?如果是输入大小 = (32, 30)。

    如果您的输入有 3 个维度,则在您的输入中包含训练示例的数量,即。 charMatrixList = (m, 40744,32,30)

    【讨论】:

    • 感谢您的回复!! 40744 确实是训练示例的数量。但是一旦我将 input_size 更改为 (32,30) ,我就会收到一个错误:ValueError: Input 0 is incompatible with layer conv2d_1: expected ndim=4, found ndim=3.此外,问题中提到的错误不是与LSTM层有关吗?
    • 您的 conv2D 输出和 LSTM 输入的形状不匹配。 Conv2d 期望 4-d 数组作为输入(m、高度、宽度、通道数)并输出 4-d。 LSTM 期望 3-d 输入(m、时间步长、序列长度)并且可以输出 2d 或 3d。
    • 感谢 BlueSkyz !!那么我可以在 Conv2D 层之后和 LSTM 层之前添加什么样的重塑层呢?为了将 4D 输出的形状修改为 3D。现在执行正在跨越 conv2d 阶段,如下所示: model.add(Conv2D(32, (3, 3), strides=(1,1) , padding="same", ativation="relu",input_shape= (32,30,1)))
    猜你喜欢
    • 2019-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-14
    • 2016-08-24
    • 1970-01-01
    • 2019-12-02
    • 2021-07-26
    相关资源
    最近更新 更多