【问题标题】:How to reduce dimension of a tensor with keeping specific indexed elements of that dimension?如何通过保留该维度的特定索引元素来减少张量的维度?
【发布时间】:2020-11-04 21:01:13
【问题描述】:

维度的减少类似于 reduce_max() 所做的,不同之处在于我想要该维度中元素的特定索引,而不是简单地选择最大的索引。例如,我有一个 2x3 张量 A = [[0,1,2],[2,2,0]]。如果我应用 tf.argmax(A),我会得到索引张量 [1, 1, 0]。如何使用这个索引张量 [1, 1, 0] 将张量设为 tf.reduce_max(A, 0) = [2, 2, 2]?

我不直接使用 tf.reduce_max 的原因是我想使用不同的索引张量而不是 argmax 索引张量来减少维度或保留索引值而不是该维度的最大值。

【问题讨论】:

    标签: python tensorflow tensorflow2.0 tensor


    【解决方案1】:

    您可以使用 tf.gather_nd 函数来执行此操作,但您需要将 [1, 1, 0] 索引张量转换为二维张量。

    这里我假设索引张量是一个numpy数组(你可以通过调用.numpy()方法将tensorflow张量转换成numpy数组。

    idx = np.array([1, 1, 0])
    
    idx = np.c_[idx[:, np.newaxis], np.arange(len(idx))]
    
    print(idx)
    
    # Output:
    # array([[1, 0],
    #        [1, 1],
    #        [0, 2]])
    

    这意味着:使用上面提到的tf.gather_nd时选择(row1,col0),(row1,col1)和(row0,col2)

    A = tf.Variable([[0, 1, 2], [2, 2, 0]])
    
    tf.gather_nd(A, idx)
    

    会给你预期的[2, 2, 2]张量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-26
      • 1970-01-01
      • 2021-07-17
      • 2021-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多