炼数成金Tensorflow学习笔记之5.1_改变学习率
代码及分析
"""
Created on Wed Mar 25 09:07:14 2020
@author: 寒火qwer
"""
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data",one_hot=True)
batch_size = 100
n_batch = mnist.train.num_examples // batch_size
x = tf.placeholder(tf.float32,[None,784])
y = tf.placeholder(tf.float32,[None,10])
keep_prob=tf.placeholder(tf.float32)
lr = tf.Variable(0.001, dtype=tf.float32)
W1 = tf.Variable(tf.truncated_normal([784,500],stddev=0.1))
b1 = tf.Variable(tf.zeros([500])+0.1)
L1 = tf.nn.tanh(tf.matmul(x,W1)+b1)
L1_drop = tf.nn.dropout(L1,keep_prob)
W2 = tf.Variable(tf.truncated_normal([500,300],stddev=0.1))
b2 = tf.Variable(tf.zeros([300])+0.1)
L2 = tf.nn.tanh(tf.matmul(L1_drop,W2)+b2)
L2_drop = tf.nn.dropout(L2,keep_prob)
W3 = tf.Variable(tf.truncated_normal([300,10],stddev=0.1))
b3 = tf.Variable(tf.zeros([10])+0.1)
p = tf.matmul(L2_drop,W3)+b3
prediction = tf.nn.softmax(p)
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=p))
train_step = tf.train.AdamOptimizer(lr).minimize(loss)
init = tf.global_variables_initializer()
correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
with tf.Session() as sess:
sess.run(init)
for epoch in range(51):
sess.run(tf.assign(lr, 0.001 * (0.95 ** epoch)))
for batch in range(n_batch):
batch_xs,batch_ys = mnist.train.next_batch(batch_size)
sess.run(train_step,feed_dict={x:batch_xs,y:batch_ys,keep_prob:1.0})
learning_rate = sess.run(lr)
acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels,keep_prob:1.0})
print ("Iter " + str(epoch) + ", Testing Accuracy= " + str(acc) + ", Learning Rate= " + str(learning_rate))
'''
Iter 0, Testing Accuracy= 0.9641, Learning Rate= 0.001
Iter 1, Testing Accuracy= 0.9722, Learning Rate= 0.00095
Iter 2, Testing Accuracy= 0.9743, Learning Rate= 0.0009025
Iter 3, Testing Accuracy= 0.9754, Learning Rate= 0.000857375
Iter 4, Testing Accuracy= 0.9766, Learning Rate= 0.000814506
Iter 5, Testing Accuracy= 0.9778, Learning Rate= 0.000773781
Iter 6, Testing Accuracy= 0.9801, Learning Rate= 0.000735092
Iter 7, Testing Accuracy= 0.9811, Learning Rate= 0.000698337
Iter 8, Testing Accuracy= 0.9805, Learning Rate= 0.00066342
Iter 9, Testing Accuracy= 0.9822, Learning Rate= 0.000630249
.....
.....
.....
Iter 46, Testing Accuracy= 0.9834, Learning Rate= 9.44682e-05
Iter 47, Testing Accuracy= 0.9832, Learning Rate= 8.97448e-05
Iter 48, Testing Accuracy= 0.9838, Learning Rate= 8.52576e-05
Iter 49, Testing Accuracy= 0.9832, Learning Rate= 8.09947e-05
Iter 50, Testing Accuracy= 0.9831, Learning Rate= 7.6945e-05
'''