Python sklearn.metrics模块混淆矩阵常用函数

Python sklearn.metrics模块混淆矩阵常用函数,第1张

1.accuracy_score(y_true, y_pred, normalize=True, sample_weight=None)

参数分别为y实际类别、预测类别、返回值要求(True返回正确的样本占比,false返回的是正确分类的样本数量)

eg:

>>>import numpy as np

>>>from sklearn.metrics import accuracy_score

>>>y_pred = [0, 2, 1, 3]

>>>y_true = [0, 1, 2, 3]

>>>accuracy_score(y_true, y_pred)

0.5

>>>accuracy_score(y_true, y_pred, normalize=False)

2.classification_report(y_true, y_pred, labels=None, target_names=None, sample_weight=None, digits=2)

参数:真是类别,预测类别,目标类别名称

eg:

3.confusion_matrix(y_true, y_pred, labels=None, sample_weight=None)

输出为混淆矩阵

eg:

太多了,写3个常用的吧,具体参考help(metrics)

defcm_plot(y,yp):#参数为实际分类和预测分类

fromsklearn.metricsimportconfusion_matrix

#导入混淆矩阵函数

cm = confusion_matrix(y,yp)

#输出为混淆矩阵

importmatplotlib.pyplotasplt

#导入作图函数

plt.matshow(cm,cmap=plt.cm.Greens)

# 画混淆矩阵图,配色风格使用cm.Greens

plt.colorbar()

# 颜色标签

forxinrange(len(cm)):

foryinrange(len(cm)):

plt.annotate(cm[x,y],xy=(x,y),horizontalalignment='center',verticalalignment='center')

#annotate主要在图形中添加注释

# 第一个参数添加注释

# 第一个参数是注释的内容

# xy设置箭头尖的坐标

#horizontalalignment水平对齐

#verticalalignment垂直对齐

#其余常用参数如下:

# xytext设置注释内容显示的起始位置

# arrowprops 用来设置箭头

# facecolor 设置箭头的颜色

# headlength 箭头的头的长度

# headwidth 箭头的宽度

# width 箭身的宽度

plt.ylabel('True label')# 坐标轴标签

plt.xlabel('Predicted label')# 坐标轴标签

returnplt

#函数调用

cm_plot(train[:,3],tree.predict(train[:,:3])).show()

# -*- coding: UTF-8 -*-

"""绘制混淆矩阵图"""

import matplotlib.pyplot as plt

from sklearn.metrics import confusion_matrix

def confusion_matrix_plot_matplotlib(y_truth, y_predict, cmap=plt.cm.Blues):

    """Matplotlib绘制混淆矩阵图

    parameters

    ----------

        y_truth: 真实的y的值, 1d array

        y_predict: 预测的y的值, 1d array

        cmap: 画混淆矩阵图的配色风格, 使用cm.Blues,更多风格请参考官网

    """

    cm = confusion_matrix(y_truth, y_predict)

    plt.matshow(cm, cmap=cmap)  # 混淆矩阵图

    plt.colorbar()  # 颜色标签

    for x in range(len(cm)):  # 数据标签

        for y in range(len(cm)):

            plt.annotate(cm[x, y], xy=(x, y), horizontalalignment='center', verticalalignment='center')

    plt.ylabel('True label')  # 坐标轴标签

    plt.xlabel('Predicted label')  # 坐标轴标签

    plt.show()  # 显示作图结果

if __name__ == '__main__':

    y_truth = [1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]

    y_predict = [1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0]

    confusion_matrix_plot_matplotlib(y_truth, y_predict)

import pandas as pd

import numpy as np

from sklearn import linear_model

# 读取数据

sports = pd.read_csv(r'C:\Users\Administrator\Desktop\Run or Walk.csv')

# 提取出所有自变量名称

predictors = sports.columns[4:]

# 构建自变量矩阵

X = sports.ix[:,predictors]

# 提取y变量值

y = sports.activity

# 将数据集拆分为训练集和测试集

X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size = 0.25, random_state = 1234)

# 利用训练集建模

sklearn_logistic = linear_model.LogisticRegression()

sklearn_logistic.fit(X_train, y_train)

# 返回模型的各个参数

print(sklearn_logistic.intercept_, sklearn_logistic.coef_)

# 模型预测

sklearn_predict = sklearn_logistic.predict(X_test)

# 预测结果统计

pd.Series(sklearn_predict).value_counts()

-------------------------------------------------------------------------------------------------------------------------------------------

# 导入第三方模块

from sklearn import metrics

# 混淆矩阵

cm = metrics.confusion_matrix(y_test, sklearn_predict, labels = [0,1])

cm

Accuracy = metrics.scorer.accuracy_score(y_test, sklearn_predict)

Sensitivity = metrics.scorer.recall_score(y_test, sklearn_predict)

Specificity = metrics.scorer.recall_score(y_test, sklearn_predict, pos_label=0)

print('模型准确率为%.2f%%:' %(Accuracy*100))

print('正例覆盖率为%.2f%%' %(Sensitivity*100))

print('负例覆盖率为%.2f%%' %(Specificity*100))

-------------------------------------------------------------------------------------------------------------------------------------------

# 混淆矩阵的可视化

# 导入第三方模块

import seaborn as sns

import matplotlib.pyplot as plt

# 绘制热力图

sns.heatmap(cm, annot = True, fmt = '.2e',cmap = 'GnBu')

plt.show()

------------------------------------------------------------------------------------------------------------------------------------------

# 绘制ROC曲线

# 计算真正率和假正率

fpr,tpr,threshold = metrics.roc_curve(y_test, sm_y_probability)

# 计算auc的值 

roc_auc = metrics.auc(fpr,tpr)

# 绘制面积图

plt.stackplot(fpr, tpr, color='steelblue', alpha = 0.5, edgecolor = 'black')

# 添加边际线

plt.plot(fpr, tpr, color='black', lw = 1)

# 添加对角线

plt.plot([0,1],[0,1], color = 'red', linestyle = '--')

# 添加文本信息

plt.text(0.5,0.3,'ROC curve (area = %0.2f)' % roc_auc)

# 添加x轴与y轴标签

plt.xlabel('1-Specificity')

plt.ylabel('Sensitivity')

plt.show()

-------------------------------------------------------------------------------------------------------------------------------------------

#ks曲线   链接:https://www.jianshu.com/p/b1b1344bd99f  风控数据分析学习笔记(二)Python建立信用评分卡 -

fig, ax = plt.subplots()

ax.plot(1 - threshold, tpr, label='tpr')# ks曲线要按照预测概率降序排列,所以需要1-threshold镜像

ax.plot(1 - threshold, fpr, label='fpr')

ax.plot(1 - threshold, tpr-fpr,label='KS')

plt.xlabel('score')

plt.title('KS Curve')

plt.ylim([0.0, 1.0])

plt.figure(figsize=(20,20))

legend = ax.legend(loc='upper left')

plt.show()


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/yw/12189595.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-21
下一篇2023-05-21

发表评论

登录后才能评论

评论列表(0条)

    保存