Chapter 2 — Sub-chapter 2.6

Decision Trees & Random Forests

If-then rules are the oldest form of engineering judgement. Decision trees formalise that intuition into a learnable algorithm, and random forests combine hundreds of trees into a robust ensemble that resists overfitting. From choosing the right concrete mix to assessing the structural risk of ageing bridges, these models speak the language of engineering decisions.

45 min read 2 interactive demos 4 quiz questions

Engineering Decisions as a Tree

Every civil engineer is already a decision tree. Consider how you might evaluate whether to use steel or concrete for a structural member: Is the span longer than 12 metres? If yes, is the expected load cyclic? If yes, is the budget above a threshold? Each question splits the problem into branches, and at the end of every path lies a recommendation. A decision tree algorithm does exactly this — but it learns the questions and thresholds from data.

Where logistic regression draws a single smooth boundary through feature space, a decision tree carves the space into axis-aligned rectangles, each mapped to a class or a value. The result is a model that is inherently interpretable: you can print it, trace each prediction, and explain it to a project manager who has never heard the word "algorithm."

But single trees have a critical weakness — they overfit. Give a tree enough depth and it will memorise every quirk in the training data, including noise. Random forests solve this by training many trees on randomly perturbed versions of the data and averaging their votes. The ensemble is more accurate, more stable, and far more trustworthy than any individual tree.

In this sub-chapter, we will cover:

  • How decision trees split data using Gini impurity and information gain
  • Recursive tree construction from root to leaves
  • Pruning strategies to fight overfitting
  • The Random Forest algorithm: bagging, feature randomness, ensemble voting
  • Civil engineering applications: material selection decisions, structural risk assessment
Prerequisites

This sub-chapter builds on Sub-chapter 2.4 (Classification Basics) and 2.5 (Logistic Regression). You should be comfortable with the confusion matrix, precision, recall, and the general idea of fitting a model to training data and evaluating it on unseen data.

What Is a Decision Tree?

A decision tree is a flowchart-like structure where each internal node represents a test on a feature (e.g., "Is compressive strength > 25 MPa?"), each branch represents the outcome of that test, and each leaf node represents a class label (for classification) or a predicted value (for regression).

1

Root Node

The topmost node that considers the entire training dataset. The algorithm picks the feature and threshold that best separate the classes at this point. For example, it might find that the single most informative question is whether the water-cement ratio exceeds 0.50.

2

Internal Nodes

Each internal node applies a binary test to one feature. The data that arrives at this node is split into two subsets: samples that pass the test go left, samples that fail go right. The algorithm repeats the process recursively on each subset.

3

Leaf Nodes

When the algorithm decides to stop splitting — because the node is pure (all samples belong to one class), or a depth limit has been reached, or there are too few samples — it creates a leaf. The leaf stores the majority class (classification) or the mean target value (regression).

A Concrete Mix Design Tree

Imagine a tree that predicts whether a concrete batch will meet its 28-day strength requirement. The root might ask: "Is W/C ratio ≤ 0.45?" If yes, the left branch asks: "Is cement content ≥ 350 kg/m³?" If yes again, the leaf predicts Pass. If not, it checks the curing duration. Each path through the tree corresponds to a combination of mix parameters that the model has learned from historical test results.

The beauty of decision trees lies in their transparency. Unlike logistic regression, which produces a single equation with coefficients that can be hard to interpret for high-dimensional data, a decision tree can be printed as a set of nested if-else statements. Every prediction can be traced through the tree to understand exactly which features drove the outcome.

Splitting Criteria: How Trees Choose Questions

The core challenge in building a decision tree is deciding which feature to split on and at what threshold. The algorithm tries every possible split and picks the one that produces the most "pure" child nodes — nodes where most samples belong to a single class. Purity is measured using one of two standard metrics: Gini impurity or information gain (entropy).

Gini Impurity

The Gini impurity measures the probability that a randomly chosen sample from a node would be misclassified if it were labelled according to the distribution of classes in that node. For a node with K classes:

Gini Impurity
            K
Gini(t) = 1 - SUM  p(k|t)^2
            k=1

Where:
  t      = the node being evaluated
  p(k|t) = proportion of class k samples at node t
  K      = total number of classes

