python混淆矩阵代码

python
from sklearn.metrics import confusion_matrix import matplotlib.pyplot as plt import numpy as np # 实际标签 actual_labels = [0, 1, 0, 1, 0, 1, 0, 0, 1, 1] # 预测标签 predicted_labels = [0, 1, 0, 1, 0, 0, 1, 0, 1, 1] # 生成混淆矩阵 cm = confusion_matrix(actual_labels, predicted_labels) # 可视化混淆矩阵 plt.imshow(cm, interpolation='nearest', cmap=plt.cm.Blues) plt.title('Confusion Matrix') plt.colorbar() classes = ['Class 0', 'Class 1'] tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes) plt.yticks(tick_marks, classes) thresh = cm.max() / 2. for i in range(cm.shape[0]): for j in range(cm.shape[1]): plt.text(j, i, format(cm[i, j], 'd'), ha="center", va="center", color="white" if cm[i, j] > thresh else "black") plt.ylabel('True label') plt.xlabel('Predicted label') plt.tight_layout() plt.show()

这段代码使用了 sklearn.metrics 中的 confusion_matrix 函数来计算混淆矩阵,然后使用 matplotlib 来可视化混淆矩阵。

如果您想更详细地解释混淆矩阵,可以添加一些代码来计算准确率、召回率和 F1 分数。

python
from sklearn.metrics import confusion_matrix, accuracy_score, precision_score, recall_score, f1_score import matplotlib.pyplot as plt import numpy as np # 实际标签 actual_labels = [0, 1, 0, 1, 0, 1, 0, 0, 1, 1] # 预测标签 predicted_labels = [0, 1, 0, 1, 0, 0, 1, 0, 1, 1] # 生成混淆矩阵 cm = confusion_matrix(actual_labels, predicted_labels) # 计算准确率 accuracy = accuracy_score(actual_labels, predicted_labels) print("Accuracy:", accuracy) # 计算精确度 precision = precision_score(actual_labels, predicted_labels) print("Precision:", precision) # 计算召回率 recall = recall_score(actual_labels, predicted_labels) print("Recall:", recall) # 计算 F1 分数 f1 = f1_score(actual_labels, predicted_labels) print("F1 Score:", f1) # 可视化混淆矩阵 plt.imshow(cm, interpolation='nearest', cmap=plt.cm.Blues) plt.title('Confusion Matrix') plt.colorbar() classes = ['Class 0', 'Class 1'] tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes) plt.yticks(tick_marks, classes) thresh = cm.max() / 2. for i in range(cm.shape[0]): for j in range(cm.shape[1]): plt.text(j, i, format(cm[i, j], 'd'), ha="center", va="center", color="white" if cm[i, j] > thresh else "black") plt.ylabel('True label') plt.xlabel('Predicted label') plt.tight_layout() plt.show()

这段代码添加了准确率、精确度、召回率和 F1 分数的计算,并将结果打印出来。