重点关注

  1. 使用 pandas 创建混淆矩阵
  2. 使用 seaborn 显示混淆矩阵
  3. 通过pandas_ml获取其他统计数据
  4. 使用非数值数据

用 Pandas 在 Python 中创建混淆矩阵

首先,下面是用于 Python 中混淆矩阵的数据集:

y_actual

y_predicted

1

1

0

1

0

0

1

1

0

0

1

1

0

1

0

0

1

1

0

0

1

0

0

0

然后,您可以通过使用以下代码创建 pandas DataFrame 来在 Python 中捕获此数据:

import pandas as pd

data = {'y_actual':    [1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0],
        'y_predicted': [1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0]
        }

df = pd.DataFrame(data)
print(df)

运行代码后,数据将如下所示:

y_actual  y_predicted
0          1            1
1          0            1
2          0            0
3          1            1
4          0            0
5          1            1
6          0            1
7          0            0
8          1            1
9          0            0
10         1            0
11         0            0

要使用 pandas 创建混淆矩阵,您需要应用 pd.crosstab,如下所示:

confusion_matrix = pd.crosstab(df['y_actual'], df['y_predicted'], rownames=['Actual'], colnames=['Predicted'])
print (confusion_matrix)

以下是创建混淆矩阵的完整 Python 代码:

import pandas as pd

data = {'y_actual':    [1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0],
        'y_predicted': [1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0]
        }

df = pd.DataFrame(data)

confusion_matrix = pd.crosstab(df['y_actual'], df['y_predicted'], rownames=['Actual'], colnames=['Predicted'])
print(confusion_matrix)

运行代码,你将获得以下矩阵:

Predicted  0  1
Actual         
0          5  2
1          1  4

使用 seaborn 显示混淆矩阵

上面创建的矩阵是相当基本的。

您可以在 Python 中使用 seaborn 来获得更生动的矩阵显示。若要完成此任务,需要将以下两个组件添加到代码中:

  • 将 Seaborn 导入为 SN
  • sn.heatmap(confusion_matrix, annot=True)

您还需要使用 matplotlib 通过添加以下内容来绘制结果:

  • 将 matplotlib.pyplot 导入为 plt
  • plt.show() 中

把所有东西放在一起:

import pandas as pd
import seaborn as sn
import matplotlib.pyplot as plt

data = {'y_actual':    [1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0],
        'y_predicted': [1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0]
        }

df = pd.DataFrame(data)
confusion_matrix = pd.crosstab(df['y_actual'], df['y_predicted'], rownames=['Actual'], colnames=['Predicted'])

sn.heatmap(confusion_matrix, annot=True)
plt.show()

或者,您还可以通过设置 margins=True 在混淆矩阵的边距处添加总计。

代码:

import pandas as pd
import seaborn as sn
import matplotlib.pyplot as plt

data = {'y_actual':    [1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0],
        'y_predicted': [1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0]
        }

df = pd.DataFrame(data)
confusion_matrix = pd.crosstab(df['y_actual'], df['y_predicted'], rownames=['Actual'], colnames=['Predicted'], margins=True)

sn.heatmap(confusion_matrix, annot=True)
plt.show()

使用 pandas_ml 获取其他统计数据

您可以在 Python 中使用 pandas_ml 包打印其他统计数据(例如准确性)。您可以使用 PIP 安装 pandas_ml :

pip install pandas_ml

然后,您需要将以下语法添加到代码中:

confusion_matrix = ConfusionMatrix(df['y_actual'], df['y_predicted'])
confusion_matrix.print_stats()

获取其他统计信息的代码:

import pandas as pd
from pandas_ml import ConfusionMatrix

data = {'y_actual':    [1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0],
        'y_predicted': [1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0]
        }

df = pd.DataFrame(data)
confusion_matrix = ConfusionMatrix(df['y_actual'], df['y_predicted'])
confusion_matrix.print_stats()

运行代码,你将看到下面的测量值(请注意,如果在运行代码时遇到错误,可以考虑更改 pandas 的版本。例如,您可以使用以下命令将 pandas 的版本更改为 0.23.4:pip install pandas==0.23.4):

population: 12
P: 5
N: 7
PositiveTest: 6
NegativeTest: 6
TP: 4
TN: 5
FP: 2
FN: 1
ACC: 0.75

对于我们的示例:

  • TP = 真阳性 = 4
  • TN = 真阴性 = 5
  • FP = 误报 = 2
  • FN = 漏报 = 1

您还可以直接从混淆矩阵中观察 TP、TN、FP 和 FN:

TN


5

FP


2

FN


1

TP


4

精度为:

精度 = (TP+TN)/总体 = (4+5)/12 = 0.75

使用非数值数据

综上,您已经了解了如何使用数值数据创建混淆矩阵。但是,如果您的数据是非数字的呢?

例如,如果您的数据包含非数字值,例如“YES”和“NO”(而不是“1”和“0”),该怎么办?

在这种情况下:

  • YES = 1
  • NO = 0

因此,数据集将如下所示:

y_actualy

y_predicted

Yes

Yes

No

Yes

No

No

Yes

Yes

No

No

Yes

Yes

No

Yes

No

No

Yes

Yes

No

No

Yes

No

No

No

然后,您可以应用简单的映射练习,将“YES”映射到 1,将“NO”映射到 0。

具体而言,您需要将以下部分添加到代码中:

df['y_actual'] = df['y_actual'].map({'Yes': 1, 'No': 0})
df['y_predicted'] = df['y_predicted'].map({'Yes': 1, 'No': 0})

这是完整的 Python 代码的样子:

import pandas as pd
from pandas_ml import ConfusionMatrix

data = {'y_actual':    ['Yes', 'No',  'No', 'Yes', 'No', 'Yes', 'No',  'No', 'Yes', 'No', 'Yes', 'No'],
        'y_predicted': ['Yes', 'Yes', 'No', 'Yes', 'No', 'Yes', 'Yes', 'No', 'Yes', 'No', 'No',  'No']    
        }

df = pd.DataFrame(data)
df['y_actual'] = df['y_actual'].map({'Yes': 1, 'No': 0})
df['y_predicted'] = df['y_predicted'].map({'Yes': 1, 'No': 0})

confusion_matrix = ConfusionMatrix(df['y_actual'], df['y_predicted'])
confusion_matrix.print_stats()

然后,您将获得相同的统计数据:

population: 12
P: 5
N: 7
PositiveTest: 6
NegativeTest: 6
TP: 4
TN: 5
FP: 2
FN: 1
ACC: 0.75