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/core.py ADDED
@@ -0,0 +1,364 @@
1
+ r"""The sum of ranking differences (SRD).
2
+
3
+ Let :math:`\mathbf{X}\in\mathbb{R}^{n\times m}` hold :math:`m` solutions
4
+ (methods, models, criteria, experts) evaluated on :math:`n` objects, and let
5
+ :math:`\mathbf{y}` be the reference. With :math:`r_{ij}` the rank of object
6
+ :math:`i` in column :math:`j` and :math:`q_i` its rank in the reference,
7
+
8
+ .. math:: \mathrm{SRD}_j = \sum_{i=1}^{n} \lvert r_{ij} - q_i \rvert ,
9
+
10
+ the city-block (:math:`L_1`) distance of the rank vectors (Héberger, 2010).
11
+ Without ties it is Spearman's footrule; the maximum, attained by the reversed
12
+ ranking, is :math:`\lfloor n^2/2\rfloor`, so that the normalized value
13
+ :math:`\mathrm{SRD}_j/\lfloor n^2/2\rfloor` lies in :math:`[0,1]` and is usually
14
+ reported in percent. The smaller the SRD, the closer the solution to the
15
+ reference.
16
+
17
+ :func:`srd` computes the values together with everything that later steps need
18
+ (ranks, signed rank differences, the reference); :func:`pairwise_srd` takes every
19
+ solution in turn as the reference; :class:`SRD` wraps the computation in a
20
+ scikit-learn-like estimator.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ from dataclasses import dataclass, field
26
+
27
+ import numpy as np
28
+ import pandas as pd
29
+
30
+ from ._utils import as_frame, check_finite, srd_max
31
+ from .ranking import rank_matrix, rank_vector, soft_rank_matrix, soft_rank_vector
32
+ from .reference import make_reference, reference_name
33
+
34
+ NORMALIZATIONS = ("max", "attainable", "leader", "none")
35
+
36
+
37
+ @dataclass
38
+ class SRDResult:
39
+ """Outcome of an SRD computation.
40
+
41
+ Attributes
42
+ ----------
43
+ srd : pandas.Series
44
+ Raw SRD value of every solution (column order of the input).
45
+ srd_max : float
46
+ Normalizing constant (``floor(n^2/2)`` by default).
47
+ n : int
48
+ Number of objects (rows).
49
+ ranks : pandas.DataFrame
50
+ Ranks of the solutions, shape ``(n, m)``.
51
+ reference : numpy.ndarray
52
+ Reference values, shape ``(n,)`` (or ``(n, m)`` for leave-one-out references).
53
+ reference_ranks : numpy.ndarray
54
+ Ranks of the reference (same shape as ``reference``).
55
+ differences : pandas.DataFrame
56
+ Signed rank differences ``r_ij - q_i``; their absolute values are the
57
+ contributions of the objects to SRD.
58
+ data : pandas.DataFrame
59
+ The input matrix.
60
+ """
61
+
62
+ srd: pd.Series
63
+ srd_max: float
64
+ n: int
65
+ ranks: pd.DataFrame
66
+ reference: np.ndarray
67
+ reference_ranks: np.ndarray
68
+ differences: pd.DataFrame
69
+ data: pd.DataFrame
70
+ reference_method: str = "mean"
71
+ ties: str = "average"
72
+ distance: str = "footrule"
73
+ meta: dict = field(default_factory=dict)
74
+
75
+ # ------------------------------------------------------------------ views
76
+ @property
77
+ def normalized(self) -> pd.Series:
78
+ """SRD divided by :attr:`srd_max` (between 0 and 1)."""
79
+ return self.srd / self.srd_max if self.srd_max > 0 else self.srd * 0.0
80
+
81
+ @property
82
+ def percent(self) -> pd.Series:
83
+ """Normalized SRD in percent."""
84
+ return 100.0 * self.normalized
85
+
86
+ @property
87
+ def contributions(self) -> pd.DataFrame:
88
+ """Absolute rank differences ``|r_ij - q_i|`` (objects x solutions)."""
89
+ return self.differences.abs()
90
+
91
+ @property
92
+ def order(self) -> list[str]:
93
+ """Solutions sorted from the closest to the farthest from the reference."""
94
+ return list(self.srd.sort_values(kind="stable").index)
95
+
96
+ @property
97
+ def best(self) -> str:
98
+ """The solution closest to the reference."""
99
+ return self.order[0]
100
+
101
+ @property
102
+ def columns(self) -> list[str]:
103
+ return list(self.srd.index)
104
+
105
+ def to_frame(self, sort: bool = True) -> pd.DataFrame:
106
+ """Table of SRD, normalized SRD and SRD% (sorted by SRD when ``sort``)."""
107
+ df = pd.DataFrame({"SRD": self.srd, "SRD_norm": self.normalized, "SRD%": self.percent})
108
+ df.index.name = "solution"
109
+ return df.sort_values("SRD", kind="stable") if sort else df
110
+
111
+ def summary(self) -> pd.DataFrame: # alias used throughout the documentation
112
+ return self.to_frame()
113
+
114
+ # --------------------------------------------------------- convenience API
115
+ def validate(self, method: str = "auto", alpha: float = 0.05, **kwargs):
116
+ """Comparison of ranks with random numbers (CRRN); see :func:`srdkit.crrn`."""
117
+ if self.meta.get("value_based"):
118
+ from .value import value_crrn
119
+
120
+ return value_crrn(self, alpha=alpha, **kwargs)
121
+ from .validation import crrn
122
+
123
+ return crrn(self, method=method, alpha=alpha, **kwargs)
124
+
125
+ def cross_validate(self, **kwargs):
126
+ """Cross-validation of the SRD values; see :func:`srdkit.cross_validate`."""
127
+ from .validation import cross_validate
128
+
129
+ ref = self.meta.get("reference_spec", self.reference_method)
130
+ if self.meta.get("value_based"):
131
+ kwargs.setdefault("measure", float(self.meta["p"]))
132
+ return cross_validate(self.data, reference=ref, **kwargs)
133
+ return cross_validate(self.data, reference=ref, ties=self.ties, **kwargs)
134
+
135
+ def plot(self, ax=None, **kwargs):
136
+ """The classical SRD plot; see :func:`srdkit.viz.plot_srd`."""
137
+ from .viz import plot_srd
138
+
139
+ return plot_srd(self, ax=ax, **kwargs)
140
+
141
+ def __repr__(self) -> str:
142
+ head = (f"SRDResult(n={self.n}, m={len(self.srd)}, reference={self.reference_method!r}, "
143
+ f"ties={self.ties!r}, distance={self.distance!r})")
144
+ tab = self.to_frame().round(3).to_string()
145
+ return head + "\n" + tab
146
+
147
+
148
+ def _reference_ranks(ref: np.ndarray, ties: str, rank_reference: bool, soft_sigma=None) -> np.ndarray:
149
+ if not rank_reference:
150
+ return np.asarray(ref, dtype=float)
151
+ if ref.ndim == 1:
152
+ return soft_rank_vector(ref, soft_sigma) if soft_sigma is not None else rank_vector(ref, ties=ties)
153
+ cols = [soft_rank_vector(ref[:, j], soft_sigma) if soft_sigma is not None else rank_vector(ref[:, j], ties=ties)
154
+ for j in range(ref.shape[1])]
155
+ return np.column_stack(cols)
156
+
157
+
158
+ def attainable_max(r, q) -> float:
159
+ """Largest footrule distance between rearrangements of the tie patterns of ``r`` and ``q``.
160
+
161
+ Solved exactly as a maximum-cost assignment; equals ``floor(n^2/2)`` without ties.
162
+ """
163
+ from scipy.optimize import linear_sum_assignment
164
+
165
+ r = np.asarray(r, dtype=float)
166
+ q = np.asarray(q, dtype=float)
167
+ cost = np.abs(r[:, None] - q[None, :])
168
+ i, j = linear_sum_assignment(cost, maximize=True)
169
+ return float(cost[i, j].sum())
170
+
171
+
172
+ def srd(X, reference="mean", *, ties: str = "average", normalization: str = "max", distance="footrule",
173
+ rank_reference: bool = True, ascending=True, soft_sigma=None, missing: str = "raise", **reference_kwargs) -> SRDResult:
174
+ r"""Sum of ranking differences of every column of ``X`` from a reference.
175
+
176
+ Parameters
177
+ ----------
178
+ X : array-like or DataFrame, shape (n_objects, n_solutions)
179
+ Rows are objects (samples, alternatives, compounds), columns are the
180
+ solutions to be compared (methods, models, criteria, experts).
181
+ reference : str, callable or array-like, default "mean"
182
+ Reference specification, see :func:`srdkit.make_reference`. An array of
183
+ length ``n`` is an external gold standard.
184
+ ties : {"average", "min", "max", "dense", "ordinal", "random"}
185
+ Rank convention for equal values (mid-ranks by default).
186
+ normalization : {"max", "attainable", "leader", "none"}
187
+ ``"max"`` divides by ``floor(n^2/2)`` (the SRD convention);
188
+ ``"attainable"`` by the largest distance reachable with the observed tie
189
+ patterns; ``"leader"`` by the largest SRD of the solutions ("compare with
190
+ leader", Héberger 2026); ``"none"`` keeps raw values (``normalized == srd``).
191
+ distance : str or callable, default "footrule"
192
+ Rank distance; ``"footrule"`` is SRD. Other choices (``"kendall"``,
193
+ ``"spearman"``, ``"cayley"``, ``"ulam"``, ``"hamming"``, ``"chebyshev"``, or
194
+ a callable ``f(r, q) -> float``) give the generalized SRD family of
195
+ :mod:`srdkit.distances`.
196
+ rank_reference : bool, default True
197
+ Rank the reference. Set to ``False`` when the reference is already on the
198
+ rank scale (e.g. a mean rank) and should be used as it is.
199
+ ascending : bool, list or dict
200
+ Ranking direction(s) of the solutions (see :func:`srdkit.rank_matrix`).
201
+ soft_sigma : float or None
202
+ If given, soft ranks with relative error ``soft_sigma`` replace the ranks
203
+ (see :func:`srdkit.ranking.soft_rank_matrix`).
204
+ missing : {"raise", "drop"}
205
+ Treatment of rows with missing values.
206
+ **reference_kwargs
207
+ Passed to :func:`srdkit.make_reference` (``weights``, ``row_methods``, ``trim``).
208
+
209
+ Returns
210
+ -------
211
+ SRDResult
212
+
213
+ Examples
214
+ --------
215
+ >>> import numpy as np
216
+ >>> X = np.array([[1, 3, 2], [2, 1, 3], [3, 2, 1], [4, 4, 4]], dtype=float)
217
+ >>> res = srd(X, reference=[1, 2, 3, 4])
218
+ >>> res.srd.tolist()
219
+ [0.0, 4.0, 4.0]
220
+ >>> res.srd_max
221
+ 8
222
+ """
223
+ df = check_finite(as_frame(X), missing=missing)
224
+ n, m = df.shape
225
+ if n < 2:
226
+ raise ValueError("SRD needs at least two objects (rows)")
227
+ ref = make_reference(df, reference, ties=ties, **reference_kwargs)
228
+ if soft_sigma is not None:
229
+ R = soft_rank_matrix(df, sigma=soft_sigma)
230
+ sig_ref = soft_sigma * (np.std(ref, ddof=1) if ref.ndim == 1 else 1.0)
231
+ q = _reference_ranks(ref, ties, rank_reference, soft_sigma=sig_ref)
232
+ else:
233
+ R = rank_matrix(df, ties=ties, ascending=ascending)
234
+ q = _reference_ranks(ref, ties, rank_reference)
235
+ Q = q[:, None] if q.ndim == 1 else q
236
+ Rv = R.to_numpy()
237
+ if distance == "footrule":
238
+ values = np.abs(Rv - Q).sum(axis=0)
239
+ dist_name = "footrule"
240
+ else:
241
+ from .distances import get_distance
242
+
243
+ f, dist_name = get_distance(distance)
244
+ values = np.asarray([f(Rv[:, j], Q[:, min(j, Q.shape[1] - 1)]) for j in range(m)], dtype=float)
245
+ diff = pd.DataFrame(Rv - Q, index=df.index, columns=df.columns)
246
+ if normalization == "max":
247
+ if distance == "footrule":
248
+ smax = srd_max(n)
249
+ else:
250
+ from .distances import distance_max
251
+
252
+ smax = distance_max(dist_name, n)
253
+ elif normalization == "attainable":
254
+ if distance != "footrule":
255
+ raise ValueError("normalization='attainable' is defined for the footrule (SRD) only")
256
+ smax = max(attainable_max(Rv[:, j], Q[:, min(j, Q.shape[1] - 1)]) for j in range(m))
257
+ elif normalization == "leader":
258
+ smax = float(values.max()) if values.max() > 0 else 1.0
259
+ elif normalization == "none":
260
+ smax = 1.0
261
+ else:
262
+ raise ValueError(f"normalization must be one of {NORMALIZATIONS}")
263
+ return SRDResult(srd=pd.Series(values, index=df.columns, name="SRD"), srd_max=smax, n=n, ranks=R,
264
+ reference=ref, reference_ranks=q, differences=diff, data=df,
265
+ reference_method=reference_name(reference), ties=ties, distance=dist_name,
266
+ meta={"reference_spec": reference if isinstance(reference, str) or callable(reference) else ref,
267
+ "normalization": normalization, "soft_sigma": soft_sigma})
268
+
269
+
270
+ def pairwise_srd(X, *, ties: str = "average", normalize: bool = True, reference=None, distance="footrule") -> pd.DataFrame:
271
+ """SRD of every pair of columns, each column taken in turn as the reference.
272
+
273
+ With ``reference`` given (a specification as in :func:`srd`), the reference
274
+ is added as the first row/column (labelled ``"reference"``). The footrule
275
+ matrix is symmetric with a zero diagonal; it is the distance matrix behind
276
+ the SRD heatmap, the SRD map, clustering and the SRD-ordered parallel
277
+ coordinates.
278
+ """
279
+ df = as_frame(X)
280
+ n = df.shape[0]
281
+ if reference is not None:
282
+ ref = make_reference(df, reference, ties=ties)
283
+ if ref.ndim != 1:
284
+ raise ValueError("pairwise_srd needs a single reference vector")
285
+ df = pd.concat([pd.Series(ref, index=df.index, name="reference"), df], axis=1)
286
+ R = rank_matrix(df, ties=ties).to_numpy()
287
+ if distance == "footrule":
288
+ D = np.abs(R[:, :, None] - R[:, None, :]).sum(axis=0)
289
+ smax = srd_max(n)
290
+ else:
291
+ from .distances import distance_max, get_distance
292
+
293
+ f, name = get_distance(distance)
294
+ k = R.shape[1]
295
+ D = np.zeros((k, k))
296
+ for a in range(k):
297
+ for b in range(a + 1, k):
298
+ D[a, b] = D[b, a] = f(R[:, a], R[:, b])
299
+ smax = distance_max(name, n)
300
+ if normalize and smax > 0:
301
+ D = D / smax
302
+ return pd.DataFrame(D, index=df.columns, columns=df.columns)
303
+
304
+
305
+ class SRD:
306
+ """Scikit-learn-style estimator for the sum of ranking differences.
307
+
308
+ Parameters are those of :func:`srd`. After :meth:`fit` the attributes
309
+ ``srd_``, ``srd_norm_``, ``ranks_``, ``reference_``, ``order_`` and
310
+ ``result_`` are available; :meth:`validate` and :meth:`cross_validate`
311
+ run the two validation steps of the SRD procedure.
312
+
313
+ Examples
314
+ --------
315
+ >>> import numpy as np
316
+ >>> X = np.array([[1, 2, 3], [2, 1, 2], [3, 3, 1], [4, 4, 4], [5, 5, 5]], dtype=float)
317
+ >>> model = SRD(reference="mean").fit(X)
318
+ >>> model.order_
319
+ ['c2', 'c1', 'c3']
320
+ """
321
+
322
+ def __init__(self, reference="mean", ties: str = "average", normalization: str = "max", distance="footrule",
323
+ rank_reference: bool = True, soft_sigma=None, **reference_kwargs):
324
+ self.reference = reference
325
+ self.ties = ties
326
+ self.normalization = normalization
327
+ self.distance = distance
328
+ self.rank_reference = rank_reference
329
+ self.soft_sigma = soft_sigma
330
+ self.reference_kwargs = reference_kwargs
331
+
332
+ def fit(self, X, y=None):
333
+ """Compute SRD; ``y`` (optional) is an external reference that overrides ``reference``."""
334
+ ref = self.reference if y is None else y
335
+ self.result_ = srd(X, reference=ref, ties=self.ties, normalization=self.normalization, distance=self.distance,
336
+ rank_reference=self.rank_reference, soft_sigma=self.soft_sigma, **self.reference_kwargs)
337
+ self.srd_ = self.result_.srd
338
+ self.srd_norm_ = self.result_.normalized
339
+ self.ranks_ = self.result_.ranks
340
+ self.reference_ = self.result_.reference
341
+ self.order_ = self.result_.order
342
+ return self
343
+
344
+ def fit_transform(self, X, y=None) -> pd.Series:
345
+ return self.fit(X, y).srd_norm_
346
+
347
+ def validate(self, **kwargs):
348
+ return self.result_.validate(**kwargs)
349
+
350
+ def cross_validate(self, **kwargs):
351
+ return self.result_.cross_validate(**kwargs)
352
+
353
+ def get_params(self, deep: bool = True) -> dict:
354
+ return {"reference": self.reference, "ties": self.ties, "normalization": self.normalization,
355
+ "distance": self.distance, "rank_reference": self.rank_reference, "soft_sigma": self.soft_sigma,
356
+ **self.reference_kwargs}
357
+
358
+ def set_params(self, **params):
359
+ for k, v in params.items():
360
+ setattr(self, k, v)
361
+ return self
362
+
363
+ def __repr__(self) -> str:
364
+ return f"SRD(reference={self.reference!r}, ties={self.ties!r}, distance={self.distance!r})"
@@ -0,0 +1,160 @@
1
+ r"""Bundled and generated data sets.
2
+
3
+ * :func:`load_co2` — greenhouse gas emissions by sector and economic indicators of
4
+ 146 countries in 2018 (Climate Watch CAIT, FAO, OECD/IEA and World Bank data as
5
+ compiled by Ipkovich, Héberger and Abonyi, 2021, github.com/abonyilab/parcoord);
6
+ the data of the SRD-based parallel coordinates and of the uSRD study.
7
+ * :func:`small_example` — a small illustrative table (8 objects, 5 methods) used
8
+ in the first chapter of the book; the numbers are invented for teaching.
9
+ * :func:`calibration_merits` — model merits of ridge-regression calibration models
10
+ along a path of the ridge parameter, computed on simulated spectra (for the
11
+ merit-fusion example of Kalivas, Héberger and Andries, 2015).
12
+ * :func:`outlier_measures` — several outlier measures of simulated multivariate
13
+ samples with planted outliers (for consensus outlier detection).
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from importlib import resources
19
+
20
+ import numpy as np
21
+ import pandas as pd
22
+
23
+ from .._utils import as_rng
24
+ from ..simulate import make_decision_problem, make_method_comparison, make_ranking_sequence, mallows
25
+
26
+ SECTORS = {"AGR": "Agriculture", "BLD": "Building", "BNK": "Bunker fuels", "ELH": "Electricity/heat", "ENG": "Energy",
27
+ "IND": "Industrial processes", "LUCF": "Land-use change and forestry", "MAN": "Manufacturing/construction",
28
+ "OFC": "Other fuel combustion", "TOT": "Total excluding LUCF", "TRP": "Transportation", "WAS": "Waste"}
29
+
30
+
31
+ def load_co2(per_capita: bool = True, include_world: bool = False, return_reference: bool = False):
32
+ """Greenhouse gas emissions by sector and economic indicators of 146 countries (2018).
33
+
34
+ Emission columns are named ``<sector>e<gas>`` (``TOTeAllGHG`` is the total of
35
+ all greenhouse gases excluding land use, the gold standard of the original
36
+ study). With ``per_capita=True`` emissions are converted to tonnes CO2e per
37
+ capita and GDP to GDP per capita; the population column is dropped.
38
+ ``include_world`` keeps the aggregate row ``World`` that is present in the
39
+ original file. With ``return_reference=True`` the function returns
40
+ ``(X, y)`` where ``y`` is total emissions per capita and ``X`` the other columns.
41
+ """
42
+ with resources.files(__package__).joinpath("data/co2_2018.csv").open("r", encoding="utf-8") as fh:
43
+ df = pd.read_csv(fh)
44
+ df = df.set_index("CountryName")
45
+ df.index.name = "country"
46
+ if not include_world:
47
+ df = df.drop(index="World", errors="ignore")
48
+ if per_capita:
49
+ pop = df["Pop"]
50
+ emis = [c for c in df.columns if "e" in c and c.split("e")[0] in SECTORS]
51
+ out = df[emis].div(pop, axis=0) * 1e6
52
+ out["GDPpc"] = df["GDP"] / pop
53
+ for c in ("RuralPop", "GDPGrowth", "UrbanGrowth"):
54
+ out[c] = df[c]
55
+ df = out
56
+ if return_reference:
57
+ y = df["TOTeAllGHG"].rename("TOTeAllGHG")
58
+ return df.drop(columns=["TOTeAllGHG"]), y
59
+ return df
60
+
61
+
62
+ def small_example() -> tuple[pd.DataFrame, pd.Series]:
63
+ """An illustrative table: five methods estimate a property of eight samples; the last vector is the reference.
64
+
65
+ The numbers are invented for teaching (no measurement behind them): M1 follows
66
+ the reference closely, M2 has two swaps, M3 is noisy, M4 is almost random and
67
+ M5 reverses the order. M2 and M3 contain ties.
68
+ """
69
+ ref = pd.Series([1.2, 2.0, 2.9, 4.1, 5.2, 6.0, 7.1, 8.3], name="reference",
70
+ index=[f"S{i}" for i in range(1, 9)])
71
+ X = pd.DataFrame({
72
+ "M1": [1.0, 2.2, 3.1, 3.9, 5.0, 6.2, 7.0, 8.4],
73
+ "M2": [2.1, 1.9, 3.0, 4.4, 4.4, 6.3, 8.0, 7.2],
74
+ "M3": [1.5, 3.3, 2.2, 5.6, 3.9, 5.6, 8.1, 6.6],
75
+ "M4": [4.0, 7.5, 1.0, 6.1, 2.8, 8.2, 3.3, 5.0],
76
+ "M5": [8.0, 7.1, 6.0, 5.2, 3.8, 3.1, 2.2, 1.0],
77
+ }, index=ref.index)
78
+ return X, ref
79
+
80
+
81
+ def calibration_merits(n_samples: int = 60, n_wavelengths: int = 40, alphas=None, n_splits: int = 10, random_state=0) -> pd.DataFrame:
82
+ """Merits of ridge-regression calibration models along the ridge path (rows = merits, columns = models).
83
+
84
+ Simulated spectra: three Gaussian bands whose intensities depend on the
85
+ concentration plus an interferent and noise. For every ridge parameter the
86
+ function computes RMSEC, RMSECV (``n_splits`` random 2/3-1/3 splits, one row per
87
+ split), ``1 - R^2`` of calibration and of cross-validation, the L2 norm of the
88
+ regression vector and its jaggedness (sum of squared second differences). All
89
+ merits are to be minimized.
90
+ """
91
+ rng = as_rng(random_state)
92
+ wl = np.linspace(0, 1, n_wavelengths)
93
+ bands = np.vstack([np.exp(-((wl - c) / 0.08) ** 2) for c in (0.25, 0.5, 0.75)])
94
+ y = rng.uniform(0, 10, n_samples)
95
+ interf = rng.uniform(0, 5, n_samples)
96
+ S = np.outer(y, bands[0] + 0.5 * bands[1]) + np.outer(interf, bands[1] + bands[2]) + rng.normal(0, 0.3, (n_samples, n_wavelengths))
97
+ alphas = np.logspace(-4, 3, 15) if alphas is None else np.asarray(alphas, float)
98
+
99
+ def fit(A, b, lam):
100
+ mu_a, mu_b = A.mean(axis=0), b.mean()
101
+ Ac = A - mu_a
102
+ coef = np.linalg.solve(Ac.T @ Ac + lam * np.eye(A.shape[1]), Ac.T @ (b - mu_b))
103
+ return coef, mu_b - mu_a @ coef
104
+
105
+ cols = {}
106
+ splits = [rng.permutation(n_samples) for _ in range(n_splits)]
107
+ for lam in alphas:
108
+ coef, b0 = fit(S, y, lam)
109
+ pred = S @ coef + b0
110
+ rmsec = np.sqrt(np.mean((pred - y) ** 2))
111
+ r2c = 1 - np.sum((pred - y) ** 2) / np.sum((y - y.mean()) ** 2)
112
+ merits = {"RMSEC": rmsec, "1-R2cal": 1 - r2c, "norm(b)": np.linalg.norm(coef),
113
+ "jaggedness": float(np.sum(np.diff(coef, 2) ** 2))}
114
+ press, ss = 0.0, 0.0
115
+ for k, perm in enumerate(splits):
116
+ tr, te = perm[: 2 * n_samples // 3], perm[2 * n_samples // 3:]
117
+ c, b = fit(S[tr], y[tr], lam)
118
+ e = S[te] @ c + b - y[te]
119
+ merits[f"RMSECV{k + 1}"] = float(np.sqrt(np.mean(e ** 2)))
120
+ press += float(np.sum(e ** 2))
121
+ ss += float(np.sum((y[te] - y[tr].mean()) ** 2))
122
+ merits["1-R2cv"] = press / ss
123
+ cols[f"ridge {lam:.2g}"] = merits
124
+ return pd.DataFrame(cols)
125
+
126
+
127
+ def outlier_measures(n_samples: int = 40, n_features: int = 10, n_outliers: int = 4, random_state=0) -> tuple[pd.DataFrame, list]:
128
+ """Outlier measures (rows) of simulated samples (columns) with planted outliers.
129
+
130
+ Measures: Hotelling's T^2 and Q residuals of PCA models with 2, 3 and 4
131
+ components, Mahalanobis distance, distance to the median and the k-nearest
132
+ neighbour distance (k = 3, 5). Returns the measure table and the names of the
133
+ planted outliers.
134
+ """
135
+ rng = as_rng(random_state)
136
+ L = rng.normal(size=(3, n_features))
137
+ Z = rng.normal(size=(n_samples, 3)) @ L + rng.normal(0, 0.3, (n_samples, n_features))
138
+ idx = rng.choice(n_samples, n_outliers, replace=False)
139
+ Z[idx] += rng.normal(0, 2.5, (n_outliers, n_features))
140
+ names = [f"s{i + 1}" for i in range(n_samples)]
141
+ Zc = Z - Z.mean(axis=0)
142
+ u, s, vt = np.linalg.svd(Zc, full_matrices=False)
143
+ rows = {}
144
+ for k in (2, 3, 4):
145
+ T = u[:, :k] * s[:k]
146
+ rows[f"T2(k={k})"] = (T ** 2 / (s[:k] ** 2 / (n_samples - 1))).sum(axis=1)
147
+ rows[f"Q(k={k})"] = ((Zc - T @ vt[:k]) ** 2).sum(axis=1)
148
+ C = np.cov(Z, rowvar=False)
149
+ rows["Mahalanobis"] = np.einsum("ij,jk,ik->i", Zc, np.linalg.pinv(C), Zc)
150
+ rows["median distance"] = np.linalg.norm(Z - np.median(Z, axis=0), axis=1)
151
+ D = np.linalg.norm(Z[:, None] - Z[None], axis=2)
152
+ Ds = np.sort(D, axis=1)
153
+ for k in (3, 5):
154
+ rows[f"kNN(k={k})"] = Ds[:, k]
155
+ M = pd.DataFrame(rows, index=names).T
156
+ return M, [names[i] for i in sorted(idx)]
157
+
158
+
159
+ __all__ = ["load_co2", "small_example", "calibration_merits", "outlier_measures", "make_method_comparison",
160
+ "make_ranking_sequence", "make_decision_problem", "mallows", "SECTORS"]