【问题标题】:Is there a way to, for each element, aggregate the maximum value in it's row without that specific element?对于每个元素,有没有办法在没有该特定元素的情况下聚合其行中的最大值?
【发布时间】:2022-01-27 04:06:51
【问题描述】:

我想知道是否有一种巧妙的方法可以用纯张量变换来表达这个操作:

equation

基本上让一行的每个元素代表该行中没有该元素的最大值。

# Input
[
  [8, -2, 9],
  [7, 100, -2],
  [5, 11, 2]
]

# Result
[
  [9, 9, 8],
  [100, 7, 100],
  [11, 5, 11]
]

我可以把它想象成也许构造一个像这样的矩阵:

[
  [[-2, 9],   [8, 9],  [8, -2]],
  [[100, -2], [7, -2], [7, 100]],
  [[11, 2],   [5, 2],  [5, 11]]
]

但我不知道该怎么做。

我希望它使用计算图仅在 GPU 上运行。

【问题讨论】:

    标签: tensorflow pytorch tensor


    【解决方案1】:

    你可以使用 tf.math.top_k 如下

    x = tf.constant([
      [8, -2, 9],
      [7, 100, -2],
      [5, 11, 2]
    ])
    
    # Find top 2 values and their indices 
    top_pairs_values, top_pair_indices = tf.math.top_k(input=x, k=2)
    
    # True value corresponds to the situation when we need second top value
    # False value corresponds to the first top value
    condition = tf.expand_dims(tf.range(tf.shape(x)[1]), 0) == top_pair_indices[:, :1]
    
    # We select either top or second top value form top_pairs_values according to the condition
    output = tf.where(
        condition=condition, 
        x=top_pairs_values[:, 1:], 
        y=top_pairs_values[:, :1]
    )
    
    output
    # <tf.Tensor: shape=(3, 3), dtype=int32, numpy=
    # array([[  9,   9,   8],
    #        [100,   7, 100],
    #        [ 11,   5,  11]], dtype=int32)>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-07
      • 2020-03-16
      • 1970-01-01
      • 2012-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多