from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
import tensorflow as tf
learning_rate=0.001
batch_size=100
display_step=1
model_path='E:/learn/pc_code/tensorflow/1.2/model.ckpt'
n_hidden_1 = 256
n_hidden_2 = 256
n_input = 784
n_classes = 10
x=tf.placeholder(tf.float32,[None,n_input])
y=tf.placeholder(tf.float32,[None,n_classes])
def multilayer(x, weights, biases):
layer_1 = tf.nn.relu(tf.matmul(x,weights['h1'])+biases['b1'])
layer_2 = tf.nn.relu(tf.matmul(layer_1,weights['h2'])+biases['b2'])
return tf.matmul(layer_2, weights['out'])+biases['out']
weights = {
'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])),
'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),
'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes]))
}
biases = {
'b1': tf.Variable(tf.random_normal([n_hidden_1])),
'b2': tf.Variable(tf.random_normal([n_hidden_2])),
'out': tf.Variable(tf.random_normal([n_classes]))
}
pre=multilayer(x,weights=weights,biases=biases)
cost=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pre,labels=y))
optimizer=tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
init=tf.global_variables_initializer()
saver=tf.train.Saver()
with tf.Session() as sess:
sess.run(init)
for epoch in range(3):
avg_cost=0.
total_batch=mnist.train.num_examples//batch_size
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,y:batch_ys})
avg_cost += c/total_batch
if epoch % display_step==0:
print('Epoch:',epoch+1,'Loss:',avg_cost)
correct_pre=tf.equal(tf.argmax(y,1),tf.argmax(pre,1))
accuracy = tf.reduce_mean(tf.cast(correct_pre,tf.float32))
print('Test accuracy:',accuracy.eval({x:mnist.test.images,y:mnist.test.labels}))
save_path=saver.save(sess, model_path)
print('Model save in %s files' % save_path)