我阅读了在 Keras 中构建自动编码器
,网址是 https://blog.keras.io/building-autoencoders-in-keras.html
在在编码表示上添加稀疏约束
部分,我根据他的描述进行了尝试,但损失无法降至0.11,而是在0.26左右。
做过这个实验的人能告诉我这个实验有什么问题吗?
这是我的代码:
from keras.layers import Input, Dense
from keras.models import Model
from keras import regularizers
encoding_dim = 32 # 压缩后维度
input_img = Input(shape = (784,))
# 编码
encoded = Dense(encoding_dim, activation = 'relu',
activity_regularizer = regularizers.l1(1e-4)
)(input_img)
# 解码
decoded = Dense(784, activation = 'sigmoid')(encoded)
# 创建自动编码器
autoencoder = Model(input_img, decoded)
# 编码器
encoder = Model(input_img, encoded)
encoded_input = Input(shape = (encoding_dim,))
# 最后一层全连接层作为解码器
decoder_layer = autoencoder.layers[-1]
# 解码器
decoder = Model(encoded_input, decoder_layer(encoded_input))
# 编译模块
autoencoder.compile(optimizer = 'adadelta', loss = 'binary_crossentropy')
from keras.datasets import mnist
import numpy as np
(x_train, _), (x_test, _) = mnist.load_data()
x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.
x_train = x_train.reshape(x_train.shape[0], np.prod(x_train.shape[1:]))
x_test = x_test.reshape(x_test.shape[0], np.prod(x_test.shape[1:]))
autoencoder.fit(x_train, x_train,
epochs = 100,
batch_size = 256,
shuffle = True,
validation_data = (x_test, x_test))
encoded_imgs = encoder.predict(x_test)
decoded_imgs = decoder.predict(encoded_imgs)
import matplotlib.pyplot as plt
n = 10
plt.figure(figsize = (20, 4))
for i in range(10):
# 原图
ax = plt.subplot(2, n, i + 1)
plt.imshow(x_test[i].reshape(28, 28))
plt.gray()
ax.set_axis_off()
# 解码后的图
ax = plt.subplot(2, n, n + i + 1)
plt.imshow(decoded_imgs[i].reshape(28, 28))
plt.gray()
ax.set_axis_off()
plt.savefig('simpleSparse.png')
from keras import backend as K
K.clear_session()
最佳答案
我逐字复制了您的代码,并重现了您收到的错误。
解决方案:将批量大小从 256 减少到 16。即使经过 10 个 epoch 的训练,您也会发现输出存在巨大差异。
解释:可能发生的情况是,即使你的训练损失减少了,你还是在太多的例子上对梯度进行平均,以至于你在梯度方向上采取的步骤正在取消它本身处于某个更高维度的空间中,并且您的学习算法被欺骗,认为它收敛到局部最小值,而实际上它无法决定去哪里。最后一部分解释了为什么您获得的所有输出看起来都模糊且完全相同。
更新:将批量大小减少到 4,即使在 10 个 epoch 后,您也将获得近乎完美的重建。
关于keras - 关于 'Building Autoencoders in Keras'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43673076/