通过建立一个两层降维的自编码网络,将MNIST数据集的数据特征提取出来,并通过这些特征再重建一个MNIST数据集。
1,引入头文件,并加载mnist数据
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
#导入mnist数据集
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/data/", one_hot = True)
2.定义网络结构
learning_rate = 0.01
n_hidden_1 = 256
n_hidden_2 = 128
n_input = 784
#占位符
x = tf.placeholder("float",[None, n_input]) #输入
y = x #输出
#学习参数
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.zeros([n_hidden_1])),
'encoder_b2': tf.Variable(tf.zeros([n_hidden_2])),
'decoder_b1': tf.Variable(tf.zeros([n_hidden_1])),
'decoder_b2': tf.Variable(tf.zeros([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_out = encoder(x)
pred = decoder(encoder_out)
#cost为y与perd的平方差
cost = tf.reduce_mean(tf.pow(y - pred, 2))
optimizer = tf.train.RMSPropOptimizer(learning_rate).minimize(cost)
上面代码里预先定义了学习率为0.01,这个值可以动态调节,会直接影响到收敛速度和学习的准确性,由于输入标签也是输出标签,所以后面直接定义y=x。
3.开始训练
接下来设置训练参数,一次取256条数据,将所有的训练数据进行20次的迭代训练。
#训练参数
training_epochs = 20
batch_size = 256
display_step = 5
#启动会话
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 = {x: batch_xs})
#x训练模型
if epoch % display_step == 0:
print("Epoch:", '%04d' %(epoch+1), "cost = ", "{:.9f}".format(c))
print("Finished")
4.测试模型
接下来通过mnist数据集里面的test集来测试一下模型的准确度。
correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y,1))
#计算错误率
accuracy = tf.reduce_mean(tf.cast(correct_prediction,"float"))
print("Accuracy:", 1-accuracy.eval({x: mnist.test.images, y:mnist.test.images}))
执行代码,输出如下信息:
Epoch: 0001 cost = 0.200834006
Epoch: 0006 cost = 0.139468685
Epoch: 0011 cost = 0.123636886
Epoch: 0016 cost = 0.113419883
Finished
Accuracy: 1.0
Process finished with exit code 0
前面打印的是每次的错误率,最终输出的Accuracy是整个模型的准确率。
5.双比输入和输出
随意取出10张照片,对比一下输入与输出,可以看到自编码网络还原的图片与真实图片几乎一样。
#可视化结果
show_num = 10
reconstruction = sess.run(pred, feed_dict = {x: mnist.test.images[: show_num]})
f, a = plt.subplots(2, 10, figsize = (10, 2))
for i in range(show_num):
a[0][i].imshow(np.reshape(mnist.test.images[i], (28, 28)))
a[1][i].imshow(np.reshape(reconstruction[i], (28, 28)))
plt.draw()
plt.show()
执行以上代码,会生成下图所示图片,图片分为上下两行,第一行为输入图片,第二行为输出图片。