我对TensorFlow还是很陌生,我正在尝试使用变量,但是我没有得到期望的结果
当我在tensorflow中声明一个常量时,我遇到了一个可以正常工作的会话。但是当我尝试对变量执行相同操作时,它不会。
下面您将在命令行中看到简单的实验
>>> import tensorflow as tf
>>> sess = tf.Session()
2019-05-23 10:13:49.540813: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2
>>> a = tf.constant(5.)
>>> print(sess.run(a))
5.0
>>> b = tf.Variable(5.)
WARNING:tensorflow:From C:\Users\gpapari\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\framework\op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.
Instructions for updating:
Colocations handled automatically by placer.
>>> print(b)
<tf.Variable 'Variable:0' shape=() dtype=float32_ref>
>>> print(sess.run(b))
执行最后一行后,我得到了一个非常长的错误。 我收到的错误/警告是什么意思?
答案 0 :(得分:0)
您需要运行一个张量来初始化会话中的所有变量,例如:
# Build graph
b = tf.Variable(5.)
# Get init tensor for all variables defined in the graph
init_op = tf.global_variables_initializer()
sess = tf.Session()
# Initialize all variables for the session
sess.run(init_op)
# Use variables in session
print(sess.run(b))
编辑以添加:当您考虑到变量通常不使用常量进行初始化时,例如:
,这样可能会减少混乱tf.Variable(tf.random_uniform([5], 0, 10))
因此初始化器需要在会话中执行。