簡介
自編碼器(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()
參考
- Building Autoencoders in Keras:https://blog.keras.io/building-autoencoders-in-keras.html