Chapter 2 — Sub-chapter 2.5

Logistic Regression

When the question is not "how much?" but "what is the probability?" — logistic regression turns linear algebra into calibrated probabilities. From predicting whether a concrete beam will crack under load to classifying dam safety risk levels, this algorithm is the workhorse of probabilistic classification in engineering practice.

40 min read 2 interactive demos 4 quiz questions

Beyond Yes or No — How Likely?

A structural inspector does not simply declare a bridge "safe" or "unsafe." They assess the probability that a component will fail within its design life. A dam safety engineer quantifies the likelihood that an embankment will overtop during a 100-year flood event. These are not binary questions — they are questions about probability.

Logistic regression is the first algorithm you will encounter that outputs a calibrated probability rather than a raw class label. It sits at the boundary between regression and classification: it uses a linear equation internally (just like the linear regression you mastered in Sub-chapter 2.2) but passes the result through a special function — the sigmoid — that squashes the output into the range [0, 1]. The result is a probability estimate that you can threshold into a decision.

In Sub-chapter 2.4, you learned the fundamentals of classification: binary vs. multi-class problems, decision boundaries, confusion matrices, and evaluation metrics like precision, recall, and the F1-score. Logistic regression is the natural next step — it is the simplest algorithm that produces probability-based classifications, and understanding it deeply will prepare you for every advanced classifier that follows.

We will cover:

  • The sigmoid function and why it maps any real number to a probability
  • Log-odds (logit) — the linear core inside logistic regression
  • Probability thresholds and how they control precision-recall trade-offs
  • Binary cross-entropy — the loss function that trains the model
  • Multi-class extension via the softmax function
  • Civil engineering applications: failure prediction and dam safety classification
Prerequisites

This sub-chapter builds on Sub-chapters 2.2 (Linear Regression) and 2.4 (Classification Basics). You should be comfortable with the idea of a linear equation, the concept of a loss function, and the confusion matrix with its derived metrics (precision, recall, F1).

Why Linear Regression Fails for Classification

Imagine you want to predict whether a concrete cylinder will fail a quality test based on its water-cement (W/C) ratio. You have historical data: cylinders with low W/C ratios tend to pass, cylinders with high W/C ratios tend to fail. The natural first thought is to use the linear regression you already know.

The problem is that linear regression predicts any real number from negative infinity to positive infinity. But a probability must stay between 0 and 1. If you fit a straight line to your pass/fail data:

The Problem with Linear Regression for Binary Outcomes
y = w * x + b

For W/C = 0.30 (very good concrete):   y = -0.35   (negative probability?!)
For W/C = 0.55 (borderline):           y =  0.50   (reasonable)
For W/C = 0.85 (very high W/C):        y =  1.30   (probability > 1?!)

Predictions below 0 or above 1 are meaningless as probabilities. You could clamp them, but this introduces hard thresholds and wastes information from the extreme data points. We need a function that naturally constrains the output to [0, 1] no matter what the input is. Enter the sigmoid function.

A Civil Engineering Analogy

Think of it like a safety factor analysis. A safety factor can theoretically range from 0 to infinity, but what the engineer really wants is a probability of failure — a value between 0 and 1. Converting a safety factor into a failure probability requires a non-linear transformation, much like the sigmoid function converts a linear score into a probability.

The Sigmoid Function

The sigmoid function (also called the logistic function) is the mathematical heart of logistic regression. It takes any real number and maps it to a value between 0 and 1:

Sigmoid Definition
                    1
sigma(z) = ----------------
            1 + exp(-z)

Where:
  z = w * x + b       (the linear combination, same as linear regression)
  exp(-z) = e^(-z)    (the exponential function)
  sigma(z) is always in (0, 1)

The sigmoid has several elegant properties that make it perfect for probability estimation:

1

Bounded Output

No matter how large or small z becomes, sigma(z) is always strictly between 0 and 1. As z approaches positive infinity, sigma(z) approaches 1. As z approaches negative infinity, sigma(z) approaches 0. This makes it a natural probability function.

2

Smooth S-Shape

The function transitions gradually from 0 to 1, centred at z = 0 where sigma(0) = 0.5. This smoothness is crucial — it means the function is differentiable everywhere, which allows gradient-based optimisation to train the model efficiently.

3

Monotonically Increasing

