TensorFlow(六)——MNIST分类之自动编码器

import input_data
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

mnist = input_data.read_data_sets('data/', one_hot=True)

#设置训练超参
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")
        
    #对测试集应用训练好的自动编码网络
    encoder_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(encoder_decode[i], (28, 28))) #重建结果
    f.show()
    plt.draw()
    plt.waitforbuttonpress()

结果:
 

Epoch: 0001 cost= 0.211196437
Epoch: 0002 cost= 0.176664159
Epoch: 0003 cost= 0.162920892
Epoch: 0004 cost= 0.145818055
Epoch: 0005 cost= 0.137731016
Epoch: 0006 cost= 0.134013832
Epoch: 0007 cost= 0.127988920
Epoch: 0008 cost= 0.127383783
Epoch: 0009 cost= 0.122124001
Epoch: 0010 cost= 0.118835218
Epoch: 0011 cost= 0.117469572
Epoch: 0012 cost= 0.114894263
Epoch: 0013 cost= 0.113978386
Epoch: 0014 cost= 0.114799604
Epoch: 0015 cost= 0.114253260
Epoch: 0016 cost= 0.111093938
Epoch: 0017 cost= 0.109217525
Epoch: 0018 cost= 0.107519224
Epoch: 0019 cost= 0.105565526
Epoch: 0020 cost= 0.104558967
Optimization Finished

猜你喜欢

转载自blog.csdn.net/MRxjh/article/details/82683948