Chapter 2 — Sub-chapter 2.2

Linear Regression

The simplest and most powerful predictive model in engineering — draw a straight line through data and use it to predict the future. From concrete strength to settlement estimation, linear regression is where every engineer's ML journey begins.

35 min read 2 interactive demos 4 quiz questions

The Line That Predicts Concrete Strength

Every civil engineer knows that increasing the water-cement (w/c) ratio weakens concrete. You learned this in your materials course, verified it in the lab, and apply it on every project. But have you ever asked: by exactly how much? If the w/c ratio goes from 0.45 to 0.50, what is the expected drop in 28-day compressive strength?

Linear regression answers that question with mathematical precision. It takes your laboratory data — dozens or hundreds of test results linking w/c ratio to compressive strength — and finds the single straight line that best describes the relationship. That line becomes a predictive tool: feed it any w/c ratio, and it returns the expected strength, along with a measure of how confident you should be in that prediction.

Linear regression is the foundation of predictive modelling. It is the simplest supervised learning algorithm, yet it remains one of the most widely used in engineering practice. Understanding it deeply — not just the formula, but the geometry, the optimisation, and the diagnostics — will prepare you for every model that follows, because more complex algorithms are built on the same principles.

Prerequisites

This sub-chapter assumes you have completed Sub-chapter 2.1 (Supervised Learning Fundamentals) and understand the concepts of features, labels, training data, and loss functions. Basic algebra and familiarity with coordinate geometry (plotting points on an x-y axis) are helpful.

The Equation: y = mx + b

Linear regression boils down to finding the best straight line through a set of data points. That line is described by the equation you first met in secondary school:

The Linear Equation
y = m * x + b

where:
  y = predicted output (e.g., compressive strength in MPa)
  x = input feature  (e.g., water-cement ratio)
  m = slope          (how much y changes per unit change in x)
  b = y-intercept    (the value of y when x = 0)

In machine learning notation, you will often see this written as ŷ = w1x + w0, where w1 is the weight (slope) and w0 is the bias (intercept). The hat on ŷ indicates it is a predicted value, not the actual measured value. Do not let the notation change confuse you — it is the same equation.

Civil Engineering Analogy

The linear equation is like Abrams' Law for concrete. Duff Abrams showed in 1918 that concrete strength is inversely related to the water-cement ratio. His empirical formula is essentially a regression model fitted to laboratory data. Linear regression formalises and generalises this process: instead of deriving a formula by hand, the algorithm finds the optimal parameters automatically from your data.

Key Points

Slope (m) = rate of change. If m = -65, every 0.01 increase in w/c drops strength by 0.65 MPa. Intercept (b) = value at x = 0; often physically meaningless but mathematically necessary. Extrapolation warning: Only trust the model within the training data range (e.g., w/c 0.35–0.65). Outside that range, the relationship may be non-linear.

CE Context: Predicting Concrete Compressive Strength

Let us ground the theory in a real civil engineering problem. We have a dataset of concrete specimens, each tested at 28 days. For each specimen, we recorded the water-cement ratio (our feature, x) and the resulting compressive strength in MPa (our label, y). Our goal: fit a line that best describes this relationship, then use that line to predict the strength of future mixes.

Sample Dataset: Water-Cement Ratio vs. 28-Day Strength

Here is a simplified dataset that we will use throughout this sub-chapter:

Specimen w/c Ratio (x) Strength MPa (y)
C-01 0.35 48.2
C-02 0.40 43.5
C-03 0.45 39.1
C-04 0.50 34.8
C-05 0.55 31.0
C-06 0.60 27.5
C-07 0.65 23.8

Notice the clear trend: as the w/c ratio increases, compressive strength decreases. The relationship is approximately linear within this range.

If you plotted these seven points on a graph, you would see them falling roughly along a straight line — but not perfectly. Real data always has scatter caused by variations in aggregate quality, curing conditions, testing equipment, and human error. The goal of linear regression is to find the line that best represents the underlying trend despite this scatter.

The Least Squares Method

How do we define "best" when fitting a line? We need a mathematical criterion that measures how well a candidate line fits the data. The most widely used criterion is the method of least squares, developed by Legendre and Gauss over two centuries ago.

Residuals: The Distance Between Prediction and Reality

For each data point, the residual is the vertical distance between the actual value (yi) and the predicted value (ŷi) on the regression line:

Residual Formula
residual_i = y_i - y_hat_i
           = y_i - (m * x_i + b)

