【问题标题】:Find all variables that a tensorflow op depends upon查找张量流操作所依赖的所有变量
【发布时间】:2017-12-15 23:41:52
【问题描述】:

有没有办法找到给定操作(通常是损失)所依赖的所有变量? 我想使用它然后使用各种set().intersection() 组合将此集合传递给optimizer.minimize()tf.gradients()

到目前为止,我已经找到 op.op.inputs 并尝试了一个简单的 BFS,但我从来没有机会遇到 tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)slim.get_variables() 返回的 Variable 对象

在对应的“Tensor.op._idandVariables.op._id”字段之间似乎确实存在对应关系,但我不确定这是我应该依赖的东西。

或者我一开始就不应该这样做? 我当然可以在构建图表时精心构建不相交的变量集,但是如果我更改模型,很容易遗漏一些东西。

【问题讨论】:

标签: tensorflow


【解决方案1】:

documentation for tf.Variable.op 不是特别清楚,但它确实引用了the implementation of a tf.Variable 中使用的关键tf.Operation:任何依赖于tf.Variable 的操作都将在该操作的路径上。由于tf.Operation对象是可哈希的,你可以将它作为dict的key,将tf.Operation对象映射到对应的tf.Variable对象,然后像以前一样执行BFS:

op_to_var = {var.op: var for var in tf.trainable_variables()}

starting_op = ...
dependent_vars = []

queue = collections.deque()
queue.append(starting_op)

visited = set([starting_op])

while queue:
  op = queue.popleft()
  try:
    dependent_vars.append(op_to_var[op])
  except KeyError:
    # `op` is not a variable, so search its inputs (if any). 
    for op_input in op.inputs:
      if op_input.op not in visited:
        queue.append(op_input.op)
        visited.add(op_input.op)

【讨论】:

  • 这种无限循环可能存在问题...我试过了,它挂了。我添加了一个set 来跟踪哪些Ops 已经在queue 中,它立即返回
  • 你说的很对!如果图形包含循环,则原始代码将失败。我已将其更新为使用 visited 集。
猜你喜欢
  • 2019-01-06
  • 1970-01-01
  • 2018-01-24
  • 2017-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-09
相关资源
最近更新 更多