1.混淆矩阵
接受者操作特征(Receiver Operating Characteristic Curve,ROC)曲线是显示分类器真正率和假正率之间折中
的⼀种图形化⽅法,也是最常⽤的评估分类模型好坏的可视化图形,在介绍ROC曲线之前,先了解下混淆矩阵。
1.1 原理
混淆矩阵是用来总结一个分类器结果的矩阵。对于k元分类,其实它就是一个k x k的表格,用来记录分类器的预测结果。 对于最常见的二元分类来说,它的混淆矩阵是2乘2的。
假设有一批test样本,这些样本只有两种类别:正例和反例。机器学习算法预测类别如下图(左半部分预测类别为正例,右半部分预测类别为反例),而样本中真实的正例类别在上半部分,下半部分为真实的反例。 如下图:
预测值为正例,记为P(Positive)
预测值为反例,记为N(Negative)
预测值与真实值相同,记为T(True)
预测值与真实值相反,记为F(False)
注: F1 score 来源:
1/ ((1/精准率)+ (1/召回率))
由于精准率,召回率最大1,此值最大0.5,会乘2,使其在0-1区间。
2. ROC曲线
横坐标:1-负样本的召回率 假正率:负样本中预测成正样本的概率
纵坐标:正样本的召回率 真正率:正样本中预测为正样本的概率
3. 绘制ROC曲线
3.1 导入波士顿房价,获取X,y
将大于均价的房价映射为1,低于映射为0,构成分类问题,并初步用逻辑斯蒂预测和评分。
import numpy as np
import pandas as pd
from pandas import Series, DataFrameimport matplotlib.pyplot as plt
%matplotlib inlinefrom sklearn.datasets import load_boston # 获取波士顿房价数据
X, y = load_boston(return_X_y=True) # 获取特征向量集X和目标房价 y
展示y
import seaborn as sns
sns.set()
sns.distplot(y)
根据均值将y映射为0和1
threshold = np.median(y)
target = Series(y).map(lambda x: (x>threshold)*1)
target.value_counts().plot(kind='bar')
image.png
逻辑斯蒂建模
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split # 获取拆分函数
X_train, X_test, y_train, y_test = train_test_split(X, target, test_size=0.2, random_state=1) # 拆分样本集,拆分比例0.8:0.2,并做随机种子,下次拆分如果还用随机种子1,可以得到一样的随机结果。
预测并评分
lr = LogisticRegression()
lr.fit(X_train, y_train)
y_ = lr.predict(X_test)
y_
from sklearn.metrics import accuracy_score
accuracy_score(y_, y_test) # 0.8725490196078431
准确率评分,即预测正确的占总数的比例。如果样本比例不均,此评分高看不出来对两种预测样本的准确度。
比如:99个男生,1个女生,预测为100个男生,准确率99%,但对女生的预测率为0,所以需要引入其他评分指标。
3.2 绘制混淆矩阵
(1)导包,准备数据
from sklearn.metrics import confusion_matrix # 导入混淆矩阵的包
y_.size # 102
cm = confusion_matrix(y_test, y_)
cm # array([[44, 3], [10, 45]], dtype=int64)
tn, fp, fn, tp = confusion_matrix(y_test, y_).ravel()
(tn, fp, fn, tp) # (44, 3, 10, 45)
(2)绘图展示
sns.set_style('white') # 设置全局的图的背景为白色
def show_cm(y_true, y_test):
tn, fp, fn, tp = confusion_matrix(y_test, y_true).ravel()
plt.imshow(cm, cmap=plt.cm.Blues)
plt.xticks([0,1])
plt.yticks([0,1])
plt.xlabel("Predict")
plt.ylabel("True")plt.text(x=0-0.1, y=0, s="TP:"+str(tp), color='black') # 设置文本,位置由x,y确定,x,y为相对位置。0-1
plt.text(x=1-0.1, y=0, s="FN:"+str(fn), color='black')
plt.text(x=0-0.1, y=1, s="FP:"+str(fp), color='black')
plt.text(x=1-0.1, y=1, s="TN:"+str(tn), >color='black')查准率 = tp/(tp + fp)
召回率 = tp/(tp + tn)
print("查准率:",查准率)
print("召回率:",召回率)
plt.show()
绘图
show_cm(y_test, y_)
image.png
(3)对预测阀值进行修改并展示混淆矩阵
原理,逻辑斯蒂回归,根据概率判断正负样本,阀值0.5,0的概率大于1时,预测为0.
对正样本的预测阈值进行修改,查看变换
y1_ = (lr.predict_proba(X_test)[:,1] > 0.7)*1 #通过predict_proba获取每个预测值的概率,如果第2列的概率大于0.7,则为1,小于为0. 即增大正样本的概率判断的阈值。
3.3 f1_score评分
3.4 绘制 ROC曲线
3.4.1计算评分
绘制曲线
from sklearn import metrics
def show_roc(y_test, scores, pos_label):
fpr, tpr, thresholds = metrics.roc_curve(y_test, scores, pos_label=pos_label)
plt.plot(fpr, tpr, color='green')
plt.plot(np.linspace(0,1,10), np.linspace(0,1,10), color='red', ls='--')
plt.xlabel("FPR")
plt.ylabel("TPR")
plt.title("LR ROC ")
plt.show()
绘制ROC曲线
绘制不同情况下的ROC曲线
参数c更小
高斯分布朴素贝叶斯预测
from sklearn.naive_bayes import GaussianNB
gnb = GaussianNB()
gnb.fit(X_train, y_train)
scores3 = gnb.predict_proba(X_test)[:,1]
show_roc(y_test, scores3, 1)
3.5 绘制ROC曲线
import numpy as np
from sklearn import metrics
y = np.array([1, 1, 2, 2])
scores = np.array([0.1, 0.4, 0.35, 0.8])
fpr, tpr, thresholds = metrics.roc_curve(y, scores, pos_label=2)
fpr, tpr, thresholds # 列方向看,当阈值为1,8时,预测FPR和TPR的值都为0,当阈值为0.8时,FPR为0,TPR为0.5.
(array([0. , 0. , 0.5, 0.5, 1. ]),
array([0. , 0.5, 0.5, 1. , 1. ]),
array([1.8 , 0.8 , 0.4 , 0.35, 0.1 ]))
import matplotlib.pyplot as plt
%matplotlib inline
plt.plot(fpr, tpr, color='blue', lw=3)
plt.xlabel('FPR')
plt.ylabel('TPR')