When Straight Lines Are Not Enough
In Sub-chapter 2.2 you learned to fit a straight line through data. That line worked beautifully for the narrow w/c-ratio-to-strength relationship. But consider a triaxial compression test on clay: the stress-strain curve starts steep, bends through a yield point, and eventually flattens toward residual strength. No single straight line can capture that shape.
Or consider predicting the 28-day compressive strength of concrete in production. The water-cement ratio matters, yes, but so do cement content, aggregate gradation, superplasticiser dosage, curing temperature, and age at testing. You need a model that ingests multiple features at once and still produces a single reliable prediction.
This sub-chapter addresses both limitations. First, we extend the single-feature model by adding polynomial terms — x2, x3, and beyond — so the model can trace curves through data. Second, we extend the model in a different direction by adding multiple features, each with its own coefficient, so the model can account for several physical variables simultaneously. Along the way you will meet two critical concepts: multicollinearity (what happens when your features are correlated with each other) and adjusted R-squared (a fairer metric when the number of features grows).
This sub-chapter assumes you have completed Sub-chapter 2.2 (Linear Regression) and are comfortable with the concepts of slope, intercept, MSE, R-squared, gradient descent, and residual analysis. We build directly on those foundations.
Polynomial Regression: Adding Curves
Polynomial regression is the natural next step when your scatter plot shows curvature. Instead of fitting y = w0 + w1x, you add higher powers of x as additional terms:
Degree 1 (linear): y = w0 + w1*x
Degree 2 (quadratic): y = w0 + w1*x + w2*x^2
Degree 3 (cubic): y = w0 + w1*x + w2*x^2 + w3*x^3
Degree n: y = w0 + w1*x + w2*x^2 + ... + wn*x^n
The key insight is that polynomial regression is still a form of linear regression. That sounds contradictory, but "linear" in "linear regression" refers to linearity in the parameters (w0, w1, w2, ...), not in x. Each parameter appears to the first power and is multiplied by a function of x. You can treat x2 as a brand-new feature — call it z — and the equation y = w0 + w1x + w2z is linear in x and z.
Polynomial regression is like fitting a vertical curve to a road profile. When you design a crest or sag curve on a highway, you do not use a straight line — you use a parabola (degree 2) to smoothly connect the two tangent grades. The degree of the polynomial determines how flexible the curve is. A parabola handles simple transitions; higher-degree curves handle more complex terrain, but you would never use a degree-20 polynomial for a simple sag because it would introduce unnecessary oscillations.
How It Works Under the Hood
To fit a polynomial of degree n, you create n new features from the original x:
Original feature: x
Engineered features: x, x^2, x^3, ..., x^n
Example (degree 3, x = 0.45):
feature_1 = 0.45
feature_2 = 0.45^2 = 0.2025
feature_3 = 0.45^3 = 0.0911
Then you feed these features into the same least-squares machinery you already know. The algorithm finds the optimal weights w0 through wn that minimise the MSE. No new maths — just more features and more weights.
CE Context: Soil Stress-Strain Curves
Every geotechnical engineer has seen a stress-strain curve from a triaxial compression or unconfined compression test. The curve starts near the origin, rises steeply (elastic region), bends through a yield point, and eventually levels off or even drops toward residual strength. This nonlinear shape is a classic candidate for polynomial regression.
Sample Dataset: Unconfined Compression Test on Clay
Consider data from an unconfined compression test on a silty clay sample:
| Strain (%) | Stress (kPa) |
|---|---|
| 0.0 | 0 |
| 0.5 | 35 |
| 1.0 | 62 |
| 2.0 | 105 |
| 3.0 | 130 |
| 4.0 | 142 |
| 6.0 | 148 |
| 8.0 | 145 |
| 10.0 | 140 |
The stress rises steeply at first, peaks around 6% strain, then declines slightly — a classic strain-softening response. A straight line cannot capture this behaviour.
If you fitted a linear regression (degree 1) to this data, the line would cut diagonally through the curve, under-predicting at both ends and over-predicting in the middle. The residuals would show a clear U-shape — the warning sign we discussed in Sub-chapter 2.2. A degree-2 (quadratic) polynomial captures the rise and flattening. A degree-3 (cubic) polynomial can also capture the slight decline after the peak. Beyond degree 3, additional terms add wiggles without physical meaning.
Always ask: does the polynomial shape make physical sense? A degree-6 polynomial might achieve a marginally lower MSE on your training data, but if it oscillates wildly between measured points, it is fitting the noise, not the signal. In geotechnical engineering, the stress-strain relationship should be smooth and monotonic (or have at most one peak). Any polynomial that violates this physical expectation is overfitting, no matter how good its R-squared looks.
Choosing the Right Degree: The Overfitting Trap
As you increase the polynomial degree, the model gains more flexibility. With enough terms, the curve can pass through every single data point — achieving an R-squared of 1.0 on the training data. But this is a trap.
Underfitting, Good Fit, and Overfitting
- Underfitting (degree too low) — The model is too simple to capture the true pattern. A straight line through a curved dataset. High training error, high test error. In civil engineering terms: you are using a rule of thumb where a proper analysis is needed.
- Good fit (degree just right) — The model captures the underlying trend without following the noise. Moderate training error, similar test error. Like a well-calibrated design equation: accurate enough for engineering decisions.
- Overfitting (degree too high) — The model memorises the training data, including measurement noise and random fluctuations. Very low training error but high test error. Like designing a road alignment that follows every GPS waypoint jitter instead of the intended centreline.
Start with degree 1 (linear)
Establish the baseline. If the residuals show no pattern, you are done. If they curve, proceed to degree 2.
Increment the degree gradually
Try degree 2, then degree 3. At each step, check the residual plot. If the pattern disappears, stop. Each additional degree should be justified by a meaningful improvement in fit and physical plausibility.
Use cross-validation or a held-out test set
Split your data into training and test sets. Train on one, evaluate on the other. The degree that minimises test error (not training error) is the best choice. If test error starts increasing while training error keeps decreasing, you have crossed into overfitting territory.
Apply engineering judgement
Does the fitted curve make physical sense? Does it extrapolate reasonably just beyond the data range? A degree-5 polynomial that fits the data perfectly but predicts negative stress at 12% strain is physically meaningless and should be rejected regardless of its metrics.
Overfitting is like using a spline with too many control points. In road design, a horizontal alignment needs smooth, sweeping curves defined by a few key control points (PI stations and curve radii). If you add a control point for every survey stake, the alignment becomes a jagged mess that no driver could follow safely. Similarly, a polynomial with too many terms follows every noisy data point instead of the smooth underlying relationship.
Interactive Demo: Polynomial Curve Fitter
See overfitting happen in real time. The canvas below displays data from a simulated soil stress-strain test. Use the degree slider to adjust the polynomial degree from 1 (linear) to 6. Watch how the curve fits the data more tightly as degree increases — and how it starts to oscillate wildly at high degrees, fitting noise rather than the true pattern. Pay attention to both the training R2 and the test R2 (computed on held-out points shown as hollow circles).
Polynomial Degree vs. Fit Quality
Drag the slider to change the polynomial degree. Solid dots are training data; hollow dots are test data. The curve fits training points — compare training R2 (always improves) with test R2 (peaks then drops).
Multiple Linear Regression: Many Features, One Prediction
Polynomial regression adds complexity along a single feature axis. Multiple linear regression adds complexity by introducing additional features. Instead of predicting concrete strength from the w/c ratio alone, you include cement content, aggregate proportions, admixture dosage, curing temperature, and any other measured variable. The model becomes:
y_hat = w0 + w1*x1 + w2*x2 + w3*x3 + ... + wp*xp
Concrete strength example:
Strength = w0
+ w1 * cement_content (kg/m3)
+ w2 * water_cement_ratio
+ w3 * fine_aggregate (kg/m3)
+ w4 * coarse_aggregate (kg/m3)
+ w5 * superplasticiser (litres/m3)
+ w6 * curing_temp (deg C)
Each weight wi represents the effect of feature xi on the prediction, holding all other features constant. For example, w1 tells you how much the predicted strength changes when cement content increases by 1 kg/m3, assuming the w/c ratio, aggregate proportions, and everything else remain fixed.
Geometry: From Lines to Hyperplanes
With one feature, the model is a line in 2D space. With two features, the model is a plane in 3D space — imagine a flat sheet tilted to best fit a cloud of data points floating in three dimensions. With three or more features, the model is a hyperplane in higher-dimensional space. You cannot visualise this directly, but the mathematics is identical: find the flat surface (of any dimensionality) that minimises the MSE.
Multiple regression is like a multi-factor design mix formula. In concrete mix design, you do not determine the 28-day strength from a single variable. You use a series of charts and tables that account for cement content, aggregate size, w/c ratio, admixtures, and curing conditions. Multiple regression automates this process: give it all the input variables and measured outcomes, and it produces a formula that predicts strength from any combination of inputs within the observed range.
CE Context: Concrete Strength from Multiple Mix Factors
The UCI Machine Learning Repository hosts a famous concrete compressive strength dataset (Yeh, 1998) with 1,030 specimens. Each record includes eight input features: cement, blast furnace slag, fly ash, water, superplasticiser, coarse aggregate, fine aggregate, and age. The label is the 28-day compressive strength in MPa.
Typical Feature Ranges
| Feature | Unit | Min | Max |
|---|---|---|---|
| Cement | kg/m3 | 102 | 540 |
| Water | kg/m3 | 122 | 247 |
| Superplasticiser | kg/m3 | 0 | 32 |
| Age | days | 1 | 365 |
| Compressive Strength | MPa | 2.3 | 82.6 |
Notice the wildly different scales. Cement ranges from 102 to 540 while superplasticiser ranges from 0 to 32. Feature scaling is essential before fitting a multiple regression model.
Using a single-feature linear regression with only the w/c ratio, a typical R2 on this dataset hovers around 0.25. Adding all eight features pushes R2 to roughly 0.60. That is a substantial improvement, but it also raises new questions: which features matter most? Are some redundant? Could we drop half the features and still get R2 = 0.55?
In a multiple regression model, the magnitude of each weight does not directly tell you which feature is most important — unless all features are on the same scale. If cement content is measured in hundreds of kg/m3 and superplasticiser in single digits, the weight for superplasticiser may be numerically larger even though cement has more physical influence. Always standardise features (zero mean, unit variance) before comparing weights.
Multicollinearity: When Features Are Tangled
Multicollinearity occurs when two or more features in your model are highly correlated with each other. In the concrete dataset, water content and w/c ratio are correlated by definition (w/c = water / cement). Including both as separate features creates redundancy that can destabilise the model.
What Multicollinearity Does
- Inflated standard errors — The uncertainty in each weight estimate balloons. A weight that should be, say, w = -12.3 +/- 2.0 might become w = -12.3 +/- 45.0. The estimate is useless because the confidence interval is enormous.
- Unstable weights — Small changes in the data (adding or removing a few specimens) cause large swings in the weight values. The model becomes fragile and unreliable for interpretation.
- Misleading feature importance — The model cannot distinguish the individual effects of correlated features. It might assign most of the effect to one feature and almost none to the other, even though both are physically important.
Crucially, multicollinearity does not harm the overall prediction accuracy on new data (as long as the same correlation structure holds). It harms interpretation of individual weights. If you only care about prediction, multicollinearity is less of a concern. If you care about understanding which factors drive strength, it is a serious problem.
Detecting Multicollinearity
- Correlation matrix — Compute the pairwise correlation between all features. Pairs with |r| > 0.8 are suspect.
- Variance Inflation Factor (VIF) — For each feature, regress it against all other features and compute VIF = 1 / (1 - R2). A VIF above 5–10 indicates problematic collinearity.
- Sign flips — If the weight for a feature has an unexpected sign (e.g., cement content shows a negative weight for strength prediction), collinearity is likely the culprit.
Remedies for Multicollinearity
- Remove one of the correlated features — If water content and w/c ratio are both present, drop one. Use domain knowledge to choose which to keep.
- Combine correlated features — Create a composite variable (e.g., use w/c ratio instead of separate water and cement columns).
- Regularisation — Techniques like Ridge Regression (covered in a later sub-chapter) add a penalty term that shrinks correlated weights toward zero, stabilising the model.
- Principal Component Analysis (PCA) — Transform correlated features into a smaller set of uncorrelated principal components. This trades interpretability for stability.
Multicollinearity is like having redundant survey benchmarks. If two benchmarks are located 0.5 metres apart and have nearly identical elevations, using both to interpolate a surface adds no new information — it only introduces numerical instability into the interpolation algorithm. You are better off picking one benchmark and discarding the other. Similarly, two highly correlated features contribute redundant information to the regression.
// For feature x_j, regress x_j against all other features:
// x_j = a0 + a1*x_1 + ... + a_{j-1}*x_{j-1} + a_{j+1}*x_{j+1} + ...
// Compute R^2_j for this regression, then:
VIF_j = 1 / (1 - R^2_j)
// Interpretation:
// VIF = 1.0 -> No collinearity (x_j is independent of others)
// VIF = 5.0 -> Moderate collinearity (80% of x_j variance explained by others)
// VIF = 10+ -> Severe collinearity (90%+ explained) -> investigate and fix
Adjusted R-Squared: A Fairer Metric
In Sub-chapter 2.2, we used R2 to evaluate model quality. But R2 has a built-in flaw: it never decreases when you add more features, even if those features are completely random and carry no real information. Add a column of lottery numbers to your concrete dataset, and R2 will tick upward (or at worst stay the same). This makes naive R2 unreliable for comparing models with different numbers of features.
Adjusted R^2 = 1 - [(1 - R^2) * (n - 1) / (n - p - 1)]
where:
n = number of data points
p = number of features (predictors) in the model
R^2 = ordinary R-squared
// The penalty factor (n-1)/(n-p-1) grows as p increases,
// so Adjusted R^2 can DECREASE when a useless feature is added.
Adjusted R2 introduces a penalty for each additional feature. If a new feature does not improve the model enough to offset the penalty, adjusted R2 drops. This makes it a better criterion for comparing models with different numbers of features. For example:
Comparing Models with Adjusted R2
| Model | Features | R2 | Adj. R2 |
|---|---|---|---|
| A (w/c ratio only) | 1 | 0.250 | 0.249 |
| B (cement + w/c + age) | 3 | 0.520 | 0.518 |
| C (all 8 features) | 8 | 0.615 | 0.612 |
| D (all 8 + 3 random cols) | 11 | 0.618 | 0.610 |
Model D has a slightly higher R2 than C because the random columns capture tiny amounts of noise. But adjusted R2 drops, correctly telling us that the random columns are not worth including.
Use R2 when comparing models with the same number of features. Use adjusted R2 when comparing models with different numbers of features. In practice, always report adjusted R2 for multiple regression models — it is the more honest metric.
Feature Selection: Choosing What Matters
Not every measured variable belongs in your model. Including irrelevant or redundant features wastes data, invites multicollinearity, and can hurt prediction accuracy on new data (especially with small datasets). Feature selection is the process of identifying the subset of features that yields the best trade-off between model simplicity and predictive power.
Domain knowledge (always start here)
As a civil engineer, you know which physical variables influence the outcome. Start with features that have a plausible causal link to the label. For concrete strength, cement content and w/c ratio are obvious candidates. The colour of the delivery truck is not.
Correlation analysis
Compute the correlation between each feature and the label. Features with very low correlation (|r| < 0.1) are unlikely to be useful. Also check for high inter-feature correlations to flag multicollinearity.
Forward / backward selection
Forward selection: start with no features, add the one that most improves adjusted R2, repeat until no feature improves the metric. Backward elimination: start with all features, remove the one whose removal hurts least, repeat until every remaining feature contributes meaningfully.
Cross-validation
Validate your final feature set on held-out data. If you selected features using the training set, the training metrics will be optimistically biased. Only the test-set performance tells you how the model will perform on new, unseen specimens.
Interactive Demo: Multiple Regression Feature Selector
Explore how different feature combinations affect model quality. The demo below simulates a concrete strength dataset with four features: cement content, water-cement ratio, superplasticiser dosage, and curing age. Toggle each feature on or off and watch how R2 and adjusted R2 change in real time. Notice that adding a weakly relevant feature may increase R2 but decrease adjusted R2.
Toggle Features — Watch R2 Change
Enable or disable features to build different regression models. The bar chart shows each feature's individual correlation with strength. The metrics update in real time.
Combining Polynomial and Multiple Regression
You are not limited to choosing between polynomial regression and multiple regression. In practice, you often use both. For example, you might model concrete strength as:
Strength = w0
+ w1 * cement
+ w2 * wc_ratio
+ w3 * wc_ratio^2 // polynomial term for nonlinearity
+ w4 * age
+ w5 * age^2 // strength gain is nonlinear with age
+ w6 * superplasticiser
Here you have multiple features (cement, w/c ratio, age, superplasticiser) and polynomial terms (wc_ratio2, age2). The model is still "linear" in the parameters — each weight appears to the first power — so all the same least-squares machinery applies. This flexibility is one of the great strengths of the regression framework: you can encode complex domain knowledge (e.g., "strength gain decelerates with age") simply by adding the right engineered features.
If you have 8 features and you create polynomial terms up to degree 3 for each, plus all pairwise interaction terms, you can easily end up with hundreds of derived features. This invites overfitting and multicollinearity. Be deliberate: only add polynomial or interaction terms that are physically motivated. If you know that strength gain is nonlinear with age, add age2. Do not blindly generate every possible combination.
Interaction Terms
Sometimes the effect of one feature depends on the value of another. For example, the benefit of superplasticiser might be greater at low w/c ratios than at high ones. You can model this by adding an interaction term:
Strength = w0 + w1*wc + w2*sp + w3*(wc * sp)
// w3 captures the interaction: the combined effect of
// w/c ratio and superplasticiser that is not explained
// by their individual effects alone.
Interaction terms are powerful but increase model complexity. Use them when domain knowledge suggests a genuine interaction, not as a shotgun approach.
The Practical Modelling Workflow
Bringing all the pieces together, here is the recommended workflow for building a polynomial or multiple regression model in civil engineering practice:
Collect and clean data
Gather test results with as many relevant features as possible. Remove duplicates, fix obvious errors, and handle missing values. Document units and measurement methods.
Explore the data
Plot scatter diagrams of each feature vs. the label. Compute the correlation matrix. Identify nonlinear patterns (candidates for polynomial terms) and highly correlated feature pairs (candidates for removal or combination).
Scale features
Standardise all features to zero mean and unit variance, or normalise to the [0, 1] range. This ensures gradient descent converges efficiently and that weight magnitudes are comparable.
Split data into training and test sets
Typically 70-80% for training, 20-30% for testing. Never peek at the test set during model building — it must remain unseen until final evaluation.
Build and compare models
Start simple (linear, few features), then add polynomial terms and additional features. Compare models using adjusted R2 on the training set and RMSE on the test set. Stop when adding complexity no longer improves test performance.
Diagnose and refine
Check VIF for multicollinearity. Plot residuals vs. predicted values. Verify that the model's predictions are physically plausible. If residuals show patterns, add or remove terms accordingly.
Report results with uncertainty
Present the final equation, adjusted R2, RMSE, and the valid input ranges. Always state the limitations: the model is valid only within the range of the training data and under similar conditions.
Practical Tips for Civil Engineers
In most civil engineering applications, a quadratic (degree 2) or cubic (degree 3) polynomial captures the relevant nonlinearity. Higher degrees rarely improve test-set performance and often introduce wild oscillations near the edges of the data range. If you need more flexibility than degree 3, consider switching to a non-parametric model (e.g., decision trees or splines) rather than pushing the polynomial degree higher.
If your feature x ranges from 100 to 500, then x3 ranges from 1,000,000 to 125,000,000. Such extreme values cause numerical instability in the least-squares solver. Always normalise x to a small range (e.g., 0 to 1) before computing polynomial features. This is equivalent to converting all measurements to consistent units before analysis.
Polynomial models are especially dangerous outside the training range. A degree-3 polynomial fitted to data from 0 to 10% strain might predict negative stress at 12% strain or absurdly high stress at 15%. Linear models extrapolate more gracefully (they just continue the line), but polynomials can skyrocket or plummet. Always enforce physical bounds when deploying polynomial models in production.
A regression model is only useful if future engineers can understand and apply it. Document the equation, the feature definitions (with units), the valid input ranges, the training data source, and the performance metrics. Treat the model like a structural calculation: it should be auditable and reproducible by someone who was not involved in its creation.
CE Applications: Polynomial & Multiple Regression
Real engineering data is rarely linear. Polynomial and multiple regression let you capture the non-linear, multi-variable reality of geotechnical and water resources problems.
Geotechnical Applications
- Soil stress-strain curves — Hyperbolic models (Duncan-Chang) fit as polynomial regression. Features: confining pressure, void ratio, plasticity. The stress-strain relationship is inherently non-linear.
- Consolidation settlement — Settlement vs. log(time) follows a curve. Multiple regression with void ratio, compression index, and overconsolidation ratio as features.
- CBR prediction — Predict California Bearing Ratio from Atterberg limits (LL, PL, PI), gradation, and compaction parameters. Polynomial degree 2–3 typically captures the relationship well.
- Permeability estimation — k = f(e, D10, Cu). Hazen's formula is linear; adding grain size distribution features via multiple regression improves predictions by 20–40%.
Water Resources Applications
- IDF curves — Rainfall intensity-duration-frequency curves are inherently polynomial. Fit I = a / (tc + b)n using log-transformed multiple regression.
- Reservoir sedimentation — Predict sediment yield from catchment area, slope, land use, and rainfall erosivity. Non-linear interactions require polynomial features.
- BOD-DO modelling — Streeter-Phelps dissolved oxygen sag curve is a polynomial fit to DO measurements downstream of outfalls.
- Crop water demand — ET0 = f(Tmax, Tmin, humidity, wind, solar radiation). Penman-Monteith is essentially a multiple regression model.
Watch polynomial degree drive underfit → overfit
Slide the polynomial degree from 1 to 15 on noisy 1-D data and watch the fitted curve, the live training-loss trace and the noise floor reshape together — the bias–variance trade-off in one slider.
Test Your Understanding
Answer the following questions to check your grasp of polynomial and multiple regression concepts. Each question relates to civil engineering applications covered in this sub-chapter.
Quick Check 1
A quadratic regression model (degree 2) has the form y = w0 + w1x + w2x2. Why is this still considered a "linear" regression model?
Quick Check 2
You fit a polynomial of degree 8 to 10 soil stress-strain data points and achieve R2 = 0.999 on the training data. When you test on 5 new data points, the RMSE is three times worse than a degree-2 fit. What has happened?
Quick Check 3
In a multiple regression model predicting concrete strength, you notice that the VIF for "water content" is 15.2 and the VIF for "cement content" is 12.8. What does this indicate, and what should you do?
Quick Check 4
You build two models for concrete strength prediction. Model A uses 3 features and achieves R2 = 0.58, adjusted R2 = 0.57. Model B uses 8 features and achieves R2 = 0.61, adjusted R2 = 0.56. Which model should you prefer, and why?
Key Takeaways
What You Should Remember
- Polynomial regression adds higher powers of x (x2, x3, ...) to model curved relationships. It is still linear in the parameters and uses the same least-squares optimisation.
- Overfitting occurs when the model is too complex for the available data. It memorises noise instead of learning the underlying pattern. Symptoms: high training R2, poor test R2, wild oscillations between data points.
- Multiple linear regression uses multiple features simultaneously. Each weight represents the effect of one feature while holding all others constant.
- Multicollinearity arises when features are correlated with each other. It inflates standard errors, destabilises weights, and misleads feature importance. Detect it with VIF; fix it by removing or combining correlated features.
- Adjusted R2 penalises unnecessary features and is the correct metric for comparing models with different numbers of predictors.
- Feature selection should be guided by domain knowledge first, then refined with correlation analysis, forward/backward selection, and cross-validation.
- Polynomial extrapolation is dangerous. Always enforce physical bounds and limit predictions to the training data range.
- In civil engineering, polynomial and multiple regression apply to soil stress-strain modelling, concrete strength prediction, settlement estimation, and any problem where a single straight line is insufficient.
In Sub-chapter 2.4, we move from regression (predicting continuous values) to Classification — predicting discrete categories. You will learn how to classify soil types, detect structural damage, and decide whether a concrete specimen passes or fails a strength threshold. The foundational concepts of features, training, and evaluation you have built across Sub-chapters 2.1–2.3 carry forward directly.