arrays - Tensorflow 中的二进制掩码

标签 arrays tensorflow masking

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

#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 中那么简单。

最佳答案

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

这里有一些解决方法:

tf.变量

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())

关于arrays - Tensorflow 中的二进制掩码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40443951/

相关文章:

php - 从多维数组中获取数组并将值传递给 PHP 中的变量

javascript - Lodash forEach 函数省略

php - 如何仅在最后出现的分隔符上 explode ?

tensorflow - tf.dataset、多个路径输入以及每批映射以加载图像

encryption - SAS 中的数据屏蔽 : Scrambling Sensitive observations at character level

c# - 屏蔽除字符串的前 6 位和后 4 位以外的所有数字(长度不同)

javascript - 如何在本地存储中保存对象、变量、数组?

tensorflow - 具有归一化二元交叉熵损失的模型不收敛

machine-learning - 如何将 LMDB 文件加载到 TensorFlow 中?

ios - 图像无法用作 Core Graphics 的 mask