# -*- coding:utf-8 -*-
import sys
import importlib
importlib.reload(sys)
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
# 加載數(shù)據(jù)
mnist = input_data.read_data_sets("./", one_hot=True)
trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels
trX = trX.reshape(-1, 28, 28, 1)? # 28x28x1 input img
teX = teX.reshape(-1, 28, 28, 1)? # 28x28x1 input img
learning_rate = 0.01? # 學(xué)習(xí)率
training_epochs = 20? # 訓(xùn)練的輪數(shù)
batch_size = 256? ?
display_step = 1
examples_to_show = 10
n_hidden_1 = 256
n_hidden_2 = 128
n_input = 784
X = tf.placeholder("float", [None, n_input])
weights = {
'encoder_h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])),
'encoder_h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),
'decoder_h1': tf.Variable(tf.random_normal([n_hidden_2, n_hidden_1])),
'decoder_h2': tf.Variable(tf.random_normal([n_hidden_1, n_input])),
}
biases = {
'encoder_b1': tf.Variable(tf.random_normal([n_hidden_1])),
'encoder_b2': tf.Variable(tf.random_normal([n_hidden_2])),
'decoder_b1': tf.Variable(tf.random_normal([n_hidden_1])),
'decoder_b2': tf.Variable(tf.random_normal([n_input])),
}
# 定義壓縮函數(shù)
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
# 定義解壓函數(shù)
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
# 構(gòu)建模型
encoder_op = encoder(X)
decoder_op = decoder(encoder_op)
# 得出預(yù)測值
y_pred = decoder_op
# 得出真實(shí)值,即輸入值
y_true = X
# 定義損失函數(shù)和優(yōu)化器
cost = tf.reduce_mean(tf.pow(y_true - y_pred, 2))
optimizer = tf.train.RMSPropOptimizer(learning_rate).minimize(cost)
init = tf.global_variables_initializer()
# 訓(xùn)練數(shù)據(jù)及評估模型
with tf.Session() as sess:
sess.run(init)
total_batch = int(mnist.train.num_examples/batch_size)
# 開始訓(xùn)練
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={X:batch_xs})
if epoch % display_step == 0:
print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(c))
print("Optimization Finished!")
# 對測試集應(yīng)用訓(xùn)練好的自動編碼網(wǎng)絡(luò)
encode_decode = sess.run(y_pred, feed_dict={X: mnist.test.images[:examples_to_show]})
# 比較此時集原始圖片和自動編碼網(wǎng)絡(luò)的重建結(jié)果
f, a = plt.subplots(2, 10, figsize=(10, 2))
for i in range(examples_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)))? # 重建結(jié)果
f.show()
plt.draw()
plt.waitforbuttonpress()
Epoch: 0001 cost= 0.227401376
Epoch: 0002 cost= 0.183739647
Epoch: 0003 cost= 0.171582803
Epoch: 0004 cost= 0.154930770
Epoch: 0005 cost= 0.147431135
Epoch: 0006 cost= 0.138016164
Epoch: 0007 cost= 0.129596651
Epoch: 0008 cost= 0.127187163
Epoch: 0009 cost= 0.123952985
Epoch: 0010 cost= 0.120612435
Epoch: 0011 cost= 0.121103674
Epoch: 0012 cost= 0.118714407
Epoch: 0013 cost= 0.115889899
Epoch: 0014 cost= 0.115912378
Epoch: 0015 cost= 0.112418912
Epoch: 0016 cost= 0.110988192
Epoch: 0017 cost= 0.109182008
Epoch: 0018 cost= 0.109269865
Epoch: 0019 cost= 0.109637171
Epoch: 0020 cost= 0.107125379
Optimization Finished!