# %% [markdown]
# # Experiment 8: Bagging, Boosting, and Stacked Ensemble Models
# 
# **Course:** UCS3512 – Machine Learning Laboratory  
# **Dataset:** Wisconsin Diagnostic Breast Cancer Dataset (569 samples, 30 features)  
# **Objective:**
# - Understand and implement Bagging, Boosting, and Stacking ensemble methods.
# - Define hyperparameter search spaces and perform 5-fold cross-validation.
# - Evaluate and compare models using Accuracy, Precision, Recall, F1-score, Confusion Matrix, and ROC/AUC.
# - Analyze bias-variance trade-offs across ensemble strategies.

# %%
# Import required libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

from sklearn.model_selection import train_test_split, cross_validate
from sklearn.preprocessing import StandardScaler
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import BaggingClassifier, AdaBoostClassifier, GradientBoostingClassifier, StackingClassifier
from sklearn.svm import SVC
from sklearn.naive_bayes import GaussianNB
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (
    accuracy_score, precision_score, recall_score, f1_score,
    confusion_matrix, ConfusionMatrixDisplay, roc_curve, auc, RocCurveDisplay
)

import warnings
warnings.filterwarnings('ignore')

# %% [markdown]
# ## Step 1: Load and Preprocess Dataset

# %%
# Load data
df = pd.read_csv('data.csv')

# Drop identifier and empty trailing artifact column from dataset export
cols_to_drop = [c for c in ['id', 'Unnamed: 32'] if c in df.columns]
df = df.drop(columns=cols_to_drop)

# Map target classes: Malignant (M) -> 1, Benign (B) -> 0
df['diagnosis'] = df['diagnosis'].map({'M': 1, 'B': 0})

X = df.drop(columns=['diagnosis'])
y = df['diagnosis']

print(f"Dataset Shape: {df.shape} (Features: {X.shape[1]}, Samples: {X.shape[0]})")
print("Target Class Counts:\n", y.value_counts().rename({0: 'Benign (0)', 1: 'Malignant (1)'}))
print("\nMissing values:", X.isnull().sum().sum())

# %% [markdown]
# ## Step 2: Exploratory Data Analysis (EDA)

# %%
# 1. Target Class Distribution
plt.figure(figsize=(4, 3))
sns.countplot(x=y.map({0: 'Benign (B)', 1: 'Malignant (M)'}), palette='Set2')
plt.title('Target Class Distribution')
plt.xlabel('Diagnosis')
plt.ylabel('Count')
plt.tight_layout()
plt.show()

# %%
# 2. Key Feature Distributions across Diagnostic Classes
sample_features = ['radius_mean', 'texture_mean', 'perimeter_mean', 'area_mean']
fig, axes = plt.subplots(2, 2, figsize=(7, 5))
for ax, feat in zip(axes.flatten(), sample_features):
    sns.boxplot(x=y.map({0: 'B', 1: 'M'}), y=X[feat], ax=ax, palette='Set2')
    ax.set_title(feat)
plt.tight_layout()
plt.show()

# %%
# 3. Correlation Heatmap for Mean Features
mean_features = [col for col in X.columns if col.endswith('_mean')]
plt.figure(figsize=(7, 5))
sns.heatmap(X[mean_features].corr(), annot=False, cmap='coolwarm', cbar=True)
plt.title('Correlation Heatmap (Mean Attributes)')
plt.tight_layout()
plt.show()

# %% [markdown]
# ## Step 3: Train-Test Split (80-20) and Feature Scaling

# %%
# Stratified split to preserve benign/malignant proportions in both splits
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.20, random_state=42, stratify=y
)

# Standardize features (crucial for distance- and margin-based learners like SVM and Logistic Regression)
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

print(f"Training samples: {X_train.shape[0]}, Testing samples: {X_test.shape[0]}")

# %% [markdown]
# ## Step 4: Bagging Classifier & Hyperparameter Evaluation (5-Fold CV)
# 
# **Base Estimator:** Decision Tree  
# **Hyperparameters explored:** `n_estimators`, `max_samples`, `max_features`

# %%
# Grid search over Bagging hyperparameters with 5-fold CV
bagging_results = []
n_estimators_list = [10, 50, 100]
max_samples_list = [0.5, 0.8, 1.0]

