Skip to content

Rankings as a sequence of choices: the Plackett–Luce model

A ranking is a first choice, then a second choice from what's left, and so on. Learn the Plackett–Luce likelihood, the independence assumption it makes, and why the set of items each judge saw must be recorded.

Advanced ~12 min8 steps

What runs in CodeSplash

You will be able to

  • Compute a ranking's probability under Plackett–Luce
  • State the independence-of-irrelevant-alternatives assumption and when it fails
  • Explain why a partial ranking needs the shown set, and why within-ranking choices aren't independent rows

Read first

01

A ranking is a sequence of choices

Read

Ask a judge to order five summaries and you get more than ten pairwise verdicts' worth of information in one go. Plackett–LucePlackett–Luce modelA model of rankings as successive choices: each next item is picked from those left with chance proportional to its worth. models the ranking as repeated choices: pick the best from all available items with probability proportional to worth, then the best of the rest, and so on.

P(r1,…,rK∣A)=∏t=1Kwrt∑j∈A∖{r1,…,rt−1}wj.P(r_1,\ldots,r_K\mid A)=\prod_{t=1}^{K}\frac{w_{r_t}}{\sum_{j\in A\setminus\{r_1,\ldots,r_{t-1}\}}w_j}.

With two items it is exactly Bradley–Terry. With worths (3,2,1)(3,2,1), the order first, third, second has probability 36⋅13\tfrac36\cdot\tfrac13, which the reference's program confirms as 0.1667.

Reference · HME003 · Runs in CodeSplashPlackett–Luce ranking modelEstimate item worth from complete or appropriately defined partial rankings by representing a ranking as sequential selections from the remaining choice set.
02

The assumption inside

Read

Each choice depends only on the worths of the items still available. That is independence of irrelevant alternatives (IIA): adding or removing a third item never changes the odds between two others.

It fails when items are near-copies (two versions of the same summary split the votes a single version would get) or when the comparison set changes how judges read the task (a very bad option makes the others look better). If preferences differ by group, one set of worths averages over them; check fit by subgroup before reporting one order.

03

Partial rankings and the shown set

Read

Judges often rank only their top kk, or see a random subset of items. Two rules:

  • Keep unranked but shown items in every denominator. The judge chose the top three from all items shown; dropping the rest pretends they chose from three.
  • An item that wasn't shown isn't "worse". A ranking missing an item can't say whether it lost or was never offered. Record the shown set for every ranking.

Selective exposure (popular items shown more often) biases worths unless the design accounts for it.

04

Predict: bootstrap what?

Predict

Predict first

You bootstrap a Plackett–Luce fit to get intervals for the worths. What should each resample draw?

Each choice step as a separate rowWhole rankings
Reveal

Whole rankings. The choices within one ranking come from one judge in one sitting and share one likelihood; splitting them into independent rows overstates the information and narrows the intervals.

05

Plackett–Luce in CodeSplash

Read

Rankings (Plackett–Luce) takes one row per ranked item with a rank (missing for shown but unranked), and resamples whole rankings for its intervals.

Plackett–Luce modelRecorded · Python and R agreeRecorded 2026-11-21 · 118 values compared
R

Plackett–Luce model: LR χ²(6) = 115.08, p < .001

LR χ²
115.08
p
< .001
AIC
1259.38
mango first
89.0%

Plots

Worths (log scale) with 95% intervalsHow large are several estimates, how precise, and which exclude the null?
View data
Worth (log)UpperItemLower
0.76040.9882mango0.5326
0.54780.7845peach0.3111
0.38510.6220melon0.1482
−0.06530.1708pear−0.3013
−0.16760.0660plum−0.4011
−0.5964−0.3467lemon−0.8460
−0.8642−0.5987lime−1.130
How often each item comes first in the bootstrapWhich categories lead on a total, mean or median?
View data
ItemShare of resamples
mango0.8900
peach0.1000
melon0.0100
pear0
plum0
lemon0
lime0

Assumptions

  • Connected rankings — Every item is ranked above and below its way to every other item, so the estimates are finite and unique.
  • First choices match the model — Largest standardized gap: lemon, first in 15 rankings against 11.4 expected (z = 1.13).
  • Rankings per item — Every item is in at least 10 rankings (fewest 101).
  • Independent rankings — Not checked from data: rankings are treated as independent, and each choice ignores the items already chosen (independence of irrelevant alternatives). The bootstrap resamples single rankings.

Worths (log scale, centered; share = chance of being ranked first among all 7)

RankItemWorth (log)SE95% CI low95% CI highShareRankingsRanked firstExpected firstFirst in resamplesRank lowRank high
1mango0.76040.11620.53260.98820.26431124139.5950.890012
2peach0.54780.12080.31110.78450.21371012729.3830.100013
3melon0.38510.12090.14820.62200.18161022725.8730.010023
4pear−0.06530.1204−0.30130.17080.11581041418.017045
5plum−0.16760.1192−0.40110.06600.10451151917.293045
6lemon−0.59640.1274−0.8460−0.34670.06811121511.410067
7lime−0.86420.1354−1.130−0.59870.052110878.429067

