classification¶
Model training and evaluation for glaucoma classification.
Overview¶
This module handles:
- Bootstrap evaluation with 1000 iterations
- STRATOS-compliant metric computation
- Multiple classifier support (CatBoost default)
- Subject-wise analysis
Main Entry Point¶
flow_classification
¶
flow_classification
¶
Main classification flow for glaucoma screening from PLR features.
Orchestrates the classification pipeline including feature-based and time-series classification approaches. Initializes MLflow experiment and delegates to subflows.
| PARAMETER | DESCRIPTION |
|---|---|
cfg
|
Hydra configuration with PREFECT flow names and settings.
TYPE:
|
Notes
Time-series classification is currently disabled as it showed limited promise after refactoring.
Source code in src/classification/flow_classification.py
Bootstrap Evaluation¶
bootstrap_evaluation
¶
prepare_for_bootstrap
¶
Prepare data arrays for bootstrap evaluation.
Sets up index arrays for stratified bootstrap resampling. The train split will be resampled into new train/val splits while test remains untouched.
| PARAMETER | DESCRIPTION |
|---|---|
dict_arrays
|
Dictionary containing: - x_train, y_train: Training features and labels - x_test, y_test: Test features and labels - subject_codes_train, subject_codes_test: Subject identifiers
TYPE:
|
method_cfg
|
Bootstrap configuration with 'join_test_and_train' option.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Updated dict_arrays with 'X_idxs' array for bootstrap sampling. |
References
- https://machinelearningmastery.com/calculate-bootstrap-confidence-intervals-machine-learning-results-python/
Source code in src/classification/bootstrap_evaluation.py
select_bootstrap_samples
¶
Select bootstrap samples for a single iteration.
Performs stratified bootstrap resampling to create new train/val splits from the original training data.
| PARAMETER | DESCRIPTION |
|---|---|
dict_arrays
|
Data arrays including X_idxs for sampling.
TYPE:
|
n_samples
|
Number of samples to draw for training.
TYPE:
|
method_cfg
|
Bootstrap configuration.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Dictionary with resampled train/val data arrays. |
Source code in src/classification/bootstrap_evaluation.py
splits_as_dicts
¶
Convert flat array dictionary to nested split-based structure.
| PARAMETER | DESCRIPTION |
|---|---|
dict_arrays_iter
|
Flat dictionary with keys like 'x_train', 'y_train', etc.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Nested dictionary with structure: {split: {'X': ..., 'y': ..., 'w': ..., 'codes': ...}} |
Source code in src/classification/bootstrap_evaluation.py
check_bootstrap_iteration_quality
¶
Validate that bootstrap iteration used all expected samples.
Checks that train/val splits used all subject codes from the original training data and that test samples match expected count.
| PARAMETER | DESCRIPTION |
|---|---|
metrics_iter
|
Metrics collected from all bootstrap iterations.
TYPE:
|
dict_arrays_iter
|
Data arrays from the current iteration.
TYPE:
|
dict_arrays
|
Original data arrays before bootstrap resampling.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
AssertionError
|
If train/val codes don't match original or test samples count is wrong. |
Source code in src/classification/bootstrap_evaluation.py
get_ensemble_stats
¶
get_ensemble_stats(
metrics_iter,
dict_arrays,
method_cfg,
call_from: str = None,
sort_list: bool = True,
verbose: bool = True,
)
Compute aggregate statistics from bootstrap iterations.
Aggregates per-iteration metrics into final statistics including: - Mean and CI for AUROC, Brier, etc. - Per-subject prediction statistics - Global uncertainty metrics
| PARAMETER | DESCRIPTION |
|---|---|
metrics_iter
|
Per-iteration metrics from bootstrap.
TYPE:
|
dict_arrays
|
Original data arrays.
TYPE:
|
method_cfg
|
Bootstrap configuration.
TYPE:
|
call_from
|
Caller identifier for logging.
TYPE:
|
sort_list
|
Sort subject statistics.
TYPE:
|
verbose
|
Enable verbose logging.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple
|
(metrics_stats, subjectwise_stats, subject_global_stats) |
Source code in src/classification/bootstrap_evaluation.py
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 | |
append_models_to_list_for_mlflow
¶
Add a trained model to the list for MLflow logging.
Handles special cases like moving TabM models from GPU to CPU to avoid memory issues during serialization.
| PARAMETER | DESCRIPTION |
|---|---|
models
|
List of trained models from previous iterations.
TYPE:
|
model
|
The trained model from current iteration.
TYPE:
|
model_name
|
Name of the classifier (e.g., 'TabM', 'CatBoost').
TYPE:
|
i
|
Current bootstrap iteration index.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list
|
Updated list of models with the new model appended. |
Source code in src/classification/bootstrap_evaluation.py
bootstrap_evaluator
¶
bootstrap_evaluator(
model_name: str,
run_name: str,
dict_arrays: dict,
best_params,
cls_model_cfg: DictConfig,
method_cfg: DictConfig,
hparam_cfg: DictConfig,
cfg: DictConfig,
debug_aggregation: bool = False,
)
Run bootstrap evaluation for classifier performance estimation.
Performs n_iterations of bootstrap resampling to estimate: - STRATOS-compliant metrics (AUROC, calibration, clinical utility) - Confidence intervals via percentile bootstrap - Per-subject prediction uncertainty
| PARAMETER | DESCRIPTION |
|---|---|
model_name
|
Classifier name (e.g., 'CatBoost', 'XGBoost').
TYPE:
|
run_name
|
MLflow run name.
TYPE:
|
dict_arrays
|
Data arrays with train/test splits.
TYPE:
|
best_params
|
Best hyperparameters from optimization.
TYPE:
|
cls_model_cfg
|
Classifier model configuration.
TYPE:
|
method_cfg
|
Bootstrap configuration with 'n_iterations', 'data_ratio'.
TYPE:
|
hparam_cfg
|
Hyperparameter configuration.
TYPE:
|
cfg
|
Full Hydra configuration.
TYPE:
|
debug_aggregation
|
Enable debug logging for metric aggregation.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple
|
(models, results_dict) where: - models: List of trained models (one per iteration) - results_dict: Contains metrics_iter, metrics_stats, subjectwise_stats, subject_global_stats |
Notes
Uses stratified resampling to maintain class balance across iterations. Test set remains fixed; only train is resampled into train/val.
Source code in src/classification/bootstrap_evaluation.py
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 | |
Metrics and Statistics¶
stats_metric_utils
¶
interpolation_wrapper
¶
interpolation_wrapper(
x: ndarray,
y: ndarray,
x_new: ndarray,
n_samples: int,
metric: str,
_kind: str = "linear",
) -> tuple[ndarray, ndarray]
Interpolate metric curves to a fixed number of points.
| PARAMETER | DESCRIPTION |
|---|---|
x
|
Original x values.
TYPE:
|
y
|
Original y values.
TYPE:
|
x_new
|
New x values to interpolate to.
TYPE:
|
n_samples
|
Number of samples for interpolation.
TYPE:
|
metric
|
Metric name ('AUROC', 'AUPR', 'calibration_curve').
TYPE:
|
_kind
|
Interpolation method (currently unused).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple
|
(x_new, y_new) interpolated arrays. |
Source code in src/classification/stats_metric_utils.py
bootstrap_get_array_axis_names
¶
Get x and y axis names for a given metric curve.
| PARAMETER | DESCRIPTION |
|---|---|
metric
|
Metric name ('AUROC', 'AUPR', 'calibration_curve').
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple
|
(x_name, y_name) axis names for the metric. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If unknown metric specified. |
Source code in src/classification/stats_metric_utils.py
bootstrap_interpolate_metric_arrays
¶
bootstrap_interpolate_metric_arrays(
arrays: dict[str, Any], n_samples: int = 200
) -> dict[str, Any]
Interpolate all metric arrays to a fixed number of samples.
Enables aggregation of ROC/PR curves across bootstrap iterations by standardizing the x-axis.
| PARAMETER | DESCRIPTION |
|---|---|
arrays
|
Dictionary of metric arrays with varying lengths.
TYPE:
|
n_samples
|
Number of points for interpolation.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Dictionary of interpolated metric arrays. |
Source code in src/classification/stats_metric_utils.py
bootstrap_aggregate_arrays
¶
bootstrap_aggregate_arrays(
arrays: dict[str, Any],
metrics_per_split: dict[str, Any],
main_key: str = "metrics",
) -> dict[str, Any]
Aggregate array metrics across bootstrap iterations.
Stacks interpolated curves (ROC, PR, calibration) horizontally for later statistical analysis.
| PARAMETER | DESCRIPTION |
|---|---|
arrays
|
Interpolated metric arrays from current iteration.
TYPE:
|
metrics_per_split
|
Accumulated metrics from previous iterations.
TYPE:
|
main_key
|
Key for storing metrics in output dict.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Updated metrics_per_split with new arrays appended. |
Source code in src/classification/stats_metric_utils.py
bootstrap_aggregate_scalars
¶
bootstrap_aggregate_scalars(
metrics_dict: dict[str, Any],
metrics_per_split: dict[str, Any],
) -> dict[str, Any]
Aggregate scalar metrics across bootstrap iterations.
Appends scalar values (AUROC, Brier, etc.) to lists for later statistical analysis.
| PARAMETER | DESCRIPTION |
|---|---|
metrics_dict
|
Metrics from current iteration.
TYPE:
|
metrics_per_split
|
Accumulated metrics from previous iterations.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Updated metrics_per_split with new scalars appended. |
Source code in src/classification/stats_metric_utils.py
bootstrap_aggregate_by_subject_per_split
¶
bootstrap_aggregate_by_subject_per_split(
arrays: dict[str, Any],
metrics_per_split: dict[str, Any],
codes_per_split: ndarray,
main_key: str,
subkey: str = "predictions",
is_init_with_correct_codes: bool = False,
) -> dict[str, Any]
Aggregate predictions by subject code across bootstrap iterations.
Used for train/val splits where subjects vary between iterations due to resampling. Stores predictions keyed by subject code.
| PARAMETER | DESCRIPTION |
|---|---|
arrays
|
Predictions from current iteration.
TYPE:
|
metrics_per_split
|
Accumulated predictions from previous iterations.
TYPE:
|
codes_per_split
|
Subject codes for current iteration.
TYPE:
|
main_key
|
Key for storing predictions.
TYPE:
|
subkey
|
Subkey within arrays.
TYPE:
|
is_init_with_correct_codes
|
If True, expects codes to already exist.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Updated metrics_per_split with predictions aggregated by subject. |
Source code in src/classification/stats_metric_utils.py
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 | |
bootstrap_aggregate_subjects
¶
bootstrap_aggregate_subjects(
metrics_per_split: dict[str, Any],
codes_per_split: ndarray,
split: str,
preds: dict[str, ndarray],
) -> dict[str, Any]
Aggregate subject predictions based on split type.
For test split, predictions are stacked as arrays (same subjects each iter). For train/val, predictions are stored in dicts keyed by subject code.
| PARAMETER | DESCRIPTION |
|---|---|
metrics_per_split
|
Accumulated metrics and predictions.
TYPE:
|
codes_per_split
|
Subject codes for current split.
TYPE:
|
split
|
Split name ('train', 'val', 'test').
TYPE:
|
preds
|
Predictions from current iteration.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Updated metrics_per_split with aggregated predictions. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If unknown split specified. |
Source code in src/classification/stats_metric_utils.py
bootstrap_metrics_per_split
¶
bootstrap_metrics_per_split(
X: ndarray,
y_true: ndarray,
preds: dict[str, ndarray],
model: Any,
model_name: str,
metrics_per_split: dict[str, Any],
codes_per_split: ndarray,
method_cfg: DictConfig,
cfg: DictConfig,
split: str,
skip_mlflow: bool = False,
recompute_for_ensemble: bool = False,
) -> dict[str, Any]
Compute and aggregate metrics for a single split in bootstrap iteration.
Calculates classifier metrics, calibration metrics, interpolates curves, and aggregates all results across iterations.
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Feature matrix for the split.
TYPE:
|
y_true
|
True labels.
TYPE:
|
preds
|
Model predictions with 'y_pred', 'y_pred_proba'.
TYPE:
|
model
|
Trained classifier model.
TYPE:
|
model_name
|
Name of the classifier.
TYPE:
|
metrics_per_split
|
Accumulated metrics from previous iterations.
TYPE:
|
codes_per_split
|
Subject codes for this split.
TYPE:
|
method_cfg
|
Bootstrap method configuration.
TYPE:
|
cfg
|
Full Hydra configuration.
TYPE:
|
split
|
Split name ('train', 'val', 'test').
TYPE:
|
skip_mlflow
|
Skip MLflow logging.
TYPE:
|
recompute_for_ensemble
|
If True, skip subject aggregation (already done).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Updated metrics_per_split with new iteration's results. |
Source code in src/classification/stats_metric_utils.py
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 | |
bootstrap_predict
¶
bootstrap_predict(
model: Any,
X: ndarray,
i: int,
split: str,
debug_aggregation: bool = True,
) -> dict[str, ndarray]
Get predictions from model for bootstrap iteration.
| PARAMETER | DESCRIPTION |
|---|---|
model
|
Trained classifier with predict_proba() method.
TYPE:
|
X
|
Feature matrix.
TYPE:
|
i
|
Bootstrap iteration index.
TYPE:
|
split
|
Split name for logging.
TYPE:
|
debug_aggregation
|
If True, log debug info for test split.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Predictions with 'y_pred_proba' and 'y_pred' keys. |
| RAISES | DESCRIPTION |
|---|---|
Exception
|
If model prediction fails. |
Source code in src/classification/stats_metric_utils.py
tabm_demodata_fix
¶
Fix TabM prediction array length mismatch on demo data.
| PARAMETER | DESCRIPTION |
|---|---|
preds
|
Predictions dictionary with 'y_pred_proba', 'y_pred', 'label'.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Fixed predictions dictionary. |
| RAISES | DESCRIPTION |
|---|---|
RuntimeError
|
If prediction length doesn't match expected ratio. |
Source code in src/classification/stats_metric_utils.py
bootstrap_metrics
¶
bootstrap_metrics(
i: int,
model: Any,
dict_splits: dict[str, dict[str, ndarray]],
metrics: dict[str, dict],
results_per_iter: dict[str, dict] | None,
method_cfg: DictConfig,
cfg: DictConfig,
debug_aggregation: bool = False,
model_name: str | None = None,
) -> dict[str, dict]
i: int which bootstrap iteration, or a submodel of the ensemble dict_splits: dict test: dict X: np.ndarray y: np.ndarray w: np.ndarray codes: np.ndarray metrics: dict, e.g. {} on i=0 results_per_iter, e.g. None on i=0
Source code in src/classification/stats_metric_utils.py
610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 | |
get_p_from_alpha
¶
Convert confidence level alpha to percentile value.
| PARAMETER | DESCRIPTION |
|---|---|
alpha
|
Confidence level (e.g., 0.95 for 95% CI).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
Percentile value for lower bound (e.g., 2.5 for alpha=0.95). |
Source code in src/classification/stats_metric_utils.py
bootstrap_scalar_stats_per_metric
¶
bootstrap_scalar_stats_per_metric(
values: ndarray, method_cfg: DictConfig
) -> dict[str, int | float | ndarray]
Compute summary statistics for a scalar metric across bootstrap iterations.
| PARAMETER | DESCRIPTION |
|---|---|
values
|
Array of metric values from all iterations.
TYPE:
|
method_cfg
|
Bootstrap configuration with 'alpha_CI'.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Statistics with 'n', 'mean', 'std', 'ci' keys. |
Source code in src/classification/stats_metric_utils.py
convert_inf_to_nan
¶
Replace infinite values with NaN in array.
| PARAMETER | DESCRIPTION |
|---|---|
values
|
2D array possibly containing inf values.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
Array with inf replaced by NaN. |
| RAISES | DESCRIPTION |
|---|---|
NotImplementedError
|
If array is not 2D. |
Source code in src/classification/stats_metric_utils.py
get_array_stats_per_metric
¶
get_array_stats_per_metric(
values: ndarray,
method_cfg: DictConfig,
inf_to_nan: bool = True,
) -> dict[str, ndarray]
Compute summary statistics for array metrics across bootstrap iterations.
| PARAMETER | DESCRIPTION |
|---|---|
values
|
2D array of shape (curve_length, n_iterations).
TYPE:
|
method_cfg
|
Bootstrap configuration with 'alpha_CI'.
TYPE:
|
inf_to_nan
|
Convert infinite values to NaN before computing stats.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Statistics with 'mean', 'std', 'ci' arrays. |
Source code in src/classification/stats_metric_utils.py
bootstrap_scalar_stats
¶
bootstrap_scalar_stats(
metrics_per_split: dict[str, ndarray],
method_cfg: DictConfig,
split: str,
) -> dict[str, dict[str, int | float | ndarray]]
Compute statistics for all scalar metrics in a split.
| PARAMETER | DESCRIPTION |
|---|---|
metrics_per_split
|
Accumulated scalar metrics per metric name.
TYPE:
|
method_cfg
|
Bootstrap configuration.
TYPE:
|
split
|
Split name (unused, for signature compatibility).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Statistics per metric with mean, std, CI. |
Source code in src/classification/stats_metric_utils.py
bootstrap_array_stats
¶
bootstrap_array_stats(
metrics_per_split: dict[str, dict[str, ndarray]],
method_cfg: DictConfig,
) -> dict[str, dict[str, dict[str, ndarray]]]
Compute statistics for all array metrics (curves) in a split.
| PARAMETER | DESCRIPTION |
|---|---|
metrics_per_split
|
Accumulated array metrics per metric name.
TYPE:
|
method_cfg
|
Bootstrap configuration.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Statistics per metric and variable with mean, std, CI arrays. |
Source code in src/classification/stats_metric_utils.py
check_bootstrap_probability_predictions
¶
Validate that bootstrap predictions vary across iterations.
Warns if all predictions are identical, which indicates a bug in model retraining or bootstrap resampling.
| PARAMETER | DESCRIPTION |
|---|---|
metrics
|
Accumulated metrics with predictions per split.
TYPE:
|
Source code in src/classification/stats_metric_utils.py
bootstrap_compute_stats
¶
bootstrap_compute_stats(
metrics: dict[str, dict],
method_cfg: DictConfig,
call_from: str,
verbose: bool = True,
) -> dict[str, dict[str, dict]]
Compute final statistics from all bootstrap iterations.
Aggregates scalar and array metrics into mean, std, and CI values.
| PARAMETER | DESCRIPTION |
|---|---|
metrics
|
Accumulated metrics from all bootstrap iterations.
TYPE:
|
method_cfg
|
Bootstrap configuration.
TYPE:
|
call_from
|
Caller identifier for conditional checks.
TYPE:
|
verbose
|
Enable logging.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Statistics per split with scalars and arrays. |
Source code in src/classification/stats_metric_utils.py
bootstrap_subject_stats_numpy_array
¶
bootstrap_subject_stats_numpy_array(
preds_per_key: ndarray, labels: ndarray, key: str
) -> dict[str, ndarray]
Compute per-subject statistics from 2D prediction array.
Used for test split where subjects are consistent across iterations.
| PARAMETER | DESCRIPTION |
|---|---|
preds_per_key
|
Predictions of shape (n_subjects, n_iterations).
TYPE:
|
labels
|
True labels (unused, for signature consistency).
TYPE:
|
key
|
Prediction key (unused, for signature consistency).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Statistics with 'mean' and 'std' arrays (n_subjects,). |
Source code in src/classification/stats_metric_utils.py
aggregate_dict_subjects
¶
aggregate_dict_subjects(
dict_out: dict[str, ndarray],
stats_per_code: dict[str, ndarray],
) -> dict[str, ndarray]
Aggregate subject statistics by horizontal stacking.
| PARAMETER | DESCRIPTION |
|---|---|
dict_out
|
Accumulated statistics.
TYPE:
|
stats_per_code
|
Statistics for a single subject code.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Updated statistics with new subject appended. |
Source code in src/classification/stats_metric_utils.py
bootstrap_subject_stats_dict
¶
bootstrap_subject_stats_dict(
preds_per_key: dict[str, list[float]],
labels: ndarray,
_codes_train: ndarray,
key: str,
split: str = "train",
verbose: bool = True,
check_preds: bool = False,
) -> tuple[dict[str, ndarray], dict[str, Any]]
Compute per-subject statistics from dictionary of predictions.
Used for train/val splits where predictions are stored by subject code. Also computes uncertainty quantification for probability predictions.
| PARAMETER | DESCRIPTION |
|---|---|
preds_per_key
|
Predictions keyed by subject code.
TYPE:
|
labels
|
True labels for subjects.
TYPE:
|
_codes_train
|
Subject codes for ordering (currently unused).
TYPE:
|
key
|
Prediction key (e.g., 'y_pred_proba').
TYPE:
|
split
|
Split name for logging.
TYPE:
|
verbose
|
Enable logging.
TYPE:
|
check_preds
|
Validate predictions vary per subject.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple
|
(stats_dict, uq_dict) with per-subject statistics and uncertainty. |
Source code in src/classification/stats_metric_utils.py
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 | |
sort_dict_keys_based_on_list
¶
sort_dict_keys_based_on_list(
dict_to_sort: dict[str, Any],
list_to_sort_by: list[str],
sort_list: bool = True,
) -> dict[str, Any]
Sort dictionary keys to match a reference list order.
| PARAMETER | DESCRIPTION |
|---|---|
dict_to_sort
|
Dictionary to reorder.
TYPE:
|
list_to_sort_by
|
Reference list defining key order.
TYPE:
|
sort_list
|
If True, reorder to match list. If False, just sort alphabetically.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Reordered dictionary. |
| RAISES | DESCRIPTION |
|---|---|
Exception
|
If keys don't match reference list. |
Source code in src/classification/stats_metric_utils.py
bootstrap_check_that_samples_different
¶
Verify predictions vary across bootstrap iterations per subject.
| PARAMETER | DESCRIPTION |
|---|---|
preds_per_key
|
Predictions keyed by subject code.
TYPE:
|
key
|
Prediction type key.
TYPE:
|
check_preds
|
If True, perform detailed validation.
TYPE:
|
Source code in src/classification/stats_metric_utils.py
check_indiv_code_for_different_preds
¶
Check if predictions for a subject vary across iterations.
Note: May raise false alarms for garbage input data where model consistently outputs same predictions.
| PARAMETER | DESCRIPTION |
|---|---|
subject_code
|
Subject identifier.
TYPE:
|
preds_per_code
|
List of predictions for this subject across iterations.
TYPE:
|
key
|
Prediction type (e.g., 'y_pred_proba').
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If all predictions are identical for probability predictions. |
Source code in src/classification/stats_metric_utils.py
bootstrap_compute_subject_stats
¶
bootstrap_compute_subject_stats(
metrics_iter,
dict_arrays,
method_cfg,
sort_list: bool = True,
call_from: str = None,
verbose: bool = True,
)
Compute per-subject statistics from bootstrap iterations.
Aggregates predictions across bootstrap iterations to compute mean predictions and uncertainty per subject.
| PARAMETER | DESCRIPTION |
|---|---|
metrics_iter
|
Accumulated metrics from all iterations.
TYPE:
|
dict_arrays
|
Original data arrays with labels and codes.
TYPE:
|
method_cfg
|
Bootstrap configuration.
TYPE:
|
sort_list
|
Sort results to match original code order.
TYPE:
|
call_from
|
Caller identifier for special handling.
TYPE:
|
verbose
|
Enable logging.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Per-subject statistics per split. |
Source code in src/classification/stats_metric_utils.py
1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 | |
global_subject_stats
¶
global_subject_stats(
values: ndarray,
labels: ndarray,
key: str,
variable: str,
method_cfg: DictConfig,
)
Compute global statistics stratified by class label.
| PARAMETER | DESCRIPTION |
|---|---|
values
|
Per-subject values to aggregate.
TYPE:
|
labels
|
Class labels for stratification.
TYPE:
|
key
|
Prediction key (unused, for logging).
TYPE:
|
variable
|
Variable name (unused, for logging).
TYPE:
|
method_cfg
|
Bootstrap configuration.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Statistics per class label with mean, std, CI. |
Source code in src/classification/stats_metric_utils.py
get_labels_and_codes
¶
Get labels and codes for a split, handling bootstrap vs ensemble cases.
| PARAMETER | DESCRIPTION |
|---|---|
split
|
Split name ('train', 'val', 'test').
TYPE:
|
dict_arrays
|
Data arrays with labels and codes.
TYPE:
|
call_from
|
Caller identifier for special handling.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple
|
(labels, codes) arrays for the split. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If unknown split specified. |
Source code in src/classification/stats_metric_utils.py
bootstrap_compute_global_subject_stats
¶
Compute global subject-level statistics across all subjects.
Aggregates per-subject statistics (e.g., mean probability, uncertainty) into population-level summaries stratified by class.
| PARAMETER | DESCRIPTION |
|---|---|
subjectwise_stats
|
Per-subject statistics from bootstrap_compute_subject_stats.
TYPE:
|
method_cfg
|
Bootstrap configuration.
TYPE:
|
verbose
|
Enable logging.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Global statistics per split, key, variable, and class. |
Source code in src/classification/stats_metric_utils.py
compute_uq_unks_from_dict_of_subjects
¶
Compute uncertainty metrics from subject-keyed probability dictionary.
Used for train/val splits where different subjects appear in different bootstrap iterations. Computes ensemble-style uncertainty metrics.
| PARAMETER | DESCRIPTION |
|---|---|
probs_dict
|
Probabilities keyed by subject code, each a list of predictions.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Uncertainty metrics (confidence, entropy, mutual_information) per subject. |
Notes
Uses ensemble_uncertainties from CatBoost tutorial code for metrics like total uncertainty, data uncertainty, and knowledge uncertainty.
Source code in src/classification/stats_metric_utils.py
compute_uq_for_subjectwise_stats
¶
Compute and merge uncertainty quantification into subject-wise stats.
Computes ensemble-based uncertainty metrics (confidence, entropy, mutual information) and adds them to subjectwise_stats.
| PARAMETER | DESCRIPTION |
|---|---|
metrics_iter
|
Accumulated metrics with predictions per split.
TYPE:
|
subjectwise_stats
|
Per-subject statistics to augment.
TYPE:
|
verbose
|
Enable logging.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Updated subjectwise_stats with uncertainty metrics added. |
Source code in src/classification/stats_metric_utils.py
Classifier Utilities¶
classifier_utils
¶
cls_train_on_this_combo
¶
Determine if classifier should be trained on this preprocessing combination.
Applies filtering logic to skip certain combinations (e.g., experimental models on non-ground-truth data, TabPFN on high-dimensional embeddings).
| PARAMETER | DESCRIPTION |
|---|---|
run_name
|
MLflow run name encoding preprocessing pipeline.
TYPE:
|
cls_model_name
|
Classifier model name.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True if this combination should be trained, False to skip. |
Source code in src/classification/classifier_utils.py
cls_is_on_ground_truth
¶
Check if run uses ground truth preprocessing.
| PARAMETER | DESCRIPTION |
|---|---|
run_name
|
MLflow run name.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True if using ground truth outlier detection and imputation. |
Source code in src/classification/classifier_utils.py
get_cls_baseline_models
¶
Get list of baseline classifier model names.
| RETURNS | DESCRIPTION |
|---|---|
list of str
|
Names of standard baseline classifiers used in the study. |
Source code in src/classification/classifier_utils.py
is_experimental_cls_model
¶
Check if classifier is experimental (not a baseline model).
| PARAMETER | DESCRIPTION |
|---|---|
cls_model_name
|
Classifier model name.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True if model is not in baseline models list. |
Source code in src/classification/classifier_utils.py
is_trained_on_embeddings
¶
Check if run uses embedding features instead of handcrafted.
| PARAMETER | DESCRIPTION |
|---|---|
run_name
|
MLflow run name.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True if using foundation model embeddings as features. |
Source code in src/classification/classifier_utils.py
get_dict_array_splits
¶
Extract split names from dict_arrays keys.
| PARAMETER | DESCRIPTION |
|---|---|
dict_arrays
|
Dictionary with keys like 'y_train', 'y_test', 'y_val'.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list
|
Unique split names (e.g., ['train', 'test', 'val']). |
Source code in src/classification/classifier_utils.py
get_classifier_run_name
¶
Generate classifier run name from imputer name.
| PARAMETER | DESCRIPTION |
|---|---|
imputer_name
|
Name of the imputation method.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
Run name for the classifier. |
Source code in src/classification/classifier_utils.py
get_cls_run_name
¶
get_cls_run_name(
imputer_mlflow_run: dict[str, Any] | None,
cls_model_name: str,
cls_model_cfg: DictConfig,
source: str,
) -> str
Generate full classifier run name encoding the preprocessing pipeline.
| PARAMETER | DESCRIPTION |
|---|---|
imputer_mlflow_run
|
MLflow run info for the imputation model.
TYPE:
|
cls_model_name
|
Classifier model name.
TYPE:
|
cls_model_cfg
|
Classifier model configuration.
TYPE:
|
source
|
Data source identifier (e.g., 'GT', 'Raw').
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
Full run name like 'CatBoost__pupil-gt__pupil-gt'. |
Source code in src/classification/classifier_utils.py
preprocess_features
¶
preprocess_features(
train_df: DataFrame,
val_df: DataFrame,
_cls_preprocess_cfg: DictConfig,
) -> tuple[DataFrame, DataFrame]
Trees do not really need standardization, but can benefit from something? See below
See e.g. Hubert Ruczyński and Anna Kozak (2024) Do Tree-based Models Need Data Preprocessing? https://openreview.net/forum?id=08Y5sFtRhN Furthermore, we introduce the preprocessibility measure, based on tunability from (Probst et al., 2018). It describes how much performance can we gain or lose for a dataset 𝐷 by using various preprocessing strategies.
Source code in src/classification/classifier_utils.py
logger_remaining_samples
¶
logger_remaining_samples(
features: dict[str, Any],
samples_in: dict[str, int],
source: str,
) -> None
Log the number of remaining samples after filtering.
| PARAMETER | DESCRIPTION |
|---|---|
features
|
Features dictionary with data per source.
TYPE:
|
samples_in
|
Original sample counts per split before filtering.
TYPE:
|
source
|
Data source name.
TYPE:
|
Source code in src/classification/classifier_utils.py
drop_unlabeled_subjects
¶
drop_unlabeled_subjects(
df: DataFrame | DataFrame,
cfg: DictConfig,
label_col_name: str = "metadata_class_label",
) -> DataFrame
Remove rows without classification labels from dataframe.
| PARAMETER | DESCRIPTION |
|---|---|
df
|
Input dataframe with subject data.
TYPE:
|
cfg
|
Hydra configuration.
TYPE:
|
label_col_name
|
Column name containing class labels.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
Filtered dataframe with only labeled subjects. |
Source code in src/classification/classifier_utils.py
drop_useless_cols
¶
Remove metadata columns not needed for classification.
| PARAMETER | DESCRIPTION |
|---|---|
features
|
Features dictionary with data per source and split.
TYPE:
|
cfg
|
Hydra configuration.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Features dictionary with useless columns removed. |
Source code in src/classification/classifier_utils.py
check_classification_labels
¶
check_classification_labels(
features: dict[str, Any],
source: str,
split: str,
features_in: int,
) -> None
Validate that classification labels are present and binary.
| PARAMETER | DESCRIPTION |
|---|---|
features
|
Features dictionary.
TYPE:
|
source
|
Data source name.
TYPE:
|
split
|
Data split name ('train', 'test').
TYPE:
|
features_in
|
Expected number of features.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
AssertionError
|
If feature count changed or labels are not binary. |
Source code in src/classification/classifier_utils.py
keep_only_labeled_subjects
¶
keep_only_labeled_subjects(
features: dict[str, Any],
cfg: DictConfig,
data_key: str = "data",
) -> dict[str, Any]
Filter features to keep only subjects with classification labels.
| PARAMETER | DESCRIPTION |
|---|---|
features
|
Features dictionary with data per source and split.
TYPE:
|
cfg
|
Hydra configuration.
TYPE:
|
data_key
|
Key in features dict containing the dataframes.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Filtered features dictionary. |
Source code in src/classification/classifier_utils.py
get_numpy_boolean_index_for_class_labels
¶
Create boolean index for samples with valid classification labels.
| PARAMETER | DESCRIPTION |
|---|---|
label_array
|
2D array of labels (n_subjects, n_timepoints).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
Boolean array where True indicates valid label. |
| RAISES | DESCRIPTION |
|---|---|
AssertionError
|
If input is not 2D numpy array or doesn't have exactly 2 classes. |
Source code in src/classification/classifier_utils.py
index_with_boolean_all_numpys_in_datadict
¶
index_with_boolean_all_numpys_in_datadict(
data_dict: dict[str, dict[str, ndarray]],
labeled_boolean: ndarray,
) -> dict[str, dict[str, ndarray]]
Apply boolean indexing to all numpy arrays in nested dictionary.
| PARAMETER | DESCRIPTION |
|---|---|
data_dict
|
Nested dictionary with numpy arrays as values.
TYPE:
|
labeled_boolean
|
Boolean index array for filtering.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Copy of data_dict with all arrays filtered by boolean index. |
Source code in src/classification/classifier_utils.py
keep_only_labeled_subjects_from_source
¶
keep_only_labeled_subjects_from_source(
data_dicts: dict[str, dict[str, dict[str, ndarray]]],
cfg: DictConfig,
) -> dict[str, dict[str, dict[str, ndarray]]]
Filter data dictionaries to keep only labeled subjects.
| PARAMETER | DESCRIPTION |
|---|---|
data_dicts
|
Dictionary with splits as keys, each containing category/variable arrays.
TYPE:
|
cfg
|
Hydra configuration.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Filtered data dictionaries with only labeled subjects. |
Source code in src/classification/classifier_utils.py
pick_subset_of_features_for_classification
¶
Select specific feature subset for classification from full features.
| PARAMETER | DESCRIPTION |
|---|---|
features
|
Full features dictionary with all sources and splits.
TYPE:
|
cfg
|
Hydra configuration with DATA_SUBSET settings.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Features dictionary with only selected feature subset. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If unknown source type encountered. |
Source code in src/classification/classifier_utils.py
check_data_for_NaNs
¶
Check feature columns for NaN values.
| PARAMETER | DESCRIPTION |
|---|---|
source
|
Data source name.
TYPE:
|
features_per_source
|
Features for a single source with 'data' key.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True if no NaNs found in feature columns, False otherwise. |
Source code in src/classification/classifier_utils.py
classifier_hpo_eval
¶
classifier_hpo_eval(
y_true: ndarray,
pred_proba: ndarray,
eval_metric: str,
model: str,
hpo_method: str,
) -> float
Evaluate classifier predictions for hyperparameter optimization.
| PARAMETER | DESCRIPTION |
|---|---|
y_true
|
True class labels.
TYPE:
|
pred_proba
|
Predicted class probabilities.
TYPE:
|
eval_metric
|
Metric to compute ('logloss', 'auc', 'f1').
TYPE:
|
model
|
Model name for logging.
TYPE:
|
hpo_method
|
HPO method ('hyperopt' negates loss for minimization).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
Computed metric value (negated for hyperopt). |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If unknown eval_metric specified. |
Source code in src/classification/classifier_utils.py
classifier_evaluation
¶
get_preds
¶
Get predictions from a trained model for train and test splits.
| PARAMETER | DESCRIPTION |
|---|---|
model
|
Trained classifier with predict() and predict_proba() methods.
TYPE:
|
dict_arrays
|
Dictionary containing 'x_train', 'x_test', 'y_train', 'y_test'.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Dictionary with 'train' and 'test' keys, each containing: - 'y_pred_proba': Class 1 probabilities (n_samples,) - 'y_pred': Predicted class labels (n_samples,) - 'label': True labels |
Source code in src/classification/classifier_evaluation.py
arrange_to_match_bootstrap_results
¶
Rearrange predictions and metrics to match bootstrap result structure.
| PARAMETER | DESCRIPTION |
|---|---|
preds
|
Predictions per split from get_preds().
TYPE:
|
metrics_dict
|
Metrics dictionary per split.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Results dictionary with 'metrics' key containing nested structure matching bootstrap evaluation output format. |
Source code in src/classification/classifier_evaluation.py
eval_sklearn_baseline_results
¶
Evaluate sklearn-style model and compute STRATOS-compliant metrics.
Computes classifier metrics (AUROC, etc.) and calibration metrics for a baseline model without bootstrap uncertainty estimation.
| PARAMETER | DESCRIPTION |
|---|---|
model
|
Trained sklearn-compatible classifier.
TYPE:
|
dict_arrays
|
Data arrays with train/test splits.
TYPE:
|
cfg
|
Hydra configuration.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Baseline results with metrics structured to match bootstrap output. |
Source code in src/classification/classifier_evaluation.py
get_the_baseline_model
¶
get_the_baseline_model(
model_name: str,
cls_model_cfg: DictConfig,
hparam_cfg: DictConfig,
cfg: DictConfig,
best_params: dict,
dict_arrays: dict,
weights_dict: dict,
)
Train and evaluate a single baseline model without bootstrap.
Used as reference before bootstrap evaluation to get deterministic baseline performance metrics.
| PARAMETER | DESCRIPTION |
|---|---|
model_name
|
Classifier name (e.g., 'CatBoost', 'XGBoost', 'TabM').
TYPE:
|
cls_model_cfg
|
Classifier model configuration.
TYPE:
|
hparam_cfg
|
Hyperparameter configuration.
TYPE:
|
cfg
|
Full Hydra configuration.
TYPE:
|
best_params
|
Best hyperparameters from optimization.
TYPE:
|
dict_arrays
|
Data arrays with train/test splits.
TYPE:
|
weights_dict
|
Sample weights per split.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple
|
(model, baseline_results) where model is the trained classifier and baseline_results contains metrics in bootstrap-compatible format. |
Source code in src/classification/classifier_evaluation.py
evaluate_sklearn_classifier
¶
evaluate_sklearn_classifier(
model_name: str,
dict_arrays: dict,
best_params,
cls_model_cfg: DictConfig,
eval_cfg: DictConfig,
cfg: DictConfig,
run_name: str,
)
Evaluate an sklearn-compatible classifier with bootstrap CI estimation.
Trains a baseline model and then performs bootstrap evaluation to estimate confidence intervals for STRATOS-compliant metrics.
| PARAMETER | DESCRIPTION |
|---|---|
model_name
|
Classifier name (e.g., 'LogisticRegression', 'XGBoost').
TYPE:
|
dict_arrays
|
Data arrays with train/test splits.
TYPE:
|
best_params
|
Best hyperparameters from optimization.
TYPE:
|
cls_model_cfg
|
Classifier model configuration.
TYPE:
|
eval_cfg
|
Evaluation configuration with method and parameters.
TYPE:
|
cfg
|
Full Hydra configuration.
TYPE:
|
run_name
|
MLflow run name for logging.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple
|
(models, metrics) where models is list of bootstrap models and metrics contains aggregated statistics. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If unknown evaluation method specified. |
Source code in src/classification/classifier_evaluation.py
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 | |
Other Classifiers¶
sklearn_simple_classifiers
¶
display_grid_search_results
¶
Display and log grid search results.
Prints all parameter combinations with scores and logs best params to MLflow.
| PARAMETER | DESCRIPTION |
|---|---|
grid_result
|
Completed grid search object.
TYPE:
|
scoring
|
Name of the scoring metric.
TYPE:
|
Source code in src/classification/sklearn_simple_classifiers.py
standardize_features
¶
Standardize features to zero mean and unit variance.
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Feature matrix (n_samples, n_features).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple
|
(X_scaled, scaler) where X_scaled is standardized features and scaler is the fitted StandardScaler. |
Source code in src/classification/sklearn_simple_classifiers.py
prepare_for_logistic_hpo
¶
Prepare data and grid for logistic regression hyperparameter optimization.
Standardizes features and constructs parameter grid from config.
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Feature matrix.
TYPE:
|
y
|
Labels.
TYPE:
|
hparam_cfg
|
Hyperparameter configuration with SEARCH_SPACE.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple
|
(X_scaled, y, grid) where grid is dict of hyperparameter lists. |
| RAISES | DESCRIPTION |
|---|---|
AssertionError
|
If X and y have different sample counts or X contains NaNs. |
Source code in src/classification/sklearn_simple_classifiers.py
logistic_regression_hpo_grid_search
¶
logistic_regression_hpo_grid_search(
X,
y,
weights_dict: dict,
hparam_cfg: DictConfig,
cls_model_cfg: DictConfig,
)
Perform grid search hyperparameter optimization for logistic regression.
Uses RepeatedStratifiedKFold cross-validation to find optimal hyperparameters.
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Feature matrix.
TYPE:
|
y
|
Labels.
TYPE:
|
weights_dict
|
Sample weights (currently unused).
TYPE:
|
hparam_cfg
|
Hyperparameter configuration with SEARCH_SPACE and cv_params.
TYPE:
|
cls_model_cfg
|
Classifier model configuration with default hyperparams.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple
|
(grid_result, best_params) where grid_result is GridSearchCV object and best_params is dict of optimal hyperparameters. |
Source code in src/classification/sklearn_simple_classifiers.py
logistic_regression
¶
logistic_regression(
model_name,
dict_arrays,
weights_dict,
cls_model_cfg,
hparam_cfg,
cfg,
run_name: str,
features_per_source: dict,
join_test_and_train: bool = True,
)
Train and evaluate logistic regression classifier with MLflow tracking.
Performs hyperparameter optimization via grid search, trains final model, and evaluates with bootstrap confidence intervals.
| PARAMETER | DESCRIPTION |
|---|---|
model_name
|
Model name for logging.
TYPE:
|
dict_arrays
|
Data arrays with train/test splits.
TYPE:
|
weights_dict
|
Sample weights.
TYPE:
|
cls_model_cfg
|
Classifier model configuration.
TYPE:
|
hparam_cfg
|
Hyperparameter configuration.
TYPE:
|
cfg
|
Full Hydra configuration.
TYPE:
|
run_name
|
MLflow run name.
TYPE:
|
features_per_source
|
Feature source metadata for logging.
TYPE:
|
join_test_and_train
|
Join train and test for HPO (currently not used for final model).
TYPE:
|
Source code in src/classification/sklearn_simple_classifiers.py
sklearn_simple_cls_main
¶
sklearn_simple_cls_main(
train_df: DataFrame,
test_df: DataFrame,
model_name: str,
cfg: DictConfig,
cls_model_cfg: DictConfig,
hparam_cfg: DictConfig,
run_name: str,
features_per_source: dict,
)
Main entry point for sklearn-based simple classifiers.
Converts dataframes to arrays and dispatches to appropriate classifier training function.
| PARAMETER | DESCRIPTION |
|---|---|
train_df
|
Training data as Polars DataFrame.
TYPE:
|
test_df
|
Test data as Polars DataFrame.
TYPE:
|
model_name
|
Classifier name (e.g., 'LogisticRegression').
TYPE:
|
cfg
|
Full Hydra configuration.
TYPE:
|
cls_model_cfg
|
Classifier model configuration.
TYPE:
|
hparam_cfg
|
Hyperparameter configuration.
TYPE:
|
run_name
|
MLflow run name.
TYPE:
|
features_per_source
|
Feature source metadata.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If unknown model_name specified. |
Source code in src/classification/sklearn_simple_classifiers.py
tabpfn_main
¶
eval_tabpfn_model
¶
eval_tabpfn_model(
model: Any, dict_arrays: Dict[str, ndarray]
) -> Tuple[Dict[str, Dict[str, ndarray]], float]
Evaluate TabPFN model on all available splits.
Computes predictions and optionally AUROC for baseline evaluation.
| PARAMETER | DESCRIPTION |
|---|---|
model
|
Fitted TabPFN model.
TYPE:
|
dict_arrays
|
Data arrays with train/test/optionally val splits.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple
|
(results, auroc) where results contains predictions per split and auroc is test AUROC (or NaN if validation split present). |
Source code in src/classification/tabpfn_main.py
train_and_eval_tabpfn
¶
train_and_eval_tabpfn(
dict_arrays: Dict[str, ndarray], hparams: Dict[str, Any]
) -> Tuple[None, Dict[str, Dict[str, ndarray]], float]
Train and evaluate TabPFN classifier.
TabPFN is a prior-fitted network that requires no training on the target dataset - it uses in-context learning.
| PARAMETER | DESCRIPTION |
|---|---|
dict_arrays
|
Data arrays with train/test splits.
TYPE:
|
hparams
|
Hyperparameters for TabPFN (currently unused for v2).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple
|
(model, results, metric) where model is None (to save RAM), results contains predictions, and metric is test AUROC. |
References
TabPFN: https://github.com/automl/TabPFN
Source code in src/classification/tabpfn_main.py
tabpfn_wrapper
¶
tabpfn_wrapper(
dict_arrays: Dict[str, ndarray],
cls_model_cfg: DictConfig,
hparam_cfg: DictConfig,
cfg: DictConfig,
run_HPO: bool = False,
) -> Tuple[
None, Dict[str, Dict[str, ndarray]], Dict[str, Any]
]
Wrapper for TabPFN training with optional hyperparameter optimization.
| PARAMETER | DESCRIPTION |
|---|---|
dict_arrays
|
Data arrays with train/test splits.
TYPE:
|
cls_model_cfg
|
TabPFN model configuration.
TYPE:
|
hparam_cfg
|
Hyperparameter configuration.
TYPE:
|
cfg
|
Full Hydra configuration.
TYPE:
|
run_HPO
|
Run hyperparameter optimization (not implemented for v2).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple
|
(model, results, best_hparams) from training. |
| RAISES | DESCRIPTION |
|---|---|
NotImplementedError
|
If run_HPO is True (was for TabPFN v1). |
Source code in src/classification/tabpfn_main.py
tabpfn_main
¶
tabpfn_main(
train_df: DataFrame,
test_df: DataFrame,
run_name: str,
cfg: DictConfig,
cls_model_cfg: DictConfig,
hparam_cfg: DictConfig,
features_per_source: Dict[str, List[str]],
) -> None
Main entry point for TabPFN classifier training with MLflow tracking.
TabPFN uses in-context learning and doesn't require traditional training. This function handles data preparation, bootstrap evaluation, and MLflow logging.
| PARAMETER | DESCRIPTION |
|---|---|
train_df
|
Training data as Polars DataFrame.
TYPE:
|
test_df
|
Test data as Polars DataFrame.
TYPE:
|
run_name
|
MLflow run name.
TYPE:
|
cfg
|
Full Hydra configuration.
TYPE:
|
cls_model_cfg
|
TabPFN model configuration.
TYPE:
|
hparam_cfg
|
Hyperparameter configuration.
TYPE:
|
features_per_source
|
Feature source metadata for logging.
TYPE:
|
Source code in src/classification/tabpfn_main.py
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 | |