【问题标题】:How to get the probability and label for each class?如何获得每个类别的概率和标签?
【发布时间】:2021-05-13 07:12:27
【问题描述】:

我有一个模型可以根据某些条件对场地进行分类,它有 10 个类别,我希望每个类别的置信度得分有多少模型预测?

我的代码: 结果是一个数组,模型在其中进行预测

        predictions=model.predict(result)
        confidence_score= model.predict_proba(list(result))

model.predict 只返回一个值,并且置信度得分具有每个类别的得分列表,如下所示:

[[0.       0.14       0.       0.       0.       0.56       0.       0.17
  0.1      0.01       0.       0.20       0.       0.       0.002    0.01]]

它还应该为每个类返回类标签,例如:A 类发生的概率为 0.2 % 等。

labelencoder.inverse_transform(predictions) 

输出应如下所示:

{Class Label A : Probability score , Class Label B: Probability score ....}

输出使用以下代码:

      dictionary=[dict(zip(labelencoder.classes_, cs)) for cs in confidence_score]

Output   
{Covent Garden': 0.0, 'London Cocktail Club - Liverpool Street': 0.0,
'Lost Society Battersea': 0.0, 'Lost Society Putney': 0.94.....}

在这种情况下,您可以看到 Lost Society 的置信度得分较高,但是当我执行 model.predict 时,它会返回一些其他标签而不是这个标签,我在代码中编写了预测得分最高的类别的代码。

My code :
        predictions=model.predict(result) //returns the single number 
        confidence_score= model.predict_proba(list(result))

        dictionary=[dict(zip(labelencoder.classes_, cs)) for cs in confidence_score]
        print(dictionary)
            
        print("Recommended Venue for this type of category is",labelencoder.inverse_transform(predictions))
        print("Confidence Score : ", np.max(confidence_score))
        return labelencoder.inverse_transform(predictions),np.max(confidence_score)

【问题讨论】:

  • 你的预期输出是什么?
  • 我想要字典,它应该返回每个类的概率分数及其标签,如上所示!
  • @Haseed IIUC,在这种情况下我们无法创建字典,因为如果多个预测具有相同的预测类,那么只有最后一个预测将存储在字典中,因为字典不能有重复的键。 . 可能你必须重新考虑预期产出的策略
  • 不,多个预测没有相同的类别,它们是唯一的,
  • 所以你每次只预测一个样本,对吧?

标签: python pandas list machine-learning artificial-intelligence


【解决方案1】:

我们可以 zip labelencoder.classes_confidence_score 并将 zip 对象传递给 dict 以创建字典

dict(zip(labelencoder.classes_, confidence_score.squeeze()))

如果您想一次性预测多个样本

[dict(zip(labelencoder.classes_, cs)) for cs in confidence_score]

【讨论】:

  • 它只显示一个类,我只得到输出 {'Class A': 0.94}
  • 你是怎么知道哪个置信度分数属于哪个类别的?
  • predict_prob 函数将返回所有 ordered by the label of classes 类的估计值/概率,labelencoder.classes_ 也是如此
  • 好的,让我编辑我的问题给你,因为这条线又发生了一个问题
  • Shubhan,我已经编辑了代码,请查看并告诉我问题发生在哪里
最近更新 更多