A higher linear score always produces a higher probability. This makes the model interpretable: if the weight for W/C ratio is negative, then increasing the W/C ratio always decreases the probability of passing — which aligns with engineering intuition.

4

Symmetry

sigma(-z) = 1 - sigma(z). This symmetry means the function treats the two classes equally — the curve is symmetric about the point (0, 0.5). In our concrete example, a W/C ratio equally far below the decision boundary is just as "confident pass" as one equally far above is "confident fail."

CE Application: Crack Probability in RC Beams

Consider predicting whether a reinforced concrete beam will develop visible cracks under service load. Your features might include the reinforcement ratio, concrete cover depth, span-to-depth ratio, and applied load intensity. The sigmoid function wraps these into a single probability:

P(crack) = sigma(w1 * reinforcement_ratio + w2 * cover + w3 * span_depth + w4 * load + b)

If P(crack) = 0.82, the model is 82% confident that cracking will occur — a much more informative statement than a binary "yes" or "no."

Log-Odds: The Linear Core

The sigmoid function maps a linear score to a probability, but the logit function does the reverse — it maps a probability back to a real number. Understanding this inverse is key to interpreting logistic regression coefficients.

The Logit (Inverse Sigmoid)
logit(p) = ln( p / (1 - p) )

Where:
  p         = probability of the positive class (e.g., P(fail))
  p/(1-p)   = the "odds" of the event
  ln(...)   = natural logarithm

Example:
  If P(fail) = 0.80,  odds = 0.80/0.20 = 4.0,   logit = ln(4.0) = 1.39
  If P(fail) = 0.50,  odds = 0.50/0.50 = 1.0,   logit = ln(1.0) = 0.00
  If P(fail) = 0.20,  odds = 0.20/0.80 = 0.25,  logit = ln(0.25) = -1.39

This reveals something elegant: logistic regression models the log-odds as a linear function of the features. While the probability itself follows an S-shaped curve, the log-odds are perfectly linear. This is why it is called logistic regression — it is regression on the logit (log-odds) scale.

The Logistic Regression Model
Step 1: Compute the log-odds (linear part)
  z = w1*x1 + w2*x2 + ... + wn*xn + b

Step 2: Convert to probability (sigmoid part)
  P(class = 1) = 1 / (1 + exp(-z))

Step 3: Classify (threshold part)
  If P(class = 1) >= threshold:  predict class 1 (e.g., "fail")
  If P(class = 1) <  threshold:  predict class 0 (e.g., "pass")

Interpreting Coefficients

Each weight in logistic regression has a direct interpretation on the log-odds scale: a one-unit increase in feature x_i changes the log-odds by w_i. Equivalently, it multiplies the odds by exp(w_i).

Example: if the weight for W/C ratio is w = 8.5, then increasing W/C by 0.01 increases the log-odds of failure by 0.085, which multiplies the odds of failure by exp(0.085) = 1.089 — roughly a 9% increase in the odds. This kind of interpretability is invaluable when explaining model predictions to project stakeholders.

The Probability Threshold

Logistic regression outputs a probability, but many applications require a definitive decision: pass or fail, safe or unsafe, accept or reject. The probability threshold (also called the decision threshold or cut-off) is the value above which you classify a sample as positive.

The default threshold is 0.5 — if P(positive) >= 0.5, predict positive. But this is not always the best choice, especially in civil engineering where the cost of different errors varies dramatically.

Safety-Critical Thresholds

Consider a model predicting whether a bridge girder has hidden corrosion damage. With a threshold of 0.5, you only flag girders that are more likely than not to be damaged. But in a safety-critical context, you might lower the threshold to 0.2 — flag any girder with even a 20% estimated probability of damage.

This means more false positives (unnecessary inspections) but far fewer false negatives (missed damage). The cost of an extra inspection is trivial compared to the cost of a structural failure. The threshold encodes your engineering judgement about acceptable risk.

Adjusting the threshold is equivalent to sliding along the precision-recall curve. As you lower the threshold:

  • Recall increases — you catch more true positives
  • Precision decreases — more of your positive predictions are wrong
  • False positive rate increases — more false alarms

As you raise the threshold:

  • Precision increases — when you flag something, you are more confident
  • Recall decreases — you miss more true positives
  • False positive rate decreases — fewer false alarms
The Right Threshold Depends on the Context

