如何列出节点所依赖的所有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]))
Run Code Online (Sandbox Code Playgroud)
我想有一个功能list_dependencies(),如:
list_dependencies(d) 回报 ['a', 'b']list_dependencies(e) 回报 ['a', 'b', 'c']示例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 = …Run Code Online (Sandbox Code Playgroud) 我将探讨如何在图中表示变量.我创建一个变量,初始化它并在每个动作后创建图形快照:
import tensorflow as tf
def dump_graph(g, filename):
with open(filename, 'w') as f:
print(g.as_graph_def(), file=f)
g = tf.get_default_graph()
var = tf.Variable(2)
dump_graph(g, 'data/after_var_creation.graph')
init = tf.global_variables_initializer()
dump_graph(g, 'data/after_initializer_creation.graph')
with tf.Session() as sess:
sess.run(init)
dump_graph(g, 'data/after_initializer_run.graph')
Run Code Online (Sandbox Code Playgroud)
变量创建后的图形看起来像
node {
name: "Variable/initial_value"
op: "Const"
attr {
key: "dtype"
value {
type: DT_INT32
}
}
attr {
key: "value"
value {
tensor {
dtype: DT_INT32
tensor_shape {
}
int_val: 2
}
}
}
}
node {
name: "Variable"
op: "VariableV2"
attr {
key: …Run Code Online (Sandbox Code Playgroud)