我是tensorflow的新手,并且使用以下脚本获取Tensorflow值错误:
W = tf.Variable(10)
print(W.eval())
我也试过这个:
with Session() as sess:
print(W.eval())
它抛出了单位化值变量的错误。
现在,当我声明W = tf.Variable(10)
时,它是否会用10初始化它?
答案 0 :(得分:4)
来自文档:
启动图表时,必须明确变量 在运行使用其值的Ops之前初始化。您可以 通过运行初始化程序op 来初始化变量,然后恢复 来自保存文件的变量,或者只是运行
assign
Op 为变量赋值。实际上,变量初始化器 op 只是一个assign
Op,用于指定变量的初始值 变量本身。# Launch the graph in a session. with tf.Session() as sess: # Run the variable initializer. sess.run(w.initializer) # ...you now can run ops that use the value of 'w'...
最常见的初始化模式是使用便捷功能
global_variables_initializer()
将Op添加到初始化的图表中 所有的变数。然后在启动图表后运行该操作。# Add an Op to initialize global variables. init_op = tf.global_variables_initializer() # Launch the graph in a session. with tf.Session() as sess: # Run the Op that initializes global variables. sess.run(init_op) # ...you can now run any Op that uses variable values...
因此您需要使用以下内容:
import tensorflow as tf
W = tf.Variable(10)
print('W: {0}'.format(W))
sess = tf.Session()
with sess.as_default():
sess.run(W.initializer)
print(W.eval())
仅供参考In TensorFlow, what is the difference between Session.run() and Tensor.eval()?
答案 1 :(得分:1)
您需要显式运行初始化程序操作
sess.run(tf.variables_initializer(W))
在评估任何依赖于W的节点之前
答案 2 :(得分:0)
另一个例子,
import tensorflow as tf
W = tf.Variable(tf.truncated_normal([700,10]))
sess = tf.Session()
with sess.as_default():
sess.run(W.initializer)
print(W.eval())
结果:
[[-0.3294761 0.6800459 1.33331 ... 1.42762 -1.3164878
1.4831722 ]
[-1.0402402 0.52254885 -1.344712 ... -0.30849338 0.15020785
1.6682776 ]
[-1.1791034 1.4859517 -1.7137778 ... 0.844212 1.5928217
-0.21043983]
...
[ 0.01982834 -1.1290654 0.33557415 ... 0.0510614 -0.6524679
0.16643837]
[-0.09969945 -0.10285325 -1.1134144 ... 1.2253191 0.13343143
-1.7491579 ]
[-1.9345136 0.63447094 1.1200713 ... 0.5357313 1.8579113
0.8549472 ]]