我想通过保留 10% 的最大条目来过滤张量。是否有 Tensorflow 函数可以做到这一点?一个可能的实现会是什么样子?我正在寻找可以处理形状为 [N,W,H,C] 和 [N,W*H*C] 的张量。
我所说的过滤器是指张量的形状保持不变,但只保留最大的 10%。因此,除了最大的 10% 之外,所有条目都变为零。
这可能吗?
请您参考如下方法:
这样做的正确方法是计算 90 个百分位数,例如 tf.contrib.distributions.percentile :
import tensorflow as tf
images = ... # [N, W, H, C]
n = tf.shape(images)[0]
images_flat = tf.reshape(images, [n, -1])
p = tf.contrib.distributions.percentile(images_flat, 90, axis=1, interpolation='higher')
images_top10 = tf.where(images >= tf.reshape(p, [n, 1, 1, 1]),
images, tf.zeros_like(images))
如果您想为 TensorFlow 2.x 做好准备,请在哪里 tf.contrib will be removed , 你可以改用 TensorFlow Probability , 这是 percentile 的位置功能将在未来永久存在。
编辑:如果你想对每个 channel 进行过滤,你可以像这样稍微修改代码:
import tensorflow as tf
images = ... # [N, W, H, C]
shape = tf.shape(images)
n, c = shape[0], shape[3]
images_flat = tf.reshape(images, [n, -1, c])
p = tf.contrib.distributions.percentile(images_flat, 90, axis=1, interpolation='higher')
images_top10 = tf.where(images >= tf.reshape(p, [n, 1, 1, c]),
images, tf.zeros_like(images))
