在 tensorflow 中,可以使用切片符号 [::n]
选择每第 n 个项目。
但是如何反其道而行之呢?我想选择除第 n 个以外的所有项目。
例如:
a = [1, 2, 3, 4, 5, 6, 7, 8]
a[2::3]
将导致 [3, 6]
现在我想要相反的结果:[1, 2, 4, 5, 7, 8]
上面的数组只是一个例子。解决方案应该适用于 tensorflow 中维度 [batch, width, height, channels] 的更大矩阵。选择仅在 channel 上完成。此外,我的矩阵包含非唯一的实数值。我也无法将它进一步向下 reshape 到二维 ([batch, channels]
)
最佳答案
一种选择是通过测试范围索引来创建 bool 索引:
import numpy as np
start, step = 2, 3
a[np.arange(len(a)) % step != start]
# array([1, 2, 4, 5, 7, 8])
您可以使用 tf.boolean_mask
在 tensorflow 中类似地实现此目的:
import tensorflow as tf
a = tf.constant([1, 2, 3, 4, 5, 6, 7, 8])
start, step = 2, 3
mask = ~tf.equal(tf.range(a.shape[-1]) % step, start)
tf.boolean_mask(a, mask).eval()
# array([1, 2, 4, 5, 7, 8], dtype=int32)
如果a
是ND张量,可以用boolean_mask
指定坐标轴;以 4D 张量 [batch, width, height, channels] 为例,要按第四轴选择,即 channels
,您可以设置 axis=3
:
mask = ~tf.equal(tf.range(a.shape[-1]) % step, start)
tf.boolean_mask(a, mask, axis=3)
关于python - 切片除第 n 个之外的每个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54775246/