1. 程式人生 > 程式設計 >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,padding='same')(x)
x = MaxPooling2D((2,padding='same')(x)
encoded = MaxPooling2D((2,padding='same')(x)

# 解碼器部分
x = Conv2D(8,padding='same')(encoded)
x = UpSampling2D((2,2))(x)
x = Conv2D(8,padding='same')(x) 
x = UpSampling2D((2,2))(x)
x = Conv2D(16,activation='relu', padding='same')(x)
x = UpSampling2D((2,2))(x)
decoded = Conv2D(1,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'].T
  trX = train_data.reshape((-1,1)).astype(np.float32)
  trY = f['train_labels'][-1].astype(np.float32)
  test_data = f['test'].T
  teX = test_data.reshape((-1,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,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 + 1
  ax = plt.subplot(1,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搬磚系列-單層卷積自編碼器

考試成績出來了,竟然有一門出奇的差,只是有點意外。

覺得應該不錯的,竟然考差了,它估計寫了個隨機數吧。

標頭檔案

from keras.layers import Input,Dense
from keras.models import Model 
from keras.datasets import mnist
import numpy as np 
import matplotlib.pyplot as plt 

匯入資料

(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),-1))
X_test = X_test.reshape((len(X_test),-1))

這裡的X_train和X_test的維度分別為(60000L,784L),(10000L,784L)

這裡進行了歸一化,將所有的數值除上255.

設定編碼的維數與輸入資料的維數

encoding_dim = 32

input_img = Input(shape=(784,))

構建模型

encoded = Dense(encoding_dim,activation='relu')(input_img)
decoded = Dense(784,activation='relu')(encoded)
 
autoencoder = Model(inputs = input_img,outputs=decoded)
encoder = Model(inputs=input_img,outputs=encoded)
 
encoded_input = Input(shape=(encoding_dim,))
decoder_layer = autoencoder.layers[-1]
deconder = Model(inputs=encoded_input,outputs = decoder_layer(encoded_input))

模型編譯

autoencoder.compile(optimizer='adadelta',loss='binary_crossentropy')

模型訓練

autoencoder.fit(X_train,X_train,batch_size=256,validation_data=(X_test,X_test))

預測

encoded_imgs = encoder.predict(X_test)

decoded_imgs = deconder.predict(encoded_imgs)

資料視覺化

n = 10
for i in range(n):
 ax = plt.subplot(2,i+1)
 plt.imshow(X_test[i].reshape(28,28))
 plt.gray()
 ax.get_xaxis().set_visible(False)
 ax.get_yaxis().set_visible(False)
 
 ax = plt.subplot(2,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()

完成程式碼

from keras.layers import Input,Dense
from keras.models import Model 
from keras.datasets import mnist
import numpy as np 
import matplotlib.pyplot as plt 
 
(X_train,-1))
 
encoding_dim = 32
input_img = Input(shape=(784,))
 
encoded = Dense(encoding_dim,outputs = decoder_layer(encoded_input))
 
autoencoder.compile(optimizer='adadelta',loss='binary_crossentropy')
autoencoder.fit(X_train,X_test))
 
encoded_imgs = encoder.predict(X_test)
decoded_imgs = deconder.predict(encoded_imgs)
 
##via
n = 10
for i in range(n):
 ax = plt.subplot(2,28))
 plt.gray()
 ax.get_xaxis().set_visible(False)
 ax.get_yaxis().set_visible(False)
plt.show()

以上這篇keras自動編碼器實現系列之卷積自動編碼器操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。