.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/03_evaluators/plot_06_preference_models.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code or to run this example in your browser via Binder. .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_examples_03_evaluators_plot_06_preference_models.py: 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. .. GENERATED FROM PYTHON SOURCE LINES 17-19 Three models, one set of answers -------------------------------- .. GENERATED FROM PYTHON SOURCE LINES 19-62 .. code-block:: Python 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([]) .. image-sg:: /auto_examples/03_evaluators/images/sphx_glr_plot_06_preference_models_001.png :alt: hidden utility and the 60 items, linear BT (ρ = 0.51), kernel BT (RFF) (ρ = 0.92), GP preference (ρ = 0.86) :srcset: /auto_examples/03_evaluators/images/sphx_glr_plot_06_preference_models_001.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 63-67 How many comparisons are needed? -------------------------------- Spearman correlation between learned and hidden utility on the grid, mean of five repetitions. .. GENERATED FROM PYTHON SOURCE LINES 67-84 .. code-block:: Python 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) .. image-sg:: /auto_examples/03_evaluators/images/sphx_glr_plot_06_preference_models_002.png :alt: plot 06 preference models :srcset: /auto_examples/03_evaluators/images/sphx_glr_plot_06_preference_models_002.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none .. GENERATED FROM PYTHON SOURCE LINES 85-89 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 τ). .. GENERATED FROM PYTHON SOURCE LINES 89-113 .. code-block:: Python 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() .. image-sg:: /auto_examples/03_evaluators/images/sphx_glr_plot_06_preference_models_003.png :alt: plot 06 preference models :srcset: /auto_examples/03_evaluators/images/sphx_glr_plot_06_preference_models_003.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none 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 .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 6.148 seconds) .. _sphx_glr_download_auto_examples_03_evaluators_plot_06_preference_models.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: binder-badge .. image:: images/binder_badge_logo.svg :target: https://mybinder.org/v2/gh/ComplexSystemsIntelligence/easyiec/main?urlpath=lab/tree/notebooks/auto_examples/03_evaluators/plot_06_preference_models.ipynb :alt: Launch binder :width: 150 px .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_06_preference_models.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_06_preference_models.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_06_preference_models.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_