QDpy
Loading...
Searching...
No Matches
qdhf.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Learn search descriptors from similarity judgments with known ground truth."""
6
7from argparse import ArgumentParser
8import json
9from time import perf_counter
10
11import numpy as np
12
13from qdpy.algorithms import qdhf_search
14from qdpy.containers import Grid
15from qdpy.phenotype import Features, Fitness, Individual
16
17
18def evaluate(genome):
19 """Return quality and raw behavior observations with four nuisance axes."""
20 raw = 2 * np.asarray(genome) - 1
21 quality = 5 - np.sum((raw[2:] - np.array([0.3, -0.1, 0.2, -0.5])) ** 2) / 2
22 return float(quality), raw
23
24
25def judge(anchor, first, second):
26 """Prefer the closer observation along the two ground-truth axes."""
27 center = np.asarray(anchor.raw_features[:2])
28 first_distance = np.sum((center - first.raw_features[:2]) ** 2)
29 second_distance = np.sum((center - second.raw_features[:2]) ** 2)
30 if first_distance == second_distance:
31 return None
32 return int(second_distance < first_distance)
33
34
35def grid(bounds):
36 """Create a grid for either learned descriptors or fixed evaluation."""
37 return Grid(shape=(8, 8), fitness_domain=((-1., 5.),), features_domain=(bounds, bounds),
38 max_items_per_bin=1, fitness_weights=(1.,))
39
40
41def accuracy(projector):
42 """Score the projection on a held-out set of 256 generated triplets."""
43 heldout = np.random.default_rng(927).uniform(-1, 1, size=(3, 256, 6))
44 projected = projector.transform(heldout.reshape(-1, 6)).reshape(3, 256, 2)
45
46 def preference(points):
47 anchor, first, second = points
48 return np.sum((anchor - first) ** 2, axis=1) < np.sum((anchor - second) ** 2, axis=1)
49
50 return float(np.mean(preference(heldout[:, :, :2]) == preference(projected)))
51
52
53def comparison(budget, feedback_budget, seed):
54 """Run both QDHF schedules and score their elites in ground-truth cells."""
55 for name, refit_every in [("qdhf", 112), ("qdhf-base", None)]:
56 start = perf_counter()
57 result = qdhf_search(evaluate, grid((-1.2, 1.2)), feedback=judge, budget=budget,
58 feedback_budget=feedback_budget, dimension=6, raw_feature_size=6,
59 refit_every=refit_every, seed=seed)
60 seconds = perf_counter() - start
61 reporting = grid((-1., 1.))
62 for elite in result.archive:
63 true_descriptor = (2 * elite[0] - 1, 2 * elite[1] - 1)
64 reporting.add(Individual(elite, fitness=Fitness(tuple(elite.fitness)),
65 features=Features(true_descriptor)))
66 yield dict(method=name, seed=seed, attempts=result.attempts, failures=result.failures,
67 labels=sum(label.choice is not None for label in result.feedback),
68 feedback_attempts=len(result.feedback), fits=result.fits,
69 learned_cells=result.archive.filled_bins, heldout_accuracy=accuracy(result.projector),
70 true_coverage=reporting.filled_bins / 64, qd_score=reporting.qd_score(normalized=False),
71 seconds=seconds)
72
73
74if __name__ == "__main__":
75 parser = ArgumentParser(description=__doc__)
76 parser.add_argument("--budget", type=int, default=512)
77 parser.add_argument("--feedback-budget", type=int, default=96)
78 parser.add_argument("--seeds", type=int, nargs="+", default=[11, 29, 47])
79 args = parser.parse_args()
80 for seed in args.seeds:
81 for row in comparison(args.budget, args.feedback_budget, seed):
82 print(json.dumps(row, sort_keys=True, allow_nan=False))