Tensorflow 中的二进制掩码

Binary mask in Tensorflow

我想屏蔽张量特定维度上的所有其他值,但没有找到生成此类屏蔽的好方法。例如

#Masking on the 2nd dimension
a = [[1,2,3,4,5],[6,7,8,9,0]
mask = [[1,0,1,0,1],[1,1,1,1,1]]
b = a * mask #would return [[1,0,3,0,5],[6,0,8,0,0]]

有没有简单的方法来生成这样的掩码?

理想情况下,我想做如下事情:

mask = tf.ones_like(input_tensor)
mask[:,::2] = 0
mask * input_tensor

但是切片分配似乎不像在 Numpy 中那么简单。

您可以使用 python 以编程方式轻松创建这样的张量掩码。然后将其转换为张量。 TensorFlow API 中没有这样的支持。 tf.tile([1,0], num_of_repeats) 可能是创建此类掩码的快速方法,但如果列数为奇数,也不是很好。

(顺便说一句,如果您最终创建了一个布尔掩码,请使用 tf.boolean_mask()

目前,Tensorflow does not support 类似 numpy 的赋值。

这里有几个解决方法:

tf.Variable

tf.Tensor无法更改,但tf.Variable可以。

a = tf.constant([[1,2,3,4,5],[6,7,8,9,10]])

mask = tf.Variable(tf.ones_like(a, dtype=tf.int32))
mask = mask[0,1::2]
mask = tf.assign(mask, tf.zeros_like(mask))
# mask = [[1,0,1,0,1],[1,1,1,1,1]]

tf.InteractiveSession()
tf.global_variables_initializer().run()
print(mask.eval())

tf.sparse_to_dense()

indices = tf.range(1, 5, 2)
indices = tf.stack([tf.zeros_like(indices), indices], axis=1)
# indices = [[0,1],[0,3]]
mask = tf.sparse_to_dense(indices, a.shape, sparse_values=0, default_value=1)
# mask = [[1,0,1,0,1],[1,1,1,1,1]]

tf.InteractiveSession()
print(mask.eval())

有一个更有效的解决方案,但这肯定会完成工作

myshape = myTensor.shape
# create tensors of your tensor's indices:
row_idx, col_idx = tf.meshgrid(tf.range(myshape[0]), tf.range(myshape[1]), indexing='ij')
# create boolean mask of odd numbered columns on a particular row.
mask = tf.where((row_idx == N) * (col_idx % 2 == 0), False, True)

masked = tf.boolean_mask(myTensor, mask)

一般来说,您可以将此方法应用于任何此类基于索引的掩码,并适用于 rank-n 张量