Note
Go to the end to download the full example code or to run this example in your browser via Binder.
Learning a utility from comparisons#
Every answer of every protocol becomes weighted pairwise preferences, and a preference model turns them into a latent utility over the search space. The package offers a linear Bradley–Terry model (Bradley and Terry, 1952) with a Laplace posterior, a kernelized one on random Fourier features (Rahimi and Recht, 2007), and Gaussian-process preference learning with the probit likelihood (Chu and Ghahramani, 2005). For merging the answers of several evaluators it offers Borda, Copeland, Kemeny, Bradley–Terry (Hunter’s MM algorithm, 2004) and Elo aggregation, and Kendall’s count of cyclic triads to detect intransitive judges.
Three models, one set of answers#
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import spearmanr
import easyiec as ei
from easyiec.preference import GPPreference, KernelBT, LinearBT, aggregate_rankings, bt_scores, cyclic_triads, elo
from easyiec.problems import SyntheticPreference
from easyiec.validation import kendall_tau, make_individuals
problem = SyntheticPreference(dim=2, kind="multimodal", seed=4)
user = ei.SimulatedUser(problem, target="random", noise=0.05, seed=8)
rng = np.random.default_rng(0)
items = make_individuals(problem.random(rng, 60))
X = np.array([problem.space.normalize(it.genome) for it in items])
def comparisons(n, rng):
out = []
for _ in range(n):
i, j = rng.choice(len(items), 2, replace=False)
o = user.evaluate(ei.Query("pairs", [items[i], items[j]])).pair_results[0][2]
if o != 0.5:
out.append((i, j, 1.0) if o > 0.5 else (j, i, 1.0))
return out
pairs = comparisons(120, rng)
models = {"linear BT": LinearBT(), "kernel BT (RFF)": KernelBT(lengthscale=0.2), "GP preference": GPPreference()}
for m in models.values():
m.fit(X, pairs)
g = np.linspace(0, 1, 60)
A, B = np.meshgrid(g, g)
Z = np.c_[A.ravel(), B.ravel()]
truth = np.array([user.true_utility(problem.space.denormalize(z)) for z in Z])
fig, axes = plt.subplots(1, 4, figsize=(13, 3.1))
axes[0].contourf(A, B, truth.reshape(A.shape), levels=20, cmap="viridis")
axes[0].scatter(X[:, 0], X[:, 1], s=6, color="white")
axes[0].set_title("hidden utility and the 60 items", fontsize=9)
for ax, (name, m) in zip(axes[1:], models.items()):
mu, _ = m.predict(Z)
ax.contourf(A, B, mu.reshape(A.shape), levels=20, cmap="viridis")
ax.set_title(f"{name} (ρ = {spearmanr(mu, truth).statistic:.2f})", fontsize=9)
for ax in axes:
ax.set_xticks([]), ax.set_yticks([])

How many comparisons are needed?#
Spearman correlation between learned and hidden utility on the grid, mean of five repetitions.
ns = [10, 20, 40, 80, 160]
fig, ax = plt.subplots(figsize=(6.4, 3.3))
for k, (name, factory) in enumerate({"linear BT": LinearBT, "kernel BT (RFF)": lambda: KernelBT(lengthscale=0.2),
"GP preference": GPPreference}.items()):
rho = []
for n in ns:
r = []
for rep in range(5):
m = factory().fit(X, comparisons(n, np.random.default_rng(rep)))
r.append(spearmanr(m.predict(Z)[0], truth).statistic)
rho.append(np.mean(r))
ax.plot(ns, rho, "o-", lw=2, label=name, color=["#285780", "#009E73", "#D55E00"][k])
ax.set_xscale("log")
ax.set_xlabel("number of comparisons", fontsize=8)
ax.set_ylabel("Spearman ρ with the hidden utility", fontsize=8)
ax.legend(frameon=False, fontsize=8)

<matplotlib.legend.Legend object at 0x7c275f2f2390>
Merging the rankings of a panel#
Seven simulated members rank the same eight items; the consensus rankings are compared with the order of the group’s mean utility (Kendall τ).
from easyiec.evaluators import make_crowd # noqa: E402
crowd = make_crowd(problem, n=7, spread=0.2, seed=2, noise=0.05)
eight = items[:8]
ids = [it.id for it in eight]
rankings = [m.evaluate(ei.Query("rank", eight)).ranking for m in crowd]
group = {it.id: np.mean([m.true_utility(it.genome) for m in crowd]) for it in eight}
true_order = sorted(ids, key=lambda i: -group[i])
pooled = [(r[a], r[b], 1.0) for r in rankings for a in range(8) for b in range(a + 1, 8)]
consensus = {meth: aggregate_rankings(rankings, ids, meth) for meth in ["borda", "copeland", "kemeny"]}
bt = bt_scores(pooled, ids)
consensus["Bradley–Terry"] = sorted(ids, key=lambda i: -bt[i])
el = elo(pooled, ids)
consensus["Elo"] = sorted(ids, key=lambda i: -el[i])
for meth, order in consensus.items():
print(f"{meth:14s} τ = {kendall_tau(order, true_order):.2f}")
n_cyc, zeta = cyclic_triads(pooled, ids)
print(f"pooled answers: {n_cyc} cyclic triads, Kendall's ζ = {zeta:.2f}")
fig, ax = plt.subplots(figsize=(6.4, 2.8))
ax.bar(list(consensus), [kendall_tau(o, true_order) for o in consensus.values()], color="#285780")
ax.set_ylim(0, 1)
ax.set_ylabel("Kendall τ with the group order", fontsize=8)
ax.tick_params(axis="x", labelsize=8)
plt.show()

borda τ = 0.64
copeland τ = 0.57
kemeny τ = 0.57
Bradley–Terry τ = 0.64
Elo τ = 0.57
pooled answers: 0 cyclic triads, Kendall's ζ = 1.00
Total running time of the script: (0 minutes 6.148 seconds)