[英]Tensorflow indicator matrix for top n values
Does anyone know how to extract the top n largest values per row of a rank 2 tensor? 有谁知道如何提取排名2张量的每行的前n个最大值?
For instance, if I wanted the top 2 values of a tensor of shape [2,4] with values: 例如,如果我希望形状[2,4]的张量的前2个值具有值:
[[40, 30, 20, 10], [10, 20, 30, 40]] [[40,30,20,10],[10,20,30,40]]
The desired condition matrix would look like: [[True, True, False, False],[False, False, True, True]] 所需的条件矩阵如下所示:[[True,True,False,False],[False,False,True,True]]
Once I have the condition matrix, I can use tf.select to choose actual values. 一旦我有了条件矩阵,我就可以使用tf.select来选择实际值。
Thank you for assistance! 谢谢你的帮助!
You can do it using built-in tf.nn.top_k function: 你可以使用内置的tf.nn.top_k函数来完成它:
a = tf.convert_to_tensor([[40, 30, 20, 10], [10, 20, 30, 40]])
b = tf.nn.top_k(a, 2)
print(sess.run(b))
TopKV2(values=array([[40, 30],
[40, 30]], dtype=int32), indices=array([[0, 1],
[3, 2]], dtype=int32))
print(sess.run(b).values))
array([[40, 30],
[40, 30]], dtype=int32)
To get boolean True/False
values, you can first get the k-th value and then use tf.greater_equal
: 要获得布尔值
True/False
值,您可以先获取第k个值,然后使用tf.greater_equal
:
kth = tf.reduce_min(b.values)
top2 = tf.greater_equal(a, kth)
print(sess.run(top2))
array([[ True, True, False, False],
[False, False, True, True]], dtype=bool)
you can also use tf.contrib.framework.argsort
你也可以使用
tf.contrib.framework.argsort
a = [[40, 30, 20, 10], [10, 20, 30, 40]]
idx = tf.contrib.framework.argsort(a, direction='DESCENDING') # sorted indices
ranks = tf.contrib.framework.argsort(idx, direction='ASCENDING') # ranks
b = ranks < 2
# [[ True True False False] [False False True True]]
Moreover, you can replace 2
with a 1d tensor so that each row/column can have different n
values. 此外,您可以使用1d张量替换
2
,以便每个行/列可以具有不同的n
值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.