Ask three friends a quiz question. If each is right 70% of the time and they think independently, the majority answer is right more often than any one of them. But if they all learned from the same flawed textbook, they make the same mistakes, and asking all three is no better than asking one. Combining opinions only helps when the opinions fail in different ways.
Voting and stacking apply this to models. Unlike bagging and boosting, which combine many copies of one kind of model, they combine different kinds: a logistic regression, a KNN, an SVM and a random forest, say. Voting averages their answers; stacking trains one more model to learn how much to trust each. Both can add a point or two of accuracy, or, as Spambase shows below, achieve nothing at all.
What you need first: bagging vs boosting, random forest explained, SVM explained, cross-validation and probability calibration.
Key terms
- Base model: one of the models being combined.
- Hard voting: each model votes for a class; the class with most votes wins.
- Soft voting: the models' predicted probabilities are averaged; the class with the highest average wins.
- Stacking: a meta-model is trained on the base models' predictions to make the final prediction.
- Out-of-fold predictions: predictions for each training row made by a model that didn't train on it, used to train the meta-model fairly.
Why voting works: a simulation
Three models, each right 70% of the time. Predict first: how often is the majority right, if their mistakes are independent? And if their mistakes are shared?
import numpy as np
rng = np.random.default_rng(0)
n = 100_000
truth_known = np.ones(n, dtype=bool)
independent = rng.random((3, n)) < 0.7
majority_independent = independent.sum(axis=0) >= 2
shared = rng.random(n) < 0.7
own = rng.random((3, n)) < 0.7
copy_shared = rng.random((3, n)) < 0.8
correlated = np.where(copy_shared, shared, own)
majority_correlated = correlated.sum(axis=0) >= 2
print(f"each model alone: {independent.mean():.3f}")
print(f"majority, independent errors: {majority_independent.mean():.3f}")
print(f"each correlated model alone: {correlated.mean():.3f}")
print(f"majority, correlated errors: {majority_correlated.mean():.3f}")
each model alone: 0.700
majority, independent errors: 0.783
each correlated model alone: 0.698
majority, correlated errors: 0.707
Each row of independent is one model, and each column one question: True where the model is right, with chance 0.7. In the correlated case, each model copies a shared answer 80% of the time and answers on its own otherwise, so the three often fail together. sum(axis=0) >= 2 asks whether at least two of three are right.
With independent mistakes, the majority of three 70% models is right 78.3% of the time: for the vote to be wrong, at least two models must be wrong on the same question, which is less likely than one being wrong. With correlated mistakes, each model is still right about 70% of the time, but the majority manages only 70.7%: when one is wrong, the others usually are too. The models' accuracy is the same in both cases; only the overlap of their mistakes changed.
The data and four different models
Spambase again: 4,601 emails, 57 features. Four models that learn in very different ways:
Download the data: spambase.csv (1.1 MB), or from the original source, the UCI Machine Learning Repository. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with
pd.read_csv("spambase.csv").
from sklearn.datasets import fetch_openml
from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_predict
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier
X, y = fetch_openml(data_id=44, as_frame=False, return_X_y=True)
y = y.astype(int)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, stratify=y, random_state=0)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
base_models = [
("logistic", make_pipeline(StandardScaler(), LogisticRegression(max_iter=2000))),
("knn", make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=15))),
("svm", make_pipeline(StandardScaler(), SVC(probability=True, random_state=0))),
("forest", RandomForestClassifier(n_estimators=300, random_state=0, n_jobs=-1)),
]
oof = {name: cross_val_predict(model, X_train, y_train, cv=cv, method="predict_proba")[:, 1]
for name, model in base_models}
for name, p in oof.items():
print(f"{name:9} cross-validated accuracy {np.mean((p >= 0.5) == y_train):.3f}")
logistic cross-validated accuracy 0.921
knn cross-validated accuracy 0.897
svm cross-validated accuracy 0.928
forest cross-validated accuracy 0.948
SVC(probability=True) makes the SVM produce probabilities, which soft voting needs. cross_val_predict gives every training email an out-of-fold probability from each model, so their mistakes can be compared fairly. This takes a minute or so, mostly for the SVM.
Do they make different mistakes?
import pandas as pd
wrong = pd.DataFrame({name: (p >= 0.5) != y_train for name, p in oof.items()})
print("correlation between the models' mistakes:")
print(wrong.astype(int).corr().round(2))
print(f"emails every model gets wrong: {wrong.all(axis=1).sum()}, at least one gets wrong: {wrong.any(axis=1).sum()}")
correlation between the models' mistakes:
logistic knn svm forest
logistic 1.00 0.62 0.72 0.54
knn 0.62 1.00 0.59 0.41
svm 0.72 0.59 1.00 0.59
forest 0.54 0.41 0.59 1.00
emails every model gets wrong: 91, at least one gets wrong: 461
wrong is True where a model misclassifies an email. .corr() measures how often two models are wrong on the same emails: 1 would mean identical mistakes, 0 unrelated ones.
The mistakes overlap a lot, but not completely. Logistic regression and the SVM are the most alike (0.72), which makes sense: both draw smooth boundaries on scaled features. The forest and KNN are the least alike (0.41). Only 91 emails fool all four models, while 461 fool at least one, so there are about 370 emails where some model is right and another wrong. That's the room an ensemble has to work in.
Voting
Experiment: soft-vote the three models of similar strength (logistic regression, KNN and the SVM), then all four. Predict first: will adding the much stronger forest to the vote help or hurt, compared with the forest alone?
def soft_vote(names):
return np.mean([oof[name] for name in names], axis=0) >= 0.5
for names in [["logistic", "knn", "svm"], ["logistic", "knn", "svm", "forest"]]:
print(f"soft vote of {', '.join(names)}: {np.mean(soft_vote(names) == y_train):.3f}")
print(f"forest alone: {np.mean((oof['forest'] >= 0.5) == y_train):.3f}")
soft vote of logistic, knn, svm: 0.932
soft vote of logistic, knn, svm, forest: 0.937
forest alone: 0.948
The three similar models vote to 0.932, a little above the best of them, the SVM at 0.928: a small gain, as their correlated mistakes would suggest. Adding the forest lifts the vote to 0.937, but that's still clearly below the forest on its own (0.948). With equal weights, three weaker models outvote the forest on emails it gets right. An ensemble isn't automatically better than its best member.
Stacking: let a model learn the weights
Equal votes are a guess. Stacking trains a meta-model on the base models' out-of-fold probabilities, so it learns from data how much to trust each one. StackingClassifier does the bookkeeping: it builds the out-of-fold predictions with internal cross-validation, fits the meta-model on them, and then refits every base model on all the training data.
from sklearn.ensemble import StackingClassifier, VotingClassifier
stack = StackingClassifier(base_models, final_estimator=LogisticRegression(max_iter=2000),
cv=5, n_jobs=-1).fit(X_train, y_train)
weights = stack.final_estimator_.coef_[0]
print("weights learned by the meta-model:", {name: round(float(w), 2) for (name, _), w in zip(base_models, weights)})
vote = VotingClassifier(base_models, voting="soft", n_jobs=-1).fit(X_train, y_train)
forest = dict(base_models)["forest"].fit(X_train, y_train)
for name, model in [("forest alone", forest), ("soft vote, all four", vote), ("stacking", stack)]:
print(f"{name:20} test accuracy {model.score(X_test, y_test):.3f}")
weights learned by the meta-model: {'logistic': 1.53, 'knn': 1.59, 'svm': -0.04, 'forest': 6.4}
forest alone test accuracy 0.959
soft vote, all four test accuracy 0.942
stacking test accuracy 0.955
final_estimator_ is the fitted meta-model, and coef_[0] its weights, one per base model's probability. float(w) turns each NumPy number into a plain Python number so it prints cleanly. dict(base_models) turns the list of name-and-model pairs into a dictionary, so the forest can be picked out by name. n_jobs=-1 trains the base models in parallel.
The meta-model has learned what the vote couldn't: the forest gets a weight of 6.4, about four times that of logistic regression or KNN, and the SVM, nearly a copy of logistic regression's mistakes, gets almost nothing (−0.04). On the test set, stacking (0.955) beats the equal vote (0.942) but still doesn't beat the forest alone (0.959). The difference of 0.004 is 6 emails out of 1,381, within chance, but there's no case here for running four models instead of one. On this data, the honest conclusion is: use the forest.
See it fail: the leak inside stacking
Why train the meta-model on out-of-fold predictions? To see, stack three models, one of which is a memoriser: a 1-nearest-neighbour classifier, which answers with the label of the single most similar training email. On its own training rows it's always right, since each email's nearest neighbour is itself. Train the meta-model first on in-sample predictions, then properly:
trio = [base_models[0], base_models[2],
("1-nn", make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=1)))]
for name, model in trio:
print(f"{name:9} alone: test accuracy {model.fit(X_train, y_train).score(X_test, y_test):.3f}")
in_sample = np.column_stack([model.predict_proba(X_train)[:, 1] for _, model in trio])
test_probs = np.column_stack([model.predict_proba(X_test)[:, 1] for _, model in trio])
leaky_meta = LogisticRegression(max_iter=2000).fit(in_sample, y_train)
proper = StackingClassifier(trio, final_estimator=LogisticRegression(max_iter=2000), cv=5).fit(X_train, y_train)
for label, weights, accuracy in [("in-sample ", leaky_meta.coef_[0], leaky_meta.score(test_probs, y_test)),
("out-of-fold", proper.final_estimator_.coef_[0], proper.score(X_test, y_test))]:
shown = {name: round(float(w), 2) for (name, _), w in zip(trio, weights)}
print(f"meta-model trained {label}: weights {shown}, test accuracy {accuracy:.3f}")
logistic alone: test accuracy 0.926
svm alone: test accuracy 0.936
1-nn alone: test accuracy 0.899
meta-model trained in-sample : weights {'logistic': 1.63, 'svm': 2.02, '1-nn': 8.25}, test accuracy 0.899
meta-model trained out-of-fold: weights {'logistic': 3.64, 'svm': 2.6, '1-nn': 1.59}, test accuracy 0.938
base_models[0] and base_models[2] are the logistic regression and the SVM. np.column_stack puts the three models' probabilities side by side as three columns, the meta-model's input.
On new emails, the 1-NN model is the weakest of the three (0.899). Trained on in-sample predictions, though, the meta-model sees a model that is never wrong, so it gives the 1-NN by far the biggest weight (8.25), and its test accuracy is exactly the 1-NN's own, 0.899. Trained properly on out-of-fold predictions, it sees the 1-NN as it really is, gives it the smallest weight, and reaches 0.938, better than any of the three models alone. This time stacking does help, because the three models are close in strength and differ in their mistakes, and only when it's done properly.
When to use voting or stacking
| Situation | Combine? | Why |
|---|---|---|
| Several models of similar accuracy that make different mistakes | Yes: voting is simple and often helps | Errors cancel |
| One model is clearly best | Probably not; try stacking | Equal votes drag it down; stacking can learn to lean on it |
| Competitions, where 0.1% matters | Yes: stacking | Small, real gains at the cost of complexity |
| A model people must understand or maintain | Usually not | Several models are harder to explain, monitor and serve |
| Models with badly calibrated probabilities | Calibrate first, or use hard voting | Soft voting averages probabilities |
Practice
- Without running code: three models are each 90% accurate, and every mistake one makes, the other two make as well. What is the majority vote's accuracy?
Show the answer
90%. When all three fail on exactly the same emails, the majority is wrong exactly when each model is wrong. Voting adds nothing without disagreement.
- Run the simulation with five independent models, each 70% accurate. How accurate is the majority?
Show the answer
five = rng.random((5, n)) < 0.7
print(round((five.sum(axis=0) >= 3).mean(), 3))
0.838
83.8%, up from 78.3% with three. With independent mistakes, every extra voter helps, which is the idea behind random forests' hundreds of trees. With real models, mistakes are correlated, so the gains are much smaller.
- Hard-vote the three similar models (logistic regression, KNN and SVM) using the out-of-fold probabilities. Is it better or worse than soft voting?
Show the answer
votes = sum((oof[name] >= 0.5).astype(int) for name in ["logistic", "knn", "svm"])
print(round(np.mean((votes >= 2) == y_train), 3))
0.93
Slightly worse: 0.930 against 0.932 for soft voting. Hard voting throws away how sure each model is; soft voting lets a confident model outweigh two unsure ones, which usually helps when the probabilities are reasonably calibrated.
- Why does
StackingClassifierrefit the base models on all the training data after training the meta-model?
Show the answer
The out-of-fold predictions are only needed to train the meta-model fairly. For predicting new data, each base model should be as good as possible, so it's refitted on all the training rows. The meta-model then combines their predictions on new data, which, like the out-of-fold ones, come from models that never saw those rows.
- Why might soft voting go wrong if one model is Naive Bayes?
Show the answer
Naive Bayes's probabilities are extreme (often 0.0 or 1.0), as probability calibration showed. In an average, a confident 1.0 outweighs several modest 0.3s, so the worst-calibrated model gets the loudest voice. Calibrate it first, or use hard voting.
Interview questions
What is the difference between bagging, boosting, voting and stacking?
Bagging and boosting combine many models of one type (bagging trains them independently on resamples; boosting trains them in sequence on the previous errors). Voting and stacking usually combine different model types: voting averages their predictions with fixed weights, stacking trains a meta-model on their out-of-fold predictions.
Why must stacking use out-of-fold predictions?
Base models predict their own training rows too well. A meta-model trained on in-sample predictions learns to trust whichever model overfits most, which fails on new data. Out-of-fold predictions show the meta-model how each base model behaves on unseen rows.
When does an ensemble of models outperform its best member?
When the members are individually good and their errors are not strongly correlated, so mistakes cancel. If one model dominates or all make the same mistakes, an ensemble adds complexity without benefit.
Key takeaways
- Combining models helps only when they're comparably good and make different mistakes.
- Hard voting counts class votes; soft voting averages probabilities and usually does better with calibrated models.
- Adding a weaker model to a vote can drag down a strong one: equal weights are a guess.
- Stacking learns the weights from out-of-fold predictions; training it on in-sample predictions leaks.
- Weigh any gain against the cost of running, explaining and maintaining several models.
Frequently asked questions
Can I weight the votes myself?
Yes: VotingClassifier(..., weights=[1, 1, 1, 3]) gives the fourth model three times the say. Choose the weights by cross-validation, not by looking at the test set, or let stacking learn them.
What meta-model should stacking use?
A simple one: logistic regression for classification, ridge regression for regression. The meta-model has only a few inputs, and a flexible one overfits them easily.
Do Kaggle winners really use stacking?
Often, with several layers and dozens of models, because tiny gains decide rankings. In production, teams usually prefer one well-tuned model, because every extra model must be trained, monitored and served.
What to learn next
- Explain individual predictions in explaining model predictions with SHAP, the next lesson.
- Revisit the other two ensemble methods in bagging vs boosting.
- Revisit why probabilities need checking before averaging in probability calibration.