从ROC曲线能看出什么
时间: 2024-06-09 12:12:18 浏览: 16
ROC曲线是一种常用的二分类模型性能评估工具,用于比较模型在正负样本分类上的性能表现。ROC曲线描述了分类器在不同阈值下真阳性率(True Positive Rate,TPR)和假阳性率(False Positive Rate,FPR)的变化情况。其中,TPR表示所有正例中被模型正确预测为正例的比例,FPR表示所有反例中被模型错误预测为正例的比例。ROC曲线越接近左上角,说明模型的性能越好;曲线越靠近对角线,则该模型的性能越差。ROC曲线下面积(Area Under Curve,AUC)越大,说明该模型的性能越好。
相关问题
对iris数据集做ROC曲线和AUC
好的,以下是针对iris数据集做ROC曲线和AUC的步骤:
1. 导入数据集
首先,我们需要导入iris数据集。可以使用sklearn库中的load_iris函数来导入数据集。
```python
from sklearn.datasets import load_iris
iris = load_iris()
X = iris.data
y = iris.target
```
2. 数据预处理
为了方便绘制ROC曲线,我们需要将数据集分成训练集和测试集,并将类别标签转换为二元标签。
```python
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import label_binarize
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 将类别标签转换为二元标签
y_train_binary = label_binarize(y_train, classes=[0, 1, 2])
y_test_binary = label_binarize(y_test, classes=[0, 1, 2])
```
3. 训练模型
在这里,我们使用Random Forest Classifier作为分类器。训练模型的代码如下:
```python
from sklearn.ensemble import RandomForestClassifier
# 创建分类器
clf = RandomForestClassifier(n_estimators=50, random_state=42)
# 训练模型
clf.fit(X_train, y_train_binary)
```
4. 绘制ROC曲线和计算AUC
接下来,我们可以使用sklearn库中的roc_curve和auc函数来绘制ROC曲线和计算AUC值。代码如下:
```python
from sklearn.metrics import roc_curve, auc
# 预测测试集的类别概率值
y_score = clf.predict_proba(X_test)
# 计算每个类别的ROC曲线和AUC值
fpr = dict()
tpr = dict()
roc_auc = dict()
for i in range(3):
fpr[i], tpr[i], _ = roc_curve(y_test_binary[:, i], y_score[:, i])
roc_auc[i] = auc(fpr[i], tpr[i])
# 计算Macro-Averaging和Micro-Averaging的AUC值
fpr["micro"], tpr["micro"], _ = roc_curve(y_test_binary.ravel(), y_score.ravel())
roc_auc["micro"] = auc(fpr["micro"], tpr["micro"])
all_fpr = np.unique(np.concatenate([fpr[i] for i in range(3)]))
# 绘制ROC曲线
plt.figure(figsize=(8, 6))
for i in range(3):
plt.plot(fpr[i], tpr[i], lw=2, label='ROC curve of class %d (AUC = %0.2f)' % (i+1, roc_auc[i]))
plt.plot(fpr["micro"], tpr["micro"], label='Micro-Avg ROC curve (AUC = {0:0.2f})'\
''.format(roc_auc["micro"]), color='deeppink', linestyle=':', linewidth=4)
plt.plot([0, 1], [0, 1], 'k--', lw=2)
plt.xlim([-0.05, 1.05])
plt.ylim([-0.05, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC curve for iris dataset')
plt.legend(loc="lower right")
plt.show()
```
运行上述代码,我们就可以得到iris数据集的ROC曲线和AUC值。
![image](https://user-images.githubusercontent.com/74955102/135929577-0dd1d8f9-9b7f-4f1b-88a9-7e2d6bd2c9d0.png)
从图中可以看出,三个类别的ROC曲线都很接近左上角,说明模型的分类能力很好。同时,Micro-Averaging的AUC值为0.98,说明模型的总体分类能力也很好。
给定一份二分类的数据,分别用决策树,贝叶斯,支持向量机,knn算法进行分类器构建,并绘制这四个方法的pr曲线和roc曲线,确定较优模型
以下是针对给定的二分类数据使用决策树、贝叶斯、支持向量机和knn算法进行分类器构建,并绘制pr曲线和roc曲线的步骤和代码:
1. 导入所需的库和数据集
```python
import numpy as np
import pandas as pd
from sklearn import tree, naive_bayes, svm, neighbors
from sklearn.metrics import precision_recall_curve, roc_curve, auc
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
# 导入数据集
data = pd.read_csv('data.csv')
X = data.iloc[:, :-1]
y = data.iloc[:, -1]
```
2. 划分训练集和测试集
```python
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
```
3. 构建决策树分类器并绘制pr曲线和roc曲线
```python
# 构建决策树分类器
clf_dt = tree.DecisionTreeClassifier()
clf_dt.fit(X_train, y_train)
# 预测测试集结果
y_pred_dt = clf_dt.predict_proba(X_test)[:, 1]
# 计算pr曲线和roc曲线
precision_dt, recall_dt, _ = precision_recall_curve(y_test, y_pred_dt)
fpr_dt, tpr_dt, _ = roc_curve(y_test, y_pred_dt)
roc_auc_dt = auc(fpr_dt, tpr_dt)
# 绘制pr曲线和roc曲线
plt.figure()
plt.step(recall_dt, precision_dt, color='b', alpha=0.2, where='post')
plt.fill_between(recall_dt, precision_dt, step='post', alpha=0.2, color='b')
plt.xlabel('Recall')
plt.ylabel('Precision')
plt.ylim([0.0, 1.05])
plt.xlim([0.0, 1.0])
plt.title('PR Curve (AUC = %0.2f) - Decision Tree' % roc_auc_dt)
plt.figure()
plt.plot(fpr_dt, tpr_dt, color='darkorange', lw=2, label='ROC curve (area = %0.2f)' % roc_auc_dt)
plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC Curve - Decision Tree')
plt.legend(loc="lower right")
```
4. 构建贝叶斯分类器并绘制pr曲线和roc曲线
```python
# 构建贝叶斯分类器
clf_nb = naive_bayes.GaussianNB()
clf_nb.fit(X_train, y_train)
# 预测测试集结果
y_pred_nb = clf_nb.predict_proba(X_test)[:, 1]
# 计算pr曲线和roc曲线
precision_nb, recall_nb, _ = precision_recall_curve(y_test, y_pred_nb)
fpr_nb, tpr_nb, _ = roc_curve(y_test, y_pred_nb)
roc_auc_nb = auc(fpr_nb, tpr_nb)
# 绘制pr曲线和roc曲线
plt.figure()
plt.step(recall_nb, precision_nb, color='b', alpha=0.2, where='post')
plt.fill_between(recall_nb, precision_nb, step='post', alpha=0.2, color='b')
plt.xlabel('Recall')
plt.ylabel('Precision')
plt.ylim([0.0, 1.05])
plt.xlim([0.0, 1.0])
plt.title('PR Curve (AUC = %0.2f) - Naive Bayes' % roc_auc_nb)
plt.figure()
plt.plot(fpr_nb, tpr_nb, color='darkorange', lw=2, label='ROC curve (area = %0.2f)' % roc_auc_nb)
plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC Curve - Naive Bayes')
plt.legend(loc="lower right")
```
5. 构建支持向量机分类器并绘制pr曲线和roc曲线
```python
# 构建支持向量机分类器
clf_svm = svm.SVC(probability=True)
clf_svm.fit(X_train, y_train)
# 预测测试集结果
y_pred_svm = clf_svm.predict_proba(X_test)[:, 1]
# 计算pr曲线和roc曲线
precision_svm, recall_svm, _ = precision_recall_curve(y_test, y_pred_svm)
fpr_svm, tpr_svm, _ = roc_curve(y_test, y_pred_svm)
roc_auc_svm = auc(fpr_svm, tpr_svm)
# 绘制pr曲线和roc曲线
plt.figure()
plt.step(recall_svm, precision_svm, color='b', alpha=0.2, where='post')
plt.fill_between(recall_svm, precision_svm, step='post', alpha=0.2, color='b')
plt.xlabel('Recall')
plt.ylabel('Precision')
plt.ylim([0.0, 1.05])
plt.xlim([0.0, 1.0])
plt.title('PR Curve (AUC = %0.2f) - SVM' % roc_auc_svm)
plt.figure()
plt.plot(fpr_svm, tpr_svm, color='darkorange', lw=2, label='ROC curve (area = %0.2f)' % roc_auc_svm)
plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC Curve - SVM')
plt.legend(loc="lower right")
```
6. 构建knn分类器并绘制pr曲线和roc曲线
```python
# 构建knn分类器
clf_knn = neighbors.KNeighborsClassifier()
clf_knn.fit(X_train, y_train)
# 预测测试集结果
y_pred_knn = clf_knn.predict_proba(X_test)[:, 1]
# 计算pr曲线和roc曲线
precision_knn, recall_knn, _ = precision_recall_curve(y_test, y_pred_knn)
fpr_knn, tpr_knn, _ = roc_curve(y_test, y_pred_knn)
roc_auc_knn = auc(fpr_knn, tpr_knn)
# 绘制pr曲线和roc曲线
plt.figure()
plt.step(recall_knn, precision_knn, color='b', alpha=0.2, where='post')
plt.fill_between(recall_knn, precision_knn, step='post', alpha=0.2, color='b')
plt.xlabel('Recall')
plt.ylabel('Precision')
plt.ylim([0.0, 1.05])
plt.xlim([0.0, 1.0])
plt.title('PR Curve (AUC = %0.2f) - KNN' % roc_auc_knn)
plt.figure()
plt.plot(fpr_knn, tpr_knn, color='darkorange', lw=2, label='ROC curve (area = %0.2f)' % roc_auc_knn)
plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC Curve - KNN')
plt.legend(loc="lower right")
```
7. 比较四个分类器的pr曲线和roc曲线,确定较优模型
```python
# 绘制四个分类器的pr曲线
plt.figure()
plt.step(recall_dt, precision_dt, color='b', alpha=0.2, where='post', label='Decision Tree')
plt.fill_between(recall_dt, precision_dt, step='post', alpha=0.2, color='b')
plt.step(recall_nb, precision_nb, color='g', alpha=0.2, where='post', label='Naive Bayes')
plt.fill_between(recall_nb, precision_nb, step='post', alpha=0.2, color='g')
plt.step(recall_svm, precision_svm, color='r', alpha=0.2, where='post', label='SVM')
plt.fill_between(recall_svm, precision_svm, step='post', alpha=0.2, color='r')
plt.step(recall_knn, precision_knn, color='c', alpha=0.2, where='post', label='KNN')
plt.fill_between(recall_knn, precision_knn, step='post', alpha=0.2, color='c')
plt.xlabel('Recall')
plt.ylabel('Precision')
plt.ylim([0.0, 1.05])
plt.xlim([0.0, 1.0])
plt.title('PR Curve')
plt.legend(loc="lower right")
# 绘制四个分类器的roc曲线
plt.figure()
plt.plot(fpr_dt, tpr_dt, color='b', lw=2, label='Decision Tree (area = %0.2f)' % roc_auc_dt)
plt.plot(fpr_nb, tpr_nb, color='g', lw=2, label='Naive Bayes (area = %0.2f)' % roc_auc_nb)
plt.plot(fpr_svm, tpr_svm, color='r', lw=2, label='SVM (area = %0.2f)' % roc_auc_svm)
plt.plot(fpr_knn, tpr_knn, color='c', lw=2, label='KNN (area = %0.2f)' % roc_auc_knn)
plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC Curve')
plt.legend(loc="lower right")
```
通过比较四个分类器的pr曲线和roc曲线,可以看出SVM分类器的PR曲线和ROC曲线的AUC值最大,因此SVM分类器是较优模型。