CS 460G Midterm Hub / Notebooks / Ensemble Methods
Python notebook · Copy of Ensemble-Methods.ipynb

Ensemble Methods

Voting, bagging, random forest, AdaBoost, stacking, mixture of experts

practice nbQ6 material

Six ensemble techniques in one notebook, all on the same 426/143 split. It is the only place you see them side by side with numbers.

Setup

breast_db = datasets.load_breast_cancer()
X, y = breast_db['data'], breast_db['target']        # (569, 30)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, stratify=y, random_state=9999)
# (426, 30), (143, 30)

Note the good practice here: stratify=y and random_state=9999. This notebook is better disciplined than the earlier ones.

1. Majority voting

from sklearn.ensemble import VotingClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.neural_network import MLPClassifier

DTree = DecisionTreeClassifier(random_state=0).fit(X_train[:,:2], y_train)
MLP   = MLPClassifier(random_state=0).fit(X_train[:,:2], y_train)
KNN   = KNeighborsClassifier(n_neighbors=3).fit(X_train[:,:2], y_train)

Voting_clf = VotingClassifier(
    estimators=[('DTree',DTree), ('MLP',MLP), ('kNN',KNN)], voting='hard')
Voting_clf.fit(X_train[:,:2], y_train)

Note X_train[:, :2] — only two features, so the decision boundaries can be plotted in a 2×2 panel. This is a visual demonstration, not a performance one; the accuracies here are much lower than the 30-feature models later.

ax = plt.subplot(2,2,1); plot_decision_boundary(DTree, ...)
ax = plt.subplot(2,2,2); plot_decision_boundary(MLP, ...)
ax = plt.subplot(2,2,3); plot_decision_boundary(KNN, ...)
ax = plt.subplot(2,2,4); plot_decision_boundary(Voting_clf, ..., 'Majority Voting')

What the four panels show: the tree's boundary is axis-aligned rectangles; the MLP's is smooth and curved; k-NN's is a jagged Voronoi mosaic; and the voting panel's boundary is a piecewise combination — it follows the tree in some regions and the MLP in others. That composite shape is what "majority voting" looks like geometrically.

voting='hard' means it takes the majority of the predicted labels. voting='soft' would average predict_proba and take the argmax — usually better, because it uses confidence information.

The bug in this section

print('Accuracy (DTree): ', 100*accuracy_score(y_test, DTree.predict(X_test[:,:2])))

→ NameError: name 'accuracy_score' is not defined

What happened: accuracy_score is imported later in the notebook, so this cell fails if run out of order. It is a cell-ordering bug, not a logic bug — but it is a real one, and a good "what is wrong here?" target.

2. Bagging

SVM_Model = SVC(kernel='linear').fit(X_train, y_train)
print('Accuracy (SVM--base): ', ...)

from sklearn.ensemble import BaggingClassifier
SVM_bagging = BaggingClassifier(
    estimator=SVC(kernel='linear'), n_estimators=20, random_state=0
).fit(X_train, y_train)
print('Accuracy (SVM--Bagging): ', ...)

The comparison being made: the same learner, once alone and once as 20 bootstrap copies. n_estimators=20 means 20 bootstrap samples of the 426 training rows.

What to say: bagging a linear SVM gains little, because a linear SVM is already low-variance — there is not much to average away. Bagging pays off for high-variance, low-bias learners, which is why random forests bag deep trees, not linear models. That single sentence is the answer to "when does bagging help?"

3. Random forest

DTree = DecisionTreeClassifier(random_state=0).fit(X_train, y_train)
print('Accuracy (Decision Tree--base model): ', ...)

from sklearn.ensemble import RandomForestClassifier
RF = RandomForestClassifier(max_depth=5, random_state=0).fit(X_train, y_train)
print('Accuracy (Random Forests): ', ...)

max_depth=5 — this is the regularisation that makes the comparison fair. Without it the single tree would overfit and the forest would look artificially good.

from sklearn.tree import plot_tree
plt.figure(figsize=(30,20))
plot_tree(RF.estimators_[0], feature_names=breast_db['feature_names'])

RF.estimators_[0] is one tree from the forest. Plotting it shows that a random forest is literally a collection of decision trees that you can inspect individually — and that each one is shallow (depth ≤ 5) and uses a random feature subset.

4. AdaBoost

from sklearn.ensemble import AdaBoostClassifier
AdaB = AdaBoostClassifier(n_estimators=100, random_state=0).fit(X_train, y_train)
y_adb = AdaB.predict(X_test)
print('Accuracy (AdaBoost): ', ...)

100 sequential stumps. Each one is trained on re-weighted samples: the previous round's mistakes get higher weight. That is the wnm+1 = wnm·exp(−½ t α y) rule from the lecture, hidden behind one constructor.

Worth noting: AdaBoostClassifier in modern scikit-learn defaults to algorithm='SAMME' rather than the original discrete AdaBoost — the maths in the lecture is the original formulation.

5. Stacking — the section with the real lesson