for n_est in n_estimators_list:
    for m_samp in max_samples_list:
        clf = BaggingClassifier(
            estimator=DecisionTreeClassifier(random_state=42),
            n_estimators=n_est,
            max_samples=m_samp,
            random_state=42
        )
        scores = cross_validate(clf, X_train_scaled, y_train, cv=5, scoring=['accuracy', 'f1'])
        bagging_results.append({
            'n_estimators': n_est,
            'max_samples': m_samp,
            'Avg CV Accuracy (%)': round(scores['test_accuracy'].mean() * 100, 2),
            'Avg CV F1 Score': round(scores['test_f1'].mean(), 4)
        })

table_1 = pd.DataFrame(bagging_results)
print("--- Table 1: Bagging Hyperparameter Evaluation ---")
print(table_1.to_string(index=False))

# Identify best Bagging configuration based on CV F1 score
best_bagging_params = table_1.sort_values(by='Avg CV F1 Score', ascending=False).iloc[0]
best_bagging = BaggingClassifier(
    estimator=DecisionTreeClassifier(random_state=42),
    n_estimators=int(best_bagging_params['n_estimators']),
    max_samples=float(best_bagging_params['max_samples']),
    random_state=42
)

# %% [markdown]
# ## Step 5: Boosting Classifiers & Hyperparameter Evaluation (5-Fold CV)
# 
# **Algorithms:** AdaBoost and Gradient Boosting  
# **Hyperparameters explored:** `n_estimators`, `learning_rate`

# %%
# Grid search over Boosting hyperparameters with 5-fold CV
boosting_results = []
learning_rates = [0.01, 0.1, 1.0]
n_estimators_boosting = [50, 100, 150]

for n_est in n_estimators_boosting:
    for lr in learning_rates:
        # AdaBoost with Decision Stump
        clf = AdaBoostClassifier(
            n_estimators=n_est,
            learning_rate=lr,
            random_state=42
        )
        scores = cross_validate(clf, X_train_scaled, y_train, cv=5, scoring=['accuracy', 'f1'])
        boosting_results.append({
            'n_estimators': n_est,
            'learning_rate': lr,
            'Avg CV Accuracy (%)': round(scores['test_accuracy'].mean() * 100, 2),
            'Avg CV F1 Score': round(scores['test_f1'].mean(), 4)
        })

table_2 = pd.DataFrame(boosting_results)
print("--- Table 2: Boosting Hyperparameter Evaluation ---")
print(table_2.to_string(index=False))

# Select best Boosting model
best_boosting_params = table_2.sort_values(by='Avg CV F1 Score', ascending=False).iloc[0]
best_boosting = AdaBoostClassifier(
    n_estimators=int(best_boosting_params['n_estimators']),
    learning_rate=float(best_boosting_params['learning_rate']),
    random_state=42
)

# %% [markdown]
# ## Step 6: Stacked Ensemble Model (5-Fold CV)
# 
# **Base Models:** Support Vector Machine (RBF kernel), Naïve Bayes, Decision Tree  
# **Meta Learner:** Logistic Regression

# %%
# Define heterogeneous base estimators
# SVM requires probability=True so stacking can use soft prediction probabilities
base_learners = [
    ('svm', SVC(probability=True, random_state=42)),
    ('nb', GaussianNB()),
    ('dt', DecisionTreeClassifier(random_state=42))
]

# Meta-learner to combine base model predictions
meta_learner = LogisticRegression(random_state=42)

stacked_model = StackingClassifier(
    estimators=base_learners,
    final_estimator=meta_learner,
    cv=5
)

stacked_scores = cross_validate(stacked_model, X_train_scaled, y_train, cv=5, scoring=['accuracy', 'f1'])

table_3 = pd.DataFrame([{
    'Base Models': 'SVM, Naïve Bayes, Decision Tree',
    'Meta Learner': 'Logistic Regression',
    'Avg CV Accuracy (%)': round(stacked_scores['test_accuracy'].mean() * 100, 2),
    'Avg CV F1 Score': round(stacked_scores['test_f1'].mean(), 4)
}])

print("--- Table 3: Stacked Ensemble Evaluation ---")
print(table_3.to_string(index=False))

# %% [markdown]
# ## Step 7: Final Model Evaluation & Comparison on Test Set (Table 4)

# %%
# Dictionary of final models with optimal hyperparameters
models = {
    'Bagging': best_bagging,
    'Boosting': best_boosting,
    'Stacked Ensemble': stacked_model
}

results = []
predictions = {}
probabilities = {}