Model fit

Value
Rankings150
Choices541
Log-likelihood−623.69
Log-likelihood, equal worths−681.23
LR χ² vs equal worths115.08
LR p1.754e-22
AIC1259.38
BIC1277.44
  • Plackett–Luce model: worths are log-worths centered to sum to 0; the last item (plum) was the reference in the fit. Lower values of rank are better. 56 of 150 rankings leave some shown items unranked; those items stay among the alternatives at every step. Newton iterations: 4.
  • Bootstrap: 200 of 200 resamples of single rankings refitted (seed 42; the same resamples in Python and R); 0 skipped because a resample's rankings weren't connected or didn't converge. Intervals are percentile intervals.
The exact R script · R R version 4.5.1 (2025-06-13)
# Rankings (Plackett–Luce)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method measurement.plackett_luce 1.0.0 · spec 8227e60eb1412e03
# Dataset: hme_rankings (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data (long rankings: one row per item shown; a missing rank = shown but not ranked)
col_r <- "taster"
col_i <- "fruit"
col_v <- "rank"
col_c <- NULL
cols <- unique(c(col_r, col_i, col_v, col_c))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/hme_rankings.parquet", col_select = cols))
stored_levels <- c("lemon", "lime", "mango", "melon", "peach", "pear", "plum")
n_input <- nrow(df)
need <- c(col_r, col_i, col_c)
df <- df[stats::complete.cases(df[need]), , drop = FALSE]  # rows without a ranking, item or cluster can't be placed
warnings <- list()
if (n_input - nrow(df) > 0) warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_input - nrow(df), total = n_input))
if (nrow(df) == 0) cs_error("CS_E_NO_ROWS")
value <- as.numeric(df[[col_v]])
cs_check_finite(value, col_v)  # infinite values stop the run (registry/errors.yaml)
item_text <- as.character(df[[col_i]])
levels_i <- if (!is.null(stored_levels)) stored_levels else sort(unique(item_text), method = "radix")
rid <- as.character(df[[col_r]])
names_r <- unique(rid)
code <- match(rid, names_r)
dup <- duplicated(paste(code, item_text, sep = "\r"))
if (any(dup)) cs_error("CS_E_INVALID_VALUES", column = col_i, requirement = "listed at most once in each ranking", count = sum(dup))
if (all(is.na(value))) cs_error("CS_E_ALL_MISSING", column = col_v)
better <- "lower"
reps <- 200
conf <- 0.95
seed <- 42  # portable Wichmann–Hill stream: Python draws the same resamples for this seed

# %% Choice stages (each ranking = a sequence of choices from the items not yet chosen)
item_all <- match(item_text, levels_i)
stg <- cs_pc_pl_stages(code, item_all, value, better)
if (stg$tied > 0) cs_error("CS_E_UNDEFINED", what = "The Plackett–Luce model", reason = sprintf("ranking %s has tied ranks; break the ties or leave that ranking out", names_r[stg$tied]))
if (length(unique(item_text)) < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = col_i, min = 2, k = length(unique(item_text)))
if (length(stg$st_choice) == 0) cs_error("CS_E_TOO_FEW_ROWS", what = "The Plackett–Luce model", min = 2, n = 0)  # no ranking shows two or more items
n_rank <- stg$n_rank
used <- sort(unique(stg$mem_item))
items <- levels_i[used]
k <- length(items)
if (k < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = col_i, min = 2, k = k)
remap <- rep(0L, length(levels_i))
remap[used] <- seq_len(k)
st_rank <- stg$st_rank
st_choice <- remap[stg$st_choice]
mem_stage <- stg$mem_stage
mem_item <- remap[stg$mem_item]
w_rank <- rep(1, n_rank)
w_stage <- w_rank[st_rank]
adj <- cs_pc_pl_graph(st_choice, mem_stage, mem_item, w_stage, k)
if (!cs_pc_strongly_connected(adj)) {
  cs_error("CS_E_UNDEFINED", what = "The Plackett–Luce model", reason = "some items are never ranked below (or never above) the rest, so their worths run off to infinity; add rankings that link them")
}
if (!is.null(col_c)) {
  cv <- as.character(df[[col_c]])
  first_row <- match(seq_len(n_rank), code)
  cl <- cv[first_row]
  unit <- match(cl, unique(cl))
  unit_label <- paste("whole values of", col_c)
} else {
  unit <- NULL
  unit_label <- "single rankings"
}

