在W = tf.Variable(tf.random_uniform(shape, -1.0, 0.0))
中,我为shape
尝试了以下三种数据类型:
shape = tf.constant([1]) # 1
shape = [1] # 2
shape = tf.Variable([1]) # 3
然后我打电话给:
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
print(sess.run(W))
1
和2
都正确输出,类似于[-0.25340891]
。但是,3
给了我
ValueError:initial_value必须具有指定的形状:Tensor(" random_uniform:0",shape =(?,),dtype = float32)
完整的代码示例:
import tensorflow as tf
import numpy as np
# shape = tf.constant([1]) # 1
# shape = [1] # 2
shape = tf.Variable([1]) # 3
W = tf.Variable(tf.random_uniform(shape, -1.0, 0.0))
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
print(sess.run(W))
为什么会这样?
答案 0 :(得分:2)
由于两个原因,您的示例无效:
工作代码:
import tensorflow as tf
import numpy as np
shape = tf.Variable([1])
W = tf.Variable(tf.random_uniform(shape, -1.0, 0.0), validate_shape=False)
sess = tf.Session()
sess.run(shape.initializer)
sess.run(W.initializer)
print(sess.run(W))