【问题标题】:Tensorflow - Sort a tensor with a custom comparatorTensorflow - 使用自定义比较器对张量进行排序
【发布时间】:2019-04-06 14:51:17
【问题描述】:

如何根据仅使用 Tensorflow 操作的自定义比较函数对形状为 [n,2] 的整数张量进行排序?

假设我的张量中有两个条目是 [x1, y1] 和 [x2, y2]。我想对张量进行排序,以便条目按条件 x1 * y2 > x2 * y1 重新排序。

【问题讨论】:

    标签: python sorting tensorflow


    【解决方案1】:

    假设您可以为您的元素创建一个指标(如果没有,请参见下面的一般情况)(此处,将不等式重新排列为 x1 / y1 > x2 / y2 ,因此度量将是 x / y 并依靠 TensorFlow 生成 inf(如无穷大)除以零),像这段代码一样使用tf.nn.top_k()(经过测试):

    import tensorflow as tf
    
    x = tf.constant( [ [1,2], [3,4], [1,3], [2,5] ] ) # some example numbers
    
    s = tf.truediv( x[ ..., 0 ], x[ ..., 1 ] ) # your sort condition
    val, idx = tf.nn.top_k( s, x.get_shape()[ 0 ].value )
    x_sorted = tf.gather( x, idx )
    
    with tf.Session() as sess:
        print( sess.run( x_sorted ) )
    

    输出:

    [[3 4]
    [1 2]
    [2 5]
    [1 3]]


    如果您不能或不容易创建度量标准,那么仍然会假设该关系会为您提供well-ordering。 (否则结果未定义。)在这种情况下,您为整个集合构建比较矩阵并按行总和对元素进行排序(即,有多少其他元素更大);这当然是要排序的元素数量的二次方。此代码(已测试):

    import tensorflow as tf
    
    x = tf.constant( [ [1,2], [3,4], [1,3], [2,5] ] ) # some example numbers
    
    x1, y1 = x[ ..., 0 ][ None, ... ], x[ ..., 1 ][ None, ... ] # expanding dims into cols
    x2, y2 = x[ ..., 0, None ],        x[ ..., 1, None ] # expanding into rows
    r = tf.cast( tf.less( x1 * y2, x2 * y1 ), tf.int32 ) # your sort condition, with implicit broadcasting
    s = tf.reduce_sum( r, axis = 1 ) # how many other elements are greater
    
    val, idx = tf.nn.top_k( s, s.get_shape()[ 0 ].value )
    x_sorted = tf.gather( x, idx )
    
    with tf.Session() as sess:
        print( sess.run( x_sorted ) )
    

    输出:

    [[3 4]
    [1 2]
    [2 5]
    [1 3]]

    【讨论】:

    • 我相信这个解决方案涵盖了排序条件x1 * y1 > x2 * y2,而不是x1 * y2 > x2 * y1(尽管这个排序条件对我来说似乎是错误的)。
    • 哦,你是对的。 x1 * y2 > x2 * y1 不能是循环的吗?
    • 确实 - 刚刚评论了 OP 的帖子 :)
    • 支持你的 cmets :) 让我们听听他的意见,如果这确实是他的意图,或者这是一个错字
    • 为什么是圆形的?这个条件可以解释为等价于在二维平面中按斜率递增的顺序对点进行排序?
    【解决方案2】:

    作为top_kPeter Szoldan 的答案的替代,1.13 之后有一个tf.argsort

    对于

    tf.nn.top_k( s, tf.shape(x)[0] )
    

    如果无法在静态图中获取形状。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 2016-11-08
      • 2020-07-11
      • 2020-12-16
      • 2019-05-06
      相关资源
      最近更新 更多