A positive residual means the data point is above the line (the model underestimates). A negative residual means the point is below the line (the model overestimates). The best line minimises these residuals — but we cannot just sum them, because positive and negative values would cancel out.

1

Compute each residual

For every data point, subtract the predicted ŷ from the actual y. This gives you a list of errors — some positive, some negative.

2

Square each residual

Squaring eliminates negative signs and penalises large errors more heavily than small ones. A point that is off by 10 MPa contributes 100 to the sum, while a point off by 2 MPa contributes only 4.

3

Sum the squared residuals

The total is the Sum of Squared Errors (SSE). The line that produces the smallest SSE is the best-fit line. This is the "least squares" criterion.

Civil Engineering Analogy

Least squares is like surveying with a total station. When you measure elevations along a proposed road alignment, no single measurement is perfectly accurate. To design the road profile, you fit a smooth curve that minimises the overall deviation from all measured points. You do not force the curve through every point (that would follow the noise), but you find the profile that best represents the true ground level. Least squares does the same thing mathematically.

The Cost Function: Mean Squared Error

In machine learning, the quantity we minimise is called the cost function (also called the loss function or objective function). For linear regression, the standard cost function is the Mean Squared Error (MSE):

Mean Squared Error
MSE = (1/n) * SUM[ (y_i - y_hat_i)^2 ]

where:
  n      = number of data points
  y_i    = actual measured value for point i
  y_hat_i = predicted value (m * x_i + b) for point i

MSE is simply the average of the squared residuals. It has the same units as y2 (MPa2 in our concrete example), which can make interpretation tricky. That is why you will sometimes see the Root Mean Squared Error (RMSE) — the square root of MSE — which returns the error to the original units (MPa).

The Cost Surface: A Bowl-Shaped Landscape

Imagine plotting MSE as a function of the two parameters m (slope) and b (intercept). For every pair (m, b), you get a single MSE value. If you plot all possible MSE values in 3D, you get a bowl-shaped surface (technically a paraboloid). The bottom of the bowl represents the optimal m and b — the values that minimise the error.

Finding the minimum of this bowl is the entire goal of training a linear regression model. There are two ways to do it: the closed-form solution (normal equations) and the iterative approach (gradient descent). Both reach the same answer, but gradient descent scales to problems with millions of features where closed-form solutions are computationally impractical.

Why "Cost" Function?

The name comes from optimisation theory. Think of the MSE as the "cost" of being wrong. High MSE = high cost = bad model. Low MSE = low cost = good model. Training is the process of reducing this cost. Civil engineers already think in terms of cost optimisation — minimising material cost subject to strength constraints. ML optimisation is conceptually identical: minimise prediction error subject to the model structure.

Gradient Descent: Walking Downhill

Gradient descent is the workhorse algorithm for training machine learning models. It finds the minimum of the cost function by taking iterative steps in the direction of steepest descent — like a ball rolling to the bottom of a bowl.

1

Initialise parameters

Start with random (or zero) values for the slope m and intercept b. At this point, the model's predictions are essentially random, and the MSE is high. You are at a random position on the bowl-shaped cost surface.

2

Compute the gradient

The gradient is the vector of partial derivatives of the cost function with respect to each parameter. It points in the direction of steepest ascent. We want to go the opposite direction (downhill), so we subtract the gradient.

3

Update parameters

Adjust m and b by subtracting a fraction of the gradient. The fraction is controlled by the learning rate (alpha) — a small positive number (e.g., 0.01) that determines the step size.

4

Repeat until convergence

Keep computing gradients and updating parameters. With each iteration, the MSE decreases and the model improves. Stop when the improvement becomes negligibly small (convergence) or after a set number of iterations.

Gradient Descent Update Rules
// For each iteration:
gradient_m = (2/n) * SUM[ x_i * (y_hat_i - y_i) ]
gradient_b = (2/n) * SUM[ (y_hat_i - y_i) ]

m = m - learning_rate * gradient_m
b = b - learning_rate * gradient_b
Civil Engineering Analogy

Gradient descent is like grading a site to find the lowest point. Imagine you are standing on hilly terrain in dense fog and need to find the lowest elevation. You cannot see the whole landscape, but you can feel the slope under your feet. At each step, you walk in the direction where the ground slopes downward most steeply. Eventually, you reach the valley floor — the minimum. The learning rate is your step length: too large and you overshoot the valley; too small and you take forever to get there.

The Learning Rate: A Critical Hyperparameter

