QDpy
Loading...
Searching...
No Matches
cosine_elites.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Rebuild an elite map in a prediction space fitted to symmetric reference points."""
7
8from dataclasses import dataclass
9from math import isfinite
10
11import numpy as np
12
13from qdpy.containers import Grid
14from qdpy.phenotype import Features, Fitness, Individual
15from ._population import _attempt_budget, _finite_vector
16from .modern import _positive_int
17
18__all__ = ["CosineMAPElites", "CosineElitesStats"]
19
20
21def _unit_rows(points):
22 scale = np.max(np.abs(points), axis=1, keepdims=True)
23 scaled = np.divide(points, scale, out=np.zeros_like(points), where=scale > 0.)
24 norms = np.linalg.norm(scaled, axis=1, keepdims=True)
25 return np.divide(scaled, norms, out=np.zeros_like(scaled), where=norms > 0.)
26
27
28def _cosine_projection(predictions, targets, alpha, dimensions):
29 with np.errstate(over="ignore", invalid="ignore"):
30 toward = (1. - alpha) * targets + alpha * predictions
31 reflected = (1. + alpha) * targets - alpha * predictions
32 references = np.vstack((toward, reflected))
33 if not np.isfinite(references).all():
34 raise ValueError("Reference predictions overflowed. Rescale the training targets.")
35 references = _unit_rows(references)
36 center = references.mean(axis=0)
37 # The cosine kernel is the linear kernel on unit rows. Thin SVD
38 # avoids the centered reference-by-reference Gram matrix.
39 _, singular, directions = np.linalg.svd(references - center, full_matrices=False)
40 tolerance = np.finfo(float).eps * max(references.shape) * max(1., singular[0])
41 selected = directions[:min(dimensions, np.count_nonzero(singular > tolerance))]
42 projected = (_unit_rows(predictions) - center) @ selected.T
43 return np.pad(projected, ((0, 0), (0, dimensions - projected.shape[1])))
44
45
46
47@dataclass(frozen=True)
49 """Count attempted fits, failed evaluations, and completed archive projections."""
50
51 evaluations: int
52 failures: int
53 rebuilds: int
54
55
56
58 """Implement the semantic search of Zhang et al. with caller-defined model encodings.
59
60 Fit a cosine-kernel projection using symmetric reference predictions
61 around the target vector. Preserve the best fraction of offspring and
62 incumbents before rebuilding the archive in the new coordinates.
63 Evaluators should provide out-of-fold or other training-only
64 predictions. Use held-out observations only for final comparison.
65
66 :param targets: Supervised target vector in evaluator prediction order.
67 :param sample: Callable (rng) returning a model genome iterable.
68 :param mutate: Callable (genome, rng) returning an offspring genome.
69 :param crossover: Optional callable (genome, donor, rng) returning a recombinant genome.
70 :param crossover_probability: Probability of crossing before mutation when supplied.
71 :param shape: Number of cells along each projected axis.
72 :param population_size: Initial sample and offspring batch size.
73 :param alpha: Reference displacement along the target-to-prediction vector.
74 :param retain_fraction: Fraction of the merged pool considered for the new archive.
75 :param maximize: Compare larger fitness when True and smaller fitness otherwise.
76 :param seed: Seed for parent selection, variation, and model evaluation.
77 """
78
79 def __init__(self, targets, *, sample, mutate, crossover=None, crossover_probability=.5,
80 shape=(8, 8), population_size=32, alpha=.1, retain_fraction=.5, maximize=False, seed=0):
81 self._targets = np.asarray(_finite_vector(targets, "Training targets"))
82 self._shape = tuple(_positive_int(size, "shape") for size in shape)
83 if not self._shape or not 0 < alpha <= 1 or not 0 < retain_fraction <= 1 or not 0 <= crossover_probability <= 1:
84 raise ValueError("Use a nonempty shape, valid probabilities, and positive alpha and retain_fraction.")
85 if not callable(sample) or not callable(mutate) or (crossover is not None and not callable(crossover)):
86 raise TypeError("Provide callable variation functions.")
87 self._size = _positive_int(population_size, "population_size")
88 self._sample, self._mutate, self._crossover = sample, mutate, crossover
89 self._probability = crossover_probability
90 self._alpha, self._fraction, self._direction = alpha, retain_fraction, 1. if maximize else -1.
91 self._variation, self._evaluation = map(np.random.default_rng, np.random.SeedSequence(seed).spawn(2))
92 self._archive = self._grid(((-1., 1.),) * len(self._shape))
93 self._children = []
94 self._pending = self._evaluations = self._failures = self._rebuilds = 0
95
96 def _grid(self, bounds):
97 return Grid(shape=self._shape, features_domain=bounds,
98 fitness_domain=((-np.inf, np.inf),), fitness_weights=(self._direction,))
99
100 @property
101 def archive(self):
102 """Return the native Grid from the most recent fit. Its geometry can change at a rebuild."""
103 return self._archive
104
105 @property
106 def stats(self):
107 """Return model evaluation and archive rebuild counts."""
108 return CosineElitesStats(self._evaluations, self._failures, self._rebuilds)
109
110 def _genome(self):
111 if not self._archive:
112 return tuple(self._sample(self._variation))
113 parent = tuple(self._archive[int(self._variation.integers(len(self._archive)))])
114 if self._crossover is not None and self._variation.random() < self._probability:
115 donor = tuple(self._archive[int(self._variation.integers(len(self._archive)))])
116 parent = tuple(self._crossover(parent, donor, self._variation))
117 return tuple(self._mutate(parent, self._variation))
118
119 def _rebuild(self):
120 if self._children:
121 previous = [(tuple(row), row.fitness.values[0], row.scores["predictions"]) for row in self._archive]
122 pool = previous + self._children
123 if previous:
124 pool.sort(key=lambda row: -self._direction * row[1])
125 pool = pool[:max(1, int(len(pool) * self._fraction))]
126 predictions = np.asarray([row[2] for row in pool])
127 points = _cosine_projection(predictions, self._targets, self._alpha, len(self._shape))
128 bounds = [(float(lo), float(hi)) if hi - lo > np.finfo(float).eps else (-2., 2.)
129 for lo, hi in zip(points.min(axis=0), points.max(axis=0))]
130 archive = self._grid(bounds)
131 for (genome, fitness, semantic), point in zip(pool, points):
132 row = Individual(genome, fitness=Fitness((fitness,), weights=(self._direction,)),
133 features=Features(tuple(point)))
134 row.scores["predictions"] = semantic
135 archive.add(row)
136 self._archive = archive
137 self._rebuilds += 1
138 self._children.clear()
139 self._pending = 0
140
141
145 def run(self, evaluate, budget):
146 """Retain any incomplete batch so a later call continues the same trajectory."""
147 budget = _attempt_budget(budget)
148 if self._pending == self._size:
149 self._rebuild()
150 for _ in range(budget):
151 genome = self._genome()
152 self._evaluations += 1
153 result = evaluate(genome, int(self._evaluation.integers(2**32)))
154 if result is None:
155 self._failures += 1
156 else:
157 fitness, predictions = result
158 if not isfinite(fitness):
159 raise ValueError("Model fitness must be finite.")
160 semantic = _finite_vector(predictions, "Predictions", len(self._targets))
161 self._children.append((genome, float(fitness), semantic))
162 self._pending += 1
163 if self._pending == self._size:
164 self._rebuild()
165 return self.stats
166
167
171 def predict(self, predict, *, size=None):
172 """Keep held-out predictions outside the evolution loop."""
173 if not self._archive:
174 raise RuntimeError("Fit at least one nonempty model batch before predicting.")
175 members = tuple(self._archive)
176 if size is not None:
177 members = sorted(members, key=lambda row: -self._direction * row.fitness.values[0])
178 members = members[:_positive_int(size, "size")]
179 predictions = [_finite_vector(predict(tuple(row)), "Held-out predictions") for row in members]
180 if len({len(row) for row in predictions}) != 1:
181 raise ValueError("Every ensemble member must predict the same held-out observations.")
182 return np.sum(np.asarray(predictions) / len(members), axis=0)
Count model measurements and archive rebuilds.
Fit cosine-kernel PCA over symmetric prediction references and retain one elite per cell.
run(self, evaluate, budget)
Evaluate and project model batches on the fixed training panel.
predict(self, predict, *, size=None)
Average final elite predictions on a new dataset.
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405