StanleyO's picture
Space: real-time kick detection GUI with bundled test/validation splits
2188714 verified
Raw History Blame Contribute Delete
3.29 kB
"""Data loading for the kick detector.
Splits stay separate. A median, a scale or a threshold must never be fitted
across a split boundary - that is how a clean validation score becomes a lie.
"""
from __future__ import annotations
import hashlib
from pathlib import Path
import numpy as np
import pandas as pd
from . import config as C
def load_split(split: str, impute: bool = True) -> pd.DataFrame:
"""Load one split from the v2 Parquet package, sorted and imputed.
The test split ships WITHOUT Event_Label; labels for it live in
`output/private_test_labels.csv`. `load_test` joins them explicitly rather
than silently producing an unlabelled frame.
"""
if split == "test":
return load_test(impute=impute)
df = pd.read_parquet(C.DATA_V2 / split)
df = df.sort_values(["Sequence_ID", "timestamp_s"]).reset_index(drop=True)
if impute:
from .features import impute
df = impute(df)
return df
def load_test(impute: bool = True) -> pd.DataFrame:
"""Test split WITH labels joined from the competition package.
Row-level labels, so the join key must include timestamp_s. Joining on
Sequence_ID alone cross-joins 1,800 label rows onto every data row.
"""
df = pd.read_parquet(C.DATA_V2 / "test")
df = df.sort_values(["Sequence_ID", "timestamp_s"]).reset_index(drop=True)
if "Event_Label" not in df.columns:
lab = pd.read_csv(C.ORIG_OUTPUT / "private_test_labels.csv")
assert set(lab.columns) == {"Sequence_ID", "timestamp_s", "Event_Label"}
df = df.merge(lab, on=["Sequence_ID", "timestamp_s"], how="left", validate="1:1")
assert len(df) == 270_000 and df.Event_Label.notna().all()
if impute:
from .features import impute
df = impute(df)
return df
def load_metadata() -> pd.DataFrame:
md = pd.read_csv(C.ORIG_OUTPUT / "metadata.csv")
return md.rename(columns={"sequence_id": "Sequence_ID"})
def split_frame(seq_id: int, split: str | None = None,
cache: dict | None = None) -> pd.DataFrame:
"""One sequence, already imputed, ready for feature building."""
key = (seq_id, split)
if cache is not None and key in cache:
return cache[key]
for sp in ([split] if split else ("train", "validation", "test")):
d = load_split(sp)
sub = d[d.Sequence_ID == seq_id]
if len(sub):
if cache is not None:
cache[key] = sub
return sub
raise KeyError(f"sequence {seq_id} not found")
def data_fingerprint() -> dict:
"""Cheap provenance: row counts, label distribution and a content hash."""
out = {}
for sp in ("train", "validation", "test"):
d = load_split(sp, impute=False)
lab = d.Event_Label
out[sp] = {
"sequences": int(d.Sequence_ID.nunique()),
"rows": int(len(d)),
"label_counts": {int(k): int(v) for k, v in lab.value_counts().items()},
}
h = hashlib.sha256()
for sp in ("train", "validation", "test"):
d = load_split(sp, impute=False)
h.update(sp.encode())
h.update(d[["Sequence_ID", "timestamp_s", "Event_Label"]]
.to_numpy().tobytes())
out["label_fingerprint_sha256"] = h.hexdigest()
return out