Example (binary classification):
  Node with 80% class A, 20% class B:
  Gini = 1 - (0.80^2 + 0.20^2)
       = 1 - (0.64 + 0.04) = 0.32

  Pure node (100% class A):
  Gini = 1 - (1.00^2) = 0.00  (perfect purity)

Gini impurity ranges from 0 (pure node) to 0.5 (maximum impurity for binary classification, where both classes are equally represented). The algorithm evaluates the weighted average Gini impurity of the two child nodes produced by a split and selects the split that minimises this weighted average.

Information Gain (Entropy)

An alternative measure uses the concept of entropy from information theory. Entropy quantifies the disorder or uncertainty in a node:

Entropy & Information Gain
                K
Entropy(t) = - SUM  p(k|t) * log2( p(k|t) )
                k=1

Information Gain = Entropy(parent) - Weighted_Avg_Entropy(children)

Example (binary classification):
  Parent node: 50% class A, 50% class B
  Entropy = -(0.5 * log2(0.5) + 0.5 * log2(0.5))
          = -(0.5 * (-1) + 0.5 * (-1)) = 1.0  (maximum disorder)

  After split:
    Left child  (90% A, 10% B): Entropy = 0.469
    Right child (20% A, 80% B): Entropy = 0.722

  If left has 60 samples, right has 40:
  Weighted Entropy = (60/100)*0.469 + (40/100)*0.722 = 0.570
  Information Gain = 1.000 - 0.570 = 0.430

The split with the highest information gain is chosen. Both Gini and entropy tend to produce very similar trees in practice. Gini is slightly faster to compute (no logarithm), which is why it is the default in most implementations like scikit-learn.

Civil Engineering Intuition

Think of Gini impurity as asking: "If I randomly grab two test specimens from this batch, how likely is it that they have different outcomes (pass vs. fail)?" A pure batch (all pass or all fail) has zero chance of disagreement — Gini = 0. A 50/50 batch has maximum disagreement — Gini = 0.5. The tree tries to sort specimens into the purest possible batches by asking the right questions.

Tree Construction: The Recursive Algorithm

Decision tree construction follows a simple recursive procedure, often called CART (Classification and Regression Trees):

1

Start with All Data at the Root

The entire training set is placed at the root node. The algorithm computes the impurity of this node using Gini or entropy.

2

Find the Best Split

For every feature and every possible threshold, the algorithm computes the impurity reduction that would result from splitting the data at that point. With N samples and D features, this means evaluating up to N × D candidate splits. The split with the greatest impurity reduction wins.

3

Split and Recurse

The data is divided into two subsets based on the winning split. The algorithm then calls itself recursively on each subset, treating it as a new root node. This continues until a stopping criterion is met.

4

Create a Leaf

When a stopping criterion triggers — the node is pure, or the maximum depth is reached, or the number of samples falls below a minimum — the recursion halts and a leaf is created. The leaf stores the majority class (or class probabilities) for the samples that reached it.

CART Pseudocode
function buildTree(data, depth):
    if isPure(data) or depth >= maxDepth or len(data) < minSamples:
        return createLeaf(majorityClass(data))

    bestFeature, bestThreshold = findBestSplit(data)
    leftData  = data[feature <= threshold]
    rightData = data[feature >  threshold]

    node = createNode(bestFeature, bestThreshold)
    node.left  = buildTree(leftData,  depth + 1)
    node.right = buildTree(rightData, depth + 1)
    return node

The algorithm is greedy — it picks the locally best split at each step without looking ahead. This makes it fast but means it may not find the globally optimal tree. In practice, this greedy strategy works remarkably well, especially when combined with ensemble methods that average over many trees.

Overfitting and Pruning

An unrestricted decision tree will keep splitting until every leaf contains a single sample or a perfectly pure subset. This produces a model that memorises the training data — including noise, outliers, and measurement errors. The tree may achieve 100% training accuracy but perform terribly on new data. This is overfitting.

Overfitting in Civil Engineering Context

Imagine building a decision tree to predict whether a soil sample is suitable for a foundation. If the tree memorises every test result, it might create a rule like "If moisture content = 23.7% and plasticity index = 14.2, then unsuitable." This rule perfectly classifies one training sample but is useless for a new sample with moisture content = 23.8%. The tree has memorised the data rather than learning the underlying pattern.

