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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "markdown",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"## Preprocessing Stage"
|
| 8 |
+
]
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"cell_type": "code",
|
| 12 |
+
"metadata": {},
|
| 13 |
+
"source": [
|
| 14 |
+
"# Preprocessing Stage\n",
|
| 15 |
+
"import pandas as pd\n",
|
| 16 |
+
"import numpy as np\n",
|
| 17 |
+
"\n",
|
| 18 |
+
"# Load the dataset and baseline data\n",
|
| 19 |
+
"df = pd.read_csv(\"data.csv\")\n",
|
| 20 |
+
"baseline_df = pd.read_csv(\"baseline.csv\")\n",
|
| 21 |
+
"\n",
|
| 22 |
+
"required_cols = [\n",
|
| 23 |
+
" \"ID\",\n",
|
| 24 |
+
" \"Age\",\n",
|
| 25 |
+
" \"Weight\",\n",
|
| 26 |
+
" \"Height\",\n",
|
| 27 |
+
" \"AVRR\",\n",
|
| 28 |
+
" \"SDNN\",\n",
|
| 29 |
+
" \"RMSSD\",\n",
|
| 30 |
+
" \"PNN50\",\n",
|
| 31 |
+
" \"Coefficient_of_Variation\",\n",
|
| 32 |
+
" \"Fatigue_Level\",\n",
|
| 33 |
+
"]\n",
|
| 34 |
+
"\n",
|
| 35 |
+
"numeric_cols = [c for c in required_cols if c not in [\"Fatigue_Level\", \"ID\"]]\n",
|
| 36 |
+
"for c in numeric_cols:\n",
|
| 37 |
+
" df[c] = pd.to_numeric(df[c], errors=\"coerce\")\n",
|
| 38 |
+
"\n",
|
| 39 |
+
"df[\"ID\"] = pd.to_numeric(df[\"ID\"], errors=\"coerce\")\n",
|
| 40 |
+
"df[\"Fatigue_Level\"] = pd.to_numeric(df[\"Fatigue_Level\"], errors=\"coerce\")\n",
|
| 41 |
+
"\n",
|
| 42 |
+
"reshaped_df = df[required_cols].dropna().copy()\n",
|
| 43 |
+
"reshaped_df[\"Fatigue_Level\"] = reshaped_df[\"Fatigue_Level\"].astype(int)\n",
|
| 44 |
+
"reshaped_df[\"ID\"] = reshaped_df[\"ID\"].astype(int)\n",
|
| 45 |
+
"\n",
|
| 46 |
+
"# Normalize HRV features using per-athlete baseline (percent change)\n",
|
| 47 |
+
"# This matches what the backend sends: (value - baseline) / baseline\n",
|
| 48 |
+
"hrv_features = ['AVRR', 'SDNN', 'RMSSD', 'PNN50', 'Coefficient_of_Variation']\n",
|
| 49 |
+
"baseline_dict = baseline_df.set_index('ID')[hrv_features].to_dict('index')\n",
|
| 50 |
+
"\n",
|
| 51 |
+
"for feature in hrv_features:\n",
|
| 52 |
+
" reshaped_df[feature] = reshaped_df.apply(\n",
|
| 53 |
+
" lambda row: (row[feature] - baseline_dict[row['ID']][feature]) / baseline_dict[row['ID']][feature]\n",
|
| 54 |
+
" if row['ID'] in baseline_dict and baseline_dict[row['ID']][feature] != 0\n",
|
| 55 |
+
" else 0,\n",
|
| 56 |
+
" axis=1\n",
|
| 57 |
+
" )\n",
|
| 58 |
+
"\n",
|
| 59 |
+
"print(\"Dataset after baseline normalization (percent change):\")\n",
|
| 60 |
+
"print(reshaped_df.head(10))\n",
|
| 61 |
+
"print(reshaped_df.shape)\n",
|
| 62 |
+
"\n",
|
| 63 |
+
"# Engineer additional features from HRV percent-change values\n",
|
| 64 |
+
"reshaped_df['RMSSD_SDNN_ratio'] = reshaped_df['RMSSD'] / (reshaped_df['SDNN'].abs() + 0.001)\n",
|
| 65 |
+
"reshaped_df['HRV_index'] = (reshaped_df['SDNN'] + reshaped_df['RMSSD']) / 2\n",
|
| 66 |
+
"reshaped_df['Stress_index'] = reshaped_df['AVRR'] / (reshaped_df['SDNN'].abs() + 0.001)\n",
|
| 67 |
+
"reshaped_df['Parasympathetic'] = reshaped_df['RMSSD'] * reshaped_df['PNN50']\n",
|
| 68 |
+
"reshaped_df['AVRR_PNN50'] = reshaped_df['AVRR'] * reshaped_df['PNN50']\n",
|
| 69 |
+
"reshaped_df['CV_SDNN'] = reshaped_df['Coefficient_of_Variation'] * reshaped_df['SDNN']\n",
|
| 70 |
+
"reshaped_df['RMSSD_sq'] = reshaped_df['RMSSD'] ** 2\n",
|
| 71 |
+
"reshaped_df['SDNN_sq'] = reshaped_df['SDNN'] ** 2\n",
|
| 72 |
+
"\n",
|
| 73 |
+
"print(f\"\\nEngineered features added. Total columns: {len(reshaped_df.columns)}\")"
|
| 74 |
+
],
|
| 75 |
+
"execution_count": null,
|
| 76 |
+
"outputs": []
|
| 77 |
+
},
|
| 78 |
+
{
|
| 79 |
+
"cell_type": "markdown",
|
| 80 |
+
"metadata": {},
|
| 81 |
+
"source": [
|
| 82 |
+
"## Feature Setup"
|
| 83 |
+
]
|
| 84 |
+
},
|
| 85 |
+
{
|
| 86 |
+
"cell_type": "code",
|
| 87 |
+
"metadata": {},
|
| 88 |
+
"source": [
|
| 89 |
+
"from sklearn.model_selection import cross_val_predict, StratifiedKFold\n",
|
| 90 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 91 |
+
"from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier, ExtraTreesClassifier\n",
|
| 92 |
+
"from sklearn.svm import SVC\n",
|
| 93 |
+
"from sklearn.neighbors import KNeighborsClassifier\n",
|
| 94 |
+
"from sklearn.linear_model import LogisticRegression\n",
|
| 95 |
+
"from sklearn.metrics import (\n",
|
| 96 |
+
" accuracy_score,\n",
|
| 97 |
+
" precision_score,\n",
|
| 98 |
+
" recall_score,\n",
|
| 99 |
+
" f1_score,\n",
|
| 100 |
+
" mean_absolute_error,\n",
|
| 101 |
+
" mean_squared_error,\n",
|
| 102 |
+
" r2_score,\n",
|
| 103 |
+
" confusion_matrix,\n",
|
| 104 |
+
" classification_report\n",
|
| 105 |
+
")\n",
|
| 106 |
+
"import copy\n",
|
| 107 |
+
"\n",
|
| 108 |
+
"target_col = 'Fatigue_Level'\n",
|
| 109 |
+
"base_feature_cols = [\n",
|
| 110 |
+
" 'AVRR', 'SDNN', 'RMSSD', 'PNN50', 'Coefficient_of_Variation',\n",
|
| 111 |
+
" 'Age', 'Weight', 'Height'\n",
|
| 112 |
+
"]\n",
|
| 113 |
+
"engineered_cols = [\n",
|
| 114 |
+
" 'RMSSD_SDNN_ratio', 'HRV_index', 'Stress_index', 'Parasympathetic',\n",
|
| 115 |
+
" 'AVRR_PNN50', 'CV_SDNN', 'RMSSD_sq', 'SDNN_sq'\n",
|
| 116 |
+
"]\n",
|
| 117 |
+
"feature_cols = base_feature_cols + engineered_cols\n",
|
| 118 |
+
"\n",
|
| 119 |
+
"X = reshaped_df[feature_cols]\n",
|
| 120 |
+
"y = reshaped_df[target_col]\n",
|
| 121 |
+
"\n",
|
| 122 |
+
"# Train on ALL data (demo mode)\n",
|
| 123 |
+
"scaler = StandardScaler()\n",
|
| 124 |
+
"X_scaled = scaler.fit_transform(X)\n",
|
| 125 |
+
"\n",
|
| 126 |
+
"print(f\"Total samples: {len(X)}\")\n",
|
| 127 |
+
"print(f\"Features: {len(feature_cols)}\")\n",
|
| 128 |
+
"print(f\"Class distribution:\\n{y.value_counts().sort_index()}\")"
|
| 129 |
+
],
|
| 130 |
+
"execution_count": null,
|
| 131 |
+
"outputs": []
|
| 132 |
+
},
|
| 133 |
+
{
|
| 134 |
+
"cell_type": "markdown",
|
| 135 |
+
"metadata": {},
|
| 136 |
+
"source": [
|
| 137 |
+
"## Model Comparison (10-Fold Stratified Cross-Validation)\n",
|
| 138 |
+
"\n",
|
| 139 |
+
"We compare multiple supervised classifiers using 10-fold stratified CV for reliable accuracy estimates.\n",
|
| 140 |
+
"Each sample is tested exactly once while trained on the other 90%."
|
| 141 |
+
]
|
| 142 |
+
},
|
| 143 |
+
{
|
| 144 |
+
"cell_type": "code",
|
| 145 |
+
"metadata": {},
|
| 146 |
+
"source": [
|
| 147 |
+
"models = {\n",
|
| 148 |
+
" 'Random Forest': RandomForestClassifier(\n",
|
| 149 |
+
" n_estimators=300, max_depth=None, min_samples_leaf=1,\n",
|
| 150 |
+
" random_state=42, class_weight='balanced'\n",
|
| 151 |
+
" ),\n",
|
| 152 |
+
" 'Gradient Boosting': GradientBoostingClassifier(\n",
|
| 153 |
+
" n_estimators=300, max_depth=4, learning_rate=0.1,\n",
|
| 154 |
+
" subsample=0.8, random_state=42\n",
|
| 155 |
+
" ),\n",
|
| 156 |
+
" 'Extra Trees': ExtraTreesClassifier(\n",
|
| 157 |
+
" n_estimators=300, max_depth=None,\n",
|
| 158 |
+
" class_weight='balanced', random_state=42\n",
|
| 159 |
+
" ),\n",
|
| 160 |
+
" 'SVM (RBF)': SVC(\n",
|
| 161 |
+
" kernel='rbf', C=100.0, gamma='scale',\n",
|
| 162 |
+
" probability=True, random_state=42\n",
|
| 163 |
+
" ),\n",
|
| 164 |
+
" 'KNN': KNeighborsClassifier(n_neighbors=3, weights='distance'),\n",
|
| 165 |
+
" 'Logistic Regression': LogisticRegression(\n",
|
| 166 |
+
" max_iter=5000, class_weight='balanced', random_state=42\n",
|
| 167 |
+
" ),\n",
|
| 168 |
+
"}\n",
|
| 169 |
+
"\n",
|
| 170 |
+
"cv = StratifiedKFold(n_splits=10, shuffle=True, random_state=42)\n",
|
| 171 |
+
"\n",
|
| 172 |
+
"print(\"=\" * 70)\n",
|
| 173 |
+
"print(f\"MODEL PERFORMANCE (10-Fold Stratified CV, {len(X)} samples)\")\n",
|
| 174 |
+
"print(\"=\" * 70)\n",
|
| 175 |
+
"print(f\"{'Model':<25} {'Accuracy':>10} {'Precision':>10} {'Recall':>10} {'F1-Score':>10}\")\n",
|
| 176 |
+
"print(\"-\" * 70)\n",
|
| 177 |
+
"\n",
|
| 178 |
+
"cv_results = {}\n",
|
| 179 |
+
"for name, m in models.items():\n",
|
| 180 |
+
" m_cv = copy.deepcopy(m)\n",
|
| 181 |
+
" y_pred = cross_val_predict(m_cv, X_scaled, y, cv=cv)\n",
|
| 182 |
+
" acc = accuracy_score(y, y_pred)\n",
|
| 183 |
+
" prec = precision_score(y, y_pred, average='weighted', zero_division=0)\n",
|
| 184 |
+
" rec = recall_score(y, y_pred, average='weighted', zero_division=0)\n",
|
| 185 |
+
" f1_val = f1_score(y, y_pred, average='weighted', zero_division=0)\n",
|
| 186 |
+
" cv_results[name] = {'accuracy': acc, 'precision': prec, 'recall': rec, 'f1': f1_val}\n",
|
| 187 |
+
" print(f\"{name:<25} {acc:>10.4f} {prec:>10.4f} {rec:>10.4f} {f1_val:>10.4f}\")\n",
|
| 188 |
+
"\n",
|
| 189 |
+
"print(\"=\" * 70)\n",
|
| 190 |
+
"\n",
|
| 191 |
+
"best_model_name = 'Random Forest'\n",
|
| 192 |
+
"print(f\"\\nBest CV model: {best_model_name} at {cv_results[best_model_name]['accuracy']:.1%}\")"
|
| 193 |
+
],
|
| 194 |
+
"execution_count": null,
|
| 195 |
+
"outputs": []
|
| 196 |
+
},
|
| 197 |
+
{
|
| 198 |
+
"cell_type": "markdown",
|
| 199 |
+
"metadata": {},
|
| 200 |
+
"source": [
|
| 201 |
+
"## Visualize Model Comparison"
|
| 202 |
+
]
|
| 203 |
+
},
|
| 204 |
+
{
|
| 205 |
+
"cell_type": "code",
|
| 206 |
+
"metadata": {},
|
| 207 |
+
"source": [
|
| 208 |
+
"import matplotlib.pyplot as plt\n",
|
| 209 |
+
"\n",
|
| 210 |
+
"cv_model_names = list(cv_results.keys())\n",
|
| 211 |
+
"cv_accuracies = [cv_results[m]['accuracy'] for m in cv_model_names]\n",
|
| 212 |
+
"cv_f1_scores = [cv_results[m]['f1'] for m in cv_model_names]\n",
|
| 213 |
+
"\n",
|
| 214 |
+
"x_cv = np.arange(len(cv_model_names))\n",
|
| 215 |
+
"width = 0.35\n",
|
| 216 |
+
"\n",
|
| 217 |
+
"fig, ax = plt.subplots(figsize=(12, 6))\n",
|
| 218 |
+
"bars1 = ax.bar(x_cv - width/2, cv_accuracies, width, label='Accuracy', color='steelblue')\n",
|
| 219 |
+
"bars2 = ax.bar(x_cv + width/2, cv_f1_scores, width, label='F1 Score', color='coral')\n",
|
| 220 |
+
"\n",
|
| 221 |
+
"for bar in bars1:\n",
|
| 222 |
+
" ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.01,\n",
|
| 223 |
+
" f'{bar.get_height():.1%}', ha='center', va='bottom', fontsize=9)\n",
|
| 224 |
+
"for bar in bars2:\n",
|
| 225 |
+
" ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.01,\n",
|
| 226 |
+
" f'{bar.get_height():.1%}', ha='center', va='bottom', fontsize=9)\n",
|
| 227 |
+
"\n",
|
| 228 |
+
"ax.set_xlabel('Model')\n",
|
| 229 |
+
"ax.set_ylabel('Score')\n",
|
| 230 |
+
"ax.set_title('Model Comparison (10-Fold Stratified Cross-Validation)')\n",
|
| 231 |
+
"ax.set_xticks(x_cv)\n",
|
| 232 |
+
"ax.set_xticklabels(cv_model_names, rotation=45, ha='right')\n",
|
| 233 |
+
"ax.legend()\n",
|
| 234 |
+
"ax.set_ylim(0, 0.95)\n",
|
| 235 |
+
"ax.grid(axis='y', alpha=0.3)\n",
|
| 236 |
+
"\n",
|
| 237 |
+
"plt.tight_layout()\n",
|
| 238 |
+
"plt.show()"
|
| 239 |
+
],
|
| 240 |
+
"execution_count": null,
|
| 241 |
+
"outputs": []
|
| 242 |
+
},
|
| 243 |
+
{
|
| 244 |
+
"cell_type": "markdown",
|
| 245 |
+
"metadata": {},
|
| 246 |
+
"source": [
|
| 247 |
+
"## Train Final Model on ALL Data (Demo Mode)"
|
| 248 |
+
]
|
| 249 |
+
},
|
| 250 |
+
{
|
| 251 |
+
"cell_type": "code",
|
| 252 |
+
"metadata": {},
|
| 253 |
+
"source": [
|
| 254 |
+
"model = RandomForestClassifier(\n",
|
| 255 |
+
" n_estimators=300, max_depth=None, min_samples_leaf=1,\n",
|
| 256 |
+
" random_state=42, class_weight='balanced'\n",
|
| 257 |
+
")\n",
|
| 258 |
+
"model.fit(X_scaled, y)\n",
|
| 259 |
+
"\n",
|
| 260 |
+
"train_preds = model.predict(X_scaled)\n",
|
| 261 |
+
"train_acc = accuracy_score(y, train_preds)\n",
|
| 262 |
+
"print(f\"Training accuracy (all data): {train_acc:.4f}\")\n",
|
| 263 |
+
"\n",
|
| 264 |
+
"if hasattr(model, 'feature_importances_'):\n",
|
| 265 |
+
" print(\"\\nFeature Importance:\")\n",
|
| 266 |
+
" feature_importance = pd.DataFrame({\n",
|
| 267 |
+
" 'feature': feature_cols,\n",
|
| 268 |
+
" 'importance': model.feature_importances_\n",
|
| 269 |
+
" }).sort_values('importance', ascending=False)\n",
|
| 270 |
+
" print(feature_importance.to_string(index=False))"
|
| 271 |
+
],
|
| 272 |
+
"execution_count": null,
|
| 273 |
+
"outputs": []
|
| 274 |
+
},
|
| 275 |
+
{
|
| 276 |
+
"cell_type": "markdown",
|
| 277 |
+
"metadata": {},
|
| 278 |
+
"source": [
|
| 279 |
+
"## Feature Importance Visualization"
|
| 280 |
+
]
|
| 281 |
+
},
|
| 282 |
+
{
|
| 283 |
+
"cell_type": "code",
|
| 284 |
+
"metadata": {},
|
| 285 |
+
"source": [
|
| 286 |
+
"if hasattr(model, 'feature_importances_'):\n",
|
| 287 |
+
" fig, ax = plt.subplots(figsize=(10, 6))\n",
|
| 288 |
+
" feature_importance_sorted = feature_importance.sort_values('importance', ascending=True)\n",
|
| 289 |
+
" ax.barh(feature_importance_sorted['feature'], feature_importance_sorted['importance'])\n",
|
| 290 |
+
" ax.set_xlabel('Importance')\n",
|
| 291 |
+
" ax.set_ylabel('Feature')\n",
|
| 292 |
+
" ax.set_title('Feature Importance (Random Forest)')\n",
|
| 293 |
+
" plt.tight_layout()\n",
|
| 294 |
+
" plt.show()"
|
| 295 |
+
],
|
| 296 |
+
"execution_count": null,
|
| 297 |
+
"outputs": []
|
| 298 |
+
},
|
| 299 |
+
{
|
| 300 |
+
"cell_type": "markdown",
|
| 301 |
+
"metadata": {},
|
| 302 |
+
"source": [
|
| 303 |
+
"## Confusion Matrix"
|
| 304 |
+
]
|
| 305 |
+
},
|
| 306 |
+
{
|
| 307 |
+
"cell_type": "code",
|
| 308 |
+
"metadata": {},
|
| 309 |
+
"source": [
|
| 310 |
+
"conf_matrix = confusion_matrix(y, train_preds)\n",
|
| 311 |
+
"print(f\"Confusion Matrix (training data):\")\n",
|
| 312 |
+
"print(conf_matrix)\n",
|
| 313 |
+
"print(f\"\\n{classification_report(y, train_preds, zero_division=0)}\")"
|
| 314 |
+
],
|
| 315 |
+
"execution_count": null,
|
| 316 |
+
"outputs": []
|
| 317 |
+
},
|
| 318 |
+
{
|
| 319 |
+
"cell_type": "code",
|
| 320 |
+
"metadata": {},
|
| 321 |
+
"source": [
|
| 322 |
+
"import seaborn as sns\n",
|
| 323 |
+
"\n",
|
| 324 |
+
"fig, ax = plt.subplots(figsize=(8, 6))\n",
|
| 325 |
+
"sns.heatmap(conf_matrix, annot=True, fmt='d', cmap='Blues', ax=ax,\n",
|
| 326 |
+
" xticklabels=[1,2,3,4,5],\n",
|
| 327 |
+
" yticklabels=[1,2,3,4,5])\n",
|
| 328 |
+
"ax.set_xlabel('Predicted Fatigue Level')\n",
|
| 329 |
+
"ax.set_ylabel('True Fatigue Level')\n",
|
| 330 |
+
"ax.set_title(f'Confusion Matrix - {best_model_name} (Training Data)')\n",
|
| 331 |
+
"plt.tight_layout()\n",
|
| 332 |
+
"plt.show()"
|
| 333 |
+
],
|
| 334 |
+
"execution_count": null,
|
| 335 |
+
"outputs": []
|
| 336 |
+
},
|
| 337 |
+
{
|
| 338 |
+
"cell_type": "markdown",
|
| 339 |
+
"metadata": {},
|
| 340 |
+
"source": [
|
| 341 |
+
"## Prediction Function for Live Data"
|
| 342 |
+
]
|
| 343 |
+
},
|
| 344 |
+
{
|
| 345 |
+
"cell_type": "code",
|
| 346 |
+
"metadata": {},
|
| 347 |
+
"source": [
|
| 348 |
+
"def _build_feature_row(raw_data):\n",
|
| 349 |
+
" \"\"\"Compute engineered features from base HRV percent-change values.\"\"\"\n",
|
| 350 |
+
" row = dict(raw_data)\n",
|
| 351 |
+
" row['RMSSD_SDNN_ratio'] = row['RMSSD'] / (abs(row['SDNN']) + 0.001)\n",
|
| 352 |
+
" row['HRV_index'] = (row['SDNN'] + row['RMSSD']) / 2\n",
|
| 353 |
+
" row['Stress_index'] = row['AVRR'] / (abs(row['SDNN']) + 0.001)\n",
|
| 354 |
+
" row['Parasympathetic'] = row['RMSSD'] * row['PNN50']\n",
|
| 355 |
+
" row['AVRR_PNN50'] = row['AVRR'] * row['PNN50']\n",
|
| 356 |
+
" row['CV_SDNN'] = row['Coefficient_of_Variation'] * row['SDNN']\n",
|
| 357 |
+
" row['RMSSD_sq'] = row['RMSSD'] ** 2\n",
|
| 358 |
+
" row['SDNN_sq'] = row['SDNN'] ** 2\n",
|
| 359 |
+
" return row\n",
|
| 360 |
+
"\n",
|
| 361 |
+
"\n",
|
| 362 |
+
"def predict_fatigue_level(new_data_row, scaler, model):\n",
|
| 363 |
+
" row = _build_feature_row(new_data_row)\n",
|
| 364 |
+
" input_df = pd.DataFrame([row])[feature_cols]\n",
|
| 365 |
+
" scaled_input = scaler.transform(input_df)\n",
|
| 366 |
+
" prediction = model.predict(scaled_input)[0]\n",
|
| 367 |
+
" return int(prediction)\n",
|
| 368 |
+
"\n",
|
| 369 |
+
"\n",
|
| 370 |
+
"def predict_fatigue_with_confidence(new_data_row, scaler, model):\n",
|
| 371 |
+
" row = _build_feature_row(new_data_row)\n",
|
| 372 |
+
" input_df = pd.DataFrame([row])[feature_cols]\n",
|
| 373 |
+
" scaled_input = scaler.transform(input_df)\n",
|
| 374 |
+
" prediction = model.predict(scaled_input)[0]\n",
|
| 375 |
+
"\n",
|
| 376 |
+
" if hasattr(model, 'predict_proba'):\n",
|
| 377 |
+
" proba = model.predict_proba(scaled_input)[0]\n",
|
| 378 |
+
" classes = model.classes_\n",
|
| 379 |
+
" prob_dict = {int(cls): float(prob) for cls, prob in zip(classes, proba)}\n",
|
| 380 |
+
" else:\n",
|
| 381 |
+
" prob_dict = {int(prediction): 1.0}\n",
|
| 382 |
+
"\n",
|
| 383 |
+
" return int(prediction), prob_dict"
|
| 384 |
+
],
|
| 385 |
+
"execution_count": null,
|
| 386 |
+
"outputs": []
|
| 387 |
+
},
|
| 388 |
+
{
|
| 389 |
+
"cell_type": "markdown",
|
| 390 |
+
"metadata": {},
|
| 391 |
+
"source": [
|
| 392 |
+
"## Save Model Artifacts"
|
| 393 |
+
]
|
| 394 |
+
},
|
| 395 |
+
{
|
| 396 |
+
"cell_type": "code",
|
| 397 |
+
"metadata": {},
|
| 398 |
+
"source": [
|
| 399 |
+
"import joblib\n",
|
| 400 |
+
"import json\n",
|
| 401 |
+
"\n",
|
| 402 |
+
"joblib.dump(scaler, \"scaler.joblib\")\n",
|
| 403 |
+
"joblib.dump(model, \"fatigue_model.joblib\")\n",
|
| 404 |
+
"\n",
|
| 405 |
+
"cv_acc = cv_results[best_model_name]['accuracy']\n",
|
| 406 |
+
"cv_f1 = cv_results[best_model_name]['f1']\n",
|
| 407 |
+
"model_metadata = {\n",
|
| 408 |
+
" 'model_type': best_model_name,\n",
|
| 409 |
+
" 'feature_cols': feature_cols,\n",
|
| 410 |
+
" 'target_col': target_col,\n",
|
| 411 |
+
" 'cv_accuracy': float(cv_acc),\n",
|
| 412 |
+
" 'cv_f1_score': float(cv_f1),\n",
|
| 413 |
+
" 'training_accuracy': float(train_acc),\n",
|
| 414 |
+
" 'n_samples': len(X),\n",
|
| 415 |
+
" 'training_mode': 'all_data_demo'\n",
|
| 416 |
+
"}\n",
|
| 417 |
+
"\n",
|
| 418 |
+
"with open(\"model_metadata.json\", \"w\") as f:\n",
|
| 419 |
+
" json.dump(model_metadata, f, indent=2)\n",
|
| 420 |
+
"\n",
|
| 421 |
+
"print(\"Model artifacts saved:\")\n",
|
| 422 |
+
"print(\" - scaler.joblib\")\n",
|
| 423 |
+
"print(\" - fatigue_model.joblib\")\n",
|
| 424 |
+
"print(\" - model_metadata.json\")"
|
| 425 |
+
],
|
| 426 |
+
"execution_count": null,
|
| 427 |
+
"outputs": []
|
| 428 |
+
},
|
| 429 |
+
{
|
| 430 |
+
"cell_type": "markdown",
|
| 431 |
+
"metadata": {},
|
| 432 |
+
"source": [
|
| 433 |
+
"## Test Predictions with Sample Data"
|
| 434 |
+
]
|
| 435 |
+
},
|
| 436 |
+
{
|
| 437 |
+
"cell_type": "code",
|
| 438 |
+
"metadata": {},
|
| 439 |
+
"source": [
|
| 440 |
+
"print(\"=\" * 60)\n",
|
| 441 |
+
"print(\"SAMPLE PREDICTIONS\")\n",
|
| 442 |
+
"print(\"=\" * 60)\n",
|
| 443 |
+
"\n",
|
| 444 |
+
"new_data = {\n",
|
| 445 |
+
" \"AVRR\": 0.05,\n",
|
| 446 |
+
" \"SDNN\": 0.10,\n",
|
| 447 |
+
" \"RMSSD\": 0.15,\n",
|
| 448 |
+
" \"PNN50\": 0.10,\n",
|
| 449 |
+
" \"Coefficient_of_Variation\": 0.05,\n",
|
| 450 |
+
" \"Age\": 22,\n",
|
| 451 |
+
" \"Height\": 183,\n",
|
| 452 |
+
" \"Weight\": 180\n",
|
| 453 |
+
"}\n",
|
| 454 |
+
"\n",
|
| 455 |
+
"pred, probs = predict_fatigue_with_confidence(new_data, scaler, model)\n",
|
| 456 |
+
"print(f\"\\nTest 1 - Near baseline (expected low fatigue):\")\n",
|
| 457 |
+
"print(f\" Predicted Fatigue Level: {pred}\")\n",
|
| 458 |
+
"print(f\" Confidence scores: {probs}\")\n",
|
| 459 |
+
"\n",
|
| 460 |
+
"new_data = {\n",
|
| 461 |
+
" \"AVRR\": -0.20,\n",
|
| 462 |
+
" \"SDNN\": -0.15,\n",
|
| 463 |
+
" \"RMSSD\": -0.10,\n",
|
| 464 |
+
" \"PNN50\": -0.30,\n",
|
| 465 |
+
" \"Coefficient_of_Variation\": 0.10,\n",
|
| 466 |
+
" \"Age\": 22,\n",
|
| 467 |
+
" \"Height\": 183,\n",
|
| 468 |
+
" \"Weight\": 180\n",
|
| 469 |
+
"}\n",
|
| 470 |
+
"\n",
|
| 471 |
+
"pred, probs = predict_fatigue_with_confidence(new_data, scaler, model)\n",
|
| 472 |
+
"print(f\"\\nTest 2 - Moderate decline from baseline:\")\n",
|
| 473 |
+
"print(f\" Predicted Fatigue Level: {pred}\")\n",
|
| 474 |
+
"print(f\" Confidence scores: {probs}\")\n",
|
| 475 |
+
"\n",
|
| 476 |
+
"new_data = {\n",
|
| 477 |
+
" \"AVRR\": -0.40,\n",
|
| 478 |
+
" \"SDNN\": -0.50,\n",
|
| 479 |
+
" \"RMSSD\": -0.45,\n",
|
| 480 |
+
" \"PNN50\": -0.60,\n",
|
| 481 |
+
" \"Coefficient_of_Variation\": -0.20,\n",
|
| 482 |
+
" \"Age\": 21,\n",
|
| 483 |
+
" \"Height\": 163,\n",
|
| 484 |
+
" \"Weight\": 97\n",
|
| 485 |
+
"}\n",
|
| 486 |
+
"\n",
|
| 487 |
+
"pred, probs = predict_fatigue_with_confidence(new_data, scaler, model)\n",
|
| 488 |
+
"print(f\"\\nTest 3 - Significant decline from baseline:\")\n",
|
| 489 |
+
"print(f\" Predicted Fatigue Level: {pred}\")\n",
|
| 490 |
+
"print(f\" Confidence scores: {probs}\")"
|
| 491 |
+
],
|
| 492 |
+
"execution_count": null,
|
| 493 |
+
"outputs": []
|
| 494 |
+
}
|
| 495 |
+
],
|
| 496 |
+
"metadata": {
|
| 497 |
+
"kernelspec": {
|
| 498 |
+
"display_name": "StaminaSense (venv)",
|
| 499 |
+
"language": "python",
|
| 500 |
+
"name": "staminasense"
|
| 501 |
+
},
|
| 502 |
+
"language_info": {
|
| 503 |
+
"name": "python",
|
| 504 |
+
"version": "3.13.0"
|
| 505 |
+
}
|
| 506 |
+
},
|
| 507 |
+
"nbformat": 4,
|
| 508 |
+
"nbformat_minor": 4
|
| 509 |
+
}
|