Python 如何在tensorflow中随机选择索引而不是最大值(tf.arg_max)

Python 如何在tensorflow中随机选择索引而不是最大值(tf.arg_max),python,tensorflow,Python,Tensorflow,我可以使用tf.arg_max选择矩阵中的最大索引, 在tensorflow中是否有一个函数,可以在前n中随机选择索引 test = np.array([ [1, 2, 3], [2, 3, 4], [5, 4, 3], [8, 7, 2]]) argmax0 = tf.arg_max(test, 0) # argmax0 = [3, 3, 1] 我需要一个函数为每个数组随机选择前2名中的索引。 例如: 第一个colmuns[1,2,5,8],top2是[5,8],只需从[5,8]中

我可以使用
tf.arg_max
选择矩阵中的最大索引, 在
tensorflow
中是否有一个函数,可以在前n中随机选择索引

test = np.array([
[1, 2, 3],
 [2, 3, 4], 
 [5, 4, 3], 
 [8, 7, 2]])
argmax0 = tf.arg_max(test, 0)
# argmax0 = [3, 3, 1]
我需要一个函数为每个数组随机选择前2名中的索引。 例如: 第一个colmuns[1,2,5,8],top2是[5,8],只需从[5,8]中随机选择一个即可。
因此,最终的答案可能是[3,2,0]、[2,2,0]、[3,3,1]、[3,2,0]或更多。

您使用.argsort方法,然后从中取顶部的N

N = 3
a = [1, 3, 4, 5, 2]
top_N_indicies = a.argsort()[-N:][::-1]

# top_N_indicies = [3, 2, 1]
获取topk值:

values, _ = tf.math.top_k(test, 2)

如何处理2-dims阵列?您希望2-dim阵列的每一行为top-N吗?
<tf.Tensor: shape=(4, 2), dtype=int32, numpy=
array([[3, 2],
       [4, 3],
       [5, 4],
       [8, 7]])>
shuffled = tf.map_fn(tf.random.shuffle, values)
<tf.Tensor: shape=(4, 2), dtype=int32, numpy=
array([[2, 3],
       [4, 3],
       [4, 5],
       [7, 8]])>
tf.gather(shuffled, [0], axis=1)
<tf.Tensor: shape=(4, 1), dtype=int32, numpy=
array([[2],
       [4],
       [4],
       [7]])>
import tensorflow as tf
import numpy as np

test = np.array([
    [1, 2, 3],
    [2, 3, 4],
    [5, 4, 3],
    [8, 7, 2]])

values, _ = tf.math.top_k(test, 2)

shuffled = tf.map_fn(tf.random.shuffle, values)

tf.gather(shuffled, [0], axis=1)