The learning rate controls how aggressively the model updates its parameters. It is a hyperparameter — a value you set before training, not learned from the data.

  • Too large — The model overshoots the minimum, bouncing back and forth across the valley or even diverging to infinity. Like a bulldozer that takes steps too big for the terrain.
  • Too small — The model creeps toward the minimum agonisingly slowly, wasting computation. Like surveying millimetre by millimetre when metre-level steps would suffice.
  • Just right — The model converges efficiently to the minimum in a reasonable number of iterations. Typical values range from 0.001 to 0.1.

R-Squared: Measuring Model Quality

Once we have fitted a line, we need to know: how good is it? The MSE tells us the average squared error, but its magnitude depends on the scale of the data. A model predicting concrete strength in MPa might have an MSE of 4.0, while a model predicting settlement in millimetres might have an MSE of 0.5 — but which model is better relative to its problem?

Enter R-squared (R2), also called the coefficient of determination. It measures the proportion of variance in the label that is explained by the model, on a scale from 0 to 1.

R-Squared Formula
R^2 = 1 - (SS_res / SS_tot)

where:
  SS_res = SUM[ (y_i - y_hat_i)^2 ]   (residual sum of squares)
  SS_tot = SUM[ (y_i - y_mean)^2 ]    (total sum of squares)

  y_mean = average of all actual y values

Interpreting R-Squared

  • R2 = 1.0 — The model explains 100% of the variance. Every prediction matches the actual value exactly. This almost never happens with real data.
  • R2 = 0.85 — The model explains 85% of the variance in the data. This is excellent for most engineering applications.
  • R2 = 0.50 — The model explains only half the variance. Significant patterns remain uncaptured. You might need more features or a non-linear model.
  • R2 = 0.0 — The model is no better than simply predicting the mean for every data point. The features have no linear relationship with the label.
R-Squared Limitations

R2 always increases (or stays the same) when you add more features, even if those features are irrelevant. This is why the Adjusted R2 exists — it penalises unnecessary features. Also, a high R2 does not guarantee the model is correct. The relationship might be non-linear, and a straight line might still achieve a decent R2 while missing important curvature. Always examine the residuals.

Residual Analysis: Diagnosing Your Model

Fitting a line is only half the job. A responsible engineer always checks the residuals — the differences between actual and predicted values — to verify that the model's assumptions hold. Residual analysis is the engineering equivalent of quality control.

Residual Patterns: Good vs. Bad

Healthy Warning Sign
Randomly scattered around zero Curved pattern → relationship is non-linear (try polynomial)
Constant spread (homoscedastic) Funnel shape → heteroscedasticity (try log transform)
Approximately normal distribution Outliers → investigate: data error, unusual specimen, or real anomaly
Civil Engineering Analogy

Residual analysis is like checking theodolite closing errors. After completing a traverse survey, you compute the closing error to assess accuracy. If the error is small and random, the survey is acceptable. If the error shows a systematic pattern (always drifting in one direction), something is wrong with the instrument or technique. Residuals serve the same diagnostic purpose for regression models.

Putting It All Together: The Complete Workflow

  1. Collect & clean data — w/c ratio (x) and 28-day strength (y) from lab records.
  2. Visualise — Scatter plot to confirm linearity and spot outliers.
  3. Fit — Least squares or gradient descent → Strength = -81.3×(w/c) + 76.8
  4. Evaluate — Compute R², RMSE, check residuals for patterns.
  5. Predict — w/c = 0.48 → 37.8 MPa. Always report uncertainty (R², RMSE).
Complete Workflow in Pseudocode
// 1. Data
x = [0.35, 0.40, 0.45, 0.50, 0.55, 0.60, 0.65]
y = [48.2, 43.5, 39.1, 34.8, 31.0, 27.5, 23.8]

// 2. Compute means
x_mean = average(x)    // 0.50
y_mean = average(y)    // 35.41

// 3. Compute slope (m) and intercept (b)
numerator   = SUM[ (x_i - x_mean) * (y_i - y_mean) ]
denominator = SUM[ (x_i - x_mean)^2 ]
m = numerator / denominator   // approx -81.3
b = y_mean - m * x_mean       // approx 76.1

// 4. Predict
for w_c_ratio = 0.48:
    predicted_strength = m * 0.48 + b  // approx 37.1 MPa

// 5. Evaluate
R_squared = 1 - SS_res / SS_tot   // approx 0.998

Interactive Demo: Build Your Own Regression Line

Experience linear regression firsthand. Click on the canvas below to add data points (imagine each click is a concrete test result). The algorithm will compute and display the best-fit line in real time, updating the slope, intercept, and R2 as you add more data. Watch how the line stabilises as you add more points and how a single outlier can shift it.