There is no universally correct threshold. For structural safety, err on the side of recall (low threshold). For routine quality control where re-testing is expensive, balance precision and recall (moderate threshold). For spam filtering in a project management system, err on the side of precision (high threshold) to avoid losing important emails. The engineering context determines the optimal operating point.

Binary Cross-Entropy: The Loss Function

In linear regression, we trained the model by minimising the Mean Squared Error (MSE) — the average squared difference between predictions and actual values. For logistic regression, we use a different loss function called binary cross-entropy (also known as log loss).

Why not use MSE for logistic regression? Because the sigmoid function creates a non-convex MSE surface with many local minima, making optimisation unreliable. Binary cross-entropy, by contrast, produces a convex loss surface with a single global minimum — gradient descent is guaranteed to find the best solution.

Binary Cross-Entropy Formula
For a single sample:
  L = -[ y * ln(p) + (1 - y) * ln(1 - p) ]

Where:
  y = true label (0 or 1)
  p = predicted probability (from sigmoid)
  ln = natural logarithm

For the full dataset (N samples):
  J = -(1/N) * SUM[ yi * ln(pi) + (1 - yi) * ln(1 - pi) ]

The intuition behind binary cross-entropy is beautifully simple:

When y = 1 (actual positive, e.g., "fail")

The loss is -ln(p). If the model predicts p = 0.95 (confident and correct), the loss is -ln(0.95) = 0.05, very small. If the model predicts p = 0.05 (confident and wrong), the loss is -ln(0.05) = 3.0, very large. The function heavily penalises confident wrong predictions.

When y = 0 (actual negative, e.g., "pass")

The loss is -ln(1 - p). If the model predicts p = 0.05 (correctly low), the loss is -ln(0.95) = 0.05, very small. If the model predicts p = 0.95 (wrongly high), the loss is -ln(0.05) = 3.0, very large. Again, confident mistakes are expensive.

CE Analogy: Cost of Mistakes

Binary cross-entropy mirrors how engineering errors are penalised in practice. A small deviation from the specification is a minor issue. But a catastrophically wrong assessment — declaring a failing component safe with high confidence — incurs enormous cost. The logarithmic penalty naturally captures this escalating risk: the worse the prediction, the disproportionately higher the penalty.

How Training Works

Training a logistic regression model means finding the weights (w) and bias (b) that minimise the binary cross-entropy loss across all training samples. The algorithm uses gradient descent, the same optimisation technique used in linear regression.

1

Initialise

Start with random (or zero) weights. The model's initial predictions will be essentially random — around 50% probability for everything.

2

Forward Pass

For each training sample, compute z = w*x + b, then apply the sigmoid to get the predicted probability p. Compare p to the true label y using binary cross-entropy to get the loss.

3

Compute Gradients

Calculate how the loss changes with respect to each weight. Thanks to the sigmoid and cross-entropy combination, the gradient has a remarkably clean form: dL/dw = (p - y) * x. The error signal is simply the difference between prediction and truth, scaled by the input feature.

4

Update Weights

Adjust each weight in the direction that reduces the loss: w = w - learning_rate * gradient. Repeat steps 2-4 for many iterations (epochs) until the loss converges.

Convergence Guarantee

Because the binary cross-entropy loss for logistic regression is convex, gradient descent is guaranteed to find the global minimum (given a sufficiently small learning rate). This is a significant advantage over more complex models like neural networks, where you can get stuck in local minima. For civil engineering applications where reliability and reproducibility matter, this guarantee is reassuring.

The Decision Boundary

The decision boundary is the set of points where the predicted probability is exactly equal to the threshold (typically 0.5). For a two-feature model, this boundary is a straight line (or hyperplane in higher dimensions), because logistic regression is a linear classifier.

Decision Boundary Equation (threshold = 0.5)
At the boundary:  P(class = 1) = 0.5
                  sigma(z) = 0.5
                  z = 0
Therefore:        w1*x1 + w2*x2 + b = 0

This is a straight line in 2D feature space.
Points above the line: z > 0, P > 0.5 => predict class 1
Points below the line: z < 0, P < 0.5 => predict class 0

The linearity of the decision boundary is both a strength and a limitation. It makes the model simple, interpretable, and fast. But it cannot capture complex, curved boundaries between classes. If the true boundary between "safe" and "unsafe" in your feature space is non-linear, logistic regression will find the best linear approximation — which may not be good enough.

