深度有趣 | 05 自編碼器影象去噪
自編碼器(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() 複製程式碼