Lecture 2: Special Topics in Machine Learning

ML Strategy, Error Analysis, and Simple ML Serving

Special Topics in Artificial Intelligence (STAI 2026)

Why This Lecture Matters

  • Training a model is the easy part. Deciding what to do next is the hard part.
  • A typical ML project offers dozens of possible improvements: more data, bigger model, new architecture, more tuning…
  • Trying them randomly can waste weeks or months.
  • Today: a way of thinking about ML projects, used by experienced practitioners.

Today’s Roadmap

Part Topic
1 Why ML strategy, and orthogonalization
2 Setting the goal: metrics and data splits
3 Human-level performance, bias and variance
4 Error analysis and prioritization
5 When training data and real data differ
6 From model to application: simple ML serving

Part 1: Why ML Strategy?

A Familiar Scenario

You built a cat classifier. After some training: 90% accuracy.

Not good enough for your application. What now?

  • Collect more data?
  • Collect a more diverse training set?
  • Train longer? Try a different optimizer?
  • Try a bigger network? A smaller network?
  • Try dropout? Add regularization?
  • Change the architecture?

Strategy Means Choosing What to Fix First

Key idea

ML strategy is a set of quick, reliable ways to figure out which ideas are worth pursuing and which you can safely discard.

  • Without strategy: trial and error, wasted effort, frustration.
  • With strategy: measure, diagnose, then act on the bottleneck.
  • The rest of this lecture is a toolbox for that diagnosis.

Part 1b: Orthogonalization

One Knob, One Effect

Old TV sets were easy to tune because each knob did one thing. Same in a car: steering for direction, pedals for speed.

Orthogonalization

Design your workflow so that each “knob” fixes one specific problem.

The Chain of Assumptions in ML

For a system to work in practice, four things must be true in order:

If stage 2 fails, stage 3 knobs will not help.

Which Knobs Fix Which Stage

Problem Typical knobs
Poor fit on training set Bigger model, train longer, better optimizer, better architecture
Poor fit on dev set Regularization, more training data
Poor fit on test set Get a bigger dev set (you over-tuned to it)
Poor real-world performance Change the dev/test set or the metric (they aim at the wrong target)

Discussion (5 minutes)

Your team’s model fits the training data almost perfectly, but performs poorly on new data.

  1. Which stage of the chain is failing?
  2. Which knobs would you consider first?
  3. Would “train longer” help here? Why or why not?

Part 2: Setting the Goal

A Single-Number Evaluation Metric

You compare two classifiers using precision and recall:

Classifier Precision Recall Which is better?
A 95% 90% ?
B 98% 85% ?

Two numbers: no clear winner, slow decisions. Combine them into one number, for example F1 (a balanced combination of precision and recall):

Classifier F1 score
A 92.4%
B 91.0%

Why One Number Speeds You Up

Applied ML is an empirical loop.

  • Every experiment ends with a decision: keep it or drop it?
  • One clear number makes each decision fast and unambiguous.
  • Faster loop = more ideas tested = faster progress.

Satisficing and Optimizing Metrics

Not every metric should be maximized. Often you want:

Maximize one metric, subject to constraints on the others.

Classifier Accuracy Running time
A 90% 80 ms
B 92% 95 ms
C 95% 1500 ms

Rule: maximize accuracy (optimizing) subject to running time below 100 ms (satisficing). Winner: B.

Guidelines for Choosing Metrics

  • Pick one optimizing metric: the thing you truly want more of.
  • Turn the rest into thresholds: latency, memory, cost, fairness constraints.
  • Write the metric down before running experiments.
  • A metric is a target, not a law: if it stops reflecting what you care about, change it (more on this soon).

Quick check (1 minute): for a voice assistant wake word, which metric is optimizing and which is satisficing?

Part 2b: Train, Dev, and Test Sets

What Each Set Is For

Set Purpose Used how often?
Training set Fit the model’s parameters Constantly
Dev set Compare models, tune choices Frequently
Test set Final, honest performance estimate Once, at the end

Important

The dev set is the target you aim at for weeks or months. Point it at the right target.

Dev and Test Must Aim at the Same Target

