Tutorial 3: Ensemble Methods
sklearn · AdaBoost · RandomForest · GradientBoosting · Submit as dm03t[RR].py
Submission
Name your file dm03t[RR].py where RR = last two digits of your roll number. All tasks in one file with # Task N comments. Submit by the deadline announced in class.
Background
Ensemble methods combine many weak classifiers to form a strong one. AdaBoost trains classifiers sequentially, each focusing on the mistakes of the previous one. Random Forest trains many decision trees on random subsets of features and data in parallel, then takes a majority vote. Gradient Boosting builds trees sequentially to minimise a loss function. All three are workhorses of real-world data mining.
We use the Breast Cancer Wisconsin dataset (30 features, 2 classes, 569 samples) for this tutorial.
Tasks
Task 1 Load Data and Create Train/Test Split
- Import:
numpy as np,from sklearn.datasets import load_breast_cancer,from sklearn.model_selection import train_test_split,from sklearn.preprocessing import StandardScaler - Load:
data = load_breast_cancer(). Store features asX, labels asy - Split into 80% train / 20% test with
random_state=42 - Standardise X using
StandardScaler(fit on train, transform both train and test) - Print the shapes of X_train, X_test, y_train, y_test and the class distribution in y_train
Task 2 AdaBoost Classifier
- Import:
from sklearn.ensemble import AdaBoostClassifier,from sklearn.metrics import accuracy_score, classification_report - Create:
ada = AdaBoostClassifier(n_estimators=100, random_state=42) - Fit on training data and predict on test data
- Print the accuracy score
- Print the full classification report (precision, recall, F1 per class)
Task 3 Random Forest Classifier
- Import:
from sklearn.ensemble import RandomForestClassifier - Create:
rf = RandomForestClassifier(n_estimators=100, random_state=42) - Fit and predict
- Print accuracy and classification report
- Print the top 5 most important features:
rf.feature_importances_: usenp.argsort()anddata.feature_names
Task 4 Gradient Boosting Classifier
- Import:
from sklearn.ensemble import GradientBoostingClassifier - Create:
gb = GradientBoostingClassifier(n_estimators=100, learning_rate=0.1, random_state=42) - Fit and predict
- Print accuracy and classification report
Task 5 Comparison Table
Print a summary table comparing the three classifiers. Use formatted print statements.
Then answer as a comment in your code: which classifier performs best on this dataset, and why might AdaBoost outperform Random Forest here?
Task 6 Extension: Effect of Number of Estimators
For Random Forest, train with n_estimators = 10, 50, 100, 200 and record the test accuracy for each. Print the results. At what point does adding more trees stop improving accuracy? Write your observation as a comment.