python - Get N maximum values and indices along an axis in a NumPy array -
i think easy question experienced numpy users.
i have score matrix. raw index corresponds samples , column index corresponds items. example,
score_matrix = [[ 1. , 0.3, 0.4], [ 0.2, 0.6, 0.8], [ 0.1, 0.3, 0.5]]
i want top-m indices of items each samples. want top-m scores. example,
top2_ind = [[0, 2], [2, 1], [2, 1]] top2_score = [[1. , 0.4], [0,8, 0.6], [0.5, 0.3]]
what best way using numpy?
i'd use argsort()
:
top2_ind = score_matrix.argsort()[:,::-1][:,:2]
that is, produce array contains indices sort score_matrix
:
array([[1, 2, 0], [0, 1, 2], [0, 1, 2]])
then reverse columns ::-1
, take first 2 columns :2
:
array([[0, 2], [2, 1], [2, 1]])
then similar regular np.sort()
values:
top2_score = np.sort(score_matrix)[:,::-1][:,:2]
which following same mechanics above, gives you:
array([[ 1. , 0.4], [ 0.8, 0.6], [ 0.5, 0.3]])
Comments
Post a Comment