QDpy
Loading...
Searching...
No Matches
ensemble_selection.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Select weighted classification ensembles from cached probabilities."""
7
8from collections import Counter, deque
9from collections.abc import Mapping
10from dataclasses import dataclass
11from itertools import combinations
12from numbers import Real
13
14import numpy as np
15
16from qdpy.containers import SlidingBoundariesGrid
17from qdpy.phenotype import Features, Fitness, Individual
18from .modern import _positive_int
19
20__all__ = ["QDOES", "EnsembleSelectionResult"]
21
22
23def _probabilities(values):
24 values = np.asarray(values, dtype=float)
25 if (values.ndim != 3 or min(values.shape) == 0 or values.shape[-1] < 2
26 or not np.isfinite(values).all() or np.any((values < 0) | (values > 1))
27 or not np.allclose(values.sum(axis=-1), 1.)):
28 raise ValueError("Use an array of class probabilities shaped (models, samples, classes).")
29 return values
30
31
32def _gower(configs):
33 keys = set().union(*(config.keys() for config in configs))
34 columns = []
35 for key in sorted(keys, key=str):
36 values = [config.get(key) for config in configs]
37 present = [value for value in values if value is not None]
38 numeric = all(isinstance(value, Real) and not isinstance(value, (bool, np.bool_)) for value in present)
39 if numeric and present and not np.isfinite(np.asarray(present, dtype=float)).all():
40 raise ValueError("Numeric model configuration values must be finite.")
41 span = float(max(present)) - float(min(present)) if numeric and present else 0.
42 if not np.isfinite(span):
43 raise ValueError("Numeric model configuration ranges must be finite.")
44 columns.append((values, numeric, span))
45 distances = np.zeros((len(configs), len(configs)))
46 for i, j in combinations(range(len(configs)), 2):
47 terms = []
48 for values, numeric, span in columns:
49 left, right = values[i], values[j]
50 if left is None or right is None:
51 continue
52 terms.append(abs(float(left) - float(right)) / span if span else float(left != right))
53 distances[i, j] = distances[j, i] = np.mean(terms) if terms else 0.
54 return distances
55
56
57
58@dataclass(frozen=True)
60 """Store the best repetition vector and loss after the requested search."""
61
62 counts: tuple[int, ...]
63 validation_loss: float
64 evaluations: int
65 archive: SlidingBoundariesGrid | None
66
67 @property
68 def weights(self):
69 """Return a probability vector over the original base models."""
70 return np.asarray(self.counts, dtype=float) / sum(self.counts)
71
72
73 def predict_proba(self, probabilities):
74 """Ensemble probabilities for any number of new observations."""
75 probabilities = _probabilities(probabilities)
76 if len(probabilities) != len(self.counts):
77 raise ValueError("Supply predictions from the same base models in the original order.")
78 return np.einsum("m,mnc->nc", self.weights, probabilities)
79
80
82 def __init__(self, minimum):
83 self._history = deque(maxlen=10)
84 self._minimum = minimum
85 self.probability = .5
86
87 def update(self, outcomes):
88 self._history.append(tuple(outcomes))
89 groups = [[loss for batch in self._history for used, loss in batch if used == decision]
90 for decision in (True, False)]
91 if min(map(len, groups)) >= 2:
92 first, second = map(np.mean, groups)
93 scale = max(first, second)
94 if scale:
95 ratio = (second / scale) / (first / scale + second / scale)
96 self.probability = float(np.clip(ratio, self._minimum, 1. - self._minimum))
97
98
99
100class QDOES:
101 """Run QDO-ES, quality-only QO-ES, or greedy selection on fixed predictions.
102
103 :param probabilities: Validation predictions shaped (models, samples, classes).
104 :param labels: Integer validation labels indexing the probability tensor.
105 :param configurations: One hyperparameter mapping per base model.
106 Numeric keys use relative distances. Categorical keys use equality.
107 Missing keys are skipped in pairwise distances.
108 :param loss: Optional callable (labels, probabilities) returning finite nonnegative loss.
109 Defaults to mean multiclass log loss.
110 :param bins: Sliding archive bins per axis, also setting QO-ES population capacity.
111 :param batch_size: Offspring per population update.
112 :param remap_frequency: Valid offers between sliding-boundary updates.
113 :param crossover: "average", "two_point", or "none".
114 :param seed: Private RNG seed for parent selection, variation, and ties.
115 """
116
117 def __init__(self, probabilities, labels, *, configurations=None, loss=None, bins=7,
118 batch_size=20, remap_frequency=100, crossover="average", seed=0):
119 self._probabilities = _probabilities(probabilities).copy()
120 models, examples, classes = self._probabilities.shape
121 self._labels = np.asarray(labels).copy()
122 if (self._labels.shape != (examples,) or self._labels.dtype.kind not in "iu"
123 or np.any(self._labels < 0) or np.any(self._labels >= classes)):
124 raise ValueError("Labels must be a vector of valid integer class indices.")
125 if configurations is None:
126 configurations = [{} for _ in range(models)]
127 configurations = tuple(configurations)
128 if (len(configurations) != models or any(not isinstance(config, Mapping) for config in configurations)
129 or any(value is not None and not isinstance(value, (str, Real, np.bool_))
130 for config in configurations for value in config.values())):
131 raise ValueError("Supply one scalar-valued configuration mapping per model.")
132 self._distances = _gower(configurations)
133 losses = 1. - self._probabilities[:, np.arange(examples), self._labels]
134 centered = losses - losses.mean(axis=1, keepdims=True)
135 centered[np.ptp(losses, axis=1) == 0.] = 0.
136 norms = np.linalg.norm(centered, axis=1, keepdims=True)
137 normalized = np.divide(centered, norms, where=norms > 0, out=np.zeros_like(centered))
138 self._correlations = np.clip(normalized @ normalized.T, -1., 1.)
139 if crossover not in ("average", "two_point", "none"):
140 raise ValueError("crossover must be average, two_point, or none.")
141 if loss is not None and not callable(loss):
142 raise TypeError("loss must be callable.")
143 self._loss, self.crossover, self.seed = loss, crossover, seed
144 self.bins = _positive_int(bins, "bins")
145 self.batch_size = _positive_int(batch_size, "batch_size")
146 self.remap_frequency = _positive_int(remap_frequency, "remap_frequency")
147
148 def _evaluate(self, counts):
149 probabilities = np.einsum("m,mnc->nc", counts / counts.sum(), self._probabilities)
150 loss = (self._loss(self._labels.copy(), probabilities) if self._loss is not None else
151 -np.log(np.clip(probabilities[np.arange(len(self._labels)), self._labels],
152 np.finfo(float).tiny, 1.)).mean())
153 if not 0 <= loss < np.inf:
154 raise ValueError("Ensemble loss must be finite and nonnegative.")
155 return float(loss)
156
157
158 def descriptors(self, counts):
159 """Ignore multiplicities and define singleton and constant-vector terms as zero."""
160 counts = np.asarray(counts)
161 if (counts.shape != (len(self._probabilities),) or counts.dtype.kind not in "iu"
162 or np.any(counts < 0) or not np.any(counts)):
163 raise ValueError("Supply one nonnegative integer count per model and at least one inclusion.")
164 active = np.flatnonzero(counts)
165 if len(active) == 1:
166 return 0., 0.
167 i, j = np.triu_indices(len(active), k=1)
168 rows, cols = active[i], active[j]
169 return float(self._correlations[rows, cols].mean()), float(self._distances[rows, cols].mean())
170
171 def _cross(self, first, second, rng):
172 active = np.flatnonzero((first != 0) | (second != 0))
173 if self.crossover == "two_point" and len(active) >= 3:
174 left, right = sorted(rng.choice(len(active) + 1, size=2, replace=False))
175 child = first.copy()
176 child[active[left:right]] = second[active[left:right]]
177 if np.any(child):
178 return child
179 return (first + second + 1) // 2
180
181
185 def fit(self, budget, *, mode="qdo"):
186 """Fit using validation predictions only. Evaluate test predictions separately."""
187 budget = _positive_int(budget, "budget")
188 if mode not in ("qdo", "quality", "greedy"):
189 raise ValueError("mode must be qdo, quality, or greedy.")
190 models = len(self._probabilities)
191 archive = (SlidingBoundariesGrid(shape=(self.bins,) * 2, features_domain=((-1., 1.), (0., 1.)),
192 fitness_domain=((0., np.inf),), fitness_weights=(-1.,),
193 remap_frequency=self.remap_frequency)
194 if mode == "qdo" else None)
195 rng = np.random.default_rng(self.seed)
196 best_counts, best_loss = None, np.inf
197 calls = 0
198 quality = {}
199
200 def score(counts):
201 nonlocal best_counts, best_loss, calls
202 loss = self._evaluate(counts)
203 calls += 1
204 if loss < best_loss:
205 best_counts, best_loss = tuple(map(int, counts)), loss
206 return loss
207
208 if mode == "greedy":
209 parent = np.zeros(models, dtype=int)
210 while calls < budget:
211 trials = []
212 for i in rng.permutation(models)[:budget - calls]:
213 child = parent.copy()
214 child[i] += 1
215 trials.append((score(child), child))
216 _, parent = min(trials, key=lambda trial: trial[0])
217 return EnsembleSelectionResult(best_counts, best_loss, calls, None)
218
219 def offer(counts, loss):
220 if archive is not None:
221 archive.add(Individual(counts.tolist(), fitness=Fitness((loss,), weights=(-1.,)),
222 features=Features(self.descriptors(counts))))
223 else:
224 quality[tuple(counts)] = loss
225 if len(quality) > self.bins ** 2:
226 del quality[max(quality, key=quality.get)]
227
228 for i in rng.permutation(models)[:budget]:
229 counts = np.zeros(models, dtype=int)
230 counts[i] = 1
231 offer(counts, score(counts))
232
233 sampling, crossover, post_mutation = (_AdaptiveChoice(.05), _AdaptiveChoice(.1), _AdaptiveChoice(.1))
234 expanded = {}
235 while calls < budget:
236 pool = ([(tuple(ind), ind.fitness.values[0]) for ind in archive]
237 if archive is not None else list(quality.items()))
238 ordered = [counts for counts, _ in sorted(pool, key=lambda pair: pair[1])]
239 batch, history = [], [[], [], []]
240 for _ in range(min(self.batch_size, budget - calls)):
241 random_parent = bool(rng.random() < sampling.probability)
242 use_cross = self.crossover != "none" and len(ordered) > 1 and rng.random() < crossover.probability
243 count = 2 if use_cross else 1
244 indices = rng.choice(len(ordered), count, replace=False) if random_parent else range(count)
245 parents = [np.asarray(ordered[i]) for i in indices]
246 child = self._cross(*parents, rng) if use_cross else parents[0].copy()
247 mutate = bool(use_cross and rng.random() < post_mutation.probability)
248 if not use_cross or mutate:
249 tried = expanded.setdefault(tuple(child), Counter())
250 least = min(tried[i] for i in range(models))
251 available = [i for i in range(models) if tried[i] == least]
252 i = int(rng.choice(available))
253 tried[i] += 1
254 child[i] += 1
255 loss = score(child)
256 batch.append((child, loss))
257 history[0].append((random_parent, loss))
258 history[1].append((use_cross, loss))
259 if use_cross:
260 history[2].append((mutate, loss))
261 for counts, loss in batch:
262 offer(counts, loss)
263 for choice, outcomes in zip((sampling, crossover, post_mutation), history):
264 choice.update(outcomes)
265 return EnsembleSelectionResult(best_counts, best_loss, calls, archive)
Ensemble weights, optimization loss, and optional sliding archive.
predict_proba(self, probabilities)
Combine probabilities in the same model order and class order as fitting.
Optimize ensembles in loss-correlation and configuration-distance space.
fit(self, budget, *, mode="qdo")
Run a seeded search with an exact count of validation loss calls.
descriptors(self, counts)
Compute average loss correlation and Gower distance for included models.
Repartition recent descriptor observations into approximately equal-mass bins.
Definition sliding.py:26
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405