关于';在Keras';中构建自动编码器;?
我在Keras中阅读了构建自动编码器的关于';在Keras';中构建自动编码器;?,keras,Keras,我在Keras中阅读了构建自动编码器的,url是 在的部分中,我根据他的描述尝试在编码表示上添加稀疏性约束,但损失不能降到0.11,而是大约0.26 所以结果是模糊的: 做过这个实验的人能告诉我有什么问题吗 这是我的密码: from keras.layers import Input, Dense from keras.models import Model from keras import regularizers encoding_dim = 32 # 压缩后维度 input_img
,url是
在的部分中,我根据他的描述尝试在编码表示上添加稀疏性约束,但损失不能降到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个阶段的培训,输出也不会有巨大差异
说明:可能发生的情况是,尽管训练损失有所减少,但在太多的例子中,你平均了梯度,在某种程度上,你在梯度方向上采取的步骤是在某个高维空间中抵消自身,你的学习算法被欺骗,认为它收敛到局部极小值,而实际上它无法决定去哪里。最后一部分解释了为什么您得到的所有输出看起来都模糊且完全相同
更新:将批处理大小减少到4,即使经过10个时代,您也将获得近乎完美的重建。您需要更改代码中的批处理大小
自动编码器.fit(x_序列,x_序列,历代数=10,批量大小=16,随机数=True,验证数据=(x_测试,x_测试))已知错误。需要将正则化器设置为10e-7
activity_regularizer=regularizers.activity_l1(10e-7))(input_img)
50个时代之后,瓦卢损失:0.1424
如果降低批处理大小,则显示代码所需的时间要长得多。与教程相同。无论出于何种原因,当我运行此代码(也是逐字)时,我会陷入0.28的丢失状态,批处理大小=4
。批量越大,损失越大。我的输出与OP的输出相匹配。