23 scaled = np.divide(points, scale, out=np.zeros_like(points), where=scale > 0.)
25 return np.divide(scaled, norms, out=np.zeros_like(scaled), where=norms > 0.)
28def _cosine_projection(predictions, targets, alpha, dimensions):
39 _, singular, directions = np.linalg.svd(references - center, full_matrices=
False)
43 return np.pad(projected, ((0, 0), (0, dimensions - projected.shape[1])))
58 """Implement the semantic search of Zhang et al. with caller-defined model encodings.
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.
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.
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")
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,))
102 """Return the native Grid from the most recent fit. Its geometry can change at a rebuild."""
107 """Return model evaluation and archive rebuild counts."""
121 previous = [(tuple(row), row.fitness.values[0], row.scores[
"predictions"])
for row
in self.
_archive]
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])
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):
134 row.scores[
"predictions"] = semantic
145 def run(self, evaluate, budget):
146 """Retain any incomplete batch so a later call continues the same trajectory."""
147 budget = _attempt_budget(budget)
150 for _
in range(budget):
153 result = evaluate(genome, int(self.
_evaluation.integers(2**32)))
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))
172 """Keep held-out predictions outside the evolution loop."""
174 raise RuntimeError(
"Fit at least one nonempty model batch before predicting.")
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)