"""Lecture 10: Ensemble methods -- verification script. Verifies the deck's worked example: single tree vs bagging vs random forest under one CV protocol, OOB score, and the impurity-vs-permutation importance comparison (the Pitfall 3 live specimen). Dataset: Breast cancer (sklearn built-in). """ import numpy as np import pandas as pd from sklearn.datasets import load_breast_cancer from sklearn.ensemble import BaggingClassifier, RandomForestClassifier from sklearn.inspection import permutation_importance from sklearn.metrics import f1_score from sklearn.model_selection import StratifiedKFold, cross_val_score, train_test_split from sklearn.tree import DecisionTreeClassifier # === Protocol (matches slides, section 05) === X, y = load_breast_cancer(return_X_y=True, as_frame=True) X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42, stratify=y ) cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42) n = len(X_train) print(f"Train rows: {n}") print(f"Bootstrap unique-row fraction: {1 - (1 - 1/n)**n:.3f}") # === Three workflows === workflows = { "Tree": DecisionTreeClassifier(random_state=42), "Bagging": BaggingClassifier( estimator=DecisionTreeClassifier(random_state=42), n_estimators=300, n_jobs=-1, random_state=42, ), "Forest": RandomForestClassifier( n_estimators=300, max_features="sqrt", n_jobs=-1, random_state=42, ), } results = {} print() for name, model in workflows.items(): scores = cross_val_score(model, X_train, y_train, cv=cv, scoring="f1") model.fit(X_train, y_train) test_f1 = f1_score(y_test, model.predict(X_test)) results[name] = (scores.mean(), scores.std(), test_f1) print(f"{name:<8} CV f1: {scores.mean():.3f} +/- {scores.std():.3f} test f1: {test_f1:.3f}") tree_mean = results["Tree"][0] bag_mean = results["Bagging"][0] rf_mean = results["Forest"][0] # === OOB score === rf_oob = RandomForestClassifier( n_estimators=300, max_features="sqrt", oob_score=True, n_jobs=-1, random_state=42, ) rf_oob.fit(X_train, y_train) print(f"\nOOB accuracy: {rf_oob.oob_score_:.3f}") # === Pitfall 3: impurity vs permutation importance === rf = workflows["Forest"] impurity = pd.Series(rf.feature_importances_, index=X.columns).sort_values(ascending=False) print("\nImpurity importance (top 5):") print(impurity.head(5).round(3)) perm = permutation_importance( rf, X_test, y_test, n_repeats=20, random_state=0, scoring="f1" ) perm_series = pd.Series(perm.importances_mean, index=X.columns).sort_values(ascending=False) print("\nPermutation importance (top 5):") print(perm_series.head(5).round(3)) # === Asserts tied to the deck's claims === assert bag_mean - tree_mean > 0.02, "tree -> bagging gap should be real" assert abs(rf_mean - bag_mean) < 0.015, "bagging -> forest should be a tie" assert 0.93 < rf_oob.oob_score_ < 0.98 assert set(impurity.head(2).index) == {"worst perimeter", "worst area"}, \ "Pitfall 3 specimen: correlated twins should top impurity importance" assert abs(impurity.iloc[0] - impurity.iloc[1]) < 0.005, "the credit split" assert perm_series.max() < 0.01, "permutation importance should be near-zero everywhere" assert abs(results["Bagging"][2] - results["Forest"][2]) < 0.001, "matching test f1" print("\nOK")