CE Example: Pavement Condition Classification

Suppose you classify pavement sections as "needs repair" or "acceptable" based on two features: International Roughness Index (IRI) and pavement age. The logistic regression decision boundary is a line in the IRI-vs-Age plane. Sections above and to the right of the line (high IRI, old pavement) are classified as needing repair. In reality, the deterioration pattern might be non-linear — pavement degrades slowly at first, then rapidly after a threshold. But the linear boundary still captures the general trend and provides a useful first-pass screening tool.

CE Application: Predicting Structural Failure Probability

One of the most impactful applications of logistic regression in civil engineering is predicting the probability that a structural component will fail under specified conditions. This goes beyond traditional factor-of-safety approaches by providing a probabilistic assessment that accounts for uncertainty in material properties and loading conditions.

Case Study: Concrete Column Failure Under Eccentric Loading

A dataset of 500 reinforced concrete column tests records:

  • Features: column height (mm), cross-section area (mm²), reinforcement ratio (%), eccentricity (mm), concrete strength f'c (MPa), applied load (kN)
  • Label: 0 = survived (no failure), 1 = failed (buckling, crushing, or combined failure)

After training, the model learns coefficients that allow it to estimate P(failure) for any new column configuration. An engineer designing a column can input the planned dimensions and expected loading to get a failure probability estimate — then iterate on the design until P(failure) is acceptably low.

Practical Benefit

Unlike a binary pass/fail check, logistic regression tells you how close a design is to the failure boundary. A column with P(failure) = 0.03 has a comfortable margin. One with P(failure) = 0.45 is dangerously close. This granularity helps engineers prioritise which designs need the most attention and where to invest in additional safety measures.

Interactive Demo: Sigmoid Function Visualiser

Explore how the sigmoid function transforms a linear score into a probability. Adjust the weight (slope) and bias (horizontal shift) sliders to see how the S-curve changes. Hover over the curve to read off probability values at specific input values.

Sigmoid Curve: sigma(z) = 1 / (1 + exp(-z))

The weight controls the steepness of the curve. A higher weight makes the transition sharper. The bias shifts the curve left or right, moving the 50% probability point.

Adjust sliders to change the sigmoid shape. Hover over the canvas to read probability values.

Multi-Class Extension: Softmax Regression

Standard logistic regression handles binary classification — two classes. But many engineering problems have more than two categories. Soil classification (clay, silt, sand, gravel), damage severity (none, minor, moderate, severe), structural condition rating (A through E) — all require multi-class classification.

The multi-class extension of logistic regression replaces the sigmoid with the softmax function. Instead of computing a single probability, softmax computes a probability for each class, and these probabilities sum to 1.

Softmax Function
For K classes, each with its own weight vector:
  z_k = w_k * x + b_k          (one linear score per class)

                 exp(z_k)
P(class = k) = -----------
               SUM exp(z_j)
               j=1..K

Properties:
  - Each P(class = k) is in (0, 1)
  - Sum of all K probabilities = 1
  - When K = 2, softmax reduces to the sigmoid

CE Application: Dam Safety Risk Classification

Dam safety regulations often require classifying dam condition into risk categories: Low, Moderate, High, and Critical. Features might include:

  • Seepage rate (litres/min)
  • Settlement rate (mm/year)
  • Pore water pressure ratio (u/gamma*h)
  • Years since last major rehabilitation
  • Peak ground acceleration at site (g)

A softmax model outputs four probabilities: P(Low) = 0.05, P(Moderate) = 0.15, P(High) = 0.65, P(Critical) = 0.15. The dam is classified as "High Risk" (the class with the highest probability), but the full distribution tells the engineer that there is a non-trivial 15% chance the situation is actually critical — information that a simple label would hide.

Cross-Entropy Generalises Too

The loss function for multi-class logistic regression is categorical cross-entropy — a natural extension of binary cross-entropy. Instead of comparing one probability to one label, it compares the full predicted probability distribution to the true class (represented as a one-hot vector). The mathematics are analogous; only the bookkeeping expands.

Regularisation: Preventing Overconfidence

Like linear regression, logistic regression can overfit when there are many features relative to the number of training samples. Overfitting manifests as extreme weight values that produce near-0 or near-1 probabilities for almost every sample — the model becomes overconfident.