Bad idea (true story pattern): dev set from some regions, test set from other regions.

Fix: shuffle everything together, then split dev and test from the same distribution.

The Golden Guideline

Guideline

Choose dev and test sets that reflect the data you expect to get in the future and consider important to do well on.

  • Future user data matters more than convenient historical data.
  • If real usage will be blurry phone photos, the dev set should contain blurry phone photos.

How Big Should Dev and Test Sets Be?

Principle: dev set big enough to detect differences between models; test set big enough for confidence in the final number.

When Metric and Dev Set Mislead You

  • Algorithm A: 3% error, but sometimes shows inappropriate images
  • Algorithm B: 5% error, never does

Metric says A; users prefer B. The data can mislead too:

Important

If doing well on your metric + dev/test set does not correspond to doing well in your application: change the metric or the dev/test set.

Discussion (5 minutes)

You are building a defect detector for a factory. You train and evaluate on sharp, well-lit photos from the vendor’s catalog. On the production line, images come from a fixed camera with glare and dust.

  1. What is wrong with the current dev/test setup?
  2. What would you change first: the model or the data split?
  3. What would your single-number metric be?

Part 3: Human-Level Performance

Why Compare With Humans?

While the model is worse than humans, you have tools:

  • get more labeled data from humans
  • error analysis: “why did a person get this right?”
  • better bias/variance diagnosis

Human-Level Error as a Proxy for Bayes Error

Bayes error: the best possible error any system could ever achieve (some noise is simply irreducible).

Medical image example: what is “human-level” error?

Who Error
Typical human 3%
Typical doctor 1%
Experienced doctor 0.7%
Team of experienced doctors 0.5%

Use the best available human performance (0.5%) as the proxy.

Avoidable Bias

Same training error (8%) and dev error (10%), opposite conclusions:

Variance

Variance = the gap between training error and dev error: the model memorized more than it generalized.

The Diagnosis Recipe

Discussion (5 minutes)

Diagnose each case (human-level error is about 0.5%):

Case Training error Dev error Your diagnosis?
A 6.0% 6.5% ?
B 0.7% 5.0% ?
C 0.7% 0.9% ?

Part 3b: Improving Performance

The Practical Decision Table

Diagnosis What to try
High avoidable bias (human → training gap) Bigger model; train longer; better optimizer; better architecture
High variance (training → dev gap) More data; regularization; data augmentation; simpler model

The two assumptions of supervised learning

  1. You can fit the training set well (low avoidable bias).
  2. Training performance generalizes to dev/test (low variance).

Part 4: Error Analysis

Look at Your Errors. Literally.

Cat classifier: 10% error. “It keeps mistaking dogs for cats, let’s fix dogs!” Before spending months, do error analysis:

  1. Take about 100 misclassified dev set examples.
  2. Look at them, one by one, by hand.
  3. Count: how many are actually dogs?
  • 5 of 100 are dogs: ceiling 10% → 9.5%. Not worth it.
  • 50 of 100 are dogs: ceiling 10% → 5%. Very promising.

Categorize Errors in a Simple Table

Evaluate several improvement ideas in parallel, in a spreadsheet:

Image # Dog Great cat (lion, panther…) Blurry Comments
1 pitbull
2
3 rainy day at zoo
% of total 8% 43% 61%

New categories can be added mid-way (rows can tick several boxes).

Classroom Activity (5 minutes)

Your error analysis of 100 misclassified images gives:

Category Share of errors
Blurry images 60%
Dogs labeled as cats 25%
Exotic cats 10%
Wrong labels 5%
  1. What would you try first, and why?
  2. Your teammate insists on fixing the dog problem because it is “technically interesting”. What do you tell them?

Debrief: Compare the Ceilings

Error analysis does not give a rigid formula. It gives a clear sense of the best options.

Incorrect Labels: Training Set

Deep learning is fairly robust to random label errors in training data.

  • A few percent of random mislabels: usually fine to leave them.
  • But systematic errors are learned! (If white dogs are consistently labeled “cat”, the model will learn it.)

Incorrect Labels: Dev and Test Sets

