Python Logistic Regression with ROC Curve and AUC Calculation
This code demonstrates how to train a Logistic Regression model on a crime dataset, calculate the ROC curve and AUC value, and finally plot the ROC curve. It includes data loading, splitting into train and test sets, model fitting, prediction, ROC curve calculation, and AUC value calculation.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import roc_curve, auc
from sklearn.model_selection import train_test_split
# 读取数据
data = pd.read_csv('mdcrime.csv')
# 划分训练集和测试集
from sklearn.linear_model import LogisticRegression
X=data.iloc[:,3:4]
y=data.iloc[:,-1]
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.3,random_state=10)
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, 2])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver Operating Characteristic')
plt.legend(loc="lower right")
plt.show()
Explanation:
-
Data Loading: The code starts by reading the crime dataset from a file named 'mdcrime.csv' using
pd.read_csv(). -
Data Splitting: The dataset is then split into training and testing sets using
train_test_split()with a test size of 30% and a random state of 10 for reproducibility. -
Model Training: A Logistic Regression model is created using
LogisticRegression()and trained on the training data (X_train,y_train) using thefit()method. -
Prediction: The model predicts probabilities for the test data using
predict_proba(). -
ROC Curve and AUC Calculation: The
roc_curve()function calculates the false positive rate (fpr), true positive rate (tpr), and thresholds for different probability thresholds. Theauc()function calculates the area under the curve (AUC) for the ROC curve. -
ROC Curve Plotting: The code then plots the ROC curve using
plt.plot()with the calculated fpr, tpr, and AUC value. The plot also includes a diagonal line representing the random classifier and labels for the axes and legend.
This code provides a basic framework for understanding and implementing Logistic Regression with ROC curve and AUC evaluation in Python.
原文地址: https://www.cveoy.top/t/topic/oxX7 著作权归作者所有。请勿转载和采集!