Regularisation adds a penalty term to the loss function that discourages large weights:

Regularised Loss
L2 Regularisation (Ridge):
  J_reg = J + (lambda / 2) * SUM(wi^2)

L1 Regularisation (Lasso):
  J_reg = J + lambda * SUM(|wi|)

Where:
  J       = original binary cross-entropy loss
  lambda  = regularisation strength (hyperparameter)
  wi      = model weights

In civil engineering terms, regularisation embodies the principle of parsimony — prefer the simplest model that adequately explains the data. A heavily regularised model produces more moderate probability estimates, which is often more realistic for engineering applications where absolute certainty is rare.

Assumptions and Limitations

Logistic regression is powerful but not magic. Understanding its assumptions helps you know when to use it and when to reach for more complex models.

1

Linear Decision Boundary

The boundary between classes is a straight line (or hyperplane). If the true boundary is curved — for example, concrete fails at both very low and very high cement content — logistic regression alone cannot capture this. You can mitigate this by adding polynomial features (e.g., x²), but this increases model complexity.

2

Independence of Observations

Each training sample should be independent. Test results from the same concrete batch, the same structure, or the same site may be correlated, violating this assumption. In practice, this is often handled by careful data collection rather than by changing the algorithm.

3

No Severe Multicollinearity

Features should not be highly correlated with each other. If cement content and water content are nearly perfectly correlated (because W/C ratio is fixed), the model cannot reliably determine individual feature effects. Feature engineering and domain knowledge help identify and resolve such issues.

4

Sufficient Sample Size

As a rule of thumb, logistic regression needs at least 10-20 observations per feature, and at least 10 events (positive cases) per feature. In civil engineering, where data collection is expensive, this can be a significant constraint. Start with few, carefully chosen features rather than throwing everything into the model.

When to Use Logistic Regression

Logistic regression is an excellent choice when:

  • You need interpretable results (coefficient meanings)
  • You need calibrated probabilities, not just class labels
  • You have a moderate dataset (not too small, not massive)
  • The classes are approximately linearly separable
  • You need to explain the model to regulators or stakeholders

For complex, non-linear boundaries or large-scale problems, decision trees, random forests, or neural networks may perform better — at the cost of interpretability.

Interactive Demo: Binary Classifier — Threshold vs. Precision/Recall

This demo simulates a logistic regression model predicting whether concrete test cylinders pass or fail based on two features. A scatter plot shows the data points coloured by their true class. The decision boundary (dashed line) separates the predicted "pass" and "fail" regions.

Use the threshold slider to change the classification cut-off. Watch how precision, recall, and the F1-score change as you slide the threshold. Notice the trade-off: lowering the threshold catches more failures (higher recall) but also flags more passing samples as failures (lower precision).

Threshold Tuning: Precision-Recall Trade-off

Slide the threshold to see how the classification and metrics change in real time. The scatter plot shows true class colours; the shaded regions show the model's predicted zones.

Accuracy: — Precision: — Recall: — F1-Score: —

Logistic Regression vs. Other Classifiers

How does logistic regression compare to the other classification methods you will encounter in this chapter? Here is a concise comparison to orient your thinking:

Classifier Comparison
Algorithm           | Boundary | Probabilities | Interpretability | Speed
--------------------|----------|---------------|------------------|-------
Logistic Regression | Linear   | Calibrated    | High             | Fast
k-NN                | Non-lin  | Approximate   | Moderate         | Slow*
Decision Tree       | Non-lin  | Crude          | Very High        | Fast
Random Forest       | Non-lin  | Good          | Moderate         | Medium
Neural Network      | Non-lin  | Varies        | Low              | Slow

* k-NN is slow at prediction time (must search all training data)

Logistic regression's key advantages are its calibrated probabilities and interpretability. When you need to explain to a regulatory body why the model flagged a structure as at-risk, logistic regression's coefficients provide a clear, auditable answer. For many civil engineering applications, this transparency is not just nice to have — it is a regulatory requirement.

Practical Workflow for CE Applications

Here is a step-by-step workflow for applying logistic regression to a civil engineering classification problem:

1

Define the Problem

Clearly state the binary (or multi-class) outcome you want to predict. Examples: "Will this concrete batch fail the 28-day strength test?" "What risk category does this dam fall into?" Ensure the outcome is well-defined and consistently labelled in your data.