Here wrong labels can corrupt your comparisons between models.

  • Add an “incorrectly labeled” column to your error analysis table.
  • Dev error 10%, of which 0.6% from bad labels: ignore for now.
  • Dev error 2%, of which 0.6% from bad labels: it dominates: fix the labels.

If you clean labels: apply the same process to dev and test, so they stay from the same distribution.

Build First, Then Iterate

Speech recognition: noisy background, accents, far microphone, children, stuttering… Which to focus on? You cannot know in advance.

Part 5: When Training and Real Data Differ

Data Mismatch Is the Normal Case

Cat app: 200,000 clean web images available, but users upload 10,000 blurry mobile images. Where should the scarce real data go?

A New Suspect Needs a New Test: the Training-Dev Set

With mismatched data, a train → dev gap has two possible causes:

  1. The model does not generalize (variance), or
  2. The dev data is simply different and harder (mismatch).

To separate them, carve out a training-dev set:

  • same distribution as training data
  • not used for training

Now: train vs training-dev isolates variance; training-dev vs dev isolates mismatch.

Reading the Four Gaps

Quick cases (human ≈ 0%):

  • train 1%, train-dev 9%, dev 10%: variance
  • train 1%, train-dev 1.5%, dev 10%: mismatch
  • train 10%, train-dev 11%, dev 12%: avoidable bias

Addressing Data Mismatch

  • Manual error analysis: how exactly does dev data differ? (noise? blur? vocabulary?)
  • Make training data more similar to dev/test, or collect more real target data.
  • Artificial data synthesis: clean speech + car noise = in-car audio; rendered objects for images:

Synthesis risk

Synthesizing from a small slice (one hour of car noise, a few 3D car models) makes the model overfit to that slice: perfect to human eyes, yet unrepresentative of the real world.

Discussion (5 minutes)

A team trains a vibration-anomaly detector for pumps using data from a clean laboratory test rig. Deployed in the plant, it misses real faults.

  1. Which diagnosis would you check first: bias, variance, or mismatch, and how?
  2. The team proposes adding synthetic factory noise to lab signals. What is the promise, and what is the risk?

Part 6: From Model to Application

Training Is Not the End

A model in a notebook helps nobody but you. It becomes useful when other people or systems can send it inputs and get predictions back.

ML serving = making your model available as a service:

What Is an API?

API = a defined way for programs to talk to each other over the network.

Your model’s API can be one single “door”:

POST /predict
  input:  { "features": [5.1, 3.5, 1.4, 0.2] }
  output: { "prediction": "class_A", "probability": 0.97 }
  • The caller does not need Python, or your libraries, or your GPU.
  • A web app, a phone app, or a factory system can all call the same door.

A Tiny Prediction API (Conceptual)

from fastapi import FastAPI
import joblib

app = FastAPI()
model = joblib.load("model.pkl")     # step 2: the saved model file

@app.post("/predict")
def predict(features: list[float]):
    prediction = model.predict([features])
    return {"prediction": prediction[0]}

About 10 lines: your model is now a web service.

What Is Docker?

Problem: “it works on my machine” (but not on the server, or your teammate’s laptop).

Docker packages your code plus its whole environment into one shippable unit:

  • Same environment everywhere: laptop, server, cloud
  • Easy sharing and easy deployment: one command to run

Demo: Two Commands

# Build the image (package the app + model + environment)
docker build -t ml-api .

# Run it as a container, exposed on port 8000
docker run -p 8000:8000 ml-api

Then, from anywhere that can reach the machine:

POST http://localhost:8000/predict  →  { "prediction": ... }

Note

You do not need to master Docker in this course. You only need the idea: model → API → container → anyone can use it. We will revisit this hands-on in the practical weeks.

Wrap-Up

Key Takeaways

  1. Good ML work needs strategy, not random trial and error.
  2. Choose one clear metric and a dev/test set that represents real future data.
  3. Diagnose before treating: avoidable bias, variance, data mismatch (three or four numbers, simple gaps).
  4. Error analysis: look at about 100 errors by hand, count categories, fix the biggest ceiling first.
  5. Build a simple system first, then iterate: Build → Evaluate → Analyze → Prioritize → Improve.
  6. A model becomes useful when it is served: API + Docker connect models to real applications.