keras自動編碼器實(shí)現(xiàn)系列之卷積自動編碼器操作
圖片的自動編碼很容易就想到用卷積神經(jīng)網(wǎng)絡(luò)做為編碼-解碼器。在實(shí)際的操作中,
也經(jīng)常使用卷積自動編碼器去解決圖像編碼問題,而且非常有效。
下面通過**keras**完成簡單的卷積自動編碼。 編碼器有堆疊的卷積層和池化層(max pooling用于空間降采樣)組成。 對應(yīng)的解碼器由卷積層和上采樣層組成。
@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
## 網(wǎng)絡(luò)結(jié)構(gòu) ##
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)
## 導(dǎo)入數(shù)據(jù), 使用常用的手寫識別數(shù)據(jù)集
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, 28, 28, 1)).astype(np.float32)
trY = f['train_labels'][-1].astype(np.float32)
test_data = f['test'].T
teX = 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的函數(shù), 就直接用那個(gè)了
return trX / 255., trY, teX/255., teY
# 開始導(dǎo)入數(shù)據(jù)
x_train, _ , x_test, _= load_mnist('mnist')
# 可視化訓(xùn)練結(jié)果, 我們打開終端, 使用tensorboard
# tensorboard --logdir=/tmp/autoencoder # 注意這里是打開一個(gè)終端, 在終端里運(yùn)行
# 訓(xùn)練模型, 并且在callbacks中使用tensorBoard實(shí)例, 寫入訓(xùn)練日志 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 + 1
ax = 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()
補(bǔ)充知識:keras搬磚系列-單層卷積自編碼器
考試成績出來了,竟然有一門出奇的差,只是有點(diǎn)意外。
覺得應(yīng)該不錯(cuò)的,竟然考差了,它估計(jì)寫了個(gè)隨機(jī)數(shù)吧。
頭文件
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
導(dǎo)入數(shù)據(jù)
(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)
這里進(jìn)行了歸一化,將所有的數(shù)值除上255.
設(shè)定編碼的維數(shù)與輸入數(shù)據(jù)的維數(shù)
encoding_dim = 32
input_img = Input(shape=(784,))
構(gòu)建模型
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')
模型訓(xùn)練
autoencoder.fit(X_train,X_train,epochs=50,batch_size=256,shuffle=True,validation_data=(X_test,X_test))
預(yù)測
encoded_imgs = encoder.predict(X_test)
decoded_imgs = deconder.predict(encoded_imgs)
數(shù)據(jù)可視化
n = 10 for i in range(n): 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) 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()
完成代碼
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))
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,epochs=50,batch_size=256,shuffle=True,validation_data=(X_test,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,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)
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()
以上這篇keras自動編碼器實(shí)現(xiàn)系列之卷積自動編碼器操作就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
讓Python腳本暫停執(zhí)行的幾種方法(小結(jié))
這篇文章主要介紹了讓Python腳本暫停執(zhí)行的幾種方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07
Python實(shí)現(xiàn)批量壓縮文件/文件夾zipfile的使用
本文主要介紹了Python實(shí)現(xiàn)批量壓縮文件/文件夾zipfile的使用,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-09-09
詳解Django中的ifequal和ifnotequal標(biāo)簽使用
這篇文章主要介紹了詳解Django中的ifequal和ifnotequal標(biāo)簽使用,Django是重多高人氣Python框架中最為著名的一個(gè),需要的朋友可以參考下2015-07-07
Python?SQLAlchemy與數(shù)據(jù)庫交互操作完整指南
SQLAlchemy 是一個(gè)強(qiáng)大的 Python 庫,用于數(shù)據(jù)庫操作,無論是簡單的數(shù)據(jù)存儲還是復(fù)雜的數(shù)據(jù)管理,SQLAlchemy 都提供了多種方法來處理數(shù)據(jù)庫,本文將全面介紹 SQLAlchemy的基本用法以及各種操作的示例代碼2024-01-01
使用Python中的greenlet包實(shí)現(xiàn)并發(fā)編程的入門教程
這篇文章主要介紹了使用Python中的greenlet包實(shí)現(xiàn)并發(fā)編程的入門教程,Python由于GIL的存在并不能實(shí)現(xiàn)真正的多線程并發(fā),greenlet可以做到一個(gè)相對的替換方案,需要的朋友可以參考下2015-04-04
python的paramiko模塊實(shí)現(xiàn)遠(yuǎn)程控制和傳輸示例
本篇文章主要介紹了python的paramiko模塊實(shí)現(xiàn)遠(yuǎn)程控制和傳輸示例,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2017-10-10
詳解python如何在django中為用戶模型添加自定義權(quán)限
這篇文章主要介紹了python如何在django中為用戶模型添加自定義權(quán)限,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-10-10

