mnist_autoencoders

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

from tensorflow.examples.tutorials.mnist import input_data

data_dir="mnist"
mnist = input_data.read_data_sets(data_dir, one_hot=True)

#hyper parameters
learning_rate = 0.01
training_epochs = 20
batch_size = 256
display_step = 1


example_to_show = 10


#network parameters
n_hidden_1 = 256
n_hidden_2 = 128
n_input = 784

#pictures without labels
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])),
}


#network structure
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

#model
encoder_op = encoder(X)
decoder_op = decoder(encoder_op)

#predict value
y_pred = decoder_op
#real value
y_true = X

#loss function and optimizer
cost = tf.reduce_mean(tf.pow(y_true - y_pred, 2))
optimizer = tf.train.RMSPropOptimizer(learning_rate).minimize(cost)


with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    total_batch = int(mnist.train.num_examples/batch_size)

    #train
    for epoch in range(training_epochs):
        for i in range(total_batch):
            batch_xs, batch_ys = mnist.train.next_batch(batch_size)

            #Run optimization op(backprop) and cost op(to get loss value)
            _, 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!"

    #test
    encode_decode =  sess.run(y_pred, feed_dict={X: mnist.test.images[:example_to_show]})

    #compare
    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))) #test
        a[1][i].imshow(np.reshape(encode_decode[i], (28, 28))) #rebuild
    f.show()
    plt.draw()
    plt.waitforbuttonpress()


Epoch: 0001 cost= 0.206697449
Epoch: 0002 cost= 0.167194173
Epoch: 0003 cost= 0.155053407
Epoch: 0004 cost= 0.145704255
Epoch: 0005 cost= 0.138243914
Epoch: 0006 cost= 0.131088555
Epoch: 0007 cost= 0.130842805
Epoch: 0008 cost= 0.122627765
Epoch: 0009 cost= 0.117633395
Epoch: 0010 cost= 0.115562417
Epoch: 0011 cost= 0.114408173
Epoch: 0012 cost= 0.112058252
Epoch: 0013 cost= 0.110839143
Epoch: 0014 cost= 0.106782250
Epoch: 0015 cost= 0.107503951
Epoch: 0016 cost= 0.106354013
Epoch: 0017 cost= 0.104745574
Epoch: 0018 cost= 0.103913017
Epoch: 0019 cost= 0.100802712
Epoch: 0020 cost= 0.101700686

Optimization Finished!


mnist_autoencoders_第1张图片


你可能感兴趣的:(TFBoy)