Tensorflow中的模型持久化

  众所周知Tensorflow解决问题都是去构建不同类型的神经网络,但是神经网络结构变化万千,当神经网络的结构变得更加复杂、参数更多时,程序的可读性会变得非常差,而且这样也会导致程序的结构中有大量的冗余代码,降低编程效率,那么变量管理也就变大尤为重要,前面已经对如何管理tensorflow的变量进行了介绍tensorflow变量管理

  在我们训练模型的过程中,如果不小心由于某些原因退出,如果没有一个持久的保存模型的方法,那么训练好的模型将无法被使用,有的模型可能需要训练几个小时,甚至几天的时间,那么如果模型没有很好的保存,这样前面训练浪费的时间将复制东流,还要重新来过,tensorflow中自带可以保存模型的方法,但是很多童鞋对这块还不是很熟悉,下面博主就来介绍一下。

   Tensorflow提供了一个非常简单的API来保存和还原一个神经网络模型。这个API就是tf.train.Saver类。以下代码给出了保存Tensorflow计算图的方法。

import tensorflow as tf

# 声明两个变量并计算他们的和
v1 = tf.Variable(tf.constant(1.0, shape=[1], name = "v1")
v2 = tf.Variable(tf.constant(2.0, shape=[1], name = "v2")
result = v1 + v2

init_op = tf.initialize_all_variables()
# 声明tf.train.Saver类用于保存模型
saver = tf.train.Saver()

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

上面的代码,通过saver.save函数将tensorflow模型保存到/path/to/model/model.ckpt文件中。tensorflow模型一般会存在后缀为.ckpt的文件中,虽然,上面的代码中只指定了一个文件路径,但是在这个文件目录下会出现三个文件。这是因为tensorflow会将计算图的结构和图上参数取值分开保存。
   这三个文件分别为:model.ckpt.meta,它保存了Tensorflow计算图的结构,也就是神经网络的结构。model.ckpt,这个文件中保存了Tensorflow程序中每一个变量的取值。check.point,这个文件中保存了一个目录下所有的模型文件列表。
   保存好了模型自然是要拿来用的,下面就介绍如何加载Tensorflow模型的方法:

import tensorflow as tf

# 使用和保存模型代码中一样的方式来声明变量
v1 = tf.Variable(tf.constant(1.0, shape=[1], name = "v1")
v2 = tf.Variable(tf.constant(2.0, shape=[1], name = "v2")
result = v1 + v2

saver = tf.train.Saver()

with tf.Session() as sess:
    # 加载已经保存的模型,并通过已经保存的模型中变量的值来运算
    saver.restore(sess, "/path/to/model/model.ckpt")
    print(sess.run(result

可以看出加载模型的代码和保存模型的代码大致相同,也需要定义Tensorflow计算图中的所有运算,并声明了一个tf.train.Saver( )类。不同的是,在加载模型的代码中并没有运行变量初始化的过程,而是将变量的值通过已经保存的模型加载进来。如果不希望重复定义图上的运算,也可以直接加载已经持久化的模型,下面代码给出一个实例:

import tensorflow as tf
# 直接加载持久化的图
saver = tf.train.import_meta_graph("/path/to/model/model.ckpt/model.cpkt.meta")

with tf.Session() as sess:
    saver.restore(sess, "/path/to/model/model.ckpt")
    # 通过张量的名称来获取张量
    print(sess.run(tf.get_default_graph().get_tensor_by_name("add:0"))
    # 输出[3.]

上面的过程中,默认保存和加载了Tensorflow graph上定义的全部变量。但是有时候可能只需要保存或者加载部分变量。比如,在自编码的过程中,我们训练好网络以后,只需要保存encode的部分,那么在利用自编码做前端的网络就可以直接加载encode的模型,仅仅需要对后面的一层神经网络就行训练就行。

为了保存或加载部分变量,子啊声明 tf.train.Saver 类时可以提供一个列表来指定需要保存或者加载的变量。比如在上面的加载模型的代码中使用saver = tf.train.Saver([v1])命令来构建 tf.train.Saver 类,那么只有变量v1会被加载进来,但是在运行时代码就会得到变量未初始化的错误:

tensorflow.python.framework.errors.FailedPreconditionError: Attempting to use uninitialized value v2

因为v2没有被加载,所以v2在运行初始化之前是没有值的。除了可以选取需要被加载的变量, tf.train.Saver 类也支持在保存或者加载时给变量重命名。下面代码就会告诉我们如何操作:

# 这里声明的变量名称和已保存模型中的变量名称不同
v1 = tf.Variable(tf.constant(1.0, shape=[1], name = "other-v1")
v2 = tf.Variable(tf.constant(2.0, shape=[1], name = "other-v2")

# 如果直接使用 tf.train.Saver() 来加载模型会报便阿玲找不到的错误,下面是报错信息:
tensorflow.python.framework.errors.NotFoundError: Tensor name "other-v2" not found in checkpoint files /path/to/model/model.ckpt

# 使用一个字典来重命名变量就可以加载原来的模型了,这个字典指定了原来名称为v1的变量现在加载到变
#量v1中(名称为other-v1),名称为v2的变量现在加载到变量v1中(名称为other-v2)
saver = tf.train.Saver({"v1": v1, "v2": v2})

这个程序中,对变量v1和v2的名称就行了修改如果直接通过 tf.train.Saver默认的构造函数来加载保存的模型,那么程序就会报变量找不到的错误。因为保存时候变量的名称和加载时变量的名称不一致,为了解决这个问题Tensorflow可以通过字典将模型保存时的变量名和需要加载的变量联系起来。

使用 tf.train.Saver 会保存运行Tensorflow程序所需要的全部信息,然而有时并不需要模型信息,比如在测试或者离线预测时,只需要知道tensorflow如何从神经网络的输入层经过前向传播计算得到输出层即可,而不需要类似变量初始化、模型保存等辅助节点的信息。在迁移学习中也会遇到类似的情况,而且将变量取值和计算图结构分成不同的文件存储有的时候也不方便,于是tensorflow提供了 convert_variables_to_constants 函数,通过这个函数可以将计算图中的变量及其取值通过常量的方式保存,这样整个Tensorflow计算图可以统一存放在一个文件中了。

说了这么多,接下来就拿个例子来实战吧,我们还是拿最经典的MNIST数据集来展示:
我们将代码分成三个部分,第一个是 mnist_inference.py,它定义了钱箱传播的过程以及神经网络中的参数。第二个是mnist_train.py,定义了神经网络的训练过程。第三个是 mnist_eval.py,它定义了测试过程。下面我们注意介绍:

mnist_inference.py代码 文件:

# -*- coding: utf-8 -*-
import tensorflow as tf
# Hyper Parameters
INPUT_NODE = 784
OUTPUT_NODE = 10
LAYER1_NODE = 500

# 这里的regularizer参数用来判断是否使用正则化
def get_weight_variable(shape, regularizer):
    weights = tf.get_variable("weights", shape, initializer=tf.truncated_normal_initializer(stddev=0.1))
    # 给出正则化生成函数时,将当前变量的正则化损失加入名字为losses的集合,在这里使用了 add_to_collection 函数将一个张量加入一个集合,名字为losses.
    if regularizer != None: tf.add_to_collection('losses', regularizer(weights))
    return weights

# build network foward_propagation
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 tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import mnist_inference
import os

# Hyper Parameters
BATCH_SIZE = 100
LEARNING_RATE_BASE = 0.8
LEARNING_RATE_DECAY = 0.99
REGULARIZATION_RATE = 0.0001
TRAINING_STEPS = 30000
MOVING_AVERAGE_DECAY = 0.99
# model saved path and file name
MODEL_SAVE_PATH="MNIST_model/"
MODEL_NAME="mnist_model"


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)
    variables_averages_op = variable_averages.apply(tf.trainable_variables())
    cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=y, labels=tf.argmax(y_, 1))
    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,
        staircase=True)
    train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step)
    with tf.control_dependencies([train_step, variables_averages_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(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 step(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("../../../datasets/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.inference(x, None)
        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)

        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)
                    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("../../../datasets/MNIST_data", one_hot=True)
    evaluate(mnist)

if __name__ == '__main__':
    main()

   运行上面的程序,可以看到如下的结果:
这里写图片描述

下面就去自己的tensorflow中实现吧!!!

猜你喜欢

转载自blog.csdn.net/WIinter_FDd/article/details/72821923