BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Evaluation metrics33 of 33 in topic

825. Compute lift at the top of a model's ranking

EasyEvaluation metrics

Why it matters Churn, fraud and lead-scoring models are judged by gain and lift charts as much as by AUC.

Marketing and risk teams ask a simple question of a scoring model: if we only contact the top 10% of users by score, how many more positives do we catch than random picking? That ratio is the lift.

Write lift_at(scores, labels, frac). Sort by score descending (ties: lower index first) and take the top ceil(frac * n) rows. Return a dict with "gain" = positives in the top / all positives and "lift" = (positive rate in the top) / (overall positive rate). If there are no positives, both are 0.0.

Functiondef lift_at(scores, labels, frac)

Example 1

Input: lift_at([0.9, 0.8, 0.3, 0.2, 0.1], [1, 0, 1, 0, 0], 0.4)

Output: {'gain': 0.5, 'lift': 1.25}

Example 2

Input: scores = [0.1, 0.2, 0.3, 0.4], labels = [1, 1, 0, 0], frac = 0.5

Output: {'gain': 0.0, 'lift': 0.0}

Example 3

Input: scores = [i / 100 for i in range(100)], labels = [1 if i >= 90 else 0 for i in range(100)], frac = 0.1

Output: {'gain': 1.0, 'lift': 10.0}

Constraints

  • Python 3 standard library. Code runs in your browser.
  • Your code must pass all 5 tests to be accepted.
Hint 1

Sort indices by (-score, index) and keep the first ceil(frac * n).

Hint 2

Gain divides by all positives; lift divides by the base rate.

Common mistakes
  • Using int() instead of ceil, which can give an empty slice.
  • Sorting ascending, which picks the lowest scores.
Understand the idea

Gain is the share of all positives you catch in the top slice. Lift compares the hit rate in that slice with the base rate; 1.0 means no better than random.

Worked example

5 users, 2 positives (base rate 0.4). Top 40% is 2 users with 1 positive: gain 1/2 = 0.5, top rate 0.5, lift 0.5 / 0.4 = 1.25.

k = ceil(frac n); gain = hits / P; lift = (hits / k) / (P / n)
Topics
Evaluation metrics
Similar questions
  • Compute precision, recall and F1 from predictionsEasy
  • Measure how overconfident a classifier is with expected calibration errorEasy
  • Build a confusion matrixEasy
  • Compute mean reciprocal rankEasy
All Evaluation metrics problems
Report
825 / 903
Python 3solution.pyPython idle
1
2
3
4
5
import math
def lift_at(scores, labels, frac):
# your code here
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks all 5 tests.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS