逻辑回归roc曲线代码
时间: 2023-10-20 10:07:54 浏览: 114
以下是一个使用 Python 中的 scikit-learn 库来绘制逻辑回归模型的 ROC 曲线的示例代码:
```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_curve, roc_auc_score
# 创建一个二分类的样本数据集
X, y = make_classification(n_samples=1000, n_features=10, random_state=42)
# 将数据集划分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 创建并训练逻辑回归模型
model = LogisticRegression()
model.fit(X_train, y_train)
# 使用模型对测试集进行预测,得到预测概率值
y_pred_proba = model.predict_proba(X_test)[:, 1]
# 计算 ROC 曲线上的各点坐标
fpr, tpr, thresholds = roc_curve(y_test, y_pred_proba)
# 计算 AUC 值
auc = roc_auc_score(y_test, y_pred_proba)
# 绘制 ROC 曲线
plt.plot(fpr, tpr, label=f'ROC curve (AUC = {auc:.2f})')
plt.plot([0, 1], [0, 1], 'k--') # 绘制对角线
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver Operating Characteristic (ROC) Curve')
plt.legend()
plt.show()
```
这段代码首先创建一个二分类的样本数据集,然后将数据集划分为训练集和测试集。接下来,创建并训练一个逻辑回归模型。使用该模型对测试集进行预测,并得到预测概率值。然后,通过计算 ROC 曲线上的各点坐标和 AUC 值,利用 matplotlib 库绘制 ROC 曲线图。最后,展示图形。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)