使用python绘制混淆矩阵

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-14 04:48:28

使用python绘制混淆矩阵

# 可视化分类器性能
# load libraries
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn import datasets
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
import pandas as pd

# load data 加载数据
iris = datasets.load_iris()

# create feature matrix
features = iris.data

# create target vector
target = iris.target

# create list of target class names
class_names = iris.target_names

# split into training and test sets
# 创建 训练集 测试集
features_train, features_test, target_train, target_test = train_test_split(features, target, random_state=1)

# create logistic regression 逻辑回归
classifier = LogisticRegression()

# train model and make predictions 做出预测
target_predicted = classifier.fit(features_train, target_train).predict(features_test)

# create confusion matrix 创建混淆矩阵
matrix = confusion_matrix(target_test, target_predicted)

# create pandas dataframe   创建数据集
dataframe = pd.DataFrame(matrix, index=class_names, columns=class_names)

# create heatmap 绘制热力图
sns.heatmap(dataframe, annot=True, cbar=None, cmap="Blues")
plt.title("Confusion Matrix"), plt.tight_layout()
plt.ylabel("True Class"), plt.xlabel("Predicted Class")
plt.show()

在这里插入图片描述

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!