对张量进行下采样

Downsample a Tensor

假设我们有一个形状为 a = [batch_size, length, 1] 的 3D 张量,我们希望从 length 轴开始每隔 5 个样本丢弃一次。每个批次元素的新索引可以计算为 indices = tf.where(tf.range(a.shape[1]) % 5 != 0).

你能帮我做一个获得更短张量形状 b = [batch_size, length2, 1] 的操作吗? length2 = 4/5 * length 在哪里?我认为这可以通过 tf.gather_nd 实现,但我在提供正确格式的索引时遇到了问题。它不仅仅是将索引 Tensor batch_size 平铺并将生成的 2D 张量提供给 tf.gather_nd 以 3D 张量作为参数。

谢谢。

您可以简单地执行以下操作:

import tensorflow as tf
# Example data
a = tf.reshape(tf.range(60), [5, 12, 1])
print(a.numpy()[:, :, 0])
# [[ 0  1  2  3  4  5  6  7  8  9 10 11]
#  [12 13 14 15 16 17 18 19 20 21 22 23]
#  [24 25 26 27 28 29 30 31 32 33 34 35]
#  [36 37 38 39 40 41 42 43 44 45 46 47]
#  [48 49 50 51 52 53 54 55 56 57 58 59]]
# Mask every one in five items
mask = tf.not_equal(tf.range(tf.shape(a)[1]) % 5, 0)
b = tf.boolean_mask(a, mask, axis=1)
# Show result
print(b.numpy()[:, :, 0])
# [[ 1  2  3  4  6  7  8  9 11]
#  [13 14 15 16 18 19 20 21 23]
#  [25 26 27 28 30 31 32 33 35]
#  [37 38 39 40 42 43 44 45 47]
#  [49 50 51 52 54 55 56 57 59]]