AI & ML Quick Path Progress

Part 3: Machine learning Lesson 16 of 20 in this part

Comparing models and trusting probabilities

What you will learn. Compare two models fairly on the same cases, use log loss and the Brier score to judge the probabilities they give, and check with a calibration table whether "80%" really means about 8 in 10.

  • Intermediate
  • Study time about 75 min
  • Maths Some algebra
  • Python: example run
  • C#: compiled and run

Before this lesson: Classification: picking a category, Measuring models honestly. Already know these? Carry on.

In plain words

Accuracy only asks whether a model landed on the right side of 50%. Two models can have the same accuracy and still be very different, because one says "55%" when it is unsure and the other says "99%" and is sometimes wrong. If people will act on the percentage (call a customer, hold a payment), the percentage itself must be trustworthy. Log loss and the Brier score judge the probabilities, not just the yes or no. A calibration table checks the promise: among all the cases where the model said about 80%, did about 80% really happen? Finally, when two scores differ, you must ask whether the gap is real or just luck. You do that by comparing the models case by case on the same cases, which is called a paired comparison.

Diagram Same accuracy, different trust

Honest probabilities

  • Says about 70% and is right about 7 times in 10
  • Confident only when the evidence is strong

Overconfident probabilities

  • Says 99% and is wrong more often than that
  • Same yes and no answers, worse numbers

Accuracy cannot tell these two apart. Log loss and calibration can.

Diagram What each score looks at
  1. InputAccuracyYes or no at one cut-off
  2. ModelLog loss and Brier scoreHow good the probability itself is
  3. OutputCalibration tableWhether the percentages match what happened

Pick the score that matches how the model's number will be used.

Diagram Comparing two models fairly
  1. InputScore both models on the same casesOne score per case
  2. ProcessSubtract the two scores case by caseOne difference per case
  3. OutputCompare the average difference with its spreadIs the gap bigger than chance?

Use the same cases for both models, then look at the difference per case.

Real-world example

A bank has two models that flag payments that might be fraud. Both flag the same payments at the 50% line, so they have the same accuracy on the test set. But the fraud team does not just read yes or no. They sort by the percentage and review the top ones first, and they set a policy: "above 90%, block the card at once". For that policy the percentages must be honest. If the model says 95% and the real rate is 70%, the bank blocks too many good customers. The team compares the models by log loss and by a calibration table, and finds one model is overconfident.

How it works

  1. Score each model on the same test cases. Use accuracy at the cut-off you plan to use, and also log loss and the Brier score.
  2. Look at the calibration table: group the cases by the percentage the model gave, and compare the average percentage with the share that really happened.
  3. For each test case, work out the difference in loss between the two models. Take the average difference and its standard error.
  4. Decide. A difference more than about two standard errors from zero is probably real. Smaller than that could be chance, so you may need more test cases.

Log loss is the average "surprise" of the model at what really happened. If the event happened, the surprise is minus the natural logarithm of the probability the model gave it. If the event did not happen, it is minus the logarithm of one minus that probability.

Python example

Python: example run The example programme behind this lesson's quoted output ran on 2026-11-19 (Python 3.12.10). 1 code block in the lesson passed a syntax check, 1 also ran on their own.

The cases come from a repeatable rule: 40 cases, an event that happens with a known chance. Model A reports the true chance. Model B ranks cases the same way but is overconfident: its percentages are pushed towards 0 and 1.

Python — model_compare.py
"""Two models, one set of cases: accuracy, log loss, Brier score, a paired comparison and a calibration table.

Model A reports the true chance for each case. Model B reports the same ranking but is overconfident:
its probabilities are pushed towards 0 and 1. The cases are generated by a repeatable rule, so the numbers
are the same on every run and in the C# version.
Run:  python model_compare.py   (needs numpy)
"""
import numpy as np

n = 40
i = np.arange(n)
p_true = np.clip(0.5 + 0.45 * np.sin(0.7 * i), 0.03, 0.97)
y = ((i * 0.6180339887498949) % 1.0 < p_true).astype(float)      # 1 means the event happened
logit = np.log(p_true / (1 - p_true))
p_a = p_true                                                      # honest probabilities
p_b = np.clip(1 / (1 + np.exp(-3 * logit)), 0.001, 0.999)         # overconfident probabilities

def case_loss(p):                                                 # log loss of each single case
    return -(y * np.log(p) + (1 - y) * np.log(1 - p))

for name, p in (("A", p_a), ("B", p_b)):
    acc = float(np.mean((p >= 0.5) == (y == 1)))
    print("model %s: accuracy %.3f  log loss %.3f  Brier %.3f" % (name, acc, case_loss(p).mean(), np.mean((p - y) ** 2)))

d = case_loss(p_b) - case_loss(p_a)                               # paired: the same case under both models
se = d.std(ddof=1) / np.sqrt(n)
print("paired difference in log loss (B minus A): mean %.3f  standard error %.3f  ratio %.2f" % (d.mean(), se, d.mean() / se))

print("model B calibration: predicted range, cases, average predicted, share that happened")
for lo in (0.0, 0.2, 0.4, 0.6, 0.8):
    m = (p_b >= lo) & (p_b < lo + 0.2 + (1e-9 if lo == 0.8 else 0))
    if m.any():
        print("  %.1f to %.1f  %2d  %.3f  %.3f" % (lo, lo + 0.2, m.sum(), p_b[m].mean(), y[m].mean()))
Output — Output of model_compare.py (executed)
model A: accuracy 0.800  log loss 0.483  Brier 0.155
model B: accuracy 0.800  log loss 0.745  Brier 0.171
paired difference in log loss (B minus A): mean 0.262  standard error 0.170  ratio 1.54
model B calibration: predicted range, cases, average predicted, share that happened
  0.0 to 0.2  16  0.034  0.250
  0.4 to 0.6   5  0.545  0.600
  0.8 to 1.0  19  0.963  0.895

