如何使用pandas_ml制作一个包含2个类的混淆矩阵?

时间:2018-02-01 22:12:33

标签: python

我试图用绘图制作一个混淆矩阵,pandas_ml似乎有一个功能,但它不适用于2个类。是否有一些秘密选择让它发挥作用?

from pandas_ml import ConfusionMatrix
ytrue = ['ham', 'ham', 'spam']
ypred = ['ham', 'spam', 'spam']
cm = ConfusionMatrix(ytrue, ypred)
cm

结果

Predicted  False  True  __all__
Actual                         
False          0     0        0
True           0     0        0
__all__        0     0        0

此:

from pandas_ml import ConfusionMatrix
ytrue = ['ham', 'ham', 'spam', 'third']
ypred = ['ham', 'spam', 'spam', 'third']
cm = ConfusionMatrix(ytrue, ypred)
cm

结果

Predicted  ham  spam  third  __all__
Actual                              
ham          1     1      0        2
spam         0     1      0        1
third        0     0      1        1
__all__      1     2      1        4

3 个答案:

答案 0 :(得分:1)

也许为时已晚,但我遇到了同样的问题。看来,当你有2个类时,来自pandas_ml的ConfusionMatrix需要输入为boolean。只需将'spam'/'ham'转换为True / False即可。

from pandas_ml import ConfusionMatrix
ytrue = np.array(['ham', 'ham', 'spam'])
ytrue = np.array(['ham', 'ham', 'spam'])
ypred = np.array(['ham', 'spam', 'spam'])
cm = ConfusionMatrix(np.where(ytrue == 'spam', True, False), np.where(ypred == 'spam', True, False))
cm

答案 1 :(得分:0)

解决此问题的方法是创建两个名为pandas的Series,并使用pandas.crosstab()。不要使用pandas_ml:

import pandas as pd

ytrue = pd.Series(['ham', 'ham', 'spam'], name='actual')
ypred = pd.Series(['ham', 'spam', 'spam'], name='predictions')
pd.crosstab(ypred, ytrue)

输出结果如下:

actual       ham  spam
predictions           
ham            1     0
spam           1     1

答案 2 :(得分:-1)

不,当我通过spyder3在我的python3.6中运行它时,我得到了这个,

from pandas_ml import ConfusionMatrix 
ytrue = ['ham', 'ham', 'spam']
ypred = ['ham', 'spam', 'spam']
cm = ConfusionMatrix(ytrue, ypred)
cm

Out[1]: 
Predicted  ham  spam  __all__
Actual                       
ham          1     1        2
spam         0     1        1
__all__      1     2        3

IN[2]: cm.print_stats()
OUT[2]:
population: 3
P: 1
N: 2
PositiveTest: 2
NegativeTest: 1
TP: 1
TN: 1
FP: 1
FN: 0
TPR: 1.0
TNR: 0.5
PPV: 0.5
NPV: 1.0
FPR: 0.5
FDR: 0.5
FNR: 0.0
ACC: 0.666666666667
F1_score: 0.666666666667
MCC: 0.5
informedness: 0.5
markedness: 0.5
prevalence: 0.333333333333
LRP: 2.0
LRN: 0.0
DOR: inf
FOR: 0.0

cm.TP
Out[3]: 1

cm.TN
Out[4]: 1

cm.FP
Out[5]: 1

cm.FN
Out[6]: 0