自编码器(Autoencoder)在MNIST数据集运行结果与示例不符问题求助
问题原因
你遇到的重建效果差的问题由两个核心错误导致:
- 优化器参数不匹配:你使用默认参数的
adadelta优化器,TensorFlow 2.x版本中Adadelta的默认学习率仅为0.001,而你参考的早期公开示例中Adadelta的默认学习率为1.0,过低的学习率导致50轮训练后模型完全没有收敛,所以输出结果全是无意义的噪声。 - 层共享写法不规范:你将同一个隐藏层、输出层实例同时添加到三个不同的Sequential模型(autoencoder、encoder、decoder)中,部分TensorFlow版本下会出现参数更新异常,导致训练失效。
修复方案
直接替换优化器,同时调整模型定义写法即可,修改后的可运行代码如下:
import tensorflow as tf from tensorflow.keras.layers import Input, Dense from tensorflow.keras.models import Model from tensorflow.keras.datasets import mnist import numpy as np import matplotlib.pyplot as plt # 模型参数 hidden_size = 32 # 不需要用784,32维就能得到很好的效果 input_layer = Input(shape=(784,)) # 用Functional API分开定义编码器、解码器,避免层共享问题 # 编码器 hidden_layer = Dense(hidden_size, activation="relu")(input_layer) encoder = Model(input_layer, hidden_layer) # 解码器 decoder_input = Input(shape=(hidden_size,)) output_layer = Dense(784, activation="sigmoid")(decoder_input) decoder = Model(decoder_input, output_layer) # 完整自编码器 autoencoder_output = decoder(encoder(input_layer)) autoencoder = Model(input_layer, autoencoder_output) # 重点:要么给Adadelta设置学习率为1.0,要么直接用Adam优化器,收敛更快 # 写法1:用适配旧教程的Adadelta配置 # autoencoder.compile(optimizer=tf.keras.optimizers.Adadelta(learning_rate=1.0), loss='binary_crossentropy') # 写法2:用更常用的Adam优化器,不需要调整参数就能得到好效果 autoencoder.compile(optimizer='adam', loss='binary_crossentropy') # 数据预处理逻辑和原来一致 (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((len(x_train), np.prod(x_train.shape[1:]))) x_test = x_test.reshape((len(x_test), np.prod(x_test.shape[1:]))) # 训练 autoencoder.fit(x_train, x_train, epochs=50, batch_size=256, validation_data=(x_test, x_test), verbose=1) # 推理 encoded_imgs = encoder.predict(x_test) decoded_imgs = decoder.predict(encoded_imgs) # 可视化 n = 10 plt.figure(figsize=(20, 4)) for i in range(n): ax = plt.subplot(2, n, i + 1) plt.imshow(x_test[i].reshape(28, 28)) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) ax = plt.subplot(2, n, i + 1 + n) plt.imshow(decoded_imgs[i].reshape(28, 28)) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) plt.show()
修改后只需要将隐藏层尺寸设为32,跑50轮就能得到和公开示例一致的清晰重建结果。
内容的提问来源于stack exchange,提问作者Boom
相关产品推荐
相关产品推荐

