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
| 5 |
+
"id": "title-cell",
|
| 6 |
+
"metadata": {},
|
| 7 |
+
"source": [
|
| 8 |
+
"# Sprint 5 Report β Resampling and Ensemble Techniques\n",
|
| 9 |
+
"**Course:** Data Intensive Systems (4DV652) \n",
|
| 10 |
+
"**Lab:** Lab Lecture 5 \n",
|
| 11 |
+
"**Deadline:** 2026-02-25 \n",
|
| 12 |
+
"\n",
|
| 13 |
+
"---\n",
|
| 14 |
+
"\n",
|
| 15 |
+
"## Overview\n",
|
| 16 |
+
"\n",
|
| 17 |
+
"This sprint focused on applying **heterogeneous ensemble methods** and **stacking** to challenge the current regression and classification champions established in Sprint 4. The team worked across two parallel tracks:\n",
|
| 18 |
+
"\n",
|
| 19 |
+
"- **Regression Ensemble** β Predict `AimoScore` (continuous target) using diverse base models with bootstrap sampling and aggregation strategies.\n",
|
| 20 |
+
"- **Classification Ensemble** β Predict `WeakestLink` (14-class target) using voting classifiers, bagging, and stacking.\n",
|
| 21 |
+
"\n",
|
| 22 |
+
"A custom `CorrelationFilter` transformer was also implemented as a reusable sklearn-compatible preprocessing component shared across both tracks.\n",
|
| 23 |
+
"\n",
|
| 24 |
+
"---"
|
| 25 |
+
]
|
| 26 |
+
},
|
| 27 |
+
{
|
| 28 |
+
"cell_type": "markdown",
|
| 29 |
+
"id": "ml-process-cell",
|
| 30 |
+
"metadata": {},
|
| 31 |
+
"source": [
|
| 32 |
+
"## 1. ML Process Iteration\n",
|
| 33 |
+
"\n",
|
| 34 |
+
"### 1.1 Problem Framing Recap\n",
|
| 35 |
+
"\n",
|
| 36 |
+
"The dataset originates from movement quality assessments (NASM Overhead Squat Assessment). Two supervised learning tasks are defined:\n",
|
| 37 |
+
"\n",
|
| 38 |
+
"| Task | Target | Type | Sprint 4 Champion Score |\n",
|
| 39 |
+
"|------|--------|------|-------------------------|\n",
|
| 40 |
+
"| Regression | `AimoScore` (continuous) | Regression | RΒ² = 0.6356, RMSE = 0.1303 |\n",
|
| 41 |
+
"| Classification | `WeakestLink` (14 classes) | Multiclass | Weighted F1 = 0.6110 |\n",
|
| 42 |
+
"\n",
|
| 43 |
+
"### 1.2 Sprint 5 Goals\n",
|
| 44 |
+
"\n",
|
| 45 |
+
"Per the lab assignment:\n",
|
| 46 |
+
"1. Define ensembles of independent models using bootstrap samples, different feature engineering, and diverse AI approaches.\n",
|
| 47 |
+
"2. Challenge the Sprint 4 champions using simple aggregation (averaging / majority vote) or stacking.\n",
|
| 48 |
+
"3. Deploy a new champion if the ensemble outperforms the previous one.\n",
|
| 49 |
+
"4. Validate improvement using the **corrected resampled t-test** (Nadeau & Bengio, 2003).\n",
|
| 50 |
+
"\n",
|
| 51 |
+
"---"
|
| 52 |
+
]
|
| 53 |
+
},
|
| 54 |
+
{
|
| 55 |
+
"cell_type": "markdown",
|
| 56 |
+
"id": "software-cell",
|
| 57 |
+
"metadata": {},
|
| 58 |
+
"source": [
|
| 59 |
+
"## 2. Software Development: CorrelationFilter\n",
|
| 60 |
+
"\n",
|
| 61 |
+
"A custom `sklearn`-compatible transformer was implemented and used in both the regression and classification pipelines. It removes highly correlated features before model fitting, reducing redundancy while preserving sklearn `Pipeline` compatibility."
|
| 62 |
+
]
|
| 63 |
+
},
|
| 64 |
+
{
|
| 65 |
+
"cell_type": "code",
|
| 66 |
+
"execution_count": null,
|
| 67 |
+
"id": "correlation-filter-code",
|
| 68 |
+
"metadata": {},
|
| 69 |
+
"outputs": [],
|
| 70 |
+
"source": [
|
| 71 |
+
"from sklearn.base import BaseEstimator, TransformerMixin\n",
|
| 72 |
+
"import pandas as pd\n",
|
| 73 |
+
"import numpy as np\n",
|
| 74 |
+
"\n",
|
| 75 |
+
"class CorrelationFilter(BaseEstimator, TransformerMixin):\n",
|
| 76 |
+
" \"\"\"\n",
|
| 77 |
+
" Removes features that are highly correlated with another feature.\n",
|
| 78 |
+
" Threshold defaults to 0.99 (absolute Pearson correlation).\n",
|
| 79 |
+
" Sklearn-compatible: can be used in Pipeline objects.\n",
|
| 80 |
+
" \"\"\"\n",
|
| 81 |
+
" def __init__(self, threshold=0.99):\n",
|
| 82 |
+
" self.threshold = threshold\n",
|
| 83 |
+
" self.keep_cols_ = None\n",
|
| 84 |
+
"\n",
|
| 85 |
+
" def fit(self, X, y=None):\n",
|
| 86 |
+
" Xdf = pd.DataFrame(X) if not isinstance(X, pd.DataFrame) else X\n",
|
| 87 |
+
" # Compute absolute correlation matrix (upper triangle only)\n",
|
| 88 |
+
" corr = Xdf.corr(numeric_only=True).abs()\n",
|
| 89 |
+
" upper = corr.where(np.triu(np.ones(corr.shape), k=1).astype(bool))\n",
|
| 90 |
+
" to_drop = [col for col in upper.columns if any(upper[col] >= self.threshold)]\n",
|
| 91 |
+
" self.keep_cols_ = [c for c in Xdf.columns if c not in to_drop]\n",
|
| 92 |
+
" return self\n",
|
| 93 |
+
"\n",
|
| 94 |
+
" def transform(self, X):\n",
|
| 95 |
+
" Xdf = pd.DataFrame(X) if not isinstance(X, pd.DataFrame) else X\n",
|
| 96 |
+
" return Xdf[self.keep_cols_].copy()\n",
|
| 97 |
+
"\n",
|
| 98 |
+
"# Example usage\n",
|
| 99 |
+
"print(\"CorrelationFilter: removes columns with |corr| >= threshold.\")\n",
|
| 100 |
+
"print(\"Used in regression pipeline with threshold=0.95 for RandomForest.\")"
|
| 101 |
+
]
|
| 102 |
+
},
|
| 103 |
+
{
|
| 104 |
+
"cell_type": "markdown",
|
| 105 |
+
"id": "regression-header",
|
| 106 |
+
"metadata": {},
|
| 107 |
+
"source": [
|
| 108 |
+
"---\n",
|
| 109 |
+
"## 3. Regression Ensemble (A5_Regression_Ensemble)\n",
|
| 110 |
+
"\n",
|
| 111 |
+
"### 3.1 Approach\n",
|
| 112 |
+
"\n",
|
| 113 |
+
"A heterogeneous ensemble was designed following the sprint lecture pattern:\n",
|
| 114 |
+
"\n",
|
| 115 |
+
"- **Bootstrap diversity**: Four different bootstrap-augmented training sets (`dataset2_train_augmented_1..4.csv`).\n",
|
| 116 |
+
"- **Model diversity**: Four distinct regressors (Lasso, Ridge, RandomForest, GradientBoosting), each trained on a different bootstrap sample.\n",
|
| 117 |
+
"- **Feature diversity**: Feature subsets were defined (full, angle-only, NASM-only, angle+NASM) to allow further differentiation.\n",
|
| 118 |
+
"- **Aggregation**: Two strategies β simple averaging and CV-RΒ²-weighted averaging.\n",
|
| 119 |
+
"\n",
|
| 120 |
+
"### 3.2 Ensemble Configuration\n",
|
| 121 |
+
"\n",
|
| 122 |
+
"| Model | Bootstrap Sample | Feature Set | Algorithm |\n",
|
| 123 |
+
"|-------|-----------------|-------------|----------|\n",
|
| 124 |
+
"| Lasso | 1 | Full | `LassoCV` (cv=5) |\n",
|
| 125 |
+
"| Ridge | 2 | Full | `RidgeCV` (cv=5) |\n",
|
| 126 |
+
"| RandomForest | 3 | Full | `RandomForestRegressor` (200 trees, depth=15) + CorrelationFilter(0.95) |\n",
|
| 127 |
+
"| GradientBoosting | 4 | Full | `GradientBoostingRegressor` (150 trees, depth=5, lr=0.1) |"
|
| 128 |
+
]
|
| 129 |
+
},
|
| 130 |
+
{
|
| 131 |
+
"cell_type": "code",
|
| 132 |
+
"execution_count": null,
|
| 133 |
+
"id": "regression-config-code",
|
| 134 |
+
"metadata": {},
|
| 135 |
+
"outputs": [],
|
| 136 |
+
"source": [
|
| 137 |
+
"# Ensemble configuration (from A5_Regression_Ensemble.ipynb)\n",
|
| 138 |
+
"ENSEMBLE_CONFIG = [\n",
|
| 139 |
+
" {\"name\": \"lasso\", \"bootstrap\": 1, \"features\": \"full\"},\n",
|
| 140 |
+
" {\"name\": \"ridge\", \"bootstrap\": 2, \"features\": \"full\"},\n",
|
| 141 |
+
" {\"name\": \"rf\", \"bootstrap\": 3, \"features\": \"full\"},\n",
|
| 142 |
+
" {\"name\": \"gb\", \"bootstrap\": 4, \"features\": \"full\"},\n",
|
| 143 |
+
"]\n",
|
| 144 |
+
"\n",
|
| 145 |
+
"# Feature subsets available (used for diversity)\n",
|
| 146 |
+
"FEATURE_SUBSETS = {\n",
|
| 147 |
+
" \"full\": \"all features\",\n",
|
| 148 |
+
" \"angle_only\": \"features with 'Angle' in name\",\n",
|
| 149 |
+
" \"nasm_only\": \"features with 'NASM' in name\",\n",
|
| 150 |
+
" \"angle_nasm\": \"angle + NASM features (excludes time)\",\n",
|
| 151 |
+
"}\n",
|
| 152 |
+
"\n",
|
| 153 |
+
"print(\"Ensemble configuration loaded.\")\n",
|
| 154 |
+
"print(f\"Number of base models: {len(ENSEMBLE_CONFIG)}\")"
|
| 155 |
+
]
|
| 156 |
+
},
|
| 157 |
+
{
|
| 158 |
+
"cell_type": "markdown",
|
| 159 |
+
"id": "regression-results",
|
| 160 |
+
"metadata": {},
|
| 161 |
+
"source": [
|
| 162 |
+
"### 3.3 Base Model Results (Test Set)\n",
|
| 163 |
+
"\n",
|
| 164 |
+
"Each base model was trained on its assigned bootstrap sample and evaluated on the held-out test set. Cross-validation RΒ² scores were used to compute ensemble weights.\n",
|
| 165 |
+
"\n",
|
| 166 |
+
"| Model | Bootstrap | CV RΒ² | Test RΒ² | Test RMSE | Test MAE |\n",
|
| 167 |
+
"|-------|-----------|-------|---------|-----------|----------|\n",
|
| 168 |
+
"| Lasso | 1 | β | β | β | β |\n",
|
| 169 |
+
"| Ridge | 2 | β | β | β | β |\n",
|
| 170 |
+
"| RandomForest | 3 | β | β | β | β |\n",
|
| 171 |
+
"| GradientBoosting | 4 | β | β | β | β |\n",
|
| 172 |
+
"\n",
|
| 173 |
+
"> *Note: Exact numeric outputs are produced at runtime. The table above is populated when executing the notebook against the dataset.*\n",
|
| 174 |
+
"\n",
|
| 175 |
+
"### 3.4 Ensemble Aggregation Results\n",
|
| 176 |
+
"\n",
|
| 177 |
+
"| Method | RΒ² | RMSE | MAE | Corr |\n",
|
| 178 |
+
"|--------|----|------|-----|------|\n",
|
| 179 |
+
"| Simple Average | runtime | runtime | runtime | runtime |\n",
|
| 180 |
+
"| Weighted Average (CV RΒ²) | runtime | runtime | runtime | runtime |\n",
|
| 181 |
+
"| **A4 Champion (baseline)** | **0.6356** | **0.1303** | **0.0972** | **0.8089** |\n",
|
| 182 |
+
"\n",
|
| 183 |
+
"Weighted averaging assigns higher influence to models with better cross-validation RΒ² scores:\n",
|
| 184 |
+
"$$\\hat{y}_{\\text{ensemble}} = \\sum_{i=1}^{4} w_i \\hat{y}_i, \\quad w_i = \\frac{\\text{CV-R}^2_i}{\\sum_j \\text{CV-R}^2_j}$$"
|
| 185 |
+
]
|
| 186 |
+
},
|
| 187 |
+
{
|
| 188 |
+
"cell_type": "markdown",
|
| 189 |
+
"id": "regression-ttest",
|
| 190 |
+
"metadata": {},
|
| 191 |
+
"source": [
|
| 192 |
+
"### 3.5 Statistical Significance β Corrected Resampled t-test\n",
|
| 193 |
+
"\n",
|
| 194 |
+
"Standard paired t-tests overstate confidence when models are compared via cross-validation because training folds overlap. The **Nadeau & Bengio (2003) correction** accounts for this by inflating the variance:\n",
|
| 195 |
+
"\n",
|
| 196 |
+
"$$\\text{Var}_{\\text{corrected}} = \\left(\\frac{1}{k} + \\frac{n_{\\text{test}}}{n_{\\text{train}}}\\right) \\cdot \\hat{\\sigma}^2_{\\Delta}$$\n",
|
| 197 |
+
"\n",
|
| 198 |
+
"For this dataset, $n_{\\text{test}}/n_{\\text{train}} \\approx 0.25$, meaning variance is inflated by ~25%, making it harder to claim statistically significant improvement.\n",
|
| 199 |
+
"\n",
|
| 200 |
+
"Hypotheses tested (Ξ± = 0.05):\n",
|
| 201 |
+
"- Hβ: Ensemble MSE = Champion MSE \n",
|
| 202 |
+
"- Hβ: Ensemble MSE β Champion MSE (two-tailed)\n",
|
| 203 |
+
"\n",
|
| 204 |
+
"| Comparison | t-stat | p-value | Significant? |\n",
|
| 205 |
+
"|------------|--------|---------|-------------|\n",
|
| 206 |
+
"| Simple Avg vs Champion | runtime | runtime | runtime |\n",
|
| 207 |
+
"| Weighted Avg vs Champion | runtime | runtime | runtime |"
|
| 208 |
+
]
|
| 209 |
+
},
|
| 210 |
+
{
|
| 211 |
+
"cell_type": "code",
|
| 212 |
+
"execution_count": null,
|
| 213 |
+
"id": "regression-ttest-code",
|
| 214 |
+
"metadata": {},
|
| 215 |
+
"outputs": [],
|
| 216 |
+
"source": [
|
| 217 |
+
"# Corrected resampled t-test implementation (Nadeau & Bengio, 2003)\n",
|
| 218 |
+
"import numpy as np\n",
|
| 219 |
+
"from scipy import stats\n",
|
| 220 |
+
"\n",
|
| 221 |
+
"def corrected_resampled_ttest(errors_1, errors_2, n_train, n_test):\n",
|
| 222 |
+
" \"\"\"\n",
|
| 223 |
+
" Corrected resampled t-test for comparing two models.\n",
|
| 224 |
+
" Accounts for variance inflation due to overlapping cross-validation folds.\n",
|
| 225 |
+
" \n",
|
| 226 |
+
" Args:\n",
|
| 227 |
+
" errors_1, errors_2: arrays of per-sample squared errors for model 1 and 2\n",
|
| 228 |
+
" n_train: number of training samples\n",
|
| 229 |
+
" n_test: number of test samples\n",
|
| 230 |
+
" Returns:\n",
|
| 231 |
+
" t_stat, p_value, mean_diff\n",
|
| 232 |
+
" \"\"\"\n",
|
| 233 |
+
" diff = errors_1 - errors_2\n",
|
| 234 |
+
" mean_diff = np.mean(diff)\n",
|
| 235 |
+
" var_diff = np.var(diff, ddof=1)\n",
|
| 236 |
+
"\n",
|
| 237 |
+
" # Correction factor: accounts for n_test/n_train overlap\n",
|
| 238 |
+
" correction = (1 / len(diff)) + (n_test / n_train)\n",
|
| 239 |
+
" corrected_var = correction * var_diff\n",
|
| 240 |
+
"\n",
|
| 241 |
+
" t_stat = mean_diff / np.sqrt(corrected_var)\n",
|
| 242 |
+
" p_value = 2 * stats.t.sf(np.abs(t_stat), df=len(diff) - 1)\n",
|
| 243 |
+
" return t_stat, p_value, mean_diff\n",
|
| 244 |
+
"\n",
|
| 245 |
+
"print(\"Corrected resampled t-test function defined.\")\n",
|
| 246 |
+
"print(\"Positive mean_diff => champion has higher MSE (ensemble is better).\")"
|
| 247 |
+
]
|
| 248 |
+
},
|
| 249 |
+
{
|
| 250 |
+
"cell_type": "markdown",
|
| 251 |
+
"id": "regression-champion",
|
| 252 |
+
"metadata": {},
|
| 253 |
+
"source": [
|
| 254 |
+
"### 3.6 Champion Decision (Regression)\n",
|
| 255 |
+
"\n",
|
| 256 |
+
"The best-performing ensemble method (Simple Average or Weighted Average) is compared against the A4 champion. If the ensemble exceeds RΒ² = 0.6356, the model is saved as `aimoscores_ensemble_A5.pkl`.\n",
|
| 257 |
+
"\n",
|
| 258 |
+
"The best ensemble selection logic:\n",
|
| 259 |
+
"- Best aggregation method: `weighted` if weighted RΒ² > average RΒ², else `average`\n",
|
| 260 |
+
"- Saved only if it outperforms the A4 champion\n",
|
| 261 |
+
"\n",
|
| 262 |
+
"---"
|
| 263 |
+
]
|
| 264 |
+
},
|
| 265 |
+
{
|
| 266 |
+
"cell_type": "markdown",
|
| 267 |
+
"id": "classification-header",
|
| 268 |
+
"metadata": {},
|
| 269 |
+
"source": [
|
| 270 |
+
"## 4. Classification Ensemble (A5_Classification_Ensemble)\n",
|
| 271 |
+
"\n",
|
| 272 |
+
"### 4.1 Problem Setup\n",
|
| 273 |
+
"\n",
|
| 274 |
+
"- **Target**: `WeakestLink` β the movement category with the highest deviation score across 14 NASM categories.\n",
|
| 275 |
+
"- **Features**: Merged movement features from `aimoscores.csv` + weakest link labels from `scores_and_weaklink.csv`.\n",
|
| 276 |
+
"- **Class imbalance**: Addressed using `class_weight='balanced'` and `class_weight='balanced_subsample'`.\n",
|
| 277 |
+
"- **A4 Champion baseline**: Random Forest with weighted F1 = **0.6110**.\n",
|
| 278 |
+
"\n",
|
| 279 |
+
"### 4.2 Data Preparation"
|
| 280 |
+
]
|
| 281 |
+
},
|
| 282 |
+
{
|
| 283 |
+
"cell_type": "code",
|
| 284 |
+
"execution_count": null,
|
| 285 |
+
"id": "classification-setup",
|
| 286 |
+
"metadata": {},
|
| 287 |
+
"outputs": [],
|
| 288 |
+
"source": [
|
| 289 |
+
"# Classification setup (from A5_Classification_Ensemble.ipynb)\n",
|
| 290 |
+
"RANDOM_STATE = 42\n",
|
| 291 |
+
"N_SPLITS = 5\n",
|
| 292 |
+
"CHAMPION_F1 = 0.6110 # Sprint 4 benchmark\n",
|
| 293 |
+
"\n",
|
| 294 |
+
"# 14 WeakestLink categories\n",
|
| 295 |
+
"weaklink_categories = [\n",
|
| 296 |
+
" 'ExcessiveForwardLean', 'ForwardHead', 'LeftArmFallForward',\n",
|
| 297 |
+
" 'LeftAsymmetricalWeightShift', 'LeftHeelRises', 'LeftKneeMovesInward',\n",
|
| 298 |
+
" 'LeftKneeMovesOutward', 'LeftShoulderElevation', 'RightArmFallForward',\n",
|
| 299 |
+
" 'RightAsymmetricalWeightShift', 'RightHeelRises', 'RightKneeMovesInward',\n",
|
| 300 |
+
" 'RightKneeMovesOutward', 'RightShoulderElevation',\n",
|
| 301 |
+
"]\n",
|
| 302 |
+
"\n",
|
| 303 |
+
"# WeakestLink = the category with the highest deviation score\n",
|
| 304 |
+
"# weaklink_scores_df['WeakestLink'] = weaklink_scores_df[weaklink_categories].idxmax(axis=1)\n",
|
| 305 |
+
"\n",
|
| 306 |
+
"print(f\"Number of classes: {len(weaklink_categories)}\")\n",
|
| 307 |
+
"print(f\"Sprint 4 champion F1: {CHAMPION_F1}\")"
|
| 308 |
+
]
|
| 309 |
+
},
|
| 310 |
+
{
|
| 311 |
+
"cell_type": "markdown",
|
| 312 |
+
"id": "classification-ensembles",
|
| 313 |
+
"metadata": {},
|
| 314 |
+
"source": [
|
| 315 |
+
"### 4.3 Ensemble Strategies\n",
|
| 316 |
+
"\n",
|
| 317 |
+
"Four ensemble strategies were designed and evaluated using **5-fold stratified cross-validation**:\n",
|
| 318 |
+
"\n",
|
| 319 |
+
"#### Ensemble 1 β Hard Voting\n",
|
| 320 |
+
"Each base classifier casts a vote; the class with the most votes wins. Base classifiers: Random Forest, Logistic Regression, XGBoost, LightGBM, KNN (k=7), LDA.\n",
|
| 321 |
+
"\n",
|
| 322 |
+
"#### Ensemble 2 β Soft Voting \n",
|
| 323 |
+
"Same base classifiers, but predictions are combined via averaged class probabilities. Generally more accurate than hard voting when calibrated probability estimates are available.\n",
|
| 324 |
+
"\n",
|
| 325 |
+
"#### Ensemble 3 β Bootstrap Bagging on LDA \n",
|
| 326 |
+
"`BaggingClassifier` wrapping `LinearDiscriminantAnalysis` (50 estimators, 80% sample size, 90% feature subset). Demonstrates how bagging can stabilise a weak linear model.\n",
|
| 327 |
+
"\n",
|
| 328 |
+
"#### Ensemble 4 β Stacking (LR meta-learner) \n",
|
| 329 |
+
"Base classifiers: Random Forest, Logistic Regression, KNN, LDA. Meta-learner: `LogisticRegression` trained on out-of-fold predictions (5-fold CV). The meta-learner learns *how to combine* base model outputs, replacing simple voting with a learned aggregation function."
|
| 330 |
+
]
|
| 331 |
+
},
|
| 332 |
+
{
|
| 333 |
+
"cell_type": "code",
|
| 334 |
+
"execution_count": null,
|
| 335 |
+
"id": "classification-ensembles-code",
|
| 336 |
+
"metadata": {},
|
| 337 |
+
"outputs": [],
|
| 338 |
+
"source": [
|
| 339 |
+
"# Ensemble model definitions (from A5_Classification_Ensemble.ipynb)\n",
|
| 340 |
+
"from sklearn.ensemble import (\n",
|
| 341 |
+
" RandomForestClassifier, VotingClassifier, BaggingClassifier, StackingClassifier\n",
|
| 342 |
+
")\n",
|
| 343 |
+
"from sklearn.linear_model import LogisticRegression\n",
|
| 344 |
+
"from sklearn.discriminant_analysis import LinearDiscriminantAnalysis\n",
|
| 345 |
+
"from sklearn.neighbors import KNeighborsClassifier\n",
|
| 346 |
+
"# import xgboost as xgb\n",
|
| 347 |
+
"# import lightgbm as lgb\n",
|
| 348 |
+
"\n",
|
| 349 |
+
"# ---- Ensemble 4: Stacking ----\n",
|
| 350 |
+
"stacking = StackingClassifier(\n",
|
| 351 |
+
" estimators=[\n",
|
| 352 |
+
" ('rf', RandomForestClassifier(n_estimators=100, max_depth=15,\n",
|
| 353 |
+
" min_samples_split=5, min_samples_leaf=2,\n",
|
| 354 |
+
" class_weight='balanced_subsample',\n",
|
| 355 |
+
" random_state=RANDOM_STATE, n_jobs=-1)),\n",
|
| 356 |
+
" ('lr', LogisticRegression(max_iter=1000, class_weight='balanced',\n",
|
| 357 |
+
" random_state=RANDOM_STATE)),\n",
|
| 358 |
+
" ('knn', KNeighborsClassifier(n_neighbors=7)),\n",
|
| 359 |
+
" ('lda', LinearDiscriminantAnalysis()),\n",
|
| 360 |
+
" ],\n",
|
| 361 |
+
" final_estimator=LogisticRegression(\n",
|
| 362 |
+
" C=1.0, max_iter=1000, class_weight='balanced', random_state=RANDOM_STATE\n",
|
| 363 |
+
" ),\n",
|
| 364 |
+
" cv=5,\n",
|
| 365 |
+
" passthrough=False,\n",
|
| 366 |
+
" n_jobs=-1,\n",
|
| 367 |
+
")\n",
|
| 368 |
+
"\n",
|
| 369 |
+
"print(\"Stacking classifier defined with LR meta-learner.\")"
|
| 370 |
+
]
|
| 371 |
+
},
|
| 372 |
+
{
|
| 373 |
+
"cell_type": "markdown",
|
| 374 |
+
"id": "classification-results",
|
| 375 |
+
"metadata": {},
|
| 376 |
+
"source": [
|
| 377 |
+
"### 4.4 Cross-Validation Results\n",
|
| 378 |
+
"\n",
|
| 379 |
+
"All models were evaluated with 5-fold **StratifiedKFold** cross-validation on the training set, using weighted F1-score as the primary metric.\n",
|
| 380 |
+
"\n",
|
| 381 |
+
"| Model | CV F1 (mean) | CV F1 (std) | CV Accuracy | CV Precision | CV Recall |\n",
|
| 382 |
+
"|-------|-------------|------------|------------|-------------|----------|\n",
|
| 383 |
+
"| A4 Champion β Random Forest | ~0.6110 | β | β | β | β |\n",
|
| 384 |
+
"| Hard Voting | runtime | runtime | runtime | runtime | runtime |\n",
|
| 385 |
+
"| Soft Voting | runtime | runtime | runtime | runtime | runtime |\n",
|
| 386 |
+
"| Bootstrap Bagging (LDA) | runtime | runtime | runtime | runtime | runtime |\n",
|
| 387 |
+
"| Stacking (LR meta) | runtime | runtime | runtime | runtime | runtime |\n",
|
| 388 |
+
"\n",
|
| 389 |
+
"> *The bar chart below (produced at runtime) visually compares all approaches, with the red dashed line marking the Sprint 4 champion.*\n",
|
| 390 |
+
"\n",
|
| 391 |
+
"### 4.5 Statistical Significance Tests\n",
|
| 392 |
+
"\n",
|
| 393 |
+
"The corrected resampled t-test was applied for each ensemble vs the A4 champion (same implementation as the regression track).\n",
|
| 394 |
+
"\n",
|
| 395 |
+
"| Ensemble | t-stat | p-value | Better than Champion? |\n",
|
| 396 |
+
"|----------|--------|---------|----------------------|\n",
|
| 397 |
+
"| Hard Voting | runtime | runtime | runtime |\n",
|
| 398 |
+
"| Soft Voting | runtime | runtime | runtime |\n",
|
| 399 |
+
"| Bootstrap Bagging (LDA) | runtime | runtime | runtime |\n",
|
| 400 |
+
"| Stacking (LR meta) | runtime | runtime | runtime |\n",
|
| 401 |
+
"\n",
|
| 402 |
+
"### 4.6 Final Test Set Results\n",
|
| 403 |
+
"\n",
|
| 404 |
+
"All models were retrained on the full training set and evaluated on the held-out 20% test split.\n",
|
| 405 |
+
"\n",
|
| 406 |
+
"| Model | Test F1 | Test Accuracy | Test Precision | Test Recall |\n",
|
| 407 |
+
"|-------|---------|--------------|---------------|------------|\n",
|
| 408 |
+
"| Best Ensemble (champion) | runtime | runtime | runtime | runtime |\n",
|
| 409 |
+
"| A4 Champion β Random Forest | ~0.6110 | β | β | β |\n",
|
| 410 |
+
"\n",
|
| 411 |
+
"### 4.7 Champion Decision (Classification)\n",
|
| 412 |
+
"\n",
|
| 413 |
+
"The top-ranked ensemble by CV F1 is selected as the new champion and saved to `models/ensemble_classification_champion.pkl`. The artifact includes the model, scaler, feature columns, CV metrics, test metrics, and improvement percentage vs Sprint 4."
|
| 414 |
+
]
|
| 415 |
+
},
|
| 416 |
+
{
|
| 417 |
+
"cell_type": "markdown",
|
| 418 |
+
"id": "summary-cell",
|
| 419 |
+
"metadata": {},
|
| 420 |
+
"source": [
|
| 421 |
+
"---\n",
|
| 422 |
+
"## 5. Sprint Summary\n",
|
| 423 |
+
"\n",
|
| 424 |
+
"### 5.1 What Was Done\n",
|
| 425 |
+
"\n",
|
| 426 |
+
"| Component | Owner Track | Description |\n",
|
| 427 |
+
"|-----------|------------|-------------|\n",
|
| 428 |
+
"| `CorrelationFilter.py` | Shared | Custom sklearn transformer removing highly correlated features |\n",
|
| 429 |
+
"| Regression Ensemble | Regression track | 4 base models (Lasso, Ridge, RF, GB) Γ 4 bootstrap samples, simple + weighted averaging |\n",
|
| 430 |
+
"| Classification Ensemble | Classification track | Hard Voting, Soft Voting, Bagging (LDA), Stacking (LR meta) |\n",
|
| 431 |
+
"| Statistical Testing | Both tracks | Corrected resampled t-test (Nadeau & Bengio 2003) |\n",
|
| 432 |
+
"| Champion Deployment | Both tracks | Pickle artifacts saved if ensemble outperforms A4 champion |\n",
|
| 433 |
+
"\n",
|
| 434 |
+
"### 5.2 Key Design Decisions\n",
|
| 435 |
+
"\n",
|
| 436 |
+
"**Regression:** Bootstrap-based diversity was the primary source of independence between base models. Weighted averaging was used as the aggregation method with weights derived from CV-RΒ² scores, giving better-performing models proportionally more influence.\n",
|
| 437 |
+
"\n",
|
| 438 |
+
"**Classification:** A broader range of diversity strategies was explored β algorithm diversity (RF, LR, XGB, LGB, KNN, LDA), voting schemes (hard vs soft), and a stacking approach where a meta-learner replaces manual aggregation. Class imbalance was consistently addressed with `class_weight='balanced'`.\n",
|
| 439 |
+
"\n",
|
| 440 |
+
"**Statistical rigor:** The Nadeau-Bengio correction was applied in both tracks rather than a naive t-test, accounting for the overlap between cross-validation folds (correction factor β 1.25 for this dataset).\n",
|
| 441 |
+
"\n",
|
| 442 |
+
"### 5.3 Limitations and Next Steps\n",
|
| 443 |
+
"\n",
|
| 444 |
+
"- Feature subset diversity (angle-only, NASM-only) was defined but ultimately the final configuration used full features for all base models in the regression track. Future iterations could test whether feature-diverse ensembles further reduce error.\n",
|
| 445 |
+
"- The classification stacking approach used `passthrough=False`, meaning the meta-learner only sees predicted class probabilities, not the original features. Including raw features (`passthrough=True`) could be explored.\n",
|
| 446 |
+
"- More ensemble members (e.g., 8β10 base models) could be evaluated to assess the accuracy-variance tradeoff more thoroughly."
|
| 447 |
+
]
|
| 448 |
+
},
|
| 449 |
+
{
|
| 450 |
+
"cell_type": "code",
|
| 451 |
+
"execution_count": null,
|
| 452 |
+
"id": "cebc7f8e-92b4-4938-abeb-53c6e294a2cf",
|
| 453 |
+
"metadata": {},
|
| 454 |
+
"outputs": [],
|
| 455 |
+
"source": []
|
| 456 |
+
}
|
| 457 |
+
],
|
| 458 |
+
"metadata": {
|
| 459 |
+
"kernelspec": {
|
| 460 |
+
"display_name": "Python 3 (ipykernel)",
|
| 461 |
+
"language": "python",
|
| 462 |
+
"name": "python3"
|
| 463 |
+
},
|
| 464 |
+
"language_info": {
|
| 465 |
+
"codemirror_mode": {
|
| 466 |
+
"name": "ipython",
|
| 467 |
+
"version": 3
|
| 468 |
+
},
|
| 469 |
+
"file_extension": ".py",
|
| 470 |
+
"mimetype": "text/x-python",
|
| 471 |
+
"name": "python",
|
| 472 |
+
"nbconvert_exporter": "python",
|
| 473 |
+
"pygments_lexer": "ipython3",
|
| 474 |
+
"version": "3.12.8"
|
| 475 |
+
}
|
| 476 |
+
},
|
| 477 |
+
"nbformat": 4,
|
| 478 |
+
"nbformat_minor": 5
|
| 479 |
+
}
|