# %% Fit (maximum likelihood: Newton steps on log-worths, the last item as reference, then centered)
fit <- tryCatch(cs_pc_fit_pl(st_choice, mem_stage, mem_item, w_stage, k), error = function(e) {
  if (grepl("singular", conditionMessage(e))) cs_error("CS_E_COLLINEAR")
  cs_error("CS_E_NO_CONVERGENCE", what = "The Plackett–Luce model")
})
s <- fit$scores
se <- sqrt(diag(fit$cov))
z <- cs_pc_z(conf)
worth <- exp(s) / sum(exp(s))
ranks <- cs_pc_point_ranks(s)
loglik <- fit$loglik
loglik0 <- fit$loglik_null
npar <- k - 1
lr <- 2 * (loglik - loglik0)
ff <- cs_pc_pl_first_fit(st_rank, st_choice, mem_stage, mem_item, fit$raw, w_rank, k)
worst <- which.max(abs(ff$z))
pairs <- unique((st_rank[mem_stage] - 1) * k + mem_item)  # rankings in which each item takes part
shown <- tabulate((pairs - 1) %% k + 1, nbins = k)
values <- list(n_rankings = n_rank, n_choices = length(st_choice), items = k, partial = stg$partial, n_left_out = n_input - nrow(df),
               loglik = loglik, loglik_null = loglik0, npar = npar, lr = lr, lr_df = npar, lr_p = cs_pc_lr_p(lr, npar),
               aic = -2 * loglik + 2 * npar, bic = -2 * loglik + npar * log(n_rank), fit_max_z = abs(ff$z[worst]),
               fit_item = items[worst], iterations = fit$iterations)
for (i in seq_len(k)) {
  it <- items[i]
  values[[sprintf("score[%s]", it)]] <- s[i]
  values[[sprintf("se[%s]", it)]] <- se[i]
  values[[sprintf("ci_low[%s]", it)]] <- s[i] - z * se[i]
  values[[sprintf("ci_high[%s]", it)]] <- s[i] + z * se[i]
  values[[sprintf("worth[%s]", it)]] <- worth[i]
  values[[sprintf("rank[%s]", it)]] <- ranks[i]
  values[[sprintf("shown[%s]", it)]] <- shown[i]
  values[[sprintf("first_choices[%s]", it)]] <- ff$O[i]
  values[[sprintf("first_expected[%s]", it)]] <- ff$E[i]
}

# %% Bootstrap of the order (shared Wichmann–Hill stream; rankings, or whole clusters)
boot <- list()
boot_failed <- 0
if (reps > 0) {
  counts <- cs_pc_boot_counts(w_rank, unit, reps, seed)
  for (r in seq_len(reps)) {
    wb <- counts[r, ][st_rank]
    if (!cs_pc_strongly_connected(cs_pc_pl_graph(st_choice, mem_stage, mem_item, wb, k))) {
      boot_failed <- boot_failed + 1
      next
    }
    res <- tryCatch(cs_pc_fit_pl(st_choice, mem_stage, mem_item, wb, k)$scores, error = function(e) NULL)
    if (is.null(res)) boot_failed <- boot_failed + 1 else boot[[length(boot) + 1]] <- res
  }
}
boot_scores <- if (length(boot)) do.call(rbind, boot) else matrix(0, 0, k)
values["boot_ok"] <- list(if (reps > 0) nrow(boot_scores) else NULL)
values["boot_failed"] <- list(if (reps > 0) boot_failed else NULL)
top <- cs_pc_top_index(s)
values$top_item <- items[top]
bsum <- NULL
if (nrow(boot_scores) >= 2) {
  bsum <- cs_pc_boot_summary(boot_scores, conf)
  for (i in seq_len(k)) {
    it <- items[i]
    values[[sprintf("boot_low[%s]", it)]] <- bsum$low[i]
    values[[sprintf("boot_high[%s]", it)]] <- bsum$high[i]
    values[[sprintf("top_freq[%s]", it)]] <- bsum$top[i]
    values[[sprintf("rank_low[%s]", it)]] <- bsum$rank_low[i]
    values[[sprintf("rank_high[%s]", it)]] <- bsum$rank_high[i]
  }
  values$top_item_freq <- bsum$top[top]
} else {
  values["top_item_freq"] <- list(NULL)
}

