Single logo
  • Courses
  • Blog
  • About
Join for freeJoin free
Learning pathChoose and Tune a Model: Classic Algorithms to a Saved Pipeline
  1. 1
    K-Nearest Neighbours (KNN): Distance, k and Why Scaling Is a Must
  2. 2
    Naive Bayes: Prior Times Likelihood, a Spam Filter by Hand and GaussianNB
  3. 3
    Support Vector Machines (SVM): The Widest Road, C, Kernels and gamma
  4. 4
    Decision Trees: Gini, max_depth and Feature Importances on Rain in Australia
  5. 5
    Bagging and Random Forest: Many Shaky Trees, One Steady Answer
  6. 6
    Boosting: Residuals by Hand, AdaBoost, Gradient Boosting and XGBoost
  7. 7
    Voting and Stacking: Does a Team of Models Beat the Best One?
  8. 8
    Hyperparameter Tuning with GridSearchCV and RandomizedSearchCV
  9. 9
    Which Features Matter? Feature Importances, Permutation Importance and SHAP
  10. 10
    Project: The Classification Master Template, from Raw CSV to a Saved Model
  1. Blog
  2. /
  3. Machine Learning
  4. /
  5. Supervised Learning

Learning path: Choose and Tune a Model: Classic Algorithms to a Saved Pipeline · Step 7 of 10

Voting and Stacking: Does a Team of Models Beat the Best One?

Three different judges on the rain data: logistic regression 0.846, KNN 0.836, a tree 0.823. Hard and soft voting land in between; stacking reaches 0.848, just four more days right out of 2,000. An honest look at when a team helps.

Chaand Sheikh

·27 November 2026Classic Algorithms

What you will learn

  • Combine different models with hard voting (count answers) and soft voting (average probabilities)
  • Explain how StackingClassifier trains a head model on out-of-fold opinions
  • Read the weights a stacking model learns for each judge
  • Compare an ensemble honestly with the best single model

Before you start

  • Logistic Regression in scikit-learn
  • K-Nearest Neighbours
  • Decision Trees: Gini and max_depth

A talent show has three judges, and each one shows a card: yes or no. Two say yes, one says no, so yes wins. That's voting: the most votes win.

Now another way. A head judge has watched many shows and has learned which judge to trust the most. That's stacking.

One rule for both: the judges must be different. Three copies of the same judge add nothing; they'd make the same mistake three times. Voting counts the answers, stacking learns whom to trust. Then you check, honestly, whether the team really beats its best member.

Three different judges

The same 10,000-day Rain in Australia sample as in the decision tree article, split first.

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import VotingClassifier, StackingClassifier

df = pd.read_csv("weatherAUS.csv").dropna(subset=["RainTomorrow"])
df = df.sample(10_000, random_state=42)
X = df.select_dtypes("number").drop(columns=["RISK_MM"])
y = df["RainTomorrow"]
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, stratify=y, random_state=42)
print(X_train.shape, X_test.shape)
(8000, 16) (2000, 16)

with_prep wraps each model in a pipeline that fills gaps with the median and scales the numbers. The three judges think very differently: logistic regression, KNN with 15 neighbours, and a depth-4 tree.

def with_prep(model):
    return make_pipeline(
        SimpleImputer(strategy="median"),
        StandardScaler(), model)
judges = [
    ("logreg", with_prep(LogisticRegression())),
    ("knn", with_prep(KNeighborsClassifier(15))),
    ("tree", with_prep(DecisionTreeClassifier(
        max_depth=4, random_state=42)))]

for name, m in judges:
    m.fit(X_train, y_train)
    print(name, round(m.score(X_test, y_test), 3))
logreg 0.846
knn 0.836
tree 0.823

The best single judge is logistic regression, 0.846. That's the score the team has to beat.

Three judges, one day

Let's look at the first test day where the judges disagree. For each judge, print its answer and its probability of rain:

votes = pd.DataFrame({n: m.predict(X_test) for n, m in judges})
i = (votes.nunique(axis=1) > 1).to_numpy().argmax()
day = X_test.iloc[[i]]
for name, m in judges:
    answer = m.predict(day)[0]
    p_yes = m.predict_proba(day)[0, 1]
    print(name, answer, round(p_yes, 2))
print("really:", y_test.iloc[i])
logreg No 0.26
knn Yes 0.73
tree Yes 0.7
really: No
answers = [m.predict(day)[0] for _, m in judges]
probs = [m.predict_proba(day)[0, 1] for _, m in judges]
print(answers.count("Yes"), "of 3 say Yes")
print("average", round(sum(probs) / 3, 2))
2 of 3 say Yes
average 0.56
Hard and soft voting on one day logreg: No P(rain) 0.26 knn: Yes P(rain) 0.73 tree: Yes P(rain) 0.70 hard: count answers 2 of 3 Yes: Yes soft: average P 0.56 > 0.5: Yes really: No team wrong On this day, logistic regression alone was right.
The first test day where the judges disagree. Both votes say Yes; it really stayed dry.
  • Hard voting counts the answers: No, Yes, Yes. Two of three say Yes, so the team says Yes.
  • Soft voting averages the probabilities: (0.26 + 0.73 + 0.70) / 3 = 0.56, above one half, so again Yes.