Pre-Pruning (Early Stopping)

Pre-pruning limits tree growth during construction by imposing constraints:

  • Maximum depth — Stop splitting when the tree reaches a specified depth. A depth of 5 means at most 5 levels of questions. This is the most commonly tuned hyperparameter.
  • Minimum samples per split — Refuse to split a node if it contains fewer than a threshold number of samples (e.g., 20). This prevents the tree from creating specialised rules for tiny subsets.
  • Minimum samples per leaf — Ensure every leaf has at least a certain number of samples. This guarantees that predictions are based on sufficient evidence.
  • Minimum impurity decrease — Only split if the impurity reduction exceeds a threshold. Trivial splits that barely improve purity are rejected.

Post-Pruning (Cost-Complexity Pruning)

Post-pruning grows a full tree first, then trims branches that do not significantly improve validation performance. The standard method is cost-complexity pruning, which adds a penalty proportional to the number of leaves. The total cost is:

Cost-Complexity Pruning
Cost_alpha(T) = Misclassification_cost(T) + alpha * |Leaves(T)|

Where:
  T                       = the pruned tree
  Misclassification_cost  = fraction of misclassified training samples
  alpha                   = complexity parameter (tuned via cross-validation)
  |Leaves(T)|             = number of leaf nodes

A larger alpha favours simpler trees with fewer leaves.
A smaller alpha allows more complex trees.

By varying alpha and evaluating on validation data, the engineer can find the sweet spot between a tree that is too simple (underfitting) and one that is too complex (overfitting). This is analogous to choosing the right level of detail in a finite element mesh — too coarse and you miss critical stress concentrations, too fine and you waste computation on noise.

Decision Boundaries: Rectangles, Not Lines

One of the most important differences between decision trees and linear models (like logistic regression) is the shape of the decision boundary. Logistic regression draws a single straight line (or hyperplane) through feature space. A decision tree, by contrast, creates axis-aligned rectangular regions.

Each split in the tree corresponds to a horizontal or vertical cut in the feature plane. After several splits, the feature space is partitioned into a grid of rectangles, each assigned to a class. This has several implications:

  • Non-linear boundaries — Trees can capture complex, non-linear patterns without feature engineering. A staircase boundary that would require polynomial features in logistic regression emerges naturally from a sequence of splits.
  • Axis-aligned constraint — Trees can only make cuts parallel to the feature axes. A diagonal boundary requires many small staircase steps, which can make the tree unnecessarily deep.
  • Interpretability — Each rectangle maps to a specific combination of feature ranges. You can read off the conditions directly: "W/C ≤ 0.45 AND curing days ≥ 14 implies Pass."

Engineering Analogy: Zoning Regulations

Think of the decision boundary as a zoning map for a city. Each zone is a rectangle defined by coordinates (streets), and each zone has a designated use (residential, commercial, industrial). The zones are always aligned with the street grid — you cannot have a diagonal zone. Similarly, a decision tree's regions are always aligned with the feature axes.

Regression Trees

Decision trees are not limited to classification. In a regression tree, each leaf predicts a continuous value (typically the mean of the training samples that reach that leaf). The splitting criterion changes from Gini/entropy to variance reduction:

Regression Splitting Criterion
Variance Reduction = Var(parent) - Weighted_Avg_Var(children)

The split that maximises variance reduction is chosen.
Each leaf predicts the mean of its samples.

For civil engineering, regression trees can predict quantities like deflection, settlement, or compressive strength. However, they produce step-function predictions — every sample in a leaf gets the same value — which can be less smooth than a linear model. Random forests partially address this by averaging many step functions.

Demo 1: Interactive Decision Tree Builder

Build your own decision tree step by step. Add split conditions on two features (W/C Ratio and Curing Days) and watch the tree grow on the canvas. The scatter plot shows how each split partitions the data into regions. Click Auto-Build to let the algorithm construct the optimal tree automatically, or Add Split to choose your own splits.

Feature space partitioning

Tree structure

Depth: 0 Leaves: 1 Accuracy: -- Weighted Gini: --

CE Application: Material Selection Decisions

Material selection is inherently a decision tree problem. Engineers routinely evaluate materials against a hierarchy of criteria: strength requirements, durability constraints, cost limits, environmental exposure, and constructability. A decision tree can formalise this process using historical performance data.

