How to plot a ROC Curve in Python?

This recipe helps you plot a ROC Curve in Python

Recipe Objective

While working on a classification model, we feel a need of a metric which can show us how our model is performing. A metric which can also give a graphical representation of the performance will be very helpful.

ROC curve can efficiently give us the score that how our model is performing in classifing the labels. We can also plot graph between False Positive Rate and True Positive Rate with this ROC(Receiving Operating Characteristic) curve. The area under the ROC curve give is also a metric. Greater the area means better the performance.
Note that we can use ROC curve for a classification problem with two classes in the target. For Data having more than two classes we have to plot ROC curve with respect to each class taking rest of the combination of other classes as False Class.

So this recipe is a short example of how to use ROC and AUC to see the performance of our model.Here we will use it on two models for better understanding.

Get Closer To Your Dream of Becoming a Data Scientist with 70+ Solved End-to-End ML Projects

Step 1 - Import the library - GridSearchCv

from sklearn import datasets from sklearn.tree import DecisionTreeClassifier from sklearn.linear_model import LogisticRegression from sklearn.metrics import roc_curve, roc_auc_score from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt

Here we have imported various modules like: datasets from which we will get the dataset, DecisionTreeClassifier and LogisticRegression which we will use a models, roc_curve and roc_auc_score will be used to get the score and help us to plot the graph, train_test_split will split the data into two parts train and test and plt will be used to plot the graph.

Step 2 - Setup the Data

Here we have used datasets to load the inbuilt wine dataset and we have created objects X and y to store the data and the target value respectively. dataset = datasets.load_wine() X = dataset.data y = dataset.target

Step 3 - Spliting the data and Training the model

The module train_test_split is used to split the data into two parts, one is train which is used to train the model and the other is test which is used to check how our model is working on unseen data. Here we are passing 0.3 as a parameter in the train_test_split which will split the data such that 30% of data will be in test part and rest 70% will be in the train part. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)

Now we are creating objects for classifier and training the classifier with the train split of the dataset i.e x_train and y_train. clf_tree = DecisionTreeClassifier(); clf_reg = LogisticRegression(); clf_tree.fit(X_train, y_train); clf_reg.fit(X_train, y_train);

Step 5 - Using the models on test dataset

After traing the classifier on test dataset, we are using the model to predict the target values for test dataset. We are storing the predicted class by both of the models and we will use it to get the ROC AUC score y_score1 = clf_tree.predict_proba(X_test)[:,1] y_score2 = clf_reg.predict_proba(X_test)[:,1]

Step 6 - Creating False and True Positive Rates and printing Scores

We have to get False Positive Rates and True Postive rates for the Classifiers because these will be used to plot the ROC Curve. This can be done by roc_curve module by passing the test dataset and the predicted data through it. Here we are doing this for both the classifier. false_positive_rate1, true_positive_rate1, threshold1 = roc_curve(y_test, y_score1) false_positive_rate2, true_positive_rate2, threshold2 = roc_curve(y_test, y_score2) Now, For getting ROC_AUC score we can simply pass the test data and the predected data into the function ruc_auc_score. We are printing it with print statements for better understanding. print('roc_auc_score for DecisionTree: ', roc_auc_score(y_test, y_score1)) print('roc_auc_score for Logistic Regression: ', roc_auc_score(y_test, y_score2))

Explore More Data Science and Machine Learning Projects for Practice. Fast-Track Your Career Transition with ProjectPro

Step 7 - Ploting ROC Curves

We are ploting two ROC Curve as subplots one for DecisionTreeClassifier and another for LogisticRegression. Both have their respective False Positive Rate on X-axis and True Positive Rate on Y-axis. plt.subplots(1, figsize=(10,10)) plt.title('Receiver Operating Characteristic - DecisionTree') plt.plot(false_positive_rate1, true_positive_rate1) plt.plot([0, 1], ls="--") plt.plot([0, 0], [1, 0] , c=".7"), plt.plot([1, 1] , c=".7") plt.ylabel('True Positive Rate') plt.xlabel('False Positive Rate') plt.show() plt.subplots(1, figsize=(10,10)) plt.title('Receiver Operating Characteristic - Logistic regression') plt.plot(false_positive_rate2, true_positive_rate2) plt.plot([0, 1], ls="--") plt.plot([0, 0], [1, 0] , c=".7"), plt.plot([1, 1] , c=".7") plt.ylabel('True Positive Rate') plt.xlabel('False Positive Rate') plt.show() As an output we get:

roc_auc_score for DecisionTree:  0.9539141414141414
roc_auc_score for Logistic Regression:  0.9875140291806959

Join Millions of Satisfied Developers and Enterprises to Maximize Your Productivity and ROI with ProjectPro - Read ProjectPro Reviews Now!

Download Materials

What Users are saying..

profile image

Ray han

Tech Leader | Stanford / Yale University
linkedin profile url

I think that they are fantastic. I attended Yale and Stanford and have worked at Honeywell,Oracle, and Arthur Andersen(Accenture) in the US. I have taken Big Data and Hadoop,NoSQL, Spark, Hadoop... Read More

Relevant Projects

Model Deployment on GCP using Streamlit for Resume Parsing
Perform model deployment on GCP for resume parsing model using Streamlit App.

Deep Learning Project for Beginners with Source Code Part 1
Learn to implement deep neural networks in Python .

Build a Graph Based Recommendation System in Python -Part 1
Python Recommender Systems Project - Learn to build a graph based recommendation system in eCommerce to recommend products.

Linear Regression Model Project in Python for Beginners Part 2
Machine Learning Linear Regression Project for Beginners in Python to Build a Multiple Linear Regression Model on Soccer Player Dataset.

Machine Learning Project to Forecast Rossmann Store Sales
In this machine learning project you will work on creating a robust prediction model of Rossmann's daily sales using store, promotion, and competitor data.

Build Customer Propensity to Purchase Model in Python
In this machine learning project, you will learn to build a machine learning model to estimate customer propensity to purchase.

BERT Text Classification using DistilBERT and ALBERT Models
This Project Explains how to perform Text Classification using ALBERT and DistilBERT

Recommender System Machine Learning Project for Beginners-1
Recommender System Machine Learning Project for Beginners - Learn how to design, implement and train a rule-based recommender system in Python

Learn to Build a Siamese Neural Network for Image Similarity
In this Deep Learning Project, you will learn how to build a siamese neural network with Keras and Tensorflow for Image Similarity.

Build a Multi Touch Attribution Machine Learning Model in Python
Identifying the ROI on marketing campaigns is an essential KPI for any business. In this ML project, you will learn to build a Multi Touch Attribution Model in Python to identify the ROI of various marketing efforts and their impact on conversions or sales..