Random forests and diversity
A forest is strong when its trees are individually useful and collectively disagree in the right ways.
A marketplace must catch rare fraud without blocking trustworthy sellers.
This chapter moves from create varied learners to check the diversity dividend. We will make the idea concrete in a small code example before placing it back inside a production system with reviewer capacity plus false-decline cost.
Plot held-out error and latency versus tree count, and inspect whether individual predictions remain highly correlated.
Verify the behavior illustrated in tiny_forest.py, then measure decision utility, slice reliability, and system latency.
High-cardinality IDs and random row splitting produce spectacular leakage that XGBoost exploits. An unsafe release must degrade to a named baseline or the last known-good version.
Build the idea one layer at a time.
A random forest gains stability by averaging trees that make different mistakes. More trees help only when there is useful diversity to average.
Bootstrap sampling changes the rows each tree sees, while random feature subsets change which questions it may ask. Averaging these decorrelated estimates mainly reduces variance without requiring one fragile tree to represent the whole boundary.
Deep trees can be reasonable inside a forest, but leakage remains leakage and correlated trees limit the benefit. Measure out-of-bag or held-out quality, prediction disagreement, memory, and batch-one latency as tree count grows.
- bagging
- feature subsampling
- pseudo-residuals
- second-order boosting
Follow the reasoning before touching the code.
- 01
Create varied learners
Sample training rows with replacement and expose a random subset of eligible features at each split.
- 02
Aggregate in probability space
Average class probabilities or regression outputs; do not let arbitrary tree order affect the result.
- 03
Check the diversity dividend
Plot held-out error and latency versus tree count, and inspect whether individual predictions remain highly correlated.
from random import Random
rows = [([1, 8], 0), ([2, 7], 0), ([7, 2], 1), ([8, 1], 1)]
rng = Random(7)
def fit_stump(sample, feature):
threshold = sum(row[0][feature] for row in sample) / len(sample)
left = [row[1] for row in sample if row[0][feature] <= threshold]
right = [row[1] for row in sample if row[0][feature] > threshold]
rate = lambda labels: (sum(labels) + 1) / (len(labels) + 2)
return feature, threshold, rate(left), rate(right)
trees = []
for _ in range(7):
bootstrap = [rng.choice(rows) for _ in rows]
trees.append(fit_stump(bootstrap, rng.randrange(2)))
query = [6, 3]
probabilities = [left if query[feature] <= threshold else right
for feature, threshold, left, right in trees]
print("tree votes", probabilities)
print("forest probability", sum(probabilities) / len(probabilities))Build bootstrapped, feature-randomized stumps and average them.
What to notice
- A fixed random seed makes the teaching forest replayable while bootstrap rows and selected features still vary by tree.
- The list of tree probabilities exposes disagreement that the final average would otherwise hide.
YOUR TURN Pause and predict before revealing the answer.
If every tree sees every row and always chooses the same strongest feature, what happens to the forest’s variance-reduction benefit?
Need a hint?
Averaging identical errors does not cancel them.
Check your reasoning
The trees become highly correlated or identical, so averaging adds little beyond one tree; row and feature randomness create the useful diversity.
Lessons 1 in this course.
Connect the chapter to the course’s quantitative spine.
A forest is strong when its trees are individually useful and collectively disagree in the right ways. The stage-wise boosting update below is the shared course-level lens that helps quantify the surrounding system. Name each symbol, check its units or shape, and use only values that were available at the production cutoff.
Stage-wise boosting update
| Symbol | Meaning / shape / unit |
|---|---|
F_m | ensemble after stage m |
h_m | new weak learner |
η | learning rate |
Open derivation and numerical substitution
Start from the production quantity being optimized, substitute the observed values with their declared units, then isolate the model-controlled term. Preserve shape annotations at each step so broadcasting or aggregation cannot silently change the result.
- Write the named inputs: F_m, h_m, η.
- Substitute one small, hand-checkable batch before vectorizing.
- Calculate an independent reference value and compare within a declared tolerance.
# equation → code contract
inputs = validate_shapes_and_units(batch)
value = compute_c05(inputs)
assert is_finite(value)Change one assumption and make the tradeoff visible.
Use the worked chapter as your prediction, then change one input in the lab and explain why the output moves. The lab runs predefined TypeScript and never executes learner code, so the focus stays on the concept rather than setup.
Tree capacity lab
Grow depth and compare training fit with estimated temporal generalization.
Assumption: Estimate calibrated to a small, imbalanced synthetic tabular dataset.
Open nonvisual data table
| Item | Computed state | Interpretation |
|---|---|---|
| fold 1 | 70.3% | stable |
| fold 2 | 69.6% | stable |
| fold 3 | 68.9% | stable |
| fold 4 | 68.2% | stable |
| fold 5 | 67.5% | stable |
Trace the complete operating path.
Carry the chapter’s central idea into the system: A forest is strong when its trees are individually useful and collectively disagree in the right ways. The path below shows where that reasoning needs an artifact, a test, an owner, or a fallback.
- 01
Turn “Create varied learners” into a written invariant and a failing test.
- 02
Promote tiny_forest.py from illustration to a versioned implementation with representative fixtures.
- 03
Use “Check the diversity dividend” as the release checkpoint: Plot held-out error and latency versus tree count, and inspect whether individual predictions remain highly correlated.
- 04
Serve or materialize behind explicit reviewer capacity plus false-decline cost.
- 05
Join telemetry to mature outcomes and retain a rollback path.
Observability
Join service health, input quality, prediction distributions, slice behavior, and mature outcomes by exact version.
Cost
Measure storage, preprocessing, compute, queueing, and human review under a representative arrival pattern.
Failure modes
High-cardinality IDs and random row splitting produce spectacular leakage that XGBoost exploits. Add a detector, owner, mitigation, and stop condition for this class of failure.
Alternatives
Compare a rule, a simpler statistical baseline, and a different system boundary before adding model complexity.
Explain the contract, not just the vocabulary.
Rare-fraud ensemble decision system
Compare a tree, forest, gradient boosting, and XGBoost with temporal validation and operational thresholding.
- Ensemble ablations
- Cost and capacity analysis
- Calibration and explanations
- Latency/fallback plan
Read primary material with a purpose.
Return to the opening failure.
Version missing-value behavior and model format; monitor calibration, explanations, latency, and reviewer yield.
For this lesson, the release evidence is the worked code example, a hand-checked formal result, deterministic simulation output, a ≥80% checkpoint, the production rubric, and a named fallback. The course resolves when the system can produce calibrated random-forest and xgboost baselines with cost-sensitive thresholds.