Isotonic Regression: Pool the Violators

Metrics & EvaluationHard+20 XP+20

Isotonic Regression: Pool the Violators

Your model's scores rank things correctly but don't behave like probabilities. Isotonic regression fixes that by fitting the data with the least restrictive assumption there is: the fitted values must never go down as the score goes up. No straight line, no curve shape — just "non-decreasing".

The algorithm is called pool adjacent violators, and it's as literal as it sounds:

  1. Sort the points by x. Start with every y as its own block, each holding one value.
  2. Scan for a neighbouring pair where the left block's value is greater than the right's — a violation of non-decreasing order.
  3. Pool them: replace both with one block whose value is their weighted mean (weight = how many original points the block holds) and whose weight is the two weights added together.
  4. Pooling can break the order with the block before it, so step back one and keep checking. Repeat until no violation is left.

Task: write isotonic_fit(x, y) returning the fitted value for each point, in ascending x order, each rounded to 4 decimal places.

  • x values are distinct but not necessarily sorted — sort the pairs first.
  • Every original point gets its own entry in the output. A block that pooled three points contributes its mean three times.
  • The output has the same length as the input, and is non-decreasing.

Watch the weights. Pooling two blocks of sizes 1 and 3 must not average their two values evenly — the second one speaks for three points and has to count three times as much, or the fit drifts.

Examples

x = [1, 2, 3, 4]
y = [1, 3, 2, 4]
returns [1.0, 2.5, 2.5, 4.0]
x = [1, 2, 3]
y = [3, 2, 1]
returns [2.0, 2.0, 2.0]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run