2.6.16 · D3Model Evaluation & Selection

Worked examples — Ensemble methods (voting, stacking, blending)

3,553 words16 min readBack to topic

This is a worked-examples companion to the parent note. There we built the why; here we grind through every kind of number an ensemble question can throw at you. The rule of this page: you forecast the answer first, then we compute, then we verify by plugging back.

Before we compute anything, one reminder of the words we will use (each is a promise the parent note made — here we cash it in with numbers):


The scenario matrix

Every ensemble arithmetic problem is one of these cells. The worked examples below are tagged with the cell they cover so you can see nothing is skipped.

Cell What makes it tricky Covered by
A. Clear majority odd number of voters, one class wins outright Example 1
B. Tie / even voters 2-vs-2 hard vote → no winner, tie-break needed Example 2
C. Hard vs soft disagree majority says one thing, confidence says another Example 3
D. Weighted vote models are not equally trusted Example 4
E. Variance formula how much does averaging models actually help? Example 5
F. Correlated models (degenerate) errors not independent — the formula's limit Example 6
G. Multi-class 3+ classes, soft vote picks the top average Example 7
H. Stacking / meta-weights out-of-fold predictions feed a weighted meta-model Example 8
I. Real-world word problem medical triage, cost of a wrong call Example 9
J. Exam twist "how many models to beat 95%?" — solve for Example 10

Example 1 — Cell A: a clear majority

Forecast: Count the hands before reading on — three of one, two of the other. Which wins?

  1. List the votes and tally them. Spam appears 3 times, Not-Spam appears 2 times. Why this step? Hard voting is literally the mode (most frequent value) — no probabilities involved, so counting is the entire computation.
  2. Take the majority. , so the ensemble says Spam. Why this step? With an odd number of voters and two classes, a tie is impossible — the mode is always unique.

Verify: voters accounted for, and backed Spam. Majority means share ; ✓.


Example 2 — Cell B: an even vote → a tie

