keras自动编码器实现系列之卷积自动编码器
生活随笔
收集整理的這篇文章主要介紹了
keras自动编码器实现系列之卷积自动编码器
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
圖片的自動編碼很容易就想到用卷積神經網絡做為編碼-解碼器。在實際的操作中,
也經常使用卷積自動編碼器去解決圖像編碼問題,而且非常有效。 下面通過**keras**完成簡單的卷積自動編碼。 編碼器有堆疊的卷積層和池化層
(max pooling用于空間降采樣)組成。 對應的解碼器由卷積層和上采樣層組成。
@requires_authorization
# -*- coding:utf-8 -*-from keras.layers import Input, Dense, Conv2D, MaxPooling2D, UpSampling2D
from keras.models import Model
from keras import backend as K
import os## 網絡結構 ##input_img = Input(shape=(28,28,1)) # Tensorflow后端, 注意要用channel_last
# 編碼器部分
x = Conv2D(16, (3,3), activation='relu', padding='same')(input_img)
x = MaxPooling2D((2,2), padding='same')(x)
x = Conv2D(8,(3,3), activation='relu', padding='same')(x)
x = MaxPooling2D((2,2), padding='same')(x)
x = Conv2D(8, (3,3), activation='relu', padding='same')(x)
encoded = MaxPooling2D((2,2), padding='same')(x)# 解碼器部分
x = Conv2D(8, (3,3), activation='relu', padding='same')(encoded)
x = UpSampling2D((2, 2))(x)
x = Conv2D(8, (3,3), activation='relu', padding='same')(x)
x = UpSampling2D((2, 2))(x)
x = Conv2D(16, (3, 3), activation='relu', padding='same')(x)
x = UpSampling2D((2, 2))(x)
decoded = Conv2D(1, (3, 3), activation='sigmoid', padding='same')(x)autoencoder = Model(input_img, decoded)
autoencoder.compile(optimizer='adam', loss='binary_crossentropy')# 得到編碼層的輸出
encoder_model = Model(inputs=autoencoder.input, outputs=autoencoder.get_layer('encoder_out').output)## 導入數據, 使用常用的手寫識別數據集
def load_mnist(dataset_name):
'''
load the data
'''data_dir = os.path.join("./data", dataset_name)f = np.load(os.path.join(data_dir, 'mnist.npz'))train_data = f['train'].TtrX = train_data.reshape((-1, 28, 28, 1)).astype(np.float32)trY = f['train_labels'][-1].astype(np.float32)test_data = f['test'].TteX = test_data.reshape((-1, 28, 28, 1)).astype(np.float32)teY = f['test_labels'][-1].astype(np.float32)# one-hot # y_vec = np.zeros((len(y), 10), dtype=np.float32)# for i, label in enumerate(y):# y_vec[i, y[i]] = 1# keras.utils里帶的有one-hot的函數, 就直接用那個了return trX / 255., trY, teX/255., teY# 開始導入數據
x_train, _ , x_test, _= load_mnist('mnist')# 可視化訓練結果, 我們打開終端, 使用tensorboard
# tensorboard --logdir=/tmp/autoencoder # 注意這里是打開一個終端, 在終端里運行# 訓練模型, 并且在callbacks中使用tensorBoard實例, 寫入訓練日志 http://0.0.0.0:6006
from keras.callbacks import TensorBoard
autoencoder.fit(x_train, x_train,epochs=50,batch_size=128,shuffle=True,validation_data=(x_test, x_test),callbacks=[TensorBoard(log_dir='/tmp/autoencoder')])# 重建圖片
import matplotlib.pyplot as plt
decoded_imgs = autoencoder.predict(x_test)
encoded_imgs = encoder_model.predict(x_test)
n = 10
plt.figure(figsize=(20, 4))
for i in range(n):k = i + 1# 畫原始圖片ax = plt.subplot(2, n, k)plt.imshow(x_test[k].reshape(28, 28))plt.gray()ax.get_xaxis().set_visible(False)# 畫重建圖片ax = plt.subplot(2, n, k + 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()# 編碼得到的特征
n = 10
plt.figure(figsize=(20, 8))
for i in range(n):k = i + 1ax = plt.subplot(1, n, k)plt.imshow(encoded[k].reshape(4, 4 * 8).T)plt.gray()ax.get_xaxis().set_visible(False)ax.get_yaxis().set_visible(False)
plt.show()
總結
以上是生活随笔為你收集整理的keras自动编码器实现系列之卷积自动编码器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 《算法图解》学习笔记(十一):十种经典的
- 下一篇: 数学建模论文的技巧与操作