Tensorflow实例:mnist最佳实践
2017-10-11 21:50
357 查看
Tensorflow最佳实践mnist程序
在Tensorflow实例:mnist中已经给出了一个完整的Tensorflow程序来解决MNIST问题。然而这个程序的可扩展性并不好。存在的问题如下:计算前向传播的函数需要将所有变量都传入,当神经网络的结果变得更加复杂、参数更多时,程序可读性会变得非常差。大量冗余代码,降低编程的效率。变量管理给出了解决方法。
当程序退出时,训练好的模型也就无法被使用了,这导致模型无法被重用。
在训练的过程中需要每隔一段时间保存一次模型训练的中间结果。
最佳实践
将训练和测试分成两个独立的程序,这可以使得每一个组件更加灵活。比如训练神经网络的程序可以持续输出训练好的模型,而测试程序可以每隔一段时间检验最新模型的正确率。将前向传播的过程抽象成一个单独的库函数。因为神经网络的前向传播过程在训练和测试的过程中都会用到,所以通过库函数的方式使用起来更加方便,而且保证训练和测试过程中使用的前向传播方法一定是一致的。
代码
重构之后的代码将会被拆成3个程序,1. mnist_inference.py:定义了前向传播的过程已经神经网络中的参数。
2. mnist_train.py:定义了神经网络的训练过程
3. mnist_eval.py:定义了测试过程
mnist_inference.py
# _*_ coding: utf-8 _*_ import tensorflow as tf # 定义神经网络结构相关的参数 INPUT_NODE = 784 OUTPUT_NODE = 10 LAYER1_NODE = 500 # 通过tf.get_variable函数来获取变量。在训练神经网络时会创建这些变量;在测试时会通过保存的模型加载这些变量的取值。 # 而且更加方便的是,因为可以在变量加载时将滑动平均变量重命名,所以可以直接通过同样的名字在训练时使用变量自身。而在测试时 # 使用变量的滑动平均值。在这个函数中也会将变量的正则化损失加入损失集合 def get_weight_variable(shape, regularizer): weights = tf.get_variable("weights", shape, initializer=tf.truncated_normal_initializer(stddev=0.1)) if regularizer != None: tf.add_to_collection('losses', regularizer(weights)) return weights # 定义神经网络的前向传播过程。 def inference(input_tensor, regularizer): # 声明第一层神经网络的变量并完成前向传播过程 with tf.variable_scope("layer1"): weights = get_weight_variable([INPUT_NODE, LAYER1_NODE], regularizer) biases = tf.get_variable("biases", [LAYER1_NODE], initializer=tf.constant_initializer(0.0)) layer1 = tf.nn.relu(tf.matmul(input_tensor, weights) + biases) # 类似的声明第二层神经网络的变量并完成前向传播过程 with tf.variable_scope("layer2"): weights = get_weight_variable([LAYER1_NODE, OUTPUT_NODE], regularizer) biases = tf.get_variable("biases", [OUTPUT_NODE], initializer=tf.constant_initializer(0.0)) layer2 = tf.matmul(layer1, weights) + biases return layer2
mnist_train.py
# _*_ coding: utf-8 _*_ import os import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data # 加载mnist_inference.py中定义的常量和前向传播的函数 import mnist_inference # 配置神经网络的参数 BATCH_SIZE = 100 LEARNING_RATE_BASE = 0.8 LEARNING_RATE_DECAY = 0.99 REGULARAZTION_RATE = 0.0001 TRAIN_STEPS = 30000 MOVING_AVERAGE_DECAY = 0.99 MODEL_SAVE_PATH = "./model/" MODEL_NAME = "model2.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(REGULARAZTION_RATE) y = mnist_inference.inference(x, regularizer) global_step = tf.Variable(0, trainable=False) variable_average = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY, global_step) variable_average_op = variable_average.apply( tf.trainable_variables()) cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=tf.argmax(y_, 1), logits=y) 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=global_step, decay_steps=mnist.train.num_examples / BATCH_SIZE, decay_rate=LEARNING_RATE_DECAY) train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step) with tf.control_dependencies([train_step, variable_average_op]): train_op = tf.no_op(name='train') saver = tf.train.Saver() with tf.Session() as sess: tf.global_variables_initializer().run() for i in range(TRAIN_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 training steps, loss on training" "batch is %g" % (step, loss_value)) saver.save(sess, os.path.join(MODEL_SAVE_PATH, MODEL_NAME), global_step=global_step) def main(argv=None): mnist = input_data.read_data_sets("E:\科研\TensorFlow教程\MNIST_data", one_hot=True) train(mnist) if __name__ == '__main__': tf.app.run()
mnist_eval.py
# _*_ coding: utf-8 _*_ import time import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data import mnist_inference import mnist_train EVAL_INTERVAL_SECS = 10 def evaluate(mnist): with tf.Graph().as_default() as g: 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') validate_feed = {x: mnist.validation.images, y_: mnist.validation.labels} y = mnist_inference(x, regularizer=None) correct_prediction = tf.equal(tf.argmax(y, 1), tf.matmul(y_, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) variable_averages = tf.train.ExponentialMovingAverage(mnist_train.MOVING_AVERAGE_DECAY) variables_to_restore = variable_averages.variables_to_restore() saver = tf.train.Saver(variables_to_restore) while True: with tf.Session() as sess: ckpt = tf.train.get_checkpoint_state(mnist_train.MODEL_SAVE_PATH) if ckpt and ckpt.model_checkpoint_path: saver.restore(sess, ckpt.model_checkpoint_path) if __name__ == '__main__': global_step = ckpt.model_checkpoint_path\ .split('/')[-1].split('-')[-1] accuracy_score = sess.run(accuracy, feed_dict=validate_feed) print("After %d training steps, " "validation accuracy = %g" % (global_step, accuracy_score)) else: print("No checkpoint file found") return time.sleep(EVAL_INTERVAL_SECS) def main(argv=None): mnist = input_data.read_data_sets("E:\科研\TensorFlow教程\MNIST_data", one_hot=True) evaluate(mnist) if __name__ == '__main__': tf.app.run()
相关文章推荐
- TensorFlow入门之MNIST最佳实践
- 【TensorFlow】神经网络优化MNIST数据最佳实践(十一)
- 【Java高并发最佳实践】线程安全的单实例模式
- Android权限最佳实践和代码实例分析
- DB2 最佳实践: 用于 IBM Smart Analytics System 的 DB2 实例恢复
- 学习笔记TF061:分布式TensorFlow,分布式原理、最佳实践
- TensorFlow下构建高性能神经网络模型的最佳实践
- ADO.NET 的最全实例,Ado.Net最佳使用方法 ADO.NET 的最佳实践技巧
- EffectiveTensorflow:Tensorflow 教程和最佳实践
- TensorFlow搭建神经网络最佳实践样例
- tensorflow学习笔记四:mnist实例--用简单的神经网络来训练和测试
- TensorFlow实战——MNIS 4000 T最佳实践样例程序
- tensorflow - mnist入门实例
- Windows环境下本地数据源Mnist的Tensorflow实例(Python3.6)
- 敏捷测试(三)从一个实例详解敏捷测试的最佳实践
- tensorflow学习笔记五:mnist实例--卷积神经网络(CNN)
- TensorFlow实例(4)--MNIST简介及手写数字分类算法
- 第4.1.1章 WEB系统最佳实践页面实例-bootstrap登录页面
- 【Android开发】BitMap优化最佳实践及官方Demo“图片墙”实例详解