ValueError:Input 0 is in compatible with layer lstm_1: expected ndim=3,found ndim=4

Posted

技术标签:

【中文标题】ValueError:Input 0 is in compatible with layer lstm_1: expected ndim=3,found ndim=4【英文标题】:ValueError:Input 0 is incompatible with layer lstm_1: expected ndim=3,found ndim=4 【发布时间】:2021-09-23 02:56:55 【问题描述】:
class SmallerVGGNet:
    @staticmethod
    def build(width, height, depth, classes, finalAct="softmax"):
        # initialize the model along with the input shape to be
        # "channels last" and the channels dimension itself
        model = Sequential()
        inputShape = (height, width, depth)
        chanDim = -1
        units = 1

        if K.image_data_format() == "channels_first":
            inputShape = (depth, height, width)
            chanDim = 1
 # CONV => RELU => POOL
        model.add(Conv2D(16, (3, 3), padding="same", input_shape=inputShape,))
        model.add(BatchNormalization(axis=chanDim))
        model.add(Activation("relu"))
 model.add(
            LSTM(128, activation='tanh', return_sequences=True, use_bias=True, kernel_initializer="glorot_uniform"))
 # softmax classifier
        model.add(Flatten())
        model.add(Dropout(0.5))

        print(model.summary())
        return model

如何解决这个错误? str(x.shape.as_list())) ValueError: 层 lstm 的输入 0 与层不兼容:预期 ndim=3,发现 ndim=4。收到的完整形状:[None, 16, 16, 128]

【问题讨论】:

【参考方案1】:

LSTM 需要输入:形状为 [batch, timesteps, feature] 的 3D 张量

工作示例代码

inputs = tf.random.normal([32, 10, 8])
lstm = tf.keras.layers.LSTM(4)
output = lstm(inputs)
print(output.shape)

输出

(32, 4)

【讨论】:

以上是关于ValueError:Input 0 is in compatible with layer lstm_1: expected ndim=3,found ndim=4的主要内容,如果未能解决你的问题,请参考以下文章

ValueError: Input 0 is in compatible with layer conv_1: expected ndim=3, found ndim=4

ValueError: Input 0 is in compatible with layer vggface_resnet50: expected shape=(None, 224, 224, 3)

如何修复:ValueError: Input 0 is in compatible with layer lstm_2: expected ndim=3, found ndim=2

TensorFlow ValueError: Input 0 is in compatible with layer model_1: expected shape=(None, 32, 32, 1)

Keras LSTM ValueError: Input 0 of layer "sequential" is in compatible with the layer: expe

Keras ValueError: Input 0 is in compatible with layer conv2d_1: expected ndim=4, found ndim=5