前 n 个值的 Tensorflow 指标矩阵 [英] Tensorflow indicator matrix for top n values
问题描述
有谁知道如何提取秩为 2 的张量每行的前 n 个最大值?
Does anyone know how to extract the top n largest values per row of a rank 2 tensor?
例如,如果我想要形状为 [2,4] 的张量的前 2 个值:
For instance, if I wanted the top 2 values of a tensor of shape [2,4] with values:
[[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]]
一旦我有了条件矩阵,我就可以使用 tf.select 来选择实际值.
Once I have the condition matrix, I can use tf.select to choose actual values.
感谢您的帮助!
推荐答案
您可以使用内置的 tf.nn.top_k 函数:
You can do it using built-in tf.nn.top_k function:
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)
要获取布尔True/False
值,可以先获取第k个值,然后使用tf.greater_equal
:
To get boolean True/False
values, you can first get the k-th value and then use 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)
这篇关于前 n 个值的 Tensorflow 指标矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!