Compute the points of a ROC curve with tied scores

Why it matters ROC curves are how fraud, credit and medical models pick an operating threshold, and tied scores are common with rounded or tree-based scores.

A ROC curve plots the true positive rate against the false positive rate as the decision threshold slides down. Tied scores must move together.

Write roc_points(y, scores). y is 0/1 with at least one of each, scores are floats. Use every distinct score as a threshold, from highest to lowest, predicting positive when score >= threshold. Return (fpr, tpr, thr) as float arrays: the first point is (0, 0) with threshold inf, followed by one point per distinct score.

Signaturedef roc_points(y, scores)

Example

y [0, 0, 1, 1], scores [0.1, 0.4, 0.35, 0.8] gives fpr [0, 0, 0.5, 0.5, 1], tpr [0, 0.5, 0.5, 1, 1] and thr [inf, 0.8, 0.4, 0.35, 0.1].

Understand the idea

A classifier gives scores, and we must pick a threshold to call something positive. Each threshold gives a true positive rate (how many real positives we catch) and a false positive rate (how many negatives we wrongly flag). The ROC curve draws all these pairs, from the strictest threshold to the most lenient.

Worked example: y = 0, 0, 1, 1 with scores 0.1, 0.4, 0.35, 0.8. Sorted from high to low: 0.8 (pos), 0.4 (neg), 0.35 (pos), 0.1 (neg). At threshold 0.8 we catch 1 of 2 positives: TPR 0.5, FPR 0. At 0.4 a negative joins: FPR 0.5. At 0.35 TPR becomes 1. At 0.1 everything is positive: (1, 1).

Ties matter: if three items share score 0.7, no threshold can separate them, so they enter together as one diagonal step.

Rule: for each distinct threshold t (descending), TPR = TP(score >= t) / P and FPR = FP(score >= t) / N, starting from (0, 0).

The area under this curve is ROC AUC, and teams read the curve to choose an operating point.

Shapes and data flow

scores (n,) -> sorted (n,) -> distinct thresholds (u,) -> curve (u + 1,)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: exampleroc_points([0, 0, 1, 1], [0.1, 0.4, 0.35, 0.8])
  • Sample 2: tiesroc_points([1, 0, 1, 0, 1], [0.9, 0.7, 0.7, 0.7, 0.2])
  • Test 3: perfectroc_points([0, 1, 0, 1], [0.2, 0.9, 0.1, 0.8])
  • Test 4: randomroc_points(_y, _s)