6"""Use human judgments about the most and least similar pair of three behaviors."""
9from dataclasses
import dataclass
10from functools
import partial
11from operator
import index
15from scipy.special
import expit
17from .qdhf
import QDHFResult, TripletProjector, _feedback_search
19__all__ = [
"DivHFJudgment",
"DivHFProjector",
"DivHFResult",
"divhf_search"]
21_TRIPLET_PAIRS = ((0, 1), (0, 2), (1, 2))
26 """Train on anchor, near, far index triples using log likelihood.
28 Two distinct pairs in a triplet share one anchor. Similarity is
29 negative squared Euclidean distance in the projected coordinates.
30 A small weight penalty regularizes otherwise separable comparisons.
32 :param raw_feature_size: Input width.
33 :param descriptor_size: Learned coordinate width.
34 :param temperature: Positive divisor for the difference in similarities.
35 :param regularization: Nonnegative squared-weight penalty.
36 :param seed: Initial projection seed.
39 def __init__(self, raw_feature_size, descriptor_size, *, temperature=.1, regularization=1e-3, seed=0):
40 super().__init__(raw_feature_size, descriptor_size, seed=seed)
41 if not 0 < temperature < np.inf
or not 0 <= regularization < np.inf:
42 raise ValueError(
"Specify finite, positive temperature and nonnegative regularization.")
45 def fit(self, raw_features, triplets, *, steps=128, batch_size=32, learning_rate=.01, seed=0):
46 """Fit probabilities for anchor, closer, farther labels by minimizing cross-entropy."""
47 return super().
fit(raw_features, triplets, steps=steps, batch_size=batch_size,
48 learning_rate=learning_rate, seed=seed)
50 def _loss_gradient(self, dp, dn, zp, zn, weights):
51 diff = (np.sum(zp ** 2, axis=1) - np.sum(zn ** 2, axis=1)) / self.
temperature
52 weight = expit(diff)[:,
None]
53 likelihood = 2. / len(dp) * (dp.T @ (weight * zp) - dn.T @ (weight * zn)) / self.
temperature
58@dataclass(frozen=True)
60 """Use pair indices 0 for (0,1), 1 for (0,2), and 2 for (1,2)."""
62 attempts: tuple[int, int, int]
63 pairs: tuple[int, int] |
None
67@dataclass(frozen=True)
69 """Each query stores the original pair ranking or an abstention."""
71 projector: DivHFProjector
72 feedback: tuple[DivHFJudgment, ...]
75def _anchored(rows, pairs):
76 first, second = map(_TRIPLET_PAIRS.__getitem__, pairs)
77 anchor = next(slot
for slot
in first
if slot
in second)
78 return rows[anchor], rows[sum(first) - anchor], rows[sum(second) - anchor]
81def _refit_pairs(projector, trials, feedback, log, requests, rng, fit_steps):
82 if len(trials) < 3
or requests == 0:
85 for _
in range(requests):
86 rows = tuple(map(int, rng.choice(len(trials), size=3, replace=
False)))
87 pairs = feedback(*(trials[i]
for i
in rows))
89 pairs = tuple(map(index, pairs))
90 if len(pairs) != 2
or len(set(pairs)) != 2
or any(pair
not in range(3)
for pair
in pairs):
91 raise ValueError(
"Return distinct closest and farthest pair indices in [0, 2], or None.")
92 labels.append(_anchored(rows, pairs))
93 log.append(
DivHFJudgment(tuple(trials[i].attempt
for i
in rows), pairs))
97 return copy(projector).fit([row.raw_features
for row
in trials], labels,
98 steps=fit_steps, seed=int(rng.integers(2**32)))
99 except FloatingPointError
as error:
100 warnings.warn(f
"Skipped DivHF projection update: {error}", stacklevel=3)
121def divhf_search(evaluate, archive, *, feedback, budget, feedback_budget, dimension,
122 raw_feature_size, ind_domain=(0., 1.), warmup=64, refit_every=
None,
123 feedback_batch=24, fit_steps=128, temperature=.1, regularization=1e-3, seed=0):
124 """Compare the two labeled extremes and fit a probabilistic projection.
126 For example, (1, 0) says records 0 and 2 are closest and records 0
127 and 1 are farthest apart. A skipped query still consumes one
128 annotation. Reuse QDHF's cached archive rebuild when refitting.
130 projector = partial(DivHFProjector, temperature=temperature, regularization=regularization)
131 return _feedback_search(evaluate, archive, feedback=feedback, budget=budget, feedback_budget=feedback_budget,
132 dimension=dimension, raw_feature_size=raw_feature_size, ind_domain=ind_domain,
133 warmup=warmup, refit_every=refit_every, feedback_batch=feedback_batch,
134 fit_steps=fit_steps, seed=seed, make_projector=projector, refit=_refit_pairs,
135 result_type=DivHFResult)
Ordered query IDs and the indices of the closest and farthest pairs.
Fit a linear descriptor with Bradley-Terry preference likelihoods.
fit(self, raw_features, triplets, *, steps=128, batch_size=32, learning_rate=.01, seed=0)
Learned archive, projection, evaluator costs, and query log.
Final QDHF search state and independent evaluation and annotation counts.
Learn a linear map using a squared-Euclidean triplet margin.