How to plot ROC curve in Python

How to plot ROC curve in Python

To plot a ROC (Receiver Operating Characteristic) curve in Python, you can use the roc_curve() function from the sklearn.metrics module to calculate the True Positive Rate (TPR) and False Positive Rate (FPR) values, and then use the matplotlib library to create the plot. The ROC curve is used to visualize the performance of binary classification models.

Here's a step-by-step example of how to plot an ROC curve using scikit-learn and matplotlib:

import numpy as np import matplotlib.pyplot as plt from sklearn.metrics import roc_curve, roc_auc_score from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression # Generate sample data X, y = make_classification(n_samples=1000, n_features=20, random_state=42) # Split data into training and test sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # Create and train a classification model (e.g., Logistic Regression) model = LogisticRegression() model.fit(X_train, y_train) # Predict probabilities for the positive class y_prob = model.predict_proba(X_test)[:, 1] # Calculate TPR, FPR, and thresholds for the ROC curve fpr, tpr, thresholds = roc_curve(y_test, y_prob) # Calculate AUC (Area Under the Curve) auc = roc_auc_score(y_test, y_prob) # Create the ROC curve plot plt.figure(figsize=(8, 6)) plt.plot(fpr, tpr, label=f'AUC = {auc:.2f}') plt.plot([0, 1], [0, 1], 'k--') # Diagonal line for random chance plt.xlabel('False Positive Rate (FPR)') plt.ylabel('True Positive Rate (TPR)') plt.title('ROC Curve') plt.legend() plt.grid(True) plt.show() 

In this example:

  • We generate synthetic data using make_classification() and split it into training and test sets.
  • We create a logistic regression model and train it on the training data.
  • We predict probabilities for the positive class on the test set using predict_proba().
  • We calculate the TPR, FPR, and thresholds using roc_curve().
  • We calculate the AUC using roc_auc_score().
  • Finally, we use matplotlib to plot the ROC curve.

Replace the model and data with your own classifier and dataset to visualize the ROC curve for your binary classification task.

