在TensorFlow图中删除除了几个节点之外的所有节点

nav*_*ari 10 python deep-learning tensorflow

我的TensorFlow用例要求我为每个需要处理的实例构建一个新的计算图.这最终会炸毁内存需求.

除了一些tf.Variables是模型参数,我想删除所有其他节点.其他有类似问题的人发现 tf.reset_default_graph()它们很有用,但这样可以摆脱我需要坚持的模型参数.

我可以用什么来删除除这些节点之外的所有节点?

编辑:实例特定的计算实际上只是意味着我添加了很多新的操作.我相信这些操作是内存问题背后的原因.

更新: 请参阅最近发布的tensorflow折叠(https://github.com/tensorflow/fold),它允许动态构建计算图.

Mar*_*ind 12

tf.graph数据结构被设计为仅附加数据结构.因此,无法删除或修改现有节点.通常这不是问题,因为在运行会话时只处理必要的子图.

您可以尝试将图形的Variabels复制到新图形中并删除旧图形.要存档这只是运行:

old_graph = tf.get_default_graph() # Save the old graph for later iteration
new_graph = tf.graph() # Create an empty graph
new_graph.set_default() # Makes the new graph default
Run Code Online (Sandbox Code Playgroud)

如果要迭代旧图中的所有节点,请使用:

for node in old_graph.get_operations():
    if node.type == 'Variable':
       # read value of variable and copy it into new Graph
Run Code Online (Sandbox Code Playgroud)

或者你可以使用:

for node in old_graph.get_collection('trainable_variables'):
   # iterates over all trainable Variabels
   # read and create new variable
Run Code Online (Sandbox Code Playgroud)

还要看一下python/framework/ops.py : 1759在图中操作节点的更多方法.

然而,在你搞砸之前,tf.Graph我强烈建议考虑这是否真的需要.通常可以尝试概括计算并使用共享变量构建图形,以便您要处理的每个实例都是此图形的子图.