我想计算大于固定阈值(此处为0.8(的元素的平均值。
numpy中的任务:
X = np.array([[0.11,0.99,0.70]])
print(np.nanmean(X[X>0.8]))
Out : 0.99
在不将张量c
转换为numpy数组的情况下,张量流中的等价物是什么?
示例:
c = tf.constant([[0.11,0.99,0.70]])
tf.reduce_mean(tf.where(tf.greater(c,(tf.constant(0.8, dtype=tf.float32)))))
输出等于0!
Output : <tf.Tensor: shape=(), dtype=int64, numpy=0>
您不需要tf.greater
和tf.where
。
c = tf.constant([[0.11,0.99,0.70]])
# Or : tf.reduce_mean(c[c > 0.8])
tf.reduce_mean(c[c > tf.constant(0.8, dtype=tf.float32)])
您可以使用tf.boolean_mask
作为替代方案:
c = tf.constant([[0.11,0.99,0.70]])
mask = c > 0.8
tf.reduce_mean(tf.boolean_mask(tensor, mask))
输出:<tf.Tensor: shape=(), dtype=float32, numpy=0.99>
您也可以使用boolean_mask
而不是张量索引:
c = tf.constant([[0.11,0.99,0.70]])
tf.reduce_mean(tf.boolean_mask(c, c > 0.8))
<tf.Tensor: shape=(), dtype=float32, numpy=0.99>