mnist.py - luckystar1992/ERM GitHub Wiki
#--coding:utf-8--
from future import absolute_import from future import division from future import print_function
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('D:\data', one_hot=True)
with tf.name_scope('input'): x = tf.placeholder(tf.float32, [None, 784], name='x-input') y = tf.placeholder(tf.float32, [None, 10], name='y-input')
将图像转换成四阶Tensor
with tf.name_scope('input_reshape'): image_shaped_input = tf.reshape(x, [-1, 28, 28, 1]) tf.summary.image('input',image_shaped_input,10)
with tf.name_scope('softmax_layer'): with tf.name_scope('weights'): weights = tf.Variable(tf.zeros([784, 10])) tf.summary.histogram('weights', weights) with tf.name_scope('bias'): bias = tf.Variable(tf.zeros([10])) tf.summary.histogram('bias', bias) with tf.name_scope('Wx_plus_b'): y_pred = tf.matmul(x, weights) + bias tf.summary.histogram('y_pred', y_pred)
with tf.name_scope('cross_entropy'): diff = tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=y_pred) with tf.name_scope('total'): cross_entropy = tf.reduce_mean(diff) tf.summary.scalar('cros_entropy', cross_entropy)
with tf.name_scope('train'): train_step = tf.train.AdadeltaOptimizer(0.001).minimize(cross_entropy)
with tf.name_scope('accuracy'): with tf.name_scope('correct_prediction'): correct_prediction = tf.equal(tf.arg_max(y, 1), tf.arg_max(y_pred, 1)) with tf.name_scope('accuracy'): accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) tf.summary.scalar('accuracy', accuracy)
merged = tf.summary.merge_all()
def feed_dict(train=True): if train: _x, _y = mnist.train.next_batch(100, fake_data=False) else: _x, _y = mnist.test.images, mnist.test.labels return {x:_x, y:_y} with tf.Session() as session: train_writer = tf.summary.FileWriter('./mnist/train', session.graph) test_writer = tf.summary.FileWriter('./mnist/test') session.run(tf.global_variables_initializer()) for i in range(10000): if i%10 == 0: summary, acc = session.run([merged, accuracy], feed_dict= feed_dict(False)) test_writer.add_summary(summary, i) print("Accuracya at step %s:%s"%(i, acc)) else: if i%100 == 99: run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE) run_metadata = tf.RunMetadata() summary, _ = session.run([merged, train_step], feed_dict=feed_dict(), options = run_options, run_metadata=run_metadata) train_writer.add_run_metadata(run_metadata, 'step%03d'%i) train_writer.add_summary(summary, i) else: summary, _ =session.run([merged, train_step], feed_dict=feed_dict()) train_writer.add_summary(summary, i)
train_writer.close()
test_writer.close()