python – numpy矩阵,通过排序每一行将0设置为值

我有一个矩阵,有很多行,有8列.
每个单元格表示当前行属于8个类别中的1个的概率.
我想在每行中只保留2个最高值,并将其余值设置为0.

到目前为止,我能想到的唯一方法是分别循环和排序每一行.
例如:

a = np.array([[ 0.2  ,  0.1  ,  0.02 ,  0.01 ,  0.031,  0.11 ],
              [ 0.5  ,  0.1  ,  0.02 ,  0.01 ,  0.031,  0.11 ],
              [ 0.2  ,  0.1  ,  0.22 ,  0.15 ,  0.031,  0.11 ]])

我想得到:

array([[ 0.2 ,  0.  ,  0.  ,  0.  ,  0.  ,  0.11],
       [ 0.5 ,  0.  ,  0.  ,  0.  ,  0.  ,  0.11],
       [ 0.2 ,  0.  ,  0.22,  0.  ,  0.  ,  0.  ]])

谢谢,

这是一个带有np.argpartition的矢量化方法 –

m,n = a.shape
a[np.arange(m)[:,None],np.argpartition(a,n-2,axis=1)[:,:-2]] = 0

样品运行 –

In [570]: a
Out[570]: 
array([[ 0.94791114,  0.48438182,  0.54574317,  0.45481231,  0.94013836],
       [ 0.03861196,  0.99047316,  0.7897759 ,  0.38863967,  0.93659426],
       [ 0.49436676,  0.93762758,  0.33694977,  0.45701655,  0.73078113],
       [ 0.21240062,  0.85141765,  0.00815352,  0.52517721,  0.49752736]])

In [571]: m,n = a.shape
     ...: a[np.arange(m)[:,None],np.argpartition(a,n-2,axis=1)[:,:-2]] = 0
     ...: 

In [572]: a
Out[572]: 
array([[ 0.94791114,  0.        ,  0.        ,  0.        ,  0.94013836],
       [ 0.        ,  0.99047316,  0.        ,  0.        ,  0.93659426],
       [ 0.        ,  0.93762758,  0.        ,  0.        ,  0.73078113],
       [ 0.        ,  0.85141765,  0.        ,  0.52517721,  0.        ]])
https://stackoverflow.com/questions/35416050/numpy-matrix-setting-0-to-values-by-sorting-each-row

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:python – numpy矩阵,通过排序每一行将0设置为值