我有一个lda_fit
具有概率的numpy 2d数组(名为),我想根据每行的最大值用0或1替换概率。
array([[0.06478282, 0.80609092, 0.06511851, 0.06400775],
[0.50386571, 0.02621445, 0.44400621, 0.02591363],
[0.259538 , 0.04266385, 0.65470484, 0.04309331],
...,
[0.01415491, 0.01527508, 0.22211579, 0.74845422],
[0.01419367, 0.01537099, 0.01521318, 0.95522216],
[0.25 , 0.25 , 0.25 , 0.25 ]])
因此,第一行毕竟应该像[0,1,0,0]
,第二行[1,0,0,0]
等等。我已经尝试过了,但是这仅适用于给定的阈值(0.5):
np.where(lda_fit < 0.5,0,1)
但是由于我的最大值可能不大于0.5,因此我想为每行指定一个新的阈值。不幸的是,这给了我整个数组的最大值。
np.where(lda_fit < np.max(lda_fit),0,1)
您可以使用np.max
指定轴:
(lda_fit.max(1,keepdims=True)==lda_fit)+0
注意:如果连续超过一个最大值,则所有最大值将返回1。对于替代解决方案,请遵循以下方法。
输出例如有问题的输入:
[[0 1 0 0]
[1 0 0 0]
[0 0 1 0]
[0 0 0 1]
[0 0 0 1]
[1 1 1 1]]
如果连续存在多个max,如果您只希望第一个为1,其余的max为0,则可以使用argmax
:
(lda_fit.argmax(axis=1)[:,None] == range(lda_fit.shape[1]))+0
或相等:
lda_fit_max = np.zeros(lda_fit.shape, dtype=int)
lda_fit_max[np.arange(len(lda_fit)),lda_fit.argmax(axis=1)]=1
输出:
[[0 1 0 0]
[1 0 0 0]
[0 0 1 0]
[0 0 0 1]
[0 0 0 1]
[1 0 0 0]]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句