2017-09-23 85 views
0

我是张量流的新手。我有一个张量score,我试图创建一个形状为score.shape[0]的张量变量。创建一个具有动态形状的张量变量

score = tf.constant(np.array([[10, 0, -5], [4, 3, 0], [-3, 0, 11]]), 
dtype=tf.float32) 
v = tf.Variable(tf.zeros(tf.shape(score)[0])) 

但我得到的错误:ValueError: Shape must be rank 1 but is rank 0 for 'zeros_2' (op: 'Fill') with input shapes: [], [].。想知道我哪里出错了。

回答

0

你可以使用score.shape[0]得到score张量的第一维:

sess = tf.InteractiveSession() 
score = tf.constant(np.array([[10, 0, -5], [4, 3, 0], [-3, 0, 11]]),dtype=tf.float32) 
v = tf.Variable(tf.zeros(score.shape[0])) 

tf.global_variables_initializer().run() 
v.eval() 
# array([ 0., 0., 0.], dtype=float32) 

tf.shape返回一个需要评估的张量,然后才能使用它:

sess = tf.InteractiveSession() 
score = tf.constant(np.array([[10, 0, -5], [4, 3, 0], [-3, 0, 11]]),dtype=tf.float32) 

v = tf.Variable(tf.zeros(tf.shape(score).eval()[0])) 

tf.global_variables_initializer().run() 
v.eval() 
# array([ 0., 0., 0.], dtype=float32)