python - 切片除第 n 个之外的每个项目

标签 python tensorflow multidimensional-array tensor tensor-indexing

在 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/

相关文章:

java - 将 2d int 数组写入 JAVA 文件

python - 无法在 CPanel 上上传媒体文件(使用 django)

python - 将 erf 函数拟合到数据

python - Numpy 中的线性代数

python - Keras try save and load model error You are trying to load a weight file containing 16 layers into a model with 0 层数

python - Tensorflow Keras - AttributeError : Layer features has no inbound nodes

Java 反射 - 使用 int[][] 参数调用方法

python - 基于列表的一个字段按数据分组

python - 在生成器中设置 Keras 变量

c - 从C中的指针检索二维数组