以下是Python中绘制ROC曲线的示例代码:

# 导入需要的包
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import roc_curve, auc

# 读取数据
data = pd.read_csv('data.csv')

# 划分训练集和测试集
train = data.sample(frac=0.7, random_state=1)
test = data.drop(train.index)

# 构建模型(这里以逻辑回归为例)
from sklearn.linear_model import LogisticRegression
x_train = train.iloc[:, :-1]
y_train = train.iloc[:, -1]
x_test = test.iloc[:, :-1]
y_test = test.iloc[:, -1]
clf = LogisticRegression()
clf.fit(x_train, y_train)
probas_ = clf.predict_proba(x_test)

# 计算ROC曲线和AUC值
fpr, tpr, thresholds = roc_curve(y_test, probas_[:, 1])
roc_auc = auc(fpr, tpr)

# 绘制ROC曲线
plt.figure(figsize=(8, 6))
lw = 2
plt.plot(fpr, tpr, color='darkorange',
         lw=lw, label='ROC curve (area = %0.2f)' % roc_auc)
plt.plot([0, 1], [0, 1], color='navy', lw=lw, 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('Receiver Operating Characteristic')
plt.legend(loc="lower right")
plt.show()

说明:

  1. 首先导入需要的包,包括pandas、numpy、matplotlib和sklearn等。
  2. 读取数据并划分训练集和测试集。
  3. 构建模型(这里以逻辑回归为例)。
  4. 计算ROC曲线和AUC值,使用sklearn中的roc_curve和auc函数。
  5. 最后绘制ROC曲线,使用matplotlib中的plot函数。

注意:在实际应用中,需要根据具体的模型和数据进行相应的调整

python画roc曲线

原文地址: https://www.cveoy.top/t/topic/gI1g 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录