Tensorflow freeze_graph无法初始化local_variables

问题描述 投票:1回答:1

使用局部变量冻结图形时,freeze_graph会出现错误,指出“尝试使用未初始化的值...”。有问题的局部变量通过以下方式初始化:

    with tf.variable_scope(tf.get_variable_scope(),reuse=tf.AUTO_REUSE):
        b_init = tf.constant(10.0, shape=[2, 1], dtype="float32",name = 'bi')
        b = tf.get_variable('b',initializer=b_init,collections=[tf.GraphKeys.LOCAL_VARIABLES])

我能够创建一个保存的模型并运行保存的模型。但是,我正在尝试冻结另一个图表以进行优化。如果我删除'LOCAL_VARIABLES'标志,这个错误就会消失。但是,此变量然后变为全局变量,这会导致重新加载检查点的问题(Tensorflow无法在检查点中找到变量)。

通常,我希望freeze_graph使用'b_init'初始化'b'。

重现问题的代码:

import os, sys, json
import tensorflow as tf
from tensorflow.python.lib.io import file_io

from tensorflow.core.framework import variable_pb2
from tensorflow.python.framework import ops
from tensorflow.python.ops import variables
from tensorflow.python.framework.ops import register_proto_function

from tensorflow.python.saved_model import tag_constants
from tensorflow.python.tools import freeze_graph
from tensorflow.python import ops
from tensorflow.tools.graph_transforms import TransformGraph

#flags
tf.app.flags.DEFINE_integer('model_version',1,'Models version number.')
tf.app.flags.DEFINE_string('export_model_dir','../model_batch/versions', 'Directory where model will be exported to')

FLAGS = tf.app.flags.FLAGS

def main(_):
    ''' main function'''
    a = tf.placeholder(dtype = tf.float32, shape = [2,1])

    with tf.variable_scope(tf.get_variable_scope(),reuse=tf.AUTO_REUSE):
        b_init = tf.constant(10.0, shape=[2, 1], dtype="float32",name = 'bi')
        b = tf.get_variable('b',initializer=b_init,collections=[tf.GraphKeys.LOCAL_VARIABLES])

    b = tf.assign(b,a)
    c = []

    for d in range(5):
        b = b * 1.1

    c.append(b)
    c = tf.identity(c,name = 'c')

    init = tf.group(tf.global_variables_initializer(),
                   tf.local_variables_initializer())

    with tf.Session() as sess:

        #init
        sess.run(init)
        print(tf.get_default_graph().get_collection(tf.GraphKeys.LOCAL_VARIABLES))

        #create saved model builder class
        export_path_base = FLAGS.export_model_dir
        export_path = os.path.join(
            tf.compat.as_bytes(export_path_base),
            tf.compat.as_bytes(str(FLAGS.model_version)))

        if tf.gfile.Exists(export_path):
            print ('Removing previous artifacts')
            tf.gfile.DeleteRecursively(export_path)

        #inputs
        tensor_info_a  = tf.saved_model.utils.build_tensor_info(a)

        #outputs
        tensor_info_c = tf.saved_model.utils.build_tensor_info(c)

        print('Exporting trained model to', export_path)
        builder = tf.saved_model.builder.SavedModelBuilder(export_path)

        #define signatures
        prediction_signature = (
            tf.saved_model.signature_def_utils.build_signature_def(
                inputs={'cameras': tensor_info_a},
                outputs = {'depthmap' : tensor_info_c},
                method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME))

        builder.add_meta_graph_and_variables(
            sess, [tf.saved_model.tag_constants.SERVING],
            signature_def_map = {'predict_batch': prediction_signature})

        #export model
        builder.save(as_text=True)

        writer = tf.summary.FileWriter("output_batch", sess.graph)
        writer.close()

    #load graph from saved model
    print ('Freezing graph')
    initializer_nodes = ''
    output_node_names = 'c'
    saved_model_dir = os.path.join(FLAGS.export_model_dir,str(FLAGS.model_version))
    output_graph_filename = os.path.join(saved_model_dir,'frozen_graph.pb')

    freeze_graph.freeze_graph(
        input_saved_model_dir=saved_model_dir,
        output_graph=output_graph_filename,
        saved_model_tags = tag_constants.SERVING,
        output_node_names=output_node_names,
        initializer_nodes=initializer_nodes,
        input_graph=None,
        input_saver=False,
        input_binary=False,
        input_checkpoint=None,
        restore_op_name=None,
        filename_tensor_name=None,
        clear_devices=False)

if __name__ == '__main__':
    tf.app.run()
tensorflow tensorflow-serving
1个回答
0
投票

我无法在冻结图中包含local_variables,但我确实提出了一个解决方法。

最初的问题是我的检查点是从包含local_variables的图形创建的。不幸的是,冻结图表会产生错误:

Attempting to use uninitialized value...

我解决这个问题的方法是将局部变量更改为无法解释的全局变量。然后,我使用以下解决方案过滤掉了不在我的检查点中的全局变量:

https://stackoverflow.com/a/39142780/6693924

我能够创建一个savedModel并冻结它的图形。

© www.soinside.com 2019 - 2024. All rights reserved.