Spe*_*pen 4 python multidimensional-array tensorflow tensor tensor-indexing
在张量流中,可以使用切片符号选择每第 n 个项目[::n]。
但如何反其道而行之呢?我想选择除第 n 个之外的所有项目。
例如:
a = [1, 2, 3, 4, 5, 6, 7, 8]
Run Code Online (Sandbox Code Playgroud)
a[2::3]会导致[3, 6]
现在我想要相反的:[1, 2, 4, 5, 7, 8]
上面的数组只是一个例子。解决方案应该适用于张量流中尺寸[批量、宽度、高度、通道]的更大矩阵。选择仅在通道上完成。我的矩阵还包含非唯一的实值。我也无法将其重塑为二维以下 ( [batch, channels])
一种选择是通过测试范围索引来创建布尔索引:
import numpy as np
start, step = 2, 3
a[np.arange(len(a)) % step != start]
# array([1, 2, 4, 5, 7, 8])
Run Code Online (Sandbox Code Playgroud)
您可以使用以下方法在张量流中类似地实现此目的tf.boolean_mask:
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)
Run Code Online (Sandbox Code Playgroud)
如果是 ND 张量,则可以用;a指定轴 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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2055 次 |
| 最近记录: |