The code to plot the Lift Curve in Python
Hey friends! This runnable Python example plots a cumulative lift curve and returns a table of selected cases, population fractions, gains and lift. It uses NumPy, Pandas and Matplotlib; no dataset download or fitted model is needed for the toy example. For the formula and interpretation, read our Lift Curve guide.
Step 1: run the full code block below in a Python notebook with numpy, pandas and matplotlib installed. Before running it, predict the lift at the top two and top four cases. Keep your answer to compare with the explanation below.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def plot_lift_curve(y_true, y_score):
y = np.asarray(y_true)
scores = np.asarray(y_score, dtype=float)
if y.ndim != 1 or scores.ndim != 1 or len(y) != len(scores):
raise ValueError("Use equally sized one-dimensional arrays.")
if len(y) == 0 or not np.isin(y, [0, 1]).all():
raise ValueError("Labels must be 0 or 1 in a nonempty array.")
if not np.isfinite(scores).all():
raise ValueError("Scores must be finite.")
if y.sum() == 0:
raise ValueError("Lift is undefined without positive outcomes.")
order = np.argsort(-scores, kind="stable")
ranked_y, ranked_scores = y[order], scores[order]
# Include entire tied-score groups: never break ties using labels.
ends = np.r_[np.flatnonzero(np.diff(ranked_scores) != 0),
len(y) - 1]
selected = ends + 1
positives = np.cumsum(ranked_y)[ends]
result = pd.DataFrame({
"selected": selected,
"fraction": selected / len(y),
"gains": positives / y.sum(),
"lift": (positives / selected) / y.mean(),
})
plt.plot(result["fraction"], result["lift"], marker="o")
plt.axhline(1, color="gray", linestyle="--", label="Random baseline")
plt.xlabel("Fraction of population selected")
plt.ylabel("Cumulative lift")
plt.title("Lift curve at observed score cutoffs")
plt.legend()
plt.show()
return result
# Toy example: predict the results at 20% and 40% before running.
y_true = [1, 0, 1, 0, 0, 1, 0, 0, 0, 1]
y_score = [0.95, 0.90, 0.80, 0.70, 0.60, 0.50, 0.40, 0.30, 0.20, 0.10]
table = plot_lift_curve(y_true, y_score)
print(table[table["selected"].isin([2, 4, 10])].to_string(index=False))
Lets check out the parameters to see what they each mean in detail:
y_true: one-dimensional binary labels, with 1 representing the outcome you want to find.y_score: one-dimensional scores in the same row order; larger values must mean more likely positive. Use probabilities or an appropriate decision score, not thresholded class predictions.- Return value: a DataFrame with
selected,fraction,gainsandlift. The chart uses observed score cutoffs, so there is nostepparameter.
Step 2: use your modelβs predictions. For a fitted classifier with predict_proba, find the column for your event with positive_column = list(model.classes_).index(1), then use y_score = model.predict_proba(X_test)[:, positive_column]. Map your chosen event to 1 in the labels too. See scikit-learnβs predict_proba documentation for class ordering.
Choose the data split intentionally. Use validation data to choose the model and review budget, then report final performance on untouched test data. Training curves can diagnose fit, but do not estimate performance on unseen cases. Keep labels and scores aligned row by row; the function rejects mismatched lengths, invalid labels, non-finite scores and datasets without positives.
Step 3: read the chart and table. With your own predictions, call table = plot_lift_curve(y_test, y_score). The toy example above produces its own chart. The image below is an illustration from another example, not the output of those ten toy observations.

Expected output and challenge answers
The toy dataset has four positives out of ten cases. Selecting two cases captures one positive: gains = 25%, lift = 1.25. Selecting four captures two positives: gains = 50%, lift = 1.25. Selecting all ten gives gains = 100% and lift = 1. The same lift can therefore represent different numbers of positives found.
One more experiment: create a tie
Change the first two scores to 0.90 and run the example again. Predict whether the first plotted point will select one case or two. Answer: two, because the function includes the entire tied-score group. It does not use known outcomes to decide which tied observation comes first.
For a fixed review budget, choose a tie-breaking rule independent of the true labels and report the actual number selected. Lines between the plotted points are visual guides, not additional evaluated cutoffs. A dataset with no positives has undefined lift; an all-positive dataset has lift 1 throughout and cannot demonstrate useful ranking.
That is it, hope you make good use of this quick code snippet for the Lift Curve in Python and its parameters! Follow us on X here! Also, if you have any doubts or comments, please feel free to contact us at howtolearnmachinelearning@gmail.com.
Spread the love and have a fantastic day π
What next? Use the full Lift Curve guide to interpret your results. For a structured learning plan, get the Free 90-Day Machine Learning Roadmap. For more guided practice, explore the ML Starter Kit and its model-evaluation chapter.
Tags: Code Snippet, Lift Curve Python Code, Model Evaluation, Matplotlib.
Subscribe to our awesome newsletter to get the best content on your journey to learn Machine Learning, including some exclusive free goodies!

