如何按元素比较 3 个 numpy 数组并将结果作为具有最大值的数组?

numpy 数组包含如下所示的预测概率:


predict_prob1 =([[0.95602106, 0.04397894],

                 [0.93332366, 0.06667634],

                 [0.97311459, 0.02688541],

                 [0.97323962, 0.02676038]])


predict_prob2 =([[0.70425144, 0.29574856],

                 [0.69751251, 0.30248749],

                 [0.7072872 , 0.2927128 ],

                 [0.68683139, 0.31316861]])


predict_prob3 =([[0.56551921, 0.43448079],

                 [0.93321106, 0.06678894],

                 [0.92345399, 0.07654601],

                 [0.88396842, 0.11603158]])

我想逐个比较这三个 numpy.ndarray 并找出哪个数组的概率最大。其中三个数组的长度相同。我试图实现这样的事情,这是不正确的。


for i in range(len(predict_prob1)):

    if(predict_prob1[i] > predict_prob2[i])

        c = predict_prob1[i]

    else

        c = predict_prob2[i]

    if(c > predict_prob3[i])

        result = c

    else

        result = array[i]

请帮忙!!


阿晨1998
浏览 162回答 3
3回答

隔江千里

如果你想要的结果是一个 4x2 数组,它索引三个数组中哪个位置的最大值,i,j那么你想要使用np.argmax>>> import numpy as np>>> predict_prob1 =([[0.95602106, 0.04397894],&nbsp; &nbsp; [0.93332366, 0.06667634],&nbsp; &nbsp; [0.97311459, 0.02688541],&nbsp; &nbsp; [0.97323962, 0.02676038]])>>> predict_prob2 =([[0.70425144, 0.29574856],&nbsp; &nbsp; [0.69751251, 0.30248749],&nbsp; &nbsp; [0.7072872 , 0.2927128 ],&nbsp; &nbsp; [0.68683139, 0.31316861]])>>> predict_prob3 =([[0.56551921, 0.43448079],&nbsp; &nbsp; [0.93321106, 0.06678894],&nbsp; &nbsp; [0.92345399, 0.07654601],&nbsp; &nbsp; [0.88396842, 0.11603158]])>>> np.argmax((predict_prob1,predict_prob2,predict_prob3), 0)array([[0, 2],&nbsp; &nbsp; &nbsp; &nbsp;[0, 1],&nbsp; &nbsp; &nbsp; &nbsp;[0, 1],&nbsp; &nbsp; &nbsp; &nbsp;[0, 1]])>>>附录阅读了 OP 的评论后,我将以下内容添加到我的答案中>>> names = np.array(['predict_prob%d'%(i+1) for i in range(3)])>>> names[np.argmax((predict_prob1,predict_prob2,predict_prob3),0)]array([['predict_prob1', 'predict_prob3'],&nbsp; &nbsp; &nbsp; &nbsp;['predict_prob1', 'predict_prob2'],&nbsp; &nbsp; &nbsp; &nbsp;['predict_prob1', 'predict_prob2'],&nbsp; &nbsp; &nbsp; &nbsp;['predict_prob1', 'predict_prob2']], dtype='<U13')>>>&nbsp;

尚方宝剑之说

你可以这样做np.maximum.reduce:np.maximum.reduce([A, B, C])其中A, B,C是numpy.ndarray对于您的示例,它的结果是:[[0.95602106 0.43448079]&nbsp;[0.93332366 0.30248749]&nbsp;[0.97311459 0.2927128 ]&nbsp;[0.97323962 0.31316861]]

守候你守候我

假设您想要,对于每一行,类别 0 的概率最高的数组的索引:which = 0np.stack([predict_prob1, predict_prob2, predict_prob3], axis=2)[:, which, :].argmax(axis=1)输出:array([0, 0, 0, 0])对于第 1 类:array([2, 1, 1, 1])
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python