随着机器学习和数据挖掘的流行,越来越多的数据科学家和研究人员开始使用Python这种高级编程语言来处理和分析数据,并且Python的直观性和易用性使其在深度学习和人工智能的领域中得到广泛应用。然而,许多初学者在使用Python时遇到了一些困难,其中之一就是混淆矩阵的难题。在本文中,我们将介绍Python中混淆矩阵的使用方法以及一些处理混淆矩阵时有用的技巧。
一、什么是混淆矩阵
在深度学习和数据挖掘中,混淆矩阵是一种矩形表格,用于比较预测结果和实际结果之间的差异。该矩阵显示了分类算法的性能,包括分类算法的准确性、错误率、精度和召回率等重要指标。混淆矩阵通常使分类器的性能可视化,并为分类器的改进和优化提供预测结果的主要参考。
通常情况下,混淆矩阵由四个参数组成:
- 真阳性(TP):分类算法正确地将正类预测为正类。
- 假阴性(FN):分类算法错误地将正类预测为负类。
- 假阳性(FP):分类算法错误地将负类预测为正类。
- 真阴性(TN):分类算法正确地将负类预测为负类。
二、如何计算混淆矩阵
Python中的scikit-learn库提供了一个方便的函数来计算混淆矩阵。该函数称为confusion_matrix(),可以作为分类器和测试集的真实结果之间的输入,并返回混淆矩阵的参数值。该函数地语法如下:
from sklearn.metrics import confusion_matrix
confusion_matrix(y_true, y_pred, labels=None, sample_weight=None)
其中,y_true表示分类器的正确结果,y_pred表示分类器的预测结果,labels表示类标签的名称(如果不提供,则默认为从y_true和y_pred中提取的值),sample_weight表示每个样本的权重(如果不需要,则不用设置该参数)。
例如,假设我们需要计算以下数据的混淆矩阵:
y_true = [1, 0, 1, 2, 0, 1]
y_pred = [1, 0, 2, 1, 0, 2]
为了计算混淆矩阵,可以使用如下代码:
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_true, y_pred)
print(cm)
输出结果为:
array([[2, 0, 0],
[0, 1, 2],
[0, 1, 0]])
即该混淆矩阵显示出“1”被正确分类为“1”的情况有2次,“0”被正确分类为“0”的情况有1次,“2”被正确分类为“2”的情况有0次,“1”被错误分类为“2”的情况有2次,“2”被错误分类为“1”的情况有1次,“0”被错误分类为“2”的情况有1次。
三、展示混淆矩阵
有许多情况下,我们需要更好的可视化混淆矩阵。Python中的matplotlib库可以使混淆矩阵可视化。下面是的Python代码,它使用了matplotlib库和sklearn.metrics来实现混淆矩阵的可视化。
import itertools
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
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')
# Compute confusion matrix
cnf_matrix = confusion_matrix(y_test, y_pred)
np.set_printoptions(precision=2)
# Plot non-normalized confusion matrix
plt.figure()
plot_confusion_matrix(cnf_matrix, classes=class_names,
title='Confusion matrix, without normalization')
# Plot normalized
.........................................................