Skip to contents

This document provides a detailed mathematical description of the multinomial logit (MNL) model as implemented in src/mnlogit.cpp.

Notation

Symbol Description
i=1,…,Ni = 1, \ldots, N Index for individuals (choice situations)
j=1,…,Jij = 1, \ldots, J_i Index for alternatives available to individual ii
CiC_i Choice set for situation ii; it contains Mi=JiM_i=J_i inside alternatives and, when requested, the implicit outside alternative 0
jij_i The alternative chosen by individual ii
wiw_i Weight for individual ii
XijX_{ij} Row vector of covariates for individual ii and alternative jj (1×K1 \times K)
β\beta Coefficient vector (K×1K \times 1)
δj\delta_j Alternative-specific constant (ASC) for alternative jj
VijV_{ij} Systematic (deterministic) utility
PijP_{ij} Probability that individual ii chooses alternative jj

1. Model Definition

1.1 Utility Specification

The utility that individual ii derives from alternative jj is:

Uij=Vij+εij U_{ij} = V_{ij} + \varepsilon_{ij}

where the systematic utility is:

Vij=Xijβ+δj V_{ij} = X_{ij}\beta + \delta_j

and εij\varepsilon_{ij} is an i.i.d. Type I Extreme Value (Gumbel) error term with location 0 and scale 1.

1.2 Alternative-Specific Constants (ASCs)

The ASC parameters δj\delta_j capture the average effect of unobserved factors for each alternative. For identification, one ASC must be normalized:

  • Without outside option (include_outside_option = FALSE): The first inside alternative’s ASC is fixed to zero (δ1=0\delta_1 = 0). The parameter vector contains J−1J-1 free ASC parameters.

  • With outside option (include_outside_option = TRUE): The outside option (alternative 0) has utility Vi0=0V_{i0} = 0, serving as the reference. All JJ inside alternatives have free ASC parameters.

Code reference: src/mnlogit.cpp


2. Log-Likelihood Function

2.1 Choice Probability

Under the Type I Extreme Value distribution assumption, the probability that individual ii chooses alternative jj follows the multinomial logit (softmax) formula:

Pij=exp⁡(Vij)∑k=1Jiexp⁡(Vik) P_{ij} = \frac{\exp(V_{ij})}{\sum_{k=1}^{J_i} \exp(V_{ik})}

If an outside option is included, the denominator includes exp⁡(Vi0)=exp⁡(0)=1\exp(V_{i0}) = \exp(0) = 1. The outside option is implicit: it has no row in XX, no free coefficient, and is prepended internally to the vector of inside utilities. Global alternative IDs (alt_idx) need not equal an alternative’s local row position in CiC_i; the former map ASCs across situations, whereas choice_idx records the local chosen position (or 0 for the outside option).

Code reference: src/mnlogit.cpp

2.2 Log-Likelihood

The log-likelihood is the weighted sum of the log-probabilities of the observed choices:

ℓ(θ)=∑i=1Nwilog⁡Piji \ell(\theta) = \sum_{i=1}^{N} w_i \log P_{ij_i}

where θ=(β,δ)\theta = (\beta, \delta) is the full parameter vector and jij_i is the alternative chosen by individual ii.

Expanding the log-probability:

log⁡Piji=Viji−log⁡(∑k=1Jiexp(Vik)) \log P_{ij_i} = V_{ij_i} - \log\left(\sum_{k=1}^{J_i} \exp(V_{ik})\right)

Code reference: src/mnlogit.cpp

2.3 Log-Sum-Exp Trick for Numerical Stability

To prevent numerical overflow when computing the denominator, the implementation subtracts the maximum utility before exponentiation:

∑kexp⁡(Vik)=exp⁡(Vmax)∑kexp⁡(Vik−Vmax) \sum_k \exp(V_{ik}) = \exp(V_{\max}) \sum_k \exp(V_{ik} - V_{\max})

where Vmax=max⁡kVikV_{\max} = \max_k V_{ik}.

This gives:

log⁡(∑kexp(Vik))=Vmax+log⁡(∑kexp(Vik−Vmax)) \log\left(\sum_k \exp(V_{ik})\right) = V_{\max} + \log\left(\sum_k \exp(V_{ik} - V_{\max})\right)

The log-probability becomes:

log⁡Piji=(Viji−Vmax)−log⁡(∑kexp(Vik−Vmax)) \log P_{ij_i} = (V_{ij_i} - V_{\max}) - \log\left(\sum_k \exp(V_{ik} - V_{\max})\right)

Code reference: src/mnlogit.cpp


3. Gradient Computation

3.1 General Formula

The gradient of the log-probability of the chosen alternative with respect to utility is:

∂log⁡Piji∂Via=𝟏a=ji−Pia \frac{\partial \log P_{ij_i}}{\partial V_{ia}} = \mathbf{1}_{a = j_i} - P_{ia}

where 𝟏a=ji\mathbf{1}_{a = j_i} is the indicator function (1 if aa is the chosen alternative, 0 otherwise).

3.2 Gradient with Respect to β\beta

Since ∂Vij∂β=XijT\frac{\partial V_{ij}}{\partial \beta} = X_{ij}^T, the contribution to the gradient from individual ii is:

∂ℓi∂β=wi∑j=1Ji(𝟏j=ji−Pij)XijT \frac{\partial \ell_i}{\partial \beta} = w_i \sum_{j=1}^{J_i} \left(\mathbf{1}_{j = j_i} - P_{ij}\right) X_{ij}^T

This simplifies to:

∂ℓi∂β=wi(XijiT−∑j=1JiPijXijT) \frac{\partial \ell_i}{\partial \beta} = w_i \left( X_{ij_i}^T - \sum_{j=1}^{J_i} P_{ij} X_{ij}^T \right)

The full gradient is:

∇βℓ=∑i=1Nwi(XijiT−∑j=1JiPijXijT) \nabla_\beta \ell = \sum_{i=1}^{N} w_i \left( X_{ij_i}^T - \sum_{j=1}^{J_i} P_{ij} X_{ij}^T \right)

Implementation note. Define the difference vector di∈ℝJid_i \in \mathbb{R}^{J_i} with entries dij=𝟏j=ji−Pijd_{ij} = \mathbf{1}_{j = j_i} - P_{ij}. Then the sum above is XiTdiX_i^T d_i, a single BLAS matrix-vector product (X_i.t() * diff_vec). When an outside option is present, XiX_i covers only the MiM_i inside alternatives and did_i is sliced accordingly (diff_vec.subvec(1, m_i)).

Code reference: src/mnlogit.cpp

3.3 Gradient with Respect to δ\delta

Since ∂Vij∂δa=𝟏j=a\frac{\partial V_{ij}}{\partial \delta_a} = \mathbf{1}_{j = a}, the contribution to the gradient from individual ii for alternative aa is:

∂ℓi∂δa=wi(𝟏ji=a−Pia) \frac{\partial \ell_i}{\partial \delta_a} = w_i \left(\mathbf{1}_{j_i = a} - P_{ia}\right)

The gradient is computed only for the free ASC parameters: - Without outside option: δ1=0\delta_1 = 0 (fixed), so we compute for a=2,…,Ja = 2, \ldots, J - With outside option: we compute for all inside alternatives a=1,…,Ja = 1, \ldots, J

The delta gradient reuses the same difference vector did_i computed for the beta block; its entries are scattered into the appropriate positions of the gradient vector via an irregular index mapping.

Code reference: src/mnlogit.cpp


4. Hessian Computation

4.1 Analytical Hessian — Full-Vector Form

The Hessian of the log-likelihood for individual ii is:

