QDpy
Loading...
Searching...
No Matches
preference.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Learn MAP-Elites parent probabilities from displayed archive choices."""
7
8from collections import Counter, deque
9
10import numpy as np
11from scipy.special import softmax
12from sklearn.linear_model import Ridge
13
14from qdpy.base import registry
15from qdpy.containers import CVTGrid, Grid
16from qdpy.tools import iso_line_dd
17from .constrained import _check_measurements
18from .modern import _FixedGeneration, _positive_int, _variation_settings
19
20__all__ = ["PreferenceLearningMAPElites"]
21
22
23
24@registry.register
26 """Illuminate a design space between feedback rounds.
27
28 Call record_feedback() with occupied cells chosen from the current
29 display. Ridge regression estimates the likelihood of a selection
30 from the descriptors (or caller-supplied features). The tabular
31 alternative uses selection counts. Both models use softmax sampling
32 with a uniform exploration component. Fitness and the descriptors
33 that determine cell membership are supplied by the evaluator.
34
35 :param container: Fixed, parentless, best-only Grid or CVTGrid.
36 :param budget: Native managed evaluation budget.
37 :param dimension: Number of real coordinates in the candidate genome.
38 :param ind_domain: Shared finite lower and upper genome bounds.
39 :param mode: "ridge", "tabular", or "uniform" for a control.
40 :param feedback_window: Most recent rounds used for learning.
41 :param regularization: Positive ridge penalty.
42 :param temperature: Positive softmax temperature in model-score units.
43 :param exploration: Probability of a uniform draw in the automated emitter.
44 :param features: Optional function mapping an evaluated elite to a finite feature vector.
45 :param iso_sigma: Independent Iso+LineDD noise scale.
46 :param line_sigma: Iso+LineDD scale along the direction between sampled elites.
47 :param batch_size: Number of proposals per fixed generation.
48 :param seed: Private proposal seed.
49 :param kwargs: Native algorithm settings, including objective direction.
50 """
51
52 _requires_proposed_genome = True
53
54 def __init__(self, container, budget, dimension, ind_domain=(0., 1.), *,
55 mode="ridge", feedback_window=8, regularization=.1, temperature=.25,
56 exploration=.15, features=None, iso_sigma=.05, line_sigma=.2,
57 batch_size=8, seed=0, **kwargs):
58 if (type(container) not in (Grid, CVTGrid) or container.parents or container.max_items_per_bin != 1
59 or container.discard_random_on_bin_overload):
60 raise ValueError("Use a fixed parentless one-elite Grid or CVTGrid.")
61 bounds = np.asarray(container.features_domain, dtype=float)
62 if (bounds.ndim != 2 or bounds.shape[1] != 2 or not np.isfinite(bounds).all()
63 or not np.isfinite(bounds[:, 1] - bounds[:, 0]).all() or np.any(bounds[:, 1] < bounds[:, 0])):
64 raise ValueError("Use finite descriptor domains with finite spans.")
65 if (mode not in ("ridge", "tabular", "uniform")
66 or not 0 < regularization < np.inf or not 0 < temperature < np.inf
67 or not 0 <= exploration <= 1 or (features is not None and not callable(features))):
68 raise ValueError("Use a valid model, finite positive regularization and temperature, and exploration in [0, 1].")
69 self.ind_domain = _variation_settings(ind_domain, iso_sigma, line_sigma)
70 if not np.isfinite(self.ind_domain[1] - self.ind_domain[0]):
71 raise ValueError("Use a finite genome width.")
72 self.iso_sigma, self.line_sigma = iso_sigma, line_sigma
73 self._offset = bounds[:, 0]
74 self._span = np.where(bounds[:, 0] == bounds[:, 1], 1., bounds[:, 1] - bounds[:, 0])
75 self._features = features
76 self.mode, self.seed = mode, seed
77 self.feedback_window = _positive_int(feedback_window, "feedback_window")
78 self.regularization, self.temperature, self.exploration = regularization, temperature, exploration
79 if container.fitness_weights is not None:
80 kwargs.setdefault("optimisation_task", tuple(container.fitness_weights))
81 super().__init__(container, _positive_int(budget, "budget"),
82 dimension=_positive_int(dimension, "dimension"),
83 batch_size=_positive_int(batch_size, "batch_size"), **kwargs)
84 for elite in container:
85 self._validate_genome(elite)
86
87 def reinit(self):
88 """Reset feedback, the parent model, and native evaluation counters."""
89 super().reinit()
90 self._rng = np.random.default_rng(self.seed)
91 self._history = deque(maxlen=self.feedback_window)
92 self._rounds = 0
93 self._model, self._table = None, Counter()
94 self._batch_parents = ()
95
96 @property
97 def feedback_rounds(self):
98 """Return cumulative feedback rounds, including rounds with no selections."""
99 return self._rounds
100
101 def _occupied(self):
102 return {cell: entries[0] for cell, entries in self.container.solutions.items() if entries}
103
104 def _vector(self, elite):
105 vector = ((np.asarray(self.container.get_ind_features(elite)) - self._offset) / self._span
106 if self._features is None else np.asarray(self._features(elite), dtype=float))
107 if vector.ndim != 1 or not len(vector) or not np.isfinite(vector).all():
108 raise ValueError("Preference features must be a finite nonempty vector.")
109 return vector
110
111
114 def record_feedback(self, selected, *, displayed=None):
115 """Use selected cells as positives and other displayed cells as negatives."""
116 if self._pending_size:
117 raise RuntimeError("Record preference feedback between complete generations.")
118 occupied = self._occupied()
119 shown = tuple(occupied if displayed is None else map(tuple, displayed))
120 selected = frozenset(map(tuple, selected))
121 if (not shown or len(shown) != len(set(shown)) or any(cell not in occupied for cell in shown)
122 or not selected.issubset(shown)):
123 raise ValueError("Supply distinct occupied displayed cells and select only from that display.")
124 vectors = np.stack([self._vector(occupied[cell]) for cell in shown]) if self.mode == "ridge" else None
125 round_data = (selected, shown, vectors)
126 history = self._history.copy()
127 history.append(round_data)
128 if self.mode == "ridge":
129 x = np.concatenate([rows for _, _, rows in history])
130 y = [float(cell in chosen) for chosen, display, _ in history for cell in display]
131 self._model = Ridge(alpha=self.regularization).fit(x, y)
132 elif self.mode == "tabular":
133 self._table = Counter(cell for chosen, _, _ in history for cell in chosen)
134 self._history = history
135 self._rounds += 1
136
137 def _weights(self, occupied):
138 if self.mode == "ridge" and self._model is not None:
139 logits = self._model.predict(np.stack([self._vector(ind) for ind in occupied.values()]))
140 elif self.mode == "tabular":
141 logits = np.array([self._table[cell] for cell in occupied])
142 else:
143 logits = np.zeros(len(occupied))
144 # Center before dividing so that tiny tolerances leave the best score finite.
145 with np.errstate(over="ignore"):
146 weights = softmax((logits - logits.max()) / self.temperature)
147 return (1 - self.exploration) * weights + self.exploration / len(occupied)
148
149
151 """Return a mapping in native cell order. The empty archive returns an empty mapping."""
152 occupied = self._occupied()
153 return dict(zip(occupied, self._weights(occupied))) if occupied else {}
154
155 def _start_fixed_batch(self, size):
156 super()._start_fixed_batch(size)
157 occupied = self._occupied()
158 self._batch_parents = tuple(occupied.values())
159 self._batch_weights = self._weights(occupied) if occupied else None
160
161 def _internal_ask(self, base_ind):
162 if self._batch_parents:
163 first, second = self._rng.choice(len(self._batch_parents), size=2, p=self._batch_weights)
164 vector = iso_line_dd(self._batch_parents[first], self._batch_parents[second],
165 bounds=self.ind_domain, iso_sigma=self.iso_sigma, line_sigma=self.line_sigma,
166 rng=self._rng)
167 else:
168 vector = self._rng.uniform(*self.ind_domain, size=self.dimension)
169 base_ind[:] = list(vector)
170 return base_ind
171
172 def _validate_genome(self, genome):
173 vector = np.asarray(genome, dtype=float)
174 if (vector.shape != (self.dimension,) or not np.isfinite(vector).all()
175 or np.any(vector < self.ind_domain[0]) or np.any(vector > self.ind_domain[1])):
176 raise ValueError("Supply a finite genome of the configured size and interval.")
177
178 def _check_candidate(self, individual):
179 self._validate_genome(individual)
180 _check_measurements(self.container, individual)
Choose parents using recent user selections while retaining ordinary grid admission.
Definition preference.py:25
record_feedback(self, selected, *, displayed=None)
Record one display and its selected cells between generations.
parent_probabilities(self)
Inspect the automated parent probability of each currently occupied cell.