本文整理汇总了Python中tensorflow.python.framework.graph_util.convert_variables_to_constants方法的典型用法代码示例。如果您正苦于以下问题:Python graph_util.convert_variables_to_constants方法的具体用法?Python graph_util.convert_variables_to_constants怎么用?Python graph_util.convert_variables_to_constants使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tensorflow.python.framework.graph_util
的用法示例。
在下文中一共展示了graph_util.convert_variables_to_constants方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from tensorflow.python.framework import graph_util [as 别名]
# 或者: from tensorflow.python.framework.graph_util import convert_variables_to_constants [as 别名]
def main(_):
# Create the model and load its weights.
sess = tf.InteractiveSession()
create_inference_graph(FLAGS.wanted_words, FLAGS.sample_rate,
FLAGS.clip_duration_ms, FLAGS.clip_stride_ms,
FLAGS.window_size_ms, FLAGS.window_stride_ms,
FLAGS.dct_coefficient_count, FLAGS.model_architecture)
models.load_variables_from_checkpoint(sess, FLAGS.start_checkpoint)
# Turn all the variables into inline constants inside the graph and save it.
frozen_graph_def = graph_util.convert_variables_to_constants(
sess, sess.graph_def, ['labels_softmax'])
tf.train.write_graph(
frozen_graph_def,
os.path.dirname(FLAGS.output_file),
os.path.basename(FLAGS.output_file),
as_text=False)
tf.logging.info('Saved frozen graph to %s', FLAGS.output_file)
示例2: setUp
# 需要导入模块: from tensorflow.python.framework import graph_util [as 别名]
# 或者: from tensorflow.python.framework.graph_util import convert_variables_to_constants [as 别名]
def setUp(self):
self.base_path = os.path.join(test.get_temp_dir(), "no_vars")
if not os.path.exists(self.base_path):
os.mkdir(self.base_path)
# Create a simple graph with a variable, then convert variables to
# constants and export the graph.
with ops.Graph().as_default() as g:
x = array_ops.placeholder(dtypes.float32, name="x")
w = variables.Variable(3.0)
y = math_ops.subtract(w * x, 7.0, name="y") # pylint: disable=unused-variable
ops.add_to_collection("meta", "this is meta")
with self.test_session(graph=g) as session:
variables.global_variables_initializer().run()
new_graph_def = graph_util.convert_variables_to_constants(
session, g.as_graph_def(), ["y"])
filename = os.path.join(self.base_path, constants.META_GRAPH_DEF_FILENAME)
saver.export_meta_graph(
filename, graph_def=new_graph_def, collection_list=["meta"])
示例3: freeze_session
# 需要导入模块: from tensorflow.python.framework import graph_util [as 别名]
# 或者: from tensorflow.python.framework.graph_util import convert_variables_to_constants [as 别名]
def freeze_session(session, keep_var_names=None, output_names=None, clear_devices=True):
graph = session.graph
with graph.as_default():
freeze_var_names = list(
set(v.op.name for v in tf.global_variables()).difference(keep_var_names or []))
output_names = output_names or []
output_names += [v.op.name for v in tf.global_variables()]
# Graph -> GraphDef ProtoBuf
input_graph_def = graph.as_graph_def()
if clear_devices:
for node in input_graph_def.node:
node.device = ""
frozen_graph = convert_variables_to_constants(session, input_graph_def,
output_names, freeze_var_names)
return frozen_graph
示例4: setUp
# 需要导入模块: from tensorflow.python.framework import graph_util [as 别名]
# 或者: from tensorflow.python.framework.graph_util import convert_variables_to_constants [as 别名]
def setUp(self):
self.base_path = os.path.join(tf.test.get_temp_dir(), "no_vars")
if not os.path.exists(self.base_path):
os.mkdir(self.base_path)
# Create a simple graph with a variable, then convert variables to
# constants and export the graph.
with tf.Graph().as_default() as g:
x = tf.placeholder(tf.float32, name="x")
w = tf.Variable(3.0)
y = tf.sub(w * x, 7.0, name="y") # pylint: disable=unused-variable
tf.add_to_collection("meta", "this is meta")
with self.test_session(graph=g) as session:
tf.global_variables_initializer().run()
new_graph_def = graph_util.convert_variables_to_constants(
session, g.as_graph_def(), ["y"])
filename = os.path.join(self.base_path, constants.META_GRAPH_DEF_FILENAME)
tf.train.export_meta_graph(
filename, graph_def=new_graph_def, collection_list=["meta"])
示例5: write_pb
# 需要导入模块: from tensorflow.python.framework import graph_util [as 别名]
# 或者: from tensorflow.python.framework.graph_util import convert_variables_to_constants [as 别名]
def write_pb(checkpoint_path, pb_path, output_nodes):
checkpoint_file = tf.train.latest_checkpoint(checkpoint_path)
sess = tf.Session()
saver = tf.train.import_meta_graph("{}.meta".format(checkpoint_file))
saver.restore(sess, checkpoint_file)
graph = tf.get_default_graph() # 获得默认的图
input_graph_def = graph.as_graph_def() # 返回一个序列化的图代表当前的图
# convert_variables_to_constants 需要指定output_node_names,list(),可以多个
constant_graph = graph_util.convert_variables_to_constants(sess,
input_graph_def,# 等于:sess.graph_def
output_nodes)
# 写入序列化的 PB 文件
with tf.gfile.FastGFile(pb_path, mode='wb') as f:
f.write(constant_graph.SerializeToString())
示例6: export_cnn
# 需要导入模块: from tensorflow.python.framework import graph_util [as 别名]
# 或者: from tensorflow.python.framework.graph_util import convert_variables_to_constants [as 别名]
def export_cnn() -> None:
input = tf.placeholder(tf.float32, shape=(1, 1, 3, 3))
filter = tf.constant(np.ones((3, 3, 1, 1)), dtype=tf.float32)
x = tf.nn.conv2d(input, filter, (1, 1, 1, 1), "SAME", data_format="NCHW")
x = tf.nn.sigmoid(x)
x = tf.nn.relu(x)
pred_node_names = ["output"]
tf.identity(x, name=pred_node_names[0])
with tf.Session() as sess:
constant_graph = graph_util.convert_variables_to_constants(
sess, sess.graph.as_graph_def(), pred_node_names
)
frozen = graph_util.remove_training_nodes(constant_graph)
output = "cnn.pb"
graph_io.write_graph(frozen, ".", output, as_text=False)
示例7: export
# 需要导入模块: from tensorflow.python.framework import graph_util [as 别名]
# 或者: from tensorflow.python.framework.graph_util import convert_variables_to_constants [as 别名]
def export(x: tf.Tensor, filename: str, sess=None):
should_close = False
if sess is None:
should_close = True
sess = tf.Session()
pred_node_names = ["output"]
tf.identity(x, name=pred_node_names[0])
graph = graph_util.convert_variables_to_constants(
sess, sess.graph.as_graph_def(), pred_node_names
)
graph = graph_util.remove_training_nodes(graph)
path = graph_io.write_graph(graph, ".", filename, as_text=False)
if should_close:
sess.close()
return path
示例8: secure_model
# 需要导入模块: from tensorflow.python.framework import graph_util [as 别名]
# 或者: from tensorflow.python.framework.graph_util import convert_variables_to_constants [as 别名]
def secure_model(model, **kwargs):
"""Secure a plaintext model from the current session."""
session = K.get_session()
min_graph = graph_util.convert_variables_to_constants(
session, session.graph_def, [node.op.name for node in model.outputs]
)
graph_fname = "model.pb"
tf.train.write_graph(min_graph, _TMPDIR, graph_fname, as_text=False)
if "batch_size" in kwargs:
batch_size = kwargs.pop("batch_size")
else:
batch_size = 1
graph_def, inputs = load_graph(
os.path.join(_TMPDIR, graph_fname), batch_size=batch_size
)
c = tfe.convert.convert.Converter(tfe.convert.registry(), **kwargs)
y = c.convert(remove_training_nodes(graph_def), "input-provider", inputs)
return PrivateModel(y)
示例9: freeze_graph_def
# 需要导入模块: from tensorflow.python.framework import graph_util [as 别名]
# 或者: from tensorflow.python.framework.graph_util import convert_variables_to_constants [as 别名]
def freeze_graph_def(sess, input_graph_def, output_node_names):
for node in input_graph_def.node:
if node.op == 'RefSwitch':
node.op = 'Switch'
for index in xrange(len(node.input)):
if 'moving_' in node.input[index]:
node.input[index] = node.input[index] + '/read'
elif node.op == 'AssignSub':
node.op = 'Sub'
if 'use_locking' in node.attr: del node.attr['use_locking']
elif node.op == 'AssignAdd':
node.op = 'Add'
if 'use_locking' in node.attr: del node.attr['use_locking']
# Get the list of important nodes
whitelist_names = []
for node in input_graph_def.node:
if (node.name.startswith('MobileFaceNet') or node.name.startswith('embeddings')):
whitelist_names.append(node.name)
# Replace all the variables in the graph with constants of the same values
output_graph_def = graph_util.convert_variables_to_constants(
sess, input_graph_def, output_node_names.split(","),
variable_names_whitelist=whitelist_names)
return output_graph_def
示例10: keras_to_tensorflow
# 需要导入模块: from tensorflow.python.framework import graph_util [as 别名]
# 或者: from tensorflow.python.framework.graph_util import convert_variables_to_constants [as 别名]
def keras_to_tensorflow(keras_model, output_dir, model_name, out_prefix="output_", log_tensorboard=True):
if os.path.exists(output_dir) == False:
os.mkdir(output_dir)
out_nodes = []
for i in range(len(keras_model.outputs)):
out_nodes.append(out_prefix + str(i + 1))
tf.identity(keras_model.output[i], out_prefix + str(i + 1))
sess = K.get_session()
init_graph = sess.graph.as_graph_def()
main_graph = graph_util.convert_variables_to_constants(sess, init_graph, out_nodes)
graph_io.write_graph(main_graph, output_dir, name=model_name, as_text=False)
if log_tensorboard:
import_pb_to_tensorboard.import_to_tensorboard(os.path.join(output_dir, model_name), output_dir)
示例11: main
# 需要导入模块: from tensorflow.python.framework import graph_util [as 别名]
# 或者: from tensorflow.python.framework.graph_util import convert_variables_to_constants [as 别名]
def main(_):
# Create the model and load its weights.
sess = tf.InteractiveSession()
create_inference_graph(FLAGS.wanted_words, FLAGS.sample_rate,
FLAGS.clip_duration_ms, FLAGS.clip_stride_ms,
FLAGS.window_size_ms, FLAGS.window_stride_ms,
FLAGS.dct_coefficient_count, FLAGS.resnet_size,
FLAGS.model_architecture)
models.load_variables_from_checkpoint(sess, FLAGS.start_checkpoint)
# Turn all the variables into inline constants inside the graph and save it.
frozen_graph_def = graph_util.convert_variables_to_constants(
sess, sess.graph_def, ['labels_softmax'])
tf.train.write_graph(
frozen_graph_def,
os.path.dirname(FLAGS.output_file),
os.path.basename(FLAGS.output_file),
as_text=False)
tf.logging.info('Saved frozen graph to %s', FLAGS.output_file)
示例12: frozen_graph_to_pb
# 需要导入模块: from tensorflow.python.framework import graph_util [as 别名]
# 或者: from tensorflow.python.framework.graph_util import convert_variables_to_constants [as 别名]
def frozen_graph_to_pb(outputs, frozen_graph_pb_path, sess, graph=None):
"""Freeze graph to a pb file."""
if not isinstance(outputs, (list)):
raise ValueError("Frozen graph: outputs must be list of output node name")
if graph is None:
graph = tf.get_default_graph()
input_graph_def = graph.as_graph_def()
logging.info("Frozen graph: len of input graph nodes: {}".format(
len(input_graph_def.node)))
# We use a built-in TF helper to export variables to constant
output_graph_def = graph_util.convert_variables_to_constants(
sess,
input_graph_def,
outputs,
)
logging.info("Frozen graph: len of output graph nodes: {}".format(
len(output_graph_def.node))) # pylint: disable=no-member
with tf.gfile.GFile(frozen_graph_pb_path, "wb") as in_f:
in_f.write(output_graph_def.SerializeToString())
示例13: save_mode_pb
# 需要导入模块: from tensorflow.python.framework import graph_util [as 别名]
# 或者: from tensorflow.python.framework.graph_util import convert_variables_to_constants [as 别名]
def save_mode_pb(pb_file_path):
x = tf.placeholder(tf.int32, name='x')
y = tf.placeholder(tf.int32, name='y')
b = tf.Variable(2, name='b')
xy = tf.multiply(x, y)
# 这里的输出需要加上name属性
op = tf.add(xy, b, name='op_to_store')
sess = tf.Session()
sess.run(tf.global_variables_initializer())
path = os.path.dirname(os.path.abspath(pb_file_path))
if os.path.isdir(path) is False:
os.makedirs(path)
# convert_variables_to_constants 需要指定output_node_names,list(),可以多个
constant_graph = graph_util.convert_variables_to_constants(sess, sess.graph_def, ['op_to_store'])
with tf.gfile.FastGFile(pb_file_path, mode='wb') as f:
f.write(constant_graph.SerializeToString())
# test
feed_dict = {x: 2, y: 4}
print(sess.run(op, feed_dict))
示例14: convertMetaModelToPbModel
# 需要导入模块: from tensorflow.python.framework import graph_util [as 别名]
# 或者: from tensorflow.python.framework.graph_util import convert_variables_to_constants [as 别名]
def convertMetaModelToPbModel(meta_model, pb_model):
# Step 1
# import the model metagraph
saver = tf.train.import_meta_graph(meta_model + '.meta', clear_devices=True)
# make that as the default graph
graph = tf.get_default_graph()
sess = tf.Session()
# now restore the variables
saver.restore(sess, meta_model)
# Step 2
# Find the output name
for op in graph.get_operations():
print(op.name)
# Step 3
output_graph_def = graph_util.convert_variables_to_constants(
sess, # The session
sess.graph_def, # input_graph_def is useful for retrieving the nodes
["Placeholder", "output/Sigmoid"])
# Step 4
# output folder
output_fld = './'
# output pb file name
output_model_file = 'model.pb'
# write the graph
graph_io.write_graph(output_graph_def, pb_model + output_fld, output_model_file, as_text=False)
示例15: freeze_graph_def
# 需要导入模块: from tensorflow.python.framework import graph_util [as 别名]
# 或者: from tensorflow.python.framework.graph_util import convert_variables_to_constants [as 别名]
def freeze_graph_def(sess, input_graph_def, output_node_names):
for node in input_graph_def.node:
if node.op == 'RefSwitch':
node.op = 'Switch'
for index in xrange(len(node.input)):
if 'moving_' in node.input[index]:
node.input[index] = node.input[index] + '/read'
elif node.op == 'AssignSub':
node.op = 'Sub'
if 'use_locking' in node.attr: del node.attr['use_locking']
elif node.op == 'AssignAdd':
node.op = 'Add'
if 'use_locking' in node.attr: del node.attr['use_locking']
# Get the list of important nodes
whitelist_names = []
for node in input_graph_def.node:
if (node.name.startswith('InceptionResnet') or node.name.startswith('embeddings') or
node.name.startswith('image_batch') or node.name.startswith('label_batch') or
node.name.startswith('phase_train') or node.name.startswith('Logits')):
whitelist_names.append(node.name)
# Replace all the variables in the graph with constants of the same values
output_graph_def = graph_util.convert_variables_to_constants(
sess, input_graph_def, output_node_names.split(","),
variable_names_whitelist=whitelist_names)
return output_graph_def