srdkit 1.0__py3-none-any.whl
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.
- srdkit/__init__.py +101 -0
- srdkit/_utils.py +75 -0
- srdkit/_version.py +1 -0
- srdkit/anova.py +185 -0
- srdkit/clustering.py +110 -0
- srdkit/core.py +364 -0
- srdkit/datasets/__init__.py +160 -0
- srdkit/datasets/data/co2_2018.csv +148 -0
- srdkit/diagnostics.py +186 -0
- srdkit/distances.py +204 -0
- srdkit/distribution.py +503 -0
- srdkit/framework.py +368 -0
- srdkit/fusion.py +221 -0
- srdkit/gpcm.py +138 -0
- srdkit/mcda.py +201 -0
- srdkit/nmf.py +141 -0
- srdkit/parcoord.py +283 -0
- srdkit/pareto.py +126 -0
- srdkit/promethee.py +371 -0
- srdkit/ranking.py +193 -0
- srdkit/reference.py +232 -0
- srdkit/report.py +114 -0
- srdkit/representation.py +127 -0
- srdkit/segmentation.py +247 -0
- srdkit/simulate.py +171 -0
- srdkit/tournament.py +167 -0
- srdkit/utility.py +277 -0
- srdkit/validation.py +501 -0
- srdkit/value.py +189 -0
- srdkit/viz/__init__.py +31 -0
- srdkit/viz/_style.py +87 -0
- srdkit/viz/applications.py +156 -0
- srdkit/viz/basic.py +201 -0
- srdkit/viz/framework.py +148 -0
- srdkit/viz/maps.py +145 -0
- srdkit/viz/validation.py +149 -0
- srdkit/weighted.py +167 -0
- srdkit/weights.py +230 -0
- srdkit-1.0.dist-info/METADATA +151 -0
- srdkit-1.0.dist-info/RECORD +42 -0
- srdkit-1.0.dist-info/WHEEL +4 -0
- srdkit-1.0.dist-info/licenses/LICENSE +21 -0
srdkit/validation.py
ADDED
|
@@ -0,0 +1,501 @@
|
|
|
1
|
+
r"""Validation of SRD: randomization test (CRRN), cross-validation and statistical tests.
|
|
2
|
+
|
|
3
|
+
The SRD procedure has two validation steps (Héberger and Kollár-Hunek, 2011;
|
|
4
|
+
Kollár-Hunek and Héberger, 2013):
|
|
5
|
+
|
|
6
|
+
1. **CRRN** (comparison of ranks with random numbers) locates every SRD value in
|
|
7
|
+
the null distribution of random rankings. Values below the 5% point (XX1) are
|
|
8
|
+
*better than random* (similar to the reference), values above the 95% point
|
|
9
|
+
(XX19) are *reversed*, values between them cannot be told from a random
|
|
10
|
+
ranking. :func:`crrn` uses the exact distribution of
|
|
11
|
+
:mod:`srdkit.distribution`, computed for the tie pattern of every column.
|
|
12
|
+
2. **Cross-validation** assigns an uncertainty to every SRD value by repeating
|
|
13
|
+
the analysis on subsets of the rows, and paired tests decide whether two
|
|
14
|
+
solutions differ. :func:`cross_validate` implements random (Monte Carlo)
|
|
15
|
+
resampling, k-fold, contiguous (stratified) blocks, leave-one-out, bootstrap and
|
|
16
|
+
the 5x2 scheme; :meth:`CVResult.test` provides the Wilcoxon signed-rank test
|
|
17
|
+
(Kollár-Hunek and Héberger, 2013), the Dietterich 5x2cv *t*-test and the Alpaydin
|
|
18
|
+
5x2cv *F*-test as adapted to SRD by Sziklai, Baranyi and Héberger (2025), and,
|
|
19
|
+
as additions, the sign test, an exact paired permutation test and the corrected
|
|
20
|
+
resampled *t*-test of Nadeau and Bengio (2003). :meth:`CVResult.friedman` gives
|
|
21
|
+
the Friedman test with the Nemenyi critical difference (Demšar, 2006), and
|
|
22
|
+
:meth:`CVResult.groups` a compact letter display of indistinguishable solutions.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import itertools
|
|
28
|
+
import math
|
|
29
|
+
from dataclasses import dataclass, field
|
|
30
|
+
|
|
31
|
+
import numpy as np
|
|
32
|
+
import pandas as pd
|
|
33
|
+
from scipy import stats
|
|
34
|
+
|
|
35
|
+
from ._utils import as_frame, as_rng, srd_max
|
|
36
|
+
from .core import SRDResult, srd
|
|
37
|
+
from .distribution import PERCENTILES, SRDDistribution, null_distribution
|
|
38
|
+
from .ranking import tie_blocks
|
|
39
|
+
|
|
40
|
+
VERDICTS = ("similar", "random", "reversed")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
# =========================================================================== CRRN
|
|
44
|
+
@dataclass
|
|
45
|
+
class CRRNResult:
|
|
46
|
+
"""Outcome of the comparison of ranks with random numbers.
|
|
47
|
+
|
|
48
|
+
``table`` holds, for every solution, the SRD value, its normalized value, the
|
|
49
|
+
lower tail probability ``p_lower = P(D <= SRD)`` (small: better than random),
|
|
50
|
+
the upper tail probability ``p_upper = P(D >= SRD)`` (small: reversed) and the
|
|
51
|
+
verdict. ``distribution`` is the null distribution drawn on SRD plots (the one
|
|
52
|
+
of a tie-free solution against the reference); ``distributions`` holds the
|
|
53
|
+
distribution actually used for every column.
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
table: pd.DataFrame
|
|
57
|
+
distribution: SRDDistribution
|
|
58
|
+
distributions: dict
|
|
59
|
+
alpha: float
|
|
60
|
+
result: SRDResult | None = None
|
|
61
|
+
|
|
62
|
+
@property
|
|
63
|
+
def percentiles(self) -> dict:
|
|
64
|
+
return self.distribution.percentiles(normalized=True)
|
|
65
|
+
|
|
66
|
+
def __repr__(self) -> str:
|
|
67
|
+
p = self.percentiles
|
|
68
|
+
head = (f"CRRNResult(n={self.distribution.n}, kind={self.distribution.kind!r}, alpha={self.alpha}, "
|
|
69
|
+
f"XX1={p['XX1']:.4f}, Med={p['Med']:.4f}, XX19={p['XX19']:.4f})")
|
|
70
|
+
return head + "\n" + self.table.round(4).to_string()
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _verdict(pl: float, pu: float, alpha: float) -> str:
|
|
74
|
+
if pl <= alpha:
|
|
75
|
+
return "similar"
|
|
76
|
+
if pu <= alpha:
|
|
77
|
+
return "reversed"
|
|
78
|
+
return "random"
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def crrn(result, reference="mean", method: str = "auto", alpha: float = 0.05, per_column: bool = True,
|
|
82
|
+
n_sim: int = 100_000, random_state=None, **srd_kwargs) -> CRRNResult:
|
|
83
|
+
"""Comparison of ranks with random numbers (randomization test of SRD).
|
|
84
|
+
|
|
85
|
+
Parameters
|
|
86
|
+
----------
|
|
87
|
+
result : SRDResult or array-like
|
|
88
|
+
An SRD result, or a data matrix (then :func:`srdkit.srd` is called with
|
|
89
|
+
``reference`` and ``srd_kwargs``).
|
|
90
|
+
method : {"auto", "exact", "enumerate", "monte-carlo", "normal"}
|
|
91
|
+
How the null distribution is obtained (see :func:`srdkit.null_distribution`).
|
|
92
|
+
alpha : float
|
|
93
|
+
Error level of both tails (5% gives the XX1 and XX19 limits).
|
|
94
|
+
per_column : bool
|
|
95
|
+
Use the exact distribution of every column's own tie pattern (default).
|
|
96
|
+
With ``False`` a single distribution (tie-free solution, the reference's
|
|
97
|
+
tie pattern) is used for all columns, as on the classical SRD plots.
|
|
98
|
+
|
|
99
|
+
Examples
|
|
100
|
+
--------
|
|
101
|
+
>>> import numpy as np
|
|
102
|
+
>>> rng = np.random.default_rng(1)
|
|
103
|
+
>>> y = np.arange(12.0)
|
|
104
|
+
>>> X = np.column_stack([y + rng.normal(0, 1, 12), rng.normal(0, 1, 12), -y])
|
|
105
|
+
>>> crrn(X, reference=y).table["verdict"].tolist()
|
|
106
|
+
['similar', 'random', 'reversed']
|
|
107
|
+
"""
|
|
108
|
+
if not isinstance(result, SRDResult):
|
|
109
|
+
result = srd(result, reference=reference, **srd_kwargs)
|
|
110
|
+
if result.distance != "footrule" or result.meta.get("soft_sigma") is not None:
|
|
111
|
+
per_column = False
|
|
112
|
+
q = result.reference_ranks
|
|
113
|
+
n = result.n
|
|
114
|
+
qd = q if q.ndim == 1 else q[:, 0]
|
|
115
|
+
display = null_distribution(None, qd, n, method=method, distance=result.distance, n_sim=n_sim, random_state=random_state)
|
|
116
|
+
dists, rows = {}, []
|
|
117
|
+
cache: dict = {}
|
|
118
|
+
for j, c in enumerate(result.columns):
|
|
119
|
+
if per_column:
|
|
120
|
+
xr = result.ranks[c].to_numpy()
|
|
121
|
+
qj = q if q.ndim == 1 else q[:, j]
|
|
122
|
+
key = (tuple(tie_blocks(xr)), tuple(tie_blocks(qj)))
|
|
123
|
+
if key not in cache:
|
|
124
|
+
cache[key] = null_distribution(xr, qj, n, method=method, n_sim=n_sim, random_state=random_state)
|
|
125
|
+
d = cache[key]
|
|
126
|
+
else:
|
|
127
|
+
d = display
|
|
128
|
+
dists[c] = d
|
|
129
|
+
val = float(result.srd[c])
|
|
130
|
+
pl, pu = d.cdf(val), d.sf(val)
|
|
131
|
+
rows.append({"solution": c, "SRD": val, "SRD%": 100 * val / result.srd_max if result.srd_max else np.nan,
|
|
132
|
+
"p_lower": pl, "p_upper": pu, "verdict": _verdict(pl, pu, alpha)})
|
|
133
|
+
table = pd.DataFrame(rows).set_index("solution").sort_values("SRD", kind="stable")
|
|
134
|
+
return CRRNResult(table=table, distribution=display, distributions=dists, alpha=alpha, result=result)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
# =========================================================================== cross-validation
|
|
138
|
+
CV_SCHEMES = ("random", "kfold", "contiguous", "loo", "bootstrap", "5x2")
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
@dataclass
|
|
142
|
+
class CVResult:
|
|
143
|
+
"""Cross-validated SRD values.
|
|
144
|
+
|
|
145
|
+
``folds`` is a DataFrame (folds x solutions) of normalized SRD values computed
|
|
146
|
+
on the retained rows of every fold. For the 5x2 scheme ``complement`` holds
|
|
147
|
+
the values on the complementary halves.
|
|
148
|
+
"""
|
|
149
|
+
|
|
150
|
+
folds: pd.DataFrame
|
|
151
|
+
scheme: str
|
|
152
|
+
n_folds: int
|
|
153
|
+
fold_rows: list
|
|
154
|
+
complement: pd.DataFrame | None = None
|
|
155
|
+
complement_rows: list | None = None
|
|
156
|
+
full: pd.Series | None = None
|
|
157
|
+
n: int = 0
|
|
158
|
+
meta: dict = field(default_factory=dict)
|
|
159
|
+
|
|
160
|
+
# ---------------------------------------------------------------- summaries
|
|
161
|
+
def summary(self) -> pd.DataFrame:
|
|
162
|
+
"""Box-plot statistics of every solution, ordered by the median."""
|
|
163
|
+
f = self.folds
|
|
164
|
+
tab = pd.DataFrame({"min": f.min(), "XX1": f.quantile(0.05), "Q1": f.quantile(0.25), "median": f.median(),
|
|
165
|
+
"Q3": f.quantile(0.75), "XX19": f.quantile(0.95), "max": f.max(), "mean": f.mean(),
|
|
166
|
+
"std": f.std(ddof=1)})
|
|
167
|
+
if self.full is not None:
|
|
168
|
+
tab.insert(0, "full", self.full)
|
|
169
|
+
tab.index.name = "solution"
|
|
170
|
+
return tab.sort_values(["median", "mean"], kind="stable")
|
|
171
|
+
|
|
172
|
+
@property
|
|
173
|
+
def order(self) -> list[str]:
|
|
174
|
+
return list(self.summary().index)
|
|
175
|
+
|
|
176
|
+
# ---------------------------------------------------------------- tests
|
|
177
|
+
def test(self, test: str = "wilcoxon", pairs: str = "consecutive", alpha: float = 0.05, correction: str | None = None,
|
|
178
|
+
random_state=None) -> pd.DataFrame:
|
|
179
|
+
"""Paired tests between solutions.
|
|
180
|
+
|
|
181
|
+
Parameters
|
|
182
|
+
----------
|
|
183
|
+
test : {"wilcoxon", "dietterich", "alpaydin", "nadeau-bengio", "sign", "permutation"}
|
|
184
|
+
``"dietterich"`` and ``"alpaydin"`` need ``scheme="5x2"``.
|
|
185
|
+
pairs : {"consecutive", "all"} or list of pairs
|
|
186
|
+
``"consecutive"`` tests the neighbours in the order of the medians (as
|
|
187
|
+
the rSRD package does), ``"all"`` every pair.
|
|
188
|
+
correction : {None, "holm", "bonferroni"}
|
|
189
|
+
Multiple-testing correction of the p-values.
|
|
190
|
+
"""
|
|
191
|
+
order = self.order
|
|
192
|
+
if pairs == "consecutive":
|
|
193
|
+
plist = list(zip(order[:-1], order[1:]))
|
|
194
|
+
elif pairs == "all":
|
|
195
|
+
plist = list(itertools.combinations(order, 2))
|
|
196
|
+
else:
|
|
197
|
+
plist = [tuple(p) for p in pairs]
|
|
198
|
+
rows = []
|
|
199
|
+
for a, b in plist:
|
|
200
|
+
stat, p = _paired_test(self, a, b, test, random_state)
|
|
201
|
+
rows.append({"A": a, "B": b, "statistic": stat, "p": p})
|
|
202
|
+
df = pd.DataFrame(rows)
|
|
203
|
+
if df.empty:
|
|
204
|
+
return df
|
|
205
|
+
if correction in ("holm", "bonferroni"):
|
|
206
|
+
df["p_adj"] = _adjust(df["p"].to_numpy(), correction)
|
|
207
|
+
else:
|
|
208
|
+
df["p_adj"] = df["p"]
|
|
209
|
+
df["significant"] = df["p_adj"] < alpha
|
|
210
|
+
df["mark"] = [_stars(p) for p in df["p_adj"]]
|
|
211
|
+
df.attrs["test"] = test
|
|
212
|
+
return df
|
|
213
|
+
|
|
214
|
+
def friedman(self, alpha: float = 0.05) -> dict:
|
|
215
|
+
"""Friedman test over the folds and the Nemenyi critical difference of the mean ranks."""
|
|
216
|
+
F = self.folds.to_numpy()
|
|
217
|
+
k = F.shape[1]
|
|
218
|
+
if k < 3:
|
|
219
|
+
raise ValueError("the Friedman test needs at least three solutions")
|
|
220
|
+
stat, p = stats.friedmanchisquare(*[F[:, j] for j in range(k)])
|
|
221
|
+
ranks = np.apply_along_axis(stats.rankdata, 1, F)
|
|
222
|
+
mean_ranks = pd.Series(ranks.mean(axis=0), index=self.folds.columns).sort_values()
|
|
223
|
+
N = F.shape[0]
|
|
224
|
+
q = stats.studentized_range.ppf(1 - alpha, k, np.inf) / math.sqrt(2)
|
|
225
|
+
cd = q * math.sqrt(k * (k + 1) / (6 * N))
|
|
226
|
+
return {"statistic": float(stat), "p": float(p), "mean_ranks": mean_ranks, "cd": float(cd), "alpha": alpha,
|
|
227
|
+
"n_folds": N}
|
|
228
|
+
|
|
229
|
+
def groups(self, test: str = "wilcoxon", alpha: float = 0.05, correction: str | None = None) -> pd.Series:
|
|
230
|
+
"""Compact letter display: solutions sharing a letter are not significantly different.
|
|
231
|
+
|
|
232
|
+
All pairs are tested; without ``correction`` (the SRD practice) the
|
|
233
|
+
letters agree with the consecutive tests, with ``"holm"`` they control the
|
|
234
|
+
family-wise error rate (with seven or eight folds the smallest attainable
|
|
235
|
+
Wilcoxon p-value is 2/2^k, so a correction may leave no pair significant).
|
|
236
|
+
"""
|
|
237
|
+
res = self.test(test=test, pairs="all", alpha=alpha, correction=correction)
|
|
238
|
+
sig = {(r.A, r.B) for r in res.itertuples() if r.significant}
|
|
239
|
+
return compact_letters(self.order, sig)
|
|
240
|
+
|
|
241
|
+
def plot(self, ax=None, **kwargs):
|
|
242
|
+
from .viz import plot_cv
|
|
243
|
+
|
|
244
|
+
return plot_cv(self, ax=ax, **kwargs)
|
|
245
|
+
|
|
246
|
+
def __repr__(self) -> str:
|
|
247
|
+
return f"CVResult(scheme={self.scheme!r}, n_folds={self.n_folds})\n" + self.summary().round(4).to_string()
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def _stars(p: float) -> str:
|
|
251
|
+
if not np.isfinite(p):
|
|
252
|
+
return ""
|
|
253
|
+
return "***" if p < 0.001 else "**" if p < 0.01 else "*" if p < 0.05 else "." if p < 0.1 else "n.s."
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def _adjust(p: np.ndarray, how: str) -> np.ndarray:
|
|
257
|
+
p = np.asarray(p, dtype=float)
|
|
258
|
+
m = p.size
|
|
259
|
+
if how == "bonferroni":
|
|
260
|
+
return np.minimum(1.0, p * m)
|
|
261
|
+
order = np.argsort(p)
|
|
262
|
+
adj = np.empty(m)
|
|
263
|
+
run = 0.0
|
|
264
|
+
for rank, i in enumerate(order):
|
|
265
|
+
run = max(run, (m - rank) * p[i])
|
|
266
|
+
adj[i] = min(1.0, run)
|
|
267
|
+
return adj
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _paired_test(cv: CVResult, a: str, b: str, test: str, random_state=None) -> tuple[float, float]:
|
|
271
|
+
x = cv.folds[a].to_numpy()
|
|
272
|
+
y = cv.folds[b].to_numpy()
|
|
273
|
+
d = x - y
|
|
274
|
+
if test == "wilcoxon":
|
|
275
|
+
if np.allclose(d, 0):
|
|
276
|
+
return 0.0, 1.0
|
|
277
|
+
r = stats.wilcoxon(x, y, zero_method="wilcox", alternative="two-sided")
|
|
278
|
+
return float(r.statistic), float(r.pvalue)
|
|
279
|
+
if test == "sign":
|
|
280
|
+
pos, neg = int((d > 0).sum()), int((d < 0).sum())
|
|
281
|
+
if pos + neg == 0:
|
|
282
|
+
return 0.0, 1.0
|
|
283
|
+
return float(pos - neg), float(stats.binomtest(pos, pos + neg, 0.5).pvalue)
|
|
284
|
+
if test == "permutation":
|
|
285
|
+
dd = d[d != 0]
|
|
286
|
+
if dd.size == 0:
|
|
287
|
+
return 0.0, 1.0
|
|
288
|
+
obs = abs(dd.sum())
|
|
289
|
+
if dd.size <= 20:
|
|
290
|
+
signs = np.array(list(itertools.product([-1, 1], repeat=dd.size)))
|
|
291
|
+
else:
|
|
292
|
+
rng = as_rng(random_state)
|
|
293
|
+
signs = rng.choice([-1, 1], size=(100_000, dd.size))
|
|
294
|
+
null = np.abs(signs @ dd)
|
|
295
|
+
return float(dd.sum()), float(np.mean(null >= obs - 1e-12))
|
|
296
|
+
if test in ("nadeau-bengio", "nadeau_bengio", "corrected-t"):
|
|
297
|
+
J = d.size
|
|
298
|
+
n_test = cv.meta.get("n_left_out", 1)
|
|
299
|
+
n_train = cv.meta.get("n_kept", max(cv.n - n_test, 1))
|
|
300
|
+
s2 = d.var(ddof=1)
|
|
301
|
+
if s2 <= 0:
|
|
302
|
+
return 0.0, 1.0
|
|
303
|
+
t = d.mean() / math.sqrt((1.0 / J + n_test / n_train) * s2)
|
|
304
|
+
return float(t), float(2 * stats.t.sf(abs(t), J - 1))
|
|
305
|
+
if test in ("dietterich", "alpaydin"):
|
|
306
|
+
if cv.complement is None:
|
|
307
|
+
raise ValueError(f"the {test} test needs scheme='5x2'")
|
|
308
|
+
dc = cv.complement[a].to_numpy() - cv.complement[b].to_numpy()
|
|
309
|
+
mean_i = (d + dc) / 2
|
|
310
|
+
s2 = (d - mean_i) ** 2 + (dc - mean_i) ** 2
|
|
311
|
+
k = d.size
|
|
312
|
+
if s2.sum() <= 0:
|
|
313
|
+
return 0.0, 1.0
|
|
314
|
+
if test == "dietterich":
|
|
315
|
+
t = d[0] / math.sqrt(s2.mean())
|
|
316
|
+
return float(t), float(2 * stats.t.sf(abs(t), k))
|
|
317
|
+
f = (d ** 2 + dc ** 2).sum() / (2 * s2.sum())
|
|
318
|
+
return float(f), float(stats.f.sf(f, 2 * k, k))
|
|
319
|
+
raise ValueError(f"unknown test {test!r}")
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def compact_letters(order: list, significant_pairs: set) -> pd.Series:
|
|
323
|
+
"""Compact letter display by the insert-and-absorb algorithm (Piepho, 2004)."""
|
|
324
|
+
groups = [set(order)]
|
|
325
|
+
for a, b in significant_pairs:
|
|
326
|
+
new = []
|
|
327
|
+
for g in groups:
|
|
328
|
+
if a in g and b in g:
|
|
329
|
+
new += [g - {a}, g - {b}]
|
|
330
|
+
else:
|
|
331
|
+
new.append(g)
|
|
332
|
+
groups = [g for g in new if not any(g < h for h in new)]
|
|
333
|
+
uniq = []
|
|
334
|
+
for g in groups:
|
|
335
|
+
if g not in uniq:
|
|
336
|
+
uniq.append(g)
|
|
337
|
+
groups = uniq
|
|
338
|
+
pos = {s: i for i, s in enumerate(order)}
|
|
339
|
+
groups.sort(key=lambda g: min(pos[s] for s in g))
|
|
340
|
+
letters = "abcdefghijklmnopqrstuvwxyz"
|
|
341
|
+
out = {s: "".join(letters[k % 26] for k, g in enumerate(groups) if s in g) for s in order}
|
|
342
|
+
return pd.Series(out, name="group")
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def _fold_reference(reference, df_sub, rows):
|
|
346
|
+
if isinstance(reference, str) or callable(reference):
|
|
347
|
+
return reference
|
|
348
|
+
ref = np.asarray(reference, dtype=float)
|
|
349
|
+
return ref[rows] if ref.ndim == 1 else ref[rows, :]
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def cross_validate(X, reference="mean", scheme: str = "random", n_folds: int = 7, n_repeats: int = 1, ties: str = "average",
|
|
353
|
+
random_state=None, reference_kwargs: dict | None = None, measure="srd", **srd_kwargs) -> CVResult:
|
|
354
|
+
r"""Cross-validated SRD values.
|
|
355
|
+
|
|
356
|
+
Parameters
|
|
357
|
+
----------
|
|
358
|
+
X : array-like or DataFrame
|
|
359
|
+
The input matrix.
|
|
360
|
+
reference : str, callable or array-like
|
|
361
|
+
Reference specification; an aggregated reference is recomputed on the
|
|
362
|
+
retained rows of every fold, an external one is subset.
|
|
363
|
+
scheme : {"random", "kfold", "contiguous", "loo", "bootstrap", "5x2"}
|
|
364
|
+
``"random"``: every fold leaves out :math:`\lceil n/k\rceil` randomly chosen
|
|
365
|
+
rows (repeated Monte Carlo resampling; the folds may overlap, as in the
|
|
366
|
+
rSRD package). ``"kfold"``: a random partition into ``n_folds`` groups, each
|
|
367
|
+
left out once. ``"contiguous"``: the same with contiguous blocks in the
|
|
368
|
+
given row order (stratified when the rows are sorted). ``"loo"``:
|
|
369
|
+
leave-one-out. ``"bootstrap"``: ``n_folds`` bootstrap samples of the rows.
|
|
370
|
+
``"5x2"``: ``n_folds`` random halvings (5 in the original tests); the SRD
|
|
371
|
+
values of the complementary halves are kept for the Dietterich and Alpaydin
|
|
372
|
+
tests.
|
|
373
|
+
n_folds : int
|
|
374
|
+
Number of folds (7 or 8 are the usual choices for SRD).
|
|
375
|
+
n_repeats : int
|
|
376
|
+
Repetitions of ``"kfold"``/``"contiguous"``/``"random"`` with new random splits.
|
|
377
|
+
measure : {"srd", "dne", "dnm"} or float or callable
|
|
378
|
+
The cross-validated measure: SRD (default), the value-based DnE or DnM of
|
|
379
|
+
Héberger (2026) (a float gives the general :math:`L_p` version), or a
|
|
380
|
+
callable ``f(sub, reference) -> Series`` of normalized values.
|
|
381
|
+
|
|
382
|
+
Returns
|
|
383
|
+
-------
|
|
384
|
+
CVResult
|
|
385
|
+
"""
|
|
386
|
+
df = as_frame(X)
|
|
387
|
+
n = df.shape[0]
|
|
388
|
+
rng = as_rng(random_state)
|
|
389
|
+
rk = reference_kwargs or {}
|
|
390
|
+
folds_rows: list[np.ndarray] = []
|
|
391
|
+
comp_rows: list[np.ndarray] = []
|
|
392
|
+
left_out = 0
|
|
393
|
+
if scheme == "random":
|
|
394
|
+
k = int(n_folds)
|
|
395
|
+
left_out = math.ceil(n / k)
|
|
396
|
+
for _ in range(n_repeats):
|
|
397
|
+
for _ in range(k):
|
|
398
|
+
out = rng.choice(n, size=left_out, replace=False)
|
|
399
|
+
folds_rows.append(np.setdiff1d(np.arange(n), out))
|
|
400
|
+
elif scheme in ("kfold", "contiguous"):
|
|
401
|
+
k = min(int(n_folds), n)
|
|
402
|
+
for _ in range(n_repeats):
|
|
403
|
+
idx = np.arange(n) if scheme == "contiguous" else rng.permutation(n)
|
|
404
|
+
parts = np.array_split(idx, k)
|
|
405
|
+
left_out = max(len(p) for p in parts)
|
|
406
|
+
for p in parts:
|
|
407
|
+
folds_rows.append(np.setdiff1d(np.arange(n), p))
|
|
408
|
+
elif scheme == "loo":
|
|
409
|
+
left_out = 1
|
|
410
|
+
for i in range(n):
|
|
411
|
+
folds_rows.append(np.delete(np.arange(n), i))
|
|
412
|
+
elif scheme == "bootstrap":
|
|
413
|
+
for _ in range(int(n_folds)):
|
|
414
|
+
folds_rows.append(np.sort(rng.integers(0, n, size=n)))
|
|
415
|
+
left_out = int(round(n * math.exp(-1)))
|
|
416
|
+
elif scheme == "5x2":
|
|
417
|
+
for _ in range(int(n_folds)):
|
|
418
|
+
perm = rng.permutation(n)
|
|
419
|
+
half = n // 2
|
|
420
|
+
folds_rows.append(np.sort(perm[:half]))
|
|
421
|
+
comp_rows.append(np.sort(perm[half:]))
|
|
422
|
+
left_out = n - n // 2
|
|
423
|
+
else:
|
|
424
|
+
raise ValueError(f"scheme must be one of {CV_SCHEMES}")
|
|
425
|
+
|
|
426
|
+
p_value = {"dne": 2.0, "dnm": 1.0}.get(measure, measure) if not callable(measure) else None
|
|
427
|
+
if not callable(measure) and measure != "srd" and not isinstance(p_value, (int, float)):
|
|
428
|
+
raise ValueError("measure must be 'srd', 'dne', 'dnm', a number p or a callable")
|
|
429
|
+
|
|
430
|
+
def evaluate(sub, ref):
|
|
431
|
+
if callable(measure):
|
|
432
|
+
return pd.Series(measure(sub, ref), index=sub.columns, dtype=float)
|
|
433
|
+
if measure == "srd":
|
|
434
|
+
return srd(sub, reference=ref, ties=ties, **rk, **srd_kwargs).normalized
|
|
435
|
+
from .value import value_srd
|
|
436
|
+
|
|
437
|
+
return value_srd(sub, reference=ref, p=float(p_value), **rk).normalized
|
|
438
|
+
|
|
439
|
+
def run(rows):
|
|
440
|
+
sub = df.iloc[rows]
|
|
441
|
+
return evaluate(sub, _fold_reference(reference, sub, rows))
|
|
442
|
+
|
|
443
|
+
vals = [run(r) for r in folds_rows]
|
|
444
|
+
folds = pd.DataFrame(vals, columns=df.columns)
|
|
445
|
+
folds.index = [f"fold{i + 1}" for i in range(len(vals))]
|
|
446
|
+
comp = None
|
|
447
|
+
if comp_rows:
|
|
448
|
+
comp = pd.DataFrame([run(r) for r in comp_rows], columns=df.columns)
|
|
449
|
+
comp.index = [f"fold{i + 1}c" for i in range(len(comp_rows))]
|
|
450
|
+
full = evaluate(df, reference)
|
|
451
|
+
return CVResult(folds=folds, scheme=scheme, n_folds=len(folds_rows), fold_rows=folds_rows, complement=comp,
|
|
452
|
+
complement_rows=comp_rows or None, full=full, n=n,
|
|
453
|
+
meta={"n_left_out": left_out, "n_kept": n - left_out if scheme != "bootstrap" else n,
|
|
454
|
+
"measure": measure if not callable(measure) else getattr(measure, "__name__", "custom")})
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
# =========================================================================== bootstrap and helpers
|
|
458
|
+
def bootstrap_srd(X, reference="mean", n_boot: int = 1000, alpha: float = 0.05, ties: str = "average", random_state=None,
|
|
459
|
+
**srd_kwargs) -> pd.DataFrame:
|
|
460
|
+
"""Percentile bootstrap confidence intervals of the normalized SRD values (rows resampled)."""
|
|
461
|
+
df = as_frame(X)
|
|
462
|
+
n = df.shape[0]
|
|
463
|
+
rng = as_rng(random_state)
|
|
464
|
+
vals = []
|
|
465
|
+
for _ in range(n_boot):
|
|
466
|
+
rows = rng.integers(0, n, size=n)
|
|
467
|
+
sub = df.iloc[rows]
|
|
468
|
+
vals.append(srd(sub, reference=_fold_reference(reference, sub, rows), ties=ties, **srd_kwargs).normalized)
|
|
469
|
+
B = pd.DataFrame(vals, columns=df.columns)
|
|
470
|
+
full = srd(df, reference=reference, ties=ties, **srd_kwargs).normalized
|
|
471
|
+
out = pd.DataFrame({"SRD_norm": full, "lower": B.quantile(alpha / 2), "upper": B.quantile(1 - alpha / 2),
|
|
472
|
+
"std": B.std(ddof=1)})
|
|
473
|
+
out.index.name = "solution"
|
|
474
|
+
return out.sort_values("SRD_norm", kind="stable")
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
def classify(srd_norm, n: int, alpha: float = 0.05) -> list[str]:
|
|
478
|
+
"""Verdicts (similar/random/reversed) of normalized SRD values for ``n`` objects without ties."""
|
|
479
|
+
d = null_distribution(n=n)
|
|
480
|
+
out = []
|
|
481
|
+
for s in np.atleast_1d(srd_norm):
|
|
482
|
+
val = s * srd_max(n)
|
|
483
|
+
out.append(_verdict(d.cdf(val), d.sf(val), alpha))
|
|
484
|
+
return out
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
def percentile_table(n_values=range(3, 41)) -> pd.DataFrame:
|
|
488
|
+
"""Exact XX1, Q1, Med, Q3 and XX19 points (normalized) of SRD without ties for a range of ``n``.
|
|
489
|
+
|
|
490
|
+
This replaces the printed tables of the random-number distributions.
|
|
491
|
+
"""
|
|
492
|
+
rows = []
|
|
493
|
+
for n in n_values:
|
|
494
|
+
d = null_distribution(n=int(n))
|
|
495
|
+
p = d.percentiles(normalized=True)
|
|
496
|
+
rows.append({"n": int(n), **p, "mean": d.mean / d.scale, "std": d.std / d.scale})
|
|
497
|
+
return pd.DataFrame(rows).set_index("n")
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
__all__ = ["CRRNResult", "crrn", "CVResult", "cross_validate", "bootstrap_srd", "compact_letters", "classify",
|
|
501
|
+
"percentile_table", "PERCENTILES", "VERDICTS"]
|
srdkit/value.py
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
r"""Value-based SRD: sums of Euclidean and Manhattan distance differences (DnE, DnM).
|
|
2
|
+
|
|
3
|
+
The rank transformation makes SRD robust and scale-free but discards the size
|
|
4
|
+
of the differences. Héberger (2026) extended SRD to the *non-ranking*
|
|
5
|
+
environment. With :math:`T_{\min}` and :math:`T_{\max}` the smallest and
|
|
6
|
+
largest elements of the input matrix extended by the reference column
|
|
7
|
+
:math:`\mathbf{y}`, and :math:`v_i=\max(y_i-T_{\min},\,T_{\max}-y_i)` the largest
|
|
8
|
+
possible deviation in row :math:`i`, the measures of column :math:`k` are
|
|
9
|
+
|
|
10
|
+
.. math::
|
|
11
|
+
|
|
12
|
+
D_nE_k = \frac{\sqrt{\sum_i (x_{ki}-y_i)^2}}{\sqrt{\sum_i v_i^2}},\qquad
|
|
13
|
+
D_nM_k = \frac{\sum_i |x_{ki}-y_i|}{\sum_i v_i},
|
|
14
|
+
|
|
15
|
+
both between 0 and 1. Their randomization test fills the interval
|
|
16
|
+
:math:`[T_{\min},T_{\max}]` with uniformly distributed random numbers (the
|
|
17
|
+
distributions are slightly biased: DnE upwards, DnM downwards). The input must be
|
|
18
|
+
on a common scale (the columns are compared directly), which is why the
|
|
19
|
+
measures suit small data tables of scores, accuracies or rank-like values.
|
|
20
|
+
|
|
21
|
+
As additions this module offers a permutation null distribution (the column's
|
|
22
|
+
values are reassigned to the rows at random, which keeps their empirical
|
|
23
|
+
distribution) and the general :math:`L_p` version.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
import itertools
|
|
29
|
+
import math
|
|
30
|
+
|
|
31
|
+
import numpy as np
|
|
32
|
+
import pandas as pd
|
|
33
|
+
|
|
34
|
+
from ._utils import as_frame, as_rng
|
|
35
|
+
from .core import SRDResult
|
|
36
|
+
from .distribution import SRDDistribution
|
|
37
|
+
from .reference import make_reference, reference_name
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _vmax(Z: np.ndarray, y: np.ndarray) -> np.ndarray:
|
|
41
|
+
tmin, tmax = Z.min(), Z.max()
|
|
42
|
+
return np.maximum(y - tmin, tmax - y)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def value_srd(X, reference="mean", p: float = 1.0, scaling: str | None = None, **reference_kwargs) -> SRDResult:
|
|
46
|
+
r"""Value-based SRD (DnM for ``p=1``, DnE for ``p=2``, Chebyshev for ``p=inf``).
|
|
47
|
+
|
|
48
|
+
Parameters
|
|
49
|
+
----------
|
|
50
|
+
X : array-like or DataFrame
|
|
51
|
+
Input matrix on a common scale.
|
|
52
|
+
reference : str, callable or array-like
|
|
53
|
+
Reference specification (see :func:`srdkit.make_reference`).
|
|
54
|
+
p : float
|
|
55
|
+
Order of the distance.
|
|
56
|
+
scaling : {None, "range", "standard", "row-range", "row-standard"}
|
|
57
|
+
Optional scaling applied *before* the reference is built: of the columns
|
|
58
|
+
(``"range"``, ``"standard"``) or of the rows (``"row-range"``,
|
|
59
|
+
``"row-standard"``), the latter puts criteria of different units on a
|
|
60
|
+
common scale. The original measures use the raw values.
|
|
61
|
+
"""
|
|
62
|
+
df = as_frame(X)
|
|
63
|
+
if scaling == "range":
|
|
64
|
+
df = (df - df.min()) / (df.max() - df.min()).replace(0, 1)
|
|
65
|
+
elif scaling == "standard":
|
|
66
|
+
df = (df - df.mean()) / df.std(ddof=1).replace(0, 1)
|
|
67
|
+
elif scaling is not None and scaling not in ("row-range", "row-standard"):
|
|
68
|
+
raise ValueError("scaling must be None, 'range', 'standard', 'row-range' or 'row-standard'")
|
|
69
|
+
a = df.to_numpy(dtype=float)
|
|
70
|
+
y = make_reference(df, reference, **reference_kwargs)
|
|
71
|
+
if y.ndim != 1:
|
|
72
|
+
raise ValueError("value_srd needs a single reference vector")
|
|
73
|
+
if scaling in ("row-range", "row-standard"):
|
|
74
|
+
# rows of the extended matrix are scaled together (affine and increasing,
|
|
75
|
+
# so aggregated references commute with the scaling)
|
|
76
|
+
ext = np.column_stack([a, y])
|
|
77
|
+
if scaling == "row-range":
|
|
78
|
+
lo, sc = ext.min(axis=1), ext.max(axis=1) - ext.min(axis=1)
|
|
79
|
+
else:
|
|
80
|
+
lo, sc = ext.mean(axis=1), ext.std(axis=1, ddof=1)
|
|
81
|
+
sc[sc == 0] = 1.0
|
|
82
|
+
ext = (ext - lo[:, None]) / sc[:, None]
|
|
83
|
+
a, y = ext[:, :-1], ext[:, -1]
|
|
84
|
+
df = pd.DataFrame(a, index=df.index, columns=df.columns)
|
|
85
|
+
Z = np.column_stack([a, y])
|
|
86
|
+
v = _vmax(Z, y)
|
|
87
|
+
dev = np.abs(a - y[:, None])
|
|
88
|
+
if np.isinf(p):
|
|
89
|
+
num, den = dev.max(axis=0), v.max()
|
|
90
|
+
else:
|
|
91
|
+
num = (dev ** p).sum(axis=0) ** (1 / p)
|
|
92
|
+
den = (v ** p).sum() ** (1 / p)
|
|
93
|
+
name = {1.0: "DnM", 2.0: "DnE"}.get(float(p), f"Dn{p:g}")
|
|
94
|
+
diff = pd.DataFrame(a - y[:, None], index=df.index, columns=df.columns)
|
|
95
|
+
return SRDResult(srd=pd.Series(num, index=df.columns, name=name), srd_max=float(den), n=a.shape[0], ranks=df.copy(),
|
|
96
|
+
reference=y, reference_ranks=y, differences=diff, data=df, reference_method=reference_name(reference),
|
|
97
|
+
ties="none", distance=name,
|
|
98
|
+
meta={"p": p, "Tmin": float(Z.min()), "Tmax": float(Z.max()), "v": v, "value_based": True,
|
|
99
|
+
"reference_spec": reference if isinstance(reference, str) or callable(reference) else y})
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def dne(X, reference="mean", **kw) -> SRDResult:
|
|
103
|
+
"""Sum of Euclidean distance differences, DnE (Héberger, 2026)."""
|
|
104
|
+
return value_srd(X, reference=reference, p=2.0, **kw)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def dnm(X, reference="mean", **kw) -> SRDResult:
|
|
108
|
+
"""Sum of absolute Manhattan distance differences, DnM (Héberger, 2026)."""
|
|
109
|
+
return value_srd(X, reference=reference, p=1.0, **kw)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def value_null(result: SRDResult, method: str = "uniform", n_sim: int = 100_000, column: str | None = None,
|
|
113
|
+
random_state=None, chunk: int = 50_000) -> SRDDistribution:
|
|
114
|
+
"""Null distribution of a value-based SRD (normalized units, scale 1).
|
|
115
|
+
|
|
116
|
+
``method="uniform"``: every element of a random column is uniform on
|
|
117
|
+
:math:`[T_{\\min},T_{\\max}]` (Héberger, 2026). ``method="permutation"``: the values
|
|
118
|
+
of ``column`` are randomly reassigned to the rows (exact enumeration for
|
|
119
|
+
``n <= 8``, Monte Carlo above).
|
|
120
|
+
"""
|
|
121
|
+
if not result.meta.get("value_based"):
|
|
122
|
+
raise ValueError("value_null needs a result of value_srd/dne/dnm")
|
|
123
|
+
y = result.reference
|
|
124
|
+
p = result.meta["p"]
|
|
125
|
+
den = result.srd_max
|
|
126
|
+
n = y.size
|
|
127
|
+
rng = as_rng(random_state)
|
|
128
|
+
|
|
129
|
+
def dist(M): # rows of M are random columns
|
|
130
|
+
dev = np.abs(M - y[None, :])
|
|
131
|
+
if np.isinf(p):
|
|
132
|
+
return dev.max(axis=1) / den
|
|
133
|
+
return (dev ** p).sum(axis=1) ** (1 / p) / den
|
|
134
|
+
|
|
135
|
+
if method == "uniform":
|
|
136
|
+
lo, hi = result.meta["Tmin"], result.meta["Tmax"]
|
|
137
|
+
vals, done = [], 0
|
|
138
|
+
while done < n_sim:
|
|
139
|
+
k = min(chunk, n_sim - done)
|
|
140
|
+
vals.append(dist(rng.uniform(lo, hi, size=(k, n))))
|
|
141
|
+
done += k
|
|
142
|
+
d = np.concatenate(vals)
|
|
143
|
+
kind = "monte-carlo"
|
|
144
|
+
elif method == "permutation":
|
|
145
|
+
if column is None:
|
|
146
|
+
raise ValueError("method='permutation' needs the column whose values are permuted")
|
|
147
|
+
x = result.data[column].to_numpy(dtype=float)
|
|
148
|
+
if n <= 8:
|
|
149
|
+
d = dist(np.array([x[list(pp)] for pp in itertools.permutations(range(n))]))
|
|
150
|
+
kind = "enumeration"
|
|
151
|
+
else:
|
|
152
|
+
d = dist(x[np.argsort(rng.random((n_sim, n)), axis=1)])
|
|
153
|
+
kind = "monte-carlo"
|
|
154
|
+
else:
|
|
155
|
+
raise ValueError("method must be 'uniform' or 'permutation'")
|
|
156
|
+
# bin to a fine grid so that the discrete machinery (cdf, percentiles) applies
|
|
157
|
+
v, cnt = np.unique(np.round(d, 6), return_counts=True)
|
|
158
|
+
return SRDDistribution(values=v, probs=cnt / cnt.sum(), n=n, scale=1.0, kind=kind,
|
|
159
|
+
info={"method": method, "n_sim": n_sim if kind != "enumeration" else math.factorial(n)})
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def value_crrn(result: SRDResult, method: str = "uniform", alpha: float = 0.05, n_sim: int = 100_000, random_state=None):
|
|
163
|
+
"""Randomization test of DnE/DnM values; returns a :class:`srdkit.validation.CRRNResult`."""
|
|
164
|
+
from .validation import CRRNResult, _verdict
|
|
165
|
+
|
|
166
|
+
rows, dists = [], {}
|
|
167
|
+
shared = value_null(result, "uniform", n_sim=n_sim, random_state=random_state) if method == "uniform" else None
|
|
168
|
+
for c in result.columns:
|
|
169
|
+
d = shared if shared is not None else value_null(result, "permutation", n_sim=n_sim, column=c, random_state=random_state)
|
|
170
|
+
dists[c] = d
|
|
171
|
+
s = float(result.normalized[c])
|
|
172
|
+
pl, pu = d.cdf(s), d.sf(s)
|
|
173
|
+
rows.append({"solution": c, "SRD": float(result.srd[c]), "SRD%": 100 * s, "p_lower": pl, "p_upper": pu,
|
|
174
|
+
"verdict": _verdict(pl, pu, alpha)})
|
|
175
|
+
table = pd.DataFrame(rows).set_index("solution").sort_values("SRD", kind="stable")
|
|
176
|
+
disp = shared if shared is not None else next(iter(dists.values()))
|
|
177
|
+
return CRRNResult(table=table, distribution=disp, distributions=dists, alpha=alpha, result=result)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def pairwise_value_srd(X, p: float = 1.0) -> pd.DataFrame:
|
|
181
|
+
"""Value-based dissimilarity of every pair of columns (each column as reference in turn)."""
|
|
182
|
+
df = as_frame(X)
|
|
183
|
+
cols = list(df.columns)
|
|
184
|
+
M = np.zeros((len(cols), len(cols)))
|
|
185
|
+
for a, ca in enumerate(cols):
|
|
186
|
+
res = value_srd(df.drop(columns=[ca]) if len(cols) > 1 else df, reference=df[ca].to_numpy(), p=p)
|
|
187
|
+
for cb, val in res.normalized.items():
|
|
188
|
+
M[a, cols.index(cb)] = val
|
|
189
|
+
return pd.DataFrame(M, index=cols, columns=cols)
|