# %% Assumptions
thin <- sprintf("%s (%d)", items, as.integer(shown))[shown < 10]
assumptions <- list(
  list(key = "connectivity", label = "Connected rankings", status = "pass",
       detail = "Every item is ranked above and below its way to every other item, so the estimates are finite and unique."),
  list(key = "fit", label = "First choices match the model", status = if (abs(ff$z[worst]) > 3) "warn" else "pass",
       detail = paste0(sprintf("Largest standardized gap: %s, first in %.0f rankings against %.1f expected (z = %.2f)", items[worst], ff$O[worst], ff$E[worst], ff$z[worst]),
                       if (abs(ff$z[worst]) > 3) " — the model misses this item's first choices." else ".")),
  list(key = "sample_size", label = "Rankings per item", status = if (length(thin)) "warn" else "pass",
       detail = if (length(thin)) paste0("In fewer than 10 rankings: ", paste(utils::head(thin, 8), collapse = ", "), if (length(thin) > 8) " …" else "", ".") else
         sprintf("Every item is in at least 10 rankings (fewest %d).", as.integer(min(shown)))),
  list(key = "independence", label = "Independent rankings", status = "info",
       detail = sprintf("Not checked from data: rankings are treated as independent, and each choice ignores the items already chosen (independence of irrelevant alternatives). The bootstrap resamples %s.", unit_label))
)

# %% Result
ord <- order(-round(s, 10), method = "radix")
pct <- sprintf("%.0f%%", conf * 100)
cols_t <- list(list(key = "rank", label = "Rank", type = "integer"), list(key = "item", label = "Item", type = "string"),
               list(key = "score", label = "Worth (log)", type = "number"), list(key = "se", label = "SE", type = "number"),
               list(key = "ci_low", label = paste(pct, "CI low"), type = "number"), list(key = "ci_high", label = paste(pct, "CI high"), type = "number"),
               list(key = "worth", label = "Share", type = "number"), list(key = "shown", label = "Rankings", type = "number"),
               list(key = "first", label = "Ranked first", type = "number"), list(key = "expected", label = "Expected first", type = "number"))
if (!is.null(bsum)) {
  cols_t <- c(cols_t, list(list(key = "top_freq", label = "First in resamples", type = "number"),
                           list(key = "rank_low", label = "Rank low", type = "number"), list(key = "rank_high", label = "Rank high", type = "number")))
}
rows <- lapply(ord, function(i) {
  r <- list(rank = ranks[i], item = items[i], score = s[i], se = se[i], ci_low = s[i] - z * se[i], ci_high = s[i] + z * se[i],
            worth = worth[i], shown = shown[i], first = ff$O[i], expected = ff$E[i])
  if (!is.null(bsum)) { r$top_freq <- bsum$top[i]; r$rank_low <- bsum$rank_low[i]; r$rank_high <- bsum$rank_high[i] }
  r
})
fit_rows <- list(list(stat = "Rankings", value = n_rank), list(stat = "Choices", value = length(st_choice)),
                 list(stat = "Log-likelihood", value = loglik), list(stat = "Log-likelihood, equal worths", value = loglik0),
                 list(stat = "LR χ² vs equal worths", value = lr), list(stat = "LR p", value = values$lr_p),
                 list(stat = "AIC", value = values$aic), list(stat = "BIC", value = values$bic))
tables <- list(list(key = "items", title = sprintf("Worths (log scale, centered; share = chance of being ranked first among all %d)", k), columns = cols_t, rows = rows),
               list(key = "fit", title = "Model fit", columns = list(list(key = "stat", label = "", type = "string"), list(key = "value", label = "Value", type = "number")), rows = fit_rows))
charts <- list(cs_chart("worths", "forest", sprintf("Worths (log scale) with %s intervals", pct), list(
  label = cs_col("Item", items[ord], "categorical", levels = items[ord]),
  estimate = cs_col("Worth (log)", s[ord], "numeric"),
  low = cs_col("Lower", (s - z * se)[ord], "numeric"),
  high = cs_col("Upper", (s + z * se)[ord], "numeric")
), controls = list(reference = 0)))
if (!is.null(bsum)) {
  charts[[2]] <- cs_chart("top", "bar-ranked", "How often each item comes first in the bootstrap", list(
    category = cs_col("Item", items[ord], "categorical", levels = items[ord]),
    value = cs_col("Share of resamples", bsum$top[ord], "numeric")
  ), controls = list(agg = "sum", top = min(30, k)))
}
notes <- list(sprintf("Plackett–Luce model: worths are log-worths centered to sum to 0; the last item (%s) was the reference in the fit. %s values of %s are better. %d of %d rankings leave some shown items unranked; those items stay among the alternatives at every step. Newton iterations: %d.",
                      items[k], if (better == "lower") "Lower" else "Higher", col_v, as.integer(stg$partial), as.integer(n_rank), as.integer(fit$iterations)))
if (reps > 0) {
  notes[[2]] <- sprintf("Bootstrap: %d of %d resamples of %s refitted (seed %s; the same resamples in Python and R); %d skipped because a resample's rankings weren't connected or didn't converge. Intervals are percentile intervals.",
                        nrow(boot_scores), as.integer(reps), unit_label, format(seed), as.integer(boot_failed))
}
summary <- paste0(sprintf("Plackett–Luce model for %d items from %d rankings: %s has the highest worth", k, as.integer(n_rank), items[top]),
                  if (!is.null(values$top_item_freq)) sprintf(" and comes first in %.0f%% of the bootstrap resamples.", 100 * values$top_item_freq) else ".")
