- View
When a “good model” won’t train
You build a simple classifier for fraud. Your features look reasonable, your train/validation/test split is clean, and you expect learning to be straightforward. But training behaves oddly: the loss barely improves, accuracy jumps around, or the model “learns” on the training set while validation performance stalls immediately. What’s happening?
At this point, the bottleneck usually isn’t data splitting anymore—it’s how the model learns. A model learns by minimizing a loss using an optimizer, but those words hide a lot of practical choices. The loss defines what “wrong” means, the optimizer defines how you move toward “less wrong,” and the model family defines what kinds of patterns you’re even capable of representing.
This lesson gives you a working mental model of those three pieces—so you can look at a training curve and say: “This is a loss mismatch,” or “This is an optimization problem,” or “This model family can’t express what the data needs.”
Loss, optimization, parameters, hyperparameters: the minimum vocabulary
A model is a function that maps inputs (x) to predictions (\hat{y}). Most training procedures pick parameters (\theta) (weights, tree splits, etc.) that make predictions match labels as well as possible on the training set. The thing that measures “match” is the loss function.
Key terms you’ll use constantly:
-
Loss function: a number that measures how bad predictions are for one example (or averaged over a batch). Training tries to minimize this.
-
Objective: the total thing you minimize—often loss + regularization. Regularization penalizes overly complex solutions to improve generalization.
-
Parameters: values learned from training data (e.g., weights in linear models, tree split thresholds).
-
Hyperparameters: choices you set outside training (learning rate, regularization strength, tree depth, model architecture).
-
Optimizer: the algorithm that updates parameters to reduce the objective (e.g., gradient descent variants).
This connects directly to generalization and honest evaluation. A model can show great training loss simply by memorizing quirks; your earlier discipline around splits is what tells you whether lower loss actually transfers to validation/test. Also note a common misconception: optimization is not the same as generalization. You can optimize perfectly (very low training loss) and still generalize poorly if the model family is too flexible, the objective is mis-specified, or regularization is weak.
What “loss” really means (and why picking the wrong one hurts)
Loss is the contract between your model and the real-world decision you care about. It answers: “How should the model be punished when it’s wrong?” For beginners, it’s tempting to treat loss as a technical detail—something the library picks. In practice, the loss shapes behavior as much as the model family does.
For regression, a common loss is mean squared error (MSE). Because errors are squared, large mistakes get punished heavily; this pushes the model to avoid big misses, but it also makes MSE sensitive to outliers. If your data has rare but extreme values (like a sudden demand spike), MSE can pressure the model to chase those spikes, which may or may not be what you want. A more robust alternative is mean absolute error (MAE), which penalizes linearly and is less dominated by outliers. The tradeoff is that MAE can be harder to optimize smoothly in some setups, and it treats all deviations equally rather than strongly preferring to eliminate large errors.
For classification, the standard loss is log loss / cross-entropy. Instead of only caring whether you got the label right, cross-entropy cares about the confidence of your predicted probabilities. If you predict 0.99 for “fraud” and it’s not fraud, you get punished a lot—because you were confidently wrong. This is why cross-entropy tends to produce better-calibrated ranking behavior than losses that only measure 0/1 correctness. A misconception to correct early: “If accuracy is my metric, I should optimize accuracy.” Accuracy is not differentiable and ignores confidence; cross-entropy is usually a better training signal, and you can still evaluate accuracy (or precision/recall) afterward on validation/test as you learned previously.
Regularization fits here naturally. Many practical objectives look like:
[ \text{Objective} = \text{Data Loss} + \lambda \cdot \text{Regularization Penalty} ]
The (\lambda) term is a hyperparameter that trades off fitting the training data vs. keeping the solution simple. This is the bias–variance story in mathematical clothing: stronger regularization increases bias but often reduces variance, improving validation performance. If you see training loss dropping nicely but validation loss increasing (classic overfitting), you often address it by strengthening regularization, reducing model capacity, or stopping earlier—choices you tune on the validation set, not the test set.
Optimization: how models actually “move” toward lower loss
Once you define loss, you still have to minimize it. Optimization is the process of finding parameters (\theta) that reduce the objective. The simplest picture is gradient descent: compute the gradient (the direction of steepest increase) and step in the opposite direction.
In many ML systems—especially neural networks—training uses stochastic gradient descent (SGD) or mini-batch variants. Instead of computing the exact gradient over the full dataset each step, you estimate it using a small batch. This makes training much faster and allows learning to start immediately, but it adds noise: the loss curve bounces because each batch is a slightly different view of the data. That “bounciness” is not automatically a problem; the question is whether the overall trend goes down and whether validation improves.
The most important hyperparameter here is the learning rate. Too high and training can diverge—loss explodes or oscillates wildly. Too low and training crawls—loss decreases painfully slowly, and you may mistake “not enough time” for “model can’t learn.” A reliable beginner heuristic is to treat learning rate problems as “shape of curve” problems: divergence and extreme oscillation often means too high; flat loss that barely changes can mean too low, or that features/labels are mismatched, or that the model family is too constrained.
Optimization also interacts with early stopping, which you’ve already met as a generalization tool. Early stopping is an optimization choice guided by validation: you stop training when validation performance stops improving, preventing the optimizer from continuing to chase small training-set quirks. The pitfall is procedural leakage: if you repeatedly use the same validation set to tune learning rate, model family, regularization, and stopping time, you can overfit the validation set through iteration. The more you “hunt,” the less trustworthy validation becomes as a proxy for test.
[[flowchart-placeholder]]
Model families: what kinds of patterns your system can represent
A model family defines the space of functions you’re searching over during optimization. The optimizer can only find solutions that exist inside that family, and regularization/early stopping influence which solutions are preferred.
At a beginner level, you can think in three broad buckets:
-
Linear models (e.g., linear regression, logistic regression): assume a weighted sum of features drives the prediction.
-
Tree-based models (e.g., decision trees, random forests, gradient-boosted trees): split the feature space into regions with different predictions.
-
Neural networks: compose many simple transformations to represent complex non-linear patterns.
Each has distinct implications for loss/optimization and for generalization. Linear models are often easy to optimize and provide strong baselines; they can underfit if the true relationship is highly non-linear unless feature engineering adds the needed interactions. Tree-based models can capture non-linearities and feature interactions with less manual feature work, but they can overfit if trees are too deep or if boosting runs too long without regularization. Neural networks can be extremely expressive but usually require more careful optimization choices (learning rate schedules, normalization, sufficient data) to train reliably.
A misconception that causes real project churn: “Neural nets are always better.” In tabular business data, strong tree-based models often win; in unstructured data (images, audio, text), neural networks often dominate because they can learn representations from raw inputs. The right question is: What data type and structure do I have, and what failure mode am I willing to manage—underfitting vs. overfitting vs. optimization instability?
Here’s a compact comparison you can reuse:
| Dimension | Linear models | Tree-based models | Neural networks |
|---|---|---|---|
| What they fit well | Relationships that are close to linear in the features; monotonic effects | Non-linear patterns and feature interactions in tabular data | Complex patterns, especially in unstructured data; learned representations |
| Optimization behavior | Usually stable and fast; fewer knobs | Training is algorithmic (splits/boosting) rather than gradient descent on weights; generally robust | Sensitive to learning rate and other hyperparameters; can be unstable without care |
| Overfitting risk | Lower by default; controlled with regularization | Moderate to high if depth/boosting is excessive; controlled with depth, subsampling, regularization | Can be high due to capacity; controlled with regularization, data, architecture, early stopping |
| Interpretability | Often highest (coefficients, signs, magnitudes) | Medium (feature importance, partial dependence; individual decisions can be complex) | Often lowest without extra tooling; behavior can be opaque |
| Strong baseline role | Excellent “sanity check” baseline | Excellent performance baseline on tabular problems | Excellent baseline on images/text/audio when set up correctly |
How the pieces fit together: objective + optimizer + family
It helps to see training as a three-part design:
- Choose an objective that reflects the task (loss + regularization).
- Choose a model family that can represent the patterns you expect.
- Choose an optimization procedure that can reliably find good parameters in that family.
These choices create predictable failure modes.
If your loss is misaligned, the model can optimize faithfully yet behave badly. Example: You optimize MSE for a problem where business cost is asymmetric (missing fraud is far worse than flagging a legitimate user). The model may minimize average error while still making the “wrong” kind of mistakes. You often keep a standard loss for training but evaluate with decision-aware metrics (precision/recall, cost-weighted score) on validation, then adjust thresholds and operating points—keeping the test set clean as you learned earlier.
If your model family is too simple, you underfit: both training and validation losses plateau at mediocre levels. Your optimizer can’t fix “expressiveness.” If your model family is too flexible, you can fit training extremely well and still fail to generalize: training loss keeps improving while validation gets worse. That’s where regularization, early stopping, and reducing capacity matter.
If your optimization is unstable, you see chaotic training dynamics: loss blows up, becomes NaN, or oscillates without progress. Beginners often misdiagnose this as “bad data” or “wrong family” when it’s simply learning rate issues, poor feature scaling, or an overly aggressive training setup. The important habit is to form hypotheses from the curves: underfitting looks different than overfitting, and both look different than divergence.
Two real-world walk-throughs (from “definition” to “what you do Monday”)
Example 1: Fraud scoring with skewed classes and threshold decisions
Imagine you’re building a fraud model where only 1% of transactions are fraudulent. You train a classifier and it reports 99% accuracy by predicting “not fraud” almost always. This is exactly the kind of metric trap you learned to avoid: accuracy can hide useless behavior under imbalance. Now bring in today’s concepts.
First, you pick a classification loss like cross-entropy so the model learns a meaningful scoring function rather than chasing accuracy directly. Cross-entropy pushes the model to separate fraud from non-fraud with probability-like outputs, which you can later threshold based on business needs. During training, you watch both training loss and validation loss. If training loss drops steadily but validation stalls or rises, you’re likely overfitting—especially if you tried a highly flexible family or many features that might encode shortcuts (IDs, aggregates computed improperly).
Second, you connect optimization and evaluation workflow. You use the validation set to choose hyperparameters (regularization strength, tree depth, learning rate) and to pick an operating threshold that meets constraints (for example, maintain high recall while keeping precision manageable for investigators). The limitation is that repeated threshold tweaking is another form of “selection pressure” on validation; after many iterations, validation can become optimistic. The best practice is to treat validation as a limited resource: make fewer, more principled changes, and reserve the test set as a one-time estimate of generalization for the whole pipeline, including threshold choice.
The impact is practical: you stop asking “What’s the accuracy?” and start asking “Are we optimizing a loss that supports ranking and calibration, and are we choosing thresholds on validation in a way that will hold up in production?” That framing prevents the common outcome where a model “looks good” but creates operational pain—too many false positives, missed fraud patterns, and brittle performance when behavior drifts.
Example 2: Demand forecasting where MSE fights your real objective
You forecast weekly demand for inventory planning. Suppose your objective is to avoid stockouts, and stockouts are much more costly than overstock by a small margin. If you train with MSE, the model emphasizes avoiding large errors in both directions—over- and under-predicting—and it is especially sensitive to rare spikes. That may cause the model to chase spikes that were caused by one-off promotions or data glitches, which can harm generalization.
Start with the loss choice: MSE vs. MAE is not cosmetic. MAE tends to produce forecasts that better represent the “typical” demand and are less pulled by outliers. But if your business cost is asymmetric, neither plain MSE nor plain MAE perfectly matches; in real systems you sometimes use weighted losses or evaluate with asymmetric cost metrics even if training uses a standard loss for stability. The key is to be explicit: what kind of error is more expensive? If under-forecasting hurts more, you should at least reflect that in how you pick models and thresholds (or safety stock rules) on the validation set.
Now connect to optimization and model family. A simple linear model may underfit if demand depends on non-linear interactions (seasonality × promotion × region). A tree-based model can capture interactions without manual feature crosses, but it can overfit if it learns tiny regions that correspond to quirks of the training period. With a time-based split (as you learned earlier), overfitting shows up clearly: training loss improves while validation on later weeks worsens. Early stopping and regularization (shallower trees, stronger penalties, fewer boosting rounds) become the tools that trade a bit of training fit for a lot more stability on future periods.
The limitation is unavoidable uncertainty: future demand can change for reasons not in the data (supply constraints, competitor moves). Loss/optimization/model family choices can’t eliminate that, but they can prevent self-inflicted wounds—like optimizing a loss that rewards fitting rare spikes, or choosing an overly flexible model that memorizes the past while failing on the next month.
A checklist for reading training behavior like a professional
You don’t need advanced math to diagnose most training problems—you need a disciplined mapping from symptoms to causes.
-
Training loss high and validation loss high: likely underfitting (model too simple, features insufficient, regularization too strong).
-
Training loss low but validation loss worse: likely overfitting (capacity too high, regularization too weak, too much tuning on validation, or leakage-like features).
-
Loss explodes/oscillates wildly: likely optimization instability (learning rate too high, poor scaling, brittle setup).
-
Metrics look great but don’t survive deployment: often evaluation mistakes (wrong split strategy, leakage, selection-induced overfitting), even if training “worked.”
Notice how this ties the section together: evaluation protects you from fooling yourself, generalization keeps you honest about the real world, and loss/optimization/model family explain why a model behaves the way it does during training.
A checklist you can trust
-
Generalization is the goal, and train/validation/test role separation is how you measure it without accidentally leaking information or overfitting your decisions to one dataset slice.
-
Loss defines what “wrong” means, and the objective often includes regularization to control overfitting—directly reflecting the bias–variance tradeoff.
-
Optimization is the search procedure (often gradient-based) that reduces the objective; many training pathologies are learning-rate or stability issues, not “mystery model failures.”
-
Model families limit what can be learned: linear models underfit some problems, flexible models overfit others, and each family comes with its own optimization and tuning realities.
With these pieces in place, you can look at a model result and ask the right question first—“Is this an evaluation mistake, a loss mismatch, an optimization issue, or a model family choice?”—which is the habit that turns ML from trial-and-error into an engineering process.