The Goldilocks Problem of Machine Learning
A geotechnical engineer collects soil samples from a construction site: 12 boreholes, each with unique moisture content, grain-size distribution, and Atterberg limits. She could design a foundation tailored exactly to each borehole — but that foundation would fail at the 13th borehole. Alternatively, she could use the same standard foundation everywhere — safe, but wasteful and sometimes inadequate.
Machine learning models face the same dilemma. An overfit model memorises the training data (including its noise and quirks) and fails on new data. An underfit model is too simple to capture real patterns and performs poorly everywhere. The goal is the sweet spot: a model complex enough to learn the true signal, but constrained enough to generalise.
This sub-chapter dissects the bias-variance tradeoff, the formal framework behind the overfitting/underfitting problem. We will then explore regularization — a family of techniques that deliberately constrain models to improve generalisation. These techniques include L1 (Lasso), L2 (Ridge), Elastic Net, dropout, and early stopping.
In this sub-chapter, we will cover:
- The bias-variance tradeoff and why every model navigates it
- Overfitting: when your model memorises noise instead of learning signal
- Underfitting: when your model is too simple to capture the real relationship
- The sweet spot: how to find the right model complexity
- Regularization: L1 (Lasso), L2 (Ridge), and Elastic Net
- Dropout and early stopping for neural networks
- Civil engineering analogies for every concept
- Two interactive demos to visualise these ideas in action
This sub-chapter builds on Sub-chapter 2.1 (Core ML Concepts) and Sub-chapter 2.3 (Linear Regression). You should be comfortable with training vs. testing data, loss functions, and polynomial regression. The evaluation metrics from Sub-chapter 2.8 will help you interpret the demo outputs.
The Bias-Variance Tradeoff
Every prediction error can be decomposed into three components:
Total Error = Bias^2 + Variance + Irreducible Noise
Bias = Error from wrong assumptions (too simple model)
Variance = Error from sensitivity to training data fluctuations
Noise = Random error inherent in the data (cannot be eliminated)
Bias measures how far off your model's average prediction is from the true value. A high-bias model makes strong assumptions — for example, assuming the relationship between concrete strength and water-cement ratio is perfectly linear, when in reality it follows a curve. No matter how much data you give it, the model will systematically miss the true pattern.
Variance measures how much your model's predictions change when trained on different subsets of data. A high-variance model is extremely sensitive to the specific training samples. Train it on Monday's data and it predicts one thing; train it on Tuesday's data and it predicts something completely different. It has effectively memorised the noise in each dataset.
Civil Engineering Analogy: The Surveyor
Imagine a surveyor measuring the elevation of a benchmark point. Bias is like a systematic error in the instrument: every reading is 5 cm too high, no matter how many measurements are taken. Variance is like random wobble in the readings: each measurement scatters around the true value. A good instrument has both low bias (accurate) and low variance (precise). In machine learning, we seek models that are both accurate (low bias) and stable (low variance).
The tradeoff arises because reducing one tends to increase the other:
- Simple models (few parameters) have high bias but low variance. They under-learn the data but are stable across different training sets.
- Complex models (many parameters) have low bias but high variance. They can capture intricate patterns but are overly sensitive to the specific training data.
The goal is to find the sweet spot where the total error (bias squared plus variance) is minimised. This is the fundamental challenge of model selection.
Error
|
| \ /
| \ Test Error /
| \ /
| \ / High Variance
| \ Sweet / (Overfitting)
| \ Spot /
| \_________ /
| \/
| High Bias \_________ Train Error
| (Underfitting) \________
|
+--------------------------------------------->
Model Complexity (e.g. polynomial degree)
As complexity increases:
- Training error decreases monotonically (model fits data better)
- Test error first decreases (less bias), then increases (more variance)
- The sweet spot is where test error is minimised
Overfitting: Memorising the Noise
Overfitting occurs when a model learns the training data too well, capturing not just the underlying pattern but also the random noise, outliers, and quirks specific to that particular dataset. The result: excellent performance on training data, terrible performance on new, unseen data.
Symptoms of Overfitting
- Training error is very low (near zero)
- Validation/test error is much higher than training error
- The gap between training and test error grows as model complexity increases
- The model's predictions are erratic and unstable on new data
- Small changes in input produce wildly different outputs
Civil Engineering Analogy: The Over-Customised Foundation
Imagine designing a foundation system based on a single borehole at one corner of the site. You optimise the pile length, diameter, and reinforcement for the exact soil profile at that one location. The design works perfectly there — but move 20 metres to where the clay layer is thicker and the sand lens is absent, and your "perfect" design fails. You have overfit your design to one specific sample of the ground conditions.
A seasoned geotechnical engineer uses multiple boreholes, incorporates uncertainty, and designs for a range of plausible conditions — just as a well-regularised model learns from the overall trend, not from individual data points.
Common Causes
When training data is scarce, the model has limited examples to learn from. With only 30 concrete cylinder test results, a model with 20 parameters can essentially memorise each sample. More data dilutes the influence of individual noise points and helps the model find the true underlying relationship.
A 15th-degree polynomial fitted to 20 data points will pass through (or near) every point, producing wild oscillations between them. The model has enough "knobs" to contort itself into any shape, matching noise rather than signal. This is the most common cause of overfitting: the model has more capacity than the data warrants.
In iterative training (gradient descent, neural networks), each epoch refines the model's fit. Early epochs capture the big patterns; later epochs start fitting the noise. If you train for 10,000 epochs when 500 would suffice, you are effectively polishing noise into your model.
Data with measurement errors, mislabelled examples, or outliers provides the model with "fake patterns" to learn. If a few concrete strength tests have typos (280 MPa instead of 28 MPa), a complex model will bend itself to accommodate those points, corrupting its predictions for legitimate data.
Underfitting: Too Simple to Learn
Underfitting is the opposite problem: the model is too simple to capture the underlying relationship in the data. It performs poorly on both training and test data because it has not learned the pattern at all.
Symptoms of Underfitting
- Both training and test errors are high
- Training and test errors are similar (both bad)
- The model's predictions are flat or overly simplistic
- Adding more training data does not improve performance
- The learning curve plateaus early at a high error
Civil Engineering Analogy: The One-Size-Fits-All Foundation
Using the same 600mm-diameter, 12-metre-long driven pile for every project — a 3-storey office building on clay, a 30-storey tower on rock, a waterfront warehouse on fill — is the structural equivalent of underfitting. The design is so generic that it is grossly over-conservative for simple cases, grossly under-designed for complex ones, and optimal for none. It ignores the actual ground conditions, building loads, and site constraints.
Common Causes
- Model too simple: Fitting a straight line to data that follows a quadratic or exponential curve.
- Important features missing: Predicting concrete strength without including water-cement ratio, curing time, or aggregate type.
- Too much regularization: Overly aggressive regularization can strangle the model, preventing it from learning even legitimate patterns. (We will see this in Demo 2.)
- Insufficient training: Stopping gradient descent after just a few epochs, before the model has had a chance to converge.
Diagnosing the Problem: Training vs. Test Error
Condition | Train Error | Test Error | Diagnosis
---------------------+-------------+------------+-------------------
Both high, similar | HIGH | HIGH | UNDERFITTING
Train low, test high | LOW | HIGH | OVERFITTING
Both low, similar | LOW | LOW | GOOD FIT (sweet spot)
Key Insight:
- If train error is already high, the model cannot even learn the
training data. Adding more data or regularization will NOT help.
You need a more complex model or better features.
- If train error is low but test error is high, the model has
learned the training data but cannot generalise. Regularization,
more data, or a simpler model can help.
Finding the Sweet Spot
The sweet spot is the model complexity at which the test error is minimised. To the left, underfitting dominates (high bias). To the right, overfitting dominates (high variance). The sweet spot balances both.
In practice, we find the sweet spot through:
- Cross-validation: Split the data into k folds, train on k-1 folds, and validate on the remaining fold. Repeat k times and average the validation error. This gives a robust estimate of generalisation performance. (Covered in detail in Sub-chapter 2.8.)
- Learning curves: Plot training and validation error as a function of training set size or model complexity. The gap between the two curves tells you whether you are overfitting or underfitting.
- Regularization: Instead of manually selecting model complexity, add a penalty term that automatically constrains the model. This is the focus of the next sections.
Civil Engineering Analogy: Design Codes
Structural design codes (Eurocode, ACI, IS codes) are essentially regularization for civil engineering. They prevent engineers from overfitting to a specific scenario by imposing minimum requirements, safety factors, and design constraints. A design code says: "Even if your specific analysis says you can use 10mm bars at 300mm spacing, you must use at least 12mm bars at 200mm spacing." This regularization sacrifices a tiny amount of optimality for a large gain in robustness across variable real-world conditions.
Interactive Demo: Overfitting Visualiser
Use the polynomial degree slider to fit curves of increasing complexity to noisy data. Watch how the training error (red) and test error (blue) diverge as the polynomial degree grows. The classic U-shaped test error curve reveals the sweet spot where generalisation is best.
Polynomial Fit
Train vs Test Error
Start with degree 1 (a straight line) and slowly increase the polynomial degree. Watch how the red fit line begins hugging the training points more closely, but the blue test error on the right chart starts rising after the sweet spot. Try increasing the noise level to see how the sweet spot shifts. With more noise, the optimal degree tends to be lower because there is more randomness to memorise. With more training points, overfitting becomes harder because the model cannot memorise as many individual samples.
Regularization: Taming Model Complexity
Regularization is the deliberate introduction of constraints that prevent a model from fitting the training data too closely. Instead of choosing a simpler model architecture, we keep the complex model but add a penalty term to the loss function that discourages large or unnecessary parameter values.
Regularized Loss = Original Loss + lambda * Penalty(weights)
Where:
- Original Loss = e.g. MSE = (1/n) * SUM(y_i - y_hat_i)^2
- lambda (lambda) = regularization strength (hyperparameter)
- Penalty = a function of the model weights
lambda = 0 --> No regularization (original loss only)
lambda = inf --> Maximum regularization (weights forced to zero)
The hyperparameter lambda controls the tradeoff between fitting the data and keeping the weights small. A small lambda applies gentle regularization; a large lambda aggressively penalises complexity, potentially causing underfitting. The optimal lambda is found through cross-validation.
L2 Regularization (Ridge Regression)
L2 regularization adds the sum of squared weights to the loss function. This is called Ridge regression when applied to linear models.
L2 Penalty = lambda * SUM(w_j^2)
Ridge Loss = MSE + lambda * SUM(w_j^2)
Effect:
- Shrinks all weights toward zero (but never exactly to zero)
- Large weights are penalised quadratically (a weight of 10 incurs
100x the penalty of a weight of 1)
- Distributes the model's capacity across all features
- Effective when many features contribute small amounts
Geometrically, L2 regularization constrains the weight vector to lie within a hypersphere. The loss contours intersect this sphere at a point where all weights are small but non-zero.
Civil Engineering Analogy
L2 regularization is like a building code requirement for ductility. The code does not eliminate any structural member, but it limits how much load any single member carries. If one column wants to take 80% of the lateral load (a very "large weight"), the code imposes capacity limits that distribute the load more evenly across all columns. Every column participates, but none dominates excessively.
L1 Regularization (Lasso)
L1 regularization adds the sum of absolute weights to the loss function. This is called Lasso (Least Absolute Shrinkage and Selection Operator) when applied to linear models.
L1 Penalty = lambda * SUM(|w_j|)
Lasso Loss = MSE + lambda * SUM(|w_j|)
Effect:
- Drives some weights exactly to zero (feature selection!)
- Produces sparse models with fewer active features
- Useful when you suspect only a few features truly matter
- Less effective when features are correlated (picks one, drops others)
The key difference from L2: L1 can produce sparse models where many coefficients are exactly zero. This makes Lasso a powerful tool for automatic feature selection. In a model with 50 input features, Lasso might discover that only 8 truly matter and set the remaining 42 weights to zero.
Geometrically, L1 constrains weights to a hypercube (diamond shape in 2D). The loss contours tend to intersect the corners of this diamond, which correspond to axis-aligned solutions where some weights are exactly zero.
Civil Engineering Analogy
L1 regularization is like a cost-optimisation exercise that eliminates unnecessary members from a truss. If a truss has 30 members but only 18 carry significant load, an optimisation algorithm with an L1-style penalty will zero out the 12 redundant members entirely, producing a lighter, simpler structure. This is exactly what Lasso does to model features: it does not just shrink unimportant weights — it removes them completely.
Elastic Net: Best of Both Worlds
Elastic Net combines L1 and L2 penalties, blending the feature-selection ability of Lasso with the stability of Ridge.
Elastic Net = MSE + lambda * [ alpha * SUM(|w_j|) + (1-alpha) * SUM(w_j^2) ]
Where:
alpha = 1.0 --> Pure Lasso (L1)
alpha = 0.0 --> Pure Ridge (L2)
alpha = 0.5 --> Equal blend
Advantages:
- Handles correlated features better than pure L1
- Can select groups of correlated features together
- Provides sparsity (from L1) + stability (from L2)
- Ideal when feature count >> sample count
Elastic Net is particularly useful in civil engineering applications where input features are often correlated. For example, in a concrete mix design model, water content and water-cement ratio are strongly correlated. Pure Lasso might arbitrarily pick one and drop the other. Elastic Net handles this gracefully by grouping correlated features together.
Comparison Summary
Method | Penalty | Sparsity | Correlated Features
-------------+---------------+----------+--------------------
Ridge (L2) | SUM(w_j^2) | No | Keeps all, shrinks
Lasso (L1) | SUM(|w_j|) | Yes | Picks one, drops rest
Elastic Net | L1 + L2 blend | Partial | Groups together
Dropout: Regularization for Neural Networks
Dropout is a regularization technique designed specifically for neural networks. During each training iteration, dropout randomly "turns off" a fraction of neurons (typically 20-50%), forcing the network to learn redundant representations. At test time, all neurons are active, but their outputs are scaled down to account for the dropout rate.
Training Phase (dropout_rate = 0.5):
For each training batch:
- Randomly select 50% of neurons in each layer
- Set their outputs to zero (temporarily "dead")
- Forward/backward pass uses only surviving neurons
- Next batch: different random neurons are dropped
Testing Phase:
- ALL neurons are active (no dropping)
- Multiply each neuron's output by (1 - dropout_rate)
- This approximates the average of all possible sub-networks
Effect:
- Prevents co-adaptation (neurons cannot rely on specific partners)
- Each neuron must learn independently useful features
- Equivalent to training an ensemble of many smaller networks
- Dramatically reduces overfitting in deep networks
Civil Engineering Analogy
Dropout is like robustness testing through redundancy. Imagine designing a bridge where, during the design verification phase, you randomly remove 30% of the structural members and check if the bridge still stands. If any single member's removal causes collapse, your design lacks redundancy. By repeatedly testing with random member removals, you force the design to distribute loads across multiple paths — exactly what dropout does to neural network weights.
Early Stopping: Knowing When to Quit
Early stopping is perhaps the simplest regularization technique: monitor the validation error during training, and stop when it starts increasing. The training error will continue decreasing, but the validation error will begin to rise as the model starts memorising noise.
Epoch: 1 50 100 200 500 1000 2000 5000
Train: 0.95 0.42 0.21 0.08 0.02 0.005 0.001 0.0002
Valid: 0.98 0.45 0.24 0.15 0.13 0.18 0.25 0.42
^
|
STOP HERE (patience = 100 epochs)
Early Stopping Algorithm:
1. Train model, recording validation loss after each epoch
2. Track the best validation loss seen so far
3. If validation loss has not improved for "patience" epochs, STOP
4. Restore the model weights from the best epoch
5. The "patience" hyperparameter controls how long you wait
Early stopping is an example of implicit regularization. It does not change the loss function but limits the model's effective complexity by restricting how long it trains. The number of training epochs effectively controls model complexity: more epochs = more complex model = higher risk of overfitting.
Civil Engineering Analogy
Early stopping is like knowing when to stop optimising a structural design. The first few iterations of optimisation yield dramatic improvements — reducing member sizes, saving material costs. But after a point, further "optimisation" starts shaving safety margins, removing redundancy, and making the design brittle against unexpected loads. A wise engineer stops optimising before the design becomes too finely tuned to the assumed loading conditions.
Regularization Techniques at a Glance
Technique | How It Works | When to Use
-----------------+-------------------------------+---------------------------
L2 (Ridge) | Penalises sum of w^2 | Many features, all relevant
L1 (Lasso) | Penalises sum of |w| | Feature selection needed
Elastic Net | Blend of L1 + L2 | Correlated features
Dropout | Randomly deactivate neurons | Deep neural networks
Early Stopping | Stop training at best val err | Any iterative model
Key Hyperparameters:
- lambda: regularization strength (L1, L2, Elastic Net)
- alpha: L1/L2 mixing ratio (Elastic Net)
- dropout_rate: fraction of neurons dropped (Dropout)
- patience: epochs to wait before stopping (Early Stopping)
Interactive Demo: Regularization Strength
Adjust the regularization strength (lambda) and toggle between L1 and L2 penalties. Watch how the coefficient magnitudes shrink as lambda increases. With L1, some coefficients snap to exactly zero (feature selection). With L2, all coefficients shrink proportionally but none reach zero.
Regularized Fit
Coefficient Magnitudes
Start with low lambda (left) and observe the wiggly, overfit curve. Slowly increase lambda and watch the curve smooth out. Switch between L1 and L2 to see the key difference: L1 drives bars on the right chart to exactly zero, while L2 shrinks them proportionally. Try Elastic Net to see the hybrid behaviour. If you push lambda too high, the curve flattens completely — that is underfitting caused by excessive regularization.
Practical Guidelines for Civil Engineers
Begin with a simple model (linear regression, low-degree polynomial). If training and validation errors are both high (underfitting), gradually increase complexity. If the training error is low but validation error is high (overfitting), add regularization or reduce complexity. This mirrors good engineering practice: start with a simple analysis, add sophistication only when the simple model is inadequate.
Never evaluate your model only on training data. Always hold out a validation set (or use cross-validation) to get an honest estimate of generalisation performance. In civil engineering terms: do not claim your structural design is adequate just because it passes the load case you designed for. Test it against a range of realistic load combinations.
When using linear models, prefer Ridge or Lasso over plain least-squares regression. The computational cost is negligible, and the generalisation benefit is almost always positive. When training neural networks, always include dropout and early stopping. Think of regularization as a safety factor: it costs almost nothing but provides substantial protection against overfitting.
The regularization strength lambda should be tuned using k-fold cross-validation (Sub-chapter 2.8). Try a range of values on a logarithmic scale (e.g., 0.001, 0.01, 0.1, 1, 10, 100) and select the value that minimises the average validation error. Do not pick lambda based on training error alone — that defeats the purpose of regularization.
The most robust cure for overfitting is more data. More training samples reduce variance without increasing bias. If you can run additional lab tests, collect more sensor readings, or obtain more inspection reports, do so. Regularization is a substitute for data when data is expensive or limited — not a replacement for good data collection practices.
CE Applications: Overfitting & Regularisation in Practice
Overfitting is especially dangerous in civil engineering because models trained on limited site-specific data are often applied to new sites with different conditions.
Geotechnical Examples
- SPT correlations — A settlement model calibrated on 50 tests from sandy soil in one city will overfit to that geology. L2 regularisation + cross-validation makes it transferable to other sites.
- Pile capacity prediction — With only 15–30 load tests per project, overfitting is almost guaranteed without regularisation. Lasso (L1) regularisation also reveals which soil parameters matter most.
- Slope stability models — 8+ features (height, angle, cohesion, friction, pore pressure, rainfall, seismicity, vegetation) with small datasets. Elastic Net prevents overfitting while retaining interpretability.
Water Resources Examples
- Rainfall-runoff models — A model that perfectly fits a 10-year calibration period may fail on extreme events (2023 flood ≠2005 flood). Early stopping prevents memorising specific storm patterns.
- Groundwater models — With sparse borehole data, a complex polynomial model will overfit to observation wells. Ridge regression constrains coefficients for better spatial generalisation.
- Reservoir inflow forecasting — Climate non-stationarity means historical patterns may not persist. K-fold cross-validation across different climate periods tests model robustness.
In CE, if your number of features approaches the number of data points (common in geotech with 10 soil properties and 20 test results), you must use regularisation. Without it, the model will memorise rather than learn.
See overfitting form before your eyes
Crank the polynomial degree up and the noise σ down: the training loss plummets while the model contorts to memorise noise. The classic overfitting signature, reproducible in three slider drags.
Test Your Understanding
Test your understanding of overfitting, underfitting, and regularization. Each question reinforces a key concept from this sub-chapter.
Quick Check 1
A neural network predicting concrete compressive strength achieves a training RMSE of 0.5 MPa and a test RMSE of 12.3 MPa. What is the most likely diagnosis?
Quick Check 2
You are building a model to predict traffic flow using 40 features (temperature, time of day, road width, lane count, etc.), but you suspect that only 8-10 features actually matter. Which regularization technique is most appropriate?
Quick Check 3
An engineer increases the regularization strength (lambda) in a Ridge regression model for predicting beam deflection. What happens?
Quick Check 4
Which civil engineering analogy best captures the concept of an overfit model?
Key Takeaways
Summary
- Bias-Variance Tradeoff: Every model navigates a tradeoff between underfitting (high bias, low variance) and overfitting (low bias, high variance). The goal is to minimise the total error.
- Overfitting occurs when the model memorises noise and fails to generalise. Symptoms: low training error, high test error.
- Underfitting occurs when the model is too simple. Symptoms: high training error, high test error.
- L2 (Ridge) shrinks all weights toward zero but never eliminates features. Best for many small contributions.
- L1 (Lasso) drives some weights to exactly zero, performing automatic feature selection. Best when few features matter.
- Elastic Net blends L1 and L2, handling correlated features gracefully.
- Dropout randomly deactivates neurons during training, forcing the network to learn redundant representations.
- Early Stopping halts training when validation error stops improving, implicitly limiting model complexity.
- Regularization is like a design code for ML: it sacrifices a small amount of training performance for a large gain in real-world robustness.
In Sub-chapter 2.10, we will apply everything from Chapter 2 to a comprehensive Civil Engineering Case Study. You will see data preprocessing, feature engineering, model selection, evaluation metrics, and regularization working together on a real-world engineering dataset. The concepts from this sub-chapter will be critical for understanding why the case study model is regularized and how we diagnose overfitting during development.