1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
| import os import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data
import mnist_inference import mnist_eval
BATCH_SIZE = 100
LEARNING_RATE_BASE = 0.8 LEARNING_RATE_DECAY = 0.99
REGULARIZATION_RATE = 0.0001 TRAINING_STEPS = 5000 MOVING_AVERAGE_DECAY = 0.99
MODEL_SAVE_PATH = "/SaveModels/" MODEL_NAME = "mnist_model.ckpt"
def train(mnist): x = tf.placeholder(tf.float32, [None, mnist_inference.INPUT_NODE], name='x-input') y_ = tf.placeholder(tf.float32, [None, mnist_inference.OUTPUT_NODE], name='y-input')
regularizer = tf.contrib.layers.l2_regularizer(REGULARIZATION_RATE) y = mnist_inference.inference(x, regularizer)
global_step = tf.Variable(0, trainable=False)
variable_averages = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY, global_step) variable_avg_op = variable_averages.apply(tf.trainable_variables()) cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=y, labels=tf.argmax(y_, 1), name='loss1') cross_entropy_mean = tf.reduce_mean(cross_entropy)
loss = cross_entropy_mean + tf.add_n(tf.get_collection("losses")) learning_rate = tf.train.exponential_decay(LEARNING_RATE_BASE, global_step, mnist.train.num_examples / BATCH_SIZE, LEARNING_RATE_DECAY) train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step)
train_op = tf.group(train_step, variable_avg_op)
saver = tf.train.Saver() with tf.Session() as sess: sess.run(tf.global_variables_initializer())
for i in range(TRAINING_STEPS): xs, ys = mnist.train.next_batch(BATCH_SIZE) _, loss_value, step = sess.run([train_op, loss, global_step], feed_dict={x: xs, y_: ys})
if i % 1000 == 0: print("After %d trainning steps, loss on trainning batch is %g." % (i, loss_value)) path = os.getcwd() + MODEL_SAVE_PATH + MODEL_NAME saver.save(sess, path, global_step=global_step) print("Save model to ", path)
print("Trainning finished.")
def runTrainning(): path = "./Resources/MINSTData" print("path = ", path)
mnist = input_data.read_data_sets(path, one_hot=True)
print("Training data size: ", mnist.train.num_examples) train(mnist)
def runTesting(): path = "./Resources/MINSTData" print("path = ", path) mnist_test = input_data.read_data_sets(path, one_hot=True) mnist_eval.evaluate(mnist_test) pass
if __name__ == '__main__': while 1: num = input("Please input num: 1-Trainning , 2-Testing, q-quit:\n") if num == 'q': break if num == '1': runTrainning() continue if num == '2': runTesting() continue break
|