自編碼器是神經網路的一種,是一種無監督學習方法,使用了反向傳播演算法,目標是使輸出=輸入。自編碼網路可以參考這篇介紹deeplearning筆記–自編碼網路
本文實現了乙個利用keras(tensorflow backend)實現的自編碼網路。keras使用了tensorflow的框架,在其之上**更加清晰簡潔。
預覽去噪結果(迭代100次):
下面**分析
"""
author=aaron
python=3.5
keras=2.0.6
tensorflow=1.2.1
"""from keras import input
import numpy as np
from keras.layers import maxpooling2d, upsampling2d, conv2d
from keras.models import model
from tensorflow.examples.tutorials.mnist import input_data
import matplotlib.pyplot as plt
mnist = input_data.read_data_sets('d:\data
\minist
\\', one_hot=true)
x_train, x_test = mnist.train.images, mnist.test.images
將784維轉換為28*28矩陣。
x_train = np.reshape(x_train, (len(x_train), 28, 28, 1))
x_test = np.reshape(x_test, (len(x_test), 28, 28, 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.)
在原圖和加雜訊圖中各選取十張繪圖顯示比對。
n = 10
plt.figure(figsize=(20, 4))
for i in range(n):
# display original images
ax = plt.subplot(2, n, i + 1)
plt.imshow(x_test[i].reshape(28, 28))
plt.gray()
ax.get_xaxis().set_visible(false)
ax.get_yaxis().set_visible(false)
# display noise images
ax = plt.subplot(2, n, i + 1 + n)
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()
繪圖結果
選定模型的輸入,decoded(即輸出)的格式
auto_encoder = model(input_img, decoded)
定義優化目標和損失函式
auto_encoder.compile(optimizer='sgd', loss='mean_squared_error')
auto_encoder.fit(x_train_noisy, x_train, # 輸入輸出
epochs=1, # 迭代次數
batch_size=128,
shuffle=true,
validation_data=(x_test_noisy, x_test))
測試集合輸入去噪網路之後輸出去噪結果。
decoded_imgs = auto_encoder.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()
最終去噪效果:
完整**:denoise_auto_encoder_keras.py
去噪自動編碼器
強制自動編碼器學習有用特徵的另一種方法是向其輸入中新增雜訊,訓練它來恢復原始的無雜訊輸入。這個想法自1980年代開始就存在 在yann lecun 1987年的碩士 中提到過 在2008年的 中,pascal vincent等人表明自動編碼器也可以用於特徵提取。在2010年的 中,vincent等人...
RNN與自編碼網路
自編碼網路的乙個高階版本 加入了雅可比矩陣限制,即在隱藏層輸出上新增了隱層輸出h對輸入x的雅可比矩陣的二範約束。rnn用在句子生成上,其中乙個主要的步驟是word embeddings,其表示將乙個單詞 對映為乙個向量,這樣在比較單詞相似性時,只需比較對應的單詞向量的歐氏距離即可。theano中定義...
自編碼網路實現Mnist
usr bin python3 coding utf 8 time 2018 3 16 author machuanbin import tensorflow as tf from tensorflow.examples.tutorials.mnist import input data impor...