from mlxtend.classifier import StackingClassifier

clf1 = KNeighborsClassifier(n_neighbors=1)
clf2 = DecisionTreeClassifier()
clf3 = SVC(kernel='linear')
lr   = LogisticRegression()

sclf = StackingClassifier(classifiers=[clf1,clf2,clf3], meta_classifier=lr)

for clf, label in zip([clf1,clf2,clf3,sclf], ['KNN','Decision Tree','SVM','StackingClassifier']):
    scores = model_selection.cross_val_score(clf, X_train[:,2:4], y_train, cv=5, scoring='accuracy')
    print("Accuracy: %0.2f (+/- %0.2f) [%s]" % (scores.mean(), scores.std(), label))

Output:

KNN                 0.86 (+/- 0.03)
Decision Tree       0.87 (+/- 0.04)
SVM                 0.89 (+/- 0.04)
StackingClassifier  0.88 (+/- 0.03)

The stack did not beat the best base model (0.88 vs 0.89). Why is that not a failure of stacking? Stacking only helps when the base models are individually strong and make different errors. Here the models are evaluated on two features (X_train[:,2:4]) and share the same 426 training rows, so they are highly correlated — the diversity term in the ensemble argument is missing. Averaging correlated predictors cannot remove the correlated part of their error. The same reasoning explains why the binomial formula over-estimates the benefit in practice: it assumes independence between members. On 2 features the models also have little to disagree about, so there is nothing for the meta-classifier to exploit.

Also note the ±0.03–0.04 standard deviations — a 0.01 difference between the stack and the SVM is well inside the noise. Reporting "SVM wins" would be over-reading a single CV run.

The second bug

clf.fit(X, y)                       # fitted on ALL 30 features
fig = plot_decision_regions(X=X_train[:,2:4], y=y_train, clf=clf)   # plotted on 2

→ ValueError: X has 2 features, but KNeighborsClassifier is expecting 30 features as input.

What happened: clf1 was re-fitted on the full X (30 features) inside the loop, then asked to plot a 2-feature decision region. That is a real shape-contract violation, and it is the kind of thing an examiner asks you to spot: scikit-learn estimators remember n_features_in_ and refuse mismatched input rather than silently mispredicting.

6. Mixture of experts — implemented by hand

n_experts = 5
experts = []
for i in range(n_experts):
    expert = SVC(kernel='linear', probability=True)
    indices = np.random.choice(len(X_train), size=int(0.8*len(X_train)), replace=False)
    expert.fit(X_train[indices], y_train[indices])
    experts.append(expert)

Five SVMs, each on a random 80% subsample. probability=True is required because the gate needs predict_proba.

expert_predictions = np.array([expert.predict_proba(X_test)[:,1] for expert in experts])

def softmax(x):
    return np.exp(x) / np.sum(np.exp(x), axis=0)

weights = softmax(expert_predictions)
pred = np.sum(weights * expert_predictions, axis=0)
y_mexp = np.where(pred > 0.5, 1, 0)

This is the gate, implemented literally. expert_predictions is (5, n_test); softmax along axis=0 normalises across experts for each test point, producing the gating weights $g_m(x)$; then sum(weights * predictions) is exactly $y(x)=\sum_m g_m(x)y_m(x)$.

This is not a real mixture of experts. A true MoE learns the gate $z_m(x)$ as a function of the input, trained jointly with the experts. Here the "gate" is a softmax over the experts' own predictions, which is a heuristic weighting — and axis=0 in the softmax means each expert's probability is exponentiated in the same vector, so the weights are driven by confidence rather than by which expert specialises in this region. It demonstrates the arithmetic of gating, not the learning of it. That distinction is worth a mark if the question says "explain this implementation."

The numbers, collected

MethodCode pathResult
Voting (hard, 2 features)VotingClassifier(voting='hard')boundary is a composite of the three
Bagging SVMBaggingClassifier(SVC, n_estimators=20)small gain over the base SVM
Random forestRandomForestClassifier(max_depth=5)beats a single unconstrained tree
AdaBoostAdaBoostClassifier(n_estimators=100)100 sequential stumps
Stacking (2 features, 5-fold CV)mlxtend.StackingClassifier0.88 ± 0.03 vs SVM 0.89 ± 0.04
Mixture of experts (5 SVCs)manual softmax gateimplemented, accuracy printed

What to take to the exam

"Which ensemble method would you choose and why?" Ask what the failure mode is. High variance (a deep tree that changes wildly with the sample) → bagging / random forest, which averages independent high-variance models. High bias (a stump that cannot express the boundary) → boosting, which sequentially concentrates on the residual errors. Base models that are individually strong but complementary, and you want a learned combiner → stacking, with out-of-fold meta-features. Genuinely heterogeneous subpopulations in the feature space → mixture of experts, where the gate routes each input to the relevant specialist. And the honest caveat this notebook demonstrates: if the members are correlated, none of them will help much — the 0.88 stacking result on two features is the evidence.