cs_publish(list(
  method = "measurement.plackett_luce",
  methodVersion = "1.0.0",
  title = "Plackett–Luce model",
  engine = cs_engine_info("stats", "codesplashr"),
  n = as.integer(n_rank),
  summary = summary,
  apa = sprintf("Plackett–Luce model: LR χ²(%d) = %s, %s", as.integer(npar), cs_fmt_num(lr), cs_fmt_p(values$lr_p)),
  statistics = list(list(key = "lr", label = "LR χ²", value = lr), list(key = "lr_p", label = "p", value = values$lr_p, format = "p"),
                    list(key = "aic", label = "AIC", value = values$aic),
                    list(key = "top_item_freq", label = paste(items[top], "first"), value = values$top_item_freq, format = "percent")),
  tables = tables,
  assumptions = assumptions,
  warnings = warnings,
  notes = notes,
  charts = charts,
  values = values
))
Python

Plackett–Luce model: LR χ²(6) = 115.08, p < .001

LR χ²
115.08
p
< .001
AIC
1259.38
mango first
89.0%

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Connected rankings — Every item is ranked above and below its way to every other item, so the estimates are finite and unique.
  • First choices match the model — Largest standardized gap: lemon, first in 15 rankings against 11.4 expected (z = 1.13).
  • Rankings per item — Every item is in at least 10 rankings (fewest 101).
  • Independent rankings — Not checked from data: rankings are treated as independent, and each choice ignores the items already chosen (independence of irrelevant alternatives). The bootstrap resamples single rankings.

Worths (log scale, centered; share = chance of being ranked first among all 7)

RankItemWorth (log)SE95% CI low95% CI highShareRankingsRanked firstExpected firstFirst in resamplesRank lowRank high
1mango0.76040.11620.53260.98820.26431124139.5950.890012
2peach0.54780.12080.31110.78450.21371012729.3830.100013
3melon0.38510.12090.14820.62200.18161022725.8730.010023
4pear−0.06530.1204−0.30130.17080.11581041418.017045
5plum−0.16760.1192−0.40110.06600.10451151917.293045
6lemon−0.59640.1274−0.8460−0.34670.06811121511.410067
7lime−0.86420.1354−1.130−0.59870.052110878.429067

Model fit

Value
Rankings150
Choices541
Log-likelihood−623.69
Log-likelihood, equal worths−681.23
LR χ² vs equal worths115.08
LR p1.754e-22
AIC1259.38
BIC1277.44
  • Plackett–Luce model: worths are log-worths centered to sum to 0; the last item (plum) was the reference in the fit. Lower values of rank are better. 56 of 150 rankings leave some shown items unranked; those items stay among the alternatives at every step. Newton iterations: 4.
  • Bootstrap: 200 of 200 resamples of single rankings refitted (seed 42; the same resamples in Python and R); 0 skipped because a resample's rankings weren't connected or didn't converge. Intervals are percentile intervals.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Rankings (Plackett–Luce)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method measurement.plackett_luce 1.0.0 · spec 8227e60eb1412e03
# Dataset: hme_rankings (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import json

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.errors import check_finite
from codesplash.stats import paired_comparison as pc  # twin of R's cs_pc_* (R/stats_paired_comparison.R)

# %% Data (long rankings: one row per item shown; a missing rank = shown but not ranked)
col_r, col_i, col_v = "taster", "fruit", "rank"
col_c = None
cols = [c for c in (col_r, col_i, col_v, col_c) if c is not None]
df = pd.read_parquet("tests/parity/fixtures/hme_rankings.parquet", columns=list(dict.fromkeys(cols)))
stored = json.loads("{\"fruit\":[\"lemon\",\"lime\",\"mango\",\"melon\",\"peach\",\"pear\",\"plum\"],\"rank\":null,\"taster\":null}")
n_input = len(df)
need = [c for c in (col_r, col_i, col_c) if c is not None]
df = df.dropna(subset=need).reset_index(drop=True)  # rows without a ranking, item or cluster can't be placed
warnings = []
if n_input - len(df):
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_input - len(df), total=n_input))
if not len(df):
    cs.cs_error("CS_E_NO_ROWS")
value = df[col_v].to_numpy(dtype=float)
check_finite(value, col_v)  # infinite values stop the run (registry/errors.yaml)
item_text = df[col_i].astype(str).to_numpy()
levels = stored.get(col_i) or sorted(set(item_text))
rid = df[col_r].astype(str).to_numpy()
names = list(pd.unique(rid))
code = np.array([names.index(x) for x in rid], dtype=np.int64)
dup = pd.Series(list(zip(code, item_text))).duplicated().to_numpy()
if dup.any():
    cs.cs_error("CS_E_INVALID_VALUES", column=col_i, requirement="listed at most once in each ranking", count=int(dup.sum()))