Hi=∂2ℓi∂θ∂θ′=−wi[∑a∈AiPiaZaZaT−(∑a∈AiPiaZa)(∑a∈AiPiaZa)T]H_i = \frac{\partial^2 \ell_i}{\partial \theta \,\partial \theta'} = -w_i \left[ \sum_{a \in A_i} P_{ia} Z_a Z_a^T - \left(\sum_{a \in A_i} P_{ia} Z_a\right)\left(\sum_{a \in A_i} P_{ia} Z_a\right)^T \right]

where AiA_i is individual ii’s choice set (including the outside option when present) and Za∈ℝK+JδZ_a \in \mathbb{R}^{K + J_\delta} is the “score vector” for alternative aa:

Za=(xaed(a))Z_a = \begin{pmatrix} x_a \\ e_{d(a)} \end{pmatrix}

Here xa∈ℝKx_a \in \mathbb{R}^K is the covariate vector for alternative aa, ed(a)e_{d(a)} is the standard basis vector in ℝJδ\mathbb{R}^{J_\delta} indicating the free ASC position d(a)d(a) for alternative aa, and JδJ_\delta is the number of free ASC parameters (J−1J-1 without outside option, JJ with outside option). For the outside option itself, Z0=0Z_0 = 0 (no covariates, no free ASC).

This can be written compactly as:

Hi=−wiVar⁡Pi(Z)H_i = -w_i \operatorname{Var}_{P_i}(Z)

where the variance is taken under the discrete distribution Pi=(Pi0,Pi1,…,PiJi)P_i = (P_{i0}, P_{i1}, \ldots, P_{iJ_i}). The full Hessian is ∇θ2ℓ=∑i=1NHi\nabla^2_\theta \ell = \sum_{i=1}^N H_i and the function returns −∇θ2ℓ-\nabla^2_\theta \ell (Hessian of the negative log-likelihood).

4.2 Block Decomposition

The parameter vector is θ=(β,δ)\theta = (\beta, \delta) with β∈ℝK\beta \in \mathbb{R}^K (covariate coefficients) and δ∈ℝJδ\delta \in \mathbb{R}^{J_\delta} (free ASC parameters). Because ZaZ_a has at most K+1K+1 nonzero entries — KK in the β\beta block and at most one in the δ\delta block — the dense nparams×nparamsn_\mathrm{params} \times n_\mathrm{params} outer product ZaZaTZ_a Z_a^T has only three nontrivial submatrices. Summing over alternatives, the individual Hessian decomposes into three blocks:

−Hi/wi=(𝐁𝐁i𝐁𝐃i𝐁𝐃iT𝐃𝐃i)-H_i / w_i = \begin{pmatrix} \mathbf{BB}_i & \mathbf{BD}_i \\ \mathbf{BD}_i^T & \mathbf{DD}_i \end{pmatrix}

Beta-beta block (K×KK \times K, symmetric):

𝐁𝐁i=∑a=1mipiaxaxaT−μβμβT,μβ=∑a=1mipiaxa\mathbf{BB}_i = \sum_{a=1}^{m_i} p_{ia} \, x_a x_a^T - \mu_\beta \mu_\beta^T, \qquad \mu_\beta = \sum_{a=1}^{m_i} p_{ia} \, x_a

where the sum runs over the mim_i inside alternatives only (since Z0=0Z_0 = 0). This is the probability-weighted covariance of the covariates:

𝐁𝐁i=𝔼Pi[xxT]−𝔼Pi[x]𝔼Pi[x]T=Cov⁡Pi(x)\mathbf{BB}_i = \mathbb{E}_{P_i}[x x^T] - \mathbb{E}_{P_i}[x]\, \mathbb{E}_{P_i}[x]^T = \operatorname{Cov}_{P_i}(x)

Delta-delta block (Jδ×JδJ_\delta \times J_\delta, symmetric):

𝐃𝐃i=diag⁡(μδ)−μδμδT,μδ[r]=∑{a:d(a)=r}pia\mathbf{DD}_i = \operatorname{diag}(\mu_\delta) - \mu_\delta \mu_\delta^T, \qquad \mu_\delta[r] = \sum_{\{a : d(a)=r\}} p_{ia}

When a situation lists an alternative once, μδ[r]\mu_\delta[r] is that alternative’s choice probability; rows that repeat an alternative add their probabilities into its one entry. The diagonal of 𝐃𝐃i\mathbf{DD}_i is μδ⊙(1−μδ)\mu_\delta \odot (1 - \mu_\delta) and the off-diagonal (r,s)(r,s) entry is −μδ[r]μδ[s]-\mu_\delta[r]\,\mu_\delta[s]; μδ\mu_\delta is zero off the constants of the alternatives the situation offers.

Beta-delta block (K×JδK \times J_\delta, generally not symmetric):

𝐁𝐃i[:,r]=∑{a:d(a)=r}piaxa−μβμδ[r]\mathbf{BD}_i[:,r] = \sum_{\{a : d(a)=r\}} p_{ia} \, x_a - \mu_\beta \, \mu_\delta[r]

This block measures the probability-weighted covariance between the covariates and the ASC indicators.

Why the decomposition equals the full-vector form. Partition Za=(xaT,ed(a)T)TZ_a = (x_a^T, e_{d(a)}^T)^T. Then:

∑apiaZaZaT=(∑apiaxaxaT∑apiaxaed(a)T∑apiaed(a)xaT∑apiaed(a)ed(a)T)\sum_a p_{ia} Z_a Z_a^T = \begin{pmatrix} \sum_a p_{ia} x_a x_a^T & \sum_a p_{ia} x_a e_{d(a)}^T \\ \sum_a p_{ia} e_{d(a)} x_a^T & \sum_a p_{ia} e_{d(a)} e_{d(a)}^T \end{pmatrix}

(∑apiaZa)(∑apiaZa)T=(μβμβTμβμδTμδμβTμδμδT)\left(\sum_a p_{ia} Z_a\right)\left(\sum_a p_{ia} Z_a\right)^T = \begin{pmatrix} \mu_\beta \mu_\beta^T & \mu_\beta \mu_\delta^T \\ \mu_\delta \mu_\beta^T & \mu_\delta \mu_\delta^T \end{pmatrix}

Subtracting block by block yields exactly 𝐁𝐁i\mathbf{BB}_i, 𝐁𝐃i\mathbf{BD}_i, 𝐃𝐃i\mathbf{DD}_i above.

4.3 Compact Blocks and Accumulation

Because μδ\mu_\delta is zero off the situation’s own constants, 𝐁𝐃i\mathbf{BD}_i and 𝐃𝐃i\mathbf{DD}_i vanish outside them: situation ii’s Hessian lives on its compact block, the KK coefficients and the ai≤mia_i \le m_i free constants of the alternatives it offers (in increasing order). The kernel forms 𝐁𝐁i\mathbf{BB}_i (its upper triangle), 𝐁𝐃i\mathbf{BD}_i (K×aiK \times a_i) and the constants’ block (ai×aia_i \times a_i, from the vector μδ\mu_\delta as it is added) and adds wiw_i times them into the upper triangle of an n×nn \times n accumulator, which is mirrored once after the loop. A situation costs O(miK2+aiK+ai2)O(m_iK^2 + a_iK + a_i^2), whatever the number of alternatives JJ; adding its dense 𝐁𝐃i\mathbf{BD}_i and 𝐃𝐃i\mathbf{DD}_i cost O(KJδ+Jδ2)O(KJ_\delta + J_\delta^2), which dominated with thousands of constants (281 s for 24,560 situations and 2,611 parameters at one thread, against 0.13 s for the compact blocks).

Each thread adds into its own packed upper triangle while the threads’ triangles fit in a budget (2 GiB by default; the kernels’ internal acc_bytes), and above it into the shared result: the coefficients’ rows through small private buffers, the constants’ block by atomic additions. Both are allocated before the parallel loop, and the kernel first compares an upper estimate of its memory with options(choicer.max_memory) or the machine’s physical memory, stopping with an error that names the number of threads that fits.

Non-finite values. The dense form subtracted μμT\mu\mu^T over every parameter, so a non-finite mean (overflowing utilities, a covariate near the largest double) reached its row’s entries outside the block as 0⋅mean0 \cdot \text{mean}, NaN; and a non-finite weight multiplied the zeros outside the block. The compact kernel adds those values where the dense form did: the spread of a non-finite mean during the loop (once per row and thread for a NaN mean, which turns the whole row NaN), and the spread of a non-finite weight after it.

4.4 ASC Normalization and Indexing

The free-delta position d(a)d(a) for inside alternative aa (0-based local index within individual ii’s choice set, with a∈{0,…,mi−1}a \in \{0,\ldots,m_i-1\}) is:

d(a)={alt_idx0_i[a]if 𝚒𝚗𝚌𝚕𝚞𝚍𝚎_𝚘𝚞𝚝𝚜𝚒𝚍𝚎_𝚘𝚙𝚝𝚒𝚘𝚗=TRUEalt_idx0_i[a]−1if 𝚒𝚗𝚌𝚕𝚞𝚍𝚎_𝚘𝚞𝚝𝚜𝚒𝚍𝚎_𝚘𝚙𝚝𝚒𝚘𝚗=FALSE and alt_idx0_i[a]>0(skip — no ASC contribution)if 𝚒𝚗𝚌𝚕𝚞𝚍𝚎_𝚘𝚞𝚝𝚜𝚒𝚍𝚎_𝚘𝚙𝚝𝚒𝚘𝚗=FALSE and alt_idx0_i[a]=0d(a) = \begin{cases} \text{alt\_idx0\_i}[a] & \text{if } \texttt{include\_outside\_option} = \text{TRUE} \\ \text{alt\_idx0\_i}[a] - 1 & \text{if } \texttt{include\_outside\_option} = \text{FALSE and alt\_idx0\_i}[a] > 0 \\ \text{(skip — no ASC contribution)} & \text{if } \texttt{include\_outside\_option} = \text{FALSE and alt\_idx0\_i}[a] = 0 \end{cases}

where alt_idx0_i[a] is the 0-based global alternative ID from alt_idx0. When there is no outside option, the first inside alternative (alt_idx0_i[a]=0\text{alt\_idx0\_i}[a] = 0) has its ASC fixed to zero by the identification convention, so it contributes no free ASC entry and is skipped in the BD and DD accumulation.

Implementation note. Each term is formed as the dense form formed it — every product of means rounded before it is subtracted — and added in the same order, so at one thread the compact Hessian is the dense one bit for bit, except where the dense form’s BLAS call fused a product into the subtraction (in designs with a single coefficient or a single constant), where the two differ in their last bits.

Code reference: src/mnlogit.cpp, function mnl_loglik_hessian_parallel.


5. Elasticity Computation

5.1 Elasticity Definitions

The elasticity measures the percentage change in choice probability with respect to a percentage change in an attribute. For attribute kk with coefficient βk\beta_k:

Own-Elasticity (elasticity of PijP_{ij} with respect to xijkx_{ijk}):

Ejjk=∂Pij∂xijk⋅xijkPij=βk⋅xijk⋅(1−Pij) E_{jj}^k = \frac{\partial P_{ij}}{\partial x_{ijk}} \cdot \frac{x_{ijk}}{P_{ij}} = \beta_k \cdot x_{ijk} \cdot (1 - P_{ij})

Cross-Elasticity (elasticity of PijP_{ij} with respect to ximkx_{imk} where m≠jm \neq j):

Ejmk=∂Pij∂ximk⋅ximkPij=−βk⋅ximk⋅Pim E_{jm}^k = \frac{\partial P_{ij}}{\partial x_{imk}} \cdot \frac{x_{imk}}{P_{ij}} = -\beta_k \cdot x_{imk} \cdot P_{im}

5.2 Derivation

Starting from the choice probability:

Pij=exp⁡(Vij)∑kexp⁡(Vik) P_{ij} = \frac{\exp(V_{ij})}{\sum_k \exp(V_{ik})}

Taking the derivative with respect to ximkx_{imk}:

∂Pij∂ximk=Pij(𝟏j=m−Pim)βk \frac{\partial P_{ij}}{\partial x_{imk}} = P_{ij} \left( \mathbf{1}_{j=m} - P_{im} \right) \beta_k

For own-elasticity (j=mj = m):

∂Pij∂xijk=Pij(1−Pij)βk \frac{\partial P_{ij}}{\partial x_{ijk}} = P_{ij} (1 - P_{ij}) \beta_k

Therefore:

Ejjk=βk⋅xijk⋅(1−Pij) E_{jj}^k = \beta_k \cdot x_{ijk} \cdot (1 - P_{ij})

For cross-elasticity (j≠mj \neq m):

∂Pij∂ximk=−PijPimβk \frac{\partial P_{ij}}{\partial x_{imk}} = -P_{ij} P_{im} \beta_k

Therefore:

Ejmk=−βk⋅ximk⋅Pim E_{jm}^k = -\beta_k \cdot x_{imk} \cdot P_{im}

5.3 Weighted Average of Individual Elasticities

The implementation computes a weighted average of the individual probability elasticities:

E‾jmk=∑i=1Nwi⋅Eijmk∑i=1Nwi \bar{E}_{jm}^k = \frac{\sum_{i=1}^{N} w_i \cdot E_{ijm}^k}{\sum_{i=1}^{N} w_i}

where EijmkE_{ijm}^k is the elasticity for individual ii.

This estimand is not, in general, the elasticity of the aggregate share sj=∑iwiPij/∑iwis_j=\sum_iw_iP_{ij}/\sum_iw_i. The latter is

∂sj∂xm,kxm,ksj, \frac{\partial s_j}{\partial x_{m,k}}\frac{x_{m,k}}{s_j},

and requires a definition of the common market-level perturbation xm,kx_{m,k} when the attribute varies over individuals. elasticities() deliberately reports the average of individual elasticities above; rows index responding alternatives and columns index perturbed alternatives. With an outside option, index 0 is included in the returned matrix; its attribute value is zero, so the outside-option perturbation column is zero.

Code reference: src/mnlogit.cpp


6. Diversion Ratio Computation

6.1 Definition

The diversion ratio from alternative jj to alternative kk measures the fraction of demand lost by jj that is captured by kk when jj becomes less attractive (e.g., due to a price increase). It is a key metric in antitrust analysis and merger simulation.

DR(j→k)=−∂Qk/∂pj∂Qj/∂pj DR(j \to k) = -\frac{\partial Q_k / \partial p_j}{\partial Q_j / \partial p_j}

where Qj=∑iwiPijQ_j = \sum_i w_i P_{ij} is the (weighted) aggregate demand for alternative jj and pjp_j is the price of jj.

6.2 Derivation for MNL

From the MNL choice probability derivatives (Section 5.2), the demand derivatives with respect to price pjp_j (with coefficient βp\beta_p) are:

∂Qk∂pj=−βp∑i=1NwiPijPik(k≠j) \frac{\partial Q_k}{\partial p_j} = -\beta_p \sum_{i=1}^{N} w_i \, P_{ij} \, P_{ik} \quad (k \neq j)

∂Qj∂pj=βp∑i=1NwiPij(1−Pij) \frac{\partial Q_j}{\partial p_j} = \beta_p \sum_{i=1}^{N} w_i \, P_{ij} \, (1 - P_{ij})

Substituting into the diversion ratio formula:

DR(j→k)=−−βp∑iwiPijPikβp∑iwiPij(1−Pij)=∑iwiPijPik∑iwiPij(1−Pij) DR(j \to k) = -\frac{-\beta_p \sum_i w_i \, P_{ij} \, P_{ik}}{\beta_p \sum_i w_i \, P_{ij} \, (1 - P_{ij})} = \frac{\sum_i w_i \, P_{ij} \, P_{ik}}{\sum_i w_i \, P_{ij} \, (1 - P_{ij})}

The price coefficient βp\beta_p cancels, so the diversion ratio does not depend on which covariate we differentiate with respect to. This is a consequence of the IIA property.

6.3 Aggregate Diversion Ratio Matrix

The implementation computes the full J×JJ \times J diversion ratio matrix DD where:

Dkj=DR(j→k)=∑i=1NwiPijPik∑i=1NwiPij(1−Pij)(k≠j) D_{kj} = DR(j \to k) = \frac{\sum_{i=1}^{N} w_i \, P_{ij} \, P_{ik}}{\sum_{i=1}^{N} w_i \, P_{ij} \, (1 - P_{ij})} \quad (k \neq j)

Djj=0 D_{jj} = 0

6.4 Properties

Column sums equal one. For a given alternative jj, the off-diagonal entries in column jj sum to 1, meaning all diverted demand is accounted for:

∑k≠jDR(j→k)=∑iwiPij∑k≠jPik∑iwiPij(1−Pij)=∑iwiPij(1−Pij)∑iwiPij(1−Pij)=1 \sum_{k \neq j} DR(j \to k) = \frac{\sum_i w_i \, P_{ij} \sum_{k \neq j} P_{ik}}{\sum_i w_i \, P_{ij} (1 - P_{ij})} = \frac{\sum_i w_i \, P_{ij} (1 - P_{ij})}{\sum_i w_i \, P_{ij} (1 - P_{ij})} = 1

where we used ∑k≠jPik=1−Pij\sum_{k \neq j} P_{ik} = 1 - P_{ij}.

IIA proportionality. When all individuals face the same choice set and the same covariates (so PijP_{ij} does not vary across ii), the diversion ratio simplifies to:

DR(j→k)=PjPkPj(1−Pj)=Pk1−Pj=sk1−sj DR(j \to k) = \frac{P_j \, P_k}{P_j (1 - P_j)} = \frac{P_k}{1 - P_j} = \frac{s_k}{1 - s_j}

where sjs_j is the market share of alternative jj. This means diversion is proportional to the receiving alternative’s market share, independent of any characteristics of the losing alternative jj other than its own share. This is a well-known limitation of MNL due to IIA.

6.5 Implementation

The function accumulates two quantities in parallel across individuals:

  1. Numerator matrix: Nkj=∑iwiPijPikN_{kj} = \sum_i w_i \, P_{ij} \, P_{ik} for each pair (k,j)(k, j)
  2. Denominator vector: dj=∑iwiPij(1−Pij)d_j = \sum_i w_i \, P_{ij} \, (1 - P_{ij}) for each jj

The final matrix is computed as Dkj=Nkj/djD_{kj} = N_{kj} / d_j for k≠jk \neq j, with Djj=0D_{jj} = 0, in place in the numerator’s J×JJ \times J sum (§12.3); a column whose denominator is at most 10−1510^{-15} (an alternative no situation offers, say) is set to zero.

Code reference: src/mnlogit.cpp


7. BLP Share Inversion

7.1 Problem Statement

Given target market shares SjS_j (with an outside option, S0S_0 too, all of them summing to one), find the alternative-specific constants δ\delta at which the model’s predicted shares equal them, with β\beta held at its value:

ŝj(δ)=∑iwiPij(δ)∑iwi=Sj∀j \hat{s}_j(\delta) = \frac{\sum_i w_i P_{ij}(\delta)}{\sum_i w_i} = S_j \quad \forall j

where ŝj(δ)\hat{s}_j(\delta) is the predicted market share for alternative jj. With every alternative available in every choice situation, any interior target is attained by a unique δ\delta, up to the normalization below (Berry 1994). Where choice sets differ, attainability restricts the targets (§7.2); a solution, where it exists, is still unique up to that normalization, the logit’s shares being connected substitutes (Berry, Gandhi and Haile 2013).

7.2 Identification and Checks of the Targets

With an outside option, whose utility is normalized to zero, every inside constant is identified. Without one, the shares depend only on differences of constants among alternatives that share choice situations, directly or through others: each such group (a connected component of the graph that links the alternatives through the choice situations of positive weight) identifies its constants up to a common level, and its shares add up to the weight of its situations. Each component’s reference, its smallest alternative code, is held at its start, after the start is normalized by subtracting its first element, so that the first constant is zero.

Targets that no constants attain stop the inversion before any evaluation of the shares, with an error: an alternative offered in no choice situation of positive weight; targets that do not sum to one (the outside share included), or, without an outside option, a component’s targets that do not add up to its situations’ weight, within a relative 1.5×10−81.5 \times 10^{-8} (within it they are rescaled); targets that leave no share to the outside option in a component; and a target not strictly below the weight of the choice situations that offer the alternative, or, without an outside option, not strictly above the weight of those that offer it alone (an alternative alone in its component is exempt: its share is its situations’ weight). These are necessary conditions: a target that passes them may still be unattainable, and the iteration then does not converge.

7.3 The Iteration

Write r=log⁡S−log⁡ŝ(δ)r = \log S - \log \hat{s}(\delta) for the log-share residuals and bb for the base: the outside option, or, without one, the reference of jj’s component. The free constants solve ρj(δ)=rj−rb=0\rho_j(\delta) = r_j - r_b = 0; with an outside option, rj−r0r_j - r_0 is the outside-share correction of Fukasawa (2024). Berry, Levinsohn and Pakes’s (1995) contraction, method = "original", updates δj←δj+rj\delta_j \leftarrow \delta_j + r_j (with the component’s reference held, δj+rj−rb\delta_j + r_j - r_b).

The derivative of ρ\rho in the free constants is

−∂ρj∂δk=1ŝj∂ŝj∂δk+Ckbŝb,Ajj=∂ŝj∂δj=∑iwiPij(1−Pij)∑iwi,Cjb=−∂ŝb∂δj=∑iwiPijPib∑iwi: -\frac{\partial \rho_j}{\partial \delta_k} = \frac{1}{\hat{s}_j}\frac{\partial \hat{s}_j}{\partial \delta_k} + \frac{C_{kb}}{\hat{s}_b}, \qquad A_{jj} = \frac{\partial \hat{s}_j}{\partial \delta_j} = \frac{\sum_i w_i P_{ij}(1 - P_{ij})}{\sum_i w_i}, \qquad C_{jb} = -\frac{\partial \hat{s}_b}{\partial \delta_j} = \frac{\sum_i w_i P_{ij} P_{ib}}{\sum_i w_i}:

a part with a dominant diagonal, Ajj/ŝjA_{jj}/\hat{s}_j, plus a term common to every row, the response of the base’s share. The step, method = "simple", treats the two in turn. A common shift τ\tau of the component’s free constants moves each ρj\rho_j by −hjτ-h_j \tau to first order, where hj=Cjb/ŝj+∑kCkb/ŝbh_j = C_{jb}/\hat{s}_j + \sum_k C_{kb}/\hat{s}_b exactly (the share Jacobian is symmetric and its rows sum to zero), and τ\tau solves ∑jŝj(ρj−hjτ)=0\sum_j \hat{s}_j (\rho_j - h_j \tau) = 0, to first order the shift that matches the base’s share. The rest of each residual takes the exact diagonal of the derivative:

δj←δj+τ+ρj−hjτDj,Dj=Ajjŝj+Cjbŝb. \delta_j \leftarrow \delta_j + \tau + \frac{\rho_j - h_j \tau}{D_j}, \qquad D_j = \frac{A_{jj}}{\hat{s}_j} + \frac{C_{jb}}{\hat{s}_b}.

The diagonal alone misjudges the common shift. Where the base’s share is small and each alternative dominates choice situations of its own, 1−hj/Dj1 - h_j/D_j falls below −1-1 and that step diverges where Berry’s contraction converges: in three choice situations, each won by one of alternatives 2 to 4 (x′βx'\beta of 3 for the winner, −3-3 for the other two and 0 for a rarely chosen alternative 1, with constants (0,1,1,1)(0, 1, 1, 1)), it is −1.82-1.82 at the solution. A choice situation that lists an alternative twice contributes its total probability. One evaluation of the shares gives ŝ\hat{s}, AA and CC together.

Safeguards keep the step from failing where Berry’s contraction converges. A step is at most max⁡(|ρj|,5)\max(|\rho_j|, 5) in magnitude: the scaling may lengthen the unscaled step ρj\rho_j to 5 log units, not beyond (an alternative chosen almost wherever it is offered has a diagonal near zero). In an iteration where a component’s outside share underflows to zero, the step drops the outside correction and the common shift (rjr_j over Ajj/ŝjA_{jj}/\hat{s}_j). An evaluation whose shares are not finite halves the step, up to ten times. An iteration whose best residual has not improved for 30 iterations (a stall) halves its later steps. If its residual at the stall is more than twice the best, the steps diverge, and it first returns to its best point, once per best point; otherwise it goes on from where it is, each such stall doubling the iterations the next one waits for. Going on matters: far from the solution the common shift can strand constants where their shares barely respond (alternatives offered with the base only in situations that others dominate), and the way back can climb for dozens of iterations at a residual above the best so far, a climb that returning to that best point at every stall would never complete. And the scaling can amplify a small residual of an alternative that nearly owns its choice situations, whose diagonal is near zero, into a step that wrecks the shares of its neighbours there; the two then oscillate, and the residual decays too slowly. Berry’s contraction never amplifies a step, so it races the step once the step stops making progress: when 100 iterations fail to halve the best residual (or a trial point’s shares stay non-finite after every halving, and the step stops), the contraction starts from the same start and the two take steps in turn, each with its halvings. The first to reach the tolerance returns. The contraction stops if 100 of its own evaluations of the shares fail to halve its best residual while the step’s best is lower; the step then has 200 iterations at a time to halve its own best residual, and whenever it fails to, the contraction goes on from where it stopped: the step can also carry the constants of alternatives that make up the whole choice set of some choice situations so far down that the residual barely responds to their common level, and then make no progress at all. Where the contraction converges in EE evaluations, the step converges within T+4ET + 4E, and within T+2ET + 2E where the contraction halves its best residual within every 100 of its evaluations, TT being the evaluations before the contraction joined; the bound leaves out the step’s halvings after the contraction joined and any 200 iterations in which the step alone halved its best residual. Berry’s contraction itself, as method = "original", takes only the halving of steps whose shares are not finite.

method = "anderson", the default, accelerates the same step, Anderson acceleration of type II (Walker and Ni 2011). Write f(δ)f(\delta) for the step at δ\delta, and ΔX\Delta X and ΔF\Delta F for the last mm differences (memory, default 10, cut to the number of free constants) between successive iterates and between their steps, newest first. Each iteration solves the least squares min⁡γ∥f−ΔFγ∥2\min_\gamma \|f - \Delta F \gamma\|_2, the combination of past changes in the step that best cancels the current one, and moves to

δ←δ−ΔXγ+(f−ΔFγ), \delta \leftarrow \delta - \Delta X \gamma + \left(f - \Delta F \gamma\right),

the capped step above while there are no differences. On a linear map, undamped and with unlimited memory, this is essentially GMRES (Walker and Ni 2011), so it handles the slow modes of segmented choice sets that the step alone crawls along. The least squares go through a Householder QR of ΔF\Delta F, one per iteration, and the oldest differences are dropped while the triangular factor’s condition estimate, max⁡i|Rii|/min⁡i|Rii|\max_i |R_{ii}| / \min_i |R_{ii}|, exceeds max_condition (default 10810^8). Its safeguards are on the residual, never on a merit function: when five iterations bring no residual below 0.9 times the best so far, or the shares at an extrapolated point are not finite, it clears its differences and takes the plain step from where it is, halved while its shares are not finite; only where its residual has grown past twice the best does it go back to its best point, once per best point, since a path to the solution can climb through larger residuals first (the step’s stalls above). Where a component’s outside share underflows it takes the step unextrapolated, keeping no differences, until the share returns: the step then has another form (no outside correction, no common shift), and its level drifts by about the same amount at every iteration, which the least squares would try to cancel instead of follow. It races the contraction like the step, each of its iterations one evaluation of the shares besides trial points whose shares are not finite (left out of the bound, as the step’s halvings are), so the bound T+4ET + 4E holds for it too.

method = "squarem" extrapolates the step by SQUAREM (Varadhan and Roland 2008), PyBLP’s default. With G(δ)=δ+f(δ)G(\delta) = \delta + f(\delta), each cycle takes δ1=G(δ0)\delta_1 = G(\delta_0) and δ2=G(δ1)\delta_2 = G(\delta_1), sets r=δ1−δ0r = \delta_1 - \delta_0 and v=δ2−2δ1+δ0v = \delta_2 - 2\delta_1 + \delta_0, and moves to

δ0+2αr+α2v,α=∥r∥2/∥v∥2 \delta_0 + 2\alpha r + \alpha^2 v, \qquad \alpha = \|r\|_2 / \|v\|_2

(scheme 3; scheme 1 takes −r′v/v′v-r'v/v'v, scheme 2 −r′r/r′v-r'r/r'v), bounded to [step_min, step_max], 1 and 1 at first; one more step GG from that point starts the next cycle. Each time α\alpha reaches step_max at a point whose residual is finite, the bound is multiplied by step_factor (4), so the extrapolation lengthens while it succeeds; where the shares at an extrapolated point are not finite, the cycle takes δ2\delta_2 instead, and a bound α\alpha had reached is divided by step_factor, not below its start. With these bounds it never steps shorter than δ2\delta_2, so it cannot damp an oscillating step as Anderson’s least squares can. It races the contraction too.

On the 121 simulated designs of choicer’s test bed (multinomial, nested and mixed logits; 2 to 5,000 alternatives; full, regional and chained choice sets; far starts), solved to 10−1210^{-12}, the step converged on every one; where Berry’s contraction converged too (113 designs), the step needed a median 0.36 of its evaluations, and never more than 1.05 times as many; no iteration stalled, and the contraction never joined. On 80 designs built like the example above, solved to 10−1010^{-10}, it did not converge within 3,000 evaluations on one, which it was still approaching (it took 9,472, the contraction’s turns included), and Berry’s contraction failed on 22; where both converged, the step needed a median 0.16 of Berry’s evaluations. On 999 small designs drawn to be hard (3 to 6 alternatives in 2 to 8 choice situations of random sizes, single-alternative ones included; covariates and constants integers in [−10,10][-10, 10] and [−3,3][-3, 3]; half with an outside option), at tolerance 10−810^{-8} and 1,000 evaluations, the step failed on 103 and Berry’s contraction on 592, never where the contraction converged; where both converged, the step needed a median 0.12 of the contraction’s evaluations.

With method = "anderson" the same 121 designs converged in medians of 13, 12 and 16.5 evaluations for the multinomial, nested and mixed logits (32, 18.5 and 174 with "simple"), never more than 1.25 times "simple"’s, and the 24-alternative market of four regions from 10 far starts in 27 to 36 evaluations, where "simple" needed 3,143 to 3,655. On the 999 small hard designs above and 999 more drawn alike it failed on 61, 29 and 20 at 1,000, 20,000 and 200,000 evaluations, against 210, 80 and 39 for "simple", and needed a median 0.45 to 0.48 of "simple"’s evaluations where both converged. On simulated claims-, census- and small-scale data (up to 10710^7 rows), at tolerance 10−810^{-8}, it took 0.25 to 1.03 times "simple"’s time, which made it the default.

7.4 Stopping Rule and Result

The iteration stops at the first evaluation whose residual is at most tol (default 10−1210^{-12}), and returns that point. The residual is max⁡j|rj−rb(j)|\max_j |r_j - r_{b(j)}| without an outside option, b(j)b(j) the reference of jj’s component, and with one max⁡j|rj|\max_j |r_j| together with each component’s outside share’s |r0c||r_{0c}|; every share, the outside option’s included, then matches its target to a relative error of about tol. The error in δ\delta is of order tol times the conditioning of the share equations, which choice sets with few alternatives in common can raise to hundreds or more.

max_iter counts evaluations of the shares (default 1,000; 0 returns the normalized start). When the iteration stops otherwise, at max_iter or at shares that are not finite, it returns the evaluated point of smallest residual and warns with class choicer_blp_unconverged; the condition’s convergence element holds the status, the iterations, the evaluations and the residual.

7.5 The Layout of delta

  1. No outside option. delta has length JJ (the blp() method prepends the normalized zero to the fitted length-(J−1)(J-1) ASC block), and the returned vector’s first element is zero; it is not the length-(J−1)(J-1) free-parameter block.
  2. Outside option. The supplied and returned delta have length JJ and contain the inside alternatives only; target_shares has J+1J + 1 entries, the outside option’s first.
  3. blp(). The method checks the targets in R first (one share per alternative, finite, positive, summing to one), starts from the fitted constants (or delta_init), and returns the J×1J \times 1 matrix with the inside alternatives’ labels as row names and the attribute "convergence": the record of §7.4 (converged, status, iterations, evaluations, residual, tol and method), there whether or not the iteration converged. The exported functions return the bare matrix.

7.6 Evaluating the Shares

After the first evaluation, the probabilities are read from exponentials kept across evaluations wherever those allow it. The first, at δ0\delta^0, keeps for each row eij=exp⁡(xij′β+δj0−ci)e_{ij} = \exp(x_{ij}'\beta + \delta^0_j - c_i), where cic_i is the largest utility in situation ii (with an outside option, its 0 included, so that ei0=exp⁡(−ci)≤1e_{i0} = \exp(-c_i) \le 1 is kept too). An evaluation at δ\delta then forms

Pij(δ)=eijajei0+∑keikak,aj=exp⁡(δj−δj0), P_{ij}(\delta) = \frac{e_{ij}\, a_j}{e_{i0} + \sum_k e_{ik}\, a_k}, \qquad a_j = \exp(\delta_j - \delta^0_j),

(ei0=0e_{i0} = 0 without an outside option): JJ exponentials per evaluation in place of one per row, which takes 0.4 to 0.6 of the time. A row whose exponential underflowed when it was kept can carry at most 2−1022e2d2^{-1022} e^{2d} into a share, where d=max⁡j|δj−δj0|d = \max_j |\delta_j - \delta^0_j|. So an evaluation at d>50d > 50, or one at which some share falls below 253⋅2−1022e2d2^{53} \cdot 2^{-1022} e^{2d} (at most about 10−24810^{-248}), exponentiates every row afresh at δ\delta and keeps those exponentials in place of the old ones; one at a δ\delta that is not finite exponentiates afresh and leaves the kept values as they were. The probabilities agree with those computed afresh to within rounding, so the iteration’s path, and the returned δ\delta, can move as two solutions within tol differ (by about tol times the conditioning, §7.4). The kept values take one double per row (and one per situation with an outside option), within half the memory limit (options(choicer.max_memory = ), else the physical memory) less what the call holds; where they do not fit, every evaluation exponentiates afresh.

The shares sum the probabilities over choice situations, and rounding in those sums sets a floor under the residual that grows with the situations each thread adds: on one thread, with four alternatives in every situation, about 10−1410^{-14} at 2222^{22} situations (about 4.2 million; 7×10−147 \times 10^{-14} with an outside option) and 1.7×10−131.7 \times 10^{-13} at 2.5×1072.5 \times 10^7 (10810^8 rows). Above 2222^{22} situations per thread the sums are compensated (Kahan’s summation; so are the weights’ total, each component’s weight and the weights that bound the targets, §7.2, above 2222^{22} situations in all), which brings the floor to the precision of a double, 2.2×10−162.2 \times 10^{-16} or less at both sizes, for up to 14% more time per evaluation on the exp-space pass and 2.5–4% on the usual pass.

Code reference: src/blp_engine.h (the components, the checks, the step and the stopping rule), src/fixed_point.h (the iteration), MnlBlpModel in src/mnlogit.cpp (the pass) and R/blp.R.


8. Willingness to Pay

8.1 Definition

When one covariate is a price pp with coefficient α=βp\alpha = \beta_p, the willingness to pay (WTP) for attribute kk is the marginal rate of substitution between the attribute and price — the price change that leaves utility unchanged after a unit change in the attribute:

WTPk=−∂V/∂xk∂V/∂p=−βkα \mathrm{WTP}_k = -\frac{\partial V / \partial x_k}{\partial V / \partial p} = -\frac{\beta_k}{\alpha}

Since utility is linear, the same ratio applies to ASCs: the WTP for alternative jj’s unobserved quality is −δj/α-\delta_j / \alpha.

8.2 Delta-Method Standard Errors

WTP is a nonlinear function g(θ)=−θk/θpg(\theta) = -\theta_k / \theta_p of the estimated coefficients. By the delta method, with V̂\hat{V} the estimated coefficient covariance matrix,

Var̂(g(θ̂))=∇gTV̂(k,p)∇g,∇g=(∂g/∂θk∂g/∂θp)=(−1/θpθk/θp2) \widehat{\mathrm{Var}}(g(\hat\theta)) = \nabla g^T \, \hat{V}_{(k,p)} \, \nabla g, \qquad \nabla g = \begin{pmatrix} \partial g / \partial \theta_k \\ \partial g / \partial \theta_p \end{pmatrix} = \begin{pmatrix} -1/\theta_p \\ \theta_k/\theta_p^2 \end{pmatrix}

where V̂(k,p)\hat{V}_{(k,p)} is the 2×22 \times 2 block of V̂\hat{V} for (θk,θp)(\theta_k, \theta_p). The gradient is analytic (exact), so no numerical differentiation is involved. Confidence intervals use the normal approximation:

WTPk±z1−(1−level)/2⋅SÊ \mathrm{WTP}_k \pm z_{1-(1-\text{level})/2} \cdot \widehat{\mathrm{SE}}

Because the estimates and covariance are stored in natural (unscaled) units, no scaling adjustment is needed even when the model was estimated with scale_vars.

Caveat. The ratio of two asymptotically normal estimators has heavy tails when the denominator is imprecisely estimated; the delta-method interval is a first-order approximation that deteriorates as |α|/SE(α̂)|\alpha| / \mathrm{SE}(\hat\alpha) falls. For a weakly identified price coefficient, simulation methods (Krinsky–Robb) or Fieller intervals are more reliable.

Code reference: R/wtp.R


9. Consumer Surplus and the Logsum

9.1 The Logsum (Expected Maximum Utility)

Under Type I Extreme Value errors, the expected maximum utility over individual ii’s choice set is, up to an additive constant (Euler’s constant γ\gamma):

𝔼[maxjUij]=log⁡(∑j∈Ciexp(Vij))+γ≡logsumi+γ \mathbb{E}\left[\max_j U_{ij}\right] = \log\left(\sum_{j \in C_i} \exp(V_{ij})\right) + \gamma \equiv \mathrm{logsum}_i + \gamma

When the model includes an outside option with normalized utility Vi0=0V_{i0} = 0, the sum includes its exp⁡(0)=1\exp(0) = 1 term. The implementation uses the same max-subtraction trick as the log-likelihood (Section 2.3).

9.2 Expected Consumer Surplus

With utility linear in price (no income effects), the marginal utility of income is −α-\alpha (positive for a negative price coefficient), and expected consumer surplus in money units is (Train 2009, Ch. 3):

𝔼[CSi]=logsumi−α \mathbb{E}[CS_i] = \frac{\mathrm{logsum}_i}{-\alpha}

Identification caveat. Like utility itself, the logsum is only defined up to an additive normalization (in particular the ASC normalization), so CS levels are not interpretable on their own. The economically meaningful quantity is the difference between scenarios,

Δ𝔼[CSi]=logsumi(1)−logsumi(0)−α, \Delta \mathbb{E}[CS_i] = \frac{\mathrm{logsum}_i^{(1)} - \mathrm{logsum}_i^{(0)}}{-\alpha},

computed by evaluating the logsum on counterfactual data (newdata) and on the baseline. The normalization constant cancels in the difference. The routine does not impose α<0\alpha<0; interpreting the denominator as positive marginal utility of income requires the analyst to verify the fitted price sign.

9.3 Delta-Method SE for the Mean Consumer Surplus

For the weighted mean m(θ)=∑iwiCSi/∑iwim(\theta) = \sum_i w_i CS_i / \sum_i w_i, the implementation reports a delta-method standard error. The building block is the derivative of the logsum, which by the envelope-style identity is a probability-weighted average of utility derivatives:

∂logsumi∂θr=∑j∈CiPij∂Vij∂θr \frac{\partial\, \mathrm{logsum}_i}{\partial \theta_r} = \sum_{j \in C_i} P_{ij} \, \frac{\partial V_{ij}}{\partial \theta_r}

with ∂Vij/∂βr=xijr\partial V_{ij}/\partial \beta_r = x_{ijr}, ∂Vij/∂δa=𝟏j=a\partial V_{ij}/\partial \delta_a = \mathbf{1}_{j = a}, and a zero contribution from the outside option row (Vi0≡0V_{i0} \equiv 0). Then:

  • For non-price parameters: ∂CSi∂θr=1−α∂logsumi∂θr\dfrac{\partial CS_i}{\partial \theta_r} = \dfrac{1}{-\alpha} \dfrac{\partial\, \mathrm{logsum}_i}{\partial \theta_r}.
  • For the price coefficient, which enters both the logsum and the 1/(−α)1/(-\alpha) factor:

∂CSi∂α=logsumiα2+1−α∑jPijxij,p \frac{\partial CS_i}{\partial \alpha} = \frac{\mathrm{logsum}_i}{\alpha^2} + \frac{1}{-\alpha} \sum_{j} P_{ij}\, x_{ij,p}

The SE is GTV̂G\sqrt{G^T \hat{V} G}, where GG is the weighted average of the per-individual gradient vectors and V̂\hat{V} the full coefficient covariance. All ingredients (PijP_{ij}, VijV_{ij}, XX) come from a single prediction pass.

Code reference: R/surplus.R


10. Goodness of Fit

10.1 McFadden Pseudo R-Squared

R2=1−ℓ(θ̂)ℓ0,Radj2=1−ℓ(θ̂)−Kℓ0 R^2 = 1 - \frac{\ell(\hat\theta)}{\ell_0}, \qquad R^2_{\text{adj}} = 1 - \frac{\ell(\hat\theta) - K}{\ell_0}

where KK is the number of estimated parameters and ℓ0\ell_0 is a null-model log-likelihood. Two nulls are available:

Equal shares (default). Every alternative in individual ii’s choice set is equally likely:

ℓ0=−∑i=1Nwilog⁡(Mi+𝟏outside) \ell_0 = -\sum_{i=1}^{N} w_i \log\left(M_i + \mathbf{1}_{\text{outside}}\right)

where MiM_i is the number of inside alternatives. This closed form is exact for unbalanced choice sets and arbitrary weights.

Market shares. The maximized log-likelihood of a constants-only (ASC-only) model. When every alternative is available in every choice situation, the ASC-only model’s fitted probabilities equal the observed market shares sjs_j, giving the closed form

ℓ0=c∑jNjlog⁡(sj), \ell_0 = c\sum_{j} N_j \log(s_j),

with NjN_j the unweighted choice counts and cc the common observation weight (usually c=1c=1 after normalization). The outside option enters as its own category when present; never-chosen alternatives contribute 0⋅log⁡0=00 \cdot \log 0 = 0. This closed form requires identical choice-set composition across individuals — equal set sizes are not sufficient — and uniform weights; otherwise an ASC-only model must be refit explicitly.

10.2 Hit Rate

The hit rate is the weighted share of choice situations in which the observed choice has the highest predicted probability:

HR=∑iwi𝟏{ĵi=ji}∑iwi,ĵi=arg⁡maxj∈CiPij \mathrm{HR} = \frac{\sum_i w_i \, \mathbf{1}\{\hat{j}_i = j_i\}}{\sum_i w_i}, \qquad \hat{j}_i = \arg\max_{j \in C_i} P_{ij}

With an outside option, the outside good competes for the maximum with probability Pi0=1−∑jPijP_{i0} = 1 - \sum_j P_{ij}, and a predicted outside choice is a hit when the outside good was in fact chosen (ji=0j_i = 0). Ties among inside alternatives are resolved by the first local row (which.max in R). The outside option replaces that inside winner only when its probability is strictly larger, not when tied.

Code reference: R/gof.R


11. Choice-Based Sampling and WESML Weighting

11.1 Endogenous Stratified (Choice-Based) Sampling

Under random (exogenous) sampling each choice situation is drawn independently of its outcome. Under choice-based (endogenous stratified) sampling the strata are defined by the chosen alternative jij_i, and situations are drawn with stratum-specific frequencies — for example, deliberately oversampling individuals who chose a rare alternative. Let Q(j)Q(j) be the population share of alternative jj and H(j)H(j) the sample share of choosers of jj.

For the multinomial logit there is a well-known special case: with a full set of alternative-specific constants, choice-based sampling biases only the constants, and the slope coefficients β\beta remain consistent (Manski & McFadden 1981). Outside that case — most importantly when the ASCs are not saturated, or when the constants themselves are of interest (welfare, counterfactual entry) — naive (unweighted) maximum likelihood is inconsistent for the population parameters, and the weighting below is required.

11.2 The WESML Weighted Log-Likelihood

Manski and Lerman (1977) restore consistency by weighting each situation’s contribution by the ratio of population to sample share of its chosen alternative,

wi=Q(ji)H(ji),ℓW(θ)=∑i=1Nwilog⁡Piji(θ). w_i = \frac{Q(j_i)}{H(j_i)}, \qquad \ell^{W}(\theta) = \sum_{i=1}^{N} w_i \log P_{i j_i}(\theta).

The maximizer θ̂\hat\theta is invariant to multiplying every wiw_i by a common positive constant, so the weights may be normalized to mean 1 without changing the estimates.

11.3 Robust (Sandwich) Variance: the w2w^2 Meat

WESML is a weighted M-estimator solving ∑iwisi(θ̂)=0\sum_i w_i\, s_i(\hat\theta) = 0, where si=∂log⁡Piji/∂θs_i = \partial \log P_{i j_i}/\partial\theta is the per-situation score ($3)and3) andH_i = ^2 P_{i j_i}/,^$ its Hessian ($$4). Its robust (Huber–White) asymptotic variance is the sandwich

V=A−1BA−1,A=∑iwi(−Hi),B=∑iwi2sisi⊤. V = A^{-1} B A^{-1}, \qquad A = \sum_{i} w_i\,(-H_i), \qquad B = \sum_{i} w_i^{2}\, s_i s_i^{\top}.

The weight enters the bread AA linearly, but the meat BB carries the weight squared: the contribution of situation ii to the estimating equation is wisiw_i s_i, so the variance of that contribution involves (wisi)(wisi)⊤=wi2sisi⊤(w_i s_i)(w_i s_i)^{\top} = w_i^{2}\, s_i s_i^{\top}.

This is exactly why the two naive variances are wrong under weighting:

  • the inverse-Hessian A−1A^{-1} assumes the information-matrix equality A=BA = B, which fails once the wiw_i are non-degenerate;
  • the ordinary BHHH/OPG (∑iwisisi⊤)−1\big(\sum_i w_i\, s_i s_i^{\top}\big)^{-1} uses the weight to the first power, not the second.

A consistency check: rescaling all weights by a constant cc sends A→cAA \to cA and B→c2BB \to c^{2} B, so V→(cA)−1(c2B)(cA)−1=A−1BA−1V \to (cA)^{-1}(c^{2}B)(cA)^{-1} = A^{-1}BA^{-1} — the sandwich is invariant to the weight scale, whereas A−1→c−1A−1A^{-1} \to c^{-1} A^{-1} is not.

11.4 Scope: Robust vs. Design-Based Variance

The estimator implemented here is the robust weighted-M-estimator (Huber–White) variance, whose meat B=∑iwi2sisi⊤B = \sum_i w_i^{2}\, s_i s_i^{\top} is uncentered. This is the asymptotic variance under variable-probability sampling (each population unit sampled independently with a stratum-dependent probability). Under a fixed-quota design the design-based variance centers the scores within strata and may be smaller; that stratum-centered estimator is out of scope here. See Manski & McFadden (1981) for the design-based treatment and Cosslett (1981) for the asymptotically efficient conditional-maximum-likelihood alternative.

11.5 Implementation and Cluster-Robust Extension

The meats come from compiled kernels that never form the N×pN\times p matrix of scores (NN situations by pp parameters): the BHHH kernel mnl_bhhh_parallel() adds wisisiTw_i\,s_is_i^T over each situation’s compact block (§4.3), with weights = w for the BHHH information and weights = w^2 for the robust meat, the weight-free score sis_i entering both. With the bread

A=𝚖𝚗𝚕_𝚕𝚘𝚐𝚕𝚒𝚔_𝚑𝚎𝚜𝚜𝚒𝚊𝚗_𝚙𝚊𝚛𝚊𝚕𝚕𝚎𝚕(θ̂;w),B=𝚖𝚗𝚕_𝚋𝚑𝚑𝚑_𝚙𝚊𝚛𝚊𝚕𝚕𝚎𝚕(θ̂;w2)=∑iwi2sisiT, A=\texttt{mnl\_loglik\_hessian\_parallel}(\widehat\theta;w), \qquad B=\texttt{mnl\_bhhh\_parallel}(\widehat\theta;w^2)=\sum_i w_i^2 s_is_i^T,

the variance is V=A−1BA−1V=A^{-1}BA^{-1}, computed equilibrated by two solves against the LULU factors of the equilibrated bread, without forming an inverse (§12.6). The fit-time variance (se_method), vcov(fit, type = ), the recomputation of a variance dropped from a fit and wesml_vcov() all compute it from the same kernels (.assemble_score_vcov(), or compute_hessian() for a Hessian or BHHH variance recomputed lazily), so a fit’s variance is the one vcov() returns post hoc: bit for bit at one thread, and up to the last bits with more, where the threads’ shares of the situations change from call to call.

For cluster labels g(i)g(i), se_method = "cluster" replaces the meat by

Bcluster=∑g(∑i:g(i)=gwisi)(∑i:g(i)=gwisi)T. B_{\mathrm{cluster}} =\sum_g\left(\sum_{i:g(i)=g}w_is_i\right) \left(\sum_{i:g(i)=g}w_is_i\right)^T.

mnl_cluster_meat_parallel() forms it without the score matrix either: the situations sorted by cluster, each cluster’s weighted compact scores summed over the parameters its situations touch, its outer product added once the cluster ends. The sorted situations are cut into about four chunks of similar row counts per thread, and a cluster that a chunk boundary cuts is merged, in chunk order, after the parallel loop. The labels are checked before any kernel runs. No G/(G−1)G/(G-1) or other finite-cluster correction is applied. Clustering changes the estimated covariance, not the likelihood or point estimate. User-facing entry points: wesml_weights() computes the Manski–Lerman weights from the population shares QQ, while sample_by_choice() draws a choice-based sample and attaches those weights; run_mnlogit(..., se_method = "sandwich") estimates with the robust variance; wesml_vcov() returns it post hoc. Passing run_mnlogit(..., weights_col = ) collapses a row-level weight column to one weight per choice situation (validated constant within id), and a provenance guard prevents a WESML-labeled sample from being silently fit unweighted.

Code reference: mnl_bhhh_parallel() / mnl_cluster_meat_parallel() in src/mnlogit.cpp; .assemble_score_vcov(), .logit_meat() and .sandwich_combine() in R/classes.R (.score_meat() there forms the same meats from the score matrix of mnl_scores_parallel(), as the tests’ reference); equilibrated_sandwich() in src/vcov.cpp; wesml_weights() / sample_by_choice() in R/sampling.R.


12. Implementation Details

12.1 Parameter Vector Structure

The full parameter vector θ\theta is organized as:

Block Indices Length Description
β\beta [0,K)[0, K) KK Coefficients for design matrix XX
δ\delta [K,K+Jasc)[K, K + J_{asc}) 00, J−1J-1, or JJ Free alternative-specific constants

where Jasc=0J_{asc}=0 when use_asc = FALSE, Jasc=J−1J_{asc} = J - 1 without outside option (first ASC normalized to 0), or Jasc=JJ_{asc} = J with outside option.

Code reference: src/mnlogit.cpp

12.2 Data Organization

  • Design matrix XX: Stacked matrix of dimension (∑iMi)×K(\sum_i M_i) \times K, where MiM_i is the number of (inside) alternatives for individual ii
  • Alternative indices: 1-based indexing in R, converted to 0-based in C++
  • Choice indices: 1-based local row positions within each situation’s block for inside alternatives, 0 for the outside option when included
  • Prefix sums SS: Used for efficient indexing into the stacked data: Si=∑j<iMjS_i = \sum_{j < i} M_j

12.3 OpenMP Parallelization

The implementation parallelizes over choice situations using OpenMP: - Each thread keeps its working arrays (utilities, probabilities, score differences, and a copy of a situation’s covariate rows where Armadillo’s product needs one) and local accumulators: the log-likelihood and gradient, or a packed upper triangle of the Hessian or BHHH matrix (§4.3; one thread adds into the result itself, and above the budget the threads share it). All are allocated before the parallel loop, once the kernel’s memory estimate has been checked, so that no choice situation allocates - A situation’s utilities, XiβX_i\beta plus its alternatives’ constants, are formed inside the loop from its rows of XX in place, sixteen rows at a time (then eight, four and two) with their sums held in registers while one loop runs over the KK columns. Nothing of the stacked length is formed per evaluation, and the thread that reads a situation’s rows for its utilities then uses them for its gradient. (A single product XβX\beta ahead of the loop, as before 0.3.0, wrote a vector as long as the design once per column and did not speed up with the threads.) Each row’s sum takes its columns in order from zero (a product and an addition per column, fused into one operation where the package is compiled for a processor that has it) and its constant last, so a row’s utility depends neither on the situation it is stacked in, nor on the thread count, nor on the BLAS that R is linked to - The Hessian’s and BHHH matrix’s triangles are added after the loop in thread order (above the budget, the constants’ entries atomically during it); the log-likelihood and gradient in an order that can vary between calls - Dynamic scheduling balances the load, each dispatch handing a thread about 256 stacked rows, at least one situation (schedule(dynamic, chunk); CHOICER_CHUNK_ROWS at compile time), so that situations of a few rows do not pay a dispatch each; fewer where the largest situation has more than eight times the mean rows, so that no dispatch holds more than about 2,048 rows whatever the situations’ order - The elasticity and diversion-ratio kernels (§5.3, §6.5) add each situation’s terms into a J×JJ \times J sum: one thread into the result itself, TT threads into copies of their own while those fit in 2 GiB (added up in thread order after the loop), and beyond that into the shared result atomically, each thread keeping the outside option’s row and column, which every situation touches, to itself. Their memory (the result, the threads’ copies and working arrays) is checked before anything is allocated, as the estimation kernels’ is; with one thread the sums do not depend on the 2 GiB budget

Code reference: src/mnlogit.cpp; the utilities, BaseUtil in src/choicer_internal.h

12.4 Negated Objectives

The likelihood/gradient kernel and analytical-Hessian kernel return, respectively: - −ℓ(θ)-\ell(\theta) (negated log-likelihood) - −∇ℓ(θ)-\nabla\ell(\theta) (negated gradient) - −∇2ℓ(θ)-\nabla^2\ell(\theta) (negated Hessian)

This is for compatibility with minimization routines (e.g., nloptr) that expect a loss function to minimize rather than a likelihood to maximize.

12.5 Finite-Value Guards

If a situation’s chosen log probability is non-finite, the likelihood kernel substitutes −1010-10^{10} for that contribution and emits one warning after leaving the OpenMP region. If the assembled negated objective is still non-finite, it returns 101010^{10} and a zero gradient; isolated non-finite gradient entries are set to zero. These sentinels let a line search backtrack from pathological trial parameters and are not part of the regular finite-utility likelihood. The kernel’s list also holds overflow, TRUE where it replaced anything (a clamped log probability, the sentinel, a gradient entry set to zero): the optimizers do not see it, and the polish (§12.7) rejects a trial point that sets it.

Code reference: src/mnlogit.cpp; the flag, logit_sanitize() in src/choicer_internal.h

12.6 Inverting the Information

Every reported variance of θ̂\hat\theta is the inverse of an estimate of the information matrix, or a sandwich built on one: V=ℐ−1V = \mathcal{I}^{-1} with ℐ\mathcal{I} the negated Hessian −∇θ2ℓ(θ̂)-\nabla^2_\theta \ell(\hat\theta) of §4 (se_method = "hessian") or the BHHH matrix ∑iwisisi⊤\sum_i w_i\, s_i s_i^{\top} of §11.3 ("bhhh"), or V=A−1BA−1V = A^{-1} B A^{-1} with the bread AA and meat BB of §11.3 ("sandwich") or §11.5 ("cluster"). In the data’s units the diagonal of ℐ\mathcal{I} can span many orders of magnitude: a covariate measured in thousands next to one measured in thousandths, or the constant of an alternative a handful of individuals chose next to that of one most chose. Inverted as it is, such a matrix can be refused as computationally singular although only the units make it so (solve() refuses a matrix whose estimated reciprocal condition number falls below the machine epsilon, and the units alone can push it there), and a sandwich built on it can lose digits. Every fit, whatever the coordinates its optimizer used (scale_vars; §1.5 of the mixed logit article), therefore inverts the equilibrated matrix:

V=D(DℐD)−1D,D=diag(d),d=2round(−12log⁡2|diag(ℐ)|), V = D\,(D \mathcal{I} D)^{-1} D, \qquad D = \mathrm{diag}(d), \quad d = 2^{\,\mathrm{round}(-\frac{1}{2}\log_2 |\mathrm{diag}(\mathcal{I})|)},

with diag(ℐ)\mathrm{diag}(\mathcal{I}) the vector of the diagonal entries of ℐ\mathcal{I} and the functions applied elementwise: dd holds the powers of two nearest, on a log scale, to the inverse square roots of the diagonal’s magnitudes, with an entry of 1 where the diagonal entry is zero or not finite and every entry clamped to [2−500,2500][2^{-500}, 2^{500}]. For the sandwich, V=DVDDV = D\,V_D\,D with VD=(DAD)−1(DBD)(DAD)−1V_D = (DAD)^{-1} (DBD) (DAD)^{-1} and DD from AA. Any DD leaves VV unchanged in exact arithmetic, and powers of two make the products with DD exact too, barring overflow or underflow: only the LULU factorization and the solves round (for the sandwich, also the symmetrization below), on a matrix whose diagonal is within a factor of two of one in magnitude except where a diagonal entry is zero or not finite, or an entry of dd is clamped. The magnitude of the diagonal is used so that an information that is not positive definite (away from a maximum) is equilibrated too, and its negative variances reported: their standard errors are NA, with a message.

DℐDD \mathcal{I} D is formed in one working copy, which LAPACK factors in place (LULU with partial pivoting) with solve()’s checks: a pivot that is exactly zero is an error, and so, when every factor is finite, is a reciprocal condition number (estimated in the 1-norm) below the machine epsilon; either error leaves the fit without a variance, its standard errors NA, with a message. The identity is then solved against the factors into the result, as reference LAPACK’s dgesv does for solve(), with two p×pp \times p matrices besides ℐ\mathcal{I} (pp the number of parameters) where solve() holds three. The sandwich is solved twice against the factors of DADDAD, first (DAD)Y=DBD(DAD)\,Y = DBD and then the transposed system (DAD)⊤VD⊤=Y⊤(DAD)^{\top} V_D^{\top} = Y^{\top}, without forming an inverse: two p×pp \times p matrices besides AA and BB where an explicit inverse and two products hold four, and 423p34\tfrac{2}{3} p^3 operations against 623p36\tfrac{2}{3} p^3. VDV_D is symmetrized, (VD+VD⊤)/2(V_D + V_D^{\top})/2, before DD is applied. At p=17,000p = 17{,}000 each such matrix takes 2.3 GB. The working copy is freed as the call returns, and the package’s own passes over whole matrices (the scaling, the scan of the factors for non-finite entries, the transposition and the symmetrization) run in parallel over columns, without sums across threads, so they do not depend on the number of threads. The fit and post-hoc vcov(fit, type = ) and wesml_vcov() take this same route.

Against an exact computation on the package’s reference battery and tests (963 inversions of 477 distinct matrices, of 2 to 13 parameters), a raw inversion refused 52 as singular; equilibrated, 44 of them, with raw condition numbers from 4.5×10184.5 \times 10^{18} to 1.2×10281.2 \times 10^{28}, had condition numbers below 20 and came out with standard errors within about 10−1510^{-15} relative of exact, while the other eight stayed ill-conditioned or singular. Equilibration removes the ill-conditioning that the parameters’ units cause, not the likelihood’s own: a matrix that stays ill-conditioned after it (a likelihood nearly flat along a combination of parameters, which no rescaling of the parameters one by one removes) keeps only the digits its condition number allows, by any inversion, and one singular to working precision is refused either way.

Code reference: invert_hessian(), .sandwich_combine() and .jacobi_scale() in R/classes.R; equilibrated_inverse() and equilibrated_sandwich() in src/vcov.cpp.

12.7 Polishing the Optimizer’s Solution

run_mnlogit(polish = ) follows the optimizer with the Newton phase of the mixed logit (§5.7 there), which finishes the climb to the maximum of the same log-likelihood and certifies it; the estimator does not change. With gg the gradient of −ℓ-\ell and CC the curvature, the information ℐ=−∇2ℓ\mathcal{I} = -\nabla^2 \ell of §4 (polish = "newton") or the BHHH matrix ∑iwisisi⊤\sum_i w_i\, s_i s_i^{\top} of §11.3 ("bhhh", its weights unsquared), the polish converges when the Newton decrement

ν=12g⊤C−1g, \nu = \tfrac{1}{2}\, g^{\top} C^{-1} g,

over the mean weight w‾\bar w, falls below tol_decrement (10−810^{-8}). On a positive definite ℐ\mathcal{I} the remaining Newton step then moves every linear combination of the estimates by at most 2ν\sqrt{2\nu} of its Hessian standard error; with "bhhh" the bound is in robust standard errors (for an unweighted fit; with weights, in the metric of ℐ−1ℬℐ−1\mathcal{I}^{-1} \mathcal{B} \mathcal{I}^{-1} with ℬ\mathcal{B}’s weights unsquared), and a small BHHH decrement on its own shows only a stationary point. The steps, their damping and maximum length, and the line search are those of the mixed logit’s §5.7 (the multinomial logit has no bounds).

The multinomial logit’s log-likelihood is concave: with XiX_i the rows of situation ii’s design, the constants’ indicators included, and pip_i its probabilities, ℐ=∑iwiXi⊤(diag(pi)−pipi⊤)Xi\mathcal{I} = \sum_i w_i\, X_i^{\top} \big(\mathrm{diag}(p_i) - p_i p_i^{\top}\big) X_i is positive semidefinite everywhere. Wherever it is positive definite (the model identified at the current point) and not singular to working precision, the Newton step needs no damping, and the maximum the polish certifies is the global one.

A trial point fails where the likelihood kernel reports that its objective or gradient is not the log-likelihood’s (§12.5): a chosen log probability clamped to −1010-10^{10}, a total that is not finite, or a gradient entry set to zero. The constant of an alternative never chosen has a negative score at every θ\theta, and that of one chosen wherever it is offered a positive one, so neither has a finite estimate (run_mnlogit() warns of them); the polish holds the constants of such inside alternatives at the optimizer’s values, and the certificate concerns the other parameters given them. Where the reference itself (the base alternative, or the outside option) is the one without, the other constants diverge together, and the polish does not report convergence unless the reference is never chosen and the held constants anchor all the others, which stops their rise. An alternative is anchored if its constant is held, or if it is offered in a choice situation whose chosen alternative is anchored. With every constant that can rise anchored, any direction of the constants that raises a set of them meets the situation that anchored the member of the set anchored first; there the chosen alternative, outside the set, has a probability that falls to zero, and with it the log-likelihood. A held alternative chosen only where it is offered alone anchors nothing.

The polish’s maximum step and its stall rule are measured in the optimizer’s coordinates mm (§1.5 of the mixed logit article). Under scale_vars = "none" those would be the parameters’ own units, in which a column measured in thousandths needs coefficient steps of hundreds, so the scales come instead from the BHHH diagonal at the optimizer’s solution, as "bhhh" takes them at the start values: one pass of the gradient kernel. The variance is computed at the polished estimates, by se_method, and the polish’s last curvature, evaluated at the point it returns, is not evaluated again where it is the variance’s own matrix: after "newton" the Hessian of "hessian" and the bread of "sandwich" and "cluster", after "bhhh" the BHHH matrix of "bhhh".

On census- and claims-style designs (2,504 and 2,602 alternatives with 24,560 and 245,031 choice situations; 499 and 500 alternatives with 17,339 and 153,721 situations; ten covariates; constants without a finite estimate removed; single runs at eleven threads, times modeled from the kernels’ calls) the default fit (scale_vars = "bhhh") stopped at the maximum in 29 to 42 evaluations, and the Newton polish certified it at once: with its Hessian serving the variance, it added one gradient pass and one Cholesky factorization, 3 to 13% of the modeled time of the fit and its variance. With scale_vars = "none" the optimizer stopped up to 9.2 log-likelihood units short, at its limit of 1,000 evaluations on three of the designs, and the polish closed the gap in 1 to 6 steps. With half of the covariates rescaled by 10310^3 and the other half by 10−310^{-3}, 20 steps at unit scales left a decrement of 1,130 to 2,060, where 8 or 9 at the BHHH scales certified the maximum.

Code reference: run_polish(), .polish_held(), .polish_anchors(), .polish_fit() and .polish_scales() in R/classes.R; newton_step() in src/newton.cpp; the curvature and its reuse in run_mnlogit(), R/mnlogit_utils.R; the kernel’s report, logit_sanitize() in src/choicer_internal.h.


References

  • McFadden, D. (1974). Conditional logit analysis of qualitative choice behavior. In P. Zarembka (Ed.), Frontiers in Econometrics (pp. 105-142). Academic Press.
  • Train, K. E. (2009). Discrete Choice Methods with Simulation (2nd ed.). Cambridge University Press.
  • Berry, S. T. (1994). Estimating discrete-choice models of product differentiation. RAND Journal of Economics, 25(2), 242-262.
  • Berry, S., Levinsohn, J., & Pakes, A. (1995). Automobile prices in market equilibrium. Econometrica, 63(4), 841-890.
  • Berry, S., Gandhi, A., & Haile, P. (2013). Connected substitutes and invertibility of demand. Econometrica, 81(5), 2087-2111.
  • Fukasawa, T. (2024). Fast and simple inner-loop algorithms of static / dynamic BLP estimations. arXiv:2404.04494.
  • Walker, H. F., & Ni, P. (2011). Anderson acceleration for fixed-point iterations. SIAM Journal on Numerical Analysis, 49(4), 1715-1735.
  • Varadhan, R., & Roland, C. (2008). Simple and globally convergent methods for accelerating the convergence of any EM algorithm. Scandinavian Journal of Statistics, 35(2), 335-353.
  • Manski, C. F., & Lerman, S. R. (1977). The estimation of choice probabilities from choice based samples. Econometrica, 45(8), 1977-1988.
  • Manski, C. F., & McFadden, D. (1981). Alternative estimators and sample designs for discrete choice analysis. In C. F. Manski & D. McFadden (Eds.), Structural Analysis of Discrete Data with Econometric Applications (pp. 2-50). MIT Press.
  • Cosslett, S. R. (1981). Maximum likelihood estimator for choice-based samples. Econometrica, 49(5), 1289-1316.