"""Exact 8:1:1 stratification that still keeps duplicate groups whole. The published build split with a greedy deficit-filling pass (`make_dataset.stratified_811`), which cannot hit exact split sizes when the last group of a class does not fit: it landed 2,243 rows on 1794/226/223 (0.02 / 0.08 / 0.06 points off 8:1:1) and `anger_split_balanced` on 150/20/18 (0.4 / 1.2 / 1.2 points off). Two changes make the counts exact without giving up the no-leakage guarantee: 1. **Bottleneck targets.** The tenth block b = floor(n / 10) is the unit: `valid` and `test` get exactly b rows each, `train` takes n - 2b. That is exact to the last row and keeps the two tail splits the same size at their plain 10% floor (2,243 -> 1795 / 224 / 224, i.e. 8b + 3 for train). `ideal_targets()` then solves the per-class-per-split cells as an integer program (scipy's HiGHS) against those column totals, minimising the total absolute distance to `n_class * fraction`. 2. **Greedy place, then repair.** Groups are placed by need, then single groups are moved between splits as long as a move lowers `PRIMARY * |column deficits| + |cell distances|`. Because all but a handful of the ~2,200 groups are singletons, the column totals always reach their exact targets, so the shipped files are 8:1:1 to the last row *and* leak-free. """ from typing import Dict, List, Sequence, Tuple import numpy as np import pandas as pd SPLITS = ("train", "valid", "test") FRACTIONS = (0.8, 0.1, 0.1) PRIMARY = 1e6 # weight on exact column totals vs. per-class cell fit def apportion(n: int, fractions: Sequence[float] = FRACTIONS) -> List[int]: """Exact 8b : 1b : 1b, where b = floor(n/10) is the bottleneck. Every split config here is built so that `n` is a multiple of ten - the balanced pools sample a multiple of ten rows per class (180 of 186, see `sample_groups_per_class`) - so `n - 2b` is exactly `8b` and the three splits are 8:1:1 to the row with nothing left over. The formula still returns a sensible answer for an `n` that is not a multiple of ten (the rows no tenth can hold go to `train`), but no shipped config relies on that. The tenth block b = floor(n / 10) is the unit every split is measured in. n is never a multiple of ten here, and 8b : 1b : 1b can only ever account for 10b <= n rows, so the rows that no tenth can hold (n - 10b, at most 9) go to `train` - the largest split, where they move the ratio least, and the only placement that keeps both tail splits at exactly one bottleneck each: 2,243 -> 1795 / 224 / 224 (b = 224, train = 8b + 3) 1,302 -> 1042 / 130 / 130 (b = 130, train = 8b + 2) 658 -> 528 / 65 / 65 (b = 65, train = 8b + 8) 475 -> 381 / 47 / 47 (b = 47, train = 8b + 5) 372 -> 298 / 37 / 37 (b = 37, train = 8b + 2) `train` is always `n - 2b`, never `8b`, so the leftover rows are never dropped. For n < 10 the tenth block is 0 rows and all n rows go to `train`. """ b = n // 10 if b == 0: return [n, 0, 0] tails = [b] * (len(fractions) - 1) return [n - sum(tails)] + tails def sample_groups_per_class(df, per_class_rows: int, seed: int, labels=None): """Down-sample to exactly `per_class_rows` rows per class, in whole duplicate groups. A balanced config is a sample, so it can be sized to whatever makes the split exact; every group (a wording that repeats, possibly with a different upstream label) is kept or dropped as a unit, so duplicate text can never straddle splits. Rows are dropped by shuffling that class's groups with `seed` and dropping whole groups until exactly `class_size - per_class_rows` rows are gone, which keeps the result deterministic and independent of the group order on disk. """ labels = list(labels) if labels is not None else sorted(df["label"].unique()) rng = np.random.RandomState(seed) keep = np.zeros(len(df), dtype=bool) dropped = {} for c in labels: idx = df.index[df["label"] == c].to_numpy() sizes = df.loc[idx].groupby("group").size() need = int(sizes.sum()) - per_class_rows assert need >= 0, f"{c}: {sizes.sum()} rows is less than the sample size {per_class_rows}" order = rng.permutation(len(sizes)) drop_groups, got = set(), 0 for k in order: # prefer groups that fit the budget exactly g = sizes.index[k] if sizes.iloc[k] <= need - got: drop_groups.add(g) got += int(sizes.iloc[k]) if got == need: break assert got == need, f"{c}: cannot drop exactly {need} rows without cutting a group" dropped[c] = [int(g) for g in drop_groups] keep |= df.index.isin(idx) & ~df["group"].isin(drop_groups) out = df[keep].reset_index(drop=True) assert len(out) == per_class_rows * len(labels) assert set(out["label"].value_counts()) == {per_class_rows} return out, dropped def ideal_targets(class_sizes: Dict[str, int], split_sizes: Sequence[int], fractions: Sequence[float] = FRACTIONS) -> Dict[str, List[int]]: """Integer per-(class, split) targets: exact column totals, minimal distance to n_c * f_s. Solves min sum_{c,s} |x_cs - n_c f_s| s.t. sum_s x_cs = n_c, sum_c x_cs = N_s (x >= 0 int) so the class-level counts stay as close to proportional as the exact split sizes allow. """ classes = list(class_sizes) S = len(split_sizes) nc, ns = len(classes), len(split_sizes) nvar = nc * S + nc * S # x (int) then d (continuous) c_obj = np.zeros(nvar) c_obj[nc * S:] = 1.0 integrality = np.zeros(nvar) integrality[:nc * S] = 1 lb = np.zeros(nvar) ub = np.full(nvar, np.inf) rows, lows, highs = [], [], [] for i, cl in enumerate(classes): # sum_s x_cs = n_c r = np.zeros(nvar); r[i * S:(i + 1) * S] = 1 rows.append(r); lows.append(class_sizes[cl]); highs.append(class_sizes[cl]) for s in range(S): # sum_c x_cs = N_s r = np.zeros(nvar) for i in range(nc): r[i * S + s] = 1 rows.append(r); lows.append(split_sizes[s]); highs.append(split_sizes[s]) for i, cl in enumerate(classes): # |x_cs - n_c f_s| <= d_cs for s in range(S): tgt = class_sizes[cl] * fractions[s] r = np.zeros(nvar); r[i * S + s] = 1; r[nc * S + i * S + s] = -1 rows.append(r); lows.append(-np.inf); highs.append(tgt) r = np.zeros(nvar); r[i * S + s] = -1; r[nc * S + i * S + s] = -1 rows.append(r); lows.append(-np.inf); highs.append(-tgt) from scipy.optimize import Bounds, LinearConstraint, milp res = milp(c=c_obj, constraints=LinearConstraint(np.array(rows), np.array(lows), np.array(highs)), integrality=integrality, bounds=Bounds(lb, ub)) if not res.success: raise RuntimeError("target rounding ILP failed: %s" % res.message) x = np.rint(res.x[:nc * S]).astype(int).reshape(nc, S) assert (x.sum(1) == np.array([class_sizes[c] for c in classes])).all() assert (x.sum(0) == np.array(split_sizes)).all(), (x.sum(0), split_sizes) return {cl: [int(v) for v in x[i]] for i, cl in enumerate(classes)} def _cost(cells: Dict[Tuple[str, int], int], ideal: Dict[Tuple[str, int], float], col_target: Sequence[int], col_now: Sequence[int]) -> float: c = 0.0 for k in ideal: c += abs(cells[k] - ideal[k]) for s in range(3): c += PRIMARY * abs(col_now[s] - col_target[s]) return c def assign_groups(df: pd.DataFrame, targets: Dict[str, List[int]], seed: int) -> List[str]: """Group-aware assignment: place by need, then repair until the column totals are exact.""" labels = sorted(targets) cols = {s: i for i, s in enumerate(SPLITS)} grp = df["group"].to_numpy() lab = df["label"].to_numpy() groups: Dict[int, List[int]] = {} for i, g in enumerate(grp): groups.setdefault(int(g), []).append(i) # label counts per group (a group can span two labels: one translation, two different tweets) gcounts = {g: pd.Series([lab[i] for i in idx]).value_counts().to_dict() for g, idx in groups.items()} col_target = [sum(targets[c][s] for c in labels) for s in range(3)] frac = np.array(FRACTIONS) ideal = {(c, s): sum(targets[c]) * frac[s] for c in labels for s in range(3)} rng = np.random.RandomState(seed) order = sorted(groups, key=lambda g: -len(groups[g])) # shuffle inside each size class so the seed controls which wording lands where buckets: Dict[int, List[int]] = {} for g in order: buckets.setdefault(len(groups[g]), []).append(g) ordered: List[int] = [] for size in sorted(buckets, reverse=True): gs = buckets[size] rng.shuffle(gs) ordered += gs rem = {c: [targets[c][s] for s in range(3)] for c in targets} cells = {(c, s): 0 for c in labels for s in range(3)} col_now = [0, 0, 0] assign: Dict[int, int] = {} for g in ordered: best, best_score = 0, -1e18 for s in range(3): score = 0.0 for c, k in gcounts[g].items(): tgt = targets[c][s] score += k * (rem[c][s] / tgt if tgt else -1.0) if score > best_score + 1e-12: best, best_score = s, score assign[g] = best for c, k in gcounts[g].items(): rem[c][best] -= k cells[(c, best)] += k col_now[best] += len(groups[g]) # ---- repair: move whole groups while a move lowers `PRIMARY * column deficits + cell distance` def col_penalty(col): return PRIMARY * sum(abs(col[s] - col_target[s]) for s in range(3)) def cell_delta(g, s_from, s_to): return sum(abs(cells[(c, s_to)] + k - ideal[(c, s_to)]) - abs(cells[(c, s_to)] - ideal[(c, s_to)]) + abs(cells[(c, s_from)] - k - ideal[(c, s_from)]) - abs(cells[(c, s_from)] - ideal[(c, s_from)]) for c, k in gcounts[g].items()) cur = col_penalty(col_now) + sum(abs(cells[k] - ideal[k]) for k in ideal) for _ in range(20000): best_move, best_cost = None, cur for g, s_from in assign.items(): n = len(groups[g]) for s_to in range(3): if s_to == s_from: continue col_after = list(col_now); col_after[s_from] -= n; col_after[s_to] += n p_delta = col_penalty(col_after) - col_penalty(col_now) if p_delta > 0: # never trade an exact column for a cell continue cst = cur + p_delta + cell_delta(g, s_from, s_to) if cst < best_cost - 1e-9: best_move, best_cost = (g, s_from, s_to), cst if best_move is None: break g, s_from, s_to = best_move assign[g] = s_to col_now[s_from] -= len(groups[g]); col_now[s_to] += len(groups[g]) for c, k in gcounts[g].items(): cells[(c, s_from)] -= k cells[(c, s_to)] += k cur = best_cost out = df.copy() out["split"] = [SPLITS[assign[int(g)]] for g in out["group"].to_numpy()] return out