网站首页 > 文章中心 > 其它

python混淆矩阵函数

作者:小编 更新时间:2023-09-20 18:15:57 浏览量:140人看过

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

①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

accuracy_score(y_true, y_pred)

accuracy_score(y_true, y_pred, normalize=False)

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

输出为混淆矩阵

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

#函数调用

Python hmmlearn中的混淆矩阵是怎么表示的

hmmlearn这个库有三种模型,分别是Gaussian,Multinomial和GMMHMM.这三种模型对应的就是三种emission

matrix(即混淆矩阵,也就是隐状态到观察态的概率).Gaussian就是说混淆矩阵是一个高斯分布,即观察态是连续的.Multinomiual就是说混淆矩阵事一个Multibimiual

distribution,即观察态势离散的.GMMHMM则是说混淆矩阵是遵循gaussinan

mixture

分布,也是连续的.

题主问如何把混淆矩阵输入到模型里面.首先你要确定你的混淆矩阵的类型.对于Gaussian类型,就是把你希望的

mean和variance值放到模型里面.我就直接把文档里面的例子搬过来,例子里是建立了一个高斯分布的隐马尔科夫模型.

import

numpy

as

np

from

hmmlearn

hmm

#一个隐马尔科夫模型由(p向量,状态转移矩阵,混淆矩阵)来定义.

startprob

=

0.1])

#

定义初始状态的概率

transmat

0.1],

means

np.array([[0.0,

0.0],

①.0.0]])

#定义混淆矩阵的均值

covars

①.))#

定义混淆矩阵的方差

model

"full",

startprob,

transmat)#

定义一个混淆矩阵为高斯分布的隐马尔科夫模型.

这里'full'的意思就是说你输入的方差矩阵每个元素都给出了,不是一个只是对角线上的元素为0的矩阵

model.means_

model.covars_

covars#把你希望的均值方差输入你定义的模型里面,到此你就把混淆矩阵输入进模型了

X,

Z

model.sample(100)

对于Multinomial

GMM,我还没用,不过Multinomial应该是需要你自己手动输入隐状态到观察态的概率的,而GMM应该是和Gaussian类型类似,只是需要多输入一个权重因子.

对于第二个问题,covariance_type意思是你的混淆矩阵的covariance

matrix是什么类型,比如若只是对角线上的元素不为0,则把covariance_type设为'diag'.

python评分卡之LR及混淆矩阵、ROC

import pandas as pd

from sklearn import linear_model

# 读取数据

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

# 提取出所有自变量名称

# 构建自变量矩阵

X = sports.ix[:,predictors]

# 提取y变量值

y = sports.activity

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

# 利用训练集建模

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)

# 混淆矩阵的可视化

import seaborn as sns

import matplotlib.pyplot as plt

# 绘制热力图

plt.show()

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

# 绘制ROC曲线

# 计算真正率和假正率

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

# 计算auc的值?

roc_auc = metrics.auc(fpr,tpr)

# 绘制面积图

# 添加边际线

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

# 添加对角线

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

# 添加文本信息

# 添加x轴与y轴标签

plt.xlabel('1-Specificity')

plt.ylabel('Sensitivity')

#ks曲线? ?链接:? 风控数据分析学习笔记(二)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])

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

python3.5做分类时,混淆矩阵加在哪一步

preface:做着最近的任务,对数据处理,做些简单的提特征,用机器学习算法跑下程序得出结果,看看哪些特征的组合较好,这一系列流程必然要用到很多函数,故将自己常用函数记录上.应该说这些函数基本上都会用到,像是数据预处理,处理完了后特征提取、降维、训练预测、通过混淆矩阵看分类效果,得出报告.

①输入

从数据集开始,提取特征转化为有标签的数据集,转为向量.拆分成训练集和测试集,这里不多讲,在上一篇博客中谈到用StratifiedKFold()函数即可.在训练集中有data和target开始.

[python]?view plain?copy

def?my_preprocessing(train_data):

from?sklearn?import?preprocessing

return?X_normalized

def?my_feature_selection(data,?target):

from?sklearn.feature_selection?import?SelectKBest

return?data_new

def?my_PCA(data):#data?without?target,?just?train?data,?withou?train?target.

from?sklearn?import?decomposition

pca_sklearn?=?decomposition.PCA()

pca_sklearn.fit(data)

main_var?=?pca_sklearn.explained_variance_

import?matplotlib.pyplot?as?plt

plt.plot(main_var[:n])

def?clf_train(data,target):

from?sklearn?import?svm

#from?sklearn.linear_model?import?LogisticRegression

clf?=?svm.SVC(C=100,kernel="rbf",gamma=0.001)

clf.fit(data,target)

#clf_LR?=?LogisticRegression()

#clf_LR.fit(x_train,?y_train)

#y_pred_LR?=?clf_LR.predict(x_test)

return?clf

def?my_confusion_matrix(y_true,?y_pred):

from?sklearn.metrics?import?confusion_matrix

labels?=?list(set(y_true))

conf_mat?=?confusion_matrix(y_true,?y_pred,?labels?=?labels)

print?"confusion_matrix(left?labels:?y_true,?up?labels:?y_pred):"

print?"labels\t",

for?i?in?range(len(labels)):

print?labels[i],"\t",

print

for?i?in?range(len(conf_mat)):

print?i,"\t",

for?j?in?range(len(conf_mat[i])):

print?conf_mat[i][j],'\t',

def?my_classification_report(y_true,?y_pred):

from?sklearn.metrics?import?classification_report

print?"classification_report(left:?labels):"

print?classification_report(y_true,?y_pred)

my_preprocess()函数:

my_feature_selection()函数:

my_PCA()函数:

主要用来观察前多少个特征是主要特征,并且画图.看看前多少个特征占据主要部分.

clf_train()函数:

可用多种机器学习算法,如SVM, LR, RF, GBDT等等很多,其中像SVM需要调参数的,有专门调试参数的函数如StratifiedKFold()(见前几篇博客).以达到最优.

my_confusion_matrix()函数:

主要是针对预测出来的结果,和原来的结果对比,算出混淆矩阵,不必自己计算.其对每个类别的混淆矩阵都计算出来了,并且labels参数默认是排序了的.

my_classification_report()函数:

主要通过sklearn.metrics函数中的classification_report()函数,针对每个类别给出详细的准确率、召回率和F-值这三个参数和宏平均值,用来评价算法好坏.另外ROC曲线的话,需要是对二分类才可以.多类别似乎不行.

主要参考sklearn官网

python是否有绘制混淆矩阵的函数,怎么来实现

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

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)

以上就是土嘎嘎小编为大家整理的python混淆矩阵函数相关主题介绍,如果您觉得小编更新的文章只要能对粉丝们有用,就是我们最大的鼓励和动力,不要忘记讲本站分享给您身边的朋友哦!!

版权声明:倡导尊重与保护知识产权。未经许可,任何人不得复制、转载、或以其他方式使用本站《原创》内容,违者将追究其法律责任。本站文章内容,部分图片来源于网络,如有侵权,请联系我们修改或者删除处理。

编辑推荐

热门文章