从经过训练的自动编码中为解码器获取多个层

2024-04-25 23:58:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从一个训练有素的自动编码器制作一个多层解码器。不幸的是,解码器似乎无法重建测试图像

我一直在关注keras的博客https://blog.keras.io/building-autoencoders-in-keras.html。但是,我做了一些细微的更改,并在自动编码器中添加了另一个密集层用于编码和解码

以下是我的自动编码器型号:

encoding_dim = 18  
input_img = Input(shape=(784,), name='img_input')

encoded_1 = Dense(100, activation='relu', name='encoded_1')(input_img)
encoded_2 = Dense(encoding_dim, activation='relu', name='encoded_2')(encoded_1)

decoded_1 = Dense(100, activation='sigmoid', name='decoded_1')(encoded_2)
decoded_2 = Dense(784,  activation='sigmoid', name='decoded_2')(decoded_1)

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

hist = autoencoder.fit(x_train, x_train,
                epochs=100,
                batch_size=256,
                shuffle=True,
                validation_data=(x_test, x_test))

plot_model(autoencoder, to_file= 'model.png')
autoencoder.summary()

现在,我定义了编码器和解码器模型:

# Making the encoder model
new_encoded_1 = autoencoder.layers[1]
new_encoded_2 = autoencoder.layers[2]

encoder = Model(input_img, new_encoded_2.output)
encoder.summary()

#The decoder model
encoded_input = Input(shape=(encoding_dim,), name='encoded_input')
new_decoded_1 = autoencoder.layers[-2](encoded_input)
new_decoded_2 = autoencoder.layers[-1](new_decoded_1)

decoder = Model(encoded_input, new_decoded_2)
decoder.summary()

最后,我在编码器和解码器上使用了测试数据集,但重建的图像与测试图像完全不相似

encoded_imgs = encoder.predict(x_test)
decoded_imgs = decoder.predict(encoded_imgs)

似乎我遗漏了一些小东西,因为在单层解码器中,似乎与单层解码器配合得很好

n = 10  # how many digits we will display
plt.figure(figsize=(20, 4))
for i in range(n):
    # display original
    ax = plt.subplot(2, n, i + 1)
    plt.imshow(x_test[i].reshape(28, 28))
    plt.gray()


    # display reconstruction
    ax = plt.subplot(2, n, i + 1 + n)
    plt.imshow(decoded_imgs[i].reshape(28, 28))
    plt.gray()

plt.show()

Tags: nametestencoderimgnewinputmodelplt