- 在分类模型中,ROC曲线和AUC值经常作为衡量一个模型拟合程度的指标。那么怎么学习呢?
我也看了很多博客,但是最有效的方式莫过于去官网https://scikit-learn.org/stable/auto_examples/ensemble/plot_feature_transformation.html#sphx-glr-auto-examples-ensemble-plot-feature-transformation-py下载代码,自己动手试试比较好。
第一步:对官网给出的代码进行解读
- 头部的包先放一边
import numpy as np
np.random.seed(10)
import matplotlib.pyplot as plt
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import (RandomTreesEmbedding, RandomForestClassifier,
GradientBoostingClassifier)
from sklearn.preprocessing import OneHotEncoder
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_curve,auc
from sklearn.pipeline import make_pipeline
- 构建数据集
使用sklearn.datasets.make_classification(...)这个函数生成一些简单的分类训练样本,样本数量是80000。
再调用train_test_split()对样本进行分割操作
n_estimator = 10
X, y = make_classification(n_samples=80000)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5)
# It is important to train the ensemble of trees on a different subset
# of the training data than the linear regression model to avoid
# overfitting, in particular if the total number of leaves is
# similar to the number of training samples
X_train, X_train_lr, y_train, y_train_lr = train_test_split(
X_train, y_train, test_size=0.5)
- 训练数据
采用sklearn.ensemble.RandomTreesEmbedding(完全随机数的集成)把数据集映射到高维稀疏表示。n_estimators表示森林中树的个数,max_depth每棵树的最大深度。关于make_pipeline不是太懂,所以这部分......(过了吧)
rt = RandomTreesEmbedding(max_depth=3, n_estimators=n_estimator,
random_state=0)
rt_lm = LogisticRegression(max_iter=1000)
pipeline = make_pipeline(rt, rt_lm)
pipeline.fit(X_train, y_train)
y_pred_rt = pipeline.predict_proba(X_test)[:, 1]
- 计算ROC和AUC
采用roc_curve()计算ROC,
1,需要的输入参数:y_true真实的测试集的标签和y_score目标分数,可以是正样本类别的概率估计值,置信度或决策的非阈值度量(若某些分类器上的decision_function(x_test)的返回值scores)
2,得到的输出结果:fpr 误报率,tpr真正率,thresholds降低用于计算fpr和tpr的决策函数的阈值(ps:不同阈值下的真正率和假证率)
采用auc()计算AUC
fpr_rt_lm, tpr_rt_lm, _ = roc_curve(y_test, y_pred_rt)
roc_auc = auc(fpr_rf, tpr_rf)
- 画图
plt.figure(1)
plt.plot([0, 1], [0, 1], 'k--')
plt.plot(fpr_rt_lm, tpr_rt_lm, label='AUC=0.93')
plt.xlabel('False positive rate')
plt.ylabel('True positive rate')
plt.title('ROC curve')
plt.legend(loc='best')
plt.show()
类似图
这个图怎么看呢:
两个指标:
- 真正率:表示所有正例中,预测为正例的比例:
image.png
-
假正例:表示所有负例中,预测为正例的比例:
image.png
以FPR为横坐标,TPR为纵坐标,那么ROC曲线就是改变各种阈值后得到的所有坐标点(FPR,TPR)的连线,画出来如下。曲线越靠左上角,分类器越佳。
网上找的 参考
https://blog.csdn.net/qq_20011607/article/details/81712811