if np.isnan(value).all():
    cs.cs_error("CS_E_ALL_MISSING", column=col_v)
better = "lower"
reps = 200
conf = 0.95
seed = 42  # portable Wichmann–Hill stream: R draws the same resamples for this seed

# %% Choice stages (each ranking = a sequence of choices from the items not yet chosen)
pos_all = {it: i for i, it in enumerate(levels)}
item_all = np.array([pos_all[x] for x in item_text], dtype=np.int64)
st_rank, st_choice, mem_stage, mem_item, n_rank, partial, tied = pc.pl_stages(code, item_all, value, better)
if tied >= 0:
    cs.cs_error("CS_E_UNDEFINED", what="The Plackett–Luce model", reason=f"ranking {names[tied]} has tied ranks; break the ties or leave that ranking out")
if len(set(item_text)) < 2:
    cs.cs_error("CS_E_TOO_FEW_GROUPS", column=col_i, min=2, k=len(set(item_text)))
if len(st_choice) == 0:  # no ranking shows two or more items
    cs.cs_error("CS_E_TOO_FEW_ROWS", what="The Plackett–Luce model", min=2, n=0)
used = sorted(set(mem_item.tolist()))
items = [levels[i] for i in used]
k = len(items)
if k < 2:
    cs.cs_error("CS_E_TOO_FEW_GROUPS", column=col_i, min=2, k=k)
remap = np.full(len(levels), -1, dtype=np.int64)
remap[used] = np.arange(k)
st_choice, mem_item = remap[st_choice], remap[mem_item]
w_rank = np.ones(n_rank)
w_stage = w_rank[st_rank]
adj = pc.pl_graph(st_choice, mem_stage, mem_item, w_stage, k)
if not pc.strongly_connected(adj):
    cs.cs_error("CS_E_UNDEFINED", what="The Plackett–Luce model", reason="some items are never ranked below (or never above) the rest, so their worths run off to infinity; add rankings that link them")
if col_c is not None:
    cv = df[col_c].astype(str).to_numpy()
    first_row = np.array([np.flatnonzero(code == g)[0] for g in range(n_rank)])
    cl_names = list(pd.unique(cv[first_row]))
    unit = np.array([cl_names.index(x) for x in cv[first_row]], dtype=np.int64)
    unit_label = f"whole values of {col_c}"
else:
    unit = None
    unit_label = "single rankings"

# %% Fit (maximum likelihood: Newton steps on log-worths, the last item as reference, then centered)
try:
    fit = pc.fit_pl(st_choice, mem_stage, mem_item, w_stage, k)
except RuntimeError:
    cs.cs_error("CS_E_NO_CONVERGENCE", what="The Plackett–Luce model")
except np.linalg.LinAlgError:
    cs.cs_error("CS_E_COLLINEAR")
s = fit["scores"]
se = np.sqrt(np.diag(fit["cov"]))
z = pc.z_value(conf)
worth = np.exp(s) / np.exp(s).sum()
ranks = pc.point_ranks(s)
loglik, loglik0 = fit["loglik"], fit["loglik_null"]
npar = k - 1
lr = 2 * (loglik - loglik0)
O, E, zr = pc.pl_first_choice_fit(st_rank, st_choice, mem_stage, mem_item, fit["raw"], w_rank, k)
worst = int(np.argmax(np.abs(zr)))
pairs = np.unique(st_rank[mem_stage] * k + mem_item)  # rankings in which each item takes part
shown = np.bincount(pairs % k, minlength=k).astype(float)
values = {"n_rankings": float(n_rank), "n_choices": float(len(st_choice)), "items": float(k), "partial": float(partial),
          "n_left_out": float(n_input - len(df)), "loglik": loglik, "loglik_null": loglik0, "npar": float(npar), "lr": lr,
          "lr_df": float(npar), "lr_p": pc.lr_p(lr, npar), "aic": -2 * loglik + 2 * npar, "bic": -2 * loglik + npar * np.log(n_rank),
          "fit_max_z": float(np.abs(zr[worst])), "fit_item": items[worst], "iterations": float(fit["iterations"])}
for i, it in enumerate(items):
    values.update({f"score[{it}]": float(s[i]), f"se[{it}]": float(se[i]), f"ci_low[{it}]": float(s[i] - z * se[i]),
                   f"ci_high[{it}]": float(s[i] + z * se[i]), f"worth[{it}]": float(worth[i]), f"rank[{it}]": float(ranks[i]),
                   f"shown[{it}]": float(shown[i]), f"first_choices[{it}]": float(O[i]), f"first_expected[{it}]": float(E[i])})