Example: Reinforcement Selection

Consider selecting between carbon steel rebar, epoxy-coated rebar, stainless steel rebar, and fibre-reinforced polymer (FRP) bars for a bridge deck. A decision tree trained on past project data might learn:

  • If chloride exposure is low AND budget is constrained: carbon steel
  • If chloride exposure is moderate AND design life < 50 years: epoxy-coated
  • If chloride exposure is high AND design life ≥ 75 years: stainless steel
  • If magnetic interference is a concern: FRP bars

Each rule is directly traceable to the tree's splits, making it easy to audit and justify the recommendation in a design report.

The key advantage over logistic regression here is multi-class support with interpretability. Logistic regression requires one-vs-rest or softmax extensions for multi-class problems, and interpreting the coefficients becomes harder. A decision tree naturally handles any number of classes and produces human-readable rules.

Feature importance scores from the tree reveal which material properties drive decisions most strongly. If chloride exposure dominates the first few splits, the engineer knows that corrosion resistance is the primary differentiator — a conclusion that aligns with engineering judgement and builds trust in the model.

The Single-Tree Problem

Despite their interpretability, single decision trees have well-known weaknesses that limit their reliability in engineering applications:

  • High variance — Small changes in the training data can produce completely different trees. Remove a few samples and the root split might change, cascading through the entire structure.
  • Overfitting — Deep trees memorise noise. A tree trained on 200 concrete test results might achieve 99% training accuracy but only 72% on new batches.
  • Greedy construction — The locally optimal split at each node may not lead to the globally optimal tree. A slightly suboptimal early split might enable much better splits downstream.
  • Instability — The model lacks confidence estimation. A leaf with 3 samples voting 2-1 for "Pass" looks the same as a leaf with 300 samples voting 200-100.

These problems motivated the development of ensemble methods — algorithms that combine multiple trees to produce a more robust and accurate predictor. The most successful of these is the random forest.

Random Forests: The Power of the Crowd

A random forest is an ensemble of decision trees, each trained on a slightly different version of the data. The final prediction is made by majority vote (classification) or averaging (regression). The two key ingredients that make this work are bagging and feature randomness.

Bootstrap Aggregating (Bagging)