Click to Add Points — Watch the Best-Fit Line

Click anywhere on the canvas to place data points. The regression line, slope, intercept, and R2 update automatically after 2+ points. Toggle residuals to see the error lines.

Equation: click to add points R2: — MSE: — Points: 0

Interactive Demo: Gradient Descent Visualiser

See gradient descent in action. This demo shows the bowl-shaped cost surface (contour plot of MSE as a function of slope and intercept) and traces the path the algorithm takes as it walks downhill toward the minimum. Adjust the learning rate to see how step size affects convergence. Too large and the path overshoots; too small and it crawls.

Gradient Descent on the Cost Surface

The contour lines represent equal MSE values. The darkest region is the minimum (optimal parameters). Click "Start" to watch gradient descent navigate to the minimum. Adjust the learning rate and observe the effect.

Iteration: 0 Slope: — Intercept: — MSE: —

Beyond One Feature: Multiple Linear Regression

So far, we have used a single feature (w/c ratio) to predict concrete strength. But concrete strength depends on many factors: cement content, aggregate type, superplasticiser dosage, curing temperature, and more. Multiple linear regression extends the single-feature model to handle multiple inputs simultaneously:

Multiple Linear Regression
y_hat = w_0 + w_1 * x_1 + w_2 * x_2 + ... + w_p * x_p

Example for concrete strength:
  Strength = w_0
           + w_1 * (cement content)
           + w_2 * (w/c ratio)
           + w_3 * (fine aggregate)
           + w_4 * (coarse aggregate)
           + w_5 * (superplasticiser)
           + w_6 * (age in days)

The principles are identical — we still minimise MSE, still use gradient descent (now with more parameters to update), and still evaluate with R2. The only difference is that instead of a 2D line, we are fitting a hyperplane in multi-dimensional space. You cannot visualise it beyond three dimensions, but the mathematics works exactly the same way.

Feature Scaling Matters

When features have vastly different scales (e.g., cement content in hundreds of kg/m3 vs. w/c ratio between 0.3 and 0.7), gradient descent can struggle. The cost surface becomes elongated (like an ellipse rather than a circle), causing the algorithm to zigzag inefficiently.

The solution is feature scaling: normalise all features to a similar range (e.g., 0 to 1) before training. This is analogous to converting all measurements to consistent units before performing structural analysis — you would not mix metres and millimetres in the same stiffness matrix.

Practical Tips for Civil Engineers

Engineer's Checklist

  1. Start simple — If linear regression gives R² = 0.92, you may not need a neural network. Simpler models are easier to explain to project managers.
  2. Check assumptions — Linearity, independent errors, constant variance, normal residuals. Always plot residuals vs. predicted values.
  3. Use domain knowledge — Concrete strength cannot be negative. Settlement increases with load. If your equation violates physics, something is wrong.
  4. Report uncertainty — "Predicted strength = 37 ± 3 MPa (R² = 0.95)" is far more useful than just "37 MPa".

CE Applications: Linear Regression in Practice

Linear regression is arguably the most frequently used ML tool in civil engineering research. Here are real geotechnical and water resources problems where the y = mx + b framework applies directly.

Geotechnical Regression Models

  • SPT-N → Settlement — Predict footing settlement (mm) from SPT blow count, footing width, and applied pressure. Classic Burland & Burbidge correlations are essentially linear regression fits.
  • CPT qc → Undrained shear strength — su = (qc - σv0) / Nk. The cone factor Nk is found by regression against lab vane shear data.
  • Atterberg limits → Compression index — Cc = 0.009(LL - 10). Terzaghi's classic correlation is linear regression with one feature.
  • Load test data → Pile capacity — Fit load-settlement curves to estimate ultimate bearing capacity from static/dynamic test results.

Water Resources Regression Models

  • Rainfall-runoff — Predict peak discharge Q from rainfall depth P, catchment area A, and curve number CN. Q = a·P + b is the simplest unit hydrograph approach.
  • Stage-discharge rating curves — Fit Q = a(h - h0)n to gauging station data. Log-transform makes this a linear regression problem.
  • Evapotranspiration estimation — Predict ET from temperature, humidity, and wind speed. Hargreaves equation is a regression-derived formula.
  • Groundwater recharge — Correlate water table rise with cumulative rainfall, land-use index, and soil permeability.
Already Using It