# %% Bootstrap of the order (shared Wichmann–Hill stream; rankings, or whole clusters)
boot_scores, boot_failed = [], 0
if reps > 0:
    counts = pc.boot_counts(w_rank, unit, reps, seed)
    for r in range(reps):
        wb = counts[r][st_rank]
        if not pc.strongly_connected(pc.pl_graph(st_choice, mem_stage, mem_item, wb, k)):
            boot_failed += 1
            continue
        try:
            boot_scores.append(pc.fit_pl(st_choice, mem_stage, mem_item, wb, k)["scores"])
        except (RuntimeError, np.linalg.LinAlgError):
            boot_failed += 1
boot_scores = np.array(boot_scores) if boot_scores else np.zeros((0, k))
values["boot_ok"] = float(len(boot_scores)) if reps > 0 else None
values["boot_failed"] = float(boot_failed) if reps > 0 else None
top = pc.top_index(s)
values["top_item"] = items[top]
if len(boot_scores) >= 2:
    blo, bhi, topf, rlo, rhi = pc.boot_summary(boot_scores, conf)
    for i, it in enumerate(items):
        values.update({f"boot_low[{it}]": float(blo[i]), f"boot_high[{it}]": float(bhi[i]), f"top_freq[{it}]": float(topf[i]),
                       f"rank_low[{it}]": float(rlo[i]), f"rank_high[{it}]": float(rhi[i])})
    values["top_item_freq"] = float(topf[top])
else:
    blo = bhi = topf = rlo = rhi = None
    values["top_item_freq"] = None

# %% Assumptions
thin = [f"{it} ({int(shown[i])})" for i, it in enumerate(items) if shown[i] < 10]
assumptions = [
    {"key": "connectivity", "label": "Connected rankings", "status": "pass",
     "detail": "Every item is ranked above and below its way to every other item, so the estimates are finite and unique."},
    {"key": "fit", "label": "First choices match the model", "status": "warn" if abs(zr[worst]) > 3 else "pass",
     "detail": f"Largest standardized gap: {items[worst]}, first in {O[worst]:.0f} rankings against {E[worst]:.1f} expected (z = {zr[worst]:.2f})"
     + (" — the model misses this item's first choices." if abs(zr[worst]) > 3 else ".")},
    {"key": "sample_size", "label": "Rankings per item", "status": "warn" if thin else "pass",
     "detail": "In fewer than 10 rankings: " + ", ".join(thin[:8]) + (" …" if len(thin) > 8 else "") + "." if thin else f"Every item is in at least 10 rankings (fewest {int(shown.min())})."},
    {"key": "independence", "label": "Independent rankings", "status": "info",
     "detail": f"Not checked from data: rankings are treated as independent, and each choice ignores the items already chosen (independence of irrelevant alternatives). The bootstrap resamples {unit_label}."},
]

# %% Result
order = np.argsort(-np.round(s, 10), kind="stable")
pct = f"{conf:.0%}"
cols_t = [{"key": "rank", "label": "Rank", "type": "integer"}, {"key": "item", "label": "Item", "type": "string"},
          {"key": "score", "label": "Worth (log)", "type": "number"}, {"key": "se", "label": "SE", "type": "number"},
          {"key": "ci_low", "label": f"{pct} CI low", "type": "number"}, {"key": "ci_high", "label": f"{pct} CI high", "type": "number"},
          {"key": "worth", "label": "Share", "type": "number"}, {"key": "shown", "label": "Rankings", "type": "number"},
          {"key": "first", "label": "Ranked first", "type": "number"}, {"key": "expected", "label": "Expected first", "type": "number"}]
if blo is not None:
    cols_t += [{"key": "top_freq", "label": "First in resamples", "type": "number"},
               {"key": "rank_low", "label": "Rank low", "type": "number"}, {"key": "rank_high", "label": "Rank high", "type": "number"}]
rows = []
for i in order:
    r = {"rank": float(ranks[i]), "item": items[i], "score": float(s[i]), "se": float(se[i]), "ci_low": float(s[i] - z * se[i]),
         "ci_high": float(s[i] + z * se[i]), "worth": float(worth[i]), "shown": float(shown[i]), "first": float(O[i]), "expected": float(E[i])}
    if blo is not None:
        r.update({"top_freq": float(topf[i]), "rank_low": float(rlo[i]), "rank_high": float(rhi[i])})
    rows.append(r)
fit_rows = [{"stat": "Rankings", "value": float(n_rank)}, {"stat": "Choices", "value": float(len(st_choice))},
            {"stat": "Log-likelihood", "value": loglik}, {"stat": "Log-likelihood, equal worths", "value": loglik0},
            {"stat": "LR χ² vs equal worths", "value": lr}, {"stat": "LR p", "value": values["lr_p"]},
            {"stat": "AIC", "value": values["aic"]}, {"stat": "BIC", "value": values["bic"]}]
