# -*- 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
# 加载数据
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 # 学习率
training_epochs = 20 # 训练的轮数
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])),
}
# 定义压缩函数
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
# 构建模型
encoder_op = encoder(X)
decoder_op = decoder(encoder_op)
# 得出预测值
y_pred = decoder_op
# 得出真实值,即输入值
y_true = X
# 定义损失函数和优化器
cost = tf.reduce_mean(tf.pow(y_true - y_pred, 2))
optimizer = tf.train.RMSPropOptimizer(learning_rate).minimize(cost)
init = tf.global_variables_initializer()
# 训练数据及评估模型
with tf.Session() as sess:
sess.run(init)
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={X:batch_xs})
if epoch % display_step == 0:
print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(c))
print("Optimization Finished!")
# 对测试集应用训练好的自动编码网络
encode_decode = sess.run(y_pred, feed_dict={X: mnist.test.images[:examples_to_show]})
# 比较此时集原始图片和自动编码网络的重建结果
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))) # 重建结果
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!