If you've ever used Terzaghi's Cc correlation, Abrams' Law, or a stage-discharge curve, you've applied linear regression. ML simply automates fitting, handles multiple features simultaneously, and quantifies uncertainty through R² and RMSE.

Try it interactively

Fit linear regression to concrete strength — in Python

Open the in-browser Python playground and run scikit-learn's LinearRegression on a real concrete dataset — train, predict and inspect coefficients live, no install required.

Open Playground

Test Your Understanding

Answer the following questions to check your grasp of linear regression concepts. Each question relates to civil engineering applications covered in this sub-chapter.

Quick Check 1

In the linear regression equation y = mx + b for predicting concrete strength from water-cement ratio, what does the slope (m) represent?

Quick Check 2

Why does the least squares method square the residuals instead of simply summing them?

Quick Check 3

In gradient descent, what happens if the learning rate is set too high?

Quick Check 4

A linear regression model predicting concrete compressive strength from w/c ratio yields R2 = 0.03. What does this tell you?

Key Takeaways

What You Should Remember

  • Linear regression fits a straight line (y = mx + b) to data by minimising the Mean Squared Error between predictions and actual values.
  • The slope tells you the rate of change; the intercept positions the line on the y-axis.
  • The least squares method finds the optimal parameters by minimising the sum of squared residuals.
  • Gradient descent is an iterative optimisation algorithm that walks downhill on the cost surface. The learning rate controls step size.
  • R-squared measures the proportion of variance explained by the model, from 0 (useless) to 1 (perfect).
  • Always check residuals for patterns — random scatter is good; systematic patterns indicate model mis-specification.
  • Do not extrapolate beyond the range of training data. The model is only reliable within the observed input range.
  • In civil engineering, linear regression powers applications from concrete strength prediction to settlement estimation and traffic volume forecasting.
Coming Up Next

In Sub-chapter 2.3, we extend the linear model to handle curved relationships using Polynomial Regression. You will learn how to fit parabolas and higher-order curves to data, when to use polynomial terms, and how to avoid the trap of overfitting. The concepts of MSE, R2, and gradient descent you learned here carry forward directly.

Real-world case study · Multivariate linear regression in concrete mix design

Concrete.ai × CRH — a regression-driven cement-reduction engine deployed at North America's largest aggregate producer

Cement is responsible for ~8% of global CO₂. Concrete.ai trains multivariate linear regression on millions of historical mix-strength records to recommend lower-cement, lower-carbon batches that still hit the 28-day strength spec — now used by CRH brands across the US.

0Embodied CO₂ cut
0Core mix variables
0Strength target preserved
0USD market (CRH revenue)

Every concrete batch is a multi-variable problem: w/c ratio, cement content, supplementary cementitious materials (fly ash, slag), admixtures, aggregate gradation, temperature. Producers traditionally pick from a small library of "safe" mixes with high cement — over-strength by 15–25% just to absorb variability.

  • That over-design wastes cement — the single biggest CO₂ lever in construction.
  • QC labs already record every batch's slump, strength, and constituents — the data exists but isn't used beyond pass/fail.
  • Producers need a recommendation that is auditable, explainable to the engineer of record, and code-compliant.

The flagship model is a deliberately linear, multivariate regression — chosen so coefficients are explainable to a concrete technician and an EOR.

  • Targets: 7-day and 28-day compressive strength fc'.
  • Features: cement, water, fly ash, slag, fine/coarse aggregate, admixture dose, curing temperature.
  • Form: fc' ≈ β0 + β1·w/c + β2·cement + β3·fly_ash + …
  • Regression is fit per producer, per plant, per region — because aggregates differ.
  • An optimiser then searches the feature space for the lowest-CO₂ mix that still satisfies the strength + slump + cost constraints.

Linear regression is "boring" — and that is the point. Auditors, EORs and ACI 318 reviewers can read the coefficients directly.

CRH brands (Aggregate Industries, Oldcastle) deploy Concrete.ai's recommendations at ready-mix plants across the US. Independent project case studies report:

  • 5–15% CO₂ reduction per cubic yard, primarily by partial cement replacement with fly ash / slag at controlled w/c.
  • No reduction in 28-day strength or workability.
  • Material-cost savings of $1–$4 / yd³ on top of the CO₂ benefit.
  • Linear isn't a limitation — it's a feature. Explainability is what gets ML accepted under ACI/AASHTO codes.
  • Local data beats global models. Coefficients differ enough between aggregates that "one giant model" loses to per-plant fits.
  • The biggest gains are decarbonisation, not cost. Even modest cement reductions add up to mega-tonnes of CO₂ at industry scale.