python - 将 Tensorflow 中除最大值以外的所有值归零

标签 python tensorflow

我有一个数组[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/

相关文章:

python - 使用 OS X automator 在 csv 文件上运行 Python 脚本

python - Python OpenCV-增加视频fps

tensorflow - 如何在 tensorflow 中随机初始化权重?

python - 清理 tensorflow 摘要

python - OpenCV 中的 Tensorflow 自定义模型

python - 刷新 Tkinter 中的窗口

python - scipy 最小化(SLSQP)的限制结果

python - 在批量 uploader 中正确编码文本

python - 在 tensorlfow 对象检测 api 中导出推理图时出错

python - 使用回归输出处理 tensorflow 中的大型 numpy 数组(51 个输出)