2

Collect and Prepare Data

Gather historical records with both features and outcomes. Check for class imbalance (if only 2% of samples are "fail," you may need resampling techniques). Standardise features so that coefficients are comparable across different scales.

3

Train and Validate

Split data into training and test sets. Fit the logistic regression model. Evaluate using the confusion matrix, precision, recall, and the ROC-AUC score. Use cross-validation for more robust estimates.

4

Set the Threshold

Choose the probability threshold based on the application's cost structure. Safety-critical applications demand low thresholds (high recall). Cost-sensitive applications may tolerate higher thresholds (higher precision). Plot the precision-recall curve to visualise the trade-off.

5

Interpret and Deploy

Examine the learned coefficients to verify they align with engineering domain knowledge. A positive weight for load intensity and a negative weight for reinforcement ratio (in a failure prediction model) make physical sense. Flag any counter-intuitive coefficients for further investigation before deploying the model.

Common Mistakes to Avoid

Mistake 1: Ignoring Class Imbalance

In many CE datasets, failures are rare (perhaps 3-5% of samples). If you train logistic regression on imbalanced data without adjustment, the model learns to predict "pass" for everything and achieves 95%+ accuracy while catching zero failures. Use class weighting, SMOTE, or stratified sampling to address this.

Mistake 2: Using the Default Threshold Blindly

The 0.5 threshold is a mathematical default, not an engineering recommendation. In safety-critical applications, it is almost always too high. Always perform a threshold analysis and choose based on the application's cost structure, not convenience.

Mistake 3: Treating Probabilities as Exact

When the model says P(failure) = 0.72, it does not mean there is a 72.0% chance of failure with three significant figures of precision. Model probabilities are estimates with their own uncertainty. Report ranges or confidence intervals, and always combine model outputs with engineering judgement.

Mistake 4: Extrapolating Beyond Training Data

If your model was trained on concrete strengths from 20 to 60 MPa, do not use it to predict failure probabilities for ultra-high- performance concrete at 150 MPa. Logistic regression (like any ML model) is unreliable outside the range of its training data. Always verify that new inputs fall within the training distribution.

CE Applications: Logistic Regression in Practice

Logistic regression excels at binary yes/no predictions with probability outputs — exactly what engineers need for safety and risk assessment decisions.

Geotechnical Applications

  • Slope failure probability — P(failure) from slope angle, soil cohesion, pore pressure ratio, and rainfall intensity. The sigmoid output gives probability of failure, not just safe/unsafe.
  • Liquefaction triggering — P(liquefaction) from CSR, CRR, fines content, D50. Logistic regression reproduces the Boulanger-Idriss (2014) triggering curves.
  • Retaining wall distress — P(excessive displacement) from wall height, backfill angle, surcharge, drainage condition. Binary outcome: within/exceeding serviceability limits.

Water Resources Applications

  • Flood occurrence prediction — P(flood) from cumulative rainfall, antecedent moisture, river level, and upstream dam releases. Threshold at P = 0.3 for early warnings.
  • Dam overtopping risk — P(overtop) from inflow hydrograph, reservoir level, spillway capacity, and storm duration. Critical for emergency action plans.
  • Pipe burst prediction — P(burst) from pipe age, material, pressure, soil movement, and temperature differential. Enables preventive maintenance scheduling.
  • Groundwater contamination — P(contaminated) from distance to source, aquifer transmissivity, soil type, and depth to water table.
Why Probability Matters

Unlike other classifiers that output just a label, logistic regression gives a probability. A slope with P(failure) = 0.72 needs urgent intervention; one with P = 0.15 can be monitored. This maps directly to engineering risk assessment frameworks (IS 14680, FEMA P-1000).

Try it interactively

Tune the decision threshold of a logistic classifier

Drag the threshold slider and watch the confusion matrix, precision, recall, F1 and the dot on the ROC curve move in lockstep — exactly the trade-off a logistic regression forces you to make.

Open Metrics

Knowledge Check

Test your understanding of logistic regression. Each question reinforces a key concept from this sub-chapter.

Quick Check 1

Why does logistic regression use the sigmoid function instead of directly outputting the linear combination z = w*x + b?

Quick Check 2

A dam safety model predicts P(critical) = 0.18 for a particular embankment dam. A safety engineer decides to set the alert threshold at 0.10 for "critical" risk. What happens compared to a threshold of 0.50?

