TensorFlow實現MNIST的自編碼網路

2021-08-22 10:14:04 字數 3104 閱讀 5773

本篇部落格將介紹基於無監督學習的乙個簡單應用———自編碼器(autoencoder),並學習tensorflow搭建乙個自編碼網路,並用它在mnist資料集上訓練。

自編碼網路的作用是將輸入樣本壓縮到隱藏層,然後解壓,在輸出端重建樣本。最終輸出層神經元數量等於輸入層神經元的數量。這裡面主要有兩個過程:壓縮和解壓。壓縮依靠的是輸入資料(影象、文字、聲音)本身存在不同程度的冗餘資訊,自動編碼網路通過學習去掉這些冗餘資訊,把有用的特徵輸入到隱藏層中。

壓縮過程一方面要限制隱藏神經元的數量,來學習到一些有意義的特徵,另一方面還希望神經元大部分時間是被抑制的,當神經元的輸出接近於1的時候是被啟用,接近於0的時候認為是被抑制的。希望部分神經元處於被抑制的狀態,這種規則稱為稀疏性限制

多個隱藏層的主要作用是,如果輸入的資料是影象,第一層會學習如何識別邊,第二層會學習如何去組合邊,從而構建輪廓、角等。更高層會學習如何去組合更有意義的特徵,例如,如果輸入的是人臉的話,更高層會學習如何識別和組合眼睛、鼻子、嘴巴等人臉器官。

tensorflow的自編碼網路實現

(1)載入資料和設定超引數

import tensorflow as tf

import numpy as np

import matplotlib.pyplot as plt

from tensorflow.examples.tutorials.mnist import input_data

mnist=input_data.read_data_sets('mnist_data',one_hot=true)

learning_rate=0.01

training_epochs=20

batch_size=256

display_step=1

example_to_show=10

(2)構建網路

#網路引數

n_hidden_1=256

n_hidden_2=128

n_input=784

#輸入佔位符

x=tf.placeholder('float',[none,n_input])

#定義權重和偏置

weights=

biases=

#定義壓縮函式

def encoder(x):

layer_1=tf.nn.sigmoid(tf.add(tf.matmul(x,weights['encoder_h1']),biases['encoder_b1']))

layer_2=tf.nn.sigmoid(tf.add(tf.matmul(layer_1,weights['encoder_h2']),biases['encoder_b2']))

return(layer_2)

#定**壓函式

def decoder(x):

layer_1=tf.nn.sigmoid(tf.add(tf.matmul(x,weights['decoder_h1']),biases['decoder_b1']))

layer_2=tf.nn.sigmoid(tf.add(tf.matmul(layer_1,weights['decoder_h2']),biases['decoder_b2']))

return(layer_2)

(3)構建模型並定義損失和優化器

#構建模型

encoder_op=encoder(x)

decoder_op=decoder(encoder_op)

#**值

y_pred=decoder_op

#真值y_ture=x

#定義損失和優化器

cost=tf.reduce_mean(tf.pow(y_ture-y_pred,2))

optimizer=tf.train.rmspropoptimizer(learning_rate).minimize(cost)

(4)訓練資料及評估模型

with tf.session() as sess:

sess.run(tf.global_variables_initializer())

total_batch=int(mnist.train.num_examples/batch_size)

#開始訓練

for epoch in range(training_epochs):

for i in range(total_batch):

batch_xs,batch_ys=mnist.train.next_batch(batch_size)

_,c=sess.run([optimizer,cost],feed_dict=)

#每一輪列印一次損失

if epoch % display_step==0:

print('epoch:', '%04d ' %(epoch+1),'cost=',''.format(c))

print('optimization finished!')

#對測試集中影象使用訓練好的自編碼網路

encode_decode=sess.run(y_pred,feed_dict=)

#比較測試集原始影象和自編碼的重建影象

f,a=plt.subplots(2,10,figsize=(10,2))

for i in range(example_to_show):

a[0][i].imshow(np.reshape(mnist.test.images[i],(28,28)))

a[1][i].imshow(np.reshape(encode_decode[i],(28,28)))

f.show()

plt.draw()

plt.waitforbuttonpress()

輸出每一輪的損失結果如下:

測試集的和進過自編碼重建特徵後的影象對比如下

tensorflow教程學習三深入MNIST

載入資料 from tensorflow.examples.tutorials.mnist import input data mnist input data.read data sets mnist data one hot true 我們使用interactivesession類可以更加靈活地...

Python keras神經網路識別mnist

上次用matlab寫過乙個識別mnist的神經網路,位址在 這次又用keras做了乙個差不多的,畢竟,現在最流行的專案都是python做的,我也跟一下潮流 資料是從本地解析好的影象和標籤載入的。神經網路有兩個隱含層,都有512個節點。import numpy as np from keras.pre...

Python keras神經網路識別mnist

上次用matlab寫過乙個識別mnist的神經網路,位址在 這次又用keras做了乙個差不多的,畢竟,現在最流行的專案都是python做的,我也跟一下潮流 資料是從本地解析好的影象和標籤載入的。神經網路有兩個隱含層,都有512個節點。import numpy as np from keras.pre...