gpt4 book ai didi

tensorflow - 将常量永久注入(inject)到 Tensorflow 图中进行推理

转载 作者:行者123 更新时间:2023-12-03 17:47:14 32 4
gpt4 key购买 nike

我用 is_training 的占位符训练模型:

is_training_ph = tf.placeholder(tf.bool)

但是,一旦完成训练和验证,我想永久注入(inject) false 的常量输入该值,然后“重新优化”图形(即使用 optimize_for_inference )。是否有类似 freeze_graph 的内容?那会这样做吗?

最佳答案

一种可能性是使用 tf.import_graph_def() 函数及其input_map参数来重写图中该张量的值。例如,您可以按如下方式构建程序:

with tf.Graph().as_default() as training_graph:
# Build model.
is_training_ph = tf.placeholder(tf.bool, name="is_training")
# ...
training_graph_def = training_graph.as_graph_def()

with tf.Graph().as_default() as temp_graph:
tf.import_graph_def(training_graph_def,
input_map={is_training_ph.name: tf.constant(False)})
temp_graph_def = temp_graph.as_graph_def()

建好后 temp_graph_def ,您可以将其用作 freeze_graph 的输入.

一种替代方案,它可能与 freeze_graph 更兼容和 optimize_for_inference脚本(对变量名和检查点键进行假设)将修改 TensorFlow 的 graph_util.convert_variables_to_constants()函数,以便它转换占位符:
def convert_placeholders_to_constants(input_graph_def,
placeholder_to_value_map):
"""Replaces placeholders in the given tf.GraphDef with constant values.

Args:
input_graph_def: GraphDef object holding the network.
placeholder_to_value_map: A map from the names of placeholder tensors in
`input_graph_def` to constant values.

Returns:
GraphDef containing a simplified version of the original.
"""

output_graph_def = tf.GraphDef()

for node in input_graph_def.node:
output_node = tf.NodeDef()
if node.op == "Placeholder" and node.name in placeholder_to_value_map:
output_node.op = "Const"
output_node.name = node.name
dtype = node.attr["dtype"].type
data = np.asarray(placeholder_to_value_map[node.name],
dtype=tf.as_dtype(dtype).as_numpy_dtype)
output_node.attr["dtype"].type = dtype
output_node.attr["value"].CopyFrom(tf.AttrValue(
tensor=tf.contrib.util.make_tensor_proto(data,
dtype=dtype,
shape=data.shape)))
else:
output_node.CopyFrom(node)

output_graph_def.node.extend([output_node])

return output_graph_def

...然后你可以建立 training_graph_def如上,并写:
temp_graph_def = convert_placeholders_to_constants(training_graph_def,
{is_training_ph.op.name: False})

关于tensorflow - 将常量永久注入(inject)到 Tensorflow 图中进行推理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40852729/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com