Scientific Data Science & EEG/Physiological ML/DL Skill
Follow this structured, leakage-free research workflow whenever developing a classification or regression model for scientific research (especially on EEG, ECG, EMG, PPG, fNIRS, or small-to-medium tabular/biomedical cohorts).
Core Non-Negotiable Principles
- Audit Before Modeling: Never feed raw files straight into a model. Inspect file integrity, ID alignment, missingness mechanisms (MCAR/MAR/MNAR), physical signal boundaries (tail zero-padding cliffs, flatline channels, artifacts), and metadata hygiene first.
- Zero-Leakage Validation: Always group splits by entity/subject (
StratifiedGroupKFold/GroupKFold), and evaluate cross-site (LOSO) or temporal generalization when applicable. Fit all imputers, scalers, nonlinear transforms, feature selectors, resamplers, and classification thresholds strictly inside each training fold. - Treat Suspiciously High CV as an Alarm: When CV jumps far above domain expectations, run the Same-Class Different-Batch vs. Different-Class Same-Batch forensic check immediately to expose site/hardware/age shortcuts.
- Build an Uncheatable Compass: Track both primary OOF metrics and anti-cheating diagnostics (same-site/same-batch score,
SiteGap/BatchGap, confounder correlation such asAge_r, and unlabeled Adversarial Validation AUC). Reject any change that inflates overall CV while degrading same-batch generalization. - Statistical Rigor Over Single-Point Scores: Report clustered Bootstrap 95% CIs, calibration (classification) or residual/Bland-Altman diagnostics (regression), significance tests (Permutation / DeLong / McNemar / paired Wilcoxon), ablation studies, and Top-K error analysis. Never claim causation from predictive feature importance.
Standard 8-Stage Execution Procedure
Stage 0–1: Study Framing & Physical/Metadata Audit
- Confirm task formulation (keep continuous targets as regression unless a validated clinical/physical cutoff exists), index time (no future/target leakage), confounders/batches, and sample-size constraints (EPV).
- For EEG/physiological recordings, inspect head/mid/tail signal segments and trim edge artifacts before any filtering to prevent filter ringing.
- Reference template: 01_signal_audit_and_preprocess.py
- Detailed guide: Research ML/DL SOP Handbook
Stage 2: Leakage-Free Validation & Domain Shift Diagnostics
- Run unlabeled Adversarial Validation (
Source=0vsTarget/Site=1) per feature group to identify domain-invariant vs. high-drift features (Adv AUC ≈ 0.50safe;> 0.75severe shift). - Lock
Repeated StratifiedGroupKFold(small $N < 500$) orNested CV+Leave-One-Site-Out (LOSO)when multiple sites/batches exist.
Stage 3: Deterministic Preprocessing & Scale-Invariant Feature Engineering
- Apply identical deterministic preprocessing to train and external/test cohorts (trim → zero-phase notch & bandpass → optional bipolar EOG regression then drop auxiliary channels → robust bad-channel handling → CAR → resample → clean epoch slicing).
- Prioritize scale- and gain-invariant features (relative band power, band ratios, 1/f aperiodic slope, hemispheric asymmetry,
wPLI,orth-AEC, Hjorth, spectral/permutation entropy, epoch-to-epoch temporal variabilityCV/IQR, trace-normalized SPD covariances). - Perform feature-group ablation (Only-1-Group + Leave-One-Group-Out) to prune noisy high-dimensional groups, and compare fold-internal distributional transforms (
Standard,Robust,Yeo-Johnson,RankGauss). - Reference template: 02_feature_extraction.py
Stage 4: Classical ML Baseline Ladder (Classification & Regression)
- Always progress along the ladder:
Dummy→ strongly regularized linear (LogisticRegression/Ridge/ElasticNet) → kernel (SVM/SVR/GPR) → shallow regularized trees (LightGBM/CatBoost). - For imbalanced classification, prefer
class_weight='balanced'+ nested fold-internal threshold calibration over blind SMOTE. - For regression, match loss to noise (
MSE,MAE,Huber,Quantile) and evaluate back in original physical units if target transforms (log1p/ Box-Cox) are used. - Reference template: 03_ml_pipeline_cls_reg.py
Stage 5: PyTorch Deep Learning Ritual (Classification & Regression)
- Mandatory Sanity Check: Before any full training, disable dropout/augmentation and verify the model can overfit a single mini-batch near zero loss (
--sanity-overfit-batch) and that initial loss matches theory ($\approx \ln 2 \approx 0.693$ for balanced binary CE; $\approx 1.0$ for standardized MSE). - Use
AdamW+ Warmup/Cosine LR + gradient clipping +GroupNorm/LayerNorm(for small batches) + strong regularization (Weight Decay, Dropout, Gaussian input noise, Mixup, physically valid augmentations). - Aggregate epoch-level predictions to subject-level metrics strictly without cross-fold subject overlap.
- Reference template: 04_dl_pipeline_pytorch.py
Stage 6–7: Rigorous Evaluation, Error Analysis & Reporting
- Report full metric suites + clustered Bootstrap 95% CIs + significance tests + ablation tables + Top-K worst-error sample inspection.
- Use the reusable checklist before finalizing any study or manuscript:
Quick Verification Commands (Built-In Synthetic Multi-Site EEG Demo)
Verify the executable templates end-to-end before adapting them to real data:
python scripts/01_signal_audit_and_preprocess.py --demo
python scripts/02_feature_extraction.py
python scripts/03_ml_pipeline_cls_reg.py --task classification
python scripts/03_ml_pipeline_cls_reg.py --task regression
python scripts/04_dl_pipeline_pytorch.py --task classification --arch eegnet1d --sanity-overfit-batch
python scripts/04_dl_pipeline_pytorch.py --task classification --arch eegnet1d --epochs 10
python scripts/04_dl_pipeline_pytorch.py --task regression --arch resmlp --epochs 15