如何列出节点所依赖的所有Tensorflow变量

如何列出节点所依赖的所有Tensorflow变量

如何列出节点所依赖的所有TensorFlow变量/常量/占位符?
例1(添加常数):

import tensorflow as tf

a = tf.constant(1, name = 'a')
b = tf.constant(3, name = 'b')
c = tf.constant(9, name = 'c')
d = tf.add(a, b, name='d')
e = tf.add(d, c, name='e')

sess = tf.Session()
print(sess.run([d, e]))

我想要一个函数,例如:
list_dependencies()返回list_dependencies(d)
['a', 'b']返回list_dependencies(e)
示例2(占位符和权重矩阵之间的矩阵乘法,然后加上偏差向量):
tf.set_random_seed(1)
input_size  = 5
output_size = 3
input       = tf.placeholder(tf.float32, shape=[1, input_size], name='input')
W           = tf.get_variable(
                "W",
                shape=[input_size, output_size],
                initializer=tf.contrib.layers.xavier_initializer())
b           = tf.get_variable(
                "b",
                shape=[output_size],
                initializer=tf.constant_initializer(2))
output      = tf.matmul(input, W, name="output")
output_bias = tf.nn.xw_plus_b(input, W, b, name="output_bias")

sess = tf.Session()
sess.run(tf.global_variables_initializer())
print(sess.run([output,output_bias], feed_dict={input: [[2]*input_size]}))

我想要一个函数,例如:
['a', 'b', 'c']返回list_dependencies()
list_dependencies(output)返回['W', 'input']

最佳答案

以下是我用于此的实用程序(来自https://github.com/yaroslavvb/stuff/blob/master/linearize/linearize.py

# computation flows from parents to children

def parents(op):
  return set(input.op for input in op.inputs)

def children(op):
  return set(op for out in op.outputs for op in out.consumers())

def get_graph():
  """Creates dictionary {node: {child1, child2, ..},..} for current
  TensorFlow graph. Result is compatible with networkx/toposort"""

  ops = tf.get_default_graph().get_operations()
  return {op: children(op) for op in ops}


def print_tf_graph(graph):
  """Prints tensorflow graph in dictionary form."""
  for node in graph:
    for child in graph[node]:
      print("%s -> %s" % (node.name, child.name))

这些功能在操作系统上工作。要获得产生张量的op,请使用。要获得由opt产生的张量,请使用

关于python - 如何列出节点所依赖的所有Tensorflow变量?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42257015/

10-08 22:40