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/__init__.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""srdkit — the sum of ranking differences (SRD) in Python.
|
|
2
|
+
|
|
3
|
+
The package implements the complete SRD family and its validation:
|
|
4
|
+
|
|
5
|
+
* the classical SRD of Héberger (2010) with ties (Kollár-Hunek and Héberger, 2013),
|
|
6
|
+
every reference rule and normalization (:func:`srd`, :class:`SRD`, :func:`pairwise_srd`);
|
|
7
|
+
* exact null distributions for any tie pattern, exact moments, Monte Carlo and
|
|
8
|
+
normal approximations (:mod:`srdkit.distribution`), the CRRN randomization test
|
|
9
|
+
and cross-validation with Wilcoxon, Dietterich, Alpaydin and further tests
|
|
10
|
+
(:mod:`srdkit.validation`), SRD-ANOVA (:mod:`srdkit.anova`);
|
|
11
|
+
* SRD variants: rank distances (:mod:`srdkit.distances`), weighted and top-k SRD
|
|
12
|
+
(:mod:`srdkit.weighted`), value-based DnE and DnM (:mod:`srdkit.value`), the
|
|
13
|
+
utility-based uSRD (:mod:`srdkit.utility`), Promethee P-SRD and GAIA
|
|
14
|
+
(:mod:`srdkit.promethee`), NMF-SRD multi-objective ranking (:mod:`srdkit.nmf`),
|
|
15
|
+
SRD-ordered parallel coordinates (:mod:`srdkit.parcoord`), GPCM (:mod:`srdkit.gpcm`);
|
|
16
|
+
* SRD as a fusion tool (:mod:`srdkit.fusion`), MCDM methods (:mod:`srdkit.mcda`),
|
|
17
|
+
Pareto analysis (:mod:`srdkit.pareto`);
|
|
18
|
+
* new tools: segmentation (:mod:`srdkit.segmentation`), representations
|
|
19
|
+
(:mod:`srdkit.representation`), clustering (:mod:`srdkit.clustering`),
|
|
20
|
+
diagnostics, power analysis and simplification (:mod:`srdkit.diagnostics`),
|
|
21
|
+
one-call reports (:func:`analyze`) and visualizations (:mod:`srdkit.viz`);
|
|
22
|
+
* the consensus framework for a fair comparison of alternatives with seven
|
|
23
|
+
complementary, statistically tested methods (:mod:`srdkit.framework`),
|
|
24
|
+
tournament tables and power–weakness ratios (:mod:`srdkit.tournament`) and
|
|
25
|
+
weights taken from the data (:mod:`srdkit.weights`).
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from . import (
|
|
29
|
+
anova,
|
|
30
|
+
clustering,
|
|
31
|
+
datasets,
|
|
32
|
+
diagnostics,
|
|
33
|
+
distances,
|
|
34
|
+
distribution,
|
|
35
|
+
framework,
|
|
36
|
+
fusion,
|
|
37
|
+
gpcm,
|
|
38
|
+
mcda,
|
|
39
|
+
nmf,
|
|
40
|
+
parcoord,
|
|
41
|
+
pareto,
|
|
42
|
+
promethee,
|
|
43
|
+
ranking,
|
|
44
|
+
reference,
|
|
45
|
+
representation,
|
|
46
|
+
segmentation,
|
|
47
|
+
simulate,
|
|
48
|
+
tournament,
|
|
49
|
+
utility,
|
|
50
|
+
validation,
|
|
51
|
+
value,
|
|
52
|
+
viz,
|
|
53
|
+
weighted,
|
|
54
|
+
weights,
|
|
55
|
+
)
|
|
56
|
+
from ._utils import srd_max
|
|
57
|
+
from ._version import __version__
|
|
58
|
+
from .anova import anova as srd_anova
|
|
59
|
+
from .clustering import representative_solutions, similarity_groups, srd_clusters, srd_linkage
|
|
60
|
+
from .core import SRD, SRDResult, pairwise_srd, srd
|
|
61
|
+
from .diagnostics import noise_robustness, object_influence, power_analysis, reduce_criteria, reference_sensitivity
|
|
62
|
+
from .distribution import SRDDistribution, footrule_null_exact, footrule_null_moments, null_distribution
|
|
63
|
+
from .framework import FairComparison, covat, fair_comparison, method_ranks
|
|
64
|
+
from .fusion import consensus_outliers, merit_fusion, srd_roc
|
|
65
|
+
from .gpcm import gpcm as gpcm_ranking
|
|
66
|
+
from .mcda import mcda_ranks, mcda_scores
|
|
67
|
+
from .nmf import nmf_srd_ranking
|
|
68
|
+
from .parcoord import compare_orderings, order_axes
|
|
69
|
+
from .pareto import nondominated_layers, post_pareto_srd
|
|
70
|
+
from .promethee import gaia, p_srd
|
|
71
|
+
from .promethee import promethee as promethee_flows
|
|
72
|
+
from .ranking import rank_matrix, soft_rank_matrix
|
|
73
|
+
from .reference import footrule_consensus, kemeny_consensus, make_reference
|
|
74
|
+
from .report import SRDReport, analyze, summarize
|
|
75
|
+
from .representation import constellation, rank_profile, soft_srd, srd_map
|
|
76
|
+
from .segmentation import change_score, displacement_segmentation, local_srd_profile, segment_rankings
|
|
77
|
+
from .tournament import pwr, pwr_sequence, spwr, tournament_table
|
|
78
|
+
from .utility import usrd
|
|
79
|
+
from .validation import CRRNResult, CVResult, bootstrap_srd, cross_validate, crrn, percentile_table
|
|
80
|
+
from .value import dne, dnm, value_crrn, value_srd
|
|
81
|
+
from .weighted import topk_srd, weighted_srd
|
|
82
|
+
from .weights import criterion_weights, self_weighted_srd, srd_weights, weighted_reference_srd
|
|
83
|
+
|
|
84
|
+
__all__ = [
|
|
85
|
+
"__version__", "srd", "SRD", "SRDResult", "pairwise_srd", "srd_max", "make_reference", "rank_matrix",
|
|
86
|
+
"soft_rank_matrix", "footrule_consensus", "kemeny_consensus",
|
|
87
|
+
"null_distribution", "footrule_null_exact", "footrule_null_moments", "SRDDistribution",
|
|
88
|
+
"crrn", "CRRNResult", "cross_validate", "CVResult", "bootstrap_srd", "percentile_table", "srd_anova",
|
|
89
|
+
"weighted_srd", "topk_srd", "dne", "dnm", "value_srd", "value_crrn", "usrd", "promethee_flows", "p_srd", "gaia",
|
|
90
|
+
"nmf_srd_ranking", "order_axes", "compare_orderings", "gpcm_ranking", "merit_fusion", "consensus_outliers", "srd_roc",
|
|
91
|
+
"mcda_scores", "mcda_ranks", "nondominated_layers", "post_pareto_srd",
|
|
92
|
+
"segment_rankings", "change_score", "local_srd_profile", "displacement_segmentation",
|
|
93
|
+
"srd_map", "constellation", "rank_profile", "soft_srd", "srd_linkage", "srd_clusters", "representative_solutions",
|
|
94
|
+
"similarity_groups", "object_influence", "reference_sensitivity", "noise_robustness", "power_analysis",
|
|
95
|
+
"reduce_criteria", "analyze", "summarize", "SRDReport",
|
|
96
|
+
"fair_comparison", "FairComparison", "covat", "method_ranks", "pwr", "spwr", "pwr_sequence", "tournament_table",
|
|
97
|
+
"srd_weights", "self_weighted_srd", "weighted_reference_srd", "criterion_weights",
|
|
98
|
+
"anova", "clustering", "datasets", "diagnostics", "distances", "distribution", "framework", "fusion", "gpcm",
|
|
99
|
+
"mcda", "nmf", "parcoord", "pareto", "promethee", "ranking", "reference", "representation", "segmentation",
|
|
100
|
+
"simulate", "tournament", "utility", "validation", "value", "viz", "weighted", "weights",
|
|
101
|
+
]
|
srdkit/_utils.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Small internal helpers shared by the modules (input checking, random states)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Sequence
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
import pandas as pd
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def as_frame(X, columns: Sequence | None = None, index: Sequence | None = None, name: str = "X") -> pd.DataFrame:
|
|
12
|
+
"""Return ``X`` as a float :class:`pandas.DataFrame` (rows = objects, columns = solutions).
|
|
13
|
+
|
|
14
|
+
NumPy arrays get the column names ``c1, c2, ...`` and the row names ``0, 1, ...``
|
|
15
|
+
unless ``columns``/``index`` are given. A 1-D input becomes a single column.
|
|
16
|
+
"""
|
|
17
|
+
if isinstance(X, pd.DataFrame):
|
|
18
|
+
df = X.copy()
|
|
19
|
+
if columns is not None:
|
|
20
|
+
df.columns = list(columns)
|
|
21
|
+
if index is not None:
|
|
22
|
+
df.index = list(index)
|
|
23
|
+
elif isinstance(X, pd.Series):
|
|
24
|
+
df = X.to_frame(name=X.name if X.name is not None else "c1")
|
|
25
|
+
else:
|
|
26
|
+
a = np.asarray(X, dtype=float)
|
|
27
|
+
if a.ndim == 1:
|
|
28
|
+
a = a[:, None]
|
|
29
|
+
if a.ndim != 2:
|
|
30
|
+
raise ValueError(f"{name} must be a 2-D array or DataFrame, got shape {a.shape}")
|
|
31
|
+
cols = list(columns) if columns is not None else [f"c{j + 1}" for j in range(a.shape[1])]
|
|
32
|
+
df = pd.DataFrame(a, columns=cols, index=index)
|
|
33
|
+
try:
|
|
34
|
+
df = df.astype(float)
|
|
35
|
+
except (TypeError, ValueError) as exc: # pragma: no cover - message only
|
|
36
|
+
raise ValueError(f"{name} must contain numbers only (non-numeric column found)") from exc
|
|
37
|
+
df.columns = [str(c) for c in df.columns]
|
|
38
|
+
return df
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def check_finite(df: pd.DataFrame, missing: str = "raise", name: str = "X") -> pd.DataFrame:
|
|
42
|
+
"""Handle missing values: ``"raise"`` (default) or ``"drop"`` (drop rows with a missing value)."""
|
|
43
|
+
bad = ~np.isfinite(df.to_numpy(dtype=float))
|
|
44
|
+
if bad.any():
|
|
45
|
+
if missing == "drop":
|
|
46
|
+
return df.loc[~bad.any(axis=1)]
|
|
47
|
+
raise ValueError(f"{name} contains missing or infinite values; use missing='drop' to drop those rows")
|
|
48
|
+
return df
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def as_rng(random_state=None) -> np.random.Generator:
|
|
52
|
+
"""A :class:`numpy.random.Generator` from ``None``, an int or a generator."""
|
|
53
|
+
if isinstance(random_state, np.random.Generator):
|
|
54
|
+
return random_state
|
|
55
|
+
return np.random.default_rng(random_state)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def srd_max(n: int) -> int:
|
|
59
|
+
r"""Theoretical maximum of SRD for ``n`` objects without ties, :math:`\lfloor n^2/2 \rfloor`.
|
|
60
|
+
|
|
61
|
+
It is attained by the reversed ranking (Héberger and Kollár-Hunek, 2011).
|
|
62
|
+
|
|
63
|
+
>>> [srd_max(n) for n in range(1, 8)]
|
|
64
|
+
[0, 2, 4, 8, 12, 18, 24]
|
|
65
|
+
"""
|
|
66
|
+
n = int(n)
|
|
67
|
+
return (n * n) // 2
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def falling_factorial(v: int, a: int) -> int:
|
|
71
|
+
"""``v (v-1) ... (v-a+1)`` (number of ordered choices of ``a`` out of ``v``)."""
|
|
72
|
+
out = 1
|
|
73
|
+
for k in range(a):
|
|
74
|
+
out *= v - k
|
|
75
|
+
return out
|
srdkit/_version.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "1.0"
|
srdkit/anova.py
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
r"""SRD combined with analysis of variance (SRD-ANOVA).
|
|
2
|
+
|
|
3
|
+
Cross-validation turns every SRD value into a sample; analysis of variance then
|
|
4
|
+
decomposes the variation of the SRD values into the effects of the factors of a
|
|
5
|
+
study design: the solutions themselves, the cross-validation variant and the
|
|
6
|
+
number of folds (Héberger and Kollár-Hunek, 2019), or the levels of a multi-level
|
|
7
|
+
comparison such as modelling method × performance metric × data split (Rácz,
|
|
8
|
+
Bajusz and Héberger, 2015, 2019) or evaluation method × tissue × preprocessing.
|
|
9
|
+
|
|
10
|
+
:func:`anova` fits a factorial linear model with sum-to-zero (effect) coding and
|
|
11
|
+
returns the type II table (sums of squares of each term adjusted for all terms
|
|
12
|
+
not containing it; for balanced designs identical to the classical table).
|
|
13
|
+
:func:`posthoc` provides Tukey's HSD, Bonferroni- or Scheffé-adjusted pairwise
|
|
14
|
+
comparisons of one factor, :func:`levene` the homogeneity test, and
|
|
15
|
+
:func:`srd_long` / :func:`multilevel_cv` build the long table from
|
|
16
|
+
cross-validation results.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import itertools
|
|
22
|
+
|
|
23
|
+
import numpy as np
|
|
24
|
+
import pandas as pd
|
|
25
|
+
from scipy import stats
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _effect_coding(col: pd.Series) -> np.ndarray:
|
|
29
|
+
levels = list(pd.unique(col))
|
|
30
|
+
k = len(levels)
|
|
31
|
+
M = np.zeros((len(col), k - 1))
|
|
32
|
+
idx = col.map({lv: i for i, lv in enumerate(levels)}).to_numpy()
|
|
33
|
+
for j in range(k - 1):
|
|
34
|
+
M[idx == j, j] = 1.0
|
|
35
|
+
M[idx == k - 1, :] = -1.0
|
|
36
|
+
return M
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _design(df: pd.DataFrame, terms: list[tuple]) -> dict:
|
|
40
|
+
blocks = {}
|
|
41
|
+
base = {f: _effect_coding(df[f].astype(str)) for f in {f for t in terms for f in t}}
|
|
42
|
+
for t in terms:
|
|
43
|
+
mats = [base[f] for f in t]
|
|
44
|
+
M = mats[0]
|
|
45
|
+
for B in mats[1:]:
|
|
46
|
+
M = np.einsum("ni,nj->nij", M, B).reshape(len(df), -1)
|
|
47
|
+
blocks[t] = M
|
|
48
|
+
return blocks
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _rss(y, blocks: list) -> tuple[float, int]:
|
|
52
|
+
X = np.column_stack([np.ones(len(y))] + blocks) if blocks else np.ones((len(y), 1))
|
|
53
|
+
beta, *_ = np.linalg.lstsq(X, y, rcond=None)
|
|
54
|
+
r = y - X @ beta
|
|
55
|
+
return float(r @ r), int(np.linalg.matrix_rank(X))
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def anova(data: pd.DataFrame, response: str = "srd", factors=None, interactions: int | None = None) -> pd.DataFrame:
|
|
59
|
+
"""Factorial ANOVA (type II sums of squares).
|
|
60
|
+
|
|
61
|
+
Parameters
|
|
62
|
+
----------
|
|
63
|
+
data : DataFrame
|
|
64
|
+
Long table, one row per observation.
|
|
65
|
+
response : str
|
|
66
|
+
Response column (normalized SRD values).
|
|
67
|
+
factors : list of str
|
|
68
|
+
Factor columns; all object/categorical columns except the response by default.
|
|
69
|
+
interactions : int, optional
|
|
70
|
+
Highest order of interactions (all by default).
|
|
71
|
+
|
|
72
|
+
Returns
|
|
73
|
+
-------
|
|
74
|
+
DataFrame with ``df``, ``SS``, ``MS``, ``F``, ``p`` and ``eta2_partial`` per term.
|
|
75
|
+
"""
|
|
76
|
+
df = data.copy()
|
|
77
|
+
if factors is None:
|
|
78
|
+
factors = [c for c in df.columns if c != response and not np.issubdtype(df[c].dtype, np.number)]
|
|
79
|
+
factors = list(factors)
|
|
80
|
+
order = len(factors) if interactions is None else int(interactions)
|
|
81
|
+
terms = [t for k in range(1, order + 1) for t in itertools.combinations(factors, k)]
|
|
82
|
+
y = df[response].to_numpy(float)
|
|
83
|
+
blocks = _design(df, terms)
|
|
84
|
+
rss_full, rank_full = _rss(y, list(blocks.values()))
|
|
85
|
+
df_res = len(y) - rank_full
|
|
86
|
+
rows = []
|
|
87
|
+
for t in terms:
|
|
88
|
+
others = [blocks[s] for s in terms if not set(t) <= set(s)]
|
|
89
|
+
with_t = others + [blocks[t]]
|
|
90
|
+
rss_without, r0 = _rss(y, others)
|
|
91
|
+
rss_with, r1 = _rss(y, with_t)
|
|
92
|
+
ss = rss_without - rss_with
|
|
93
|
+
dft = r1 - r0
|
|
94
|
+
ms = ss / dft if dft > 0 else np.nan
|
|
95
|
+
mse = rss_full / df_res if df_res > 0 else np.nan
|
|
96
|
+
F = ms / mse if mse and mse > 0 else np.nan
|
|
97
|
+
p = stats.f.sf(F, dft, df_res) if np.isfinite(F) else np.nan
|
|
98
|
+
rows.append({"term": ":".join(t), "df": dft, "SS": ss, "MS": ms, "F": F, "p": p,
|
|
99
|
+
"eta2_partial": ss / (ss + rss_full) if ss + rss_full > 0 else np.nan})
|
|
100
|
+
rows.append({"term": "Residual", "df": df_res, "SS": rss_full, "MS": rss_full / df_res if df_res > 0 else np.nan,
|
|
101
|
+
"F": np.nan, "p": np.nan, "eta2_partial": np.nan})
|
|
102
|
+
return pd.DataFrame(rows).set_index("term")
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def posthoc(data: pd.DataFrame, factor: str, response: str = "srd", method: str = "tukey") -> pd.DataFrame:
|
|
106
|
+
"""Pairwise comparisons of the levels of one factor: ``"tukey"`` (HSD), ``"bonferroni"`` or ``"scheffe"``."""
|
|
107
|
+
groups = {lv: g[response].to_numpy(float) for lv, g in data.groupby(factor, sort=False)}
|
|
108
|
+
names = list(groups)
|
|
109
|
+
rows = []
|
|
110
|
+
if method == "tukey":
|
|
111
|
+
res = stats.tukey_hsd(*groups.values())
|
|
112
|
+
for i, j in itertools.combinations(range(len(names)), 2):
|
|
113
|
+
rows.append({"A": names[i], "B": names[j], "diff": groups[names[i]].mean() - groups[names[j]].mean(),
|
|
114
|
+
"p": float(res.pvalue[i, j])})
|
|
115
|
+
else:
|
|
116
|
+
k = len(names)
|
|
117
|
+
N = sum(len(g) for g in groups.values())
|
|
118
|
+
mse = sum(((g - g.mean()) ** 2).sum() for g in groups.values()) / (N - k)
|
|
119
|
+
m = k * (k - 1) / 2
|
|
120
|
+
for i, j in itertools.combinations(range(k), 2):
|
|
121
|
+
a, b = groups[names[i]], groups[names[j]]
|
|
122
|
+
diff = a.mean() - b.mean()
|
|
123
|
+
se = np.sqrt(mse * (1 / len(a) + 1 / len(b)))
|
|
124
|
+
if method == "bonferroni":
|
|
125
|
+
t = diff / se
|
|
126
|
+
p = min(1.0, 2 * stats.t.sf(abs(t), N - k) * m)
|
|
127
|
+
elif method == "scheffe":
|
|
128
|
+
F = diff ** 2 / (se ** 2 * (k - 1))
|
|
129
|
+
p = float(stats.f.sf(F, k - 1, N - k))
|
|
130
|
+
else:
|
|
131
|
+
raise ValueError("method must be 'tukey', 'bonferroni' or 'scheffe'")
|
|
132
|
+
rows.append({"A": names[i], "B": names[j], "diff": diff, "p": float(p)})
|
|
133
|
+
out = pd.DataFrame(rows)
|
|
134
|
+
out["significant"] = out["p"] < 0.05
|
|
135
|
+
return out
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def levene(data: pd.DataFrame, factor: str, response: str = "srd") -> tuple[float, float]:
|
|
139
|
+
"""Levene's test (median-centred, Brown-Forsythe) of equal variances across the levels of ``factor``."""
|
|
140
|
+
groups = [g[response].to_numpy(float) for _, g in data.groupby(factor, sort=False)]
|
|
141
|
+
r = stats.levene(*groups, center="median")
|
|
142
|
+
return float(r.statistic), float(r.pvalue)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def srd_long(cv_results: dict, factor_names=None) -> pd.DataFrame:
|
|
146
|
+
"""Long table from cross-validation results.
|
|
147
|
+
|
|
148
|
+
``cv_results`` maps a key (a string or a tuple of factor levels, e.g.
|
|
149
|
+
``("random", 7)``) to a :class:`srdkit.validation.CVResult`. The solution names
|
|
150
|
+
become the factor ``solution``; with tuple keys ``factor_names`` names their
|
|
151
|
+
elements.
|
|
152
|
+
"""
|
|
153
|
+
frames = []
|
|
154
|
+
for key, cv in cv_results.items():
|
|
155
|
+
f = cv.folds.reset_index(names="fold").melt(id_vars="fold", var_name="solution", value_name="srd")
|
|
156
|
+
keys = key if isinstance(key, tuple) else (key,)
|
|
157
|
+
names = factor_names or [f"F{i + 1}" for i in range(len(keys))]
|
|
158
|
+
for nm, kv in zip(names, keys):
|
|
159
|
+
f[nm] = str(kv)
|
|
160
|
+
frames.append(f)
|
|
161
|
+
return pd.concat(frames, ignore_index=True)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def multilevel_cv(X, reference="mean", schemes=("random", "contiguous"), folds=(5, 7, 10), random_state=0, **kwargs) -> pd.DataFrame:
|
|
165
|
+
"""The design of Héberger and Kollár-Hunek (2019): CV variant x number of folds x solution, as a long table."""
|
|
166
|
+
from .validation import cross_validate
|
|
167
|
+
|
|
168
|
+
res = {}
|
|
169
|
+
for s in schemes:
|
|
170
|
+
for k in folds:
|
|
171
|
+
res[(s, k)] = cross_validate(X, reference=reference, scheme=s, n_folds=k, random_state=random_state, **kwargs)
|
|
172
|
+
return srd_long(res, factor_names=["cv_variant", "n_folds"])
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def split_factors(data: pd.DataFrame, column: str = "solution", sep: str = "|", names=None) -> pd.DataFrame:
|
|
176
|
+
"""Split composite solution names (``"PLS|RMSE"``) into separate factor columns for a multi-level ANOVA."""
|
|
177
|
+
parts = data[column].astype(str).str.split(sep, expand=True)
|
|
178
|
+
names = names or [f"level{i + 1}" for i in range(parts.shape[1])]
|
|
179
|
+
out = data.copy()
|
|
180
|
+
for i, nm in enumerate(names):
|
|
181
|
+
out[nm] = parts[i]
|
|
182
|
+
return out
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
__all__ = ["anova", "posthoc", "levene", "srd_long", "multilevel_cv", "split_factors"]
|
srdkit/clustering.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
r"""Grouping of solutions with SRD-type dissimilarities.
|
|
2
|
+
|
|
3
|
+
SRD groups solutions: close SRD values on the SRD plot suggest similar rankings,
|
|
4
|
+
and Héberger (2026) proposed DnE and DnM as clustering tools as well. Because the
|
|
5
|
+
one-dimensional distance from the reference can put two very different solutions
|
|
6
|
+
side by side, grouping should use the *pairwise* dissimilarities. This module
|
|
7
|
+
offers hierarchical clustering with optimal leaf ordering, k-medoids, and
|
|
8
|
+
statistically founded groups: solutions whose pairwise SRD is not smaller than
|
|
9
|
+
the XX1 point of the null distribution are not considered similar.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import numpy as np
|
|
15
|
+
import pandas as pd
|
|
16
|
+
from scipy.cluster import hierarchy
|
|
17
|
+
from scipy.spatial.distance import squareform
|
|
18
|
+
|
|
19
|
+
from ._utils import as_frame, as_rng
|
|
20
|
+
from .core import pairwise_srd
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def dissimilarity(X, kind: str = "srd", ties: str = "average", reference=None) -> pd.DataFrame:
|
|
24
|
+
"""Pairwise dissimilarity of the columns: ``"srd"`` (normalized footrule), ``"kendall"``, ``"dne"``, ``"dnm"``."""
|
|
25
|
+
if kind in ("srd", "footrule"):
|
|
26
|
+
return pairwise_srd(X, ties=ties, reference=reference)
|
|
27
|
+
if kind in ("kendall", "spearman", "cayley", "ulam", "hamming"):
|
|
28
|
+
return pairwise_srd(X, ties=ties, reference=reference, distance=kind)
|
|
29
|
+
if kind in ("dne", "dnm"):
|
|
30
|
+
from .value import pairwise_value_srd
|
|
31
|
+
|
|
32
|
+
M = pairwise_value_srd(X, p=2.0 if kind == "dne" else 1.0)
|
|
33
|
+
return (M + M.T) / 2
|
|
34
|
+
raise ValueError("kind must be 'srd', 'kendall', 'spearman', 'cayley', 'ulam', 'hamming', 'dne' or 'dnm'")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def srd_linkage(X, method: str = "average", kind: str = "srd", ties: str = "average", optimal_ordering: bool = True):
|
|
38
|
+
"""Hierarchical clustering of the solutions; returns ``(linkage matrix, labels)``."""
|
|
39
|
+
D = dissimilarity(X, kind, ties)
|
|
40
|
+
Z = hierarchy.linkage(squareform(D.to_numpy(), checks=False), method=method, optimal_ordering=optimal_ordering)
|
|
41
|
+
return Z, list(D.index)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def srd_clusters(X, n_clusters: int = 3, method: str = "average", kind: str = "srd", ties: str = "average") -> pd.Series:
|
|
45
|
+
"""Flat clusters (labels 1..k) of the solutions from the hierarchical tree."""
|
|
46
|
+
Z, labels = srd_linkage(X, method, kind, ties)
|
|
47
|
+
return pd.Series(hierarchy.fcluster(Z, n_clusters, criterion="maxclust"), index=labels, name="cluster")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def kmedoids(D, k: int, max_iter: int = 100, random_state=0) -> tuple[np.ndarray, np.ndarray]:
|
|
51
|
+
"""Partitioning around medoids on a dissimilarity matrix; returns medoid indices and labels."""
|
|
52
|
+
D = np.asarray(D, float)
|
|
53
|
+
m = D.shape[0]
|
|
54
|
+
rng = as_rng(random_state)
|
|
55
|
+
# BUILD: greedy start
|
|
56
|
+
med = [int(np.argmin(D.sum(axis=1)))]
|
|
57
|
+
while len(med) < k:
|
|
58
|
+
gain = [np.minimum(D[:, med].min(axis=1), D[:, c]).sum() if c not in med else np.inf for c in range(m)]
|
|
59
|
+
med.append(int(np.argmin(gain)))
|
|
60
|
+
med = np.array(med)
|
|
61
|
+
for _ in range(max_iter):
|
|
62
|
+
labels = np.argmin(D[:, med], axis=1)
|
|
63
|
+
new = med.copy()
|
|
64
|
+
for c in range(k):
|
|
65
|
+
members = np.flatnonzero(labels == c)
|
|
66
|
+
if members.size:
|
|
67
|
+
new[c] = members[np.argmin(D[np.ix_(members, members)].sum(axis=1))]
|
|
68
|
+
if set(new) == set(med):
|
|
69
|
+
break
|
|
70
|
+
med = new
|
|
71
|
+
labels = np.argmin(D[:, med], axis=1)
|
|
72
|
+
_ = rng # deterministic BUILD start; the generator is kept for API symmetry
|
|
73
|
+
return med, labels
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def representative_solutions(X, k: int = 3, kind: str = "srd", ties: str = "average") -> pd.DataFrame:
|
|
77
|
+
"""The ``k`` most representative solutions (medoids) and the group of every solution."""
|
|
78
|
+
D = dissimilarity(X, kind, ties)
|
|
79
|
+
med, lab = kmedoids(D.to_numpy(), k)
|
|
80
|
+
names = list(D.index)
|
|
81
|
+
return pd.DataFrame({"group": lab + 1, "medoid": [names[med[g]] for g in lab]}, index=names)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def similarity_groups(X, alpha: float = 0.05, ties: str = "average") -> pd.DataFrame:
|
|
85
|
+
"""Pairs of solutions whose mutual SRD is significantly small (better than random at level ``alpha``).
|
|
86
|
+
|
|
87
|
+
Each column is taken in turn as the reference of the others; the exact null
|
|
88
|
+
distribution of the pair's tie patterns decides. Returns the boolean matrix of
|
|
89
|
+
significantly similar pairs.
|
|
90
|
+
"""
|
|
91
|
+
from .distribution import null_distribution
|
|
92
|
+
from .ranking import rank_matrix
|
|
93
|
+
|
|
94
|
+
df = as_frame(X)
|
|
95
|
+
R = rank_matrix(df, ties=ties)
|
|
96
|
+
cols = list(df.columns)
|
|
97
|
+
n = df.shape[0]
|
|
98
|
+
S = pd.DataFrame(False, index=cols, columns=cols)
|
|
99
|
+
cache = {}
|
|
100
|
+
from .ranking import tie_blocks
|
|
101
|
+
|
|
102
|
+
for i, a in enumerate(cols):
|
|
103
|
+
for b in cols[i + 1:]:
|
|
104
|
+
key = (tuple(tie_blocks(R[a])), tuple(tie_blocks(R[b])))
|
|
105
|
+
if key not in cache:
|
|
106
|
+
cache[key] = null_distribution(R[a].to_numpy(), R[b].to_numpy(), n)
|
|
107
|
+
d = float(np.abs(R[a] - R[b]).sum())
|
|
108
|
+
sig = cache[key].cdf(d) <= alpha
|
|
109
|
+
S.loc[a, b] = S.loc[b, a] = bool(sig)
|
|
110
|
+
return S
|