TensorFlow - 显示会话中的所有变量 [英] TensorFlow - show all variables in session
问题描述
我玩过一点
import tensorflow as tf
x = tf.Variable([1.0, 2.0])
initializer = tf.global_variables_initializer()
session.run(initializer)
x
<tf.Variable 'Variable:0' shape=(2,) dtype=float32_ref>
y = 2 * x
y
<tf.Tensor 'mul:0' shape=(2,) dtype=float32>
z = y + 1
z
<tf.Tensor 'add:0' shape=(2,) dtype=float32>
v = session.run(x)
sess.run(initializer)
v = sess.run(x)
print (v)
[ 1. 2.]
v1 = sess.run(z)
print (v1)
[ 3. 5.]
v = sess.run(x)
我有 3 个变量 x,y,z.是否可以从提示符显示用一个命令定义的所有变量?如果我尝试乔纳斯建议的内容
I have 3 variables x,y,z.Is it possible to show all the variables defined with one command from prompt? If I try what Jonas suggested
new = tf.trainable_variables()
print (new)
[<tf.Variable 'Variable:0' shape=(2,) dtype=float32_ref>]
推荐答案
tf.trainable_variables()
打印出图中所有可训练的变量,在您的情况下,它只是 x.当你在做y = 2 * x
时,这实际上是隐式定义了一个常量值mul/x
,并将原始变量作为Variable/阅读
tf.trainable_variables()
prints out all the trainable variables in your graph, which in your case, is only x. When you're doing y = 2 * x
, this is actually implicitly defining a constant value mul/x
, and taking in the original variable as a Variable/read
如果您运行以下代码:
x = tf.Variable(1)
y = 2 * x
z = y + 1
for v in tf.get_default_graph().as_graph_def().node:
print v.name
您将获得以下输出:
Variable/initial_value
Variable
Variable/Assign
Variable/read
mul/x
mul
add/y
add
这些是图中的所有节点.您可以使用它来过滤掉您需要的所有相关信息.具体到您的情况,我不会调用 y
和 z
变量.
These are all the nodes in your graph. You can use this to filter out all the relevant information that you need. Specific to your case, I wouldn't call y
and z
variables.
请注意,这是从图表而不是会话中获取所有信息.如果您想从特定会话中获取它,则需要获取相关会话并调用 sess.graph
.
Note that this is getting all the information from a graph and not a session. If you'd like to get it from a particular session, you'd need to get the relevant session and call sess.graph
.
最后一点,上面的例子使用了v.name
,但实际上每个图节点都有更多的属性,比如name
、op
>、input
、device
、attr
.有关详细信息,请参阅 API.
As a last note, the above example used v.name
, but each graph node actually has more attributes, such as name
, op
, input
, device
, attr
. Refer to the API for more information.
这篇关于TensorFlow - 显示会话中的所有变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!