我有一个数组[0.3, 0.5, 0.79, 0.2, 0.11].
我想将除最大值以外的所有值都转换为零。所以结果数组将是:
[0, 0, 0.79, 0, 0]
在 Tensorflow 图中执行此操作的最佳方法是什么?
最佳答案
如果你想保留所有出现的最大值,你可以使用
cond = tf.equal(a, tf.reduce_max(a))
a_max = tf.where(cond, a, tf.zeros_like(a))
如果你只想保留最大值的一次出现,你可以使用
argmax = tf.argmax(a)
a_max = tf.scatter_nd([[argmax]], [a[argmax]], tf.to_int64(tf.shape(a)))
但是根据the doc of tf.argmax
,
Note that in case of ties the identity of the return value is not guaranteed
据我了解,保留的最大值可能不是第一个或最后一个——如果在同一个数组上运行两次,甚至可能不相同。
关于python - 将 Tensorflow 中除最大值以外的所有值归零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50563215/