Skip to main content
 首页 » 编程设计

python之TensorFlow:如果我在图形中处理二次计算,是否会消耗更多内存

2025年02月15日27JustinYoung

如果我有一个来自 Google 的经过训练的 Imagnet 模型 (inception-resnet-v2),并且该模型实际上返回了两个输出:logits,以及一个名为 end_points 的列表,我可以在其中提取最终结果已使用 softmax 激活执行的预测层,即称为 predictions 的变量。但是,这并不能明确地给我预测所需的类标签。为此,我要么必须执行 label = tf.argmax(predictions, 1) 在我在图中定义了 train_op,这样我就不会影响原始计算。

或者,我可以使用从图中计算出的 np.argmax(sess.run(predictions), 1)。

我的问题是,如果我选择第一种方法,它会消耗更多内存并影响我的计算(就我可以使用的 batch_size 而言)吗?仅从图中计算必要的标签是否更安全、更好?

请您参考如下方法:

当您发出多个 .run 时调用,图形定义被缓存。如果您修改 Graph,则需要重新编码并再次发送。所以 graph_def.SerializeToString 可能使用了一些额外的内存第一次运行修改后的图形,但它不应该影响 .run之后的步骤。

相关逻辑在session.py , 请注意检查 self._graph.version > self._current_version 的行

 def _extend_graph(self): 
    # Ensure any changes to the graph are reflected in the runtime. 
    with self._extend_lock: 
      if self._graph.version > self._current_version: 
        # pylint: disable=protected-access 
        graph_def, self._current_version = self._graph._as_graph_def( 
            from_version=self._current_version, 
            add_shapes=self._add_shapes) 
        # pylint: enable=protected-access 
 
        with errors.raise_exception_on_not_ok_status() as status: 
          tf_session.TF_ExtendGraph( 
              self._session, graph_def.SerializeToString(), status) 
        self._opened = True