【问题标题】:How to mask specific slices for each row in a tensor如何屏蔽张量中每一行的特定切片
【发布时间】:2017-12-04 22:51:59
【问题描述】:

我想根据位置(索引)列表修改 3D 张量中的特定向量:

#indices: 1D vector of positions, indices.shape: (k)

mask = np.zeros(k, n, m)
for i in range(k):
  mask[i][indices[i]] = 1

此蒙版将应用于另一个 3D 张量(相同形状),我想在其中保留特定向量,并将其余向量归零。

在 TensorFlow 中构建这种掩码的最佳方法是什么?我可以使用分配操作通过循环来做到这一点,但我想找到一个更优雅的解决方案。也许使用tf.scatter_nd

编辑:示例:

>>> mask_before
array([[[ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.]],

       [[ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.]],

       [[ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.]]])

>>> indices
array([2, 1, 4])

>>> mask_after
array([[[ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.],
        [ 1.,  1.,  1.,  1.],
        [ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.]],

       [[ 0.,  0.,  0.,  0.],
        [ 1.,  1.,  1.,  1.],
        [ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.]],

       [[ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.],
        [ 1.,  1.,  1.,  1.]]])

【问题讨论】:

  • 请提供样本数据集和您想要的数据集
  • @MaxU,请看一下

标签: python numpy tensorflow


【解决方案1】:

这是 Divakar 答案的相应 TF 代码:

indices = tf.constant([2,1,4])
a1 = tf.expand_dims(indices, axis=1)
a1 = tf.expand_dims(a1, axis=1)
a2 = tf.range(5)
a2 = tf.expand_dims(a2, axis=1)
a3 = tf.equal(a1, a2)
mask = tf.tile(a3, [1,1,4])


>>> tf.cast(mask, dtype=tf.int8)
<tf.Tensor: id=55, shape=(3, 5, 4), dtype=int8, numpy=
array([[[0, 0, 0, 0],
    [0, 0, 0, 0],
    [1, 1, 1, 1],
    [0, 0, 0, 0],
    [0, 0, 0, 0]],

   [[0, 0, 0, 0],
    [1, 1, 1, 1],
    [0, 0, 0, 0],
    [0, 0, 0, 0],
    [0, 0, 0, 0]],

   [[0, 0, 0, 0],
    [0, 0, 0, 0],
    [0, 0, 0, 0],
    [0, 0, 0, 0],
    [1, 1, 1, 1]]], dtype=int8)>

【讨论】:

    【解决方案2】:

    一种矢量化方式是扩展维度,从而利用broadcasting -

    np.tile((indices[:,None,None] == np.arange(n)[:,None]), m)
    

    示例运行 -

    In [755]: # Sample Setup
         ...: indices = np.array([2,3,1])
         ...: 
         ...: k = 3
         ...: n = 4
         ...: m = 2
         ...: mask = np.zeros((k, n, m),dtype=bool)
         ...: for i in range(k):
         ...:     mask[i][indices[i]] = 1
    
    In [756]: out = np.tile((indices[:,None,None] == np.arange(n)[:,None]), m)
    
    In [757]: np.allclose(out, mask)
    Out[757]: True
    

    要移植到tensorflow,我们有对应的:

    tf.expand_dimstf.tile

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-10
      • 1970-01-01
      • 1970-01-01
      • 2020-08-01
      • 1970-01-01
      • 2019-11-02
      • 2019-04-13
      相关资源
      最近更新 更多