Both models are right on 80% of cases (accuracy 0.800), yet model B has the worse log loss (0.745 against 0.483) and the worse Brier score (0.171 against 0.155). Accuracy hid the difference.

The calibration table shows why B is worse. Among the 16 cases where B said under 20%, it averaged 0.034, but the event happened 0.250 of the time. Among the 19 cases where it said over 80%, it averaged 0.963 but the event happened 0.895 of the time. B is too sure at both ends.

If a model's probabilities are off but its ranking is good, you can repair them without retraining by fitting a small correction on held-out data. Platt scaling fits a smooth S-curve; isotonic regression fits a staircase. Both are available in scikit-learn.

.NET (C#) example

C#: compiled and run The C# sample compiled on 2026-11-19 with .NET SDK 10.0.400 (no extra packages). It also ran to the end without error.

This is the same comparison written from scratch in C# with no packages. It prints exactly the same numbers. ML.NET reports log loss for a trained model, and the same formulas apply.

C# — Program.cs
// Same cases and same numbers as model_compare.py. Written from scratch, so it needs no packages.
const int n = 40;
double[] pTrue = new double[n], y = new double[n], pA = new double[n], pB = new double[n];
for (int i = 0; i < n; i++)
{
    pTrue[i] = Math.Clamp(0.5 + 0.45 * Math.Sin(0.7 * i), 0.03, 0.97);
    y[i] = (i * 0.6180339887498949) % 1.0 < pTrue[i] ? 1 : 0;              // 1 means the event happened
    double logit = Math.Log(pTrue[i] / (1 - pTrue[i]));
    pA[i] = pTrue[i];                                                      // honest probabilities
    pB[i] = Math.Clamp(1 / (1 + Math.Exp(-3 * logit)), 0.001, 0.999);      // overconfident probabilities
}

double CaseLoss(double[] p, int i) => -(y[i] * Math.Log(p[i]) + (1 - y[i]) * Math.Log(1 - p[i]));
void Report(string name, double[] p)
{
    double acc = Enumerable.Range(0, n).Average(i => ((p[i] >= 0.5) == (y[i] == 1)) ? 1.0 : 0.0);
    double ll = Enumerable.Range(0, n).Average(i => CaseLoss(p, i));
    double brier = Enumerable.Range(0, n).Average(i => Math.Pow(p[i] - y[i], 2));
    Console.WriteLine($"model {name}: accuracy {acc:F3}  log loss {ll:F3}  Brier {brier:F3}");
}
Report("A", pA);
Report("B", pB);

double[] d = Enumerable.Range(0, n).Select(i => CaseLoss(pB, i) - CaseLoss(pA, i)).ToArray();   // paired: same case, both models
double mean = d.Average();
double sd = Math.Sqrt(d.Sum(v => Math.Pow(v - mean, 2)) / (n - 1));
double se = sd / Math.Sqrt(n);
Console.WriteLine($"paired difference in log loss (B minus A): mean {mean:F3}  standard error {se:F3}  ratio {mean / se:F2}");

Console.WriteLine("model B calibration: predicted range, cases, average predicted, share that happened");
foreach (double lo in new[] { 0.0, 0.2, 0.4, 0.6, 0.8 })
{
    double hi = lo + 0.2 + (lo == 0.8 ? 1e-9 : 0);
    var rows = Enumerable.Range(0, n).Where(i => pB[i] >= lo && pB[i] < hi).ToArray();
    if (rows.Length > 0)
        Console.WriteLine($"  {lo:F1} to {lo + 0.2:F1}  {rows.Length,2}  {rows.Average(i => pB[i]):F3}  {rows.Average(i => y[i]):F3}");
}

Maths behind it

  • Natural logarithm and log loss (information theory)
  • Brier score as mean squared error of probabilities (statistics)
  • Standard error of an average difference (statistics)
  • Calibration as comparing predicted and observed rates (probability)

Common mistakes

  • Comparing models by accuracy alone when a percentage drives the decision.
  • Comparing scores computed on different cases or different splits. Use the same cases for both models.
  • Declaring a winner from a small gap on a small test set without checking the standard error.
  • Checking calibration on the training data. Use cases the model has not seen.
  • Forgetting that a model can rank well and still give poor percentages. Fix the percentages with Platt or isotonic scaling, on held-out data.

Quick check

  1. Two fraud models both have 80% accuracy. Why might you still prefer one?

    Show answer

    Accuracy ignores how confident each model was. The one with the lower log loss and the better calibration table gives percentages you can use for decisions such as "block above 90%".

  2. A model says 99% for a case where the event did not happen. Why does log loss treat this so harshly?

    Show answer

    Log loss takes minus the logarithm of the probability given to what really happened, here 1%, which is about 4.6. A confident wrong answer costs far more than an unsure one.

  3. Model B scores 0.262 worse than model A, with a standard error of 0.170. Can you be sure B is worse?

    Show answer

    Not yet. The ratio is about 1.54, below the rough guide of 2, so chance could explain the gap. Collect more test cases and repeat the paired comparison.

  4. In a calibration table, the 80 to 100% row shows an average prediction of 0.96 but an observed rate of 0.90. What does it mean?

    Show answer

    The model is overconfident in that range. It promises 96% and delivers 90%. You can correct this with Platt scaling or isotonic regression fitted on held-out data.

Completion

Evidence of completion. A comparison of two models on one dataset with accuracy, log loss, a paired difference with its standard error, and a calibration table, plus a sentence saying which model you would use and whether the gap could be chance.

Saved in this browser only. Reading and exercise are ticked separately because they are different achievements. A tick records your own work; it is not a test result. See all progress.