构建自动编码器时收到错误

Error Received while building the Auto encoder

我正在尝试使用 CNN 作为编码器和 LSTM 作为解码器为我的学期项目构建一个自动编码器,但是当我显示模型的摘要时。我收到以下错误:

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

x.shape = (45406, 100, 100)
y.shape = (45406,)

我已经尝试过更改 LSTM 输入的形状,但没有成功。

def keras_model(image_x, image_y):

model = Sequential()
model.add(Lambda(lambda x: x / 127.5 - 1., input_shape=(image_x, image_y, 1)))

last = model.output
x = Conv2D(3, (3, 3), padding='same')(last)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = MaxPooling2D((2, 2), padding='valid')(x)

encoded= Flatten()(x)
x = LSTM(8, return_sequences=True, input_shape=(100,100))(encoded)
decoded = LSTM(64, return_sequences = True)(x)

x = Dropout(0.5)(decoded)
x = Dense(400, activation='relu')(x)
x = Dense(25, activation='relu')(x)
final = Dense(1, activation='relu')(x)

autoencoder = Model(model.input, final)

autoencoder.compile(optimizer="Adam", loss="mse")
autoencoder.summary()

model= keras_model(100, 100)

鉴于您使用的是 LSTM,您需要一个时间维度。所以你的输入形状应该是:(time, image_x, image_y, nb_image_channels)。

我建议更深入地了解自动编码器、LSTM 和 2D 卷积,因为它们在这里一起发挥作用。这是一个有用的介绍:https://machinelearningmastery.com/lstm-autoencoders/ and this https://blog.keras.io/building-autoencoders-in-keras.html)。

另请查看此示例,有人使用 Conv2D 实现了 LSTM。 TimeDistributed 层在这里很有用。

但是,为了修复错误,您可以添加一个 Reshape() 层来伪造额外的维度:

def keras_model(image_x, image_y):

    model = Sequential()
    model.add(Lambda(lambda x: x / 127.5 - 1., input_shape=(image_x, image_y, 1)))

    last = model.output
    x = Conv2D(3, (3, 3), padding='same')(last)
    x = BatchNormalization()(x)
    x = Activation('relu')(x)
    x = MaxPooling2D((2, 2), padding='valid')(x)

    encoded= Flatten()(x)
    # (50,50,3) is the output shape of the max pooling layer (see model summary)
    encoded = Reshape((50*50*3, 1))(encoded)
    x = LSTM(8, return_sequences=True)(encoded)  # input shape can be removed
    decoded = LSTM(64, return_sequences = True)(x)

    x = Dropout(0.5)(decoded)
    x = Dense(400, activation='relu')(x)
    x = Dense(25, activation='relu')(x)
    final = Dense(1, activation='relu')(x)

    autoencoder = Model(model.input, final)

    autoencoder.compile(optimizer="Adam", loss="mse")
    print(autoencoder.summary())

model= keras_model(100, 100)