我知道tf.where
将返回True
值的位置,这样我就可以使用结果的shape[0]
来获得True
的数量
但是,当我尝试使用它时,维度是未知的(这是有意义的,因为它需要在运行时计算)。所以我的问题是,我怎样才能访问一个维度,并在一个操作中像求和一样使用它?
例如:
myOtherTensor = tf.constant([[True, True], [False, True]])
myTensor = tf.where(myOtherTensor)
myTensor.get_shape() #=> [None, 2]
sum = 0
sum += myTensor.get_shape().as_list()[0] # Well defined at runtime but considered None until then.
您可以将值强制转换为浮点数并计算它们的和:
tf.reduce_sum(tf.cast(myOtherTensor, tf.float32))
根据实际的用例,如果指定了调用的reduce维度,还可以计算每行/列的总和。
我认为这是最简单的方法:
Rafal的答案几乎可以肯定是计算张量中
true
元素数量的最简单方法,但问题的另一部分是:为此,可以使用TensorFlow的shape-related operations,它作用于tensor的运行时值。例如,^{} 生成标量} 生成一维
Tensor
,包含t
中的元素数,^{Tensor
,包含每个维度中t
的大小。使用这些运算符,您的程序也可以编写为:
相关问题 更多 >
编程相关推荐