Datasets:
Download load_chbmit.py from JayF14/chb-mit-preprocessed-eeg: direct link, hf CLI and curl.
- Browser
- Download file 4.41 kB
-
https://huggingface.co/datasets/JayF14/chb-mit-preprocessed-eeg/resolve/main/load_chbmit.py
- Command line
-
hf download hf://datasets/JayF14/chb-mit-preprocessed-eeg/load_chbmit.py
-
curl -L -o load_chbmit.py https://huggingface.co/datasets/JayF14/chb-mit-preprocessed-eeg/resolve/main/load_chbmit.py
4.41 kB
| """ | |
| load_chbmit.py — safe loader for JayF14/chb-mit-preprocessed-eeg | |
| Handles every known issue in the CSVs: | |
| * different columns per patient (dummy channels, missing right-temporal chain) | |
| * 12 coherence columns that are always 0 | |
| * rows that contain no usable EEG (e.g. recordings with only dummy/ECG channels) | |
| * rows stored in random recording order | |
| * chb01 and chb21 being the same person | |
| Usage | |
| ----- | |
| from load_chbmit import load_all | |
| X, y, groups, meta = load_all("./chb_mit_data", feature_set="common") | |
| feature_set: | |
| "common" (446) - features with real values for all 24 patients (recommended) | |
| "full" (578) - chb01's 590 features minus the 12 always-zero coherence columns; | |
| right-temporal features are NaN for chb12-chb22 and part of chb11 | |
| """ | |
| import os | |
| import re | |
| import numpy as np | |
| import pandas as pd | |
| META = ["epoch_id", "window_start", "window_end", "file_source", "target_label"] | |
| RIGHT_TEMPORAL = ["FP2-F8", "F8-T8", "T8-P8-0", "P8-O2"] | |
| RIGHT_TEMPORAL_U = [c.replace("-", "_") for c in RIGHT_TEMPORAL] | |
| SAME_SUBJECT = {"chb21": "chb01"} # PhysioNet: chb21 is chb01 recorded 1.5 years later | |
| def _is_right_temporal(col): | |
| return any(col.startswith(p + "_") for p in RIGHT_TEMPORAL + RIGHT_TEMPORAL_U) | |
| def feature_lists(data_dir): | |
| """Build the 'full' and 'common' feature lists from chb01's header.""" | |
| ref = pd.read_csv(os.path.join(data_dir, "chb01_labeled_features.csv"), nrows=0) | |
| chb01 = [c for c in ref.columns if c not in META] | |
| assert len(chb01) == 590, f"expected 590 features in chb01, got {len(chb01)}" | |
| dead_coh = [c for c in chb01 if c.startswith("coh_") and "T8_P8" in c] # always 0 | |
| rt_coh = [c for c in chb01 if c.startswith("coh_") | |
| and any(k in c for k in ("FP2_F8", "F8_T8", "T8_P8", "P8_O2"))] | |
| full = [c for c in chb01 if c not in dead_coh] | |
| common = [c for c in chb01 if not _is_right_temporal(c) and c not in rt_coh] | |
| return {"full": full, "common": common} | |
| def _file_key(name): | |
| """Natural sort key for EDF names like chb17a_04.edf, chb02_16+.edf.""" | |
| return [int(t) if t.isdigit() else t for t in re.split(r"(\d+)", str(name))] | |
| def load_patient(data_dir, pid, features): | |
| path = os.path.join(data_dir, f"{pid}_labeled_features.csv") | |
| cols = set(pd.read_csv(path, nrows=0).columns) | |
| use = META + [c for c in features if c in cols] | |
| raw = pd.read_csv(path, usecols=use, low_memory=False) | |
| # absent columns -> NaN, inf -> NaN, built in one block (fast, no fragmentation) | |
| vals = raw.reindex(columns=features).to_numpy(dtype=np.float64) | |
| vals[np.isinf(vals)] = np.nan | |
| meta = raw[META].copy() | |
| meta["patient"] = pid | |
| meta["subject"] = SAME_SUBJECT.get(pid, pid) | |
| # Drop rows with no usable EEG: every non-coherence feature missing | |
| eeg_idx = [i for i, c in enumerate(features) if not c.startswith("coh_")] | |
| usable = ~np.isnan(vals[:, eeg_idx]).all(axis=1) | |
| dropped = int((~usable).sum()) | |
| meta, vals = meta[usable], vals[usable] | |
| # Restore time order (rows were written in random recording order) | |
| order = sorted(range(len(meta)), key=lambda i: ( | |
| [str(t) for t in _file_key(meta["file_source"].iat[i])], meta["window_start"].iat[i])) | |
| meta = meta.iloc[order].reset_index(drop=True) | |
| vals = vals[order] | |
| df = pd.concat([meta, pd.DataFrame(vals, columns=features)], axis=1) | |
| return df, dropped | |
| def load_all(data_dir, feature_set="common", patients=None): | |
| features = feature_lists(data_dir)[feature_set] | |
| patients = patients or [f"chb{i:02d}" for i in range(1, 25)] | |
| frames, report = [], {} | |
| for pid in patients: | |
| df, dropped = load_patient(data_dir, pid, features) | |
| frames.append(df) | |
| report[pid] = {"rows_kept": len(df), "rows_dropped_no_eeg": dropped} | |
| full = pd.concat(frames, ignore_index=True) | |
| X = full[features].to_numpy(dtype=np.float32) | |
| y = full["target_label"].to_numpy() | |
| groups = full["subject"].to_numpy() # use for GroupKFold: keeps chb01+chb21 together | |
| return X, y, groups, {"features": features, "report": report, "frame": full[META + ["patient", "subject"]]} | |
| if __name__ == "__main__": | |
| import sys | |
| d = sys.argv[1] if len(sys.argv) > 1 else "./chb_mit_data" | |
| X, y, g, m = load_all(d) | |
| print(X.shape, "pre-ictal:", int((y == 1).sum()), "subjects:", len(set(g))) | |
| for k, v in m["report"].items(): | |
| print(k, v) | |