從本講開始,筆者將花一些時間和大家一起學習深度學習中的無監(jiān)督模型。從現(xiàn)有情況來看,無監(jiān)督學習很有可能是一把決定深度學習未來發(fā)展方向的鑰匙,在缺乏高質(zhì)量打標數(shù)據(jù)的監(jiān)督機器學習時代,若是能在無監(jiān)督學習方向上有所突破對于未來深度學習的發(fā)展意義重大。從自編碼器到生成對抗網(wǎng)絡(luò),筆者將和大家一起來探索深度學習中的無監(jiān)督學習。
所謂自編碼器(Autoencoder,AE),就是一種利用反向傳播算法使得輸出值等于輸入值的神經(jīng)網(wǎng)絡(luò),它現(xiàn)將輸入壓縮成潛在空間表征,然后將這種表征重構(gòu)為輸出。所以,從本質(zhì)上來講,自編碼器是一種數(shù)據(jù)壓縮算法,其壓縮和解壓縮算法都是通過神經(jīng)網(wǎng)絡(luò)來實現(xiàn)的。自編碼器有如下三個特點:
數(shù)據(jù)相關(guān)性。就是指自編碼器只能壓縮與自己此前訓練數(shù)據(jù)類似的數(shù)據(jù),比如說我們使用mnist訓練出來的自編碼器用來壓縮人臉圖片,效果肯定會很差。
數(shù)據(jù)有損性。自編碼器在解壓時得到的輸出與原始輸入相比會有信息損失,所以自編碼器是一種數(shù)據(jù)有損的壓縮算法。
自動學習性。自動編碼器是從數(shù)據(jù)樣本中自動學習的,這意味著很容易對指定類的輸入訓練出一種特定的編碼器,而不需要完成任何新工作。
構(gòu)建一個自編碼器需要兩部分:編碼器(Encoder)和解碼器(Decoder)。編碼器將輸入壓縮為潛在空間表征,可以用函數(shù)f(x)來表示,解碼器將潛在空間表征重構(gòu)為輸出,可以用函數(shù)g(x)來表示,編碼函數(shù)f(x)和解碼函數(shù)g(x)都是神經(jīng)網(wǎng)絡(luò)模型。
所以,我們大致搞清楚了自編碼器是一種讓輸入等于輸出的算法。但僅僅如此嗎?當然不是,如果一個算法只是為了讓輸入等于輸出,那這個算法意義肯定不大,自編碼器的核心價值在于經(jīng)編碼器壓縮后的潛在空間表征。上面我們提到自編碼器是一種數(shù)據(jù)有損的壓縮算法,經(jīng)過這種有損的數(shù)據(jù)壓縮,我們可以學習到輸入數(shù)據(jù)種最重要的特征。
雖然自編碼器對于我們是個新概念,但是其內(nèi)容本身非常簡單。在后面的keras實現(xiàn)中大家可以看到如何用幾行代碼搭建和訓練一個自編碼器。那么重要的問題來了,自編碼器這樣的自我學習模型到底有什么用呢?這個問題的答案關(guān)乎無監(jiān)督學習在深度學習領(lǐng)域的價值,所以還是非常有必要說一下的。自編碼器吸引了一大批研究和關(guān)注的主要原因之一是很長時間一段以來它被認為是解決無監(jiān)督學習的可能方案,即大家覺得自編碼器可以在沒有標簽的時候?qū)W習到數(shù)據(jù)的有用表達。但就具體應(yīng)用層面上而言,自編碼器通常有兩個方面的應(yīng)用:一是數(shù)據(jù)去噪,二是為進行可視化而降維。自編碼器在適當?shù)木S度和系數(shù)約束下可以學習到比PCA等技術(shù)更有意義的數(shù)據(jù)映射。
原始的自編碼器實現(xiàn)起來非常容易,我們來看一下如何使用keras來實現(xiàn)一個簡易的自編碼器。使用全連接網(wǎng)絡(luò)作為編碼和解碼器:
from keras.layers import Input, Dense
from keras.models import Model
import warningswarnings.filterwarnings('ignore')
# 編碼潛在空間表征維度
encoding_dim = 32
# 自編碼器輸入
input_img = Input(shape=(784,))
# 使用一個全連接網(wǎng)絡(luò)來搭建編碼器
encoded = Dense(encoding_dim, activation='relu')(input_img)
# 使用一個全連接網(wǎng)絡(luò)來對編碼器進行解碼
decoded = Dense(784, activation='sigmoid')(encoded)
# 構(gòu)建keras模型
autoencoder = Model(input=input_img, output=decoded)
模型概要如下:
我們也可以把編碼器和解碼器當作單獨的模型來使用:
# 編碼器模型
encoder = Model(input=input_img, output=encoded)
# 解碼器模型
encoded_input = Input(shape=(encoding_dim,))decoder_layer = autoencoder.layers[-1]decoder = Model(input=encoded_input, output=decoder_layer(encoded_input))
對自編碼器模型進行編譯并使用mnist數(shù)據(jù)進行訓練:
# 編譯模型
autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')
# 準備mnist數(shù)據(jù)
from keras.datasets import mnist
import numpy as np(x_train, _), (x_test, _) = 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), np.prod(x_train.shape[1:])))x_test = x_test.reshape((len(x_test), np.prod(x_test.shape[1:])))
# 訓練
autoencoder.fit(x_train, x_train, nb_epoch=50, batch_size=256, shuffle=True, validation_data=(x_test, x_test))
50輪訓練之后的損失降低到0.1:
對原始輸入圖像和自編碼器訓練后的圖像進行可視化的直觀展示,看看自編碼器學習效果如何:
import matplotlib.pyplot as pltencoded_imgs = encoder.predict(x_test)decoded_imgs = decoder.predict(encoded_imgs)n = 10
plt.figure(figsize=(20, 4))
for i in range(1, n):
# 展示原始圖像 ax = plt.subplot(2, n, i) plt.imshow(x_test[i].reshape(28, 28)) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False)
# 展示自編碼器重構(gòu)后的圖像 ax = plt.subplot(2, n, i + 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()
效果如下,可見基于全連接網(wǎng)絡(luò)的自編碼器在mnist數(shù)據(jù)集上表現(xiàn)還不錯。
前面我們講到自編碼器的一個重要作用就是給數(shù)據(jù)進行降噪處理。同樣是mnist數(shù)據(jù)集,我們給原始數(shù)據(jù)添加一些噪聲看看:
from keras.datasets import mnist
import numpy as np(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), 1, 28, 28))x_test = np.reshape(x_test, (len(x_test), 1, 28, 28))
# 給數(shù)據(jù)添加噪聲
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.)
展示添加了噪聲后的mnist數(shù)據(jù)示例:
# 噪聲數(shù)據(jù)展示
n = 10
plt.figure(figsize=(20, 4))
for i in range(1, n): ax = plt.subplot(2, n, i) plt.imshow(x_train_noisy[i].reshape(28, 28)) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False)plt.show()
下面我們想要自編碼器模型對上述經(jīng)過噪聲處理后的數(shù)據(jù)進行降噪和還原,我們使用卷積神經(jīng)網(wǎng)絡(luò)作為編碼和解碼模型:
from keras.layers import Input, Dense, UpSampling2D
from keras.layers import Convolution2D, MaxPooling2D
from keras.models import Model
# 輸入維度
input_img = Input(shape=(1, 28, 28))
# 基于卷積和池化的編碼器
x = Convolution2D(32, 3, 3, activation='relu', border_mode='same')(input_img)x = MaxPooling2D((2, 2), border_mode='same')(x)x = Convolution2D(32, 3, 3, activation='relu', border_mode='same')(x)encoded = MaxPooling2D((2, 2), border_mode='same')(x)
# 基于卷積核上采樣的解碼器
x = Convolution2D(32, 3, 3, activation='relu', border_mode='same')(encoded)x = UpSampling2D((2, 2))(x)x = Convolution2D(32, 3, 3, activation='relu', border_mode='same')(x)x = UpSampling2D((2, 2))(x)decoded = Convolution2D(1, 3, 3, activation='sigmoid', border_mode='same')(x)
# 搭建模型并編譯
autoencoder = Model(input_img, decoded)autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')
對噪聲數(shù)據(jù)進行自編碼器的訓練:
# 對噪聲數(shù)據(jù)進行自編碼訓練
autoencoder.fit(x_train_noisy, x_train, nb_epoch=100, batch_size=128, shuffle=True, validation_data=(x_test_noisy, x_test))
經(jīng)過卷積自編碼器訓練之后的噪聲圖像還原效果如下:
添加的噪聲基本被消除了,可見自編碼器確實是一種較好的數(shù)據(jù)降噪算法。本講的筆記就到這里,后面筆者將繼續(xù)深入分享關(guān)于變分自編碼器(VAE)的相關(guān)內(nèi)容。
參考資料:
https://blog.keras.io/building-autoencoders-in-keras.html
深度學習 Ian GoodFellow
https://zhuanlan.zhihu.com/p/34238979