Skip to main content
 首页 » 编程设计

python之根据 tensorflow 中的两列对张量进行排序

2025年01月19日26me-sa

是否可以在 Tensorflow 中根据两列中的值对张量进行排序?

例如,假设我有以下张量。

[[1,2,3] 
[2,3,5] 
[1,4,6] 
[2,2,1] 
[0,4,2]] 

我愿意 喜欢先根据第一列排序,然后根据第二列排序。排序后如下所示。

[[0,4,2] 
[1,2,3] 
[1,4,6] 
[2,2,1] 
[2,3,5]] 

有什么方法可以使用 tensorflow 实现这一点?我能够根据单个列进行排序。但是基于两列的排序对我来说是个问题。请问有人能帮忙吗?

请您参考如下方法:

一个非常幼稚的方法,

import tensorflow as tf 
 
a = tf.constant([[1, 2, 3], 
                 [2, 3, 5], 
                 [1, 4, 6], 
                 [2, 2, 1], 
                 [0, 4, 2]]) 
 
# b = a[:0]*10 + a[:1]*1 -- > (e.g 1*10+2*1 =12) 
b = tf.add(tf.slice(a, [0, 0], [-1, 1]) * 10, tf.slice(a, [0, 1], [-1, 1])) 
 
reordered = tf.gather(a, tf.nn.top_k(b[:, 0], k=5, sorted=False).indices) 
reordered = tf.reverse(reordered, axis=[0]) 
 
with tf.Session() as sess: 
    result = sess.run(reordered) 
    print(result) 

希望这对您有所帮助。