# Train on full training split and evaluate on unseen 20% test split
for name, model in models.items():
    model.fit(X_train_scaled, y_train)
    y_pred = model.predict(X_test_scaled)
    y_prob = model.predict_proba(X_test_scaled)[:, 1]
    
    predictions[name] = y_pred
    probabilities[name] = y_prob
    
    results.append({
        'Model': name,
        'Accuracy (%)': round(accuracy_score(y_test, y_pred) * 100, 2),
        'Precision': round(precision_score(y_test, y_pred), 4),
        'Recall': round(recall_score(y_test, y_pred), 4),
        'F1 Score': round(f1_score(y_test, y_pred), 4)
    })

table_4 = pd.DataFrame(results)
print("--- Table 4: Performance Comparison of Ensemble Models ---")
print(table_4.to_string(index=False))

# %% [markdown]
# ## Step 8: Visualizations - Confusion Matrices & ROC Curves

# %%
# Confusion Matrices
fig, axes = plt.subplots(1, 3, figsize=(11, 3.5))
for ax, (name, y_pred) in zip(axes, predictions.items()):
    cm = confusion_matrix(y_test, y_pred)
    ConfusionMatrixDisplay(cm, display_labels=['Benign', 'Malignant']).plot(
        ax=ax, cmap='Blues', colorbar=False
    )
    ax.set_title(f"{name}")
plt.tight_layout()
plt.show()

# %%
# ROC Curves and AUC Comparison
plt.figure(figsize=(6, 5))
for name, y_prob in probabilities.items():
    fpr, tpr, _ = roc_curve(y_test, y_prob)
    auc_score = auc(fpr, tpr)
    plt.plot(fpr, tpr, label=f"{name} (AUC = {auc_score:.3f})")

plt.plot([0, 1], [0, 1], 'k--', label='Chance (AUC = 0.500)')
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC Curves of Ensemble Models')
plt.legend(loc='lower right')
plt.grid(True, linestyle=':', alpha=0.6)
plt.tight_layout()
plt.show()

# %% [markdown]
# ## Step 9: Observation Questions and Analysis
# 
# ### 1. How does Bagging reduce variance?
# Bagging (Bootstrap Aggregation) generates multiple overlapping training subsets through sampling with replacement (bootstrapping). It trains independent high-variance, low-bias estimators (e.g., deep Decision Trees) on each subset. By averaging probabilities or taking a majority vote across $M$ distinct trees, idiosyncratic variance and errors from individual models cancel each other out, mathematically reducing variance by a factor of approximately $\frac{1}{M}$ without increasing bias.
# 
# ### 2. How does Boosting address model bias?
# Boosting trains weak learners sequentially rather than in parallel. Each new base estimator is forced to focus specifically on samples that were misclassified or yielded high residuals in earlier stages (by upweighting misclassified samples in AdaBoost or fitting negative gradients in Gradient Boosting). Iteratively correcting previous mistakes progressively shifts the combined decision boundary, thereby systematically reducing model bias.
# 
# ### 3. Why does Stacking benefit from heterogeneous models?
# Heterogeneous base models (e.g., linear margin models like SVM, probabilistic classifiers like Naïve Bayes, and orthogonal boundary partitioners like Decision Trees) carry completely different inductive biases. They commit errors on different instances across the feature space. The meta-learner (Logistic Regression) learns which model performs best in which feature region, effectively blending their individual strengths.
# 
# ### 4. Which ensemble method performed best and why?
# Refer to the metrics in Table 4. All three ensemble architectures achieve strong predictive performance ($>95\%$ accuracy). Typically, the **Stacked Ensemble** or fine-tuned **Boosting** model achieves the highest F1-score and AUC because Stacking harnesses diverse hypothesis spaces while Boosting optimizes hard boundary cases. In medical diagnosis (breast cancer detection), **Recall** for the malignant class is the most vital metric to minimize harmful False Negatives.

# %%
# Console summary of observations
print("\n" + "="*60)
print("OBSERVATION QUESTIONS & ANALYSIS SUMMARY")
print("="*60)
print("1. How does Bagging reduce variance?")
print("   -> Independent models trained on bootstrap subsets cancel out random errors upon aggregation.")
print("\n2. How does Boosting address model bias?")
print("   -> Sequential training with higher weights on hard/misclassified samples iteratively corrects errors.")
print("\n3. Why does stacking benefit from heterogeneous models?")
print("   -> Different model families have distinct inductive biases; the meta-learner combines complementary strengths.")
print("\n4. Which ensemble method performed best and why?")
best_model_row = table_4.sort_values(by='F1 Score', ascending=False).iloc[0]
print(f"   -> {best_model_row['Model']} achieved highest test F1 score ({best_model_row['F1 Score']}) and accuracy ({best_model_row['Accuracy (%)']}%).")
print("      High recall on malignant diagnoses is especially critical for medical screening.")
print("="*60)
