一、Python绘制混淆矩阵
混淆矩阵是用来对分类器进行评价的一种矩阵,它展示了分类器在测试集上的预测效果。我们可以使用Python来画出混淆矩阵。 首先需要明确的是,混淆矩阵的行表示实际类别,列表示预测类别。例如,对于一个二分类问题,其中一个类别为阳性,另一个类别为阴性,如果将阳性预测为阴性,则是一个False Negative(FN);如果将阴性预测为阳性,则是一个False Positive(FP)。同理,如果将阳性预测为阳性,则是一个True Positive(TP);如果将阴性预测为阴性,则是一个True Negative(TN)。
| | Predicted No | Predicted Yes |
|---------|-------------------|-------------------|
| No | TN | FP |
| Yes | FN | TP |
我们可以使用Python中的sklearn库来获取分类器的混淆矩阵。下面是一个代码示例:
from sklearn.metrics import confusion_matrix
y_true = [0, 1, 0, 1]
y_pred = [1, 1, 0, 0]
confusion_matrix(y_true, y_pred)
运行结果如下:
array([[1, 1],
[1, 1]])
上方的结果表示,将0(No)预测为1(Yes)的次数为1,将1(Yes)预测为0(No)的次数为1,将0(No)预测为0(No)的次数为1,将1(Yes)预测为1(Yes)的次数为1。
二、混淆矩阵怎么画 Python
在了解了混淆矩阵的表示后,我们可以使用Python来画出混淆矩阵的可视化图。下方是一个代码示例:
import numpy as np
import itertools
import matplotlib.pyplot as plt
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues):
"""
将混淆矩阵画出
"""
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print("Normalized confusion matrix")
else:
print('Confusion matrix, without normalization')
print(cm)
# 画图
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
# 循环遍历混淆矩阵并填上数字
fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, format(cm[i, j], fmt),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
plt.show()
# 测试数据
y_true = [0, 1, 0, 1]
y_pred = [1, 1, 0, 0]
# 获取混淆矩阵
cnf_matrix = confusion_matrix(y_true, y_pred)
# 绘制混淆矩阵
plot_confusion_matrix(cnf_matrix, classes=[0, 1])
运行结果如下: 上方的图表清晰地展示了混淆矩阵的各个元素以及数字标注。
三、Python混淆矩阵
要理解Python绘制混淆矩阵的原理,首先需要知道Python混淆矩阵的运作机制。混淆矩阵是指,将预测分类的结果与测试实际结果进行比较的矩阵。它是在机器学习数学领域中,用于衡量分类器(也称模型)质量的矩阵。 在Python中,我们可以使用许多不同的Python库来绘制混淆矩阵。常见的有matplotlib和seaborn等。这些库提供了一些内置的函数,用于绘制各种矩阵和图表。其中matplotlib.pyplot是Python中最常用的数据可视化库之一,因此下文将使用它来完善混淆矩阵的可视化图表。
四、Python混淆矩阵代码
下面是一个Python绘制混淆矩阵的代码示例:
import matplotlib.pyplot as plt
import numpy as np
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues):
"""
绘制混淆矩阵
"""
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print("Normalized confusion matrix")
else:
print('Confusion matrix, without normalization')
print(cm)
# 画图
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
# 设定横纵坐标及标签
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
# 标注数字
fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, format(cm[i, j], fmt),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
# 设置其他参数
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
plt.show()
# 测试数据
y_true = [0, 1, 0, 1]
y_pred = [1, 1, 0, 0]
# 获取混淆矩阵
confusion_matrix = confusion_matrix(y_true, y_pred)
# 绘制混淆矩阵
class_names = ['0', '1'] # 类别名称
plot_confusion_matrix(confusion_matrix, classes=class_names)
五、Python生成混淆矩阵
要生成Python混淆矩阵,我们需要预测的结果和实际的结果。如果我们善用该矩阵的可视化表示形式,我们就可以清晰地了解分类器的表现,并根据我们的真实数据来更新算法。 下面是一个Python生成混淆矩阵的代码示例:
from sklearn.metrics import confusion_matrix
import seaborn as sns
# 获得测试数据
predictions = [0, 1, 1, 0, 1, 1]
true_classes = [1, 0, 1, 1, 1, 0]
# 获取混淆矩阵并利用热力图展示
cm = confusion_matrix(true_classes, predictions)
sns.heatmap(cm, annot=True, fmt='d', cmap='Reds')
六、Python画混淆矩阵
现在我们已经掌握了Python生成和绘制混淆矩阵的基本原理,下面这个代码示例演示了如何用Python画混淆矩阵:
from sklearn.metrics import confusion_matrix, classification_report
import seaborn as sns
import pandas as pd
# 定义画图函数
def plot_confusion_matrix(y_true, y_pred, cmap="Blues"):
# 计算混淆矩阵数据
cm = confusion_matrix(y_true, y_pred)
cm_sum = np.sum(cm, axis=1, keepdims=True)
cm_perc = cm / cm_sum.astype(float) * 100
annot = np.empty_like(cm).astype(str)
nrows, ncols = cm.shape
for i in range(nrows):
for j in range(ncols):
c = cm[i, j]
p = cm_perc[i, j]
if i == j:
s = cm_sum[i]
annot[i, j] = '%.1f%%\n%d/%d' % (p, c, s)
elif c == 0:
annot[i, j] = ''
else:
annot[i, j] = '%.1f%%\n%d' % (p, c)
cm = pd.DataFrame(cm, index=['True A', 'True B'], columns=['Pred A', 'Pred B'])
cm.index.name = 'Actual'
cm.columns.name = 'Predicted'
# 设置画布
fig, ax = plt.subplots(figsize=(2.5, 2.5))
ax.text(-1.2, 1.2, 'Confusion\nMatrix', fontsize=12, transform=ax.transAxes)
# 设置其它参数
sns.heatmap(cm, annot=annot, fmt='', cmap=cmap, ax=ax)
plt.show()
# 测试数据
actuals = ['A', 'B', 'B', 'A', 'A', 'B']
predicted = ['A', 'B', 'B', 'A', 'A', 'A']
# 画混淆矩阵
plot_confusion_matrix(actuals, predicted)
上方的混淆矩阵清晰且易于理解,对于评估分类结果具有重要意义。