5.变量管理和模型持久化:基于MINIST数字识别

1.变量管理

1.1Tensorflow通过变量名来创建或者获取一个变量的两种机制:

二者最大的区别是指定变量名称的参数,对于tf.Variable是可选的,而对于tf.get_variable变量名称是必须的。tf.get_variable会根据变量名称去创建和获取变量,如果有同名的参数,就会创建失败,这是为了避免无意识的变量复用造成的错误。变量复用会造成一些难以发现的错误。

v = tf.get_variable("v", shape=[1],
					initializer=tf.constant_initializer(1.0))
v = tf.Variable(tf.constant(1.0, shape=[1]), name="v")

1.2通过tf.variable_scope函数控制tf.get_variable函数的语义

当tf.variable_scope函数使用参数reuse=True生成上下文管理器时,这个上下文管理器内所有的tf.get_variable函数会直接获取已经创建的变量。如果变量不存在,则tf.get_variable函数将报错。
相反,reuse=None或者reuse=False时,tf.get_variable操作将创建新的变量,如果同名变量已经存在,则tf.get_variable报错。

# 在名字为foo的命名空间内创建名字为v的变量
with tf.variable_scope("foo"):
    v = tf.get_variable(
        "v", [1], initializer=tf.constant_initializer(1.0))

with tf.variable_scope("foo", reuse=True):
    v1 = tf.get_variable("v", [1])
    print(v == v1) # 输出为True

当tf.variable_scope函数嵌套时,reuse参数的取值会和外面一层保持一致

with tf.variable_scope("root", reuse=True):
    # 可以通过tf.get_variable_scope函数来获取当前上下文管理器中的reuse
    print(tf.get_variable_scope().reuse) # 输出True
    with tf.variable_scope("foo"):
        print(tf.get_variable_scope().reuse)  # 输出True

tf.variable_scope函数生成的上下文管理器也会创建一个Tensorflow中的命名空间,在命名空间内创建的变量名称都会带上这个命名空间名作为后缀。所以,tf.variable_scope函数除了可以控制tf.get_variable执行的功能,也提供了一个管理变量命名空间的方式。

v1 = tf.get_variable("v", [1])
print(v1.name) # 输出v:0.v为变量的名称,0表示这个变量是生成变量这个运算的第一个结果

with tf.variable_scope("foo"):
    with tf.variable_scope("bar"):
        v2 = tf.get_variable("v", [1])
        print(v2.name) # 输出foo/bar/v:0

# 创建一个名称为空的命名空间
with tf.variable_scope("", reuse=True):
    v3 = tf.get_variable("foo/bar/v", [1]) # 通过变量名获取变量
    print(v3 == v2) # 输出为True
# 改进的前向传播算法,不用将所有变量都传递到不同函数中,提高代码可读性
def inference(input_tensor, reuse=False):
    
    with tf.variable_scope('layer1', reuse=reuse):
        weights = tf.get_variable("weights", [INPUT_NODE, LAYER1_NODE],
                                  initializer=tf.truncated_normal_initializer(stddev=0.1))
    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', reuse=reuse):
        weights = tf.get_variable("weights", [LAYER1_NODE, OUTPUT_NODE],
                                  initializer=tf.truncated_normal_initializer(stddev=0.1))
        biases = tf.get_variable("biases", [OUTPUT_NODE],
                             initializer=tf.constant_initializer(0.0))
        layer2 = tf.matmul(layer1, weights) + biases
    return layer2


x = tf.placeholder(tf.float32, [None, INPUT_NODE], name='x-input')
y = inference(x)

2.模型持久化

  • model.ckpt.meta:保存了计算图的结构
  • model.ckpt: 保存程序中每一个变量的值
  • checkpoint:保存了一个目录下所有的模型文件列表
import tensorflow as tf

v1 = tf.Variable(tf.constant(1.0, shape=[1], name="v1"))
v2 = tf.Variable(tf.constant(1.0, shape=[1], name="v2"))
result = v1 + v2

init_op = tf.global_variables_initializer()
saver = tf.train.Saver()

with tf.Session() as sess:
    sess.run(init_op)
    # 将模型保存到model/model.ckpt文件
    saver.save(sess, "/model/model.ckpt")
import tensorflow as tf

v1 = tf.Variable(tf.constant(1.0, shape=[1], name="v1"))
v2 = tf.Variable(tf.constant(1.0, shape=[1], name="v2"))
result = v1 + v2

init_op = tf.global_variables_initializer()
saver = tf.train.Saver()


with tf.Session() as sess:
    # 加载已经保存的模型,并通过已经保存的模型中变量的值来计算加法
    saver.restore(sess, "/model/model.ckpt")
    print(sess.run(result))
import tensorflow as tf
# 直接加载持久化的图
saver = tf.train.import_meta_graph(
    "/model/model.ckpt/model.ckpt.meta")
with tf.Session() as sess:
    saver.restore(sess, "model/model.ckpt")
    # 通过张量的名称来获取张量
    print(sess.run(tf.get_default_graph().get_tensor_by_name("add:0")))

为了保存和加载部分变量,在声明tf.train.Saver类时可以提供一个列表来指定需要保存或者加载的变量。比如saver = tf.train.Saver([v1])构建类,那么只有变量v1会被加载进来。
除了选取需要要被加载的变量,tf.train.Saver类也支持在保存或者加载时给变量重命名

# 保存滑动平均模型
import tensorflow as tf

