Machine Learning in the Real World
Metrics, messy data, deployment and responsibility.
A model can top a leaderboard and still fail the people who rely on it. In practice, most of machine learning happens around the algorithm: deciding what a prediction is for, counting the mistakes that matter, taming messy data, and watching the model after it ships, when the world starts to change under it.
What you’ll learn
- Walk through a real machine learning project, from framing the decision to monitoring the deployed model.
- Explain why accuracy misleads when one class is rare, and read precision and recall from a confusion matrix.
- Choose a decision threshold from the costs of the two kinds of mistakes, and say what it means for a predicted probability to be calibrated.
- Spot missing values, leakage and class imbalance in messy data, and name the ways the world can shift after deployment.
- Explain why fairness criteria can conflict, and why explanations and causal reasoning matter when predictions drive decisions.
From a model to a decision
A hospital asks you for a model that predicts which patients will be readmitted within 30 days of leaving. Before you choose any algorithm, ask what the hospital will do with a prediction. If the answer is "a nurse calls the riskiest patients for a check-up", then what matters is the ranking near the top of the list and how many calls the nurses can make. A model that is excellent on average but muddled among the riskiest patients is useless for that job.
Real projects follow a loop that looks roughly like this:
- Frame the decision. What action does a prediction trigger, and what does each kind of mistake cost?
- Build a baseline. The simplest thing that could work: always predict the common class, a one-line rule, or a small logistic regression.
- Split the data into training, validation and test sets the way the future will arrive: by date, by patient, by store.
- Pick a metric that matches the cost of mistakes.
- Iterate with error analysis. Read the cases the model gets wrong; fixing data and features often beats a bigger model.
- Deploy, with exactly the same data preparation as in training.
- Monitor the inputs, the predictions and, once they arrive, the outcomes.
You have one week to build a model that flags fraudulent insurance claims. What should you build first?
- A large neural network, tuned until its training accuracy is as high as possible
- Nothing, until you have collected ten times more data
- A model judged by its accuracy on the training data, to see how high the score can go
- A simple baseline, such as a small logistic regression, scored next to the trivial rule "no claim is fraud"
Show the answer
D. A simple baseline, such as a small logistic regression, scored next to the trivial rule "no claim is fraud"
A baseline tells you what "good" means. If an elaborate model barely beats the trivial rule or a small logistic regression, its complexity is not paying for itself, and the simple model is often what ends up in production. It also gives you a working pipeline from raw data to a score on day one.
The accuracy trap
On a production line, 1 part in 100 is defective. A "model" that passes every part is right 99% of the time and catches nothing. Accuracy, the fraction of correct predictions, hides how the errors are split between the two classes, and when one class is rare (class imbalance) that split is the whole story.
A confusion matrix keeps the four outcomes apart. Call the rare class (defective) positive:
| The part really is… | Flagged as defective | Passed as fine |
|---|---|---|
| defective | true positive (TP) | false negative (FN): a defect shipped |
| fine | false positive (FP): a good part scrapped | true negative (TN) |
Two rates summarize the matrix. Precision asks: of the parts I flagged, how many were really defective? Recall asks: of the defective parts, how many did I flag?
An inspection model catches 90% of defective parts and wrongly flags 5% of good parts. One part in 100 is defective. Of the parts it flags, what percentage are actually defective?
Show the answer
15 %
Take 10,000 parts: 100 are defective and 90 of those are flagged; 9,900 are fine and 5% of them, 495, are flagged too. So only 90 of the 585 flagged parts are defective: about 15%. More than five false alarms for every real defect, from a model that is right about 95% of good parts. When positives are rare, even a small false-positive rate swamps the real hits.
One score, many thresholds
Most classifiers do not output "defective" or "fine" directly. They output a score, and you choose a threshold: everything above it is flagged. Lower the threshold and you catch more positives (recall goes up) but also flag more negatives (precision usually goes down). Raise it and the reverse happens.
So the threshold is a business decision, not a property of the model. A cancer screen followed by a cheap second test can afford many false alarms; a filter that deletes posts with no human review cannot.
Airport scanners send suspicious bags to a manual search, which takes a few minutes. Missing a dangerous item is unacceptable. How should the threshold be set, and which metric should you watch most closely?
- Low, keeping recall very high, and accept many false alarms
- High, keeping precision very high, so few bags are searched
- At 50%, to maximize accuracy
- Anywhere: the threshold does not affect what gets caught
Show the answer
A. Low, keeping recall very high, and accept many false alarms
A missed item is catastrophic and a false alarm costs a few minutes, so the threshold goes low enough that nearly every dangerous bag is flagged: high recall, with low precision accepted as the price. The manual search, a second and more accurate test, sorts out the false alarms.
Can you trust the probability?
Many models output a probability: "this loan has a 12% chance of default". If the number itself is used to price the loan, to triage patients or to weigh costs, it has to mean what it says. A forecaster who says "80% chance of rain" should see rain on about 80% of those days. A model with this property is calibrated.
Calibration and ranking are different things. A model can put cases in exactly the right order, from least to most likely, and still say 99% when it should say 60%. You check calibration with a reliability diagram: group the predictions into bins, and compare each bin's average prediction with how often the event really happened.
Over a year, a model said "20% chance of default" for 500 loans, and 100 of them defaulted. For another 500 loans it said "60%", and 150 defaulted. What can you conclude?
- It is calibrated in both groups
- It underestimates the risk of the 20% group
- It is calibrated at 20% but overestimates the risk of the 60% group
- Nothing: calibration can only be judged from the accuracy
Show the answer
C. It is calibrated at 20% but overestimates the risk of the 60% group
In the first group 100 of 500 defaulted, exactly 20%. In the second, 150 of 500 is 30%, half of the 60% the model claimed. A lender pricing those loans at a 60% risk would turn away many good customers.
Messy data
Textbook datasets arrive clean. Real ones arrive with holes, traps and quirks, and fixing them is usually where the biggest gains are. A few of the most common problems:
| Problem | Example | Why it hurts | First response |
|---|---|---|---|
| Missing values | a lab test that was never ordered | dropping incomplete rows wastes data and can skew the sample; the very fact that a value is missing can predict the outcome | fill the gap (imputation) and keep a "was missing" flag as a feature |
| Leakage | a field filled in after the outcome you are predicting | the model looks brilliant in testing and fails in use | for every feature, ask: would I know this at the moment of prediction? |
| Class imbalance | 1 fraudulent payment in 1,000 | accuracy and a default 50% threshold both mislead | measure precision and recall; move the threshold |
| Mixed scales | income in dollars next to age in years | methods based on distances let the biggest numbers dominate | standardize the features |
| Duplicates | the same patient in training and test data | test scores overstate performance | deduplicate, and split by patient |
| Wrong labels | misrecorded diagnoses | the model learns the mistakes | audit a random sample of labels |
A model predicts which customers will cancel their subscription next month. Its test accuracy is 99.7%, far above anything else you tried. One feature is "support tickets in the last 30 days", computed on the day the data were exported, months after the cancellations happened. What is the most likely explanation?
- The model is excellent and should be deployed
- The model overfits because it has too many features
- Leakage: the feature was computed after the moment of prediction, so it partly records the outcome, for instance tickets filed to cancel or to ask for a refund
- Class imbalance makes the accuracy look high
Show the answer
C. Leakage: the feature was computed after the moment of prediction, so it partly records the outcome, for instance tickets filed to cancel or to ask for a refund
A feature must use only information available when the prediction would be made. Counting tickets up to the export date lets the outcome, a cancellation and the tickets around it, flow back into the inputs. A near-perfect score on a hard problem is a reason to hunt for leaks before celebrating.
After launch, the world moves
A test set is a snapshot of the past. Once a model is deployed, the data it sees can drift away from the data it learned from, a distribution shift. Three kinds come up again and again:
- The inputs change (covariate shift): the model of readmissions goes to a new hospital whose patients are older.
- The class balance changes (label shift): during a flu season, many more patients are readmitted.
- The relationship changes (concept drift): fraudsters adapt, so yesterday's warning signs stop working.
Models can also change their own future data. A recommender that shows only popular items collects clicks only on popular items, which seems to confirm that they are the best: a feedback loop.
Think first Your model's performance dropped a month after launch, yet nobody touched its code. List at least three different things that could have changed.
The inputs (a new group of customers), the class balance (a seasonal surge), the relationship between inputs and outcome (adaptive fraud), or the model's own influence on the data (a feedback loop). Very often it is none of these but a broken pipe upstream: a unit switched from pounds to kilograms, a renamed category, a sensor that started reporting zeros. That is why monitoring watches the inputs and the predictions, not only the final accuracy, which may arrive weeks late.
Fair, explainable and causal
When predictions decide who gets a loan, a job interview or a treatment, two more requirements become engineering requirements. Fairness: the model should not treat groups of people differently in ways that are unjustified. But "treat equally" has several precise meanings that pull against each other:
- Demographic parity: both groups are approved at the same rate.
- Equal opportunity: among people who would repay, both groups are approved at the same rate.
- Equalized odds: equal approval rates among those who would repay and among those who would not.
Interpretability: people affected by a decision may be owed a reason, regulators may demand one, and engineers need one to debug. Some models are readable by design, such as a short decision tree or a sparse linear model; for others, explanation methods estimate which features drove a prediction, and those estimates can mislead.
Causality: a predictive model learns associations, not effects. In a famous case from the 1990s, retold by Caruana and colleagues (2015), a model trained on hospital records learned that pneumonia patients with asthma were at lower risk of dying. In the records they were, because doctors sent them straight to intensive care. Used to decide who could be treated at home, the model would have marked these high-risk patients as safe to send home. Questions of the form "what happens if we intervene?" need causal inference: randomized experiments, or careful assumptions about confounders.
| Descent lesson | What you will do there |
|---|---|
| Measuring Performance | Build every rate from the confusion matrix, read ROC and precision–recall curves, average over many classes, choose regression metrics that do not mislead, and score probabilities with proper scoring rules. |
| Feature Engineering & Messy Data | Scale and encode features (categories, text, dates), impute missing values, handle outliers and imbalanced classes, and build pipelines that cannot leak. |
| Deployment & a Changing World | Serve and monitor models, detect covariate, label and concept shift, run online experiments, and attach honest uncertainty to predictions. |
| Fairness, Interpretability & Causality | Formalize fairness criteria and their trade-offs, explain predictions with SHAP and LIME and learn where they fail, and tell prediction from causation. |
Key takeaways
- Start from the decision: what a prediction triggers and what each mistake costs. Build a simple baseline before anything clever.
- Accuracy misleads when one class is rare. Precision and recall split the errors, and the threshold, a business decision, trades one against the other.
- A calibrated 80% means 80%. Recalibration such as temperature scaling fixes the numbers without changing the ranking.
- Missing values, leakage, imbalance and mixed scales break more models than weak algorithms do, and after launch the world shifts: monitor inputs and predictions, not just accuracy.
- Fairness criteria conflict when base rates differ, so choosing among them is a value judgment; and a predictive model is not a causal one.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A disease affects 2% of the people screened. Model A has 98% accuracy; model B has 93% accuracy. Which model could be more useful?
- Model A, because its accuracy is higher
- Model B: A's accuracy is exactly what the rule "nobody is sick" scores, so A may detect no one at all
- Neither: 93% accuracy is too low for medicine
- They are equally useful, since both are above 90%
Show the answer
B. Model B: A's accuracy is exactly what the rule "nobody is sick" scores, so A may detect no one at all
With 2% prevalence, declaring everyone healthy is 98% accurate. Model A may be doing exactly that, while model B may catch most real cases at the cost of some false alarms. You cannot tell without recall and precision, which is the point: accuracy alone cannot tell you.
You lower a classifier's decision threshold. What typically happens?
- Precision and recall both rise
- Recall falls and precision rises
- Nothing: the threshold only changes the scores
- Recall rises, and precision usually falls
Show the answer
D. Recall rises, and precision usually falls
A lower threshold flags more cases. More of the real positives are caught, so recall rises (or stays the same); but more negatives are flagged too, so the flagged set usually becomes less pure.
A calibrated model assigns a probability of 0.3 to each of 1,000 cases. About how many of them should turn out positive?
- About 300
- About 700
- About 500
- None, since 0.3 is below the 0.5 threshold
Show the answer
A. About 300
Calibration means the predicted probability matches the long-run frequency: among cases given 0.3, about 30% are positive. The threshold decides what you do with a case; it does not change how often the event happens.
After deployment, the share of positive cases drops from 30% to 5%, while each class's score distribution stays the same. At a fixed threshold, what happens?
- Recall falls and the ROC curve sinks
- Precision falls, while recall and the ROC curve stay the same
- Nothing changes, since the scores are the same
- Accuracy and precision both rise
Show the answer
B. Precision falls, while recall and the ROC curve stay the same
Recall and the false-positive rate are measured within each class, and the classes' scores did not change, so they stay put, and so does the ROC curve built from them. Precision mixes the two classes: with fewer positives, the same false-positive rate produces relatively more false alarms.
Two groups of loan applicants have different repayment rates, and the scores are not perfect. Why can a lender usually not satisfy demographic parity and equalized odds at the same time?
- Because the law forbids using thresholds
- Because equalized odds is impossible for every model
- Because equal approval rates force different error rates when the groups' base rates differ, and equal error rates force different approval rates
- Because demographic parity requires a perfect model
Show the answer
C. Because equal approval rates force different error rates when the groups' base rates differ, and equal error rates force different approval rates
With equalized odds, a group's approval rate equals its base rate times the shared true-positive rate plus its share of defaulters times the shared false-positive rate. Different base rates then give different approval rates, unless the true-positive and false-positive rates are equal, which means approvals carry no information about who repays. In the widget, parity left the defaulters' approval rates 20 points apart. Choosing which criterion to keep is a value judgment.
Go deeper
- Measuring Performance · Accuracy, precision, recall, ROC curves and choosing what to optimize.
- Feature Engineering & Messy Data · Scaling, encoding, missing values and imbalanced classes.
- Deployment & a Changing World · Models in production, and the shifts that break them.
- Fairness, Interpretability & Causality · Making models fair, understandable and causally sound.
Further reading
- P. Domingos, "A few useful things to know about machine learning," Communications of the ACM 55(10), 78–87 (2012).
- D. Sculley et al., "Hidden technical debt in machine learning systems," Advances in Neural Information Processing Systems 28 (2015).
- M. Hardt & B. Recht, Patterns, Predictions, and Actions: Foundations of Machine Learning (Princeton University Press, 2022).