Quick Check 3

Binary cross-entropy penalises confident wrong predictions more heavily than uncertain wrong predictions. Why is this property useful for engineering applications?

Quick Check 4

A soil classification model needs to assign each sample to one of four categories: Clay, Silt, Sand, or Gravel. Which function should replace the sigmoid in the logistic regression model?

Key Takeaways

  • Logistic regression wraps a linear model in the sigmoid function to produce calibrated probabilities in [0, 1]. It is the simplest probabilistic classifier and the foundation for understanding more complex models.
  • The sigmoid function maps any real number to a probability. Its S-shape provides smooth, monotonic, bounded output with a natural midpoint at 0.5.
  • Log-odds (logit) are linear in the features. Each coefficient tells you how much a one-unit change in a feature shifts the log-odds, making the model fully interpretable.
  • The probability threshold controls the precision-recall trade-off. Safety-critical CE applications should use low thresholds to maximise recall, even at the cost of more false alarms.
  • Binary cross-entropy is the loss function that trains the model. It penalises confident wrong predictions disproportionately, mirroring the escalating cost of engineering errors.
  • The softmax function extends logistic regression to multi-class problems like dam safety risk classification, outputting a full probability distribution across all categories.
What Comes Next

In the next sub-chapter, we will explore Decision Trees — a fundamentally different approach to classification that uses a tree of if-then rules instead of a smooth probability function. Decision trees are highly interpretable, can capture non-linear boundaries without feature engineering, and form the building blocks for powerful ensemble methods like Random Forests and Gradient Boosting. The logistic regression concepts you learned here (probabilities, thresholds, loss functions) will help you compare and contrast these approaches.

Real-world case study · Logistic regression in operational warnings

USGS post-fire debris-flow model — a single logistic equation that triggers National Weather Service warnings

After every major wildfire, the USGS runs a logistic-regression debris-flow model (Staley et al. 2017) on the burn scar. The resulting probability maps tell NWS forecasters which 15-minute rainfall intensity will set off a debris flow — and drive the Flash Flood Warnings that evacuate the canyon below.

0Training basins
0Input variables
0Rainfall window
0Montecito 2018 — model issued warnings

A wildfire strips vegetation and bakes a hydrophobic crust into the soil. The next intense rain can mobilise the burn scar as a debris flow within minutes — sweeping vehicles and houses downcanyon (Montecito, CA, January 2018: 23 dead).

  • USGS needs to publish, basin-by-basin, the rainfall intensity-duration threshold that triggers a flow.
  • NWS needs that threshold so its rain-gauge / radar data can issue a Flash Flood Warning before, not after.
  • The model must be fast, transparent, and runnable for any new fire within days.

Staley et al. fit logistic regression to 1,100+ basins from 14 historical fires — each basin labelled "produced a debris flow" or "did not" for a given storm.

  • Features (just three!): 15-min peak rainfall intensity I15, proportion of basin burned at high/moderate severity %B, average soil dry-ravel R.
  • Model: logit(P) = β0 + β1·I15 + β2·%B + β3·R
  • Output: probability of debris flow given the storm; inverted to give the I15 threshold at P = 0.5.
  • Deployment: within days of a new fire, USGS publishes a basin map with rainfall thresholds, handed to the local NWS office.

Three predictors, one sigmoid, one nation-wide warning system — the textbook case for keeping it simple.

The Staley 2017 model has been deployed after essentially every major Western US wildfire since publication, including the Thomas Fire (CA, 2017), the East Troublesome (CO, 2020), and the Hermits Peak / Calf Canyon (NM, 2022).

  • NWS issued Flash Flood Warnings for Montecito based on these thresholds in January 2018 — the warnings were correct; many residents chose not to evacuate.
  • Now embedded in NOAA's National Water Center post-fire workflow.
  • USGS interactive maps (Post-Fire Debris-Flow Hazard Assessments) are linked from county emergency-management pages within a week of containment.
  • Operational beats clever. The model could be more accurate with deep nets, but logistic regression is fast enough, transparent enough, and good enough to drive life-safety decisions.
  • Feature parsimony wins. Three predictors mean the model still works at sites with sparse soil data.
  • The hard problem isn't the model — it's getting people to evacuate when the warning fires.