Forecast: Two each. Can hard voting even answer?

  1. Tally. Spam = 2, Not-Spam = 2. Why this step? Even voter counts allow exact ties; you must check for this before declaring a winner.
  2. Recognise the failure. is undefined — there is no single most-frequent class. Why this step? The naive "majority wins" rule silently breaks here, exactly like the formula breaking across quadrants — you cannot let the reader hit this unwarned.
  3. Apply a tie-break rule — but choose it by what your models expose.
    • If every model outputs a probability, fall back to soft voting (average the probabilities — a real number rarely ties exactly). Preferred whenever available, because it uses real information.
    • If some models are label-only (e.g. a plain SVM, a rule-based classifier, or any model without calibrated probabilities), soft voting is impossible — you have no numbers to average. Then break the tie by prior class frequency: predict whichever class is more common in the training data, since that is the safer base rate.
    • If even priors are unavailable or equal, use a fixed deterministic rule — lowest label index / alphabetical order (this is scikit-learn's default). It is arbitrary but reproducible, which matters for testing. Why this ordering? Prefer the rule that uses the most information you actually have; only drop to arbitrary label order as a last resort.

Verify: confirms the tie. Note the cure: whichever applicable rule you pick produces a deterministic answer, so the ensemble never returns "no prediction." Sanity check on the soft-vote fallback — if the four values were , then Not-Spam, tie broken.


Example 3 — Cell C: hard and soft disagree

Forecast: Hard voting counts who crossed 0.5. Soft voting averages the raw numbers. Guess whether they agree.

  1. Hard vote: threshold each at 0.5. Spam, Not-Spam, Not-Spam. Tally: Spam 1, Not-Spam 2 → Not-Spam. Why this step? Hard voting throws away magnitude — it only asks "which side of 0.5?" So the confident counts the same as a barely-over would.
  2. Soft vote: average the probabilities into . Since Spam. Why this step? Soft voting keeps the magnitude; one very confident correct model can outvote two lukewarm dissenters. Look at the figure below — the tall lavender bar drags the average across the line.

Figure — Ensemble methods (voting, stacking, blending)
Figure 1 — Three probability bars (lavender, coral, mint) for one email. The dashed line is the 0.5 threshold; the solid butter line is the soft-vote average . Even though two of the three bars sit below 0.5 (so hard voting says Not-Spam), the tall 0.90 bar pulls the average above the line, so soft voting says Spam.

Verify: Recompute the mean: , ✓. The disagreement is real and instructive: hard voting = 2-vs-1 for Not-Spam; soft voting = Spam. This is exactly why soft voting usually wins when probabilities are well-calibrated — it uses the extra information hard voting discards. See 2.6.8-Bias-variance-tradeoff for why that extra information reduces variance.


Example 4 — Cell D: weighted voting

Forecast: The strong model (0.95) says a mild Spam; two weak models say Not-Spam. Whom does the weighting favour?

  1. Compute the weighted numerator. Why this step? Equal weights would treat the 60%-accurate model as trustworthy as the 95%-accurate one — the parent note's [!mistake] callout warns against exactly that. Weighting by accuracy fixes it.
  2. Divide by the total weight to get a proper probability (a weighted ). Why this step? Weights must be normalised so the result stays in ; otherwise it isn't a probability.
  3. Threshold. Not-Spam.

Verify: Try unweighted for contrast: , also Not-Spam. Weighting changed the value ( vs ) but not the decision here — a good reminder that weights matter most near the boundary. Numeric check: ✓.


Example 5 — Cell E: how much does averaging help?

Forecast: The parent note derived . Guess the number before dividing.

  1. Apply the variance-reduction formula. Why this step? Averaging independent errors — this is the whole mathematical reason ensembles exist. Standard deviation is the real "spread," so also note vs original .
  2. State the improvement factor. Variance shrank by a factor of ; standard deviation shrank by . Why this step? People quote variance, but you feel error in units of standard deviation — halving it is the headline. This is the same law behind 2.7.2-Random-Forest.

Verify: recovers the single-model variance ✓, and recovers the single-model standard deviation ✓.


Example 6 — Cell F: the degenerate case — correlated models

Forecast: If four models are clones, does averaging help at all? Guess before we build the formula.

  1. Write the ensemble error and expand its variance. The ensemble error is the average error . Its variance expands into two kinds of terms: Why this step? When errors are not independent, the cross-terms no longer vanish — that is the whole difference from the parent note's derivation. We must keep them.
  2. Count and substitute each kind of term. There are diagonal terms, each . There are off-diagonal pairs, each , where (read "rho") is the correlation — a number from 0 (unrelated errors) to 1 (identical errors). So: Why this step? The first term is the old "averaging helps" piece; the new second term is the penalty for models copying each other's mistakes. It is exactly what the parent note's independence assumption hid.
  3. Plug in (independent — the parent note's case). Why this step? It must reproduce Example 5 — a formula that doesn't collapse to the known case would be wrong.
  4. Plug in (perfectly correlated — the degenerate limit). Why this step? This is the crucial limiting behaviour: identical models give zero improvement. Averaging clones changes nothing.
  5. Read the moral. Ensembles buy accuracy from diversity, not from headcount. This is why we use different algorithms, different feature subsets, and 2.6.12-Cross-validation folds — see also 2.5.6-Feature-engineering for creating diverse inputs.

Figure — Ensemble methods (voting, stacking, blending)
Figure 2 — Ensemble variance (lavender curve) as the error correlation slides from 0 to 1, for and . At (independent) the variance is at its lowest, ; at (clones) it climbs back to the single-model dotted line at — no improvement. The mint shaded gap is the accuracy you earn by keeping models diverse.

Verify: At we got = Example 5 ✓. At we got ✓ (no gain). A halfway case : , which lies between and ✓ — monotone in , as physics demands.


Example 7 — Cell G: multi-class

Forecast: No single class dominates every row. Average each column and eyeball the winner.

  1. Average each class column into its own . Why this step? With classes, soft voting averages each class independently — think of parallel binary averages.
  2. Take — the class with the largest average. is largest → predict Dog. Why this step? means "the label where the max occurs," not the max value itself. Note Dog won even though no single model ranked it first — the ensemble found a consensus middle ground.
  3. Handle the edge case: what if two classes tie for the top average? Here Cat and Fox both average — but they lost to Dog, so no problem. Suppose instead two classes had both topped the table at, say, each. Then is ambiguous and you need a rule, exactly as in Example 2:
    • break by highest single-model confidence for either class (a proxy for who is more sure);
    • or by prior class frequency in training;
    • or, as a deterministic last resort, by lowest label index (most libraries return the first max encountered). Why this step? is silently undefined on ties; a reader who never saw this rule would hit an unhandled scenario.

Verify: The three averages must sum to 1 (they are averages of rows that each sum to 1): ✓. Winner Dog at ✓.


Example 8 — Cell H: stacking with a weighted meta-model

Forecast: The meta-model trusts RF most (0.5). Expect an answer pulled toward 270k, plus a 5k nudge.

  1. Form the meta-feature vector . (in thousands). Why this step? In stacking the base predictions are the features the meta-model reads — this is the whole idea.
  2. Compute the weighted sum plus intercept. Why this step? A linear meta-model is just a dot product plus bias — it learns how much to trust each base model, unlike plain averaging which forces equal weight.
  3. Sanity-check the weights. , so ignoring the intercept the output is a weighted average that must land between the smallest (250) and largest (270) base prediction.

Verify: Without the intercept: k, which lies in ✓. Adding k gives k ✓. Contrast plain averaging: k — stacking's k differs precisely because it weights and shifts. So stacking here nudges the estimate up by k relative to naive averaging, reflecting the meta-model's learned trust in RF plus its bias correction. Remember (parent note): those OOF predictions must come from 2.6.12-Cross-validation to avoid leakage.


Example 9 — Cell I: a real-world word problem

Forecast: The average is around . But the threshold moved down to catch more urgent cases. Guess the call.

  1. Average the probabilities into (soft vote). Why this step? Same soft-vote machinery as Example 3 — the medical dressing changes only the threshold, not the averaging.
  2. Compare to the policy threshold , not . flag as URGENT. Why this step? Because a missed emergency is 10× costlier, we lower the bar for raising the alarm — we deliberately accept more false alarms to catch true urgents. This is threshold tuning, closely related to 2.8.5-Regularization's idea of trading one error for another.

Verify: ✓. Notice the answer is robust here: at the strict standard threshold the patient is still urgent (), and only a very cautious threshold above would flip it. To see the cost logic pay off, imagine a borderline patient with : at the standard they would be sent home (), but the cost-aware threshold catches them () — exactly the missed-emergency we were trying to prevent. Units check: probabilities and thresholds are both dimensionless, so the comparison is valid ✓.


Example 10 — Cell J: the exam twist ("solve for ")

Forecast: More voters → higher accuracy (if independent). The parent note claims gives . Guess how many it takes to reach 95%.

  1. Set up "ensemble correct" as "more than half correct." For odd , majority means at least of the models are right. Probability of exactly correct is the binomial with . Why this step? Independent correct/wrong outcomes across models is exactly the binomial setting — the same distribution behind Example 5's variance law.
  2. Compute (the warm-up).
    • Exactly 2 correct:
    • Exactly 3 correct: Why this step? Reproduces the parent note's figure and confirms our binomial machinery before scaling up.
  3. March upward until we cross 95%. Summing for each odd :
    • (just at the line)
    • → first value strictly above 95%. Why this step? We only need to find the smallest that clears the bar, so we walk up in steps of 2 (keeping odd to avoid ties) and stop at the first crossing.

Verify: The warm-up gives , matching Example 10's forecast and the parent note ✓. The accuracies are monotonically increasing in () ✓, exactly as the wisdom-of-crowds intuition demands. Complement check for : wrong = correct , and ✓. So the answer to the twist is models for accuracy to strictly exceed 95% (with landing exactly on 95.0%).


Recall Quick self-test

Even number of hard voters splitting 2-2 gives what? ::: An undefined mode (a tie) — fall back to soft voting if probabilities exist, else prior frequency, else label order. Four identical (perfectly correlated) models reduce variance by what factor? ::: None — ; averaging clones does nothing. In stacking, what plays the role of "features" for the meta-model? ::: The base models' out-of-fold predictions. Why can soft voting disagree with hard voting? ::: Soft voting keeps confidence magnitudes; one very confident model can outweigh several lukewarm dissenters. What does stand for on this page? ::: The average of the models' probabilities for one class. How many independent 70%-accurate models to push majority-vote accuracy above 95%? ::: (odd); sits exactly at 95.0%.