The math behind choicer: nested logit
Source:vignettes/articles/nested_logit_math.Rmd
nested_logit_math.RmdThis document provides a detailed mathematical description of the
nested logit (NL) model as implemented in
src/nestlogit.cpp.
Table of Contents
- Notation
- Model Definition
- Log-Likelihood Function
- Gradient Computation
- Hessian Computation
- Implementation Details
- Post-Estimation Quantities
- Choice-Based Sampling and WESML Weighting
Notation
| Symbol | Description |
|---|---|
| Index for individuals (choice situations) | |
| Index for inside alternatives available to individual | |
| Choice set of inside alternatives available in situation | |
| The alternative chosen by individual | |
| Weight for individual | |
| Row vector of covariates for individual and alternative () | |
| Coefficient vector () | |
| Alternative-specific constant (ASC) for alternative | |
| Systematic (deterministic) utility | |
| Global set of inside alternatives belonging to nest ; situation contributes | |
| The nest containing alternative | |
| Inclusive value (dissimilarity) coefficient for nest | |
| Inclusive value for nest | |
| Probability of choosing conditional on choosing nest | |
| Marginal probability of choosing nest | |
| Probability that individual chooses alternative |
1. Model Definition
1.1 Utility Specification
The utility that individual derives from alternative is:
where the systematic utility is:
The error term follows a Generalized Extreme Value (GEV) distribution that induces within-nest correlation.
1.2 Nest Structure
The inside alternatives are partitioned into mutually exclusive and exhaustive nests . An outside option (alternative 0) with may optionally be included, and it is always assigned its own singleton nest with .
1.3 Inclusive Value Coefficients
Each nest has a dissimilarity parameter that governs within-nest substitution:
- corresponds to independent (MNL-like) alternatives within the nest.
- indicates positive within-nest correlation (the typical case).
- is mathematically evaluable in the implemented probability formula but lies outside the standard globally RUM-consistent nested-GEV restriction . It should not automatically be interpreted as a valid negative within-nest correlation parameter.
The optimizer in run_nestlogit() currently imposes the
lower bound
but does not impose
.
An estimate above one should therefore be read as a diagnostic about the
nesting tree or maintained assumptions, not as evidence of especially
strong within-nest substitution.
Singleton nests (nests with exactly one alternative) have fixed to 1 and are not estimated. Only non-singleton nests contribute parameters to . The low-level parser requires at least one globally non-singleton nest; a specification in which every nest is a singleton is rejected rather than estimated as an MNL through this entry point.
Code reference: src/nestlogit.cpp
1.4 Alternative-Specific Constants (ASCs)
The ASC identification follows the same convention as MNL:
-
Without outside option
(
include_outside_option = FALSE): The first inside alternative’s ASC is fixed to zero (). The parameter vector contains free ASC parameters. -
With outside option
(
include_outside_option = TRUE): The outside option serves as the reference with . All inside alternatives have free ASC parameters.
Code reference: src/nestlogit.cpp
2. Log-Likelihood Function
2.1 Probability Decomposition
The nested logit choice probability decomposes as:
The two components are derived from the GEV generating function.
2.2 Inclusive Value
The inclusive value for nest is the log-sum of scaled utilities within the nest:
The rest of the article suppresses the subscript and writes . Nests with no available alternative in have log inclusive value and contribute zero to the upper-level denominator.
2.3 Conditional Choice Probability
The probability of choosing alternative given that nest is chosen:
In log form:
2.4 Nest (Marginal) Probability
The probability of choosing nest :
If an outside option is included, its contribution enters the denominator as .
In log form:
2.5 Joint Choice Probability
Taking logs of the joint probability:
where (plus 1 if an outside option is present).
Code reference: src/nestlogit.cpp
2.6 Log-Likelihood
The log-likelihood is the weighted sum of log-probabilities of the observed choices:
where and is the alternative chosen by individual .
Code reference: src/nestlogit.cpp
2.7 Log-Sum-Exp Trick for Numerical Stability
Two log-sum-exp stabilizations are applied.
Within-nest inclusive value. To compute without overflow, the implementation subtracts the maximum scaled utility in each nest:
where .
Across-nest denominator. The denominator is similarly stabilized by subtracting before exponentiation.
Nests an individual does not face. A nest none of whose alternatives individual faces has , so when : it never raises the maximum, and its term adds nothing to . Where every is positive and the nests outnumber an individual’s alternatives on average, the kernels therefore form the inclusive values, the maximum and over the nests the individual faces, in increasing order and in the same two partial sums (by each nest’s index parity) as the loops over every nest, which changes no bit of the result. With a that is NaN, zero or negative (which no exported function accepts), they loop over every nest.
Code reference: src/nestlogit.cpp
2.8 Relation to Other Nested-Logit Parameterizations
The probabilities in §§2.3–2.4 are the utility-normalized GEV form
used by choicer (McFadden 1978; Train 2009, Ch. 4): utility
is scaled by
inside the conditional probability, and the inclusive value is
multiplied by
in the nest probability. Some software uses a normalization in which its
reported systematic index enters the within-nest logit unscaled. These
conventions can represent different definitions of utility coefficients
and error scales; they are not generally numerically identical under a
common-coefficient restriction, and their reported
and
cannot be compared without deriving the normalization mapping. It is too
strong to label every unscaled convention non-RUM; the precise point is
which utility, inclusive-value, and scale normalization is being
estimated (Koppelman & Wen 1998; Hensher & Greene 2002; Heiss
2002).
3. Gradient Computation
3.1 Gradient with Respect to (Utility Scores)
To derive the gradients with respect to and , we first compute the derivative of the log-probability of the chosen alternative with respect to the systematic utility of each alternative .
Let denote the chosen nest (i.e., ). The log-probability of the chosen alternative is:
Derivative of the conditional term. Since and :
Derivative of the nest term. Using :
Combined. Adding both terms:
This is implemented as the vector grad_vec of length
:
Code reference: src/nestlogit.cpp
3.2 Gradient with Respect to
Since , the contribution from individual is:
The full gradient is accumulated as a single BLAS matrix-vector product, identically to MNL.
Code reference: src/nestlogit.cpp
3.3 Gradient with Respect to
Since
,
the gradient entries are the corresponding elements of
grad_vec, scattered to the appropriate positions in
:
The same free-ASC convention as MNL applies (first inside alternative’s ASC excluded when no outside option).
Code reference: src/nestlogit.cpp
3.4 Gradient with Respect to
Define the within-nest probability-weighted mean utility:
For the chosen nest (). The log-probability decomposes as:
Using :
Combining:
For a non-chosen nest (). The conditional probability is independent of , so only the nest probability contributes:
The common factor
is labeled term_in_brackets in the code.
Code reference: src/nestlogit.cpp
4. Hessian Computation
This section documents the Hessian of the negated
log-likelihood. The function
nl_loglik_hessian_parallel returns
,
the same quantity that invert_hessian() expects (positive
semi-definite at the MLE) and inverts equilibrated (§5.8). The sign
convention matches the numeric oracle
nl_loglik_numeric_hessian (which differences the negated
gradient), so both functions are interchangeable as inputs to
invert_hessian().
Two implementations are available:
-
nl_loglik_hessian_parallel— default (se_method = "hessian"): single-pass analytical Hessian derived below. Validated against the numeric oracle at a maximum absolute difference of across the package’s test fixtures, well below the tolerance those tests enforce. At extreme , the oracle’s own finite-difference accuracy degrades; the analytical Hessian remains finite and symmetric throughout. -
nl_loglik_numeric_hessian— retained oracle (se_method = "numeric"): central finite differences on the analytical gradient with step . Use for diagnostic comparison or whenever a direct verification of the analytical path is required.
4.1 Notation and Scope
All notation follows §§0–3. Subscripts (individual), (alternative local indices within ’s choice set, 0-based), and / (nest indices, 0-based) are used throughout. Additional symbols specific to this section:
| Symbol | Description |
|---|---|
| 0-based index of the chosen nest ( when outside option is chosen) | |
| 0-based local index of the chosen inside alternative | |
| — -weighted mean utility in nest | |
| — the “bracket term” from §3.4 | |
| — conditional second moment | |
| — -weighted variance of in nest | |
| — -weighted mean of in nest (-vector) | |
| — -weighted mean of in nest (-vector) | |
| — -weighted second moment of () | |
| — -weighted second moment of () | |
| — -weighted global mean of for individual (-vector) |
The negated per-individual log-likelihood contribution is . The full Hessian is the sum where .
4.2 V-Space Hessian
Because is linear in and , the second derivatives with respect to these parameters factor through the V-space Hessian. Define:
Starting from the gradient formula (§3.1):
differentiating with respect to yields:
Partial derivative of with respect to . Write , . Expanding via the product rule and using :
Partial derivative of with respect to . Non-zero only when :
Combined V-space Hessian (correct formula). Negating and combining:
The chosen-nest correction is nonzero only when both and are in the chosen nest (and ). It arises from the factor in coupling the conditional probability gradient back to .
Structural notes and MNL limit:
- For : (cross-nest entries are the negative product of marginal probabilities, the familiar multinomial covariance term).
- MNL limit ( for all ): , the standard multinomial Hessian of . Own diagonal ; off-diagonal . The chosen-nest correction vanishes because .
- When the outside option is chosen () or when (singleton chosen nest), for all pairs.
Implementation note: The implementation never forms as an matrix: it forms one column at a time, for each row with a free constant (§4.4, §4.8), and the outer-product decomposition used for the beta-beta block (§4.3) needs no entry of it.
Code reference: src/nestlogit.cpp
4.3 Beta-Beta Block
Since :
The matrix product is decomposed into three terms that can be accumulated in a single nest-level pass, exploiting the outer-product structure of :
Term A — universal outer product (subtracted):
This arises from the term universal to all pairs: .
Term B — per-nest within-nest correction (added), summed over all nests :
For singleton nests (): , so the contribution reduces to .
Term C — chosen-nest correction (subtracted), only when :
Here is the -weighted covariance of within the chosen nest.
Full beta-beta block (Hessian of the negated log-likelihood; positive semi-definite at the MLE):
MNL limit check. At for all : Term B ; Term C vanishes; the formula yields the standard MNL expression .
Code reference: src/nestlogit.cpp
4.4 Beta-Delta and Delta-Delta Blocks
Since , these blocks are direct projections of onto free-ASC alternatives.
Delta-delta block (for free-ASC alternatives and ):
Beta-delta block (for covariate index and free-ASC alternative ):
Both blocks use the column of each row with a free constant, formed once (§4.8). No additional auxiliary quantities are required.
ASC normalization. Without an outside option, the
first inside alternative’s ASC is fixed to zero: free-ASC alternatives
satisfy alt_idx0[a] > 0, mapped to theta positions
delta_start_idx + alt_idx0[a] - 1.
Code reference: src/nestlogit.cpp
4.5 Lambda-V Cross Derivative
The lambda parameters enter nonlinearly through both and the nest probabilities, so cross-derivatives between and must be computed via the chain rule. Define:
Key intermediates (derived from §3.4):
For non-chosen nests (), using :
The first term is a universal “shift” proportional to ; the second is the within-nest correction active only for .
For the chosen nest (, only when ), using :
The extra term for arises from differentiating the component of the chosen-nest gradient.
4.6 Lambda-Beta and Lambda-Delta Blocks
Using and :
Both are filled symmetrically. Singleton nests (theta index ) contribute no rows or columns to these blocks.
Code reference: src/nestlogit.cpp
4.7 Lambda-Lambda Block
Differentiating with respect to , using:
Off-diagonal (any combination of chosen/non-chosen nests):
This formula holds uniformly regardless of whether or equals . It can be negative (whenever and share the same sign), reflecting correlation between nest-level inclusive values.
Diagonal (non-chosen nest):
The first term is a Fisher-information-type squared-gradient term; the second is positive and captures curvature from ’s dependence on through the within-nest utility variance.
Diagonal (chosen nest, only when ):
The chosen-nest diagonal differs from the non-chosen formula because the term in contributes when differentiated. Since the chosen alternative tends to have above-average utility within its nest ( in expectation), the last term is typically negative, making the chosen-nest diagonal somewhat smaller than the non-chosen counterpart.
When the outside option is chosen (), all lambda diagonals use the non-chosen formula.
Code reference: src/nestlogit.cpp
4.8 Single-Pass Implementation and Auxiliary Accumulations
All six blocks are accumulated in a single parallel pass over individuals. The per-nest auxiliary quantities below are accumulated in an inner loop over alternatives at cost before any block is computed, for the nests the situation offers only: a nest it does not offer has zero sums and contributes nothing.
Per-nest scalars (zero-initialized per individual, indexed by nest ):
| Quantity | Formula | Blocks that use it |
|---|---|---|
| , lambda-lambda, lambda-V cross | ||
| for lambda-lambda diagonal | ||
| lambda-lambda (all entries), lambda-V cross | ||
| lambda-lambda diagonal |
Per-nest K-vectors:
| Quantity | Formula | Blocks that use it |
|---|---|---|
| beta-beta Term B | ||
| beta-beta Terms B and C |
Per-nest matrices:
| Quantity | Formula | Blocks that use it |
|---|---|---|
| beta-beta Term B | ||
| beta-beta Term C (formed for the chosen nest only) |
Global per-individual: (beta-beta Term A).
Compact blocks. A situation’s terms touch only its compact block: the coefficients, the dissimilarities of the non-singleton nests it offers (those whose is finite), and the free constants of its alternatives, in increasing order. is formed a column at a time (no matrix), the symmetric sums are kept as packed upper triangles, and the lambda-lambda block runs over the pairs of touched nests. A situation’s blocks thus cost , whatever the number of alternatives in the model; its probabilities still visit every nest.
OpenMP structure. The outer loop over individuals is
parallelized with dynamic scheduling. Each thread adds into its own
packed upper triangle while the threads’ triangles fit in a budget (2
GiB by default), and above it into a shared result: each thread keeps
the coefficients’ rows private (and the dissimilarities’, while the
threads’ copies of them fit in the budget) and adds the rest atomically.
All of it is allocated before the loop, once the kernel’s memory
estimate has been checked against
options(choicer.max_memory) or the physical memory.
Symmetrization and sanitization. and Term B’s are symmetric in exact arithmetic (, so ) but not in floating point. Each entry therefore receives the mean of its two transposed terms, computed term by term (halving is exact except for subnormal terms, so no running sum is doubled on the way); any remaining non-finite entries are zeroed.
Singleton-nest handling. Singleton nests (, theta index ) contribute nothing to the lambda-lambda, lambda-beta, or lambda-delta blocks. Their beta-beta contribution via Term B simplifies to (since ).
Per-individual weights. Every contribution is multiplied by (WESML weight; equals 1 for unweighted data).
Code reference: src/nestlogit.cpp
5. Implementation Details
5.1 Parameter Vector Structure
The full parameter vector is organized as:
| Block | Indices | Length | Description |
|---|---|---|---|
| Coefficients for design matrix | |||
| Non-singleton nest dissimilarity parameters | |||
| , , or | Free alternative-specific constants |
where
is the number of non-singleton nests and
when use_asc = FALSE,
without an outside option, or
with an outside option.
Code reference: src/nestlogit.cpp
5.2 Singleton Nest Handling
At startup, the implementation identifies which nests are singletons
(contain exactly one alternative). These nests: - Have their
fixed to 1 (no contribution to the upper-level logit denominator beyond
their single utility term). - Are excluded from the estimated parameter
vector. - Are tracked via nest_k_to_theta_idx, an integer
vector of length
where entry
holds the corresponding index in
for non-singleton nests and
for singletons.
This ensures that the NL model degenerates gracefully to MNL on a per-nest basis when nests are singletons.
Code reference: src/nestlogit.cpp
5.3 Data Organization
- Design matrix : Stacked matrix of dimension , where is the number of inside alternatives for individual .
-
alt_idx: 1-based indices mapping rows of to global alternative IDs. -
nest_idx: 1-based nest assignment of length (number of unique inside alternatives), not length . Accessed vianest_idx.elem(alt_idx0_i)to handle varying choice sets. -
choice_idx: 1-based local row position of the chosen inside alternative within each situation’s block; 0 for the outside option. - Prefix sums : Used for efficient slicing into the stacked data: .
Code reference: src/nestlogit.cpp
5.4 Base Utilities
The systematic utilities of an individual’s alternatives are formed inside the parallel loop, when the individual’s turn comes, from its rows of in place:
for each individual i (in parallel):
V_i = X_i * beta // each row's sum over the columns, in order
if use_asc: V_i += delta[alt_idx0_i]
Nothing of the stacked length is formed per evaluation, and the thread that reads an individual’s rows of for its utilities is the one that then uses them for its gradient. The rows are taken sixteen at a time (then eight, four and two), their sums held in registers while one loop runs over the columns. A single product ahead of the loop, as the kernels formed 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. A row’s utility therefore depends neither on the choice set it is stacked in, nor on the thread count, nor on the BLAS that R is linked to. The multinomial logit’s kernels form theirs with the same routine, and so do both models’ share inversions.
Code reference: BaseUtil in src/choicer_internal.h
5.5 OpenMP Parallelization
The implementation parallelizes over individuals using OpenMP: - Each
thread keeps local accumulators (the log-likelihood and gradient, or a
packed upper triangle of the Hessian or BHHH matrix, §4.8; one thread
adds into the result itself) and its working arrays (the probabilities,
the individual’s nests, a copy of its covariate rows where Armadillo’s
product needs one), all allocated before the parallel loop once the
kernel’s memory estimate has been checked, so that no individual
allocates. - The Hessian’s and BHHH matrix’s triangles are added after
the loop in thread order (above the budget, the shared entries
atomically during it); the log-likelihood and gradient in an order that
can vary between calls. - The loops over the dissimilarities (their
gradient, scores and Hessian terms) run over the nests the individual
faces, and so do the inclusive values and nest probabilities where every
is positive and the nests outnumber the alternatives on average (§2.7).
- Dynamic scheduling balances load across individuals with varying
choice set sizes, each dispatch handing a thread about 256 stacked rows,
at least one individual (CHOICER_CHUNK_ROWS at compile
time), and fewer where the largest choice set has more than eight times
the mean rows, so that no dispatch holds more than about 2,048. - The
elasticity and diversion-ratio kernels add each individual’s terms into
a
sum, as the multinomial logit’s do: one thread into the result itself,
threads into copies of their own while those fit in 2 GiB, and beyond
that into the shared result atomically, the outside option’s row and
column kept per thread; its memory is checked before it is
allocated.
Code reference: src/nestlogit.cpp
5.6 Negated Objectives
The likelihood/gradient kernel returns: - (negated log-likelihood) - (negated gradient)
for compatibility with minimization routines (e.g.,
nloptr) that minimize a loss function rather than maximize
a likelihood. The analytical and numeric Hessian kernels return
;
the BHHH kernel instead returns the positive-semidefinite OPG
information approximation
.
5.7 Finite-Value Guards
The likelihood kernel replaces a non-finite chosen log probability by
.
If the final negated objective is non-finite it returns
and a zero gradient; isolated non-finite gradient entries are zeroed.
The analytical Hessian skips a situation whose chosen log probability is
non-finite, adds the mean of each pair of transposed terms (§4.8), and
replaces any remaining non-finite entries by zero. These rules are
optimizer failure guards, not part of the regular finite-parameter
nested-logit criterion; encountering them calls for rescaling or
revising the specification. The likelihood kernel’s list also holds
overflow, TRUE where it replaced anything (a
clamped log probability, the sentinel, a gradient entry set to zero, as
where an unchosen nest’s inclusive value overflows and the nest drops
out of the denominator, leaving the chosen probability finite and too
high): the optimizers do not see it, and the polish (§5.9) rejects a
trial point that sets it.
Code reference: src/nestlogit.cpp;
the flag, logit_sanitize() in src/choicer_internal.h
5.8 Inverting the Information
Every reported variance of
is the inverse of an estimate of the information matrix, or a sandwich
built on one:
with
the negated Hessian
of §4 (se_method = "hessian", or its finite-difference
oracle under "numeric") or the BHHH matrix
of §5.6 ("bhhh"), or
with the bread
and meat
of §7.3 ("sandwich") or §7.5 ("cluster"). In
the data’s units the diagonal of
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, "bhhh" by default; §1.5 of the mixed logit article), therefore inverts
the equilibrated matrix:
with
the vector of the diagonal entries of
and the functions applied elementwise:
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
.
For the sandwich,
with
and
from
.
Any
leaves
unchanged in exact arithmetic, and powers of two make the products with
exact too, barring overflow or underflow: only the
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
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.
is formed in one working copy, which LAPACK factors in place
(
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
matrices besides
(
the number of parameters) where solve() holds three. The
sandwich is solved twice against the factors of
,
first
and then the transposed system
,
without forming an inverse: two
matrices besides
and
where an explicit inverse and two products hold four, and
operations against
.
is symmetrized,
,
before
is applied. At
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
to
,
had condition numbers below 20 and came out with standard errors within
about
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. Some of the
package’s nested logit test designs give such matrices, with condition
numbers up to
after equilibration; two more, near
,
are refused (six inversions). Where an exact variance is zero, as at
some degenerate test fits, the computed one is rounding noise of either
sign, and a negative one gets an NA standard error like any
negative variance.
Code reference: invert_hessian(),
.sandwich_combine() and .jacobi_scale() in R/classes.R;
equilibrated_inverse() and
equilibrated_sandwich() in src/vcov.cpp.
5.9 Polishing the Optimizer’s Solution
run_nestlogit(polish = ) follows the optimizer with the
Newton phase of the mixed logit
(§5.7 there), which finishes the climb to the maximum the optimizer
approached and certifies it; the estimator does not change. With
the gradient of
and
the curvature, the analytic information
of §4 (polish = "newton") or the BHHH matrix
of §5.6 ("bhhh", its weights unsquared), the polish
converges when the Newton decrement
,
over the mean weight, falls below tol_decrement
().
On a positive definite
the remaining Newton step then moves every linear combination of the
estimates by at most
of its Hessian standard error; with "bhhh" the bound is in
robust standard errors (for an unweighted fit; with weights, in the
metric of
with
’s
weights unsquared), and a small BHHH decrement on its own shows only a
stationary point. The steps, their damping and maximum length, the line
search and the projection onto the dissimilarities’ bound are those of
the mixed logit’s §5.7.
Curvature. For given dissimilarities all at most 1 the log-likelihood is concave in : each (the sum also holding the outside option’s 1, where there is one) adds to a linear term a nonpositive multiple of a log-sum-exp, which is convex in the utilities, and subtracts a log-sum-exp, convex and nondecreasing in each argument, of the convex functions . It need not be concave jointly with , nor in where some : the information can be indefinite away from the maximum, where the steps are damped (Levenberg–Marquardt), and a maximum the polish certifies can be local. The dissimilarities keep their lower bound of . Where the steps drive one to that bound, they are damped at nearly every iteration and the polish does not report convergence. In one of the package’s test designs (200 choice situations) a fit from a poor start went there, 24 log-likelihood units below the interior maximum that a polish from another stop certified in six steps; in two others every start ended at the bound. Refit from other starts: where they all end there, the likelihood’s supremum is at the bound, the dissimilarity has no interior estimate and no polish certifies the fit, and the nest is to be revised.
What is held. The constants of inside alternatives without a finite estimate are held at the optimizer’s values, and the certificate concerns the other parameters given them, with one exception. An alternative chosen wherever it is offered has a positive score for its constant at every , and is held, as in the multinomial logit. A never-chosen alternative in nest is held only where is a singleton or at the optimizer’s solution. Where is offered and the alternative chosen, , belongs to another nest, its constant’s score is ; where is a nest-mate, it is
negative for
but positive for
where the nest’s probability
is below
.
Above 1 the constant can then have a finite estimate, which the polish
seeks, so it is moved. Both terms vanish in proportion to
as
:
where they are negative on balance there, the constant still has no
finite estimate, and the polish moves it down until its share of the
decrement is below the tolerance. It may then certify a point where the
constant, and its standard error, are set by tol_decrement:
in mode_choice with a never-chosen copy of bus (its
generalized cost raised by 5), whose public nest has
,
about
,
its standard error about
.
A polish that held such a constant at
and ends with
does not report convergence, nor does one that moved it and ends with
,
where it has no finite estimate. The reference’s divergence is treated
as in the multinomial logit
(§12.7 there): the held constants must anchor every other constant that
can rise (a never-chosen one cannot rise without bound, since wherever
it is offered the chosen alternative lies outside any set of
never-chosen ones). A never-chosen base alternative, the reference, is
treated as a moved constant (the others move against it), so that rule
applies only where its nest is a singleton or ends with
.
Other limits. A nest that no situation offers two of
has a dissimilarity on which the likelihood does not depend. Its score,
its BHHH column and its Hessian entries are zero in exact arithmetic.
The score and the BHHH column are exactly zero at the default start of
0.5, where the optimizer then leaves it (1/λ is exact there), and of
rounding size elsewhere; the Hessian’s diagonal holds a rounding residue
everywhere, 0.5 included (of either sign, about
to
in a test design). The BHHH polish leaves such a dissimilarity out of
its steps, as without information or as stalled, and does not report
convergence. Where the Hessian’s residue is positive, the Newton polish
certifies the other parameters, leaving the dissimilarity at 0.5 or
moving it on the score’s rounding elsewhere; where it is negative, the
steps are damped and the polish does not certify. Its standard error is
huge (about
in a test design) or NA. A trial point fails where the
likelihood kernel reports that its objective or gradient is not the
log-likelihood’s (§5.7 above): a log probability clamped to
,
a total that is not finite, or a gradient entry set to zero, as where an
unchosen nest’s inclusive value overflows and the nest drops out of the
denominator, which leaves the chosen probability finite and too high.
The optimizers do not see that report.
Scales and the variance. The maximum step and the
stall rule are measured in the optimizer’s coordinates
(§1.5 of the mixed logit article). Under
scale_vars = "none" those would be the parameters’ own
units, so the scales come instead from the BHHH diagonal at the
optimizer’s solution projected onto the bound, as "bhhh"
takes them at the start values: one pass of the gradient kernel. With
half of the covariates rescaled by
and the other half by
,
20 steps at unit scales left a decrement of 1,054 to 1,786, where 8 or 9
at these scales certified the maximum. 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
analytic Hessian of "hessian" and the bread of
"sandwich" and "cluster"; after
"bhhh", the BHHH matrix of "bhhh".
se_method = "numeric" takes its own numerical Hessian.
On census- and claims-style designs (2,504 and 2,602
alternatives in 50 nests, with 24,560 and 245,031 choice situations; 499
and 500 alternatives with 17,339 and 153,721; ten covariates; constants
without a finite estimate removed; single runs at eleven threads, times
modeled from the kernels’ calls), the fit under
scale_vars = "none" reached its limit of 1,000 evaluations
on three of the four designs: 0.35 and 15.8 log-likelihood units short
of the maximum on the census-style ones (up to 6.7 standard errors),
on the smaller claims-style one; the larger stopped by its tolerance,
short. The Newton polish certified the maximum in 3 and 5 steps on the
census-style designs, for about a tenth of the fit’s time, and in one
step on the claims-style ones. Stopping the optimizer after 100
evaluations and polishing took about a fifth of the time of that fit and
its polish, and the default, scale_vars = "bhhh", stopped
at the maximum in 50 to 66 evaluations on three of the four designs.
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, the hold rule (.nl_nest_lambda()) and the
reuse in run_nestlogit(), R/nestlogit_utils.R;
the kernels’ report, logit_sanitize() in src/choicer_internal.h.
6. Post-Estimation Quantities
6.1 Choice Probabilities (predict)
The joint probability is the decomposition from §2.1:
with
and
given in §§2.3–2.4. nl_predict returns individual-level
probabilities
and systematic utilities
for every observation row. nl_predict_shares aggregates
over individuals to obtain weighted market shares:
Code reference: src/nestlogit.cpp
6.2 Elasticities
6.2.1 Semi-elasticity with respect to utility
Let be the nest of the responding alternative and be the nest of the perturbed alternative . From §3.1, the derivative of with respect to the systematic utility of any alternative is:
This is the general expression; the gradient formula in §3.1 applies it only to the chosen alternative, whereas here we evaluate it for all pairs to construct the full elasticity matrix.
6.2.2 Elasticity of with respect to covariate of alternative
Since :
Substituting the three cases:
| Case | Condition | Semi-elasticity |
|---|---|---|
| Own | ||
| Cross, same nest | ||
| Cross, different nest |
Reduction to MNL. When for all nests the within-nest term vanishes and the conditional probability drops out, giving , which is exactly the MNL semi-elasticity (§3.1 of the MNL document).
Outside option. When an outside option is present it occupies its own singleton nest with and . Its row (responding = outside option) has semi-elasticity for every inside alternative (different nest, §3.1); its column (perturbed = outside option) is identically zero because .
The implementation accumulates across individuals and divides by to produce a weighted average of individual probability elasticities. This is not generally the elasticity of an aggregate share under a common market-level perturbation when attributes vary across situations. Rows index responding alternatives and columns perturbed alternatives.
Code reference: src/nestlogit.cpp
6.3 Diversion Ratios
6.3.1 Definition
The utility-based diversion ratio from losing alternative to receiving alternative is:
where is aggregate demand and the perturbation is through the systematic utility of the losing alternative .
6.3.2 Partial derivatives of demand
Using and the semi-elasticity from §6.2.1, the three cases with :
6.3.3 Utility Perturbation and Covariate Interpretation
The implemented matrix is defined with respect to a common additive perturbation of . If a fixed-coefficient attribute of alternative receives the same additive change in every situation, , so the common scalar cancels:
It is in this additive-shift sense that NL diversion is independent of the chosen fixed covariate. For a proportional perturbation , the values remain inside both population sums and generally do not cancel. The kernel does not compute that attribute-specific proportional diversion. In MXL even a common additive perturbation of a random-coefficient attribute carries draw-specific , so the coefficient cannot be factored out.
6.3.4 Population aggregation and column-sum property
Define:
so that for .
Columns sum to 1. The fundamental identity (probabilities sum to 1 for every individual and every perturbation direction, including the outside option when present) gives:
When an outside option is present it acts as both a source (it can lose demand) and a destination (it can receive diverted demand), so it appears in both the row index and the column index of the diversion matrix, and the column sums still equal 1 over all alternatives including the outside option. Because its systematic utility is fixed at zero in estimation, the outside-as-source column is a derivative with respect to a hypothetical perturbation of that normalized utility, not an available outside-option covariate.
6.3.5 Reduction to MNL at
When all the cross-same-nest case collapses to the cross-different-nest case ( for ) and the own case gives . Substituting:
which is the MNL diversion ratio (§6.3 of the MNL document).
Code reference: src/nestlogit.cpp
6.4 BLP Share Inversion
6.4.1 Problem statement
Given observed market shares , find the ASC vector such that the NL model reproduces those shares, with and held at their values:
where . The identification of , the checks of the targets, the stopping rule and the result are the multinomial logit’s (§7 of the multinomial logit article); this section gives the nested logit’s step.
6.4.2 The step
With , the outside option (or, without one, the reference of ’s component) and , the step is the multinomial logit’s (§7.3 of the multinomial logit article): a common shift of the component’s free constants, then the exact diagonal of the derivative of on the rest,
for alternative
in nest
,
where
is damping (default 1),
solves
,
and : over with an outside option, and without one
The nested logit’s share Jacobian is symmetric (its shares are the
gradient of the log-sum, for any
)
and its rows sum to zero, so
is the exact rate at which
responds to the common shift, as in the logit. Berry, Levinsohn and
Pakes’s (1995) contraction, method = "original", takes
(
without an outside option, the reference held): no shift, no
outside-share correction, and 1 in place of
.
It therefore overshoots within a nest: its step’s derivative there is
about
,
and its iteration can diverge where
is small (it failed on 8 of the 18 simulated designs we tried with
,
and on none with larger
)
unless damped by about
.
The exact diagonal carries the
,
so no damping is needed. For a nest’s dominant alternative,
is formed as the sum of its nest-mates’ conditional probabilities, since
can be as small as
,
where the difference loses every digit. The logit’s other safeguards
apply: the step’s cap, its halving where the shares are not finite, its
stalls, and the contraction racing it once 100 iterations fail to halve
the best residual (multiplied by damping like the step;
where it diverges, at small
,
it falls behind and stops, going on whenever the step alone fails to
halve its best residual within 200 iterations, or its trial point
fails). method = "anderson", the default, and
method = "squarem" accelerate this step as in the logit
(Anderson acceleration and SQUAREM; §7.3 of the multinomial logit article), with
damping multiplying the step’s part of each update.
6.4.3 Nests with
Where nest-mates are complements: raising raises the nest’s inclusive value, and with it the shares of ’s nest-mates where the nest is small. Two safeguards apply.
- An alternative whose co-choice with the base is negative ( in its nest, without an outside option) has a diagonal of at least 1: its exact diagonal nets out the complementarity and can be near zero or negative.
- The diagonal is at least times the one the same probabilities give with ( over , plus over ). A common shift of a nest’s constants moves its shares as in a logit, with derivative about 1, while a shift within the nest moves them with derivative about ; the exact diagonal is close to the latter, so its step would overshoot the common shift by up to and diverge for above 2. The factor relaxes the two directions equally: the step’s error then contracts by about in each.
On 80 simulated designs with from 1.05 to 5, nests of 2 and 5 alternatives, 12 and 60 alternatives and heterogeneous choice sets, solved to , the step converged on every one, in a median 0.32 of Berry’s evaluations and never more (with an outside option, Berry’s contraction needed 129 to 170 evaluations, the step 9 to 70).
6.4.4 The layout of delta
Without an outside option, delta is a full
length-
vector, normalized by subtracting its first entry, so the returned
baseline is zero. With an outside option, supplied and returned
delta contain the
inside ASCs only, and target_shares has
entries, the outside option’s first.
Note on the lambda argument.
nl_blp_contraction expects a full
length-
vector where singleton nests have their entry set to 1, every entry
positive and finite. This differs from the estimated parameter block
in
,
which contains only non-singleton entries. The caller is responsible for
expanding the estimated lambdas into the full vector before invoking the
inversion.
6.4.5 Evaluating the shares
As in the logit (§7.6 of the multinomial logit article), after the first evaluation the probabilities are read from exponentials kept across evaluations wherever those allow it, here within each nest. The first, at , keeps for alternative in nest , where is the largest of these scaled utilities in nest of situation : one shift per situation would not do, since at a nest 15 utility units below the best would underflow (750 scaled units down) while its probability is still about . An evaluation at forms with , each offered nest’s inclusive value from (one logarithm per nest), the nests’ probabilities from those (one exponential per nest) and : three exponentials per row fewer than afresh. The distance is , what exponentiates, with the logit’s bound of 50 and its floor, so small dissimilarities make an evaluation afresh more often: at , 3 of the 39 evaluations of an inversion of census-style data, which took 0.68 of the time.
Code reference: NlBlpModel and
nl_blp_solve() in src/nestlogit.cpp,
over src/blp_engine.h.
6.5 Willingness to Pay
Utility is linear in covariates, so willingness to pay is the same marginal rate of substitution as in the MNL model: for attribute and price coefficient ,
with the block of the coefficient covariance. The nest parameters rescale within-nest substitution but do not enter the ratio of marginal utilities, so they affect WTP only through the estimated covariance of . ASCs may also be used as the numerator (). See §8 of the MNL document for the full derivation and caveats.
Code reference: R/wtp.R
6.6 Consumer Surplus and the Nested Logsum
For the nested logit, expected maximum utility is the two-level
logsum below plus the scenario-invariant extreme-value location constant
(omitted by logsum(), as in MNL):
where the term appears when an outside option is present and singleton nests have (§5.2). Both levels are computed with the max-subtraction trick (§2.7).
Two useful identities:
- Reduction to MNL. With all , and the nested logsum collapses to the MNL logsum .
- Outside-option link. Since (§2.5), the logsum equals — a direct consistency check against the probability kernel.
Expected consumer surplus follows Train (2009, Ch. 3) exactly as in the MNL case:
with the same caveats: no income effects, and CS levels inherit the
ASC normalization, so only differences across scenarios (counterfactual
newdata vs. baseline) are meaningful. The implementation
reports point estimates for NL (the delta-method SE of the mean CS is
currently provided for MNL only; Krinsky–Robb resampling of the
coefficients is the practical interval method here). The routine does
not enforce
;
interpreting
as positive marginal utility of income requires the analyst to verify
the estimated sign.
Code reference: R/surplus.R
6.7 Goodness of Fit
The measures are model-agnostic and identical to §10 of the MNL document, computed from the NL log-likelihood and predicted probabilities:
- McFadden pseudo R²: and , with counting all estimated parameters including the block.
- Equal-shares null (default, exact for unbalanced sets and weights): .
- Market-shares null (constants-only closed form): , where is the common weight; requires identical choice-set composition across individuals and uniform weights. The constants-only model is itself an MNL—at and free ASCs the nest structure is not identified from constant shares—so the same closed form applies.
- Hit rate: weighted share of choice situations whose observed choice has the highest predicted NL probability; with an outside option the outside good competes with .
Code reference: R/gof.R
7. Choice-Based Sampling and WESML Weighting
7.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 and situations are drawn with stratum-specific frequencies — for example, deliberately oversampling individuals who chose a rare alternative. Let be the population share of alternative and the sample share of choosers of .
Unlike the MNL special case (a full set of ASCs leaves the slopes consistent), the nested logit has no such free pass: the dissimilarity parameters enter the within- and between-nest probabilities nonlinearly, so choice-based sampling generally biases the slopes , the constants , and the block. Weighting is therefore required for consistent estimation of the population parameters.
7.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,
The maximizer is invariant to multiplying every by a common positive constant, so the weights may be normalized to mean 1 without changing the estimates.
7.3 Robust (Sandwich) Variance: the Meat
WESML is a weighted M-estimator solving , where is the full per-situation score over the , and blocks ($$3) and its Hessian ($$4). Its robust (Huber–White) asymptotic variance is the sandwich
The weight enters the bread
linearly, but the meat
carries the weight squared: the contribution of
situation
to the estimating equation is
,
so its variance involves
.
The score
is assembled exactly as in the gradient kernel ($$3.3–3.4): the
and
blocks from grad_vec, and the
blocks from the per-nest expression
, with singleton nests
()
contributing no score.
As in the MNL/MXL cases, both naive variances are wrong under weighting: the inverse-Hessian assumes the information-matrix equality (which fails once the are non-degenerate), and ordinary BHHH/OPG uses the weight to the first power, not the second. The sandwich is invariant to the weight scale: , , hence .
7.4 Scope: Robust vs. Design-Based Variance
The estimator implemented here is the robust weighted-M-estimator (Huber–White) variance, with uncentered meat — the asymptotic variance under variable-probability sampling. The smaller stratum-centered (design-based) variance for a fixed-quota design is out of scope; see Manski & McFadden (1981) and Cosslett (1981).
7.5 Implementation and Cluster-Robust Extension
The meats come from compiled kernels that never form the
matrix of weight-free scores (singleton lambdas are not parameters, so
the meats have no rows for them): the BHHH kernel
nl_bhhh_parallel() adds
over each situation’s compact block (§4.8), with
weights = w for the BHHH information and
weights = w^2 for the robust meat, so that
For a fit whose selected method is the numeric NL Hessian, the bread
uses the numeric oracle instead. 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. For cluster labels
,
se_method = "cluster" uses
formed by nl_cluster_meat_parallel() without the score
matrix either (the situations sorted by cluster, each cluster’s weighted
compact scores summed over the parameters its situations touch), with no
finite-cluster correction. These matrices are combined as
,
computed equilibrated by two solves against the
factors of the equilibrated bread, without forming an inverse (§5.8).
User-facing entry points: wesml_weights() computes the
Manski–Lerman weights from the population shares
,
while sample_by_choice() draws a choice-based sample and
attaches those weights;
run_nestlogit(..., se_method = "sandwich") estimates with
the robust variance; wesml_vcov() returns it post hoc.
Passing run_nestlogit(..., 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: nl_bhhh_parallel() /
nl_cluster_meat_parallel() in src/nestlogit.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 nl_scores_parallel(), as the tests’ reference);
equilibrated_sandwich() in src/vcov.cpp;
wesml_weights() / sample_by_choice() in R/sampling.R.
References
- McFadden, D. (1978). Modelling the choice of residential location. In A. Karlqvist et al. (Eds.), Spatial Interaction Theory and Planning Models (pp. 75-96). North-Holland.
- Ben-Akiva, M., & Lerman, S. R. (1985). Discrete Choice Analysis: Theory and Application to Travel Demand. MIT Press.
- Koppelman, F. S., & Wen, C.-H. (1998). Alternative nested logit models: structure, properties and estimation. Transportation Research Part B, 32(5), 289-298.
- Hensher, D. A., & Greene, W. H. (2002). Specification and estimation of the nested logit model: alternative normalisations. Transportation Research Part B, 36(1), 1-17.
- Heiss, F. (2002). Structural choice analysis with nested logit models. The Stata Journal, 2(3), 227-252.
- Berry, S., Levinsohn, J., & Pakes, A. (1995). Automobile prices in market equilibrium. Econometrica, 63(4), 841–890.
- Train, K. E. (2009). Discrete Choice Methods with Simulation (2nd ed.). Cambridge University Press. Chapter 4.
- 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.