Autoencoder的训练目标就是尽可能地重构出输入数据本身,也就是输入数据就是标签数据。解决方法是在模型训练的时候将输入数据作为标签数据同时传入。
下面给出一个简单的Autoencoder代码示例:
import tensorflow as tf
# 定义Autoencoder的输入和输出
inputs = tf.keras.layers.Input(shape=(784,))
outputs = tf.keras.layers.Dense(units=784, activation='relu')(inputs)
# 定义编码器和解码器
encoder = tf.keras.models.Model(inputs, outputs, name='encoder')
decoder = tf.keras.models.Sequential([
tf.keras.layers.Dense(units=256, activation='relu'),
tf.keras.layers.Dense(units=784, activation='sigmoid')
], name='decoder')
# 定义完整的Autoencoder模型
autoencoder = tf.keras.models.Sequential([encoder, decoder])
autoencoder.compile(optimizer='adam', loss='binary_crossentropy')
# 加载MNIST数据集
(x_train, _), (x_test, _) = tf.keras.datasets.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), 784))
x_test = x_test.reshape((len(x_test), 784))
# 训练Autoencoder
autoencoder.fit(x_train, x_train,
epochs=10,
batch_size=256,
shuffle=True,
validation_data=(x_test, x_test))
代码中的x_train
和x_test
都是既作为输入数据也作为标签数据传入模型的。