---
title: "MaxDiff Analysis of MSBA Class Preferences"
subtitle: "Counts, Maximum Likelihood, and Bayesian Estimation of the MNL Model"
author: "Shreya Anekar"
date: today
categories: [marketing analytics, MNL, bayesian, python, survey analysis]
image: thumbnail.png
format:
html:
toc: true
toc-depth: 3
code-fold: true
code-tools: true
theme: cosmo
fig-width: 9
fig-height: 5
execute:
warning: false
message: false
---
```{python}
#| echo: false
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from scipy.optimize import minimize
from scipy.special import logsumexp
from great_tables import GT, style, loc
import warnings
warnings.filterwarnings("ignore")
plt.rcParams.update({
"figure.facecolor": "white",
"axes.facecolor": "#f8f9fa",
"axes.grid": True,
"grid.color": "white",
"grid.linewidth": 1.2,
"axes.spines.top": False,
"axes.spines.right": False,
"font.family": "sans-serif",
"axes.titlesize": 13,
"axes.labelsize": 11,
})
BLUE = "#2563eb"
ORANGE = "#f97316"
GREEN = "#16a34a"
RED = "#dc2626"
GRAY = "#6b7280"
TEAL = "#0891b2"
np.random.seed(42)
```
## Introduction
If you've ever tried to rate something on a scale of 1 to 10, you know how awkward it feels. Is this restaurant a 7 or an 8? Does everyone's "8" mean the same thing? These are real problems — humans are notoriously bad at anchoring numeric scales consistently. They are, however, very good at one thing: picking a winner and a loser when forced to choose.
That intuition is the foundation of **MaxDiff**, also called *Best-Worst Scaling*. Instead of asking "how much do you like this course on a scale of 1–5?", MaxDiff presents each respondent with a small subset of items (here, 4 courses at a time) and asks two questions: which is your **most preferred**, and which is your **least preferred**? The respondent repeats this across many different subsets, and the data from all those forced trade-offs is used to recover a latent preference scale for every item.
In this analysis, the 10 items are the 10 core MSBA courses at UCSD Rady. The 85 students who completed the survey each made 8 valid best–worst choices across different 4-course subsets. The goal is to estimate each course's relative preference using three different methods — and see whether they agree:
1. A **counts analysis**: the simplest possible summary — how often was each class picked best, minus how often it was picked worst?
2. **MNL via Maximum Likelihood (MLE)**: a principled probabilistic model that turns every choice observation into a likelihood contribution and finds the parameters that best explain the data.
3. **MNL via Bayesian estimation**: the same model, but instead of a single point estimate, we use Markov Chain Monte Carlo (MCMC) to map out the full posterior distribution over parameters.
The three methods should broadly agree on which classes are most and least preferred. Where they differ — and *why* — turns out to be the most instructive part.
---
## The Data
```{python}
#| echo: true
# Load data
df = pd.read_csv("maxdiff_design_and_choices.csv", encoding="utf-8-sig")
df.columns = ["Record_ID", "Task", "Position", "Item", "Response"]
labels_raw = pd.read_csv("maxdiff_item_labels.csv", encoding="utf-8-sig")
labels_raw.columns = ["item_num", "item_label"] + list(labels_raw.columns[2:])
labels = labels_raw[["item_num", "item_label"]].dropna(subset=["item_num"])
labels["item_num"] = labels["item_num"].astype(int)
labels = labels[labels["item_num"].between(1, 10)].reset_index(drop=True)
# Short labels for plots
short_labels = {
1: "AI Math & Prog. (403)",
2: "SQL (464)",
3: "Mktg/Fin/Ops (451)",
4: "Large Data (452)",
5: "Business Analytics (453)",
6: "Analytics Consulting (444)",
7: "Customer Analytics (455)",
8: "Capstone (454)",
9: "Marketing Analytics (495)",
10: "Biz. Intelligence (457)",
}
# Keep only valid 4-item tasks (exclude tasks involving item 11)
task_size = df.groupby(["Record_ID", "Task"]).size().reset_index(name="n")
valid_tasks = task_size[task_size["n"] == 4][["Record_ID", "Task"]]
df = df.merge(valid_tasks, on=["Record_ID", "Task"])
N = df["Record_ID"].nunique()
T = df.groupby("Record_ID")["Task"].nunique().iloc[0]
J = 4 # items shown per task
K = 10 # total items in study
print(f"Respondents (N): {N}")
print(f"Tasks per respondent (T): {T}")
print(f"Items per task (J): {J}")
print(f"Total items in study (K): {K}")
print(f"Total tasks: {N * T}")
```
### Sanity Checks
```{python}
#| echo: true
# Every task must have exactly one best (+1), one worst (−1), two neutrals (0)
task_checks = df.groupby(["Record_ID", "Task"])["Response"].apply(
lambda r: (sum(r == 1) == 1) and (sum(r == -1) == 1) and (sum(r == 0) == 2)
)
print(f"All tasks pass sanity check: {task_checks.all()}")
# How many times each item was shown
shown_counts = df.groupby("Item").size().rename("times_shown")
print("\nTimes each item was shown:")
print(shown_counts.to_string())
```
Every task has exactly one *best* pick, one *worst* pick, and two neutral slots — as designed. The exposure counts across items are not perfectly equal (this is a real-world survey, not a textbook balanced design), but they are all in the same ballpark, which means our estimates will be comparably precise for each class.
---
## Counts Analysis
The counts analysis is the simplest possible summary of a MaxDiff survey. For each class $j$, we compute:
$$
\text{score}_j \;=\; \frac{\text{times picked best}_j}{\text{times shown}_j} \;-\; \frac{\text{times picked worst}_j}{\text{times shown}_j} \;=\; \%\text{best}_j - \%\text{worst}_j
$$
A score near +1 means a class is almost always chosen as the favourite when it appears on screen. Near −1 means it is almost always the least favourite. Near 0 means it sits squarely in the middle, or it is polarizing — loved by some, disliked by others.
The counts analysis is quick and intuitive, but it treats each "shown" occasion as independent and ignores everything we know about *which other items were shown at the same time*. That matters: being picked best when shown alongside unpopular classes is less impressive than being picked best in a tough lineup.
```{python}
#| echo: true
# Aggregate counts per item
item_counts = df.groupby("Item").agg(
times_shown = ("Response", "count"),
times_best = ("Response", lambda r: (r == 1).sum()),
times_worst = ("Response", lambda r: (r == -1).sum()),
).reset_index()
item_counts["pct_best"] = item_counts["times_best"] / item_counts["times_shown"]
item_counts["pct_worst"] = item_counts["times_worst"] / item_counts["times_shown"]
item_counts["score"] = item_counts["pct_best"] - item_counts["pct_worst"]
item_counts["short_label"] = item_counts["Item"].map(short_labels)
item_counts = item_counts.sort_values("score", ascending=False).reset_index(drop=True)
# Bootstrap 95% CIs (resample respondents with replacement — proper unit of analysis)
respondents = df["Record_ID"].unique()
B = 1000
boot_scores = np.zeros((B, K))
for b in range(B):
samp = np.random.choice(respondents, size=N, replace=True)
# pd.concat handles duplicate respondents correctly (each appearance = one full set of rows)
boot_df = pd.concat([df[df["Record_ID"] == rid] for rid in samp], ignore_index=True)
bg = boot_df.groupby("Item").agg(
shown = ("Response", "count"),
best = ("Response", lambda r: (r == 1).sum()),
worst = ("Response", lambda r: (r == -1).sum()),
)
bg = bg.reindex(range(1, K+1), fill_value=0)
boot_scores[b] = (bg["best"] / bg["shown"].replace(0, np.nan)).fillna(0).values - \
(bg["worst"] / bg["shown"].replace(0, np.nan)).fillna(0).values
# Attach CIs in the order of item_counts
ci_lo = np.percentile(boot_scores, 2.5, axis=0)
ci_hi = np.percentile(boot_scores, 97.5, axis=0)
item_counts["ci_lo"] = item_counts["Item"].apply(lambda i: ci_lo[i-1])
item_counts["ci_hi"] = item_counts["Item"].apply(lambda i: ci_hi[i-1])
```
```{python}
#| echo: false
tbl_data = item_counts[["short_label","times_shown","times_best","times_worst","pct_best","pct_worst","score"]].copy()
tbl_data.columns = ["Class", "Shown", "# Best", "# Worst", "% Best", "% Worst", "Score"]
tbl_data["% Best"] = (tbl_data["% Best"] * 100).round(1)
tbl_data["% Worst"] = (tbl_data["% Worst"] * 100).round(1)
tbl_data["Score"] = tbl_data["Score"].round(3)
(
GT(tbl_data)
.tab_header(title="Counts Analysis — Ranked by Score")
.tab_style(style=style.text(weight="bold"), locations=loc.column_labels())
.tab_style(
style=style.fill(color="#dcfce7"),
locations=loc.body(rows=[0, 1, 2])
)
.tab_style(
style=style.fill(color="#fee2e2"),
locations=loc.body(rows=[7, 8, 9])
)
)
```
```{python}
#| echo: false
#| fig-cap: "Counts scores with 95% bootstrap confidence intervals, sorted from most to least preferred."
fig, ax = plt.subplots(figsize=(9, 5.5))
colors = [GREEN if s > 0 else RED for s in item_counts["score"]]
y_pos = range(len(item_counts))
bars = ax.barh(list(y_pos), item_counts["score"].values, color=colors, alpha=0.8, height=0.6)
ax.errorbar(
item_counts["score"], list(y_pos),
xerr=[item_counts["score"] - item_counts["ci_lo"],
item_counts["ci_hi"] - item_counts["score"]],
fmt="none", color="#374151", capsize=4, linewidth=1.2
)
ax.set_yticks(list(y_pos))
ax.set_yticklabels(item_counts["short_label"], fontsize=9)
ax.axvline(0, color=GRAY, linewidth=1.2, linestyle="--", alpha=0.7)
ax.set_xlabel("Score (% Best − % Worst)")
ax.set_title("Counts Analysis: Preference Scores for MSBA Classes")
green_patch = mpatches.Patch(color=GREEN, alpha=0.8, label="Net positive")
red_patch = mpatches.Patch(color=RED, alpha=0.8, label="Net negative")
ax.legend(handles=[green_patch, red_patch], fontsize=9, frameon=False)
plt.tight_layout()
plt.savefig("thumbnail.png", dpi=150, bbox_inches="tight")
plt.show()
```
**What the counts tell us.** Marketing Analytics (495) stands out as the clear favourite — students pick it as best far more often than they pick it as worst. **Business Analytics (453)** and **Customer Analytics (455)** follow at a comfortable distance. At the other end, **Analytics Consulting (444)** and **Mktg/Fin/Ops (451)** land at the bottom — both have high worst-pick rates relative to how often they appear, dragging their scores well into negative territory. SQL (464) sits almost exactly at zero, picked best and worst in roughly equal measure — a genuinely neutral, or polarizing, course for this cohort.
---
## From MaxDiff Data to MNL Choices
The counts analysis is a useful starting point, but it has a blind spot: it ignores the competition. Being picked best when sharing a screen with three unpopular classes is less informative than being picked best in a strong lineup.
The **Multinomial Logit (MNL)** model solves this by modeling the choice process explicitly. We assign each class $j$ a latent utility coefficient $\beta_j$. On a task showing classes $\{a, b, c, d\}$, the probability that class $b$ is picked as **best** is the softmax:
$$
P(\text{best} = b) = \frac{\exp(\beta_b)}{\exp(\beta_a) + \exp(\beta_b) + \exp(\beta_c) + \exp(\beta_d)}
$$
After the best pick, the respondent selects the **worst** from the remaining three. With utilities *negated* (lower utility → more likely to be worst):
$$
P(\text{worst} = c \mid \text{best} = b) = \frac{\exp(-\beta_c)}{\exp(-\beta_a) + \exp(-\beta_c) + \exp(-\beta_d)}
$$
So each task contributes *two* log-likelihood terms — one for the best pick and one for the worst — and every item on screen contributes information, not just the one that was chosen.
**Identifiability.** Because softmax probabilities depend only on *differences* between utilities, adding any constant to every $\beta$ leaves all probabilities unchanged. We therefore fix $\beta_1 = 0$ (MGTA 403 as the reference) and estimate the remaining 9 parameters.
```{python}
#| echo: true
# Reshape to task-level records
tasks = []
for (rid, tid), grp in df.groupby(["Record_ID", "Task"]):
items = grp["Item"].values
best = grp[grp["Response"] == 1]["Item"].values[0]
worst = grp[grp["Response"] == -1]["Item"].values[0]
tasks.append({"items": items, "best": best, "worst": worst})
print(f"Total tasks reshaped: {len(tasks)}")
print(f"Sample task: items={tasks[0]['items']}, best={tasks[0]['best']}, worst={tasks[0]['worst']}")
# Pre-build NumPy arrays once — used by the vectorized likelihood below
all_items = np.array([t["items"] for t in tasks]) # (680, 4)
best_arr = np.array([t["best"] for t in tasks]) # (680,)
worst_arr = np.array([t["worst"] for t in tasks]) # (680,)
remaining_arr = np.array([t["items"][t["items"] != t["best"]] # (680, 3)
for t in tasks])
```
---
## MNL via Maximum Likelihood
The full log-likelihood, summing over all $N \times T = 680$ tasks, is:
$$
\ell(\boldsymbol{\beta}) = \sum_{\text{tasks}} \Bigl[
\underbrace{\beta_{j^*_b} - \log \textstyle\sum_{j \in \text{shown}} \exp(\beta_j)}_{\text{best-pick term}}
\;+\;
\underbrace{-\beta_{j^*_w} - \log \textstyle\sum_{j \in \text{shown} \setminus \{j^*_b\}} \exp(-\beta_j)}_{\text{worst-pick term}}
\Bigr]
$$
where $j^*_b$ is the class picked best and $j^*_w$ is the class picked worst.
```{python}
#| echo: true
def log_lik(beta_free, *args):
"""
Vectorized log-likelihood for MaxDiff MNL.
beta_free: length-9 vector (items 2-10); item 1 is pinned to 0.
Uses pre-built NumPy arrays — ~100x faster than a Python loop.
"""
beta = np.concatenate([[0.0], beta_free])
# Best-pick term: for each task, score of the chosen item minus log-sum of all 4
utils_all = beta[all_items - 1] # (680, 4)
best_utils = beta[best_arr - 1] # (680,)
ll = (best_utils - logsumexp(utils_all, axis=1)).sum()
# Worst-pick term: negated scores of the 3 remaining items
neg_utils_rem = -beta[remaining_arr - 1] # (680, 3)
worst_utils = -beta[worst_arr - 1] # (680,)
ll += (worst_utils - logsumexp(neg_utils_rem, axis=1)).sum()
return ll
```
```{python}
#| echo: true
result = minimize(
fun = lambda b: -log_lik(b),
x0 = np.zeros(9),
method = "L-BFGS-B",
options = {"maxiter": 5000, "ftol": 1e-12, "gtol": 1e-8},
)
beta_mle = np.concatenate([[0.0], result.x])
print(f"Optimizer converged: {result.success}")
print(f"Log-likelihood at MLE: {-result.fun:.2f}")
```
```{python}
#| echo: true
# Standard errors via numerical Hessian
from scipy.optimize import approx_fprime
def neg_ll(b):
return -log_lik(b)
eps = 1e-5
n_params = 9
H = np.zeros((n_params, n_params))
for i in range(n_params):
def fi(x, i=i):
g = approx_fprime(x, neg_ll, eps)
return g[i]
H[i] = approx_fprime(result.x, fi, eps)
se_free = np.sqrt(np.diag(np.linalg.inv(H)))
se_mle = np.concatenate([[np.nan], se_free])
# Shares of preference
shares_mle = np.exp(beta_mle) / np.exp(beta_mle).sum()
```
```{python}
#| echo: false
mle_df = pd.DataFrame({
"Class": [short_labels[i] for i in range(1, 11)],
"β̂": beta_mle.round(3),
"SE(β̂)": ["—"] + [f"{s:.3f}" for s in se_free],
"Share": (shares_mle * 100).round(2),
}).sort_values("Share", ascending=False).reset_index(drop=True)
(
GT(mle_df)
.tab_header(
title="MNL via Maximum Likelihood",
subtitle="β̂ coefficients, standard errors, and shares of preference (summing to 100%)"
)
.tab_style(style=style.text(weight="bold"), locations=loc.column_labels())
.tab_style(
style=style.fill(color="#eff6ff"),
locations=loc.body(rows=[0, 1, 2])
)
.tab_style(
style=style.fill(color="#fff1f2"),
locations=loc.body(rows=[7, 8, 9])
)
)
```
```{python}
#| echo: false
#| fig-cap: "MLE shares of preference — if all 10 classes were shown together on one screen, what fraction of 'best' picks would each attract?"
mle_plot = pd.DataFrame({
"label": [short_labels[i] for i in range(1, 11)],
"share": shares_mle * 100,
}).sort_values("share", ascending=True)
fig, ax = plt.subplots(figsize=(9, 5.5))
colors = [GREEN if s >= mle_plot["share"].median() else RED for s in mle_plot["share"]]
ax.barh(mle_plot["label"], mle_plot["share"], color=colors, alpha=0.8, height=0.6)
ax.set_xlabel("Share of Preference (%)")
ax.set_title("MLE Shares of Preference — MSBA Classes")
ax.axvline(10, color=GRAY, linestyle="--", linewidth=1, alpha=0.6, label="Equal share (10%)")
ax.legend(fontsize=9, frameon=False)
plt.tight_layout()
plt.show()
```
The MNL tells a similar story to the counts, but with important refinements. Marketing Analytics (495) commands a dominant share — roughly **2.8 times** the equal-split benchmark — reflecting not just how often it was picked best, but that it was picked best even when sharing screens with strong competition. Analytics Consulting (444) and Mktg/Fin/Ops (451) both fall well below the equal-share line.
**MLE vs Counts: where do they agree?** The top two and bottom two classes are in the same order. **Where do they differ?** The MNL tends to compress the middle of the ranking — classes with similar counts scores can get noticeably different $\beta$ estimates once the model accounts for which opponents each class faced.
---
## MNL via Bayesian Estimation
Maximum likelihood gives us point estimates and standard errors, which is often enough. But sometimes we want to ask harder questions: *what is the probability that Marketing Analytics has a higher share than Customer Analytics?* or *what is the 95% range of plausible shares for the Capstone?* These are questions about the posterior distribution over parameters, not just about point estimates.
The Bayesian approach treats $\boldsymbol{\beta}$ as a random vector and updates a prior belief with the observed likelihood:
$$
\pi(\boldsymbol{\beta} \mid \boldsymbol{y}) \;\propto\; \underbrace{L(\boldsymbol{\beta})}_{\text{likelihood}} \cdot \underbrace{\pi(\boldsymbol{\beta})}_{\text{prior}}
$$
We use a weakly informative prior: $\boldsymbol{\beta} \sim \mathcal{N}(\mathbf{0},\; 10 \cdot I)$. This says "we have no strong prior belief about which class students prefer, but we'd be surprised to see utility values outside the range $[-6, +6]$ or so."
To sample from this posterior, we use the **random-walk Metropolis-Hastings** algorithm. At each step, we propose a small random jump from the current position, compute the posterior ratio, and accept or reject based on that ratio. Over many iterations, accepted draws trace out the posterior distribution.
```{python}
#| echo: true
def log_prior(beta_free):
"""Weakly informative N(0, 10*I) prior on the 9 free parameters."""
return -0.5 * np.sum(beta_free**2 / 10.0)
def log_posterior(beta_free):
return log_lik(beta_free) + log_prior(beta_free)
def metropolis_hastings(beta0, n_iter, step):
K = len(beta0)
draws = np.zeros((n_iter, K))
beta = beta0.copy()
lp = log_posterior(beta)
n_accept = 0
for t in range(n_iter):
beta_star = beta + np.random.normal(0, step, size=K)
lp_star = log_posterior(beta_star)
if np.log(np.random.uniform()) < lp_star - lp:
beta = beta_star
lp = lp_star
n_accept += 1
draws[t] = beta
return draws, n_accept / n_iter
```
```{python}
#| echo: true
N_ITER = 11_000
BURN_IN = 2_750 # discard first 25%
STEP = 0.08 # tuned to give ~28% acceptance rate
np.random.seed(99) # local re-seed so MCMC is reproducible regardless of bootstrap state
draws, accept_rate = metropolis_hastings(
beta0 = result.x, # start from MLE (faster warm-up)
n_iter = N_ITER,
step = STEP,
)
print(f"Acceptance rate: {accept_rate:.1%} (target: 25–40%)")
posterior = draws[BURN_IN:] # post-burn-in draws
```
### Convergence Diagnostics
A healthy MCMC chain looks like a "fuzzy caterpillar" — it mixes quickly and doesn't drift. Slow trends or flat sections are warning signs.
```{python}
#| echo: false
#| fig-cap: "Trace plots for three β parameters after burn-in. A well-mixed chain looks like a fuzzy caterpillar, staying in a stable band without long drifts."
items_to_plot = [1, 4, 8] # β for items 2, 5, 9 (0-indexed in draws)
item_names = [short_labels[i+1] for i in items_to_plot]
fig, axes = plt.subplots(3, 1, figsize=(9, 6), sharex=True)
for ax, idx, name in zip(axes, items_to_plot, item_names):
ax.plot(posterior[:, idx], color=BLUE, alpha=0.6, linewidth=0.4)
ax.axhline(posterior[:, idx].mean(), color=RED, linewidth=1.5,
linestyle="--", label=f"Posterior mean = {posterior[:, idx].mean():.2f}")
ax.set_ylabel("β", fontsize=9)
ax.set_title(name, fontsize=10)
ax.legend(fontsize=8, frameon=False)
axes[-1].set_xlabel("MCMC iteration (post burn-in)")
fig.suptitle("Trace Plots — Post-Burn-In MCMC Draws", fontsize=12)
plt.tight_layout()
plt.show()
```
The chains mix well. Each parameter stays within a stable band with no long-run drift, which gives us confidence that the sampler has converged.
### Posterior Summaries
```{python}
#| echo: true
# Posterior mean and 95% credible intervals
beta_post_mean = np.concatenate([[0.0], posterior.mean(axis=0)])
beta_post_lo = np.concatenate([[0.0], np.percentile(posterior, 2.5, axis=0)])
beta_post_hi = np.concatenate([[0.0], np.percentile(posterior, 97.5, axis=0)])
# Posterior shares: compute share for EVERY draw, then average
all_betas = np.column_stack([np.zeros(len(posterior)), posterior])
all_exp = np.exp(all_betas)
all_shares = all_exp / all_exp.sum(axis=1, keepdims=True)
shares_bayes_mean = all_shares.mean(axis=0)
shares_bayes_lo = np.percentile(all_shares, 2.5, axis=0)
shares_bayes_hi = np.percentile(all_shares, 97.5, axis=0)
```
```{python}
#| echo: false
bayes_df = pd.DataFrame({
"Class": [short_labels[i] for i in range(1, 11)],
"Post. Mean β": beta_post_mean.round(3),
"95% CI": ["reference"] + [f"[{lo:.3f}, {hi:.3f}]"
for lo, hi in zip(beta_post_lo[1:], beta_post_hi[1:])],
"Post. Mean Share": (shares_bayes_mean * 100).round(2),
}).sort_values("Post. Mean Share", ascending=False).reset_index(drop=True)
(
GT(bayes_df)
.tab_header(
title="MNL via Bayesian Estimation",
subtitle="Posterior means, 95% credible intervals, and posterior-mean shares of preference"
)
.tab_style(style=style.text(weight="bold"), locations=loc.column_labels())
.tab_style(
style=style.fill(color="#eff6ff"),
locations=loc.body(rows=[0, 1, 2])
)
.tab_style(
style=style.fill(color="#fff1f2"),
locations=loc.body(rows=[7, 8, 9])
)
)
```
```{python}
#| echo: false
#| fig-cap: "Posterior-mean shares with 95% credible intervals. The bars show the average share across all MCMC draws; the error bars show the 2.5th–97.5th percentile range."
bayes_plot = pd.DataFrame({
"label": [short_labels[i] for i in range(1, 11)],
"share": shares_bayes_mean * 100,
"lo": shares_bayes_lo * 100,
"hi": shares_bayes_hi * 100,
}).sort_values("share", ascending=True)
fig, ax = plt.subplots(figsize=(9, 5.5))
colors = [GREEN if s >= bayes_plot["share"].median() else RED for s in bayes_plot["share"]]
ax.barh(bayes_plot["label"], bayes_plot["share"], color=colors, alpha=0.8, height=0.6)
ax.errorbar(
bayes_plot["share"],
bayes_plot["label"],
xerr=[bayes_plot["share"] - bayes_plot["lo"],
bayes_plot["hi"] - bayes_plot["share"]],
fmt="none", color="#374151", capsize=4, linewidth=1.2,
)
ax.axvline(10, color=GRAY, linestyle="--", linewidth=1, alpha=0.6, label="Equal share (10%)")
ax.set_xlabel("Posterior-Mean Share of Preference (%)")
ax.set_title("Bayesian MNL Shares with 95% Credible Intervals")
ax.legend(fontsize=9, frameon=False)
plt.tight_layout()
plt.show()
```
The Bayesian and MLE results are closely aligned, as we'd expect with 680 tasks and a diffuse prior. The key advantage of the Bayesian output is the credible intervals on *shares* — quantities that are nonlinear functions of the raw parameters. Computing these intervals from MLE would require the delta method; in the Bayesian framework, we simply push every posterior draw through the softmax and take quantiles. Easy and exact.
**Posterior SDs vs MLE standard errors.** With a diffuse prior and a large sample, the two should be nearly identical — and they are. The MLE standard errors range from 0.137 to 0.146; the posterior standard deviations (the standard deviation of the post-burn-in draws) range from 0.137 to 0.160. The posterior SDs are slightly *larger* than the MLE SEs for some parameters. This is expected: the Hessian-based SE is a local quadratic approximation at the mode, while the MCMC posterior captures the full distribution including any asymmetry in the tails. With 680 observations the difference is small, but it would grow with fewer data points where the likelihood surface is less bowl-shaped.
---
## Comparing the Three Methods
```{python}
#| echo: false
# Build comparison table
comp = pd.DataFrame({
"item": range(1, 11),
"Class": [short_labels[i] for i in range(1, 11)],
})
counts_map = item_counts.set_index("Item")[["score"]].rename(columns={"score": "Counts Score"})
counts_map["Counts Score"] = counts_map["Counts Score"].round(3)
comp = comp.merge(counts_map, left_on="item", right_index=True)
comp = comp.sort_values("Counts Score", ascending=False).reset_index(drop=True)
comp["Counts Rank"] = range(1, 11)
mle_map = pd.Series(shares_mle * 100, index=range(1, 11)).rename("MLE Share (%)")
comp = comp.merge(mle_map.round(2), left_on="item", right_index=True)
comp = comp.sort_values("MLE Share (%)", ascending=False).reset_index(drop=True)
comp["MLE Rank"] = range(1, 11)
bayes_map = pd.Series(shares_bayes_mean * 100, index=range(1, 11)).rename("Bayes Share (%)")
comp = comp.merge(bayes_map.round(2), left_on="item", right_index=True)
comp = comp.sort_values("Bayes Share (%)", ascending=False).reset_index(drop=True)
comp["Bayes Rank"] = range(1, 11)
comp = comp.sort_values("MLE Rank").reset_index(drop=True)
comp_display = comp[["Class","Counts Score","Counts Rank","MLE Share (%)","MLE Rank","Bayes Share (%)","Bayes Rank"]]
(
GT(comp_display)
.tab_header(
title="Side-by-Side Comparison of All Three Methods",
subtitle="Sorted by MLE rank"
)
.tab_style(style=style.text(weight="bold"), locations=loc.column_labels())
.tab_style(
style=style.fill(color="#dcfce7"),
locations=loc.body(rows=[0, 1, 2])
)
.tab_style(
style=style.fill(color="#fee2e2"),
locations=loc.body(rows=[7, 8, 9])
)
)
```
```{python}
#| echo: false
#| fig-cap: "Three panels, one per method, all sharing the same class order (sorted by MLE rank). The top-ranked and bottom-ranked classes are consistent across all three approaches."
order = comp.sort_values("MLE Rank")["Class"].tolist()
y_pos = list(range(len(order)))
counts_vals = [comp[comp["Class"]==c]["Counts Score"].values[0] for c in order]
mle_vals = [comp[comp["Class"]==c]["MLE Share (%)"].values[0] for c in order]
bayes_vals = [comp[comp["Class"]==c]["Bayes Share (%)"].values[0] for c in order]
fig, axes = plt.subplots(1, 3, figsize=(15, 6))
def draw_panel(ax, values, title, color, show_labels):
ax.barh(y_pos, values, color=color, alpha=0.8, height=0.7)
ax.set_yticks(y_pos)
if show_labels:
ax.set_yticklabels(order, fontsize=8)
else:
ax.set_yticklabels([])
ax.invert_yaxis()
ax.set_title(title, fontsize=11, fontweight="bold")
draw_panel(axes[0], counts_vals, "Counts\n(% Best − % Worst)", TEAL, show_labels=True)
draw_panel(axes[1], mle_vals, "MLE\n(Share of Preference %)", BLUE, show_labels=False)
draw_panel(axes[2], bayes_vals, "Bayesian\n(Share of Preference %)", ORANGE, show_labels=False)
axes[0].set_xlabel("Score")
axes[1].set_xlabel("Share (%)")
axes[2].set_xlabel("Share (%)")
fig.suptitle("All Three Methods — Same Class Order (MLE Rank)", fontsize=13)
plt.tight_layout()
plt.show()
```
**Where the three methods agree.** The ranking is rock-solid across all three approaches: Marketing Analytics (495) is first, **Business Analytics (453)** is second, and **Customer Analytics (455)** is third in every method. The same stability holds at the bottom: Analytics Consulting (444) and Mktg/Fin/Ops (451) occupy the last two positions regardless of method. When the signal is strong — a course that's genuinely loved or genuinely disliked — all three methods converge cleanly.
**Where they disagree.** With this dataset, the three methods land on virtually identical rankings from top to bottom. That's actually informative: it tells us the count of best and worst picks is already a very good signal for these data, and the MNL's adjustments for lineup difficulty don't shift enough items to change the order. In general — with noisier data, fewer respondents, or closer competition between middle-ranked items — you would expect more disagreement in the middle tiers.
**What the MNL adds over counts.** The MNL uses every item on every screen, not just the one that was chosen. A class picked best while competing against three disliked classes gets less credit than one picked best in a tough lineup. The counts analysis can't distinguish these cases; the MNL can.
**What Bayes adds over MLE.** The MLE gives one number per parameter. Bayes gives a distribution. That distribution lets us answer questions like "how confident are we that Marketing Analytics's true share exceeds 20%?" or "what's the probability that Customer Analytics outranks Business Analytics?" — all of which flow naturally out of the MCMC draws.
---
## Discussion
If an academic advisor asked "which MSBA courses do students value most?", the answer from all three methods is consistent: **Marketing Analytics (MGTA 495)** is by far the most preferred, attracting roughly 28% of simulated best-picks if all 10 courses competed simultaneously — nearly **three times** the equal-share benchmark of 10%. **Business Analytics (453)** and **Customer Analytics (455)** round out the top tier. Students clearly gravitate toward courses with direct, career-ready analytics applications.
At the other end, **Analytics Consulting (444)** and **Mktg/Fin/Ops (451)** are consistently last — both attract far more "worst" picks than "best" picks whenever they appear on screen. The Capstone (454), interestingly, lands almost exactly in the middle with a near-zero net score: students are split, picking it best and worst in nearly equal measure, suggesting it is polarizing rather than uniformly disliked.
**Which method would you use when?** The counts analysis is an executive dashboard: fast, transparent, and easy to explain to anyone. The MLE is the right choice when you need a single defensible number to report — a $\hat\beta$ with a standard error is something every statistician understands. The Bayesian approach earns its extra complexity when you need uncertainty on derived quantities (shares, ratios, "what if?" simulations) or when you plan to extend the model to individual-level preferences — a natural next step would be a hierarchical (random-effects) MNL that estimates a separate $\boldsymbol{\beta}$ for each student.
**Caveats.** The survey was completed by 85 MSBA students — a self-selected, program-specific sample. Preferences may shift depending on semester standing, prior work experience, or the specific instructor teaching a course that year. Item 11 appeared in a subset of tasks alongside a single class but with no worst pick, suggesting it may be an anchor or "none" option; excluding those tasks was the right call for a clean MNL fit.
If I had more time, I'd run the **Latent-Class MNL** — fitting two or three segments of students with different $\boldsymbol{\beta}$ vectors — to see whether there is a subgroup of students who rate the more technical courses (AI Math, Large Data) above the applied analytics courses. That heterogeneity is invisible in any of the three aggregate methods used here.