简介
自编码器 (AutoEncoder) 是深度学习中的一类无监督学习模型, 由 encoder 和 decoder 两部分组成
encoder 将原始表示编码成隐层表示
decoder 将隐层表示解码成原始表示
训练目标为最小化重构误差
隐层特征维度一般低于原始特征维度, 降维的同时学习更稠密更有意义的表示
自编码器主要是一种思想, encoder 和 decoder 可以由全连接层, CNN 或 RNN 等模型实现
以下使用 keras, 用 CNN 实现自编码器, 通过学习从加噪图片到原始图片的映射, 完成图像去噪任务
准备
用到的数据是 MNIST, 手写数字识别数据集, Keras 中自带
训练集 5W 条, 测试集 1W 条, 都是 28*28 的灰度图
这里我们用 IPython 写代码, 因为有些地方需要交互地进行展示
在项目路径运行以下命令, 启动 IPython
jupyter notebook
加载库
- # -*- coding: utf-8 -*-
- from keras.datasets import mnist
- import numpy as np
加载 MNIST 数据, 不需要对应的标签, 将像素值归一化到 0 至 1, 重塑为 N*1*28*28 的四维 tensor, 即张量, 1 表示颜色通道, 即灰度图
- (x_train, _), (x_test, _) = mnist.load_data()
- x_train = x_train.astype('float32') / 255.
- x_test = x_test.astype('float32') / 255.
- x_train = np.reshape(x_train, (len(x_train), 28, 28, 1))
- x_test = np.reshape(x_test, (len(x_test), 28, 28, 1))
添加随机白噪声, 并限制加噪后像素值仍处于 0 至 1 之间
- noise_factor = 0.5
- x_train_noisy = x_train + noise_factor * np.random.normal(loc=0.0, scale=1.0, size=x_train.shape)
- x_test_noisy = x_test + noise_factor * np.random.normal(loc=0.0, scale=1.0, size=x_test.shape)
- x_train_noisy = np.clip(x_train_noisy, 0., 1.)
- x_test_noisy = np.clip(x_test_noisy, 0., 1.)
看一下加噪后的效果
- import matplotlib.pyplot as plt
- %matplotlib inline
- n = 10
- plt.figure(figsize=(20, 2))
- for i in range(n):
- ax = plt.subplot(1, n, i + 1)
- plt.imshow(x_test_noisy[i].reshape(28, 28))
- plt.gray()
- ax.get_xaxis().set_visible(False)
- ax.get_yaxis().set_visible(False)
- plt.show()
模型实现
定义模型的输入
- from keras.layers import Input, Dense, Conv2D, MaxPooling2D, UpSampling2D
- from keras.models import Model, load_model
- input_img = Input(shape=(28, 28, 1,))
实现 encoder 部分, 由两个 3*3*32 的卷积和两个 2*2 的最大池化组成
- x = Conv2D(32, (3, 3), padding='same', activation='relu')(input_img)
- x = MaxPooling2D((2, 2), padding='same')(x)
- x = Conv2D(32, (3, 3), padding='same', activation='relu')(x)
- encoded = MaxPooling2D((2, 2), padding='same')(x)
实现 decoder 部分, 由两个 3*3*32 的卷积和两个 2*2 的上采样组成
- # 7 * 7 * 32
- x = Conv2D(32, (3, 3), padding='same', activation='relu')(encoded)
- x = UpSampling2D((2, 2))(x)
- x = Conv2D(32, (3, 3), padding='same', activation='relu')(x)
- x = UpSampling2D((2, 2))(x)
- decoded = Conv2D(1, (3, 3), padding='same', activation='sigmoid')(x)
将输入和输出连接, 构成自编码器并 compile
- autoencoder = Model(input_img, decoded)
- autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')
使用 x_train 作为输入和输出进行训练, 使用 x_test 进行校验
- autoencoder.fit(x_train_noisy, x_train,
- epochs=100,
- batch_size=128,
- shuffle=True,
- validation_data=(x_test_noisy, x_test))
- autoencoder.save('autoencoder.h5')
在 CPU 上训练比较慢, 有条件的话可以用 GPU, 速度快上几十倍
这里将训练后的模型保存下来, 之后或在其他地方都可以直接加载使用
使用自编码器对 x_test_noisy 预测, 绘制预测结果, 和原始加噪图像进行对比, 便可以得到一开始的对比效果图
- autoencoder = load_model('autoencoder.h5')
- decoded_imgs = autoencoder.predict(x_test_noisy)
- n = 10
- plt.figure(figsize=(20, 4))
- for i in range(n):
- # display original
- ax = plt.subplot(2, n, i + 1)
- plt.imshow(x_test_noisy[i].reshape(28, 28))
- plt.gray()
- ax.get_xaxis().set_visible(False)
- ax.get_yaxis().set_visible(False)
- # display reconstruction
- 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()
来源: https://juejin.im/post/5ba2571be51d450e7762c010