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

      Slice Evaluation and Fairness Checks: Score the Model Group by Group

      One overall MAE of $4,181 hides a group the insurance model misses by twice as much. Cut the test rows by smoker, sex, region and age band, check each gap with row counts, bootstrap ranges and 20 re-splits, and write a failure-slice report that says what was measured and nothing more.

      Chaand Sheikh

      ·27 November 2026Experiments and Model Quality

      What you will learn

      • Compute a metric per slice with groupby and compare it with the overall score
      • Use row counts, bootstrap ranges and re-splits to tell a real gap from noise
      • Build a failure-slice report with a written flag rule
      • Describe a bad slice with numbers, without claiming a cause you did not test

      Before you start

      • Regression Metrics: MAE, RMSE and R-squared
      • pandas groupby

      One good overall score can hide a group where the model does badly. In this article we check a model group by group: a metric per slice, a failure-slice report, and the row count beside every number.

      A class average of 75, and one row failing

      Twenty students sit in four rows of five. Three rows scored 90, and the class average comes out at 75. Looks fine. But every student in row four scored 30.

      The average looks fine while one whole row is failing. For us, the class average is the overall score, and a row is a slice: a group of test rows that share a value, like smoker = yes.

      The same model, and one overall number

      The model is the one from Regression Metrics: the insurance data, the same split, the same linear regression, fit on the train rows only. test_table then copies the test rows into one table with the actual bill, the guess and the miss.

      """Train the insurance model, and give back the test rows with misses."""
      import pandas as pd
      from sklearn.compose import ColumnTransformer
      from sklearn.linear_model import LinearRegression
      from sklearn.model_selection import train_test_split
      from sklearn.pipeline import Pipeline
      from sklearn.preprocessing import OneHotEncoder
      
      CSV = "data/insurance.csv"
      
      
      def test_table(seed=42):
          df = pd.read_csv(CSV)
          X, y = df.drop(columns="charges"), df["charges"]
          X_train, X_test, y_train, y_test = train_test_split(
              X, y, test_size=0.2, random_state=seed)
          pre = ColumnTransformer([
              ("num", "passthrough", ["age", "bmi", "children"]),
              ("cat", OneHotEncoder(drop="first"),
               ["sex", "smoker", "region"])])
          model = Pipeline([("pre", pre), ("reg", LinearRegression())])
          model.fit(X_train, y_train)
          t = X_test.copy()
          t["actual"] = y_test
          t["pred"] = model.predict(X_test)
          t["miss"] = (t["actual"] - t["pred"]).abs()
          t["age_band"] = pd.cut(t["age"], [17, 29, 44, 64],
                                 labels=["18-29", "30-44", "45-64"])
          return t
      
      
      if __name__ == "__main__":
          t = test_table()
          print("test rows", len(t))
          print("overall MAE", round(t["miss"].mean()))
      test rows 268
      overall MAE 4181

      The miss is the gap between bill and guess, without the sign. The first person is off by only $126; a smoker a few rows down is off by $7,527. The average of all 268 misses is our score, $4,181, the same number as before. age_band cuts age into three groups so we can slice by it later.

      Cut the test rows by one column

      slice_report groups the test rows, gives each group its own average miss, and divides it by the overall miss:

      import numpy as np
      import pandas as pd
      
      MIN_ROWS = 30
      FLAG_AT = 1.5
      
      
      def flag(rows, x_all):
          if rows < MIN_ROWS:
              return "FEW ROWS"
          return "CHECK" if x_all >= FLAG_AT else ""
      
      
      def slice_report(t, by):
          overall = t["miss"].mean()
          out = []
          for key, g in t.groupby(by, observed=True):
              key = key if isinstance(key, tuple) else (key,)
              name = " & ".join(f"{c}={v}" for c, v in zip(by, key))
              mae = g["miss"].mean()
              x_all = mae / overall
              bill = g["actual"].mean()
              out.append({"slice": name, "rows": len(g), "mae": mae,
                          "x_all": x_all, "bill": bill, "pct": mae / bill,
                          "flag": flag(len(g), x_all)})
          return pd.DataFrame(out)
      python report.py smoker
      slice                    rows    MAE  x all  flag
      smoker=no                 214   3130   0.75
      smoker=yes                 54   8348   2.00  CHECK

      214 non-smokers with an average miss of $3,130, and 54 smokers at $8,348. The smokers sit at two times the overall miss; the non-smokers at 0.75. Same model, same rows, and each group gets its own score, with the row count right beside it.

      Every column is a way to slice

      python report.py sex region age_band
      slice                    rows    MAE  x all  flag
      sex=female                140   3733   0.89
      sex=male                  128   4672   1.12
      region=northeast           57   3922   0.94
      region=northwest           69   3571   0.85
      region=southeast           81   5174   1.24
      region=southwest           61   3796   0.91
      age_band=18-29             87   3845   0.92
      age_band=30-44             82   4145   0.99
      age_band=45-64             99   4506   1.08  
      Average miss per slice against the overall miss and the flag line smoker=no (214 rows) $3,130 smoker=yes (54 rows) $8,348 sex=female (140 rows) $3,733 sex=male (128 rows) $4,672 region=northeast (57 rows) $3,922 region=northwest (69 rows) $3,571 region=southeast (81 rows) $5,174 region=southwest (61 rows) $3,796 age_band=18-29 (87 rows) $3,845 age_band=30-44 (82 rows) $4,145 age_band=45-64 (99 rows) $4,506 overall $4,181 flag line, 1.5x
      Average miss per slice, drawn from the project's own run. Only smokers cross the flag line at 1.5 times the overall miss.

      Southeast is the highest, at 1.24 times, but nothing here reaches the flag line. A column with no failing slice is a result too.

      A small slice is a noisy slice

      How much should we trust a slice with only a few rows? Take the rows of one slice and resample them with replacement 1,000 times. Each resample gives its own average miss; the middle 95% of those averages is the range.

      def resample_means(values, n=1000, seed=0):
          rng = np.random.default_rng(seed)
          return [rng.choice(values, len(values)).mean() for _ in range(n)]
      
      
      def interval(values, n=1000, seed=0):
          return np.percentile(resample_means(values, n, seed), [2.5, 97.5])
      python ranges.py
      slice                    rows    MAE   95% range
      smoker=no                 214   3130   2676 to 3626
      smoker=yes                 54   8348   7729 to 9091
      smoker=yes & sex=female    23   8731   7769 to 10304
      sex=female                140   3733   3085 to 4404
      sex=male                  128   4672   3958 to 5356
      male minus female: +939, range -28 to +1883

      The 54 smokers range from $7,729 to $9,091. The 23 female smokers range much wider, from $7,769 to $10,304. Fewer rows, wider range.

      The same works on a gap. Male minus female is $939, but its range runs from -28 to +1,883. Zero is just inside it, so this split alone can't tell you the gap is real.

      Is the gap real, or did one split make it?

      Another check: split the data 20 other ways, retrain each time, and measure both gaps again.

      from model import test_table
      
      smoker_x, sex_gap = [], []
      for seed in range(20):
          t = test_table(seed)
          by_smoker = t.groupby("smoker")["miss"].mean()
          by_sex = t.groupby("sex")["miss"].mean()
          smoker_x.append(by_smoker["yes"] / t["miss"].mean())
          sex_gap.append(by_sex["male"] - by_sex["female"])
      # ... then print the counts and ranges (see resplit.py)
      20 re-splits, seeds 0 to 19
      smoker MAE above overall: 20 of 20
      smoker x overall: 1.89 to 2.40
      male MAE above female: 14 of 20
      male minus female: -707 to +806

      The smoker miss is above the overall in every split, between 1.89 and 2.40 times. The sex gap changes side: male is higher in 14 of 20, anywhere from -$707 to +$806. One gap holds; the other doesn't.

      The failure-slice report

      Now turn all of this into a short report. The flag function above holds two numbers we chose, written down in the code:

      • Fewer than MIN_ROWS = 30 rows: flagged FEW ROWS, and it gets no verdict.
      • FLAG_AT = 1.5 times the overall miss or more: flagged CHECK.
      python report.py --flagged smoker sex region age_band smoker,sex
      slice                     rows    MAE  x all  flag
      smoker=yes                  54   8348   2.00  CHECK
      smoker=yes & sex=female     23   8731   2.09  FEW ROWS
      smoker=yes & sex=male       31   8064   1.93  CHECK

      Fifteen slices go in (including the four smoker-and-sex combinations), and only three come out. The female smokers have a high miss, but with 23 rows the report refuses to judge them.

      The same misses, two readings

      python report.py --pct smoker
      slice                    rows    MAE  x all  avg bill  % of bill  flag
      smoker=no                 214   3130   0.75      7862        40%
      smoker=yes                 54   8348   2.00     33204        25%  CHECK

      In dollars, smokers are missed by more: $8,348 on an average bill of $33,204. As a share of the bill it flips: non-smokers are missed by 40%, smokers by 25%. Neither view is wrong. Pick the one that matches the cost of a mistake, and say which one you used.

      A bad slice gets numbers, not a verdict

      def describe(row, overall):
          if row["flag"] == "FEW ROWS":
              return f"{row['slice']}: only {row['rows']} rows, too few to read."
          return (f"{row['slice']}: {row['rows']} rows, MAE {row['mae']:.0f}, "
                  f"{row['x_all']:.1f} times the overall {overall:.0f}.")
      python report.py --say smoker sex smoker,sex
      smoker=yes: 54 rows, MAE 8348, 2.0 times the overall 4181.
      smoker=yes & sex=female: only 23 rows, too few to read.
      smoker=yes & sex=male: 31 rows, MAE 8064, 1.9 times the overall 4181.

      Put together, the write-up reads like this:

      • Smokers: 54 rows, a miss of $8,348, two times the overall, on the same side in 20 of 20 splits. Why? We haven't tested that.
      • Sex: no clear gap. $939 on this split, a range that includes zero, and male higher in only 14 of 20 splits. No verdict.
      Say what you measured. Don't claim a cause you didn't test. Whether to use the model at all is a decision for the people who own it.

      This check shows how the misses differ by group. It doesn't say why.

      Common mistakes

      • Reporting only the overall score. $4,181 hid a group missed by $8,348.
      • Hiding the row count. A slice of 23 rows can swing by thousands of dollars. Always print the count.
      • Trusting a gap from one split. The sex gap looked like $939, then changed side across re-splits.
      • Moving the flag rule after seeing the results. Choose MIN_ROWS and FLAG_AT first and write them in the code.
      • Turning a measurement into a cause. "Smokers are missed more" is measured. "Because of X" needs its own test.

      Recap

      CheckWhat it tells youHere
      Metric per slicewhich group the model misses mostsmokers 2.00x overall
      Row counthow much to trust itfemale smokers: 23 rows, no verdict
      Bootstrap rangehow far the number could movesex gap -28 to +1,883
      Re-splitswhether the gap survivessmokers 20/20, sex 14/20
      Flag rulewhich slices deserve a second look< 30 rows, or >= 1.5x

      Try it yourself

      Run python report.py region,age_band. Which slices are too small to read, and what does the report call them?

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

      Join free on Skool →
      ← Previous
      Probability Calibration: Can You Trust the 0.8? Reliability Curves, Platt and Isotonic
      Next →
      Saving and Loading Models with joblib: One Pipeline, One File
      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 class average of 75, and one row failing
      • The same model, and one overall number
      • Cut the test rows by one column
      • Every column is a way to slice
      • A small slice is a noisy slice
      • Is the gap real, or did one split make it?
      • The failure-slice report
      • The same misses, two readings
      • A bad slice gets numbers, not a verdict
      • 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.