"""Does the build hit exact 8b:1b:1b with no leakage - and are the whole pools really whole? Checks, on the labels actually shipped in `build/out/anger_ekman_rows.csv`: 1. `balanced` (7 classes) and `anger_split_balanced` (2 classes) land exactly on 8b : 1b : 1b with b = N/10, per class as well as overall, and no duplicate group straddles a split; 2. `full` and `anger_split` carry the complete pools in one split; 3. the balanced sample is exactly `m` rows per class, m the largest multiple of ten that fits, and dropping rows never cuts a group. The last block re-runs the *published* greedy splitter (`make_dataset.stratified_811_greedy`) on the earlier pools for contrast - that is the splitter whose rounding these checks exist to replace. """ import time import numpy as np import pandas as pd from make_dataset import (LABELS_BINARY, LABELS_EKMAN, SOURCE_TO_EKMAN, add_text_group, balanced_pool, norm) from split_exact import SPLITS, apportion, assign_groups, ideal_targets def build_pool(labels_csv="build/out/anger_ekman_rows.csv"): f1 = pd.read_csv("data/file1.csv", index_col=0) f2 = pd.read_csv("data/file2.csv", index_col=0) df = f1.join(f2) df["text"] = df["tweet"].map(norm) df["text_en"] = df["tweet_en"].map(norm) df["row_src"] = df.index df["source_label"] = df["label"].astype(str).str.strip().str.lower() df["label"] = df["source_label"].replace({"joy": "enjoyment"}) lab = pd.read_csv(labels_csv) m = df.merge(lab[["row_src", "label"]].rename(columns={"label": "ek"}), on="row_src", how="left") df["label"] = m["ek"].where(m["ek"].notna(), df["label"]).values return add_text_group(df) def check_split(name, sub, labels, m): """Exact 8b:1b:1b, every class the same size in every split, no group in two splits.""" t0 = time.time() N = len(sub) per_class_want = apportion(m) assert N % 10 == 0, f"{name}: {N} rows is not a multiple of ten" b = N // 10 want = [8 * b, b, b] assert apportion(N) == want, (apportion(N), want) out = assign_groups(sub, ideal_targets(sub["label"].value_counts().to_dict(), want), 0) got = [int((out["split"] == s).sum()) for s in SPLITS] leak = 0 for s in SPLITS: g = set(out.loc[out["split"] == s, "group"]) for o in SPLITS: if o != s: leak += len(g & set(out.loc[out["split"] == o, "group"])) per_class_ok = all( set(out.loc[out["split"] == s, "label"].value_counts().values) == {per_class_want[i]} for i, s in enumerate(SPLITS)) print("%-22s N=%-5d b=%-4d got=%-16s per class %s per-class=%s leak=%d %.1fs" % ( name, N, b, "/".join(map(str, got)), "/".join(map(str, per_class_want)), "uniform" if per_class_ok else "RAGGED", leak, time.time() - t0)) assert got == want and leak == 0 and per_class_ok return out, want def main(): df = build_pool() ang = df[df["source_label"] == "anger"].reset_index(drop=True) # 1-2: the balanced configs split exactly, the whole-pool configs are not split at all for name, base, labels in (("balanced", df, LABELS_EKMAN), ("anger_split_balanced", ang, LABELS_BINARY)): sub, m, dropped = balanced_pool(base, labels) assert set(sub["label"].value_counts().values) == {m}, (name, m) assert m % 10 == 0 and len(sub) == m * len(labels) assert all(len(g) > 1 for c in dropped for g in []), "sanity" check_split(name, sub, labels, m) for name, base in (("full", df), ("anger_split", ang)): print("%-22s N=%-5d one split, complete pool, nothing held out" % (name, len(base))) # 3: the sample size rule - largest multiple of ten that fits the smallest class small = pd.DataFrame({"label": ["a"] * 186 + ["b"] * 200, "group": range(386)}) sub, m, _ = balanced_pool(small, ["a", "b"]) assert m == 180 and set(sub["label"].value_counts().values) == {180}, (m, sub["label"].value_counts()) print("\nsample rule: 186 / 200 eligible -> %d rows per class (largest multiple of ten)" % m) # contrast: the published pools and the published greedy splitter, for reference print("\ncontrast - the earlier pools, split by the published greedy splitter:") dfp = build_pool("out_prev/anger_ekman_rows.csv") angp = dfp[dfp["source_label"] == "anger"].reset_index(drop=True) from make_dataset import stratified_811_greedy def old_pool(frame, labels, seed=0): """the earlier rule: equal to the smallest class exactly, no ten-row block""" per = min(int((frame["label"] == l).sum()) for l in labels) rng = np.random.RandomState(seed + 1) take = [] for l in labels: idx = frame.index[frame["label"] == l].to_list() take += idx if len(idx) == per else list(np.array(idx)[rng.permutation(len(idx))[:per]]) return frame.loc[sorted(take)].reset_index(drop=True) for name, base in (("full", dfp), ("balanced", old_pool(dfp, LABELS_EKMAN)), ("anger_split", angp), ("anger_split_balanced", old_pool(angp, LABELS_BINARY))): o = stratified_811_greedy(base, 0) got = [int((o["split"] == s).sum()) for s in SPLITS] N = len(base) print(" %-22s N=%-5d got=%-18s dev=%s pts" % ( name, N, "/".join(map(str, got)), "/".join("%.2f" % (abs(got[i] / N - f) * 100) for i, f in enumerate((0.8, 0.1, 0.1))))) print("\n[test] exact 8b:1b:1b, per-class uniform, no group leakage, complete pools: PASS") if __name__ == "__main__": main()