环境:Keras 2.2.5,TensorFlow 1.12.0后端
我在终端中键入以下代码,注意到分配的变量名称中的数字一直在增加。由于tf 1.x使用静态图,因此我怀疑在此过程中创建的张量是否存在,直到我使用重置默认图为止K.clear_session()
。我的猜测正确吗?还是垃圾收集器自动破坏了张量?
>>> import keras.backend as K
>>> a = K.constant(1.0)
>>> a = K.constant(2.0)
>>> a
<tf.Tensor 'Const_1:0' shape=() dtype=float32>
>>> b = K.constant(2.2)
>>> b
<tf.Tensor 'Const_2:0' shape=() dtype=float32>
>>> a = K.constant(222.1)
>>> a
<tf.Tensor 'Const_3:0' shape=() dtype=float32>
>>> a = K.constant(222.1)
>>> a
<tf.Tensor 'Const_4:0' shape=() dtype=float32>
您的猜测是正确的;张量是持久的,直到会话被清除。简单的演示:
import tensorflow as tf
import keras.backend as K
a = K.constant(1.0)
print(a) # Tensor("Const:0", shape=(), dtype=float32)
print(a.name) # Const:0
del a
a = K.constant(1.0)
print(a) # Tensor("Const_1:0", shape=(), dtype=float32)
尽管如此del a
,新张量的名称仍会增加:Const_1:0
。但是,如果会话仅通过来简单地“存储”(例如,缓存了)第一次创建的会话K.constant
,那么即使删除了先前的张量,它也会增加名称吗?不,可以验证:
print(tf.get_default_graph().get_tensor_by_name("Const:0"))
# Tensor("Const:0", shape=(), dtype=float32)
它仍然在那里。与常规Python对象不同(在引用计数达到零后将其删除),Tensor对象会保留(该图会设置自己的引用)。要完全删除张量(和所有其他张量),您将需要两个命令:
K.clear_session() # clear Keras graph
tf.compat.v1.reset_default_graph() # clear TF graph
(有时第一个就足够了,但最好同时使用两者)。现在尝试访问张量:
print(tf.get_default_graph().get_tensor_by_name("Const:0"))
# KeyError: "The name 'Const:0' refers to a Tensor which does not exist.
# The operation, 'Const', does not exist in the graph."
创建一个新的:
a = K.constant(1.0)
print(a) # Tensor("Const:0", shape=(), dtype=float32)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句