您的位置:首页 > 其它

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()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: