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/gpcm.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
r"""Pair-correlation method (PCM) and its generalization (GPCM).
|
|
2
|
+
|
|
3
|
+
PCM (Rajkó and Héberger, 2001) decides which of two predictors :math:`x_1`,
|
|
4
|
+
:math:`x_2` is more closely related to a response :math:`y` without assuming a
|
|
5
|
+
model. For every pair of objects with :math:`y_i\ne y_j` the change of each
|
|
6
|
+
predictor either agrees with the change of :math:`y` (+) or disagrees (−); the
|
|
7
|
+
four outcomes are counted in a :math:`2\times2` table,
|
|
8
|
+
|
|
9
|
+
===== ================== ==================
|
|
10
|
+
:math:`x_2` agrees :math:`x_2` disagrees
|
|
11
|
+
===== ================== ==================
|
|
12
|
+
x1 + A B
|
|
13
|
+
x1 − C D
|
|
14
|
+
===== ================== ==================
|
|
15
|
+
|
|
16
|
+
and :math:`x_1` is superior when :math:`B` exceeds :math:`C` significantly. The
|
|
17
|
+
generalization (GPCM; Héberger and Rajkó, 2002) compares all predictors pairwise;
|
|
18
|
+
each comparison yields a winner, a loser or no decision, and the predictors are
|
|
19
|
+
ranked by (i) the number of wins, (ii) wins minus losses or (iii) probability-
|
|
20
|
+
weighted wins minus losses. With the gold standard as :math:`y`, GPCM is an
|
|
21
|
+
MCDM tool parallel to SRD (Andrić et al., 2015; Héberger, 2026).
|
|
22
|
+
|
|
23
|
+
Decisions use the conditional exact test of :math:`B` against :math:`B+C` (the
|
|
24
|
+
exact McNemar test, default; ``"ce"``), Fisher's exact test of the whole table,
|
|
25
|
+
or Williams' :math:`t` test of two dependent correlations with :math:`y`
|
|
26
|
+
(Williams, 1959, in the form given by Steiger, 1980),
|
|
27
|
+
|
|
28
|
+
.. math::
|
|
29
|
+
|
|
30
|
+
t = (r_{1y}-r_{2y})\sqrt{\frac{(n-1)(1+r_{12})}
|
|
31
|
+
{2\frac{n-1}{n-3}\lvert\mathbf R\rvert+\bar r^{2}(1-r_{12})^{3}}},
|
|
32
|
+
\qquad \nu=n-3,
|
|
33
|
+
|
|
34
|
+
with :math:`\lvert\mathbf R\rvert=1-r_{1y}^2-r_{2y}^2-r_{12}^2+2r_{1y}r_{2y}r_{12}`
|
|
35
|
+
and :math:`\bar r=(r_{1y}+r_{2y})/2`. The probability-weighted rankings with the
|
|
36
|
+
two tests are the CEpW and WtpW orderings used by Héberger (2026) in the
|
|
37
|
+
consensus framework of :mod:`srdkit.framework`. Pairs tied in a predictor are
|
|
38
|
+
not counted in the contingency table.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
from __future__ import annotations
|
|
42
|
+
|
|
43
|
+
import itertools
|
|
44
|
+
|
|
45
|
+
import numpy as np
|
|
46
|
+
import pandas as pd
|
|
47
|
+
from scipy import stats
|
|
48
|
+
|
|
49
|
+
from ._utils import as_frame
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def pcm_table(x1, x2, y) -> dict:
|
|
53
|
+
"""The PCM contingency counts A, B, C, D of two predictors against ``y``."""
|
|
54
|
+
x1, x2, y = (np.asarray(v, float) for v in (x1, x2, y))
|
|
55
|
+
iu = np.triu_indices(y.size, 1)
|
|
56
|
+
dy = (y[:, None] - y[None, :])[iu]
|
|
57
|
+
s1 = np.sign((x1[:, None] - x1[None, :])[iu] * dy)
|
|
58
|
+
s2 = np.sign((x2[:, None] - x2[None, :])[iu] * dy)
|
|
59
|
+
ok = (dy != 0) & (s1 != 0) & (s2 != 0)
|
|
60
|
+
s1, s2 = s1[ok], s2[ok]
|
|
61
|
+
return {"A": int(np.sum((s1 > 0) & (s2 > 0))), "B": int(np.sum((s1 > 0) & (s2 < 0))),
|
|
62
|
+
"C": int(np.sum((s1 < 0) & (s2 > 0))), "D": int(np.sum((s1 < 0) & (s2 < 0)))}
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def williams_t(x1, x2, y) -> dict:
|
|
66
|
+
"""Williams' t test of :math:`r(x_1,y)=r(x_2,y)` for dependent correlations (Steiger, 1980, Eq. 7).
|
|
67
|
+
|
|
68
|
+
>>> r = williams_t([1, 2, 3, 4, 5, 6], [1, 3, 2, 4, 6, 5], [1, 2, 3, 4, 5, 6])
|
|
69
|
+
>>> round(r["r1y"], 3), round(r["r2y"], 3), r["df"]
|
|
70
|
+
(1.0, 0.886, 3)
|
|
71
|
+
"""
|
|
72
|
+
x1, x2, y = (np.asarray(v, float) for v in (x1, x2, y))
|
|
73
|
+
n = y.size
|
|
74
|
+
if n < 4:
|
|
75
|
+
raise ValueError("Williams' test needs at least four objects")
|
|
76
|
+
r1, r2, r12 = (float(np.corrcoef(a, b)[0, 1]) for a, b in ((x1, y), (x2, y), (x1, x2)))
|
|
77
|
+
detR = 1 - r1 ** 2 - r2 ** 2 - r12 ** 2 + 2 * r1 * r2 * r12
|
|
78
|
+
rbar = (r1 + r2) / 2
|
|
79
|
+
den = 2 * (n - 1) / (n - 3) * detR + rbar ** 2 * (1 - r12) ** 3
|
|
80
|
+
t = (r1 - r2) * np.sqrt((n - 1) * (1 + r12) / den) if den > 0 else (np.inf * np.sign(r1 - r2) if r1 != r2 else 0.0)
|
|
81
|
+
p = 2 * stats.t.sf(abs(t), n - 3) if np.isfinite(t) else 0.0
|
|
82
|
+
return {"r1y": r1, "r2y": r2, "r12": r12, "t": float(t), "df": n - 3, "p": float(p)}
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def pcm_test(x1, x2, y, test: str = "mcnemar") -> dict:
|
|
86
|
+
"""PCM decision between two predictors.
|
|
87
|
+
|
|
88
|
+
Returns the counts, the two-sided p-value and the winner (``"x1"``, ``"x2"`` or
|
|
89
|
+
``None``). ``test``: ``"mcnemar"``/``"ce"`` (conditional exact binomial test of
|
|
90
|
+
B vs C), ``"fisher"`` (Fisher's exact test of the table) or ``"williams"``
|
|
91
|
+
(Williams' t test of the two correlations with ``y``).
|
|
92
|
+
"""
|
|
93
|
+
t = pcm_table(x1, x2, y)
|
|
94
|
+
B, C = t["B"], t["C"]
|
|
95
|
+
if test in ("mcnemar", "ce", "conditional"):
|
|
96
|
+
p = stats.binomtest(B, B + C, 0.5).pvalue if B + C > 0 else 1.0
|
|
97
|
+
winner = "x1" if B > C else "x2" if C > B else None
|
|
98
|
+
elif test == "fisher":
|
|
99
|
+
p = stats.fisher_exact([[t["A"], t["B"]], [t["C"], t["D"]]])[1]
|
|
100
|
+
winner = "x1" if B > C else "x2" if C > B else None
|
|
101
|
+
elif test in ("williams", "wt"):
|
|
102
|
+
w = williams_t(x1, x2, y)
|
|
103
|
+
p = w["p"]
|
|
104
|
+
winner = "x1" if w["r1y"] > w["r2y"] else "x2" if w["r2y"] > w["r1y"] else None
|
|
105
|
+
t = {**t, "r1y": w["r1y"], "r2y": w["r2y"], "t": w["t"]}
|
|
106
|
+
else:
|
|
107
|
+
raise ValueError("test must be 'mcnemar' ('ce'), 'fisher' or 'williams'")
|
|
108
|
+
return {**t, "p": float(p), "winner": winner}
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def gpcm(X, y, test: str = "mcnemar", alpha: float = 0.05) -> dict:
|
|
112
|
+
"""Generalized pair-correlation method: pairwise decisions and three rankings.
|
|
113
|
+
|
|
114
|
+
Returns a dict with ``decisions`` (one row per pair), ``wins`` and ``losses``
|
|
115
|
+
matrices and the ``ranking`` table (wins, wins-losses, probability-weighted
|
|
116
|
+
wins-losses, rank by the latter, 1 = best).
|
|
117
|
+
"""
|
|
118
|
+
df = as_frame(X)
|
|
119
|
+
y = np.asarray(y, float)
|
|
120
|
+
cols = list(df.columns)
|
|
121
|
+
rows = []
|
|
122
|
+
W = pd.DataFrame(0, index=cols, columns=cols)
|
|
123
|
+
pw = {c: 0.0 for c in cols}
|
|
124
|
+
for a, b in itertools.combinations(cols, 2):
|
|
125
|
+
r = pcm_test(df[a], df[b], y, test=test)
|
|
126
|
+
win = None
|
|
127
|
+
if r["p"] < alpha and r["winner"] is not None:
|
|
128
|
+
win = a if r["winner"] == "x1" else b
|
|
129
|
+
lose = b if win == a else a
|
|
130
|
+
W.loc[win, lose] = 1
|
|
131
|
+
pw[win] += 1 - r["p"]
|
|
132
|
+
pw[lose] -= 1 - r["p"]
|
|
133
|
+
rows.append({"A_var": a, "B_var": b, **{k: r[k] for k in "ABCD"}, "p": r["p"], "winner": win})
|
|
134
|
+
wins = W.sum(axis=1)
|
|
135
|
+
losses = W.sum(axis=0)
|
|
136
|
+
tab = pd.DataFrame({"wins": wins, "wins-losses": wins - losses, "pW": pd.Series(pw)})
|
|
137
|
+
tab["rank"] = tab["pW"].rank(ascending=False, method="min").astype(int)
|
|
138
|
+
return {"decisions": pd.DataFrame(rows), "wins": W, "ranking": tab.sort_values(["pW", "wins"], ascending=False)}
|
srdkit/mcda.py
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
r"""Classical multicriteria decision making (MCDM) scores.
|
|
2
|
+
|
|
3
|
+
SRD is often used to compare the rankings produced by different MCDM methods
|
|
4
|
+
and to find their consensus: Lourenço and Lebensztajn (2018) applied it to eight
|
|
5
|
+
methods in post-Pareto analysis, and Héberger and co-workers showed that SRD with
|
|
6
|
+
the row-average reference agrees with the consensus of desirability, quality
|
|
7
|
+
loss, weighted Tchebycheff, MOORA and other methods. This module provides compact
|
|
8
|
+
implementations so that such comparisons run inside the package:
|
|
9
|
+
:func:`mcda_scores` returns an (alternatives x methods) table of scores in which
|
|
10
|
+
larger is always better; it can be passed directly to :func:`srdkit.srd`.
|
|
11
|
+
|
|
12
|
+
All methods take ``directions`` (``"max"``/``"min"`` per criterion) and
|
|
13
|
+
``weights`` (equal by default).
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import numpy as np
|
|
19
|
+
import pandas as pd
|
|
20
|
+
|
|
21
|
+
from ._utils import as_frame
|
|
22
|
+
from .ranking import rank_vector
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _prep(X, weights, directions):
|
|
26
|
+
df = as_frame(X)
|
|
27
|
+
A = df.to_numpy(float)
|
|
28
|
+
m = A.shape[1]
|
|
29
|
+
w = np.full(m, 1.0 / m) if weights is None else np.asarray(weights, float) / np.sum(weights)
|
|
30
|
+
if directions is None:
|
|
31
|
+
benefit = np.ones(m, bool)
|
|
32
|
+
elif isinstance(directions, dict):
|
|
33
|
+
benefit = np.array([str(directions.get(c, "max")).lower() != "min" for c in df.columns])
|
|
34
|
+
else:
|
|
35
|
+
benefit = np.array([str(d).lower() != "min" for d in directions])
|
|
36
|
+
return df, A, w, benefit
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _minmax_benefit(A, benefit):
|
|
40
|
+
lo, hi = A.min(axis=0), A.max(axis=0)
|
|
41
|
+
rng = np.where(hi > lo, hi - lo, 1.0)
|
|
42
|
+
N = (A - lo) / rng
|
|
43
|
+
N[:, ~benefit] = 1 - N[:, ~benefit]
|
|
44
|
+
return N
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def saw(X, weights=None, directions=None) -> pd.Series:
|
|
48
|
+
"""Simple additive weighting on min-max normalized criteria."""
|
|
49
|
+
df, A, w, b = _prep(X, weights, directions)
|
|
50
|
+
return pd.Series(_minmax_benefit(A, b) @ w, index=df.index, name="SAW")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def wpm(X, weights=None, directions=None) -> pd.Series:
|
|
54
|
+
"""Weighted product model (positive data): product of ``(x/max)^w`` (benefit) and ``(min/x)^w`` (cost)."""
|
|
55
|
+
df, A, w, b = _prep(X, weights, directions)
|
|
56
|
+
if (A <= 0).any():
|
|
57
|
+
raise ValueError("WPM needs positive data")
|
|
58
|
+
R = np.where(b, A / A.max(axis=0), A.min(axis=0) / A)
|
|
59
|
+
return pd.Series(np.exp(np.log(R) @ w), index=df.index, name="WPM")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def topsis(X, weights=None, directions=None) -> pd.Series:
|
|
63
|
+
"""TOPSIS closeness coefficient (vector normalization, Euclidean distances)."""
|
|
64
|
+
df, A, w, b = _prep(X, weights, directions)
|
|
65
|
+
nrm = np.sqrt((A ** 2).sum(axis=0))
|
|
66
|
+
V = A / np.where(nrm > 0, nrm, 1.0) * w
|
|
67
|
+
ideal = np.where(b, V.max(axis=0), V.min(axis=0))
|
|
68
|
+
anti = np.where(b, V.min(axis=0), V.max(axis=0))
|
|
69
|
+
dp = np.sqrt(((V - ideal) ** 2).sum(axis=1))
|
|
70
|
+
dm = np.sqrt(((V - anti) ** 2).sum(axis=1))
|
|
71
|
+
return pd.Series(dm / np.where(dp + dm > 0, dp + dm, 1.0), index=df.index, name="TOPSIS")
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def vikor(X, weights=None, directions=None, v: float = 0.5) -> pd.Series:
|
|
75
|
+
"""VIKOR; the score is ``-Q`` (larger is better)."""
|
|
76
|
+
df, A, w, b = _prep(X, weights, directions)
|
|
77
|
+
best = np.where(b, A.max(axis=0), A.min(axis=0))
|
|
78
|
+
worst = np.where(b, A.min(axis=0), A.max(axis=0))
|
|
79
|
+
rng = np.where(best != worst, best - worst, 1.0)
|
|
80
|
+
D = w * (best - A) / rng
|
|
81
|
+
S, R = D.sum(axis=1), D.max(axis=1)
|
|
82
|
+
sr = S.max() - S.min() or 1.0
|
|
83
|
+
rr = R.max() - R.min() or 1.0
|
|
84
|
+
Q = v * (S - S.min()) / sr + (1 - v) * (R - R.min()) / rr
|
|
85
|
+
return pd.Series(-Q, index=df.index, name="VIKOR")
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def moora(X, weights=None, directions=None) -> pd.Series:
|
|
89
|
+
"""MOORA ratio system: weighted vector-normalized benefits minus costs."""
|
|
90
|
+
df, A, w, b = _prep(X, weights, directions)
|
|
91
|
+
nrm = np.sqrt((A ** 2).sum(axis=0))
|
|
92
|
+
N = A / np.where(nrm > 0, nrm, 1.0) * w
|
|
93
|
+
return pd.Series(N[:, b].sum(axis=1) - N[:, ~b].sum(axis=1), index=df.index, name="MOORA")
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def tchebycheff(X, weights=None, directions=None) -> pd.Series:
|
|
97
|
+
"""Weighted Tchebycheff distance to the ideal point on normalized criteria (score = -distance)."""
|
|
98
|
+
df, A, w, b = _prep(X, weights, directions)
|
|
99
|
+
N = _minmax_benefit(A, b)
|
|
100
|
+
return pd.Series(-np.max(w * (1 - N), axis=1), index=df.index, name="Tchebycheff")
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def desirability_index(X, weights=None, directions=None, eps: float = 1e-3) -> pd.Series:
|
|
104
|
+
"""Weighted geometric mean of linear (Derringer, s = 1) desirabilities."""
|
|
105
|
+
df, A, w, b = _prep(X, weights, directions)
|
|
106
|
+
N = np.clip(_minmax_benefit(A, b), eps, 1)
|
|
107
|
+
return pd.Series(np.exp(np.log(N) @ w), index=df.index, name="Desirability")
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def quality_loss(X, weights=None, directions=None) -> pd.Series:
|
|
111
|
+
"""Taguchi-type quadratic quality loss from the ideal (score = -loss)."""
|
|
112
|
+
df, A, w, b = _prep(X, weights, directions)
|
|
113
|
+
N = _minmax_benefit(A, b)
|
|
114
|
+
return pd.Series(-((1 - N) ** 2) @ w, index=df.index, name="QualityLoss")
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def borda(X, weights=None, directions=None) -> pd.Series:
|
|
118
|
+
"""Weighted Borda count: weighted sum of the criterion ranks (larger = better)."""
|
|
119
|
+
df, A, w, b = _prep(X, weights, directions)
|
|
120
|
+
R = np.column_stack([rank_vector(A[:, k] if b[k] else -A[:, k]) for k in range(A.shape[1])])
|
|
121
|
+
return pd.Series(R @ w, index=df.index, name="Borda")
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def copeland(X, weights=None, directions=None) -> pd.Series:
|
|
125
|
+
"""Copeland score: weighted pairwise majority wins minus losses."""
|
|
126
|
+
df, A, w, b = _prep(X, weights, directions)
|
|
127
|
+
G = np.where(b, A, -A)
|
|
128
|
+
D = np.sign(G[:, None, :] - G[None, :, :]) @ w
|
|
129
|
+
return pd.Series(np.sign(D).sum(axis=1), index=df.index, name="Copeland")
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def promethee_ii(X, weights=None, directions=None, functions="usual", params=None) -> pd.Series:
|
|
133
|
+
"""Promethee II net flow (see :mod:`srdkit.promethee`)."""
|
|
134
|
+
from .promethee import promethee
|
|
135
|
+
|
|
136
|
+
return promethee(X, weights, functions, params, directions).phi.rename("PrometheeII")
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
METHODS = {"SAW": saw, "WPM": wpm, "TOPSIS": topsis, "VIKOR": vikor, "MOORA": moora, "Tchebycheff": tchebycheff,
|
|
140
|
+
"Desirability": desirability_index, "QualityLoss": quality_loss, "Borda": borda, "Copeland": copeland,
|
|
141
|
+
"PrometheeII": promethee_ii}
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def objective_weights(X, method: str = "entropy", directions=None) -> pd.Series:
|
|
145
|
+
r"""Classical "objective" criterion weights of a decision matrix (rows = alternatives).
|
|
146
|
+
|
|
147
|
+
``"equal"``; ``"entropy"`` (Shannon entropy of the column shares of the
|
|
148
|
+
min-max normalized values, :math:`w_j\propto 1-E_j`; Hwang and Yoon, 1981);
|
|
149
|
+
``"std"`` (standard deviation of the normalized values); ``"critic"``
|
|
150
|
+
(:math:`w_j\propto\sigma_j\sum_k(1-r_{jk})`; Diakoulaki, Mavrotas and
|
|
151
|
+
Papayannakis, 1995). Different schemes give different weights and often
|
|
152
|
+
different rankings --- the reason why Héberger (2026) regards the choice among
|
|
153
|
+
them as subjective, and why SRD-based weights taken from the data are offered
|
|
154
|
+
in :mod:`srdkit.weights`.
|
|
155
|
+
|
|
156
|
+
>>> objective_weights([[1, 10], [2, 10], [3, 11]], "std").round(3).tolist()
|
|
157
|
+
[0.464, 0.536]
|
|
158
|
+
"""
|
|
159
|
+
df, A, _, benefit = _prep(X, None, directions)
|
|
160
|
+
N = _minmax_benefit(A, benefit)
|
|
161
|
+
m = A.shape[1]
|
|
162
|
+
if method == "equal":
|
|
163
|
+
w = np.ones(m)
|
|
164
|
+
elif method == "entropy":
|
|
165
|
+
P = (N + 1e-12) / (N + 1e-12).sum(axis=0)
|
|
166
|
+
E = -(P * np.log(P)).sum(axis=0) / np.log(A.shape[0])
|
|
167
|
+
w = 1 - E
|
|
168
|
+
elif method == "std":
|
|
169
|
+
w = N.std(axis=0, ddof=0)
|
|
170
|
+
elif method == "critic":
|
|
171
|
+
sd = N.std(axis=0, ddof=0)
|
|
172
|
+
C = np.corrcoef(N, rowvar=False) if m > 1 else np.ones((1, 1))
|
|
173
|
+
C = np.nan_to_num(C, nan=0.0)
|
|
174
|
+
w = sd * (1 - C).sum(axis=0)
|
|
175
|
+
else:
|
|
176
|
+
raise ValueError("method must be 'equal', 'entropy', 'std' or 'critic'")
|
|
177
|
+
w = np.clip(w, 0, None)
|
|
178
|
+
w = w / w.sum() if w.sum() > 0 else np.ones(m) / m
|
|
179
|
+
return pd.Series(w, index=df.columns, name=method)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def mcda_scores(X, weights=None, directions=None, methods=None) -> pd.DataFrame:
|
|
183
|
+
"""Scores of several MCDM methods (columns), larger is better for every method.
|
|
184
|
+
|
|
185
|
+
``methods`` is a list of names from :data:`METHODS` (all applicable methods by
|
|
186
|
+
default; WPM is skipped for non-positive data).
|
|
187
|
+
"""
|
|
188
|
+
df = as_frame(X)
|
|
189
|
+
names = list(METHODS) if methods is None else list(methods)
|
|
190
|
+
out = {}
|
|
191
|
+
for name in names:
|
|
192
|
+
if name == "WPM" and methods is None and (df.to_numpy() <= 0).any():
|
|
193
|
+
continue
|
|
194
|
+
out[name] = METHODS[name](df, weights, directions)
|
|
195
|
+
return pd.DataFrame(out, index=df.index)
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def mcda_ranks(X, weights=None, directions=None, methods=None) -> pd.DataFrame:
|
|
199
|
+
"""Ranks (1 = best) of the alternatives by several MCDM methods."""
|
|
200
|
+
S = mcda_scores(X, weights, directions, methods)
|
|
201
|
+
return S.apply(lambda s: pd.Series(rank_vector(-s.to_numpy()), index=s.index))
|
srdkit/nmf.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
r"""Matrix factorization-based multi-objective ranking with SRD (NMF-SRD).
|
|
2
|
+
|
|
3
|
+
With many objectives the Pareto front saturates: almost every solution is
|
|
4
|
+
non-dominated. Abonyi, Ipkovich, Dörgő and Héberger (2023) reduce the
|
|
5
|
+
:math:`n` objectives to :math:`p\ll n` aggregated ones by non-negative matrix
|
|
6
|
+
factorization,
|
|
7
|
+
|
|
8
|
+
.. math:: \min_{\mathbf W\ge0,\ \mathbf H\ge0}\ \lVert\mathbf X-\mathbf W\mathbf H\rVert_F^2
|
|
9
|
+
\;+\;\alpha\lVert\mathbf W\rVert_F^2\;+\;\beta\sum_k\lVert\mathbf h_k\rVert_2^2 ,
|
|
10
|
+
|
|
11
|
+
whose non-negative loadings never mix negatively correlated objectives (unlike
|
|
12
|
+
PCA), so that the Pareto front of the scores :math:`\mathbf W` is meaningful.
|
|
13
|
+
Ranks are the layers of non-dominated sorting of :math:`\mathbf W`. SRD with the
|
|
14
|
+
row-maximum reference selects the objectives: those ranked like random numbers
|
|
15
|
+
or reversely are removed before the factorization, and SRD validates the result.
|
|
16
|
+
|
|
17
|
+
:func:`nmf` implements the multiplicative updates of Lee and Seung (1999) with the
|
|
18
|
+
:math:`L_2` penalties of eq. 11 of the paper; :func:`nmf_srd_ranking` runs the
|
|
19
|
+
whole procedure.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import numpy as np
|
|
25
|
+
import pandas as pd
|
|
26
|
+
|
|
27
|
+
from ._utils import as_frame, as_rng
|
|
28
|
+
from .pareto import hypervolume, nondominated_layers, relative_entropy
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def nmf(X, n_components: int = 2, alpha: float = 0.0, beta: float = 0.0, max_iter: int = 2000, tol: float = 1e-8,
|
|
32
|
+
random_state=0, n_init: int = 5) -> tuple[np.ndarray, np.ndarray, float]:
|
|
33
|
+
"""Non-negative matrix factorization ``X ~ W H`` with optional L2 penalties.
|
|
34
|
+
|
|
35
|
+
Returns ``W`` (n x p scores), ``H`` (p x m loadings) and the relative residual.
|
|
36
|
+
The best of ``n_init`` random initializations is kept.
|
|
37
|
+
"""
|
|
38
|
+
A = as_frame(X).to_numpy(float)
|
|
39
|
+
if (A < 0).any():
|
|
40
|
+
raise ValueError("NMF needs non-negative data (min-max scale the objectives first)")
|
|
41
|
+
rng = as_rng(random_state)
|
|
42
|
+
n, m = A.shape
|
|
43
|
+
eps = 1e-12
|
|
44
|
+
best = None
|
|
45
|
+
scale = np.sqrt(A.mean() / n_components) if A.mean() > 0 else 1.0
|
|
46
|
+
for _ in range(n_init):
|
|
47
|
+
W = rng.random((n, n_components)) * scale + eps
|
|
48
|
+
H = rng.random((n_components, m)) * scale + eps
|
|
49
|
+
prev = np.inf
|
|
50
|
+
for it in range(max_iter):
|
|
51
|
+
H *= (W.T @ A) / (W.T @ W @ H + beta * H + eps)
|
|
52
|
+
W *= (A @ H.T) / (W @ H @ H.T + alpha * W + eps)
|
|
53
|
+
if it % 20 == 0:
|
|
54
|
+
err = np.linalg.norm(A - W @ H) ** 2
|
|
55
|
+
if abs(prev - err) <= tol * max(prev, 1.0):
|
|
56
|
+
break
|
|
57
|
+
prev = err
|
|
58
|
+
res = np.linalg.norm(A - W @ H) / max(np.linalg.norm(A), eps)
|
|
59
|
+
if best is None or res < best[2]:
|
|
60
|
+
best = (W.copy(), H.copy(), float(res))
|
|
61
|
+
W, H, res = best
|
|
62
|
+
# order the components by their contribution and normalize H rows to unit maximum
|
|
63
|
+
norm = H.max(axis=1, keepdims=True)
|
|
64
|
+
norm[norm == 0] = 1.0
|
|
65
|
+
H = H / norm
|
|
66
|
+
W = W * norm.T
|
|
67
|
+
order = np.argsort(-(W.sum(axis=0)))
|
|
68
|
+
return W[:, order], H[order], res
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def select_objectives_srd(X, reference="max", alpha: float = 0.05, keep: str = "similar", max_rounds: int | None = None) -> dict:
|
|
72
|
+
"""Remove the objectives that SRD ranks randomly or reversely (iteratively).
|
|
73
|
+
|
|
74
|
+
In every round SRD (with the given reference, row maximum by default) and its
|
|
75
|
+
CRRN test are computed on the remaining objectives; those whose verdict is not
|
|
76
|
+
``keep`` are dropped, until all remaining ones pass. Returns the kept and
|
|
77
|
+
removed objectives and the final SRD/CRRN results.
|
|
78
|
+
"""
|
|
79
|
+
from .core import srd
|
|
80
|
+
from .validation import crrn
|
|
81
|
+
|
|
82
|
+
df = as_frame(X)
|
|
83
|
+
cols = list(df.columns)
|
|
84
|
+
removed = []
|
|
85
|
+
rounds = 0
|
|
86
|
+
while True:
|
|
87
|
+
res = srd(df[cols], reference=reference)
|
|
88
|
+
val = crrn(res, alpha=alpha)
|
|
89
|
+
bad = [c for c in cols if val.table.loc[c, "verdict"] != keep]
|
|
90
|
+
if not bad or len(cols) - len(bad) < 2 or (max_rounds is not None and rounds >= max_rounds):
|
|
91
|
+
break
|
|
92
|
+
removed += [(c, val.table.loc[c, "verdict"], rounds) for c in bad]
|
|
93
|
+
cols = [c for c in cols if c not in bad]
|
|
94
|
+
rounds += 1
|
|
95
|
+
return {"kept": cols, "removed": pd.DataFrame(removed, columns=["objective", "verdict", "round"]), "srd": res, "crrn": val}
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def nmf_srd_ranking(X, n_components: int = 2, directions=None, select: bool = True, reference="max", alpha_srd: float = 0.05,
|
|
99
|
+
alpha: float = 0.0, beta: float = 0.0, random_state=0) -> dict:
|
|
100
|
+
"""The NMF-SRD multi-objective ranking of Abonyi et al. (2023).
|
|
101
|
+
|
|
102
|
+
Steps: orientation (minimized objectives are reversed), min-max scaling,
|
|
103
|
+
SRD-based objective selection, NMF, non-dominated sorting of the scores.
|
|
104
|
+
Returns the Pareto layer of every solution (``"rank"``, 0 = first front), the
|
|
105
|
+
scores and loadings, the relative entropy of the ranking, the hypervolume of the
|
|
106
|
+
first front and the selection record.
|
|
107
|
+
"""
|
|
108
|
+
df = as_frame(X)
|
|
109
|
+
if directions is not None:
|
|
110
|
+
dirs = directions if isinstance(directions, dict) else dict(zip(df.columns, directions))
|
|
111
|
+
for c, d in dirs.items():
|
|
112
|
+
if str(d).lower() == "min":
|
|
113
|
+
df[c] = -df[c]
|
|
114
|
+
Z = (df - df.min()) / (df.max() - df.min()).replace(0, 1)
|
|
115
|
+
sel = select_objectives_srd(Z, reference=reference, alpha=alpha_srd) if select else None
|
|
116
|
+
cols = sel["kept"] if sel else list(Z.columns)
|
|
117
|
+
W, H, res = nmf(Z[cols], n_components, alpha=alpha, beta=beta, random_state=random_state)
|
|
118
|
+
layers = nondominated_layers(W)
|
|
119
|
+
comp = [f"NMF{k + 1}" for k in range(n_components)]
|
|
120
|
+
return {"rank": pd.Series(layers, index=df.index, name="layer"),
|
|
121
|
+
"scores": pd.DataFrame(W, index=df.index, columns=comp),
|
|
122
|
+
"loadings": pd.DataFrame(H.T, index=cols, columns=comp), "residual": res,
|
|
123
|
+
"relative_entropy": relative_entropy(layers), "hypervolume": hypervolume(W) if n_components <= 6 else np.nan,
|
|
124
|
+
"selection": sel, "objectives": cols}
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def pca_pareto_ranking(X, n_components: int = 2) -> dict:
|
|
128
|
+
"""The PCA alternative used for comparison in the paper (scores may mix conflicting objectives)."""
|
|
129
|
+
Z = as_frame(X)
|
|
130
|
+
Z = (Z - Z.mean()) / Z.std(ddof=1).replace(0, 1)
|
|
131
|
+
u, s, vt = np.linalg.svd(Z.to_numpy(float), full_matrices=False)
|
|
132
|
+
T = u[:, :n_components] * s[:n_components]
|
|
133
|
+
for k in range(n_components): # orient every component positively with the mean objective
|
|
134
|
+
if np.corrcoef(T[:, k], Z.mean(axis=1))[0, 1] < 0:
|
|
135
|
+
T[:, k] *= -1
|
|
136
|
+
vt[k] *= -1
|
|
137
|
+
layers = nondominated_layers(T)
|
|
138
|
+
comp = [f"PC{k + 1}" for k in range(n_components)]
|
|
139
|
+
return {"rank": pd.Series(layers, index=Z.index, name="layer"), "scores": pd.DataFrame(T, index=Z.index, columns=comp),
|
|
140
|
+
"loadings": pd.DataFrame(vt[:n_components].T, index=Z.columns, columns=comp),
|
|
141
|
+
"relative_entropy": relative_entropy(layers)}
|