Single logo
  • Courses
  • Blog
  • About
Join for freeJoin free
Machine Learning
  • First Look at a Dataset: 6 Checks Before You Plot or Model
  • Plotting Distributions with seaborn: Histograms, KDE, Counts and log1p
  • Scatter Plots and Pair Plots: See How Two Columns Relate
  • Finding Outliers: Box Plots, Violin Plots and the IQR Rule
  • Correlation and Heatmaps: Covariance, df.corr() and What They Miss
  • Train-Test Split and Data Leakage: Split First, Learn After
  • Handling Missing Data: Count the Blanks, Then Fill Them with SimpleImputer
  • Encoding Categorical Data: OrdinalEncoder, OneHotEncoder and LabelEncoder
  • Feature Scaling: StandardScaler, MinMaxScaler and Which Models Care
  • Pipelines and ColumnTransformer: All Preprocessing and the Model in One Object
  • Feature Selection and the Curse of Dimensionality: Keep the Columns That Matter
  • Project: Preprocess Rain in Australia from Raw CSV to Model-Ready Data
    Regression
    • Linear Regression and the Cost Function: Draw a Line, Score It
    • Gradient Descent Explained: Feel the Slope, Step Downhill
    • Linear Regression in scikit-learn: Fit, Predict and Read the Price Tags
    • Regression Metrics: MAE, RMSE, R-squared and the Baseline to Beat
    • Polynomial Regression, Overfitting and Underfitting: Bend the Line, Watch the Test Score
    • Regularisation with Ridge and Lasso: Put a Price on Big Weights
    Classification and Evaluation
    • Logistic Regression and the Sigmoid: Score, Squash, Decide
    • Logistic Regression in scikit-learn: predict, predict_proba and Softmax
    • Why Accuracy Lies: The Confusion Matrix, Baselines and Type I/II Errors
    • Precision, Recall and F1 Score: Two Questions and One Balance
    • ROC Curve, AUC and Choosing a Classification Threshold
    • Handling Imbalanced Data: class_weight, SMOTE and the Resampling Leak
    • Cross-Validation: KFold, StratifiedKFold, cross_val_score and cross_validate
    Classic Algorithms
    • K-Nearest Neighbours (KNN): Distance, k and Why Scaling Is a Must
    • Naive Bayes: Prior Times Likelihood, a Spam Filter by Hand and GaussianNB
    • Support Vector Machines (SVM): The Widest Road, C, Kernels and gamma
    • Decision Trees: Gini, max_depth and Feature Importances on Rain in Australia
    • Bagging and Random Forest: Many Shaky Trees, One Steady Answer
    • Boosting: Residuals by Hand, AdaBoost, Gradient Boosting and XGBoost
    • Voting and Stacking: Does a Team of Models Beat the Best One?
    Model Selection and Tuning
    • Hyperparameter Tuning with GridSearchCV and RandomizedSearchCV
    • Which Features Matter? Feature Importances, Permutation Importance and SHAP
    • Project: The Classification Master Template, from Raw CSV to a Saved Model
    • K-Means Clustering: Find Groups in Data With No Labels
    • Choosing k for K-Means: the Elbow Method and the Silhouette Score
    • Hierarchical Clustering and DBSCAN: Dendrograms, Linkage, eps and Noise
    • Dimensionality Reduction with PCA: 13 Columns Down to 2
    • Association Rules and Market Basket Analysis: Support, Confidence, Lift and Apriori
    • Recommender Systems: Item-Based Collaborative Filtering with Cosine Similarity
    • Bag of Words with CountVectorizer: Turn Text into Word Counts
    • TF-IDF with TfidfVectorizer: Common Words Fade, Rare Words Speak
    • Build a Text Classifier with TF-IDF and a Pipeline: Naive Bayes vs LinearSVC
    • Why Neural Networks: Pixels, One Neuron and Layers
    • The Forward Pass and Activation Functions: ReLU, Sigmoid, Tanh and Softmax
    • Loss and Backpropagation: How Wrong, and Who Is to Blame
    • The Training Loop: Epochs, Mini-Batches, Learning Rate and Optimisers
    • Your First Neural Network with Keras: MNIST Digits at 97.7%
    • The Same Network in PyTorch: DataLoader, nn.Module and the Five-Line Training Loop
    • Convolutional Neural Networks (CNN) Basics: Filters, Feature Maps and Pooling
    • Embeddings: Words as Vectors, Cosine Similarity and nn.Embedding
    • Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
    • Dropout, Early Stopping and Batch Norm: Judge Each One by the Validation Curve
    • Transfer Learning on Images: A Frozen ResNet-18, a Small Head and an Honest Baseline
    • Attention Explained Without the Maths: Query, Key, Value and the Word "it"
    • Transformer Building Blocks in PyTorch: Follow the Shapes Through Attention and a Block
    • Pretrained Models from Hugging Face: A Sentiment Pipeline and Sentence Embeddings on a CPU
    • Loading a Language Model and Running Inference: Download, Load, Tokenize, Generate
    • Model Size and Memory: Parameters x Bytes, Quantization, and Where to Run a Model
    • Training on a GPU: Mixed Precision, Gradient Accumulation and Checkpoints That Really Resume
    • When NOT to Fine-Tune: A Decision Tree of Prompt, RAG, Tools, Then Fine-Tuning
    • Full Fine-Tuning vs LoRA vs QLoRA: What Each One Changes and What It Costs
    • LoRA Fine-Tune of a Tiny Model: Teach SmolLM2-135M Your House Style on a CPU
    • Knowledge Distillation: Teach a Model 100 Times Smaller From a Teacher's Soft Labels
    • Serving Open Models: Continuous Batching, vLLM and Cold Starts
      Engineering Basics
      • Python Virtual Environments: One Project, One Toolbox
      • Git and GitHub Fundamentals: Commits, Branches, Push and Pull
      • Testing a FastAPI App with pytest: Three Small Tests
      • Config and Logging Instead of Hard-Coded Values in ML Training
      • SQL Essentials for Python: SELECT, WHERE, JOIN and GROUP BY
      Data and Features in Production
      • Time Splits and Group Splits: Make the Split Match How the Model Is Used
      • Time Series Basics: Lags, Rolling Windows and Walk-Forward Backtesting
      • Feature Engineering Patterns, Each One Tested: Date Parts, Differences, Windows and Target Encoding
      • Point-in-Time Correctness: Join Features as of Each Event with merge_asof
      • Data Validation and Schema Checks: Stop Bad Input Before It Reaches the Model
      • Training-Serving Skew: Same Model, Different Inputs, and How to Detect It
      • Feature Stores: Offline and Online Stores, and When You Actually Need One
      • Data Versioning with DVC: Tie Every Model to the Exact Data That Trained It
      Experiments and Model Quality
      • MLOps in One Picture: Code, Data, Model and the Lifecycle Loop
      • Experiment Tracking with MLflow: Log Params, Metrics and the Model, Then Compare Runs
      • MLflow Model Registry Aliases: Serve the Champion, Ship a New Version and Roll Back in One Line
      • The Cost of Being Wrong: Baselines, a Price per Mistake and the Cheapest Threshold
      • Probability Calibration: Can You Trust the 0.8? Reliability Curves, Platt and Isotonic
      • Slice Evaluation and Fairness Checks: Score the Model Group by Group
      Serving Models
      • Saving and Loading Models with joblib: One Pipeline, One File
      • FastAPI Hello World: Routes, uvicorn and the Free Swagger Page
      • Deploy a Machine Learning Model with FastAPI: POST /predict for a Saved Model
      • Docker Essentials for ML: Images, Containers and Volumes with a Model API
      • Containerising a Model API: A Dockerfile for FastAPI and scikit-learn, Line by Line
      • Online, Batch or Streaming? Picking the Serving Pattern for an ML Model
      • A Production FastAPI for an ML Model: Input Limits, /health, /ready and a Model Version
      • Batch Scoring a Million Rows: Chunks, a Run ID and a Safe Rerun
      • Latency Math: p50, p95, p99 and Why the Tail Reaches Your Users
      • Measuring Latency of an ML API: Timing Inside with OpenTelemetry, Outside with a Load Test and Locust
      • Making ML Inference Fast: ONNX, Micro-Batching and Quantisation, Measured
      • Sizing and Autoscaling an Inference Service: From One Replica to a Replica Count
      Pipelines, CI/CD and Cloud
      • The Training Pipeline as a DAG: Steps, Files, Retries and a Safe Rerun
      • Orchestrating ML Pipelines with Airflow: Schedule, Retries and Backfill
      • Retries and Backoff for Reliable Tasks: Retry What Heals, Wait Longer, Add Jitter, Set Limits
      • CI with GitHub Actions: Run the Tests and Build the Docker Image on Every Push
      • CI/CD for ML: A Quality Gate That Blocks a Weaker Model, Even When Every Test Passes
      • Which Cloud for What: AWS, Azure, Google Cloud, GPU Clouds, Edge and Platforms
      • IaaS, PaaS, Containers or Serverless? Choosing Where a Model API Runs
      • Kubernetes at a High Level: Pods, a Deployment and a Service for a Model API
      • Managed ML Platforms: What SageMaker, Vertex AI and Azure ML Give You, and Tie You To
      • Deploying a Model API to AWS: ECR, Secrets Manager, CloudWatch and Fargate, Then Teardown
      • Cloud Cost Thinking for ML: Size x Count x Hours x Rate, and Three Decisions Worth Ten Times
      Monitoring and Release
      • Monitoring Drift and Retraining: When a Model Gets Worse With No Code Change
      • Drift Detection in Code: PSI Bin by Bin, the KS Test, Evidently and a Measured Threshold
      • Shadow, Canary and Rollback: Releasing a New Model Without Betting Everything on It
      • A/B Tests for Models: Did the New Model Make Things Better for People?
      • When Labels Arrive Weeks Late: What to Watch Before You Can Grade the Model
      • Retraining Triggers: Schedule, Drift and Performance, Wired to One Retrain Pipeline
      • The User Feedback Loop: Why Thumbs Up Isn't the Truth, and What a Small Random Review Adds
      • Debugging a Model in Production: A Four-Step Runbook, Cheap Checks First
      • Project: Car Price Predictor End to End, from CSV to a FastAPI Price API
      1. Blog
      2. /
      3. Machine Learning
      4. /
      5. MLOps and Production ML

      Probability Calibration: Can You Trust the 0.8? Reliability Curves, Platt and Isotonic

      When a model says 0.85, does it rain 85 times in 100? On Rain in Australia a Naive Bayes model says 0.85 and it rains 47 times. A reliability curve shows the gap, Platt and isotonic close it (ECE 0.117 to 0.039 and 0.005), and fitting the fix on training rows makes a forest worse.

      Chaand Sheikh

      ·27 November 2026Experiments and Model Quality

      What you will learn

      • Draw a reliability curve and compute ECE to see if a model's scores mean what they say
      • Calibrate scores with Platt scaling and isotonic regression on a separate calibration split
      • Show that calibration changes the numbers but barely the ranking (AUC)
      • Explain why the calibrator must never be fitted on the training rows

      Before you start

      • ROC Curve, AUC and Choosing a Classification Threshold
      • Naive Bayes Classifier
      • Train-Test Split and Data Leakage

      A model gives you a score, and the score often drives a decision. So here's the question: when a model says 0.8, does it really happen eight times in ten? In this article we draw a reliability curve to find out, then fix a bad one in two ways, Platt and isotonic.

      A forecaster who says 80%

      Think of a weather forecaster. Every time she says 80%, we look at those days. Out of ten, it rains on eight. That's an honest 80%, and you can plan around it.

      Another forecaster also says 80%, but it rains on only five days in ten. Same words, but you can't plan around them.

      A model that gives a score is a forecaster too. Eight days in ten is calibrated. Five in ten is not.

      Three parts, one job each

      The data is Rain in Australia, predicting RainTomorrow. Two small helpers load it and split it into three parts:

      import numpy as np
      import pandas as pd
      from sklearn.model_selection import train_test_split
      
      
      def load_rain(path="weatherAUS.csv"):
          df = pd.read_csv(path).dropna(subset=["RainTomorrow"])
          y = (df["RainTomorrow"] == "Yes").astype(int)
          X = df.drop(columns=["RISK_MM"]).select_dtypes("number")
          return X, y
      
      
      def three_way_split(X, y, seed=42):
          """60% to train, 20% to calibrate, 20% to test."""
          X_train, X_rest, y_train, y_rest = train_test_split(
              X, y, test_size=0.4, stratify=y, random_state=seed)
          X_cal, X_test, y_cal, y_test = train_test_split(
              X_rest, y_rest, test_size=0.5, stratify=y_rest, random_state=seed)
          return X_train, X_cal, X_test, y_train, y_cal, y_test
      train 85315  cal 28439  test 28439

      142,193 days with 16 number columns, and it rains on about 22 days in 100. The model learns from train. The calibrators learn from cal, which the model never sees. Test is only for scoring. (RISK_MM is dropped because it leaks the answer; see Train-Test Split and Data Leakage.)

      The model ranks the days well

      from sklearn.impute import SimpleImputer
      from sklearn.metrics import roc_auc_score
      from sklearn.naive_bayes import GaussianNB
      from sklearn.pipeline import make_pipeline
      
      X, y = load_rain()
      X_train, X_cal, X_test, y_train, y_cal, y_test = three_way_split(X, y)
      
      model = make_pipeline(SimpleImputer(strategy="median"), GaussianNB())
      model.fit(X_train, y_train)
      p_cal = model.predict_proba(X_cal)[:, 1]
      p_test = model.predict_proba(X_test)[:, 1]
      print(f"AUC on test {roc_auc_score(y_test, p_test):.3f}")
      AUC on test 0.828

      Naive Bayes behind a median imputer. An AUC of 0.828 means a rainy day scores above a dry day in about 83 pairs out of 100 (more on AUC). So the ranking is fine. But does a score of 0.85 really mean 85 in 100?

      The reliability curve and ECE

      Group the calibration days by score into ten bins, and in each bin compare the average score with the share of days it really rained:

      def reliability(y, p, bins=10):
          """Per bin: days, average score, share that really rained."""
          y = np.asarray(y)
          idx = np.minimum((p * bins).astype(int), bins - 1)
          rows = []
          for b in range(bins):
              m = idx == b
              if m.any():
                  rows.append((int(m.sum()), p[m].mean(), y[m].mean()))
          return rows
      
      
      def ece(y, p, bins=10):
          """Average gap between score and outcome, weighted by days."""
          rows = reliability(y, p, bins)
          total = sum(n for n, _, _ in rows)
          return sum(n * abs(said - rained) for n, said, rained in rows) / total
      
      
      for days, said, rained in reliability(y_cal, p_cal):
          print(f"said {said:.2f}  rained {rained:.2f}  ({days} days)")
      print(f"ECE on cal {ece(y_cal, p_cal):.3f}")
      said 0.02  rained 0.08  (17585 days)
      said 0.14  rained 0.23  (1781 days)
      said 0.25  rained 0.28  (1022 days)
      said 0.35  rained 0.31  (786 days)
      said 0.45  rained 0.34  (686 days)
      said 0.55  rained 0.37  (588 days)
      said 0.65  rained 0.46  (610 days)
      said 0.75  rained 0.46  (659 days)
      said 0.85  rained 0.47  (872 days)
      said 0.98  rained 0.67  (3850 days)
      ECE on cal 0.119

      Each line is one dot on the reliability curve. Days scored near 0.85 had rain on only 47 in 100. The model said 85 and it rained 47. That's a big gap.

      ECE (expected calibration error) turns the curve into one number: the average gap between "said" and "rained", weighted by how many days sit in each bin. Here it's 0.119. A perfectly calibrated model scores 0.

      Fix 1: Platt scaling, a sigmoid

      Platt fits a plain logistic regression on the score, using the calibration part:

      from sklearn.linear_model import LogisticRegression
      
      # Platt: a sigmoid fitted on the scores
      platt = LogisticRegression().fit(p_cal.reshape(-1, 1), y_cal)

      The result is a sigmoid with just two numbers: a = 3.09 and b = -2.30. A score of 0.90 rides up that curve and comes out as 0.62. Two numbers, one smooth bend.

      Fix 2: isotonic regression, a staircase

      from sklearn.isotonic import IsotonicRegression
      
      # isotonic: a staircase that only goes up
      iso = IsotonicRegression(out_of_bounds="clip").fit(p_cal, y_cal)
      print(f"score 0.90 becomes {platt.predict_proba([[0.9]])[0, 1]:.2f}"
            f" (Platt), {iso.predict([0.9])[0]:.2f} (isotonic)")
      score 0.90 becomes 0.62 (Platt), 0.53 (isotonic)

      No formula this time, just steps: a staircase that only goes up, with 58 different step heights, following the dots. The same 0.90 becomes 0.53. Isotonic lets the data pick the shape; its one rule is that the curve never goes down.

      Only now: score all three on the test part

      p_platt = platt.predict_proba(p_test.reshape(-1, 1))[:, 1]
      p_iso = iso.predict(p_test)
      scored = (("raw", p_test), ("platt", p_platt), ("isotonic", p_iso))
      for name, p in scored:
          print(f"{name:<9} ECE {ece(y_test, p):.3f}"
                f"  AUC {roc_auc_score(y_test, p):.3f}")
      raw       ECE 0.117  AUC 0.828
      platt     ECE 0.039  AUC 0.828
      isotonic  ECE 0.005  AUC 0.827
      Reliability curves: raw, Platt and isotonic 0.0 0.0 0.2 0.2 0.4 0.4 0.6 0.6 0.8 0.8 1.0 1.0 what the model said (average score) share of days it really rained raw, ECE 0.117 Platt, ECE 0.039 isotonic, ECE 0.005 perfect calibration
      Reliability curves on the 28,439 test days, drawn from the project's own run. Raw scores sit below the diagonal; Platt pulls them closer; isotonic sits on it.

      The raw curve mostly sits below the diagonal. Platt pulls it much closer (ECE 0.039), and isotonic sits right on the diagonal (0.005). Meanwhile the AUC barely moves: 0.828, 0.828, 0.827. Calibration changes the numbers, not the order.

      Fit the fix on rows the model never saw

      We've been following one rule: the calibrator learns from the calibration part. Let's break it on purpose, with a random forest, and fit isotonic on the training rows instead. These are the two key lines inside the loop of wrong_way.py, where fit_iso is the same IsotonicRegression(out_of_bounds="clip") fit, and the results are averaged over ten splits:

      right = fit_iso(p_cal, y_cal)
      wrong = fit_iso(p_train, y_train)
      naive bayes: test ECE raw 0.120, fitted on cal 0.007, fitted on train 0.006
        fitted on train was worse than raw in 0 of 10 splits
      forest: test ECE raw 0.015, fitted on cal 0.005, fitted on train 0.136
        fitted on train was worse than raw in 10 of 10 splits

      Fitted on cal, the forest's ECE drops from 0.015 to 0.005. Fitted on train, it jumps to 0.136, far worse than doing nothing, and worse than raw on all ten splits. A forest has already seen its training rows, so they're the wrong place to learn the fix. Naive Bayes barely notices, but don't count on that.

      Does it hold on other splits?

      One split isn't enough, so seeds.py repeats the check on ten splits for both models:

      naive bayes: ECE raw 0.120  Platt 0.043  isotonic 0.007
        better than raw, of 10 splits: Platt 10, isotonic 10
      forest: ECE raw 0.015  Platt 0.023  isotonic 0.005
        better than raw, of 10 splits: Platt 0, isotonic 10

      For Naive Bayes, both fixes beat raw on all ten splits. The forest is different: it's already close (0.015). Isotonic still helps on all ten, but Platt never beat raw on any of them. So calibrate when the curve says so, and check before you assume.

      Common mistakes

      • Reading a good AUC as good probabilities. AUC 0.828 and a score of 0.85 that rains 47% of the time live happily together.
      • Fitting the calibrator on the training rows. It made the forest's ECE nine times worse than raw.
      • Calibrating and scoring on the same rows. Keep three parts: train, calibrate, test.
      • Calibrating by habit. Platt made an already-good forest worse. Look at the curve first.

      Recap

      ToolWhat it doesTest ECE here
      Reliability curvesaid vs happened, per score bin
      ECEaverage gap, weighted by daysraw 0.117
      Plattsigmoid with two numbers (a, b)0.039
      Isotonicstaircase that only goes up0.005
      AUCranking, barely changed by calibration0.828 / 0.828 / 0.827

      Try it yourself

      Add HistGradientBoostingClassifier to the models in seeds.py. Does it need calibrating? Check the curve before you decide.

      Built this? Share your solution in the StudyEasy AI Community.

      Join free on Skool →
      ← Previous
      The Cost of Being Wrong: Baselines, a Price per Mistake and the Cheapest Threshold
      Next →
      Slice Evaluation and Fairness Checks: Score the Model Group by Group
      Single logo

      StudyEasy AI Community

      Hosted onSkool

      Learn AI engineering, share what you build, and connect with other learners.

      • Free resources: lesson files, notebooks and code

      • Ask questions and join engineering discussions

      • Meet real people learning and building with AI

      Join free on Skool
      Go deeper with a course

      Machine Learning Engineer: From First Model to ML Engineer

      Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)

      Related articles
      Python Virtual Environments: One Project, One Toolbox

      Why every Python project gets its own virtual environment: two projects that need different versions of requests, python -m venv .venv, activation, pip install and the PyCharm setting that activates it for you.

      Git and GitHub Fundamentals: Commits, Branches, Push and Pull

      The Git you use every day, on a tiny hello-ml project: commits as save points, the staging area, a branch merged with a fast-forward, then push, clone, pull and pull requests with a teammate.

      Testing a FastAPI App with pytest: Three Small Tests

      A tiny FastAPI app with a Hello World route and a name route that refuses numbers, three pytest tests that check it, and what happens when the validation is deleted by mistake.

      Config and Logging Instead of Hard-Coded Values in ML Training

      Take the hard-coded values out of a car price training script: one config.toml read with tomllib, logging with levels and a run id on every line, and secrets read from the environment. Same RMSE, 2195, before and after.

      On this page
      • A forecaster who says 80%
      • Three parts, one job each
      • The model ranks the days well
      • The reliability curve and ECE
      • Fix 1: Platt scaling, a sigmoid
      • Fix 2: isotonic regression, a staircase
      • Only now: score all three on the test part
      • Fit the fix on rows the model never saw
      • Does it hold on other splits?
      • Common mistakes
      • Recap
      • Try it yourself
      Single logo

      StudyEasy AI Community

      Hosted onSkool

      Learn AI engineering, share what you build, and connect with other learners.

      • Free resources: lesson files, notebooks and code

      • Ask questions and join engineering discussions

      • Meet real people learning and building with AI

      Join free on Skool
      Go deeper with a course

      Machine Learning Engineer: From First Model to ML Engineer

      Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)

      Single logo

      Empowering Education, One Course at a Time

      About
      About usContact usFAQs
      Legal
      Terms of ServicePrivacy Policy

      © 2026 StudyEasy Organization. All rights reserved.