sai*_*hor 11 python session object-detection models tensorflow
Tensorflow API提供了一些预先训练的模型,并允许我们使用任何数据集对它们进行训练.
我想知道如何在一个tensorflow会话中初始化和使用多个图.我想在两个图中导入两个经过训练的模型并将它们用于对象检测,但我在一次会话中尝试运行多个图表时迷失了方向.
是否有任何特定方法可以在一个会话中使用多个图形?
另一个问题是,即使我为2个不同的图创建两个不同的会话并尝试使用它们,我最终会在第一个实例化会话中获得与第二个类似的结果.
gol*_*enk 12
每个人Session只能有一个Graph.话虽这么说,取决于你特别想要做什么,你有几个选择.
第一个选项是创建两个单独的会话并将一个图表加载到每个会话中,如此处的文档中所述.您提到您使用该方法从每个会话中获得了意外类似的结果,但没有更多细节,很难确定具体问题在您的案例中.我怀疑是否在每个会话中加载了相同的图表,或者当您尝试单独运行每个会话时,同一会话正在运行两次,但没有更多细节,这很难说.
第二个选项是将两个图形作为主会话图的子图加载.您可以在图形中创建两个范围,并为要在该范围内加载的每个图形构建图形.然后你可以将它们视为独立的图形,因为它们之间没有连接.在正常运行图形全局函数时,您需要指定这些函数应用于哪个范围.例如,当使用其优化器对其中一个子图执行更新时,您需要使用此答案中显示的内容,仅获取该子图范围的可训练变量.
除非您明确要求两个图形能够在TensorFlow图形中以某种方式进行交互,否则我建议您使用第一种方法,这样您就不需要跳过子图将需要的额外环节(例如需要过滤哪个确定您在任何特定时刻的工作范围,以及两者之间共享图表全局事物的可能性.
小智 5
我面临着同样的挑战,经过几个月的研究,我终于能够解决这个问题。我用tf.graph_util.import_graph_def. 根据文档:
name:(可选。)将添加到 graph_def 中的名称前面的前缀。请注意,这不适用于导入的函数名称。默认为“导入”。
这样通过添加这个前缀,就可以区分不同的会话。
举个例子:
first_graph_def = tf.compat.v1.GraphDef()
second_graph_def = tf.compat.v1.GraphDef()
# Import the TF graph : first
first_file = tf.io.gfile.GFile(first_MODEL_FILENAME, 'rb')
first_graph_def.ParseFromString(first_file.read())
first_graph = tf.import_graph_def(first_graph_def, name='first')
# Import the TF graph : second
second_file = tf.io.gfile.GFile(second_MODEL_FILENAME, 'rb')
second_graph_def.ParseFromString(second_file.read())
second_graph = tf.import_graph_def(second_graph_def, name='second')
# These names are part of the model and cannot be changed.
first_output_layer = 'first/loss:0'
first_input_node = 'first/Placeholder:0'
second_output_layer = 'second/loss:0'
second_input_node = 'second/Placeholder:0'
# initialize probability tensor
first_sess = tf.compat.v1.Session(graph=first_graph)
first_prob_tensor = first_sess.graph.get_tensor_by_name(first_output_layer)
second_sess = tf.compat.v1.Session(graph=second_graph)
second_prob_tensor = second_sess.graph.get_tensor_by_name(second_output_layer)
first_predictions, = first_sess.run(
first_prob_tensor, {first_input_node: [adapted_image]})
first_highest_probability_index = np.argmax(first_predictions)
second_predictions, = second_sess.run(
second_prob_tensor, {second_input_node: [adapted_image]})
second_highest_probability_index = np.argmax(second_predictions)
Run Code Online (Sandbox Code Playgroud)
如您所见,您现在可以在一个张量流会话中初始化和使用多个图。
希望这会有所帮助
| 归档时间: |
|
| 查看次数: |
9580 次 |
| 最近记录: |