使用Tensorflow在运行时拟合张量的索引向量

时间:2017-04-08 10:42:48

标签: python tensorflow deep-learning tensor

我有这个使用 Tensorflow框架的python函数:

def compute_ap(gain_vector):

    #this vector must fit the dimension of the gain_vector
    index_vector = tf.range(1, gain_vector.get_shape()[0],dtype=tf.float32)

    ap = tf.div(tf.reduce_sum(tf.div(tf.cast(gain_vector,tf.float32), index_vector), 1),tf.reduce_sum(tf.cast(gain_vector,tf.float32), 1))
    return ap 

当我运行程序时,我收到此错误:

ValueError: Tensor conversion requested dtype float32 for Tensor with dtype int32: 'Tensor("inputs/strided_slice:0", shape=(), dtype=int32)'

似乎 gain_vector.get_shape()[0] 没有得到增益向量的向量,有什么问题?

1 个答案:

答案 0 :(得分:2)

tf.range()只接受int32类型的参数。

  

参数数量:
   start:类型为int32的0-D(标量)。首先按顺序进入。
     默认为0。

因此,您可以稍后创建一个int32张量并将其投射到float32。所以,使用这样的东西:

In [80]: index_vector = tf.range(1, tf.shape(gain_vector)[0])
In [81]: vec_float32 = tf.cast(index_vector, dtype=tf.float32)