Bagging is the first randomisation technique. For each tree in the forest, a new training set is created by sampling with replacement from the original data. This is called a bootstrap sample. If the original dataset has N samples, each bootstrap sample also has N samples, but some appear multiple times while others are left out (on average, about 37% of the data is excluded from each tree's training set).

Bagging Procedure
Original data: [S1, S2, S3, S4, S5, S6, S7, S8, S9, S10]

Bootstrap sample 1: [S3, S1, S7, S3, S9, S2, S5, S1, S8, S6]  (S4, S10 left out)
Bootstrap sample 2: [S5, S2, S10, S8, S2, S4, S1, S6, S5, S3]  (S7, S9 left out)
Bootstrap sample 3: [S9, S9, S4, S1, S6, S3, S8, S10, S2, S7]  (S5 left out)
...
Bootstrap sample B: [random sample with replacement]

Each tree is trained on a different bootstrap sample.
Prediction = majority vote across all B trees.

The left-out samples (called out-of-bag or OOB samples) serve as a built-in validation set. OOB error is an estimate of the forest's generalisation performance without needing a separate test split.

The Engineering Committee Analogy

Think of a random forest as a committee of structural engineers, each reviewing a project independently. Each engineer sees a slightly different subset of the test reports (bagging), and each focuses on different aspects of the design (feature randomness). When they vote, the committee's collective judgement is far more reliable than any single engineer's opinion. Individual biases and errors cancel out through aggregation.

Feature Randomness: Decorrelating the Trees

Bagging alone is not enough. If one feature is overwhelmingly informative (e.g., W/C ratio for concrete strength), every tree will use it as the root split. The trees will be highly correlated, and averaging correlated predictions does not reduce variance much.

Random forests add a second layer of randomness: at each split, only a random subset of features is considered as candidates. The typical choice is:

Feature Subset Size
Classification: m = sqrt(D)    (D = total number of features)
Regression:     m = D / 3

Example: Dataset with 16 features
  Classification: each split considers sqrt(16) = 4 random features
  Regression: each split considers 16/3 ~ 5 random features

At every split in every tree, a NEW random subset is drawn.

This forces the trees to explore different parts of the feature space. Some trees will find good splits using less obvious features that would be overshadowed in a full-feature search. The resulting trees are more diverse — they make different errors — and their average prediction is more accurate than any individual tree.

The combination of bagging (data randomness) and feature subsampling (feature randomness) is what makes random forests so powerful. Each tree sees the problem from a slightly different angle, and the ensemble captures patterns that no single tree could find alone.

Ensemble Voting and Prediction

Once all trees are trained, making a prediction is straightforward:

1

Pass the Input Through Every Tree

The new sample traverses each tree from root to leaf, following the split conditions. Each tree independently produces a prediction.

2

Aggregate the Votes

For classification, the forest counts how many trees voted for each class. The class with the most votes wins. For regression, the forest averages the predicted values from all trees.

3

Confidence from Vote Proportions

The vote proportions serve as a rough confidence estimate. If 95 out of 100 trees predict "Fail," the forest is highly confident. If the split is 55-45, the prediction is uncertain. This information is invaluable in engineering, where knowing how sure the model is matters as much as the prediction itself.

Ensemble Prediction
Classification:
  Tree 1 -> Pass     Tree 4 -> Pass     Tree 7 -> Pass
  Tree 2 -> Fail     Tree 5 -> Pass     Tree 8 -> Pass
  Tree 3 -> Pass     Tree 6 -> Fail     Tree 9 -> Fail

  Votes: Pass = 6, Fail = 3
  Prediction: Pass (confidence: 6/9 = 66.7%)

Regression:
  Tree 1 -> 32.1 MPa   Tree 4 -> 30.8 MPa   Tree 7 -> 33.2 MPa
  Tree 2 -> 29.5 MPa   Tree 5 -> 31.4 MPa   Tree 8 -> 30.1 MPa
  Tree 3 -> 31.7 MPa   Tree 6 -> 32.5 MPa   Tree 9 -> 29.9 MPa

  Prediction: Average = 31.2 MPa

CE Application: Structural Risk Assessment

Random forests have become popular for structural risk assessment because they handle the complexity of real-world inspection data — mixed feature types, missing values, nonlinear interactions — while providing feature importance rankings that engineers can verify against domain knowledge.

Bridge Condition Rating

A random forest trained on bridge inspection records can predict the condition rating (Good / Fair / Poor / Critical) based on features such as:

  • Age of the structure (years since construction)
  • Average daily traffic (ADT)
  • Deck area and span length
  • Number of previous repairs
  • Climate zone (freeze-thaw cycles per year)
  • Material type (steel, reinforced concrete, prestressed concrete)

Feature importance might reveal that age and freeze-thaw exposure dominate the predictions, aligning with the known mechanisms of concrete deterioration. This agreement between model and domain knowledge builds confidence in the predictions for bridges not yet inspected.

Another advantage for risk assessment is the forest's ability to provide probability calibration. Rather than a hard class label, the vote proportions can be used to rank structures by risk level. A bridge with 82% of trees voting "Poor" requires more urgent attention than one with 55% — even though both receive the same predicted class. This probabilistic ranking enables efficient allocation of limited inspection and repair budgets.

Practical Tip

Random forests handle missing data gracefully. If a particular bridge record is missing the "number of previous repairs" field, the trees that do not use that feature at any split along the path for this sample still produce valid predictions. This robustness is critical for real-world infrastructure databases, which are often incomplete.

Key Hyperparameters

Both decision trees and random forests have hyperparameters that control model complexity. Tuning them correctly is the difference between a model that generalises and one that memorises.

1

n_estimators (Forest Only)

The number of trees in the forest. More trees generally improve performance up to a point of diminishing returns. Typical values range from 100 to 1000. Unlike many hyperparameters, more trees never cause overfitting — they only increase computation time.

2

max_depth

Maximum depth of each tree. Shallow trees (depth 3-5) are more interpretable and less prone to overfitting. Deep trees (depth 15+) can capture complex interactions but may memorise noise. In random forests, individual trees are often grown deep because the ensemble averaging mitigates overfitting.

3

max_features

Number of features considered at each split. Lower values increase tree diversity (lower correlation between trees) but may reduce individual tree accuracy. The defaults — sqrt(D) for classification, D/3 for regression — work well in most cases.

4

min_samples_split / min_samples_leaf

Controls the minimum number of samples required to split a node or to be present in a leaf. Higher values produce simpler trees with fewer, more statistically reliable leaves.

Feature Importance

One of the most valuable outputs of a random forest is the feature importance ranking. For each feature, the importance is computed as the total reduction in impurity (Gini or entropy) across all trees in the forest, weighted by the number of samples reaching each split. Features that appear in early splits of many trees have high importance.

Feature Importance Calculation
For each feature j:
  Importance(j) = SUM over all trees, all nodes where feature j is used:
                    (n_samples_at_node / n_total_samples)
                    * (impurity_before - weighted_impurity_after)

Normalise so all importances sum to 1.

Example output for concrete strength prediction:
  W/C Ratio:       0.38   (most important)
  Cement Content:  0.24
  Curing Days:     0.18
  Aggregate Size:  0.11
  Admixture Type:  0.06
  Ambient Temp:    0.03

For civil engineers, feature importance serves as a sanity check. If the model assigns high importance to a feature that domain knowledge says should not matter (e.g., the lab technician's ID number), it signals a data leakage or confounding variable problem. If the ranking aligns with engineering expectations, it builds trust in the model's predictions.

Demo 2: Random Forest Visualizer

Watch how multiple decision trees vote independently, then see how the ensemble combines their predictions into a final classification. Adjust the number of trees and feature subset size to see how diversity affects ensemble accuracy. Each small tree shows its individual prediction, and the large panel shows the aggregate vote.

Pass votes: -- Fail votes: -- Ensemble: -- Confidence: --

Trees vs. Logistic Regression: When to Use Which

Both decision trees (and their ensembles) and logistic regression are classification workhorses. Choosing between them depends on the problem characteristics:

Favour Trees / Random Forests When:

  • The relationship between features and target is non-linear
  • There are complex feature interactions (e.g., W/C ratio matters differently depending on curing method)
  • You have mixed feature types (numerical and categorical)
  • Missing values are common in the dataset
  • Interpretability of individual rules is needed (single tree) or high accuracy is the priority (random forest)

Favour Logistic Regression When:

  • The relationship is roughly linear in the log-odds
  • You need calibrated probabilities for risk assessment
  • The dataset is small and overfitting is a concern
  • You need to understand the direction and magnitude of each feature's effect
  • Regulatory or contractual requirements demand a transparent model equation

CE Applications: Trees & Forests in Practice

Decision trees and random forests are among the most popular ML algorithms in civil engineering research due to their interpretability and built-in feature importance rankings.

Geotechnical Applications

  • Soil type from CPT data — Decision tree splits on cone resistance qc, sleeve friction fs, and pore pressure u2 to classify Robertson soil behaviour types. Trees naturally handle the SBT chart boundaries.
  • Landslide susceptibility mapping — Random forest with features: slope, aspect, curvature, lithology, land use, distance to faults, rainfall. Feature importance reveals which terrain factors dominate.
  • Ground improvement method selection — Tree decides between vibro-compaction, stone columns, PVD, or grouting based on soil type, depth, target improvement, and budget. Mirrors the engineer's own decision process.

Water Resources Applications

  • Flood susceptibility mapping — Random forest classifies catchment zones as low/medium/high flood risk from DEM elevation, TWI, slope, distance to drainage, land use, and soil group.
  • Water treatment process selection — Decision tree selects treatment train (conventional / direct filtration / membrane / disinfection only) based on source water quality parameters.
  • Reservoir operation rules — Tree-based models learn operating rules from historical releases, inflow, storage, and downstream demand. Feature importance shows which variables drive release decisions.
  • Urban drainage design — Classify pipe sizing decisions from catchment area, imperviousness, slope, and design storm return period.
Feature Importance = Engineering Insight

Random forests rank features by importance. If your landslide model says "slope angle" contributes 35% and "lithology" contributes 28%, that's quantitative confirmation of engineering intuition — and sometimes reveals surprising factors engineers overlooked.

Try it interactively

Train a decision-tree beam-safety classifier in Python

Open the playground and run scikit-learn's DecisionTreeClassifier on a synthetic beam dataset — fit, predict and inspect the splits without leaving the browser.

Open Playground

Knowledge Check

Test your understanding of decision trees and random forests. Each question reinforces a key concept from this sub-chapter.

Quick Check 1

A decision tree node contains 60 samples of class A and 40 samples of class B. What is the Gini impurity of this node?

Quick Check 2

Why do random forests use bootstrap sampling (bagging) instead of training every tree on the full dataset?

Quick Check 3

In a random forest with 100 trees, 73 trees predict "Fair" and 27 trees predict "Poor" for a bridge's condition rating. What is the ensemble prediction and approximate confidence?

Quick Check 4

An unpruned decision tree achieves 99% training accuracy but only 68% test accuracy on a soil classification task. Which technique would most directly address this problem?

Key Takeaways

  • Decision trees partition feature space using axis-aligned splits. They are inherently interpretable and can capture non-linear patterns without feature engineering.
  • Gini impurity and information gain (entropy) are the two standard criteria for choosing splits. Both measure the purity of child nodes after a split.
  • Overfitting is the primary weakness of single trees. Pre-pruning (depth limits, minimum samples) and post-pruning (cost-complexity) are the main defences.
  • Random forests combine bagging (bootstrap sampling) and feature randomness to build an ensemble of diverse, decorrelated trees. The ensemble reduces variance while maintaining low bias.
  • Ensemble voting (majority vote for classification, averaging for regression) produces robust predictions with built-in confidence estimates from vote proportions.
  • In civil engineering, trees and forests excel at material selection (multi-class, interpretable rules) and structural risk assessment (handles missing data, provides feature importance rankings).
What Comes Next

In the next sub-chapter, we will explore Support Vector Machines (SVMs) — algorithms that find the optimal separating hyperplane with the maximum margin between classes. SVMs approach the classification problem from a completely different angle than trees, and understanding both perspectives will deepen your toolkit for engineering applications.

Real-world case study · Random forests for utility asset management

BlueConduit — predicting lead service lines in Flint, Toledo and Newark with a random-forest classifier

After Flint, every US water utility has to find & replace its lead service lines — but most have no idea where they are. BlueConduit trains a random forest on parcel records, build year, soil and prior excavation history to predict which homes have lead pipes, cutting blind digs by an order of magnitude.

0Hit rate (vs ~15% random)
0US lead service lines (EPA est.)
0Cost per blind excavation
0Utilities served

The EPA Lead & Copper Rule Revisions (2021) require every US public water system to inventory its service lines and replace all lead ones. But utility records are notoriously incomplete — in Flint, a third of records turned out to be wrong. Blind excavations cost ~$5,000 per home; a 15% hit rate means ~$33k of digging per actual lead line found.

  • Need to prioritise which parcels to dig first.
  • Features available: parcel record, year built, prior plumbing permits, neighbourhood, soil class, distance to main.
  • Errors are politically loaded — under-predict and you leave families on lead; over-predict and you waste limited federal money.

BlueConduit's flagship model is a random-forest classifier: dozens of decision trees voting on "is this home's service line lead?"

  • Features: build year, parcel value, prior plumbing permits, owner type, neighbourhood, soil corrosivity, distance to main, prior lead-test results from the same block.
  • Label: verified lead vs non-lead from confirmed excavations.
  • Why a forest? Handles mixed numeric/categorical features, missing values, and gives feature-importance maps a utility manager can defend at council.
  • Active learning loop: as crews dig, results are fed back; the model retrains and re-ranks remaining parcels.

Per-parcel predictions → ranked dig list → trucks routed by the model → results fed back. A textbook supervised-learning operations loop.

In Flint, BlueConduit's model raised the hit rate from ~15% (random digging) to 80%+, saving an estimated $10M in excavation costs and accelerating the city's replacement programme. The same approach scaled to:

  • Toledo, OH — full LSL inventory under the LCRR.
  • Newark, NJ — one of the largest US LSL replacement programmes (23,000+ lines).
  • Trenton, NJ; Benton Harbor, MI; and 100+ other systems now in production.
  • Random forests are still a workhorse — explainable feature importance, robust to mixed data, and well understood by regulators.
  • Active learning matters. The model's value compounds as each confirmed dig becomes a new training row.
  • Equity is a modelling decision. Re-weighting to over-sample historically under-served neighbourhoods is now a published methodological norm in this work.