tables = [{"key": "items", "title": f"Worths (log scale, centered; share = chance of being ranked first among all {k})", "columns": cols_t, "rows": rows},
          {"key": "fit", "title": "Model fit", "columns": [{"key": "stat", "label": "", "type": "string"}, {"key": "value", "label": "Value", "type": "number"}], "rows": fit_rows}]
charts = [cs.chart("worths", "forest", f"Worths (log scale) with {pct} intervals", {
    "label": cs.col("Item", [items[i] for i in order], "categorical", levels=[items[i] for i in order]),
    "estimate": cs.col("Worth (log)", [float(s[i]) for i in order], "numeric"),
    "low": cs.col("Lower", [float(s[i] - z * se[i]) for i in order], "numeric"),
    "high": cs.col("Upper", [float(s[i] + z * se[i]) for i in order], "numeric"),
}, controls={"reference": 0})]
if topf is not None:
    charts.append(cs.chart("top", "bar-ranked", "How often each item comes first in the bootstrap", {
        "category": cs.col("Item", [items[i] for i in order], "categorical", levels=[items[i] for i in order]),
        "value": cs.col("Share of resamples", [float(topf[i]) for i in order], "numeric"),
    }, controls={"agg": "sum", "top": min(30, k)}))
notes = [f"Plackett–Luce model: worths are log-worths centered to sum to 0; the last item ({items[-1]}) was the reference in the fit. "
         f"{'Lower' if better == 'lower' else 'Higher'} values of {col_v} are better. {partial} of {n_rank} rankings leave some shown items unranked; "
         f"those items stay among the alternatives at every step. Newton iterations: {fit['iterations']}."]
if reps > 0:
    notes.append(f"Bootstrap: {len(boot_scores)} of {reps} resamples of {unit_label} refitted (seed {seed}; the same resamples in Python and R); "
                 f"{boot_failed} skipped because a resample's rankings weren't connected or didn't converge. Intervals are percentile intervals.")
summary = f"Plackett–Luce model for {k} items from {n_rank} rankings: {items[top]} has the highest worth" + (
    f" and comes first in {values['top_item_freq']:.0%} of the bootstrap resamples." if values["top_item_freq"] is not None else ".")
cs.publish({
    "method": "measurement.plackett_luce",
    "methodVersion": "1.0.0",
    "title": "Plackett–Luce model",
    "engine": cs.engine_info("numpy", "scipy", "codesplash"),
    "n": int(n_rank),
    "summary": summary,
    "apa": f"Plackett–Luce model: LR χ²({npar}) = {cs.fmt_num(lr)}, {cs.fmt_p(values['lr_p'])}",
    "statistics": [{"key": "lr", "label": "LR χ²", "value": lr}, {"key": "lr_p", "label": "p", "value": values["lr_p"], "format": "p"},
                   {"key": "aic", "label": "AIC", "value": values["aic"]}, {"key": "top_item_freq", "label": f"{items[top]} first", "value": values["top_item_freq"], "format": "percent"}],
    "tables": tables,
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": notes,
    "charts": charts,
    "values": values,
})

From 150 rankings, 56 of them top-3 only, the fit uses 541 choices. mango leads in 89% of resamples, and the fit check's largest gap is 1.13 standard deviations.

Pairwise judgments written as two-item rankings reproduce Bradley–Terry's log-likelihood, −549.5.

06

Where it stands in CodeSplash

Read
EntryIn CodeSplash
Plackett–Luce (HME003)Runs in CodeSplash: Rankings (Plackett–Luce) with partial rankings, shown sets, ranking-level bootstrap and a fit check, Python ≡ R; tied ranks need the generalized likelihood, which isn't offered
07

Check your understanding

Checkpoint

Check yourself

Three items have worths 3, 2 and 1. What is the probability of the ranking second item, then first, then third?

Show the answer

Answer: 0.25

26⋅34⋅1=0.25\tfrac{2}{6}\cdot\tfrac{3}{4}\cdot1=0.25. The first choice is from all three (total 6), the second from the remaining two (total 4), and the last item is left over.

Check yourself

Adding a near-duplicate of summary A to the set lowers A's share of first places and leaves B's unchanged. Which Plackett–Luce assumption does that strain?

Show the answer

Answer: b

Near-copies compete with each other more than with other items. IIA-based models misread that as A losing worth.

Check yourself

A taster ranked their top three of seven fruits shown. How should the four unranked fruits enter the likelihood?

Show the answer

Answer: c

They were on the table at every step. Dropping them pretends a smaller choice set; tying them invents judgments.

08

Recap

Recap
  • Plackett–Luce: a ranking is sequential choices with probability proportional to worth among what's left.
  • It assumes IIA; near-duplicates and context effects break it.
  • Record the shown set; keep unranked shown items in the denominators; resample whole rankings.

Concepts in this lesson