# SPDX-License-Identifier: LGPL-3.0-or-later ## @file # @brief Compare offline and online triplet supervision with a synthetic judge. """Learn search descriptors from similarity judgments with known ground truth.""" from argparse import ArgumentParser import json from time import perf_counter import numpy as np from qdpy.algorithms import qdhf_search from qdpy.containers import Grid from qdpy.phenotype import Features, Fitness, Individual def evaluate(genome): """Return quality and raw behavior observations with four nuisance axes.""" raw = 2 * np.asarray(genome) - 1 quality = 5 - np.sum((raw[2:] - np.array([0.3, -0.1, 0.2, -0.5])) ** 2) / 2 return float(quality), raw def judge(anchor, first, second): """Prefer the closer observation along the two ground-truth axes.""" center = np.asarray(anchor.raw_features[:2]) first_distance = np.sum((center - first.raw_features[:2]) ** 2) second_distance = np.sum((center - second.raw_features[:2]) ** 2) if first_distance == second_distance: return None return int(second_distance < first_distance) def grid(bounds): """Create a grid for either learned descriptors or fixed evaluation.""" return Grid(shape=(8, 8), fitness_domain=((-1., 5.),), features_domain=(bounds, bounds), max_items_per_bin=1, fitness_weights=(1.,)) def accuracy(projector): """Score the projection on a held-out set of 256 generated triplets.""" heldout = np.random.default_rng(927).uniform(-1, 1, size=(3, 256, 6)) projected = projector.transform(heldout.reshape(-1, 6)).reshape(3, 256, 2) def preference(points): anchor, first, second = points return np.sum((anchor - first) ** 2, axis=1) < np.sum((anchor - second) ** 2, axis=1) return float(np.mean(preference(heldout[:, :, :2]) == preference(projected))) def comparison(budget, feedback_budget, seed): """Run both QDHF schedules and score their elites in ground-truth cells.""" for name, refit_every in [("qdhf", 112), ("qdhf-base", None)]: start = perf_counter() result = qdhf_search(evaluate, grid((-1.2, 1.2)), feedback=judge, budget=budget, feedback_budget=feedback_budget, dimension=6, raw_feature_size=6, refit_every=refit_every, seed=seed) seconds = perf_counter() - start reporting = grid((-1., 1.)) for elite in result.archive: true_descriptor = (2 * elite[0] - 1, 2 * elite[1] - 1) reporting.add(Individual(elite, fitness=Fitness(tuple(elite.fitness)), features=Features(true_descriptor))) yield dict(method=name, seed=seed, attempts=result.attempts, failures=result.failures, labels=sum(label.choice is not None for label in result.feedback), feedback_attempts=len(result.feedback), fits=result.fits, learned_cells=result.archive.filled_bins, heldout_accuracy=accuracy(result.projector), true_coverage=reporting.filled_bins / 64, qd_score=reporting.qd_score(normalized=False), seconds=seconds) if __name__ == "__main__": parser = ArgumentParser(description=__doc__) parser.add_argument("--budget", type=int, default=512) parser.add_argument("--feedback-budget", type=int, default=96) parser.add_argument("--seeds", type=int, nargs="+", default=[11, 29, 47]) args = parser.parse_args() for seed in args.seeds: for row in comparison(args.budget, args.feedback_budget, seed): print(json.dumps(row, sort_keys=True, allow_nan=False))