Download benchmark/protocol.py from Zipeng365/WristHARBench: direct link, hf CLI and curl.
- Browser
- Download file 7.53 kB
-
https://huggingface.co/datasets/Zipeng365/WristHARBench/resolve/main/benchmark/protocol.py
- Command line
-
hf download hf://datasets/Zipeng365/WristHARBench/benchmark/protocol.py
-
curl -L -o protocol.py https://huggingface.co/datasets/Zipeng365/WristHARBench/resolve/main/benchmark/protocol.py
7.53 kB
| """Public WristHARBench v1.1 loading, preprocessing, and scoring contract. | |
| Author: ZipengWu. Code license: MIT. Data licenses are task-view-specific. | |
| """ | |
| from __future__ import annotations | |
| import hashlib | |
| import json | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| from typing import Any, Iterable | |
| import numpy as np | |
| import pandas as pd | |
| from datasets import Dataset, load_dataset | |
| from sklearn.metrics import f1_score | |
| REVISION = "v1.1.2" | |
| REPO_ID = "Zipeng365/WristHARBench" | |
| FULL_SCOPE = "full_task_view" | |
| PAPER_SCOPE = "paper_snapshot_20260828" | |
| MODEL_SEEDS = (42, 43, 44) | |
| FOLDS = (0, 1, 2, 3, 4) | |
| SPLIT_SEEDS = (1000, 2000, 3000, 4000, 5000) | |
| MAIN_TASK_VIEWS = ( | |
| "capture24_wearable_activity_v1", | |
| "wisdm_watch_accel_v1", | |
| "adl_wrist_accel_v1", | |
| "iuwds_wrist_accel_v1", | |
| "paal_adl_wrist_accel_v1", | |
| "handy_wrist_accel_v1", | |
| "domino_watch_accel_v1", | |
| "harmes_left_wrist_accel_v1", | |
| "harmes_right_wrist_accel_v1", | |
| "gotov_wrist_accel_v1", | |
| ) | |
| AUXILIARY_TASK_VIEWS = ( | |
| "pamap2_hand_imu_v1", | |
| "mhealth_right_lower_arm_v1", | |
| ) | |
| HARMES_LEFT = "harmes_left_wrist_accel_v1" | |
| HARMES_RIGHT = "harmes_right_wrist_accel_v1" | |
| HARMES_ENTRY = "harmes_paired_wrist_accel_v1" | |
| class FoldData: | |
| task_view_id: str | |
| fold: int | |
| split_seed: int | |
| model_seed: int | |
| scope: str | |
| revision: str | |
| train: Dataset | |
| validation: Dataset | |
| test: Dataset | |
| def config_name(task_view_id: str, scope: str) -> str: | |
| if scope not in {FULL_SCOPE, PAPER_SCOPE}: | |
| raise ValueError(f"Unknown scope: {scope}") | |
| if scope == PAPER_SCOPE and task_view_id == "capture24_wearable_activity_v1": | |
| return "capture24_wearable_activity_v1_paper_snapshot_20260828" | |
| return task_view_id | |
| def load_task( | |
| task_view_id: str, | |
| *, | |
| scope: str = PAPER_SCOPE, | |
| revision: str = REVISION, | |
| ) -> Dataset: | |
| """Load one physical task view pinned to a release tag.""" | |
| if task_view_id not in MAIN_TASK_VIEWS + AUXILIARY_TASK_VIEWS: | |
| raise ValueError(f"Unknown task view: {task_view_id}") | |
| return load_dataset( | |
| REPO_ID, | |
| name=config_name(task_view_id, scope), | |
| split="full", | |
| revision=revision, | |
| ) | |
| def split_dataset(dataset: Dataset, fold: int, split: str) -> Dataset: | |
| if fold not in FOLDS: | |
| raise ValueError(f"fold must be one of {FOLDS}") | |
| if split not in {"train", "validation", "test"}: | |
| raise ValueError("split must be train, validation, or test") | |
| column = f"fold_{fold}" | |
| return dataset.filter( | |
| lambda value: value == split, | |
| input_columns=[column], | |
| desc=f"fold {fold} {split}", | |
| ) | |
| def preprocess_signal(signal: Any) -> np.ndarray: | |
| """Registered ffill/bfill then per-series, per-channel z-normalization.""" | |
| array = np.asarray(signal, dtype=np.float64) | |
| if array.ndim != 2: | |
| raise ValueError(f"Expected [time, channel], got {array.shape}") | |
| array = pd.DataFrame(array).ffill().bfill().to_numpy(dtype=np.float64) | |
| if not np.isfinite(array).all(): | |
| raise ValueError("A sequence remains non-finite after registered imputation") | |
| mean = array.mean(axis=0, keepdims=True) | |
| std = array.std(axis=0, keepdims=True) | |
| std[std == 0.0] = 1.0 | |
| return (array - mean) / std | |
| def macro_f1(y_true: Iterable[str], y_pred: Iterable[str]) -> float: | |
| truth = np.asarray(list(y_true), dtype=object) | |
| pred = np.asarray(list(y_pred), dtype=object) | |
| if truth.shape != pred.shape or truth.ndim != 1 or not len(truth): | |
| raise ValueError(f"Prediction shape mismatch: truth={truth.shape}, pred={pred.shape}") | |
| return float(f1_score(truth, pred, average="macro")) | |
| def sha256(path: Path) -> str: | |
| digest = hashlib.sha256() | |
| with path.open("rb") as handle: | |
| for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): | |
| digest.update(block) | |
| return digest.hexdigest() | |
| def aggregate_runs(run_rows: pd.DataFrame) -> pd.DataFrame: | |
| required = {"task_view_id", "fold", "model_seed", "macro_f1"} | |
| if not required.issubset(run_rows.columns): | |
| raise ValueError(f"Missing run columns: {sorted(required - set(run_rows.columns))}") | |
| duplicated = run_rows.duplicated(["task_view_id", "fold", "model_seed"]) | |
| if duplicated.any(): | |
| raise ValueError("Duplicate task/fold/model-seed run receipts") | |
| rows: list[dict[str, Any]] = [] | |
| for task in MAIN_TASK_VIEWS: | |
| if task in {HARMES_LEFT, HARMES_RIGHT}: | |
| continue | |
| values = run_rows.loc[run_rows["task_view_id"] == task, "macro_f1"] | |
| if len(values): | |
| rows.append({"dataset_id": task, "macro_f1": float(values.mean())}) | |
| left = run_rows[run_rows["task_view_id"] == HARMES_LEFT][ | |
| ["fold", "model_seed", "macro_f1"] | |
| ].rename(columns={"macro_f1": "left_macro_f1"}) | |
| right = run_rows[run_rows["task_view_id"] == HARMES_RIGHT][ | |
| ["fold", "model_seed", "macro_f1"] | |
| ].rename(columns={"macro_f1": "right_macro_f1"}) | |
| if len(left) or len(right): | |
| paired = left.merge(right, on=["fold", "model_seed"], how="outer", validate="one_to_one") | |
| if paired.isna().any().any(): | |
| raise ValueError("HARMES left/right runs are not paired by fold and model seed") | |
| rows.append( | |
| { | |
| "dataset_id": HARMES_ENTRY, | |
| "macro_f1": float( | |
| ((paired["left_macro_f1"] + paired["right_macro_f1"]) / 2.0).mean() | |
| ), | |
| } | |
| ) | |
| return pd.DataFrame(rows).sort_values("dataset_id").reset_index(drop=True) | |
| def compare_with_frozen20( | |
| dataset_scores: pd.DataFrame, | |
| *, | |
| method_id: str, | |
| frozen_scores_path: Path, | |
| ) -> tuple[pd.DataFrame, pd.DataFrame]: | |
| """Insert a complete submission into the frozen formal-20 main-track table.""" | |
| expected = { | |
| task for task in MAIN_TASK_VIEWS if task not in {HARMES_LEFT, HARMES_RIGHT} | |
| } | {HARMES_ENTRY} | |
| observed = set(dataset_scores["dataset_id"].astype(str)) | |
| if observed != expected: | |
| raise ValueError(f"Strict main track is incomplete: missing={sorted(expected-observed)}") | |
| frozen = pd.read_csv(frozen_scores_path) | |
| if method_id in set(frozen["method_id"].astype(str)): | |
| raise ValueError(f"Submission method_id collides with a frozen method: {method_id}") | |
| submission = dataset_scores.assign(method_id=method_id) | |
| combined = pd.concat( | |
| [frozen[["method_id", "dataset_id", "macro_f1"]], submission], | |
| ignore_index=True, | |
| ) | |
| combined["dataset_rank"] = combined.groupby("dataset_id")["macro_f1"].rank( | |
| method="min", ascending=False | |
| ) | |
| ranking = ( | |
| combined.groupby("method_id", as_index=False) | |
| .agg( | |
| mean_dataset_rank=("dataset_rank", "mean"), | |
| mean_macro_f1=("macro_f1", "mean"), | |
| dataset_wins=("dataset_rank", lambda values: int((values == 1).sum())), | |
| dataset_top3=("dataset_rank", lambda values: int((values <= 3).sum())), | |
| datasets=("dataset_id", "nunique"), | |
| ) | |
| .sort_values( | |
| ["mean_dataset_rank", "mean_macro_f1", "method_id"], | |
| ascending=[True, False, True], | |
| ) | |
| .reset_index(drop=True) | |
| ) | |
| ranking["rank_with_submission"] = np.arange(1, len(ranking) + 1) | |
| return combined, ranking | |
| def write_json(path: Path, payload: dict[str, Any]) -> None: | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8") | |