But it didn't rain. On this day the team is wrong, and logistic regression alone was right.

Stacking: a head judge learns the weights

Stacking does it a bit smarter. Each judge gives its probability of rain, and a small model, the final estimator, takes those opinions as its inputs and learns how much to trust each one.

The opinions must be honest. With cv=5, each judge's opinion on a training row comes from a fold that judge did not train on (just like cross-validation). Otherwise the head judge would learn from opinions on rows the judges had already memorised.

hard = VotingClassifier(judges, voting="hard")
soft = VotingClassifier(judges, voting="soft")
stack = StackingClassifier(
    judges, final_estimator=LogisticRegression(),
    cv=5)
team = {"hard": hard, "soft": soft, "stack": stack}
for name, m in team.items():
    m.fit(X_train, y_train)
    print(name, round(m.score(X_test, y_test), 3))
hard 0.84
soft 0.839
stack 0.848

What did the head judge learn? Its coefficients, one per judge:

weights = stack.final_estimator_.coef_[0]
for (name, _), w in zip(judges, weights):
    print(name, round(w, 2))
logreg 3.2
knn 1.89
tree 1.27

It trusts logistic regression the most, the strongest single model. Voting gives every judge the same say; stacking learns it.

Does the team beat the best judge?

Only stacking passes the best single judge, by a hair test accuracy (axis starts at 0.80) tree 0.823 knn 0.836 soft vote 0.839 hard vote 0.840 logreg 0.846 stacking 0.848 best single judge
Hard and soft voting land between the judges. Only stacking passes the best single model (dashed line), and only just. (The bars start at 0.80 so the differences are visible.)

Both votes lose to logistic regression alone. Stacking is ahead, but by a hair. How big is that gain in days?

two = {"logreg": judges[0][1], "stack": stack}
for name, m in two.items():
    right = (m.predict(X_test) == y_test).sum()
    print(name, right, "of", len(y_test))
logreg 1691 of 2000
stack 1695 of 2000

Four more test days right, out of 2,000. An ensemble does not always win. A team helps when its members are good and make different mistakes, and you only know it helped if you compare it with the best single model.

Common mistakes

  • Judges that think alike. Copies of the same kind of model make the same mistakes, and voting can't cancel them.
  • Adding a weak judge to a vote. In hard and soft voting it gets as much say as the best one.
  • Soft voting with poorly calibrated probabilities. Soft voting averages predict_proba, so every judge needs sensible probabilities.
  • Not comparing with the best single model. Here both votes scored below logistic regression alone.

Quick recap

MethodHow it decidesRain test accuracy
Best single judgeLogistic regression0.846
Hard votingCounts the answers0.84
Soft votingAverages the probabilities0.839
StackingA head model learns weights (3.2 / 1.89 / 1.27) on out-of-fold opinions0.848

Try it yourself

Add a RandomForestClassifier(random_state=42) as a fourth judge. Does stacking now beat the forest on its own?

Before this: Boosting.

Built this? Share your solution in the StudyEasy AI Community.

Join free on Skool →
← Previous
Boosting: Residuals by Hand, AdaBoost, Gradient Boosting and XGBoost
Next →
Hyperparameter Tuning with GridSearchCV and RandomizedSearchCV
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool
Go deeper with a course

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)

Related articles
Linear Regression and the Cost Function: Draw a Line, Score It

Draw a straight line through six kids' ages and weights, measure every miss, and turn the misses into one score, the mean squared error. Then let np.polyfit find the line with the lowest score.

Gradient Descent Explained: Feel the Slope, Step Downhill

Instead of handing over the best line, let the computer walk to it: measure the slope of the cost, step downhill with a learning rate, repeat. Shown step by step on six kids' ages and weights.

Linear Regression in scikit-learn: Fit, Predict and Read the Price Tags

Predict a yearly medical bill with scikit-learn's LinearRegression: first from age alone, then from every column inside a pipeline. Each coefficient reads like a price tag, and smoker_yes is by far the biggest.

Regression Metrics: MAE, RMSE, R-squared and the Baseline to Beat

Score a regression model honestly: MAE, MSE and RMSE from four darts, then the insurance model on 268 test people, a DummyRegressor baseline to beat, R-squared and adjusted R-squared, and a residual plot.

On this page
  • Three different judges
  • Three judges, one day
  • Stacking: a head judge learns the weights
  • Does the team beat the best judge?
  • Common mistakes
  • Quick recap
  • Try it yourself
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool
Go deeper with a course

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.