Lecture 2: Machine Learning Strategy and Best Practices

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 Introduction to ML strategy
2 Setting up your goal: metrics and data splits
3 Comparing to human-level performance
4 Error analysis
5 Mismatched training and dev/test data
6 From model to application: simple ML serving

Introduction to 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.

A Useful Habit: One Knob, One Job

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

This habit has a name, orthogonalization: set up your workflow so that each control primarily addresses one objective, as independently as possible from the others.

Four Things Must Be True, in Order

For a system to work in practice, four things must be true in order, and each stage has its own knobs:

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

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?

Setting Up Your 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?

Train, Dev, and Test Sets

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 to Change Dev/Test Sets and Metrics

  • 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?

Comparing to 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).

If humans do a task quite well and you can estimate their error, that human-level error is a good proxy for Bayes error.

Hypothetical 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.

Quick check (1 minute): training error 2%, dev error 9%, humans around 1.5%. Bias or variance?

The Diagnosis Recipe

Surpassing Human-Level Performance

Once your model is better than humans, these tools become less effective: human labels and manual comparisons provide less guidance, and the Bayes proxy itself becomes unclear.

ML already surpasses humans in some areas:

  • Where: online advertising, product recommendations, logistics (predicting transit times), loan approvals.
  • What these share: structured data, huge datasets, and no natural perception involved.
  • On perception tasks (vision, speech), humans are hard to beat, though it happens: some speech recognition, some image recognition, some medical imaging (ECG reading, skin cancer).

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% ?

Improving Your Model Performance

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).

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 Big cat (lion, panther…) Blurry Comments
1 ✓ husky
2 ✓
3 ✓ ✓ night photo at the 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.

Cleaning Up Incorrect Labels: Training Set

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

  • Some random mislabels may be acceptable if they do not significantly affect performance.
  • But systematic errors are learned! (If white dogs are consistently labeled “cat”, the model will learn it.)

Cleaning Up Incorrect Labels: Dev and Test Sets

The dev set has one job: telling you which model is better. Wrong labels add fake error that can drown out that signal. So count how many “mistakes” are really labeling mistakes, and check their share of the total error:

Dev error From bad labels Share What to do
10% 0.6% 6% Ignore for now: noise, not the bottleneck
2% 0.6% 30% Fix the labels: comparisons break down

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

Build Your First System Quickly, Then Iterate

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

Mismatched Training and Dev/Test Data

Training and Testing on Different Distributions

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 Three 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) can make 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?

From Model to Application: Simple ML Serving

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:  [5.1, 3.5, 1.4, 0.2]
  output: { "prediction": "class_A" }
  • 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": str(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.

Discussion (3 minutes)

Instead of serving the model, you simply email model.pkl to a teammate.

  1. Name two things that can go wrong when they try to use it.
  2. Which step of the serving workflow fixes each one?

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, compare the ceilings before choosing what to fix.
  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.