v = tf.Variable(0, dtype=tf.float32, name="v")
ema = tf.train.ExponentialMovingAverage(0.99)
maintain_averages_op = ema.apply(tf.global_variables())
# 在声明滑动平均模型之后,Tensorflow会自动生成一个影子变量 v/ExponentialMovinng Average

saver = tf.train.Saver()
with tf.Session() as sess:
    init_op = tf.global_variables_initializer()
    sess.run(init_op)

    sess.run(tf.assign(v, 10))
    sess.run(maintain_averages_op)

    # 保存时,Tensorflow会把v:0和v/ExponentialMovinng Average两个变量都保存下来
    saver.save(sess, "/model/model.ckpt")

通过变量重命名直接读取变量的滑动平均值,读取的v值实际上就是上面代码中变量v的滑动平均值

v = tf.Variable(0, dtype=tf.float32, name="v")
# 通过变量重命名将原来变量v的滑动平均值直接赋值给v 
saver = tf.train.Saver({"v/ExponentialMovingAverage": v})
with tf.Session() as sess:
    saver.restore(sess, "model/model.ckpt")
    print(sess.run(v))

为了方便加载时重命名滑动平均变量,tf.train.ExponentialMovingAverage类提供了variables_to_restore函数生成tf.train.Saver类所需要的变量重命名字典。

import tensorflow as tf 

v = tf.Variable(0, dtype=tf.float32, name="v")
ema = tf.train.ExponentialMovingAverage(0.99)

saver = tf.train.Saver(ema.variables_to_restore())
with tf.Session() as sess:
    saver.restore(sess, "/model/model.ckpt")
    print(sess.run(v))

3.完整的程序

# -*- coding: utf-8 -*-
import tensorflow as tf 

# 定义神经网络结构相关参数
INPUT_NODE = 784 # (28*28)
OUTPUT_NODE = 10 
LAYER1_NODE = 500


def get_weight_variable(shape, regularizer):
    weights = tf.get_variable(
        "weights", shape,
        initializer=tf.truncated_normal_initializer(stddev=0.1))
    if regularizer is not 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
# -*- coding: utf-8 -*-
import os

import tensorflow as tf 
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow.contrib as contrib

# 加载mnist_inference.py中定义的常量和前向传播的函数
import mnist_inference

# 配置神经网络参数
BATCH_SIZE = 100
LEARNING_RATE_BASE = 0.8
LEARNING_RATE_DECAY = 0.99
REGULARAZTION_RATE = 0.0001
TRAINING_STEPS = 30000
MOVING_AVERAGE_DECAY = 0.99

# 模型保存的路径和文件名
MODEL_SAVE_PATH = "/python/bp/model/"
MODEL_NAME = "model.ckpt"


def train(mnist):
    # 定义输出输入palceholder
    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)
    # 直接使用mnist_inference.py中定义的前向传播过程
    y = mnist_inference.inference(x, regularizer)
    global_step = tf.Variable(0, trainable=False)

    # 应用滑动平均模型
    Variable_averages = tf.train.ExponentialMovingAverage(
        MOVING_AVERAGE_DECAY, global_step)
    Variable_averages_op = Variable_averages.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'))
	
	# 学习率衰减
    learing_rate = tf.train.exponential_decay(
        LEARNING_RATE_BASE,
        global_step,
        mnist.train.num_examples / BATCH_SIZE,
        LEARNING_RATE_DECAY)
    train_step = tf.train.ProximalGradientDescentOptimizer(learing_rate)\
                    .minimize(loss, global_step=global_step)
   	# 指定操作执行的依赖关系[详细介绍](https://blog.csdn.net/Miracle_520/article/details/93494228)
    with tf.control_dependencies([train_step, Variable_averages_op]):
        train_op = tf.no_op(name='train')

    # TensorFlow持久化
    saver = tf.train.Saver()
    with tf.Session() as sess:
        tf.initialize_all_variables().run()

        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})

            # 每1000轮保存一次模型
            if i % 1000 == 0:
                # 输出当前的训练情况
                print("After %d training steps(s), 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("/python/bp/data", one_hot=True)
    train(mnist)


if __name__ == '__main__':
    main()
# -*- coding: utf-8 -*-
import time 
import tensorflow as tf 
from tensorflow.examples.tutorials.mnist import input_data

import mnist_inference
import mnist_train

# 每10秒加载一次最新得模型,并在测试数据上测试最新模型得正确率
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}
                        
        # 直接通过调用封装好的函数来计算前向传播得结果,测试不关注正则化损失得值
        # 所以这里用于计算正则化损失得函数被设置为None
        y = mnist_inference.inference(x, None)

        # 使用前向传播得结果计算正确率,如果需要对未知得样例进行分类,那么使用
        # tf.argmax(y,1)就可以得到输入样例得预测类别了
        correct_prediction = tf.equal(tf.argmax(y ,1), tf.argmax(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)

        # 每隔EVAL_INTERVAL_SECS秒调用一次计算正确率得过程以检测训练过程中得正确率变化
        while True:
            with tf.Session() as sess:
                # tf.train.get_checkpoint_state函数会通过checkpoint文件自动
                # 找到目录中最新模型得文件名
                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)
                    # 通过文件名得到模型保存时迭代得轮数
                    global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1]
                    accuracy_score = sess.run(accuracy, feed_dict=validate_feed)
                    print("After %s training step(s), 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("/python/bp/data", one_hot=True)
    evaluate(mnist)


if __name__ == '__main__':
    tf.app.run()
发布了59 篇原创文章 · 获赞 17 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Miracle_520/article/details/93461049
今日推荐