- View
When “great metrics” crumble after launch
A team ships a fraud model that looked strong during development. In production, fraud slips through in new patterns, and legitimate customers get blocked more often than expected. The model might not have “gotten worse” overnight—the evaluation logic may have been optimistic because the model and the team inadvertently learned from the wrong slice of data (or from the future).
Train/validation/test splits exist to answer one question honestly: How will this model perform on new, unseen data? Without disciplined splits, it’s easy to mistake memorization, leakage, or repeated tuning for real generalization. This lesson gives you a practical way to separate “learning” from “proving it works.”
What train/val/test actually means (and what each is for)
A dataset split partitions labeled examples into subsets with different jobs. The key idea is role separation: the data you use to fit the model should not be the same data you use to decide which model is best, and neither should be the same data you use to report final performance. This isn’t bureaucracy—it’s how you avoid fooling yourself.
Training set is what the model learns from. During training, the algorithm adjusts parameters to reduce loss on these examples. High training performance alone is not evidence of a good model; flexible models can score extremely well here by fitting quirks or shortcuts, especially when you add high-cardinality features, identifiers, or engineered signals that accidentally fingerprint the labels.
Validation set is for decisions. You use it to pick model families, select features, tune hyperparameters (tree depth, regularization strength, learning rate), and decide when to stop training (early stopping). The validation set is “held out” from fitting, but it still influences your choices—so it becomes part of the development loop and can be overfit through repeated iteration.
Test set is for the final exam. It should be touched once (or rarely) to estimate how the chosen approach generalizes. The moment you start making choices based on test performance—trying another feature, running “just one more” tuning pass—you’ve turned the test set into another validation set, and your reported number becomes less trustworthy.
| Dimension | Train | Validation | Test |
|---|---|---|---|
| Primary purpose | Fit parameters by minimizing loss | Choose among models and settings | Estimate generalization for the chosen system |
| How it influences the model | Directly shapes learned weights/structure | Indirectly shapes choices through iteration | Should not shape choices at all |
| What can go wrong | Model memorizes noise, IDs, or leakage-like patterns | You overfit by trying many variants (“selection-induced overfitting”) | You “peek” and tune, making the number optimistic |
| Mental model | Practice | Coaching and strategy | Final exam |
A useful misconception to kill early: “I didn’t train on the test set, so I’m safe.” You can still leak information by using the test set to decide anything. The leakage is procedural: your workflow adapts to the test outcomes even if the optimizer never sees those labels during fitting.
How splits protect you from overfitting (and how they can still fail)
The deeper principle behind splitting is the same tension you see with overfitting: the training data is a sample, not the world. A model can learn relationships that look stable inside your sample but don’t hold outside it. The split is a simulation of “outside,” giving you a stress test against brittle patterns.
The first failure mode is data leakage, where the model gets access to information it wouldn’t have at prediction time. Leakage doesn’t always look like a blatant “future feature.” It can come from subtle pipeline choices: computing an aggregate (like “average fraud rate per user”) using the full dataset before splitting, including timestamps that indirectly encode label timing, or using post-event fields that exist only after the outcome occurs. When leakage exists in both train and evaluation slices, metrics can look excellent while the model is effectively cheating.
The second failure mode is selection-induced overfitting. Each time you try a variant and keep the one that scores best on the same validation set, you increase the chance you’re selecting a model that got lucky on that specific sample. This is why validation performance can slowly become less predictive of real-world behavior after extensive iteration. The more degrees of freedom in your process—feature searches, architecture changes, threshold tweaks—the more you need to treat validation as a limited resource.
A third failure mode is using the wrong split strategy for the data-generating process. Random splits assume examples are independent and identically distributed (IID). But many ML problems are not IID: transactions are grouped by customer, medical images by hospital, forecasts by time, and logs by device. If you randomly split correlated examples across train and test, the test set becomes “too similar” to training, and the model looks like it generalizes when it mostly recognizes repeating entities or contexts.
Common split strategies (and when to use them)
Different splits protect against different kinds of accidental similarity between train and evaluation data. The right choice depends on what “new data” will look like in deployment: new time periods, new users, new sites, or just new random samples from the same stream.
| Split strategy | When it fits | What it prevents | Typical pitfall |
|---|---|---|---|
| Random split | Data is close to IID; deployment draws from the same distribution | Basic overfitting detection | Inflated metrics when entities repeat (same user/device appears in both) |
| Time-based split | Forecasting, churn, fraud drift, any “predict the future” setup | Future leakage and unrealistic evaluation | Hidden lookahead via features computed using future windows |
| Group-based split (by user, hospital, device, company) | Strong correlation within groups; want generalization to new groups | Memorizing group identity or artifacts | Losing too much data if groups are tiny; imbalance across splits |
| Stratified split | Classification with class imbalance; want stable label proportions | Overly skewed evaluation metrics | Stratifying incorrectly when groups/time must be respected first |
A practical assumption that keeps you safe: split by the unit you’ll generalize across. If success means working for new customers, split by customer. If success means working next month, split by time. Random splitting is fine only when it matches how the world will hand you new examples.
[[flowchart-placeholder]]
Evaluation logic you can trust: metrics, thresholds, and baselines
A clean split is necessary, but not sufficient. You also need evaluation logic that matches the decision you’re making. In many real systems, the model doesn’t just output “yes/no”—it outputs a score (a probability-like number), and you choose a threshold that trades off false positives and false negatives. If you change that threshold after looking at test outcomes, you’re again letting the test set influence decisions.
Start by being explicit about what you’re measuring. Accuracy can be misleading when classes are imbalanced (common in fraud, rare disease, defect detection). A model that predicts “not fraud” for every transaction can have high accuracy and still be useless. More decision-aware metrics include:
-
Precision: of what you flagged, how much was truly positive.
-
Recall: of all true positives, how many you caught.
-
ROC-AUC / PR-AUC: ranking quality across thresholds (PR-AUC is often more informative under heavy imbalance).
-
Cost-weighted metrics: when mistakes have different business costs.
A reliable workflow uses validation data to pick thresholds and operating points. For example, you might choose a threshold that achieves 90% recall while keeping precision above a minimum the fraud team can handle. The test set then estimates how well that chosen operating point generalizes. This keeps roles clean: validation is where you make tradeoffs; test is where you confirm performance.
Baselines matter, too. A “good” model should beat:
-
A naive baseline (majority class, last value, simple heuristic).
-
A simple model baseline (logistic regression, shallow tree) that acts as a sanity check.
-
A process baseline (what the business does today), when possible.
Baselines protect you from a common misconception: “complex model + high metric = progress.” Sometimes your pipeline is leaking, your split is too easy, or your metric doesn’t reflect the real decision. A baseline makes it harder for those issues to hide.
Two real-world split decisions, end to end
Example 1: Medical imaging across hospitals (avoiding “hospital recognition”)
You train a pneumonia detector on chest X-rays collected from Hospital A and Hospital B. Hospital A uses a different scanner and image processing pipeline, and it also happens to have a higher pneumonia rate. A flexible model can pick up scanner artifacts, text overlays, or border patterns that correlate with “Hospital A,” then use that as a shortcut for pneumonia risk.
A naive random split across all images mixes hospitals into both train and test. The model sees Hospital A-specific artifacts in training and can rely on them during evaluation, so test performance looks impressive. But this test is quietly asking the wrong question: “Can you perform well when the same hospital artifacts appear in both train and test?” Deployment might instead ask: “Can you perform well at a new site, or after scanner upgrades?”
A more trustworthy evaluation uses a group-based split by hospital (or, even better, by site and time if both matter). You might train on Hospital A + part of B, validate on a held-out portion of B for tuning, and reserve an entire hospital (or scanner type) as test if your deployment target includes new domains. This often lowers your headline metric, but it raises the honesty of the estimate. The impact is practical: fewer surprises, clearer risk communication to clinicians, and a better map of where the model will fail.
Limitations remain. If you only have two hospitals, holding one out creates a small test set and high uncertainty; performance may vary widely by disease prevalence and imaging protocol. In that case, you document the uncertainty, avoid over-claiming, and treat evaluation as an ongoing process as you onboard more sites.
Example 2: Retail demand forecasting over time (preventing “future peeking”)
You predict weekly demand for a product. The main question in production is: “Given what we know up to this week, what will happen next week?” If you randomly split weeks, you let the model learn from future weeks that are statistically similar (same seasonality, same promotional cycles) and then evaluate on weeks that come before them. This makes the task artificially easy and can hide fragility.
A better split is time-based: train on earlier weeks, validate on a more recent window for tuning, and test on the latest window to mimic deployment. This structure forces the model to confront drift: promotion strategies change, supply constraints appear, and customer behavior evolves. It also exposes whether engineered features are legal at prediction time. For instance, a feature like “average demand this month” can leak future information if computed using the whole month that includes the forecast week.
Step by step, the logic becomes disciplined. You compute features using only past data relative to each training example, pick hyperparameters and any demand-smoothing choices using validation, then freeze the design and report test performance once. The benefit is that your forecast errors look more like production errors, leading to better inventory decisions and more realistic safety stock planning.
The limitation is that time splits reduce the amount of “effective” training diversity, especially if the history is short or highly seasonal. You may see higher variance in estimates, and you might need to accept that some uncertainty is irreducible until more time passes and you collect more data.
Closing: the simplest way to stay honest
Train/val/test isn’t just a mechanical split—it’s an agreement with yourself about what evidence counts.
-
Train is for learning parameters.
-
Validation is for making choices (models, hyperparameters, thresholds).
-
Test is for one-time, decision-free estimation of generalization.
When splits match the real deployment scenario (time, groups, or IID), and when you treat validation as a limited resource, you sharply reduce leakage and selection-induced overfitting—the two most common ways “great metrics” fail in the real world.
In the next lesson, you’ll take this further with Loss, Optimization & Model Families [20 minutes].