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.
What runs in CodeSplash
- HME003Plackett–Luce ranking model Runs in CodeSplash
- Rankings (Plackett–Luce) Verified in Python and R
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
A ranking is a sequence of choices
ReadAsk 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.
With two items it is exactly Bradley–Terry. With worths , the order first, third, second has probability , 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.The assumption inside
ReadEach 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.
Partial rankings and the shown set
ReadJudges often rank only their top , 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.
Predict: bootstrap what?
PredictPredict first
You bootstrap a Plackett–Luce fit to get intervals for the worths. What should each resample draw?
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.
Plackett–Luce in CodeSplash
ReadRankings (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 model: LR χ²(6) = 115.08, p < .001
- LR χ²
- 115.08
- p
- < .001
- AIC
- 1259.38
- mango first
- 89.0%
Plots
View data
| Worth (log) | Upper | Item | Lower |
|---|---|---|---|
| 0.7604 | 0.9882 | mango | 0.5326 |
| 0.5478 | 0.7845 | peach | 0.3111 |
| 0.3851 | 0.6220 | melon | 0.1482 |
| −0.0653 | 0.1708 | pear | −0.3013 |
| −0.1676 | 0.0660 | plum | −0.4011 |
| −0.5964 | −0.3467 | lemon | −0.8460 |
| −0.8642 | −0.5987 | lime | −1.130 |
View data
| Item | Share of resamples |
|---|---|
| mango | 0.8900 |
| peach | 0.1000 |
| melon | 0.0100 |
| pear | 0 |
| plum | 0 |
| lemon | 0 |
| lime | 0 |
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)
| Rank | Item | Worth (log) | SE | 95% CI low | 95% CI high | Share | Rankings | Ranked first | Expected first | First in resamples | Rank low | Rank high |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | mango | 0.7604 | 0.1162 | 0.5326 | 0.9882 | 0.2643 | 112 | 41 | 39.595 | 0.8900 | 1 | 2 |
| 2 | peach | 0.5478 | 0.1208 | 0.3111 | 0.7845 | 0.2137 | 101 | 27 | 29.383 | 0.1000 | 1 | 3 |
| 3 | melon | 0.3851 | 0.1209 | 0.1482 | 0.6220 | 0.1816 | 102 | 27 | 25.873 | 0.0100 | 2 | 3 |
| 4 | pear | −0.0653 | 0.1204 | −0.3013 | 0.1708 | 0.1158 | 104 | 14 | 18.017 | 0 | 4 | 5 |
| 5 | plum | −0.1676 | 0.1192 | −0.4011 | 0.0660 | 0.1045 | 115 | 19 | 17.293 | 0 | 4 | 5 |
| 6 | lemon | −0.5964 | 0.1274 | −0.8460 | −0.3467 | 0.0681 | 112 | 15 | 11.410 | 0 | 6 | 7 |
| 7 | lime | −0.8642 | 0.1354 | −1.130 | −0.5987 | 0.0521 | 108 | 7 | 8.429 | 0 | 6 | 7 |
Model fit
| Value | |
|---|---|
| Rankings | 150 |
| Choices | 541 |
| Log-likelihood | −623.69 |
| Log-likelihood, equal worths | −681.23 |
| LR χ² vs equal worths | 115.08 |
| LR p | 1.754e-22 |
| AIC | 1259.38 |
| BIC | 1277.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
))
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)
| Rank | Item | Worth (log) | SE | 95% CI low | 95% CI high | Share | Rankings | Ranked first | Expected first | First in resamples | Rank low | Rank high |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | mango | 0.7604 | 0.1162 | 0.5326 | 0.9882 | 0.2643 | 112 | 41 | 39.595 | 0.8900 | 1 | 2 |
| 2 | peach | 0.5478 | 0.1208 | 0.3111 | 0.7845 | 0.2137 | 101 | 27 | 29.383 | 0.1000 | 1 | 3 |
| 3 | melon | 0.3851 | 0.1209 | 0.1482 | 0.6220 | 0.1816 | 102 | 27 | 25.873 | 0.0100 | 2 | 3 |
| 4 | pear | −0.0653 | 0.1204 | −0.3013 | 0.1708 | 0.1158 | 104 | 14 | 18.017 | 0 | 4 | 5 |
| 5 | plum | −0.1676 | 0.1192 | −0.4011 | 0.0660 | 0.1045 | 115 | 19 | 17.293 | 0 | 4 | 5 |
| 6 | lemon | −0.5964 | 0.1274 | −0.8460 | −0.3467 | 0.0681 | 112 | 15 | 11.410 | 0 | 6 | 7 |
| 7 | lime | −0.8642 | 0.1354 | −1.130 | −0.5987 | 0.0521 | 108 | 7 | 8.429 | 0 | 6 | 7 |
Model fit
| Value | |
|---|---|
| Rankings | 150 |
| Choices | 541 |
| Log-likelihood | −623.69 |
| Log-likelihood, equal worths | −681.23 |
| LR χ² vs equal worths | 115.08 |
| LR p | 1.754e-22 |
| AIC | 1259.38 |
| BIC | 1277.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.
Where it stands in CodeSplash
Read| Entry | In 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 |
Check your understanding
CheckpointCheck 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
. 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.
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