Examples

  1. "Python plot ROC curve example"

    • Description: This query seeks a simple example code to plot a Receiver Operating Characteristic (ROC) curve in Python.
    • Code:
      import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split from sklearn.metrics import roc_curve, auc from sklearn.linear_model import LogisticRegression # Generate synthetic data X, y = make_classification(n_samples=1000, n_features=20, n_classes=2, random_state=42) # Split data into train and test sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # Fit a logistic regression model model = LogisticRegression() model.fit(X_train, y_train) # Predict probabilities y_probs = model.predict_proba(X_test)[:, 1] # Compute ROC curve and AUC fpr, tpr, thresholds = roc_curve(y_test, y_probs) roc_auc = auc(fpr, tpr) # Plot ROC curve plt.figure() plt.plot(fpr, tpr, color='darkorange', lw=2, label=f'ROC curve (area = {roc_auc:.2f})') plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--') plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver Operating Characteristic (ROC) Curve') plt.legend(loc='lower right') plt.show() 
  2. "Python plot ROC curve using sklearn"

    • Description: This query aims to plot an ROC curve using the sklearn library in Python.
    • Code:
      import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split from sklearn.metrics import roc_curve, auc from sklearn.linear_model import LogisticRegression # Generate synthetic data X, y = make_classification(n_samples=1000, n_features=20, n_classes=2, random_state=42) # Split data into train and test sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # Fit a logistic regression model model = LogisticRegression() model.fit(X_train, y_train) # Predict probabilities y_probs = model.predict_proba(X_test)[:, 1] # Compute ROC curve and AUC fpr, tpr, thresholds = roc_curve(y_test, y_probs) roc_auc = auc(fpr, tpr) # Plot ROC curve plt.figure() plt.plot(fpr, tpr, color='darkorange', lw=2, label=f'ROC curve (area = {roc_auc:.2f})') plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--') plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver Operating Characteristic (ROC) Curve') plt.legend(loc='lower right') plt.show() 
  3. "Python plot ROC curve from predicted probabilities"

    • Description: This query focuses on plotting an ROC curve from predicted probabilities using Python.
    • Code:
      import numpy as np import matplotlib.pyplot as plt from sklearn.metrics import roc_curve, auc # Sample predicted probabilities and true labels y_probs = np.random.rand(100) y_true = np.random.randint(2, size=100) # Compute ROC curve and AUC fpr, tpr, thresholds = roc_curve(y_true, y_probs) roc_auc = auc(fpr, tpr) # Plot ROC curve plt.figure() plt.plot(fpr, tpr, color='darkorange', lw=2, label=f'ROC curve (area = {roc_auc:.2f})') plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--') plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver Operating Characteristic (ROC) Curve') plt.legend(loc='lower right') plt.show() 
  4. "Python plot ROC curve with AUC"

    • Description: This query seeks code to plot an ROC curve with the Area Under the Curve (AUC) included in Python.
    • Code:
      import numpy as np import matplotlib.pyplot as plt from sklearn.metrics import roc_curve, auc # Sample data y_true = np.array([0, 1, 1, 0, 1]) y_scores = np.array([0.1, 0.4, 0.35, 0.8, 0.6]) # Compute ROC curve and AUC fpr, tpr, thresholds = roc_curve(y_true, y_scores) roc_auc = auc(fpr, tpr) # Plot ROC curve with AUC plt.figure() plt.plot(fpr, tpr, color='darkorange', lw=2, label=f'ROC curve (area = {roc_auc:.2f})') plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--') plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver Operating Characteristic (ROC) Curve') plt.legend(loc='lower right') plt.show() 
  5. "Python plot ROC curve for binary classification"

    • Description: This query is about plotting an ROC curve for binary classification tasks using Python.
    • Code:
      import numpy as np import matplotlib.pyplot as plt from sklearn.metrics import roc_curve, auc # Sample data y_true = np.array([0, 1, 1, 0, 1]) y_scores = np.array([0.1, 0.4, 0.35, 0.8, 0.6]) # Compute ROC curve and AUC fpr, tpr, thresholds = roc_curve(y_true, y_scores) roc_auc = auc(fpr, tpr) # Plot ROC curve plt.figure() plt.plot(fpr, tpr, color='darkorange', lw=2, label=f'ROC curve (area = {roc_auc:.2f})') plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--') plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver Operating Characteristic (ROC) Curve') plt.legend(loc='lower right') plt.show() 
  6. "Python plot ROC curve with sklearn"

    • Description: This query aims to plot an ROC curve using the sklearn library in Python.
    • Code:
      import numpy as np import matplotlib.pyplot as plt from sklearn.metrics import roc_curve, auc # Sample data y_true = np.array([0, 1, 1, 0, 1]) y_scores = np.array([0.1, 0.4, 0.35, 0.8, 0.6]) # Compute ROC curve and AUC fpr, tpr, thresholds = roc_curve(y_true, y_scores) roc_auc = auc(fpr, tpr) # Plot ROC curve plt.figure() plt.plot(fpr, tpr, color='darkorange', lw=2, label=f'ROC curve (area = {roc_auc:.2f})') plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--') plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver Operating Characteristic (ROC) Curve') plt.legend(loc='lower right') plt.show() 
  7. "Python plot ROC curve for binary classification task"

    • Description: This query is about plotting an ROC curve for binary classification tasks using Python.
    • Code:
      import numpy as np import matplotlib.pyplot as plt from sklearn.metrics import roc_curve, auc # Sample data y_true = np.array([0, 1, 1, 0, 1]) y_scores = np.array([0.1, 0.4, 0.35, 0.8, 0.6]) # Compute ROC curve and AUC fpr, tpr, thresholds = roc_curve(y_true, y_scores) roc_auc = auc(fpr, tpr) # Plot ROC curve plt.figure() plt.plot(fpr, tpr, color='darkorange', lw=2, label=f'ROC curve (area = {roc_auc:.2f})') plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--') plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver Operating Characteristic (ROC) Curve') plt.legend(loc='lower right') plt.show() 
  8. "Python plot ROC curve from predicted probabilities"

    • Description: This query focuses on plotting an ROC curve from predicted probabilities using Python.
    • Code:
      import numpy as np import matplotlib.pyplot as plt from sklearn.metrics import roc_curve, auc # Sample predicted probabilities and true labels y_probs = np.random.rand(100) y_true = np.random.randint(2, size=100) # Compute ROC curve and AUC fpr, tpr, thresholds = roc_curve(y_true, y_probs) roc_auc = auc(fpr, tpr) # Plot ROC curve plt.figure() plt.plot(fpr, tpr, color='darkorange', lw=2, label=f'ROC curve (area = {roc_auc:.2f})') plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--') plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver Operating Characteristic (ROC) Curve') plt.legend(loc='lower right') plt.show() 
  9. "Python plot ROC curve with AUC using sklearn"

    • Description: This query seeks code to plot an ROC curve with the Area Under the Curve (AUC) included in Python using sklearn.
    • Code:
      import numpy as np import matplotlib.pyplot as plt from sklearn.metrics import roc_curve, auc # Sample data y_true = np.array([0, 1, 1, 0, 1]) y_scores = np.array([0.1, 0.4, 0.35, 0.8, 0.6]) # Compute ROC curve and AUC fpr, tpr, thresholds = roc_curve(y_true, y_scores) roc_auc = auc(fpr, tpr) # Plot ROC curve with AUC plt.figure() plt.plot(fpr, tpr, color='darkorange', lw=2, label=f'ROC curve (area = {roc_auc:.2f})') plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--') plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver Operating Characteristic (ROC) Curve') plt.legend(loc='lower right') plt.show() 
  10. "Python plot ROC curve example using sklearn"

    • Description: This query seeks a simple example code to plot an ROC curve in Python using the sklearn library.
    • Code:
      import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split from sklearn.metrics import roc_curve, auc from sklearn.linear_model import LogisticRegression # Generate synthetic data X, y = make_classification(n_samples=1000, n_features=20, n_classes=2, random_state=42) # Split data into train and test sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # Fit a logistic regression model model = LogisticRegression() model.fit(X_train, y_train) # Predict probabilities y_probs = model.predict_proba(X_test)[:, 1] # Compute ROC curve and AUC fpr, tpr, thresholds = roc_curve(y_test, y_probs) roc_auc = auc(fpr, tpr) # Plot ROC curve plt.figure() plt.plot(fpr, tpr, color='darkorange', lw=2, label=f'ROC curve (area = {roc_auc:.2f})') plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--') plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver Operating Characteristic (ROC) Curve') plt.legend(loc='lower right') plt.show() 

More Tags

swipe-gesture resttemplate appkit sdp android-viewholder operating-system nosql android-gridlayout configparser multimedia

More Python Questions

More Mortgage and Real Estate Calculators

More Cat Calculators

More Organic chemistry Calculators

More Investment Calculators