首页 > 解决方案 > 如何使用 Keras 从密集层转到 conv2D 层?

问题描述

我只是想按照标题所说的去做。这是我的代码:

def ConvAutoEncoder(train_data,test_data,n_epochs = 50,batchSize = 128,data_shape=(IMAGE_SIZE,IMAGE_SIZE,3)):

print('Training Neural Network')
input_img = Input(shape=data_shape)

x = Conv2D(32, (3, 3), activation='relu', padding='same')(input_img)
x = MaxPooling2D((2, 2), padding='same')(x)
print(x.shape)
x = Conv2D(16, (3, 3), activation='relu', padding='same')(x)
x = MaxPooling2D((2, 2), padding='same')(x)
print(x.shape)
x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
x = MaxPooling2D((2, 2), padding='same')(x)
print(x.shape)
x = Conv2D(4, (3, 3), activation='relu', padding='same')(x)
encoded = MaxPooling2D((2, 2), padding='same')(x)
print(encoded.shape)

# at this point the representation is (6, 6, 4 i.e. 128-dimensional
encoded = Flatten()(encoded)
encoded = Dense( 6*6*4,activation='relu')(encoded)
print(encoded.shape)
endoded = Reshape((6,6,4))(encoded)
print(encoded.shape)

x = Conv2D(4, (3, 3), activation='relu', padding='same')(encoded)
x = UpSampling2D((2, 2))(x)
print(x.shape)
x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
x = UpSampling2D((2, 2))(x)
print(x.shape)
x = Conv2D(16, (3, 3), activation='relu', padding='same')(x)
x = UpSampling2D((2, 2))(x)
print(x.shape)
x = Conv2D(32, (3, 3), activation='relu', padding='same')(x)
x = UpSampling2D((2, 2))(x)
print(x.shape)
decoded = Conv2D(3, (3, 3), activation='sigmoid', padding='same')(x)

autoencoder = Model(input_img, decoded)
autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')

autoencoder.fit(train_data, train_data,
            epochs=n_epochs,
            batch_size=batchSize,
            shuffle=True,
            verbose=2,
            validation_data=(test_data, test_data),
            callbacks=[TensorBoard(log_dir='/tmp/autoencoder')])


return autoencoder

但是,当我运行它时,Reshape 层根本不做任何事情,reshape 之前的输出形状是 (?,144),之后的形状也是 (?,144)。我使用 reshape 错误还是有其他方法可以将密集层连接到 conv2D 层?

标签: pythonkerasreshapelayer

解决方案


推荐阅读