自编码器的多种类型、训练方法及应用
1. 可视化重建结果
为确保自编码器训练得当,可对比输入和输出,二者差异不应过大。以下是绘制验证集中部分图像及其重建结果的代码:
import matplotlib.pyplot as plt def plot_image(image): plt.imshow(image, cmap="binary") plt.axis("off") def show_reconstructions(model, n_images=5): reconstructions = model.predict(X_valid[:n_images]) fig = plt.figure(figsize=(n_images * 1.5, 3)) for image_index in range(n_images): plt.subplot(2, n_images, 1 + image_index) plot_image(X_valid[image_index]) plt.subplot(2, n_images, 1 + n_images + image_index) plot_image(reconstructions[image_index]) # 假设 stacked_ae 是训练好的自编码器模型 show_reconstructions(stacked_ae)重建结果虽可识别,但存在一定损失。可能需要延长训练时间、加深编码器和解码器或增大编码尺寸。不过,若网络过强,可能在未学习到