komlos-split 0.1.0__tar.gz → 0.2.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {komlos_split-0.1.0 → komlos_split-0.2.0}/Cargo.lock +1 -1
- {komlos_split-0.1.0 → komlos_split-0.2.0}/Cargo.toml +1 -1
- {komlos_split-0.1.0 → komlos_split-0.2.0}/PKG-INFO +9 -1
- {komlos_split-0.1.0 → komlos_split-0.2.0}/README.md +8 -0
- {komlos_split-0.1.0 → komlos_split-0.2.0}/pyproject.toml +1 -1
- {komlos_split-0.1.0 → komlos_split-0.2.0}/python/komlos_split/__init__.py +173 -62
- {komlos_split-0.1.0 → komlos_split-0.2.0}/src/lib.rs +45 -7
- {komlos_split-0.1.0 → komlos_split-0.2.0}/.gitignore +0 -0
- {komlos_split-0.1.0 → komlos_split-0.2.0}/AUDIT_DOSSIER.md +0 -0
- {komlos_split-0.1.0 → komlos_split-0.2.0}/BENCHMARK_STUDY.md +0 -0
- {komlos_split-0.1.0 → komlos_split-0.2.0}/CITATION.cff +0 -0
- {komlos_split-0.1.0 → komlos_split-0.2.0}/benches/baseline.rs +0 -0
- {komlos_split-0.1.0 → komlos_split-0.2.0}/examples/ab_test_demo.py +0 -0
- {komlos_split-0.1.0 → komlos_split-0.2.0}/examples/crossover_study.rs +0 -0
- {komlos_split-0.1.0 → komlos_split-0.2.0}/examples/profile_study.rs +0 -0
- {komlos_split-0.1.0 → komlos_split-0.2.0}/spec/invariants.dfy +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: komlos-split
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.0
|
|
4
4
|
Summary: Covariate-balanced A/B & train/val splitting via Guo-Fang-Lu Komlos Discrepancy (arXiv:2609.23540 / arXiv:2609.33215) and Gram-Schmidt Walk
|
|
5
5
|
License: MIT
|
|
6
6
|
Requires-Python: >=3.10
|
|
@@ -73,12 +73,20 @@ Works directly on **pandas DataFrames**, **Polars DataFrames**, **NumPy arrays**
|
|
|
73
73
|
import pandas as pd
|
|
74
74
|
import komlos_split
|
|
75
75
|
|
|
76
|
+
# 1. Two-way A/B split (50/50)
|
|
76
77
|
control, treatment, report = komlos_split.split_ab(
|
|
77
78
|
df, # pandas / Polars DataFrame or 2D NumPy array
|
|
78
79
|
method="auto", # auto-routes: gfl for m >= 4n, gsw for n > m
|
|
79
80
|
return_report=True,
|
|
80
81
|
)
|
|
81
82
|
print(report.summary())
|
|
83
|
+
|
|
84
|
+
# 2. Custom-ratio train/val split (e.g., 80/20)
|
|
85
|
+
train, val, tv_report = komlos_split.train_val_split(df, train_size=0.8, return_report=True)
|
|
86
|
+
|
|
87
|
+
# 3. Multi-arm A/B/C/D or k-fold CV (any k >= 2: 3, 4, 5, ...)
|
|
88
|
+
groups, k_report = komlos_split.split_k(df, k=4, return_report=True)
|
|
89
|
+
print(k_report.summary())
|
|
82
90
|
```
|
|
83
91
|
|
|
84
92
|
Verified output from `examples/ab_test_demo.py` (256 users × 24 mixed covariates, 20 simulated A/B trials):
|
|
@@ -63,12 +63,20 @@ Works directly on **pandas DataFrames**, **Polars DataFrames**, **NumPy arrays**
|
|
|
63
63
|
import pandas as pd
|
|
64
64
|
import komlos_split
|
|
65
65
|
|
|
66
|
+
# 1. Two-way A/B split (50/50)
|
|
66
67
|
control, treatment, report = komlos_split.split_ab(
|
|
67
68
|
df, # pandas / Polars DataFrame or 2D NumPy array
|
|
68
69
|
method="auto", # auto-routes: gfl for m >= 4n, gsw for n > m
|
|
69
70
|
return_report=True,
|
|
70
71
|
)
|
|
71
72
|
print(report.summary())
|
|
73
|
+
|
|
74
|
+
# 2. Custom-ratio train/val split (e.g., 80/20)
|
|
75
|
+
train, val, tv_report = komlos_split.train_val_split(df, train_size=0.8, return_report=True)
|
|
76
|
+
|
|
77
|
+
# 3. Multi-arm A/B/C/D or k-fold CV (any k >= 2: 3, 4, 5, ...)
|
|
78
|
+
groups, k_report = komlos_split.split_k(df, k=4, return_report=True)
|
|
79
|
+
print(k_report.summary())
|
|
72
80
|
```
|
|
73
81
|
|
|
74
82
|
Verified output from `examples/ab_test_demo.py` (256 users × 24 mixed covariates, 20 simulated A/B trials):
|
|
@@ -4,7 +4,7 @@ build-backend = "maturin"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "komlos-split"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.2.0"
|
|
8
8
|
description = "Covariate-balanced A/B & train/val splitting via Guo-Fang-Lu Komlos Discrepancy (arXiv:2609.23540 / arXiv:2609.33215) and Gram-Schmidt Walk"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.10"
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"""komlos-split:
|
|
1
|
+
"""komlos-split v0.2: Covariate-balanced 2-way, custom-ratio, and k-way splitting backed by Rust.
|
|
2
2
|
|
|
3
3
|
Implements the Guo-Fang-Lu Spectral-Potential Walk (arXiv:2609.23540 / arXiv:2609.33215)
|
|
4
4
|
and Gram-Schmidt Walk (STOC 2018) with automatic regime routing:
|
|
@@ -23,8 +23,10 @@ from ._komlos_split import (
|
|
|
23
23
|
|
|
24
24
|
__all__ = [
|
|
25
25
|
"BalanceReport",
|
|
26
|
+
"MultiBalanceReport",
|
|
26
27
|
"assign_groups",
|
|
27
28
|
"split_ab",
|
|
29
|
+
"split_k",
|
|
28
30
|
"train_val_split",
|
|
29
31
|
"guo_fang_lu",
|
|
30
32
|
"gram_schmidt_walk",
|
|
@@ -63,6 +65,33 @@ class BalanceReport:
|
|
|
63
65
|
return "\n".join(lines)
|
|
64
66
|
|
|
65
67
|
|
|
68
|
+
@dataclass
|
|
69
|
+
class MultiBalanceReport:
|
|
70
|
+
"""Pairwise covariate balance diagnostics across k >= 2 groups."""
|
|
71
|
+
|
|
72
|
+
k: int
|
|
73
|
+
method_used: str
|
|
74
|
+
group_sizes: list[int]
|
|
75
|
+
max_pairwise_smd: float
|
|
76
|
+
mean_pairwise_smd: float
|
|
77
|
+
random_max_pairwise_smd: float
|
|
78
|
+
|
|
79
|
+
def summary(self) -> str:
|
|
80
|
+
reduction = (
|
|
81
|
+
(1.0 - self.max_pairwise_smd / self.random_max_pairwise_smd) * 100.0
|
|
82
|
+
if self.random_max_pairwise_smd > 0.0
|
|
83
|
+
else 0.0
|
|
84
|
+
)
|
|
85
|
+
return "\n".join(
|
|
86
|
+
[
|
|
87
|
+
f"komlos-split MultiBalanceReport (k={self.k}, method={self.method_used})",
|
|
88
|
+
f" Group sizes : {self.group_sizes}",
|
|
89
|
+
f" Max Pairwise SMD : {self.max_pairwise_smd:.4f} (random: {self.random_max_pairwise_smd:.4f}, {reduction:+.1f}%)",
|
|
90
|
+
f" Mean Pairwise SMD: {self.mean_pairwise_smd:.4f}",
|
|
91
|
+
]
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
|
|
66
95
|
def _extract_matrix(
|
|
67
96
|
data: Any, covariates: Sequence[str] | None = None
|
|
68
97
|
) -> tuple[list[list[float]], list[str], str]:
|
|
@@ -70,7 +99,6 @@ def _extract_matrix(
|
|
|
70
99
|
cls_mod = type(data).__module__
|
|
71
100
|
cls_name = type(data).__name__
|
|
72
101
|
|
|
73
|
-
# 1. pandas DataFrame
|
|
74
102
|
if cls_mod.startswith("pandas") and cls_name == "DataFrame":
|
|
75
103
|
if covariates is None:
|
|
76
104
|
num_df = data.select_dtypes(include=["number", "bool"])
|
|
@@ -81,14 +109,12 @@ def _extract_matrix(
|
|
|
81
109
|
rows = num_df.astype(float).values.tolist()
|
|
82
110
|
return rows, [str(c) for c in cols], "pandas"
|
|
83
111
|
|
|
84
|
-
# 2. Polars DataFrame
|
|
85
112
|
if cls_mod.startswith("polars") and cls_name == "DataFrame":
|
|
86
113
|
cols = list(covariates) if covariates is not None else list(data.columns)
|
|
87
114
|
sub = data.select(cols)
|
|
88
115
|
rows = [[float(v) for v in r] for r in sub.iter_rows()]
|
|
89
116
|
return rows, [str(c) for c in cols], "polars"
|
|
90
117
|
|
|
91
|
-
# 3. NumPy ndarray
|
|
92
118
|
if cls_mod.startswith("numpy") and hasattr(data, "ndim"):
|
|
93
119
|
if data.ndim != 2:
|
|
94
120
|
raise ValueError(f"Expected 2D array (n_samples, n_features), got ndim={data.ndim}")
|
|
@@ -97,21 +123,17 @@ def _extract_matrix(
|
|
|
97
123
|
names = [str(c) for c in covariates] if covariates is not None else [f"f{i}" for i in range(n_feat)]
|
|
98
124
|
return rows, names, "numpy"
|
|
99
125
|
|
|
100
|
-
# 4. Plain Python sequence of rows
|
|
101
126
|
rows = [[float(v) for v in r] for r in data]
|
|
102
127
|
n_feat = len(rows[0]) if rows else 0
|
|
103
128
|
names = [str(c) for c in covariates] if covariates is not None else [f"f{i}" for i in range(n_feat)]
|
|
104
129
|
return rows, names, "list"
|
|
105
130
|
|
|
106
131
|
|
|
107
|
-
def
|
|
108
|
-
rows: list[list[float]], feature_names: list[str],
|
|
132
|
+
def _compute_smd_indices(
|
|
133
|
+
rows: list[list[float]], feature_names: list[str], idx_a: list[int], idx_b: list[int]
|
|
109
134
|
) -> tuple[float, float, dict[str, float]]:
|
|
110
|
-
"""Compute absolute Standardized Mean Difference (SMD) per feature between
|
|
111
|
-
n = len(rows)
|
|
135
|
+
"""Compute absolute Standardized Mean Difference (SMD) per feature between two index sets."""
|
|
112
136
|
m = len(feature_names)
|
|
113
|
-
idx_a = [j for j, s in enumerate(signs) if s == 1]
|
|
114
|
-
idx_b = [j for j, s in enumerate(signs) if s == -1]
|
|
115
137
|
if not idx_a or not idx_b:
|
|
116
138
|
inf_map = {name: float("inf") for name in feature_names}
|
|
117
139
|
return float("inf"), float("inf"), inf_map
|
|
@@ -132,6 +154,14 @@ def _compute_smd(
|
|
|
132
154
|
return max(vals, default=0.0), (sum(vals) / len(vals) if vals else 0.0), per_feat
|
|
133
155
|
|
|
134
156
|
|
|
157
|
+
def _compute_smd(
|
|
158
|
+
rows: list[list[float]], feature_names: list[str], signs: list[int]
|
|
159
|
+
) -> tuple[float, float, dict[str, float]]:
|
|
160
|
+
idx_a = [j for j, s in enumerate(signs) if s == 1]
|
|
161
|
+
idx_b = [j for j, s in enumerate(signs) if s == -1]
|
|
162
|
+
return _compute_smd_indices(rows, feature_names, idx_a, idx_b)
|
|
163
|
+
|
|
164
|
+
|
|
135
165
|
def _standardize_for_komlos(rows: list[list[float]], balance_size: bool = True) -> tuple[list[float], int, int]:
|
|
136
166
|
"""Z-score features, transpose to (m_rows, n_samples), append size-balance row, and unit-normalize columns."""
|
|
137
167
|
n = len(rows)
|
|
@@ -141,7 +171,6 @@ def _standardize_for_komlos(rows: list[list[float]], balance_size: bool = True)
|
|
|
141
171
|
if m == 0:
|
|
142
172
|
raise ValueError("Input data must contain at least 1 numeric covariate.")
|
|
143
173
|
|
|
144
|
-
# Validate finite inputs early
|
|
145
174
|
for r in rows:
|
|
146
175
|
if len(r) != m:
|
|
147
176
|
raise ValueError("All sample rows must have identical feature length.")
|
|
@@ -149,7 +178,6 @@ def _standardize_for_komlos(rows: list[list[float]], balance_size: bool = True)
|
|
|
149
178
|
if not math.isfinite(v):
|
|
150
179
|
raise ValueError("Input contains non-finite values (NaN or Inf). Impute or drop before splitting.")
|
|
151
180
|
|
|
152
|
-
# Z-score each feature across samples and pack row-major (m_total x n)
|
|
153
181
|
m_total = m + (1 if balance_size else 0)
|
|
154
182
|
flat = [0.0] * (m_total * n)
|
|
155
183
|
|
|
@@ -164,7 +192,6 @@ def _standardize_for_komlos(rows: list[list[float]], balance_size: bool = True)
|
|
|
164
192
|
flat[base + j] = (col[j] - mean) * inv_sd
|
|
165
193
|
|
|
166
194
|
if balance_size:
|
|
167
|
-
# Weight the headcount-balance row so |group_a| ≈ |group_b|
|
|
168
195
|
base = m * n
|
|
169
196
|
for j in range(n):
|
|
170
197
|
flat[base + j] = 1.0
|
|
@@ -173,32 +200,34 @@ def _standardize_for_komlos(rows: list[list[float]], balance_size: bool = True)
|
|
|
173
200
|
return norm_flat, m_total, n
|
|
174
201
|
|
|
175
202
|
|
|
203
|
+
def _random_signs_with_ratio(n: int, ratio: float, seed: int) -> list[int]:
|
|
204
|
+
"""Deterministic Bernoulli(ratio) +/-1 baseline."""
|
|
205
|
+
x = seed ^ 0x9E3779B97F4A7C15
|
|
206
|
+
out: list[int] = []
|
|
207
|
+
for _ in range(n):
|
|
208
|
+
x = (x + 0x9E3779B97F4A7C15) & 0xFFFFFFFFFFFFFFFF
|
|
209
|
+
z = x
|
|
210
|
+
z = ((z ^ (z >> 30)) * 0xBF58476D1CE4E5B9) & 0xFFFFFFFFFFFFFFFF
|
|
211
|
+
z = ((z ^ (z >> 27)) * 0x94D049BB133111EB) & 0xFFFFFFFFFFFFFFFF
|
|
212
|
+
z = z ^ (z >> 31)
|
|
213
|
+
u = (z >> 11) * (1.0 / (1 << 53))
|
|
214
|
+
out.append(1 if u < ratio else -1)
|
|
215
|
+
return out
|
|
216
|
+
|
|
217
|
+
|
|
176
218
|
def assign_groups(
|
|
177
219
|
data: Any,
|
|
178
220
|
covariates: Sequence[str] | None = None,
|
|
179
221
|
method: str = "auto",
|
|
222
|
+
ratio: float = 0.5,
|
|
180
223
|
seed: int = 42,
|
|
181
224
|
step_size: float = 2.0,
|
|
182
225
|
balance_size: bool = True,
|
|
183
226
|
) -> list[int]:
|
|
184
|
-
"""Return a balanced {-1, +1} assignment vector
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
data : pandas.DataFrame | polars.DataFrame | numpy.ndarray | list[list[float]]
|
|
189
|
-
Input samples of shape (n_samples, n_features).
|
|
190
|
-
covariates : sequence of str, optional
|
|
191
|
-
Column names to balance (for DataFrames). Defaults to all numeric columns.
|
|
192
|
-
method : {"auto", "gfl", "gsw", "greedy", "random"}
|
|
193
|
-
"auto" routes to Guo-Fang-Lu when n_features >= 4 * n_samples (tall/overconstrained)
|
|
194
|
-
and Gram-Schmidt Walk otherwise.
|
|
195
|
-
seed : int
|
|
196
|
-
Deterministic PRNG seed.
|
|
197
|
-
step_size : float
|
|
198
|
-
Step size eta for Guo-Fang-Lu (default 2.0; use 0.25 for tighter high-m discrepancy).
|
|
199
|
-
balance_size : bool
|
|
200
|
-
Include an explicit headcount-balance constraint so groups stay ~50/50.
|
|
201
|
-
"""
|
|
227
|
+
"""Return a balanced {-1, +1} assignment vector with target `+1` fraction `ratio` in (0, 1)."""
|
|
228
|
+
if not (0.0 < ratio < 1.0):
|
|
229
|
+
raise ValueError(f"ratio must be strictly between 0.0 and 1.0, got {ratio}")
|
|
230
|
+
|
|
202
231
|
rows, _, _ = _extract_matrix(data, covariates=covariates)
|
|
203
232
|
flat, m_total, n = _standardize_for_komlos(rows, balance_size=balance_size)
|
|
204
233
|
|
|
@@ -208,50 +237,37 @@ def assign_groups(
|
|
|
208
237
|
chosen = "gfl" if n_features >= 4 * n else "gsw"
|
|
209
238
|
|
|
210
239
|
if chosen in ("gfl", "guo_fang_lu"):
|
|
211
|
-
return list(guo_fang_lu(flat, m_total, n, step_size=step_size, seed=seed))
|
|
240
|
+
return list(guo_fang_lu(flat, m_total, n, step_size=step_size, seed=seed, ratio=ratio))
|
|
212
241
|
if chosen in ("gsw", "gram_schmidt"):
|
|
213
|
-
return list(gram_schmidt_walk(flat, m_total, n, seed=seed))
|
|
242
|
+
return list(gram_schmidt_walk(flat, m_total, n, seed=seed, ratio=ratio))
|
|
214
243
|
if chosen == "greedy":
|
|
215
244
|
return list(greedy_split(flat, m_total, n))
|
|
216
245
|
if chosen in ("random", "rademacher"):
|
|
217
|
-
return
|
|
246
|
+
return _random_signs_with_ratio(n, ratio, seed)
|
|
218
247
|
raise ValueError(f"Unknown method '{method}'. Expected one of: auto, gfl, gsw, greedy, random.")
|
|
219
248
|
|
|
220
249
|
|
|
221
|
-
def
|
|
222
|
-
mask_b = [not b for b in mask_a]
|
|
250
|
+
def _slice_indices(data: Any, kind: str, indices: list[int]) -> Any:
|
|
223
251
|
if kind == "pandas":
|
|
224
|
-
return data.
|
|
252
|
+
return data.iloc[indices].copy()
|
|
225
253
|
if kind == "polars":
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
return data.filter(pl.Series(mask_a)), data.filter(pl.Series(mask_b))
|
|
254
|
+
return data[indices]
|
|
229
255
|
if kind == "numpy":
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
arr_a = np.asarray(mask_a, dtype=bool)
|
|
233
|
-
return data[arr_a], data[~arr_a]
|
|
234
|
-
return (
|
|
235
|
-
[row for row, m in zip(data, mask_a) if m],
|
|
236
|
-
[row for row, m in zip(data, mask_b) if m],
|
|
237
|
-
)
|
|
256
|
+
return data[indices]
|
|
257
|
+
return [data[i] for i in indices]
|
|
238
258
|
|
|
239
259
|
|
|
240
260
|
def split_ab(
|
|
241
261
|
data: Any,
|
|
242
262
|
covariates: Sequence[str] | None = None,
|
|
243
263
|
method: str = "auto",
|
|
264
|
+
ratio: float = 0.5,
|
|
244
265
|
seed: int = 42,
|
|
245
266
|
step_size: float = 2.0,
|
|
246
267
|
balance_size: bool = True,
|
|
247
268
|
return_report: bool = False,
|
|
248
269
|
) -> Any:
|
|
249
|
-
"""Split `data` into two covariate-balanced groups
|
|
250
|
-
|
|
251
|
-
Preserves the input type (pandas DataFrame, Polars DataFrame, NumPy ndarray, or list).
|
|
252
|
-
Set `return_report=True` to also receive a `BalanceReport` with Standardized Mean
|
|
253
|
-
Difference (SMD) diagnostics compared against a same-seed random split.
|
|
254
|
-
"""
|
|
270
|
+
"""Split `data` into two covariate-balanced groups with target Group A fraction `ratio`."""
|
|
255
271
|
rows, feature_names, kind = _extract_matrix(data, covariates=covariates)
|
|
256
272
|
n = len(rows)
|
|
257
273
|
n_features = len(feature_names)
|
|
@@ -260,23 +276,26 @@ def split_ab(
|
|
|
260
276
|
signs = assign_groups(
|
|
261
277
|
rows,
|
|
262
278
|
method=resolved,
|
|
279
|
+
ratio=ratio,
|
|
263
280
|
seed=seed,
|
|
264
281
|
step_size=step_size,
|
|
265
282
|
balance_size=balance_size,
|
|
266
283
|
)
|
|
267
|
-
|
|
268
|
-
|
|
284
|
+
idx_a = [i for i, s in enumerate(signs) if s == 1]
|
|
285
|
+
idx_b = [i for i, s in enumerate(signs) if s == -1]
|
|
286
|
+
group_a = _slice_indices(data, kind, idx_a)
|
|
287
|
+
group_b = _slice_indices(data, kind, idx_b)
|
|
269
288
|
|
|
270
289
|
if not return_report:
|
|
271
290
|
return group_a, group_b
|
|
272
291
|
|
|
273
|
-
max_smd, mean_smd, per_feat =
|
|
274
|
-
rand_signs =
|
|
292
|
+
max_smd, mean_smd, per_feat = _compute_smd_indices(rows, feature_names, idx_a, idx_b)
|
|
293
|
+
rand_signs = _random_signs_with_ratio(n, ratio, seed)
|
|
275
294
|
r_max_smd, r_mean_smd, _ = _compute_smd(rows, feature_names, rand_signs)
|
|
276
295
|
report = BalanceReport(
|
|
277
296
|
method_used=resolved,
|
|
278
|
-
n_group_a=
|
|
279
|
-
n_group_b=
|
|
297
|
+
n_group_a=len(idx_a),
|
|
298
|
+
n_group_b=len(idx_b),
|
|
280
299
|
max_smd=max_smd,
|
|
281
300
|
mean_smd=mean_smd,
|
|
282
301
|
random_max_smd=r_max_smd,
|
|
@@ -288,16 +307,108 @@ def split_ab(
|
|
|
288
307
|
|
|
289
308
|
def train_val_split(
|
|
290
309
|
data: Any,
|
|
310
|
+
train_size: float = 0.8,
|
|
291
311
|
covariates: Sequence[str] | None = None,
|
|
292
312
|
method: str = "auto",
|
|
293
313
|
seed: int = 42,
|
|
294
314
|
return_report: bool = False,
|
|
295
315
|
) -> Any:
|
|
296
|
-
"""
|
|
316
|
+
"""Split `data` into covariate-balanced `(train, val)` with arbitrary `train_size` (default 0.8)."""
|
|
297
317
|
return split_ab(
|
|
298
318
|
data,
|
|
299
319
|
covariates=covariates,
|
|
300
320
|
method=method,
|
|
321
|
+
ratio=train_size,
|
|
301
322
|
seed=seed,
|
|
302
323
|
return_report=return_report,
|
|
303
324
|
)
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def split_k(
|
|
328
|
+
data: Any,
|
|
329
|
+
k: int = 4,
|
|
330
|
+
covariates: Sequence[str] | None = None,
|
|
331
|
+
method: str = "auto",
|
|
332
|
+
seed: int = 42,
|
|
333
|
+
step_size: float = 2.0,
|
|
334
|
+
balance_size: bool = True,
|
|
335
|
+
return_report: bool = False,
|
|
336
|
+
) -> Any:
|
|
337
|
+
"""Split `data` into `k >= 2` equally sized, covariate-balanced groups (A/B/C/D or k-fold CV).
|
|
338
|
+
|
|
339
|
+
Works for any `k >= 2` (including non-powers of 2 like 3, 5, 10) via recursive
|
|
340
|
+
ratio-weighted Komlos / Gram-Schmidt splits.
|
|
341
|
+
"""
|
|
342
|
+
if k < 2:
|
|
343
|
+
raise ValueError(f"k must be >= 2, got {k}")
|
|
344
|
+
rows, feature_names, kind = _extract_matrix(data, covariates=covariates)
|
|
345
|
+
n = len(rows)
|
|
346
|
+
if n < k:
|
|
347
|
+
raise ValueError(f"Cannot split {n} samples into {k} non-empty groups.")
|
|
348
|
+
|
|
349
|
+
n_features = len(feature_names)
|
|
350
|
+
resolved = ("gfl" if n_features >= 4 * n else "gsw") if method.lower() == "auto" else method.lower()
|
|
351
|
+
|
|
352
|
+
def _recurse(indices: list[int], arms: int, cur_seed: int) -> list[list[int]]:
|
|
353
|
+
if arms == 1:
|
|
354
|
+
return [indices]
|
|
355
|
+
left_arms = arms // 2
|
|
356
|
+
right_arms = arms - left_arms
|
|
357
|
+
sub_ratio = left_arms / arms
|
|
358
|
+
sub_rows = [rows[i] for i in indices]
|
|
359
|
+
signs = assign_groups(
|
|
360
|
+
sub_rows,
|
|
361
|
+
method=resolved,
|
|
362
|
+
ratio=sub_ratio,
|
|
363
|
+
seed=cur_seed,
|
|
364
|
+
step_size=step_size,
|
|
365
|
+
balance_size=balance_size,
|
|
366
|
+
)
|
|
367
|
+
left_idx = [idx for idx, s in zip(indices, signs) if s == 1]
|
|
368
|
+
right_idx = [idx for idx, s in zip(indices, signs) if s == -1]
|
|
369
|
+
# Safety guard if tiny subgroup degenerated
|
|
370
|
+
if len(left_idx) < left_arms or len(right_idx) < right_arms:
|
|
371
|
+
cut = max(left_arms, min(len(indices) - right_arms, round(len(indices) * sub_ratio)))
|
|
372
|
+
left_idx = indices[:cut]
|
|
373
|
+
right_idx = indices[cut:]
|
|
374
|
+
return _recurse(left_idx, left_arms, cur_seed * 31 + 1) + _recurse(
|
|
375
|
+
right_idx, right_arms, cur_seed * 31 + 2
|
|
376
|
+
)
|
|
377
|
+
|
|
378
|
+
group_indices = _recurse(list(range(n)), k, seed)
|
|
379
|
+
groups = [_slice_indices(data, kind, idxs) for idxs in group_indices]
|
|
380
|
+
|
|
381
|
+
if not return_report:
|
|
382
|
+
return groups
|
|
383
|
+
|
|
384
|
+
# Pairwise SMD across all k(k-1)/2 pairs
|
|
385
|
+
pair_maxes: list[float] = []
|
|
386
|
+
pair_means: list[float] = []
|
|
387
|
+
for i in range(k):
|
|
388
|
+
for j in range(i + 1, k):
|
|
389
|
+
mx, mn, _ = _compute_smd_indices(rows, feature_names, group_indices[i], group_indices[j])
|
|
390
|
+
pair_maxes.append(mx)
|
|
391
|
+
pair_means.append(mn)
|
|
392
|
+
|
|
393
|
+
# Same-seed random k-way baseline
|
|
394
|
+
x = seed ^ 0x9E3779B97F4A7C15
|
|
395
|
+
rand_buckets: list[list[int]] = [[] for _ in range(k)]
|
|
396
|
+
for idx in range(n):
|
|
397
|
+
x = (x + 0x9E3779B97F4A7C15) & 0xFFFFFFFFFFFFFFFF
|
|
398
|
+
z = ((x ^ (x >> 30)) * 0xBF58476D1CE4E5B9) & 0xFFFFFFFFFFFFFFFF
|
|
399
|
+
rand_buckets[(z >> 16) % k].append(idx)
|
|
400
|
+
rand_pair_maxes = [
|
|
401
|
+
_compute_smd_indices(rows, feature_names, rand_buckets[i], rand_buckets[j])[0]
|
|
402
|
+
for i in range(k)
|
|
403
|
+
for j in range(i + 1, k)
|
|
404
|
+
]
|
|
405
|
+
|
|
406
|
+
report = MultiBalanceReport(
|
|
407
|
+
k=k,
|
|
408
|
+
method_used=resolved,
|
|
409
|
+
group_sizes=[len(g) for g in group_indices],
|
|
410
|
+
max_pairwise_smd=max(pair_maxes, default=0.0),
|
|
411
|
+
mean_pairwise_smd=sum(pair_means) / len(pair_means) if pair_means else 0.0,
|
|
412
|
+
random_max_pairwise_smd=max(rand_pair_maxes, default=0.0),
|
|
413
|
+
)
|
|
414
|
+
return groups, report
|
|
@@ -216,9 +216,24 @@ fn solve_spd(g: &[f64], rhs: &[f64], k: usize) -> Vec<f64> {
|
|
|
216
216
|
/// minimizing `||A_V u||_2^2`, and moves to the boundary +/-1 with zero-mean
|
|
217
217
|
/// randomized step size so at least one coordinate freezes every iteration.
|
|
218
218
|
pub fn gram_schmidt_walk(a: &[f64], m: usize, n: usize, seed: u64) -> Result<Vec<i8>, &'static str> {
|
|
219
|
+
gram_schmidt_walk_with_ratio(a, m, n, 0.5, seed)
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/// Gram–Schmidt Walk starting from fractional point `x_0 = (2 * ratio - 1) * 1`
|
|
223
|
+
/// for arbitrary split ratios `ratio in (0, 1)` (e.g., 0.8 for 80/20 train/val).
|
|
224
|
+
pub fn gram_schmidt_walk_with_ratio(
|
|
225
|
+
a: &[f64],
|
|
226
|
+
m: usize,
|
|
227
|
+
n: usize,
|
|
228
|
+
ratio: f64,
|
|
229
|
+
seed: u64,
|
|
230
|
+
) -> Result<Vec<i8>, &'static str> {
|
|
219
231
|
validate_matrix(a, m, n)?;
|
|
232
|
+
if !ratio.is_finite() || ratio <= 0.0 || ratio >= 1.0 {
|
|
233
|
+
return Err("ratio must be strictly between 0.0 and 1.0");
|
|
234
|
+
}
|
|
220
235
|
let mut rng = Rng64::new(seed);
|
|
221
|
-
let mut x = vec![0.
|
|
236
|
+
let mut x = vec![2.0 * ratio - 1.0; n];
|
|
222
237
|
let mut alive: Vec<usize> = (0..n).collect();
|
|
223
238
|
let eps = 1e-9;
|
|
224
239
|
|
|
@@ -361,6 +376,8 @@ pub struct GflConfig {
|
|
|
361
376
|
pub step_size: f64,
|
|
362
377
|
/// Slack threshold `sigma_crit` below which a medium row is marked dangerous.
|
|
363
378
|
pub danger_slack: f64,
|
|
379
|
+
/// Target fraction of `+1` assignments in `(0, 1)` (default `0.5` -> `x_0 = 0`).
|
|
380
|
+
pub ratio: f64,
|
|
364
381
|
/// Deterministic PRNG seed for initial subspace direction sampling.
|
|
365
382
|
pub seed: u64,
|
|
366
383
|
}
|
|
@@ -371,6 +388,7 @@ impl Default for GflConfig {
|
|
|
371
388
|
target_beta: 0.0,
|
|
372
389
|
step_size: 2.0,
|
|
373
390
|
danger_slack: 0.5,
|
|
391
|
+
ratio: 0.5,
|
|
374
392
|
seed: 42,
|
|
375
393
|
}
|
|
376
394
|
}
|
|
@@ -446,8 +464,12 @@ pub fn guo_fang_lu_walk(
|
|
|
446
464
|
cfg: GflConfig,
|
|
447
465
|
) -> Result<Vec<i8>, &'static str> {
|
|
448
466
|
validate_matrix(a, m, n)?;
|
|
467
|
+
if !cfg.ratio.is_finite() || cfg.ratio <= 0.0 || cfg.ratio >= 1.0 {
|
|
468
|
+
return Err("cfg.ratio must be strictly between 0.0 and 1.0");
|
|
469
|
+
}
|
|
449
470
|
let mut rng = Rng64::new(cfg.seed);
|
|
450
|
-
let
|
|
471
|
+
let x0_val = 2.0 * cfg.ratio - 1.0;
|
|
472
|
+
let mut x = vec![x0_val; n];
|
|
451
473
|
let mut alive: Vec<usize> = (0..n).collect();
|
|
452
474
|
let eps = 1e-8;
|
|
453
475
|
const K_KOMLOS: f64 = 16.0;
|
|
@@ -473,6 +495,7 @@ pub fn guo_fang_lu_walk(
|
|
|
473
495
|
};
|
|
474
496
|
|
|
475
497
|
// One-sided doubled rows: indices 0..m are +a_i, indices m..2m are -a_i.
|
|
498
|
+
// Track discrepancy relative to starting point x_0 (so d_0(i) = <a_i, x - x_0> = 0).
|
|
476
499
|
let m2 = 2 * m;
|
|
477
500
|
let mut row_disc = vec![0.0f64; m2];
|
|
478
501
|
// Section 4 heavy-entry tracking mask: tracked[i * n + j] == true while j is in S_{i,t}.
|
|
@@ -972,10 +995,18 @@ pub fn guo_fang_lu_walk(
|
|
|
972
995
|
|
|
973
996
|
#[cfg(feature = "python")]
|
|
974
997
|
#[pyfunction]
|
|
975
|
-
#[pyo3(signature = (a, m, n, step_size = 0
|
|
976
|
-
fn py_guo_fang_lu(
|
|
998
|
+
#[pyo3(signature = (a, m, n, step_size = 2.0, seed = 42, ratio = 0.5))]
|
|
999
|
+
fn py_guo_fang_lu(
|
|
1000
|
+
a: Vec<f64>,
|
|
1001
|
+
m: usize,
|
|
1002
|
+
n: usize,
|
|
1003
|
+
step_size: f64,
|
|
1004
|
+
seed: u64,
|
|
1005
|
+
ratio: f64,
|
|
1006
|
+
) -> PyResult<Vec<i8>> {
|
|
977
1007
|
let cfg = GflConfig {
|
|
978
1008
|
step_size,
|
|
1009
|
+
ratio,
|
|
979
1010
|
seed,
|
|
980
1011
|
..GflConfig::default()
|
|
981
1012
|
};
|
|
@@ -984,9 +1015,16 @@ fn py_guo_fang_lu(a: Vec<f64>, m: usize, n: usize, step_size: f64, seed: u64) ->
|
|
|
984
1015
|
|
|
985
1016
|
#[cfg(feature = "python")]
|
|
986
1017
|
#[pyfunction]
|
|
987
|
-
#[pyo3(signature = (a, m, n, seed = 42))]
|
|
988
|
-
fn py_gram_schmidt_walk(
|
|
989
|
-
|
|
1018
|
+
#[pyo3(signature = (a, m, n, seed = 42, ratio = 0.5))]
|
|
1019
|
+
fn py_gram_schmidt_walk(
|
|
1020
|
+
a: Vec<f64>,
|
|
1021
|
+
m: usize,
|
|
1022
|
+
n: usize,
|
|
1023
|
+
seed: u64,
|
|
1024
|
+
ratio: f64,
|
|
1025
|
+
) -> PyResult<Vec<i8>> {
|
|
1026
|
+
gram_schmidt_walk_with_ratio(&a, m, n, ratio, seed)
|
|
1027
|
+
.map_err(pyo3::exceptions::PyValueError::new_err)
|
|
990
1028
|
}
|
|
991
1029
|
|
|
992
1030
|
#[cfg(feature = "python")]
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|