The math behind choicer: mixed logit
Source:vignettes/articles/mixed_logit_math.Rmd
mixed_logit_math.RmdThis document provides a detailed mathematical description of the
mixed logit (random coefficients logit) model as implemented in
src/mxlogit.cpp.
Table of Contents
- Notation
- Model Definition
- Log-Likelihood Function
- Gradient Computation
- Hessian Computation
- Implementation Details
- Elasticity Computation
- Diversion Ratios
- BLP Share Inversion
- Choice-Based Sampling and WESML Weighting
- Willingness to Pay
- Consumer Surplus and the Simulated Logsum
- Goodness of Fit
- Conditional (Individual-Level) Tastes
Notation
| Symbol | Description |
|---|---|
| Index for choice situations | |
| Index for alternatives available to individual | |
| Index for simulation draws | |
| The alternative chosen by individual | |
| Weight for individual | |
| Row vector of covariates with fixed coefficients () | |
| Row vector of covariates with random coefficients () | |
| Fixed coefficient vector () | |
| Mean parameters for random coefficients () | |
| Lower-triangular Cholesky factor () | |
| Covariance matrix of the latent Gaussian deviations (and of realized coefficients only in the all-normal case) | |
| Alternative-specific constant (ASC) for alternative | |
| Standard-normal integration draw for choice situation and draw () | |
| Latent Gaussian random-coefficient deviation | |
Index for decision makers (respondents) when person_col
groups situations into a panel;
is the number of decision makers |
|
| Index for the choice situations belonging to decision maker ; is their count | |
| Posterior weight of draw given decision maker ’s observed choices ($$2.6) |
Sections 2–12 are written per choice situation
,
the default likelihood unit. §1.6 introduces the decision maker
as an optional coarser unit; §2.6, §3.5 and §4.5 give the corresponding
panel likelihood, score and Hessian. Without person_col,
and
for every
,
so
and
index the same choice situation and every panel formula collapses to its
§2–4 counterpart.
1. Model Definition
1.1 Utility Specification
The utility that individual derives from alternative under simulation draw is:
where: - captures the systematic utility from fixed coefficients - captures the mean contribution of random coefficients - captures the individual-specific random deviation - is the alternative-specific constant (the first inside ASC is normalized without an outside option; with an outside option all inside ASCs are free)
1.2 Random Coefficient Structure
Random coefficients are generated through a Cholesky decomposition structure:
This implies:
For finite parameter values the exponentiated diagonal makes nonsingular, so is positive definite (positive semidefinite in the limiting sense as a diagonal element tends to zero). Here is the covariance of the latent Gaussian deviation . It is the covariance of the realized coefficient vector only when all entries are normal. After any componentwise log-normal transformation, the realized coefficient covariance is a nonlinear function of and is not .
1.3 Distribution Transformations
The implementation supports two distributions for each random coefficient :
Normal Distribution (rc_dist[k] = 0):
Log-Normal Distribution
(rc_dist[k] = 1):
Note: This is a shifted log-normal parameterization: , which differs from the textbook parameterization .
When rc_mean = FALSE,
for every distribution. Thus a normal random coefficient is centered at
zero, while a log-normal random coefficient is
and has median one. Correlation is introduced on the latent-normal scale
by the rows of
;
componentwise transformations then induce a generally non-Gaussian joint
coefficient distribution.
1.4 Cholesky Parameterization
For a full covariance matrix (rc_correlation = TRUE),
the lower-triangular matrix
is parameterized as:
where: - Diagonal elements: (ensures positivity) - Off-diagonal elements: for (unconstrained)
For diagonal-only covariance
(rc_correlation = FALSE):
The parameter vector for has length: - Full: - Diagonal:
1.5 Scaling the Optimizer’s Coordinates
Motivation. scale_vars changes how the
optimizer moves, never what it maximizes. L-BFGS starts each iteration
from a single scalar multiple of the identity as its curvature, so it is
slow, and can fail, when the log-likelihood’s curvature differs by
orders of magnitude across parameters. Two things spread it. Units: a
price in thousands next to a 0/1 dummy gives their coefficients
curvatures far apart. The model: the constant of a small alternative (a
school with few applicants, a rarely chosen hospital) has far less
curvature than a large one’s, and the Cholesky entries of
vary as well. Column scales reach the first; only the curvature itself
reaches the second.
A change of coordinates. The kernels evaluate the model at , on the data as supplied. The optimizer works on , with
The objective in its coordinates is
,
with gradient
:
the map is affine and diagonal,
,
so the chain rule has no second-order term and the Hessian in
is
.
The maximizer is the same:
.
Start values and bounds are given in natural units and mapped by
,
which keeps their order. scale_vars = "bhhh" is the default
of run_mxlogit() and run_mnlogit();
"none" bypasses the map entirely.
Column scales ("sd", "mad",
"iqr"). Let
and
be the columns’ scales. The map
| Parameter | ||
|---|---|---|
| 0 | ||
| (normal RC) | 0 | |
| (Cholesky diagonal, stored as ) | 1 | |
| (Cholesky off-diagonal, ) | 0 | |
| 1 | 0 |
makes
the log-likelihood of the design with every column divided by its scale:
,
and
implies
,
row
of
(on the log diagonal, an additive shift; the scale is keyed on the row
,
not the column
).
The data are never divided: the optimizer sees the scaled problem
through the map. "sd" uses the sample standard deviation;
"mad" (stats::mad,
)
and "iqr" (stats::IQR(x) / 1.349) are
SD-equivalent under normality and preferable when outliers dominate a
column’s SD.
Why centering is omitted. Without an outside option, subtracting a column’s mean from every alternative shifts every utility in a situation by the same amount, which cancels from the softmax; the same argument applies draw by draw to . With an implicit outside option fixed at utility zero, an inside-only shift does not cancel against the outside: a fixed- shift could be offset only by shifting every inside ASC, and a random- shift cannot generally be absorbed by fixed ASCs. So the column-scale map corresponds to dividing the data by their scales, never to centering them.
Log-normal coefficients. For a log-normal coefficient
(,
rc_dist[k] == 1), dividing the column by
has no closed form in
,
because the two exponentials cannot share a scale factor; the
column-scale map leaves those parameters at
,
.
BHHH scales ("bhhh"). With
the BHHH (outer product of gradients) matrix at the start values
,
from the unit scores
and the fit’s weights,
for every parameter, the constants, the Cholesky entries and
log-normal coefficients included. The diagonal of
is then within a factor of two of one, for entries neither floored nor
clamped: insofar as
tracks the curvature, the optimizer starts from curvatures near one in
those coordinates. One extra gradient pass returns
,
accumulated beside the gradient (the full matrix is never formed). A
that is not finite, or below
times the median of the finite positive ones, carries no information at
and takes the median’s scale; scales are clamped to
.
Powers of two make the map exact:
round-trips without rounding, bounds included. The scales are fixed for
the whole run, because L-BFGS’s line search and stored curvature pairs
assume one fixed function of
.
A start near the estimate (theta_init) gives
closer to the information at the optimum. The scales fix the optimizer’s
metric, not a start that is wrong in a column’s units; the default start
is set in the columns’ units (below).
The default start. With
theta_init = NULL the start is zero for
,
,
the off-diagonal
and the constants, and on the diagonal
for a normal random coefficient, where
is the typical step of column
:
the distance between its values for a column with two (a dummy, a
two-level attribute), the mean of
over the other rows when one value
fills more than half of the column (a mostly-zero column), and its
standard deviation otherwise. At the start, a step of
in
moves the utility by a random amount with standard deviation one (the
logit error’s is
).
For a dummy with a share
of ones the standard deviation,
,
would understate the step its coefficient multiplies, which is 1; with
one of
alternatives marked per situation,
,
it would start
about
times higher. For a column far from zero with an implicit outside
option, the contrast with the outside good is the level
itself, so a root mean square might seem the step; on a census-style
design with a price of mean 100 and standard deviation 5 it put the
start at the true heterogeneity and took 169 evaluations, against 104
from the standard deviation (the level errs high, below). A column with
no variation (a step below
of its level) or a step that is not finite starts at
,
and steps are clamped to
.
A default start outside lower/upper is moved
to the nearest bound, with a message.
Rescaling the column,
,
gives the same model with row
of
(and
,
with rc_mean = TRUE) divided by
,
its
shifted by
;
is multiplied by
,
so this start transforms with it. So does the map of "sd"
(and of "mad" and "iqr"), whose shift
puts
at
,
a constant that does not depend on the units
(
under "sd" for a column whose step is its standard
deviation): in exact arithmetic the optimizer’s problem is then the same
in any units. Under "bhhh", a parameter divided by
has its score multiplied by
,
so
is multiplied by
and
(before rounding, for entries neither floored nor clamped) divided by
:
is unchanged up to the power-of-two rounding.
,
shifted by
,
keeps its score and its scale, so
is translated by
,
which L-BFGS’s steps do not see; only nloptr’s relative step test
(xtol_rel,
by default) does.
From
in each column’s own units (the 0.2.x default), no choice of
scale_vars reached the maximum of a census-style design
with columns rescaled by
or
in 2,000 likelihood evaluations; from this start "bhhh"
reaches it in 54, against 56 on the original units. The level, one, errs
high on purpose.
is fixed at the start, and while
is small the simulated likelihood depends on it only at second order
(the draws have mean zero, or nearly): the score in
is
,
so
is
and
at the start, while the curvature in
grows like
as the optimizer raises it. A start with too little heterogeneity
therefore yields a scale too generous for where the optimizer goes: from
one design reported convergence 554 log-likelihood units short.
A log-normal coefficient starts at : there is the standard deviation of the logarithm of the coefficient’s random part, which has no units. That random part, , has median one in any units, so no start makes a log-normal column’s units irrelevant: its covariate belongs in units where the coefficient is of order one.
Variance. The variance is computed at , in natural units, whatever the coordinates the optimizer used: with the information (the negated Hessian of the log-likelihood), the BHHH variance at , or the sandwich of §9.3 (with the meat, its weights squared) or its cluster-robust extension (§9.5). The natural information can be ill-conditioned for the reasons a fit is scaled (columns in different units, the constants of rarely and often chosen alternatives), so every fit, scaled or not, inverts it equilibrated, as §5.6 describes.
The other models. run_mnlogit() and
run_nestlogit() take the same map: column scales reach the
coefficients only
(
on
;
the constants and the nest parameters keep
),
and "bhhh" reaches every parameter, the nest parameters
included, whose lower bound is mapped with the start values.
"bhhh" is the default of both; in the nested logit the BHHH
scales fixed at
can slow the optimizer where nest parameters end far from their start,
but "none" can stop at the start values where the
covariates’ units make its first step too long. Their variances are
inverted equilibrated in the same way, whatever scale_vars
(§12.6 of the multinomial logit
article, §5.8 of the nested logit
article).
1.6 Likelihood Unit: Cross-Section or Panel
By default
indexes a choice situation, and the likelihood
integrates a separate coefficient distribution for each situation — the
right model when tastes are redrawn every situation, or each decision
maker is observed once. Passing person_col to
run_mxlogit() / prepare_mxl_data() switches
the likelihood unit from the choice situation to the
decision maker
(Revelt and Train 1998): the
choice situations belonging to
then share one taste draw
,
and the likelihood integrates their joint probability,
in place of the per-situation
used elsewhere in this
document (§2.2–2.3). id_col must still identify choice
situations uniquely across the data set — situation ids do not restart
within person. person_col = NULL (the default) makes every
situation its own decision maker,
,
and recovers the cross-sectional likelihood exactly, so every formula in
§2–§9 written per situation
applies unchanged, read with
.
On panel data, imposing
on genuinely repeated tasks (i.e., fitting cross-sectionally) maximizes
a composite (pseudo-) likelihood: each situation’s
marginal probability is still correctly specified under
,
so the estimator stays consistent for
,
provided the per-situation marginals identify
,
but it is statistically inefficient — it never uses the fact that the
same
generated a person’s repeated choices, which is exactly the variation
that identifies
most sharply (the marginals identify it too, but only through the shape
of the mixture). Cluster-robust standard errors
(cluster_col=, or vcov(fit, type = "cluster");
§9.5) repair the inference for the resulting score dependence
but leave the likelihood unchanged; §2.6, §3.5 and §4.5 give the panel
likelihood, score and Hessian that use the repetition directly.
run_hmnlogit() is the Bayesian counterpart of the panel
likelihood, adding partially-pooled alternative effects and posterior
rather than asymptotic inference.
2. Log-Likelihood Function
2.1 Choice Probability
For a given draw , the probability that individual chooses alternative follows the logit formula:
If an outside option is included, it is normalized to .
2.2 Simulated Probability
Since the random coefficients are unobserved, we integrate over their distribution using simulation:
where is the alternative chosen by individual .
2.4 Log-Sum-Exp Trick for Numerical Stability
To avoid numerical overflow/underflow, the implementation uses:
Probability computation: Before computing , subtract :
-
Log-probability averaging: Use log-sum-exp to compute :
Applied iteratively across draws . With
person_col(§2.6), each draw’s log-probability is first summed across a decision maker’s situations, , and only then does log-sum-exp run over draws to obtain . Log-probability of the chosen alternative: each term of is formed directly in log space, as the chosen utility minus the log-sum-exp of the choice set, never as the logarithm of , which turns subnormal beyond a utility gap of about 708 and underflows to zero beyond about 745 (the multinomial logit kernels use the same form). Neither a single choice probability nor a product of many is ever formed outside log space, so and are finite, and exact, whenever the utilities are finite, however poorly the parameter vector fits the observed choices.
2.5 Statistical Properties of the Finite-Draw Criterion
For independent pseudo-random draws, is an unbiased simulator of the exact mixed-logit probability. Its logarithm is not: Jensen’s inequality gives when the simulator is nondegenerate, and a second-order expansion gives the familiar criterion bias. Under the regularity conditions in Hajivassiliou and Ruud (1994), Lee (1995), Gouriéroux and Monfort (1996), and Train (2009, Ch. 10), the classical pseudo-random MSL benchmarks are:
- Fixed : MSL is inconsistent — the simulation bias does not vanish as .
- with (at any rate): MSL is consistent.
- rising faster than : MSL is asymptotically equivalent to exact maximum likelihood — simulation bias is and simulation variance is negligible under the maintained draw scheme.
choicer uses a Halton sequence rather than independent
pseudo-random draws (§5.4), so the first sentence above is not a literal
property of its deterministic store-mode simulator, and the
pseudo-random rate conditions should not be quoted as an exact theorem
for this implementation. Quasi-Monte Carlo often reduces integration
error markedly at a given
(Bhat 2003), but its error depends on integrand smoothness, dimension,
sequence construction, and randomization. The operational implication is
to treat
and, for generated scrambled draws, the seed as part of the numerical
specification; increase
until estimates, the Cholesky block, the objective, and standard errors
stabilize. mc_asymptotics() supplies Monte Carlo
diagnostics rather than a proof that a particular
finite-
fit satisfies exact-ML asymptotics.
2.6 Panel Likelihood
With person_col, §1.6 replaces the per-situation
likelihood by the per-decision-maker one. Writing
for the log-probability of decision maker
’s
choices at draw
— a sum, over the situations sharing that draw, of the situation-level
log-probabilities of §2.1 — the simulated log-likelihood is
with
a decision-maker weight, constant across
’s
situations — a requirement of this panel objective, not of §9.1–§9.2’s
WESML weights, which vary with the alternative a person chose and can
therefore differ across their situations; WESML is accordingly not
supported with person_col. Define the posterior
draw weight
the simulated posterior probability that draw is decision maker ’s taste, given the choices they made — computed via the max-shifted log-sum-exp of §2.4, so it never forms the product of many situation probabilities outside log space. §3.5 and §4.5 write the panel score and Hessian in terms of . Setting collapses to and to , the per-draw share already implicit in §2.3’s , so the panel and cross-sectional log-likelihoods agree termwise.
3. Gradient Computation
3.1 General Formula
Define for draw the log-probability of the chosen alternative:
The gradient of this with respect to utility is:
3.2 Per-Draw Gradient
Define as the gradient of utility with respect to parameters. The per-draw gradient is:
Vectorized implementation. Define the logit residual vector with elements . The per-block gradient components collapse to matrix-vector products — computed once per draw rather than looped over alternatives:
| Block | Scalar sum | Vectorized form |
|---|---|---|
where
(Wt_diff in the code) is computed once and shared across
the
and
blocks. The
block uses an irregular alt-index scatter and is kept as a loop.
Code reference: src/mxlogit.cpp
3.3 Gradient of Simulated Log-Likelihood
Using the identity for the derivative of a logarithm of a sum:
The full gradient is:
Code reference: src/mxlogit.cpp
3.4 Utility Derivatives by Parameter Block
3.4.2 Random Coefficient Means ()
For Normal distribution:
For Log-Normal distribution:
Both cases are captured by dmu_final_dmu(p)
(
for normal,
for log-normal). Summing over alternatives:
.
Code reference: src/mxlogit.cpp
3.4.3 Cholesky Parameters ()
Let denote the parameter for (where ).
Step 1: Derivative of with respect to :
Step 2: Derivative of with respect to :
Note: , so only the term with contributes.
Step 3: Derivative of transformed :
For Normal distribution:
For Log-Normal distribution:
Step 4: Chain rule for utility derivative:
Step 5: Summing over alternatives using :
For the diagonal case, all
parameters are computed simultaneously as
Wt_diff % dgamma_final_dgamma % L.diag() % eta_i_s. For the
full correlated case,
Wt_p = Wt_diff(p) * dgamma_final_dgamma(p) is factored out
per row
.
Code reference: src/mxlogit.cpp
3.4.4 Alternative-Specific Constants ()
where (normalized) if no outside option, or all for are free if outside option is included. The sum over alternatives is a simple scatter (one non-zero contribution per alternative), implemented as a loop.
Code reference: src/mxlogit.cpp
3.5 Panel Score and Posterior Draw Weights
With person_col, the per-draw score of §3.2 is first
summed across a decision maker’s situations,
(each
the situation-level score of §3.2–§3.4), and then averaged over draws
with the posterior weight of §2.6 in place of the per-draw probability
share of §3.3:
This is §3.3’s with replaced by and replaced by the situation-summed ; recovers §3.3 termwise. The block decomposition of §3.4 (the // BLAS collapse via , and the scatter) is unchanged within a situation.
Implementation. The double sum over situations and
draws needs no explicit loop over
:
mxl_unit_simulate() already stacks the logit residual
of every row of every situation belonging to unit
into one
matrix DiffW
(
= stacked alternative rows across all of
’s
situations), because
is a single per-draw weight shared by every situation in the unit.
then gives the
,
and
blocks directly, exactly as §3.2’s vectorized table builds them from
— the situation sum is absorbed into the row-stacking, and the draw sum
into the matrix-vector product, in a single pass.
DiffW is formed
draws at a time,
,
with
unless the two
matrices (DiffW and
)
would exceed a small per-thread budget (4 MiB, sized to stay in cache):
a unit is split into batches (of sizes differing by at most one draw)
only when
,
i.e. for a long panel, a choice set of hundreds of alternatives or a
very large
,
and a thread’s memory then grows with
rather than
.
Each batch is folded in before the next one overwrites it.
accumulates by a streaming max shift: the batch’s weights
are taken relative to the largest
seen so far. The running sum is rescaled by
whenever
rises, then divided by
at the end, the same denominator used to normalize
.
Keeping the maximum separate from this denominator avoids losing
normalization accuracy through subtraction of a large-magnitude
log-sum-exp. Batching changes
only by rounding (about one rounding per batch), and a unit in one batch
computes exactly the unbatched values. The
block cannot collapse through
alone: its per-draw derivative couples the residuals with that draw’s
(§3.4.3), so the draw sum has to happen after that coupling;
each batch writes its columns of
(,
small whatever
is), and mxl_unit_score_cont() then forms
(;
a situation-stacked dgemm for the inner product, then a
draw-block dgemm against
),
and reads
’s
score off
.
(The Hessian, §4.5, needs an explicit per-situation loop because its
outer-product terms cannot be pre-summed across situations before being
squared.)
Code reference: mxl_unit_simulate(),
mxl_unit_score_cont() (the continuous block, with the
collapse), mxl_unit_score() and
mxl_unit_score_local() (the delta block, over every
parameter or the unit’s own, §4.4.6) in src/mxlogit.cpp,
shared by mxl_loglik_gradient_parallel,
mxl_scores_parallel, mxl_bhhh_parallel and
mxl_cluster_meat_parallel.
4. Hessian Computation
4.1 General Formula
Define: - — the gradient for individual - — the per-draw gradient - — the per-draw Hessian
The Hessian of the simulated log-probability for individual is:
The full Hessian is:
Code reference: src/mxlogit.cpp
4.2 Per-Draw Hessian
The per-draw Hessian has the form:
where is the Hessian of utility.
In the code, this is computed as: - sum_Pzz
- sum_Pz
- sum_diff_H_V
Then:
Code reference: src/mxlogit.cpp
4.3 Second Derivatives of Utility
Most second derivatives are zero since utility is linear in most parameters. Non-zero second derivatives arise from:
4.3.1 Mean Parameters () — Log-Normal Only
For log-normal distribution:
Code reference: src/mxlogit.cpp
4.3.2 Cholesky Diagonal Parameters ()
Since :
For normal distribution:
For log-normal distribution (combining chain rule):
where .
Code reference: src/mxlogit.cpp
4.3.3 Cholesky Cross-Derivatives Within a Row
Let with and define
Distinct Cholesky parameters affect the same transformed coefficient only when they belong to the same row . Their cross derivative is
where for a normal coefficient and for a log-normal coefficient. Hence the cross derivative is zero for normal coefficients and equals for log-normal coefficients. This expression also covers a diagonal/off-diagonal pair (say ); restricting both indices to be off-diagonal would omit terms that the C++ Hessian includes. Cross derivatives across different rows of are zero. The separate shifted term implies no – cross derivative.
Code reference: src/mxlogit.cpp
4.4 Implementation Tricks in mxl_hessian_parallel
The subsections below describe the computational restructuring used
by mxl_hessian_parallel. They cover (i) a block
decomposition of the score vector and Hessian terms, (ii) buffer
accumulation that eliminates the per-draw dense matrix allocation, (iii)
BLAS-3 batching of two outer-product sums, (iv) the separation of the
draws from the alternatives, which turns every sum over both into matrix
products of the situation’s probabilities with small matrices, (v) the
symmetry strategy used for final assembly, and (vi) the compact block of
the parameters a unit’s likelihood involves, in which (i)–(v) run, and
how the blocks are accumulated into the result.
A reader who has never seen the C++ can understand what the function does and why the result is numerically equivalent to the per-draw naive form (§4.1–4.2) from these sections alone.
4.4.1 Parameter Block Layout and Score Vector Decomposition
The parameter vector is partitioned into a continuous block of length and a delta block (ASCs) of length :
The boundary index
is stored as idx_delta_start in the code.
The per-draw score vector inherits this partition: . The continuous sub-vector is
where is the continuous-block utility gradient for alternative at draw . The delta sub-vector scatters logit residuals into the ASC index for each alternative.
Define also: - (the cc weighted-score sum, plus a -length delta counterpart ), - (, symmetric), and its cd () and dd (diagonal -vector) sub-blocks.
4.4.2 Block Buffer Accumulation — Identity C
Two of the three terms in (§4.2) are linear in the draw weight :
Their draw-weighted sum can therefore be accumulated directly into per-individual buffer matrices without constructing the full dense matrix at each draw:
This replaces the original path that assembled the full
at every draw and then computed
hess_term1_numerator += P_s * (g_is * g_isᵀ + H_is). The
per-draw blocks
and
are not formed either: §4.4.4 reads every buffer off two matrix products
per situation, except for a likelihood unit outside that section’s
range, whose blocks are formed as here.
The block structure of buf_Pzz minimizes memory by
storing only the three structurally distinct sub-blocks:
| Buffer | Shape | Content | Notes |
|---|---|---|---|
buf_Pzz_cc |
Symmetric | ||
buf_Pzz_cd |
Rectangular; not symmetric | ||
buf_Pzz_dd |
-vector | Diagonal only | |
buf_diff_HV_cc |
Symmetric; cc block only ( has no delta rows) |
All four buffers are thread-private scratch, zeroed at the start of each individual . In the code the cd and dd buffers hold only the constants that ’s likelihood involves (§4.4.6), so they grow only to the largest such block their thread meets.
4.4.3 BLAS-3 Batching of Outer-Product Sums — Identities A and B
The third term in — — is not linear in , so it cannot go into a linear buffer. Instead, together with the OPG term , it is handled by reformulating both weighted outer-product sums as a single BLAS level-3 matrix multiply.
Identity A (OPG batching). With the normalized draw weights , , and the weighted mean score , define the matrix with columns
Then
Proof.
,
because
.
The identity requires only
,
which holds because
is a softmax probability (guaranteed by stable_softmax). It
folds the OPG term and the final
of the Hessian (§4.4.5) into one product, and the centered form is also
the numerically stable one. The implementation normalizes max-shifted
exponentials directly, then subtracts the highest-weight draw’s score
before computing the weighted mean of the deviations. This prevents a
large common score from amplifying rounding in the weights into spurious
covariance.
Identity B (sum-Pz outer-product batching). Define the matrix with columns
Then
by the same expansion without the centering. The linear buffers of §4.4.2 are likewise accumulated with in place of , which divides them by once and for all.
Combined BLAS-3 form. Concatenating and into and forming one matrix product gives
because
and the block multiply sums over
columns with no
-
cross term. This is the form implemented in
mxl_hessian_parallel: G_stash and
F_stash are filled column by column from the products of
§4.4.4, and opg_pz accumulates
and
as two separate
rank-
BLAS level-3 updates rather than one join_rows product
(§4.5 explains why: with person_col,
is squared and added once per situation while
accumulates across situations and is squared once per unit; the two
coincide here because §4.4 is the single-situation,
case). The result is
in cache-friendly level-3 kernels.
Floating-point precision. Changing the summation
order (per-draw increments vs. one level-3 multiply) is a reassociation
of additions that is exact in real arithmetic. In floating-point the
results differ only by rounding. Across 10 equivalence scenarios
sweeping all combinations of rc_dist,
rc_correlation, and rc_mean, the worst-case
element-wise deviation from the per-draw form was
,
several orders of magnitude below the
tolerance enforced by the package’s equivalence tests.
4.4.4 Separating the Draws from the Alternatives — Identity D
Identities A–C still sum over every alternative
and draw
of the situation. Formed term by term, buf_Pzz_cc alone
takes a
rank-one update per alternative and draw,
operations per situation, and these updates dominated the kernel: on a
school-census design, removing them halved its time with ten fixed
coefficients
()
and cut three quarters of it with thirty. The derivatives of utility
have a structure that turns every such double sum into matrix products
of the situation’s
probability matrix with small matrices, so that what remains per
alternative and draw is the softmax that forms the probabilities.
The factorization. Split the continuous part of the utility gradient (§3.4) into the coefficients whose derivatives do not depend on the draw and the Cholesky parameters:
where , (§3.4.2), indexes the Cholesky parameter , and as in §4.3.3; is the derivative of the transformed deviation in (§3.4.3, Steps 1–3). The constants’ part of is an indicator. So and the constants do not depend on the draw, and each Cholesky entry of is a covariate of the alternative, , times a factor of the draw, . The second derivatives of utility (§4.3) factor the same way: they are nonzero only at , where they equal , and between two Cholesky parameters and of one row, where they equal with
Two products per situation. Every term of Identity C has the form : a covariate of the alternative times a factor of the draw (with the residual in place of for ), and every entry of the columns of and that Identities A and B multiply out is such a sum at one draw, (with the residuals for ). A sum over both can be taken over the alternatives first or over the draws first,
where is the matrix of the probabilities , a row per alternative, the outside option’s included when there is one (its covariates are zero, so it drops out of every sum until they are centered below). Collect the covariates in , whose last block holds the products for , and the draw factors in , an matrix for Cholesky parameters. Two products per situation then give every sum:
The columns of are the sums over the alternatives at each draw: , and . The rows of are the sums over the draws for each alternative: its posterior probability and . The residuals need no product of their own: and
are rows of less the chosen alternative’s covariates (nothing is subtracted from when the outside option is chosen); is the matrix of §3.5.
Identity C, block by block, is then
with the row of in the second, the column of a constant in the cd block, , and its dd entry (sums over the rows that list alternative ); and
The blocks with at most one Cholesky index sum over the draws first (through ); the block sums over the alternatives first, since its covariate products number where its draw products number ; and , whose sum over the alternatives is , does too.
Identities A and B read their columns off as well. Column of (§4.4.3) is
and the score in column of is the same with the residuals for the probabilities, . and are formed as in §4.4.3.
Cost. Per situation the two products take operations, against for the rank-one updates they replace, and the per-draw vectors of §4.4.1 are never formed. The blocks read off the products cost per situation and per likelihood unit, and Identities A and B keep their products (§4.4.6).
Centering. Identities B and C nearly cancel: at each draw, is minus the covariance of across the situation’s alternatives, which is small next to either term when the covariates share a large common level or the probabilities are nearly degenerate; and the two products of this subsection associate their sums differently, so that, formed from the levels, their rounding errors would not cancel with them. The covariance, and the scores, are unchanged when every alternative’s covariates are shifted by one vector , the outside option’s included (its covariates are zero, so it takes ): the probabilities sum to one and the residuals to zero,
with the sums over every alternative. A shift of by shifts each Cholesky entry by , the same for every alternative at a draw, so the identities hold for it as well. The kernel shifts and by the covariates of the alternative with the largest posterior probability (by zero when that is the outside option) before forming , so that both products work on the covariates’ deviations rather than their levels.
Floating point. The identities hold in real arithmetic and change only the order of the additions. Judged against a 60-digit evaluation of the per-draw formulas (§4.1–§4.3) on 137 Hessians of the package’s reference battery, the largest normwise error, , was on designs with columns of ordinary scale, on designs with columns rescaled by factors between and , and with columns rescaled by (nearly degenerate probabilities); the per-alternative accumulation it replaces erred by , and on the same Hessians, the last in entries whose exact value is below .
Range. Identity D takes the utility’s derivatives apart. A Cholesky entry and a mean’s derivative are products, and the blocks above multiply their factors separately ( in ; and after the sums), where the per-alternative formula of §4.4.1–§4.4.2 squares the derivatives themselves. A factor can then pass the double range (about before it is squared) where the derivative does not: a log-normal draw factor of against covariates that are zero, whose exact terms are zero rather than ; covariates of against Cholesky entries of ; a mean derivative of against covariates of ; covariates of and , whose difference, the centering, overflows by itself; or covariates of against draw factors of (about ), whose products underflow to zero where the derivatives’ squares, near , do not. Information that small still matters: it can be strongly correlated with that of a parameter of ordinary size, so that dropping it, or reversing its sign, moves that parameter’s standard error. Scaling a unit’s covariates by one power of two does not mend this: in a panel, one task’s large covariates would push another task’s ordinary ones below the double range.
The kernel therefore checks each likelihood unit before forming it. It uses Identity D when every nonzero covariate, draw factor and mean derivative is at least (about ) in magnitude, every and at most (about ), and every covariate’s spread over a situation’s alternatives (its maximum less its minimum, the outside option’s zeros included) at most , all of them finite. A covariate’s common level, however large, spreads nothing. The centered covariates are then zero or between and , so no product overflows, and one can fall below the normal range () where the derivatives’ products would not only at an alternative and draw whose probability times draw weight is below . A term lost there is below , and every term formed there below : a parameter whose information comes from such alternatives alone has a standard error beyond , and its correlation with any parameter of ordinary information is negligible.
A unit outside that range is formed by the per-alternative formula instead, which forms the utility’s derivatives before any product and so keeps their range. Its arithmetic is that formula’s, in its order, with three kinds of term left out where exact arithmetic leaves them out and the formula’s would not be finite, or not zero. A draw of weight zero adds nothing to Identity C or , as in Identity D. Where is zero (a normal coefficient, or a log-normal draw whose underflowed), the diagonal factor (§4.3.2) has no first term, which would be once passes about (Identity D’s leaves it out too). And a covariate with one value on all of a situation’s alternatives adds nothing to that situation: it moves no probability there, so its terms cancel exactly. forms none of its curvature factors there, which can overflow against a covariate that is zero (with or without an outside option), giving where the exact term is zero. Without an outside option, a finite, nonzero value also enters as zero, as Identity D’s centering makes it: summed from its level, its terms leave rounding, enough to give a covariate that varies within no situation a nonzero row of the Hessian and a finite standard error. Elsewhere it repeats that formula bit for bit: with every unit sent to it, 1,683 of the 1,700 Hessians that main’s tests compute equal main’s, and the other 17, each with a situation where a covariate has one value (in 16, a situation with one alternative), differ from them by at most in the measure above.
Scores that cancel. Both formulas, like the kernel before them, weight by the residuals of rounded probabilities: through the sums above, or one alternative at a time. Where a unit’s situations mirror one another, the residuals’ sums over its situations cancel at leading order, leaving a term of first order in the random coefficients’ contributions to utility. Two binary situations with covariates and on their two alternatives, chosen differently, where the rest of the utility ties the alternatives, give , with the random coefficients’ utility difference at draw . What is left of , in the information, is of the same order in as the rest of that parameter’s information, , and can be as large, and through that parameter’s correlation with a fixed coefficient it moves the fixed coefficient’s standard error. Formed from probabilities rounded near , it carries a relative error of about , and once is below about it is lost: Identity D drops it, and the per-alternative formula leaves in its place a rounding residue of either sign, far larger than the term. The problem is ill-conditioned there. In such a panel with near (covariates of against a log-normal coefficient near ), the fixed coefficient’s standard error is 1.81, and moving one situation’s covariate by one unit in the last place makes it 1.41, or leaves the information indefinite (exact arithmetic, at 1,300 digits). At these draws the kernel gives 3.09, the standard error without the term; at nearby draws the per-alternative formula also gives 1.41, or an information that is not positive definite. Each is what exact arithmetic gives for a covariate less than one unit in the last place from the given one. With near the kernel gives 1.81 to eight digits.
4.4.5 Final Assembly and Symmetry
After the products of §4.4.3–§4.4.4 for individual
,
let
, with the weights of
§4.4.3. The Hessian
is assembled
block-by-block into hess_t1 (the code builds it in place in
opg_pz, reading each block before overwriting it):
The cd block is rectangular
()
and not symmetric, so both the cd and dc sub-matrices are written
explicitly into hess_t1. The normalized draw weight
replaces a separate division by
,
and the centered
of Identity A already carries
,
matching §4.5’s Louis-identity assembly:
Symmetry strategy.
is exactly symmetric in floating point, not only in exact arithmetic:
and
are symmetric products, each block of buf_Pzz_cc and
buf_diff_HV_cc is formed on its upper triangle and
mirrored, and the dc block is written as the transpose of the cd block.
So only the upper triangle of
is added into the result, which is mirrored once after the parallel
region (§4.4.6); the mirror is the sum the lower triangle would have
accumulated.
4.4.6 Compact Blocks and Accumulation
A likelihood unit’s score and Hessian are zero outside the continuous block and the constants of the alternatives the unit faced (unit : a decision maker, or a choice situation in the cross-section, §1.6). Let be the number of free ASCs among the alternatives in ’s choice situations (the normalized reference has none without an outside option, and the outside option has none), and the number in situation . Everything in §4.4.1–§4.4.5 runs in ’s compact block of local parameters, the continuous parameters first and then ’s free ASCs in increasing global order, so that each -sized piece there is restricted to the constants ’s likelihood involves. Each situation has its own slots as well: the per-situation pieces (the probability sums and ) are formed on its parameters and added into ’s slots, and an alternative listed twice in a situation adds into one slot, as the dense scatter did. The product then costs per unit and each costs per situation, instead of : on a school-census design with 2,620 parameters, a student’s likelihood involves 59 of them on average.
is added into the result at its global indices, upper triangle only (§4.4.5). With one thread the blocks are added into the result itself. With several, each thread adds into its own packed upper triangle while the threads’ triangles, doubles each, fit in 2 GiB together (up to about 7,000 parameters at eleven threads), and the triangles are added up in thread order. Above that the threads share the result: each keeps private only the rows of the continuous parameters, which every unit touches, and adds the ASC block atomically. The two differ only in the order of the additions. Per-thread triangles are kept where they fit because they need no atomic additions: at census scale with eleven threads, the clustered meat of 200,000 students in 2,000 clusters (§9.5) took 1.37 s with them and 1.82 s with a shared result, and the BHHH matrix of 200,000 students 1.23 s and 1.32 s; the Hessian took the same time either way, and only with two draws, where accumulation dominates, was the shared result faster (the BHHH matrix in 0.47 s against 0.52 s). The BHHH kernel’s rank-one updates (§4.1’s score) use the same blocks and accumulators, and the cluster meat’s update with each cluster’s summed weighted scores (§9.5) the union of its units’ blocks.
Non-finite terms spread as the dense products spread them: a
non-finite row of
or of the centered
makes the rows and columns of the parameters concerned NaN
in the result
(),
and a non-finite weight makes every entry outside the unit’s block
NaN
(;
NA for a missing weight), or, with several such units,
every entry outside the intersection of their blocks. A draw whose
weight
is zero (its likelihood underflows next to the unit’s largest) is left
out of the per-unit sums of §4.4.4’s
and
blocks, as in exact arithmetic, because their draw factors
and
may overflow at such a draw; it still enters
and
,
so a draw factor
that is itself non-finite makes its parameters’ rows and columns
NaN by the rule above.
4.5 Panel Hessian: the Louis (1982) Identity and Its Two-Pass Assembly
With person_col, §4.1’s per-situation Hessian
generalizes to decision maker
by the Louis (1982) missing-information identity, treating the draw
as missing data and
’s
choices as the observed data:
with as in §3.5 and the situation-summed per-draw Hessian of §4.2. Because is already normalized (, §2.6), this is directly, with no separate division step — the same normalized form as §4.4.5’s (defined there). Setting makes §4.4.5’s formula the special case of the one above, term by term.
Two passes per decision maker. Unlike the score
(§3.5), the Hessian cannot be read off the situation-stacked residual
matrix alone: its outer-product terms must be squared within a
situation before being summed across situations, since summing residuals
across situations first and squaring once would cross-multiply different
situations’
vectors — an identity the algebra does not license.
mxl_hessian_parallel therefore runs two passes per unit,
sharing the same draw loop that computes
(§2.6):
-
Pass 1 is the draw loop of
mxl_unit_simulate()without residuals, the same operations in the same order: it yields (the per-draw log-likelihoods of the unit’s choices), their log-sum-exp over draws, and — exactly as in §3.5 — and keeps every situation’s probabilities at every draw for pass 2. -
Pass 2 loops over the situations
.
For each it takes the probability matrix
(its
inside alternatives and the outside option, at every draw) from pass 1,
or, for a unit whose rows-by-draws matrices exceed the batch budget of
§3.5
(
above
,
with an outside option) and which pass 1 therefore splits into batches
of draws without keeping them, forms it from that situation’s
rows of
,
so that a thread’s memory grows with the largest choice set rather than
with the unit; then it forms the two products of §4.4.4,
and
.
The draw weights
and the draw factors
are the unit’s, shared by all its situations, since its draws are:
-
Identity C (linear pieces): the blocks read off
(
buf_Pzz_cc’s and blocks,buf_Pzz_cd,buf_Pzz_dd) are summed over the situations; the block andbuf_diff_HV_ccdepend on the situation only through and , so these are summed across the situations draw by draw, and (the latter is §3.5’s ), and the two blocks are formed once per unit — linear accumulation does not care whether it is summed within or across situations. -
Identity B (
F_stash, the term): column is overwritten each situation with , read off , and , formed on the situation’s slots (§4.4.6), is added intoopg_pzonce per situation, immediately after it is formed — situations’ outer products are added, never combined before squaring: . -
Identity A (
G_stash, the score outer product): column instead accumulates across every situation in the unit (its and Cholesky rows once per unit, from ), and only after the situation loop ends is it centered at , scaled by and squared once: with — the situation sum must happen before squaring here, the opposite order from Identity B, because it is the person’s total score that enters the outer product, not each situation’s on its own. Since the sum to one, this is the Louis identity’s , computed without its cancellation. In code,g_barfirst holds a highest-weight draw’s score, which is subtracted from every column; it then holds the weighted mean of those deviations, subtracted in turn. This is equivalent to centering at while avoiding amplification of weight-rounding error by a large common score.
-
Identity C (linear pieces): the blocks read off
(
Final assembly mirrors §4.4.5’s block-by-block combination
(hess_t1 = opg_pz - buf_Pzz + buf_diff_HV, cc/cd/dc/dd),
whose centered Identity A already carries the Louis identity’s
,
and closes by adding the upper triangle of
hess_t1
into the result (§4.4.6) — no
step, because
is already a normalized weight (§2.6), as in §4.4.5. Setting
collapses pass 2 to a single situation per unit: F_stash
(holding
)
and G_stash (holding
)
remain different vectors, but with only one situation to loop over, F’s
per-situation overwrite and G’s cross-situation
accumulate produce the same result, and the two-pass structure
reduces exactly to §4.4’s single-situation accumulation.
The non-finite-likelihood guard. Pass 1 skips a unit
only when its log-sum-exp is non-finite,
!std::isfinite(lse). Because every
is formed in log space (§2.4), lse is finite whenever the
unit’s utilities are, however poorly the unit is fit; the guard fires
only for utilities that overflow, where the unit’s log-likelihood is
undefined. It replaces the former
threshold of §5.4, which could also discard a unit that was merely very
poorly fit under the current parameter vector. See §5.4 and
NEWS.md.
Code reference: mxl_hessian_parallel() in src/mxlogit.cpp.
5. Implementation Details
5.1 Parameter Vector Structure
The full parameter vector is organized as:
| Block | Indices | Length | Description |
|---|---|---|---|
| Fixed coefficients | |||
(if rc_mean=TRUE) |
Random coefficient means | ||
| next block | or | Cholesky parameters | |
| remaining | , , or | Free ASCs |
The ASC length is zero when use_asc = FALSE,
without an outside option, and
with an outside option. The low-level parser requires at least one
fixed-coefficient column
(),
even when the substantive focus is entirely on random coefficients.
5.2 Delta Method for Variance Parameters
When reporting results, the Cholesky parameters are transformed to variance matrix elements .
The Jacobian
is computed analytically in jacobian_vech_Sigma().
For element :
This follows from the product rule applied to : , where is the matrix with a single non-zero entry .
The variance-covariance matrix of is then:
Code reference: src/mxlogit.cpp
5.3 OpenMP Parallelization
The implementation parallelizes over likelihood units (§1.6) using
OpenMP, with dynamic scheduling for load balancing
(#pragma omp for schedule(dynamic)): - The log-likelihood
and gradient keep thread-local accumulators, combined in a
#pragma omp critical section. - The Hessian and BHHH
kernels add each unit’s compact block, and the cluster meat each
cluster’s, into per-thread packed upper triangles, added up in thread
order after the parallel region, or into a shared result when those
would exceed 2 GiB (§4.4.6). - Before allocating, each estimation kernel
compares an upper estimate of its working memory, per thread and shared,
with the machine’s physical memory (or
options(choicer.max_memory)), and stops with an error
naming the number of threads that would fit instead of running out of
memory inside the parallel region. - The elasticity and diversion-ratio
kernels (§6, §7) add each choice situation’s terms into a
sum: one thread into the result itself,
threads into copies of their own while those fit in 2 GiB (added up in
thread order), and beyond that into the shared result atomically, each
thread keeping the outside option’s row and column to itself. They check
the memory of that sum and of their working arrays the same way
first.
5.4 Practical Notes
Negated Objectives:
mxl_loglik_gradient_parallelreturns and ;mxl_hessian_parallelreturns . The BHHH kernel instead returns the positive-semidefinite information approximation .ASC Identification: When
include_outside_option = FALSE, the first inside alternative’s ASC () is fixed to zero for identification. Wheninclude_outside_option = TRUE, all inside ASCs are free parameters (the outside option with serves as the reference).Gradient vectorization: The per-draw gradient is computed without a per-alternative loop. After forming , the and / blocks are evaluated with two BLAS dgemv calls ( and ). The delta block uses an irregular scatter and remains a loop.
Exact draw layout and source: In both modes, likelihood unit (§1.6: a decision maker under
person_col, a choice situation otherwise) receives the contiguous global indices for ; dimension uses the th prime base and the resulting uniform is mapped through the standard-normal inverse CDF. Indraws = "store",randtoolbox::halton(n = U*S, dim = K_w, normal = TRUE)is materialized as a cube during estimation, one block per unit ( decision makers underperson_col, or choice situations otherwise). It is filled a block of units at a time withhalton(start = ), which returns exactly those points. Store mode needs , the largest starting indexhalton()accepts. The prediction family (predict(),elasticities(),diversion_ratios(),blp(),logsum(),consumer_surplus(), andgof()throughpredict()) integrates over one block per choice situation instead ( blocks for a panel fit, not ), which it forms on the fly from the same points of the sequence (§5.5), with no limit on for up to 128 random coefficients. The fitted object retains onlydraws_infometadata, not the cube; the estimation-type functions (vcov(type = ),wesml_vcov(),conditional_tastes()) rebuild it. This mode is deterministic and has no seed or scramble. Indraws = "generate",HaltonGencomputes the radical inverse on demand.scramble = "none"uses identity permutations and is tested against therandtoolboxsequence.scramble = "permuted"(the default) constructs one independently seeded Fisher–Yates permutation for every (dimension, digit-position) pair and shares that table across sequence indices. Evaluation stops after the last nonzero base- digit, so trailing zero digits remain unchanged. This is not Owen nested-uniform scrambling: the digit permutation does not depend on the preceding digit prefix, and the construction does not make each point marginally uniform. Consequently it carries no standard RQMC unbiasedness, variance-rate, or replicate-based error-estimation guarantee. The historical API value"owen"is a deprecated alias for"permuted"; old fitted objects carrying that serialized label remain readable. The result is deterministic conditional on the seed and independent of OpenMP scheduling. Numerical sensitivity should be assessed by increasing and, for permuted draws, varying the seed. Generate mode is available only through the convenience data workflow; the advancedinput_dataworkflow requires an expliciteta_drawscube.Finite-value guards: The likelihood/gradient kernel replaces a non-finite global negated objective by and a zero gradient, allowing the optimizer’s line search to backtrack; isolated non-finite gradient entries are zeroed. The Hessian contributes a likelihood unit — decision maker under
person_col, choice situation otherwise (§1.6, §4.5) — only when its log-sum-exp is finite. Since every is the chosen utility minus a log-sum-exp (§2.4), , and the objective are finite whenever the utilities are, however poorly the parameter vector fits the observed choices: the sentinel, the Hessian’s skip and theNAconditional tastes (§13) all fire only when the utilities themselves overflow (for instance an exploding Cholesky diagonal during a line search), where the log-likelihood is undefined. (Earlier releases skipped a situation whenever , which could also discard a situation that was merely very poorly fit rather than genuinely zero-probability, biasing the reported Hessian and its standard errors; and until the log-space form of §2.4, a single choice probability that underflowed to zero, at a utility gap beyond about 745, made the whole objective the sentinel with a zero gradient, while subnormal probabilities, at gaps beyond about 708, lost precision. SeeNEWS.md.) Relatedly, the posterior draw weights (§2.6) that both the score (§3.5) and the Hessian (§4.5) are built from are computed in log space via log-sum-exp rather than as a ratio of raw probabilities, so they stay finite and accurate even when the product over situations falls far below the smallest double — the earlier raw-probability construction could return an identically zero gradient at a genuinely poorly-fit point, a false stationary point for the optimizer. These are numerical failure guards, not changes to the mathematical criterion in its regular finite region.Constants without a finite estimate: By §3.5 the score of alternative ’s constant is , with the alternative chosen in situation of unit and the inner sum over the situations that offer : a positively weighted sum of terms with . If is never chosen in the data every term is negative, and if it is chosen in every situation that offers it every term is positive, at every value of . The likelihood then keeps rising as (or ), toward a supremum it never attains: has no finite maximum-likelihood estimate, the optimizer stops it wherever its tolerance does, and its standard error is not meaningful. At that supremum ’s probabilities are 0 (or 1), so the other parameters approach the maximum of the likelihood without alternative (or without the situations that offer it). The same holds for the reference whose constant is normalized to 0, the outside option or the base alternative: the other constants then diverge together, and with the outside option never chosen the supremum is the model without it.
run_mxlogit(), likerun_mnlogit()andrun_nestlogit(), warns before the optimizer runs, from the counts inalt_mapping(classchoicer_unbounded_constants); a finite bound in the direction a constant diverges (lowerfor a never-chosen alternative’s,upperfor an always-chosen one’s) holds it at the bound, and that alternative is not named. The Newton phase (§5.7) holds the named constants of inside alternatives at the optimizer’s values.
5.5 Data Layout
- has rows; situation occupies rows (64-bit offsets in the kernels).
-
may be row-aligned with
or have one row per global inside alternative; the kernels either read
the situation’s block of rows or gather rows by the global 1-based
alt_idx. The convenience R workflow constructs the row-aligned form. -
choice_idxis a 1-based local row position within each situation block, or 0 for an implicit outside choice.alt_idxis instead the global alternative ID used to gather ASCs and alternative-level rows. - Stored draws have dimensions
,
one block per likelihood unit
(
decision makers under
person_col, choice situations otherwise). Generate-mode kernels receive an empty placeholder cube plusgen_seed,gen_scramble, andgen_S. - Prediction kernels read one block per choice situation: situation
gets points
of the Halton sequence. With stored draws and up to 128 random
coefficients (the on-the-fly generator’s limit; beyond it they build the
cube), the prediction-type functions (
predict(),logsum(),elasticities(),diversion_ratios(),blp(), and through themconsumer_surplus()andgof()) never build that cube (thoughblp()may keep the draws across its iterations, §8.4): they pass an empty placeholder andgen_scramble = 2, and each thread forms its situation’s block on the fly fromHaltonGen’s identity-permutation uniforms, which arerandtoolbox::halton()’s points, mapped to normals by R’sqnorm()(R::qnorm, libR’s ownqnorm5), asget_halton_normals()maps them. The draws, and so the results, are the cube’s bit for bit (per situation at any thread count, and sums over situations at one thread; at more threads their rounding depends on the order in which threads take the situations, as it always did) whererandtoolboxand choicer are compiled with the same floating-point contraction: both add each digit’s term to the radical inverse in the same order, and agree bit for bit when both fuse those multiply-adds or neither does, as on CRAN’s platforms. Otherwise under 1% of the uniforms, all of bases 5 and up, differ in their last bit.
5.6 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 the BHHH matrix
of §9.5 ("bhhh"), or
with the bread
and meat
of §9.3 ("sandwich") or §9.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, §1.5), 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.
On one test design, a mixed logit’s robust variance, the bread had condition number , and equilibrated: its inverse was accurate either way, with standard errors within relative of an exact computation, but the sandwich’s standard errors, computed raw from an explicit inverse and two products, were off by relative, and equilibrated by . 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.
Code reference: invert_hessian(),
.sandwich_combine() and .jacobi_scale() in R/classes.R;
equilibrated_inverse() and
equilibrated_sandwich() in src/vcov.cpp.
5.7 Polishing the Optimizer’s Solution
run_mxlogit(polish = ) follows the optimizer with a
Newton phase. It does not change the estimator: it finishes the climb to
the maximum of the same simulated log-likelihood that the optimizer
approached, and certifies it. L-BFGS converges slowly at the end where
the curvature spreads over orders of magnitude, as it does across
thousands of alternative-specific constants (§1.5); near a regular
maximum Newton’s method converges quadratically.
The certificate. Write
,
at the current
,
and
for the curvature: the information
of §4 and §5.6 (polish = "newton") or the BHHH matrix
of §9.5, with the fit’s
weights ("bhhh"). The Newton step is
, and the Newton decrement
is the gain in log-likelihood that the quadratic model predicts for that step. On a positive definite information, is the step to the maximum of the quadratic model, and since , Cauchy–Schwarz in the metric of gives, for every linear combination ,
the remaining step moves each linear combination of the estimates by
at most
of its Hessian standard error. The polish has converged when
, computed with the undamped
curvature and
the mean weight, falls below tol_decrement
(
by default:
standard errors with weights of mean one); dividing by
makes the rule independent of the weights’ scale, as the estimates are,
where in raw units weights summing to one would loosen it by the sample
size. The polish then stops without taking the step, so the certificate
is for the point returned. With parameters held or on a bound (below),
is computed over the others, and the bound holds in their standard
errors conditional on the rest, which are no larger than the reported
ones.
BHHH needs no second derivatives and is positive semidefinite
everywhere; it can be positive definite only with at least as many
likelihood units as the parameters it moves, which "bhhh"
requires. Where
is positive definite, the step
to the quadratic model’s maximum satisfies
its squared length in the metric of the sandwich , the robust variance of §9.3 for an unweighted fit: bounds the remaining step in robust standard errors. But a small on its own shows only that is small, a stationary point, which BHHH’s positive definiteness cannot tell from a saddle. BHHH’s steps converge linearly, fast only where the information-matrix equality holds, which finitely many draws and misspecification break.
The step. The step solves, by Cholesky, the system equilibrated by the Jacobi scale of §5.6 and damped,
on the free parameters
(below).
consists of powers of two, so the scaled block is formed exactly, and
on it is the damping
of Levenberg (1944) and Marquardt (1963) to within a factor of two: the
step does not depend on the parameters’ units.
when the block’s diagonal is positive and its factorization succeeds
with a reciprocal condition number (estimated in the 1-norm, as
solve() does) above the machine epsilon
.
Otherwise (away from the maximum the simulated likelihood need not be
concave), and also when the step is not finite or its line search fails,
starts at
and grows tenfold, up to
.
A step longer than 10 units of the optimizer’s coordinates in some free
parameter
(,
with
the map of §1.5) is shortened to that length, its direction kept: a
maximum step, as in Dennis and Schnabel’s (1983) methods and
nlm()‘s stepmax. A free parameter whose step
exceeds ten maximum steps,
,
on a curvature that has all but vanished
(
below
times the free parameters’ median; see the limits below) is instead held
for that iteration and the step solved again without it: shortening its
step to the maximum would shorten every other parameter’s by more than
ten. A step that is long because the start is far from the maximum is
shortened. Under scale_vars = "none", whose coordinates are
the parameters’ natural units, the scales
are instead the BHHH map’s of §1.5 taken where the polish starts: one
gradient pass at the optimizer’s solution (clipped to the bounds),
powers of two, ones where the pass overflows. In natural units a badly
scaled column far from its maximum would be held as if its curvature had
vanished: in the multinomial and nested logits’ census- and claims-style
designs with half of the covariates rescaled by
and the other half by
,
20 steps at unit scales left a decrement of 1,054 to 2,060, where 8 or 9
at these scales certified the maximum.
Bounds. With lower/upper
the polish projects (Bertsekas 1982). A parameter within
of a bound across which its descent direction
points is
-active
and moves to the projection of its scaled-gradient step,
,
which reaches the bound when that step covers the distance (the line
search may shorten it);
,
the maximum over the parameters not held, with
the projected gradient step, shrinks to zero at a stationary point. The
other parameters are free. Convergence then requires the
-active
parameters on their bounds and the decrement over the free ones below
the tolerance: the Karush–Kuhn–Tucker conditions of the bounded
problem.
The line search. On the projected path , with displacement , is halved, up to 40 times, until Armijo’s condition holds. Near the maximum of a likelihood summed over units the rounding in is about , which at population scale reaches the gain of a correct step, so Armijo’s test can refuse it. Where the predicted gain is within , a step is also accepted on the approximate Armijo condition of Hager and Zhang (2005), the upper half of their approximate Wolfe conditions: and , which reads the gradient, accurate where is not. A trial point whose utilities overflow (§5.4), or whose objective or gradient is not finite, fails. Should accepted steps add up to a point worse than the start by more than , the start is returned.
What is held. The constants of §5.4, item 6, of inside alternatives (never chosen, or chosen wherever offered) are held at the optimizer’s values: they have no finite estimate, and the certificate concerns the other parameters given the held values. Those parameters approach the maximum without the alternative (or without the situations that offer it) only as the held constants approach their limits, so an optimizer stopped early leaves them further from it. When the reference itself, the outside option or the base alternative, is never chosen or chosen wherever offered, the other constants diverge together, and the polish does not report convergence, whatever its decrement, unless the reference is never chosen and the constants held or bounded above anchor all the others, which stops their rise. An alternative is anchored if its constant is held or bounded above, or if it is offered in a choice situation whose chosen alternative is anchored. With every constant that moves anchored, any direction that raises a set of them meets the situation that anchored the first of them; 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. A parameter whose curvature column and gradient are exactly zero carries no information at the current point (as where a log-Cholesky diagonal has gone so far toward that its derivatives underflow), and one held by the step rule above has all but none: either is left out of the steps, and the polish does not report convergence.
Limits. A random coefficient whose variance’s
maximum is at zero drives its log-Cholesky diagonal
(§1.4) toward
.
There
moves with
like
,
so the Newton step in
is about
and the decrement shrinks by a factor of only about
per step: the polish may stop at max_iter unconverged, or
certify a point where the variance is negligible but
,
and its standard error, are set by tol_decrement. With
finitely many draws the simulated likelihood can also carry a term
linear in the standard deviation,
. Of one sign it sends the
supremum to
as before (Newton steps of about
);
of the other it puts a maximum at a negligible standard deviation, which
the Newton polish certifies. BHHH’s curvature in that direction falls
faster than the Hessian’s (like
against
where the quadratic term leads,
against
where the linear one does), and its steps grow accordingly until the
rule above holds
,
before they can carry it to where its information underflows: the other
parameters then reach their maximum given it, and the polish stops
unconverged. On the shipped mode_choice data, with a
travel-time coefficient of mean zero and free variance
(rc_mean = FALSE), fixed cost and waiting-time coefficients
and 50 draws, the simulated likelihood has its maximum at
,
a standard deviation of about
per minute (0.001 to 0.023 in utility over the data’s 63 to 1,440
minutes of travel): the Newton polish of a loose fit
(maxeval = 10,
)
certifies it in 11 steps, while the BHHH polish holds
at
and stops after 18 steps,
log-likelihood units short.
The restart. A point where the linear term puts the
supremum at
is a local maximum of the simulated likelihood on the boundary of the
parameter space, but often a false one. The linear term comes from the
draws’ finite-sample asymmetry and has mean zero over the draws, while
the quadratic term is what identifies the variance. If the
log-likelihood moves with the standard deviation
like
, with
,
it falls to a minimum at
and passes its value at zero at
,
so the decrement certifies a point below a higher maximum. So a polish
whose estimates end with
below
of the default start’s (its typical effect on a utility below
,
for a normal coefficient) restarts once: the optimizer and the polish
again from the same point with those standard deviations raised, in
coordinates taken afresh, and the higher likelihood stands. The level is
the default start’s
for a normal coefficient; a log-normal’s
has no units, and 1 is used, since from the default start’s 0.5, below
the design’s truth of 0.70 here, more fits came back. A probe along the
axis alone cannot do this: with the other parameters at the plateau’s
values the likelihood rose in only 3 of 57 composite fits so stopped,
because they must adjust, where the restart raised it in 45. On a
simulated stated-preference panel with 200 persons
(),
4 of 40 fits from the default start stopped so, 4.1 to 10.3
log-likelihood units below the maximum, and the restart reached it in
all 4. On composite fits of those data
(),
57 of 100 stopped so, and 54 of them then stood at or above the fit from
the true parameters; certified fits more than 0.01 below that fit fell
from 47 to 6. At 800 persons, all 6 that stopped so reached it. Where
the variance is zero, the restart comes back: on logit data with two
random coefficients
(,
),
23 of 40 fits stopped so and all 23 ended at zero again, as did all 4 of
24 with a random coefficient of zero variance added to the panel. A
variance that ends at zero warns, with or without a polish: the
diagonal’s standard error says nothing (a clustered one is of order one,
the Hessian’s about
),
and a test that a variance is zero has a null on the boundary, where
Wald and likelihood ratio statistics do not have their usual
distributions (Self and Liang 1987). The restart took 0.5 to 1 times the
first fit’s time at the median and 2.4 at most, on the fits that stop
there, and where the first point stands the variance evaluates its
matrix once more; polish_control = list(restart = FALSE)
turns it off. Under the profile likelihood, whose constants have their
own solver, the fit warns without restarting.
The variance is computed afterwards at the polished estimates, by
se_method, through §5.6. Since every stop is decided at the
point whose curvature the polish has just evaluated, that matrix is the
variance’s own at the estimates returned (unless the start is returned,
as above, or the curvature itself fails) wherever se_method
needs it, and is not evaluated again: after a Newton polish,
for "hessian" and as the bread of "sandwich"
and "cluster"; after a BHHH polish,
for "bhhh" (the sandwich’s meat squares the weights, so it
is computed). There, a polish that certifies the optimizer’s solution at
once costs one evaluation of the log-likelihood and its gradient and one
Cholesky factorization of the curvature beyond the fit without it.
fit$optimizer$polish records the phase. A profile fit
(§5.8) takes its variance the same way, from the full matrices at its
estimates.
Code reference: run_polish(),
.polish_control(), and the wiring the wrappers share (the
held constants and the BHHH rank check, .polish_held(); the
decrement over the mean weight, the divergence rule and the record,
.polish_fit()) in R/classes.R;
newton_step() in src/newton.cpp;
the curvature and its reuse in run_mxlogit(), R/mxlogit_utils.R.
5.8 Concentrating Out the Constants
With many alternatives the constants are most of the parameters:
2,511 of 2,530 in a census-style design of school choice.
run_mxlogit(concentrate_out_asc = "profile_likelihood")
splits
,
with
, and maximizes the profile
log-likelihood
over alone. Its maximizer is the part of the joint maximizer, and the part: the estimator does not change.
The constants’ first-order condition. By §3.4.4 and §3.5, with the posterior draw weights of §2.6,
each alternative’s weighted chosen count equals its predicted count,
each decision maker’s probabilities averaged over the draws with the
weight of the draw given their choices. In the multinomial logit,
without draws, this is the familiar property that the fitted shares
match the observed ones. With random coefficients it is not BLP’s share
matching (§8), which equates the unconditional shares, with
replaced by
,
to the observed ones: a different estimator,
concentrate_out_asc = "blp" (§5.9).
runs over the free constants (the outside option’s or the base
alternative’s is normalized).
The envelope gradient. At an interior maximum the constants’ score vanishes, so
the joint gradient’s part at the solved constants, with no derivative of .
The inner solve. At each
the optimizer evaluates, the constants are solved by the Newton phase of
§5.7 on
alone:
held, no bounds, unit scales (the maximum step and the stall rule in
units of utility), and the decrement over the mean weight (§5.7). Its
curvature is the information’s constants block
,
from mxl_delta_hessian_parallel() in the same pass as the
objective and the gradient: minus the
rows and columns of §4.5’s assembly,
with
the situation’s slot probabilities scaled by
and
the decision maker’s per-draw scores of the constants, centered at their
posterior mean and scaled likewise: the complete information less the
missing one (Louis 1982, §4.5). It needs no continuous block and costs
about three gradient passes, against three to four for the full Hessian,
whose continuous blocks Identity D forms (§4.4.4). A trial point the
line search accepts gives the next step’s curvature from the same pass.
The solve stops when the Newton decrement
over the mean weight falls below tol_decrement
(),
or when every constant’s score, and the reference’s (minus their sum:
the scores of all the alternatives’ constants sum to zero), is below
tol_residual
()
relative to its alternative’s weighted chosen count plus the mean
weight, a test that needs no factorization; neither rule depends on the
weights’ scale. It fails after max_iter (25) steps or
max_iter
passes, or when it stops otherwise (a failed line search, negligible
steps). The first solve, at the start values, starts from
,
with
the weighted chosen counts and
the reference’s (the estimate when the model has constants only and
every situation offers every alternative), or from a supplied
theta_init’s constants, and may take four times as many
steps; where it fails, the fit stops (class
choicer_profile_unconverged; an error inside it is reported
as itself).
How exact the inner solve must be. Write for the information at , for the gradient of in at a solve’s constants , and for its decrement. To first order , and the envelope gradient errs by . At the outer maximum this moves by , where
is the profile’s curvature (below). A linear combination has standard error , and by Cauchy–Schwarz it moves by at most of it. By the inverse of the partitioned ,
with the largest eigenvalue of , the most by which estimating inflates the variance of a combination of the constants. The outer solution therefore moves by at most standard errors: at , even for . The bound is in standard errors of the likelihood with weights of mean one, the unit of the decrement over the mean weight. Usually the decrement rule stops the solve first.
Warm starts and failures. A line search tries points it then rejects, and constants solved at a rejected point are a poor start for the next. Every solve starts from the constants of the best point so far (the lowest objective among converged solves), which under a monotone line search is the current iterate or a better trial on its line. That point’s value, constants and gradient are kept, so an evaluation at exactly its , as the optimizer’s last one often is, needs no solve. A solve that does not converge reaches the optimizer as the overflow sentinel of §5.4, so that its line search backtracks: at unconverged constants only bounds from above, and the part of the gradient is not the profile’s. Such failures are counted; the fit warns of those after the best point last improved, which may have stopped the optimizer. The constants returned are solved at the optimizer’s solution.
The outer problem. The optimizer works in the
coordinates of §1.5 restricted to
;
under "bhhh" the BHHH diagonal is taken at
, after the
first solve. Bounds on
go to the optimizer. The constants may not be bounded, and each must
have a finite estimate (§5.4, item 6): either case is an error, before
the draws.
The variance. By the same partitioned inverse,
: inverting the full information
at
,
as §5.6 does for a joint fit, gives
the inverse of the profile’s curvature, which accounts for the constants
being estimated. Inverting
alone, as if
were known, gives
:
standard errors too small. The profile fit’s variance is therefore the
joint fit’s, by se_method, from the full matrices; after a
polish, from its last curvature where that is the matrix
se_method needs (§5.7).
Cost. A solve from a warm start takes about two Newton steps, each a pass of the constants’ kernel (about three gradient passes) and a Cholesky factorization of the block ( operations: 0.17 s at on 11 threads, 4 to 5 s at 10,000). In the validation study of NEWS (census- and claims-style designs of 518 to 2,620 parameters, two sizes each) the profile took 21 to 49 evaluations of the optimizer and reached the joint maximum, ending closer to it (the joint Newton decrement at its stop to , against to at the default joint fit’s stop), but at 2 to 4 times the joint fit’s time (modeled from the kernels’ calls; 1.8 to 4.9 times on the clock): L-BFGS in the coordinates of §1.5 needed only 46 to 224 evaluations of the joint problem, each about a third of a pass of the constants’ kernel. Profiling would pay where the joint optimizer needs many more evaluations than that, which the study did not find.
Code reference: .profile_objective() and
.concentrate_control() in R/classes.R;
.mxl_profile_solver(),
.check_profile_inputs(), .chosen_counts() and
the wiring in run_mxlogit(), R/mxlogit_utils.R;
mxl_delta_hessian_parallel() in src/mxlogit.cpp.
5.9 Matching Aggregate Shares
run_mxlogit(concentrate_out_asc = "blp") is a different
estimator of the same model: the constants are held at the values at
which the model’s market shares equal target shares, and the other
parameters maximize the likelihood given them. With
the probability
averaged over the decision maker’s own estimation draws (each draw
weighted
,
not by the posterior weight
of §2.6 that §5.8’s condition uses), the predicted share of inside
alternative
in market
is
a market being a group of alternatives that share choice situations, directly or through others (the components of the share inversion, §8; one in most data), and its choice situations. The constants solve for every free constant: for each the solution, where one exists, is unique (Berry 1994), and smooth in . The estimator is
Train and Winston (2007, §3) estimated the mixed logit of new-vehicle choice this way, with the constants recomputed by BLP’s contraction at every trial value of the other parameters so that the shares averaged over their sample equal national market shares; Berry, Levinsohn and Pakes (2004) and Petrin (2002) instead combine moments of the micro data with the share constraint by GMM. Imbens and Lancaster (1994) give the theory of aggregate information in micro estimation.
The targets. target_shares gives
external shares
,
each inside alternative’s share within its market (BLP’s
,
their market); with an outside option a market’s outside share is one
minus its inside targets. By default the targets are the sample’s own
weighted shares,
: the fitted model then
reproduces them exactly, a calibration of the constants. A choice-based
sample’s population shares
(§9), when its provenance carries them, are the default targets of a
WESML fit, taken as exact: under choice-based sampling the weighted
sample shares equal
only by construction of the weights, and the chosen counts are fixed by
the strata. The predicted shares are the weighted sample’s, so the
weights must make each market’s sample represent the population its
targets describe. With an outside option that population includes the
outside choices, so samples of buyers only (as in Berry, Levinsohn and
Pakes 2004) are outside this option’s scope; without one, the model is
the choice among buyers, fitted to buyers’ shares, as in Train and
Winston (2007, §2.1).
Where it is maximum likelihood. Two cases make the estimators coincide, and the tests pin both.
- The logit with the sample’s shares. Without random coefficients and , so the share equations are the constants’ first-order conditions (§5.8), and .
- The ML fit’s own shares as targets. Let be the profile of §5.8. For any , , and with the ML fit’s predicted shares on its estimation draws , so the last bound is attained: is the global constrained maximum, for any heterogeneity, panel or not.
Otherwise the estimators differ. With the sample’s own shares the share-constrained estimator is asymptotically at least as variable as ML, which is efficient among estimators that use the sample alone. With external shares known exactly it can be more precise, since the targets carry information the sample does not: in the Monte Carlo below its constants’ standard deviations are 0.51 to 0.60 of ML’s. It is not the efficient use of external shares: it gives the share equations infinite weight while they carry the sample’s covariate noise. The efficient combination stacks the two sources’ likelihoods or moments (Imbens and Lancaster 1994; Grieco, Murry, Pinkse and Sagl 2025).
The inner solve. At each
the optimizer tries, the share inversion of §8 runs on the estimation
draws: each situation integrates over its decision maker’s draws (the
draws of the panel likelihood, cube slice
or the Halton block the kernels form for
),
Anderson acceleration, exponentials kept across evaluations and
compensated sums at scale, to a largest log-share residual of
tol_shares
(;
Dubé, Fox and Su 2012). It starts from the best point’s constants
advanced along the tangent
,
(below): 4 to 6 evaluations of the shares per solve in the Monte Carlo
below (5.0 to 5.6 on three datasets of its cross-section design, against
6.8 to 7.1 from the best point’s constants alone), and 17 and 9.5 on the
census- and claims-style data of the last paragraph. A solve that does
not converge within max_iter (1000) evaluations is the
overflow sentinel to the optimizer (§5.4), as in §5.8; the first, at the
start values, from the targets’ log ratios
(or a supplied theta_init’s constants) with four times the
budget, stops the fit where it fails (class
choicer_blp_unconverged).
The objective and its gradient. The envelope theorem does not apply: at the gradient of in the constants, (§5.8), is not zero. With its gradient in and the Jacobian of the predicted counts (its blocks and on the free constants), the implicit function theorem gives , and
one solve with
(symmetric positive definite on the free constants). Per draw,
is the constants’ rows of the logit’s information
,
:
on the diagonal,
off it and
against
.
So
is the constants’ rows of the complete-information part of §4.5’s
assembly (Identities B and C, without Identity A’s missing information
or second derivatives of utility), every draw weighted
.
mxl_blp_jacobian_parallel() forms it in the gradient’s
pass, at the cost of 2.2 to 3.5 gradient passes (one thread, 20,000
situations,
).
An inner error
moves
by
,
a first-order error the optimizer would see as noise; the objective it
is given is instead
with
the target counts: the residual’s term cancels
to first order, so the error is
.
At tol_shares =
both errors are at the objective’s rounding; at
the correction took the largest error over ten warm starts from
to
,
on one dataset of the Monte Carlo’s cross-section design.
The variance. With decision maker ’s score of (§4.5), the estimate solves the stacked equations , (the score projected along the constraint; the gradients of above are ), and , for the sample’s shares or for supplied targets. With the information, (the curvature along the constraint) and ,
and with the variance of the stacked sums,
’s own sampling error does not enter to first order: it multiplies the constants’ score, whose mean is zero at the truth.
se_method |
, | , sample shares | , supplied | |
|---|---|---|---|---|
"hessian" |
negated Hessian | , 0 | ||
"bhhh" |
BHHH | , 0 | ||
"sandwich" |
negated Hessian | blocks of , | its block | its block |
"cluster" |
negated Hessian | blocks of , | its block | its block |
Under the model,
(,
and
) and a decision maker’s
chosen counts vary by
,
(the law
of total variance over the equally weighted draws); supplied targets’
vary only through the covariates. Targets estimated from an independent
sample add
to
,
with
= target_vcov and
free constant
’s
market weight (for shares from
independent choices in market
,
on its block: a
diagonal
drops the covariances the shares’ adding up imposes, and overstates the
variance of the market’s total inside share, so of the constants’ common
level). In the logit with the sample’s shares,
and
,
and
is §5.8’s Schur complement
:
"hessian" (where
),
"sandwich" and "cluster" return ML’s
variances. All four types assume correctly specified probabilities:
"sandwich" and "cluster" relax the information
equality (sampling weights, dependence), not the model. Under
misspecification the constants’ expected score is not zero, and two
terms omitted here become first order:
in the bread and
’s
sampling error in the meat. Simulation noise in the share equations is
omitted too, as maximum simulated likelihood omits its own.
What the fit records. fit$share_targets
holds the targets and their source;
fit$optimizer$concentration the outer and inner work, the
residuals,
at the estimate
(the derivative of
with respect to each free constant’s target count: positive where the
micro data would put that alternative’s share below its target) and the
outer certificate
over the mean weight.
is not the curvature of
,
which adds
,
the constants’ score at the solution. That score is not zero even with
the sample’s own shares (§5.8: the share equations average each
situation’s probabilities over the draws, the score weights each draw by
its posterior given the choices). The term is
against the
of
,
which is why the variance can omit it, but it can turn a minimum’s
curvature positive. So where the optimizer reports a failure or stops at
its cap and the certificate decides whether the point is a maximum, the
decrement is taken in the objective’s own Hessian, from central
differences of its gradient (two solves of the constants per continuous
parameter), whatever the standard errors. logLik(), AIC and
BIC are the likelihood at the constrained estimate, and a
likelihood-ratio test between such fits is not
.
conditional_tastes()’s identities rest on the scores of
and
being zero, which they are not here.
predict(type = "shares") and blp(fit, targets)
reproduce the targets, as shares of the whole sample
(fit$share_targets$engine), and
only in a cross-section: a panel’s predictions integrate per situation,
the estimator per decision maker.
A Monte Carlo. Family F10 of the validation suite
(Rscript _validation/mc.R --family=F10) simulates four
designs of 2,000 choice situations among ten alternatives, each
situation offering a random subset of at least half of them (of its
market’s): a cross-section with an outside option; 500 decision makers
with four situations each, with an outside option; a cross-section
without one; and two markets of five alternatives, with an outside
option and targets within each. Utility is
,
with
,
,
and
evenly spaced from
to
,
and every fit uses
draws. Each of 1,000 replications per design fits ML (certified by
Newton steps) and this estimator with the sample’s shares, with the
population’s exact shares, and with shares estimated from
and
choices per market
(
= 2,000 divided by the number of markets), their multinomial covariance
as target_vcov. Over the four designs:
| targets | constants’ SD / ML’s | ’s SD / ML’s | 95% coverage | largest bias / SD, |
|---|---|---|---|---|
| (ML itself) | 1 | 1 | 0.946–0.954 | 0.05–0.10 |
| the sample’s shares | 1.02–1.05 | 1.00 | 0.944–0.956 | 0.06–0.10 |
| exact shares | 0.51–0.60 | 0.99–1.00 | 0.945–0.951 | 0.07–0.13 |
| shares from choices | 0.60–0.70 | 0.99–1.00 | 0.945–0.953 | 0.08–0.15 |
| shares from choices | 1.15–1.31 | 0.99–1.00 | 0.941–0.954 | 0.16–0.29 |
Coverage is the Hessian form’s. The SD ratios and coverage average over ’s parameters or over the constants; the bias column is the largest over ’s, each with a Monte Carlo standard error of about 0.03. Every inner solve converged, and every fit’s outer decrement was below (one optimizer stop carried nloptr’s generic failure code, at a decrement of ). Averaged over each group’s parameters, the mean standard error was within 2.3% of the estimates’ standard deviation for every estimator, ML’s included, and the sandwich covered as the Hessian form did. Exact shares roughly halve the constants’ standard deviations and shares from ten times the sample’s choices cut them by a third, while stays as precise as under ML; shares from as many choices as the sample’s make the constants noisier than ML’s. Noisy targets bias toward zero, coefficients and standard deviations alike, by an amount that grows with the targets’ variance: in the panel, beyond exact targets’ bias, by 0.16 standard deviations for ’s mean with shares from choices and by 0.02 with . That costs the intervals at most a point of coverage.
Cost. On the census- and claims-style designs of
_benchmarks/scale/ (fit_study.R, cell
blp_lbfgs: the sample’s shares, no outside option,
correlated coefficients,
, 11 threads), a fit took about as
long as the profile likelihood of §5.8: 16 s against 16 s on 20,000
students in 24,560 situations with 2,511 constants (the joint fit 4.4
s), and 26 s against 23 s on 1,500 patients in 17,339 situations with
499 constants (the joint fit 14 s). It took 21 and 46 outer evaluations,
each one share inversion and one pass of the share Jacobian, and the
passes took about half the time on census and two-thirds on claims.
Code reference: .mxl_blp_solver(),
.mxl_blp_setup(), .blp_resolve_targets(),
.blp_vcov() and .blp_fit_vcov() in R/mxlogit_blp.R;
mxl_blp_jacobian_parallel(),
mxl_blp_meat_parallel(), blp_check_targets()
and mxl_blp_solve() in src/mxlogit.cpp;
spd_solve() in src/newton.cpp.
6. Elasticity Computation
6.1 Elasticity Definitions
The elasticity measures the percentage change in choice probability with respect to a percentage change in an attribute. For the mixed logit model, we compute elasticities using simulated probabilities.
Simulated Probability:
6.2 Elasticity for Fixed Coefficients (X Variables)
For a variable in the design matrix with fixed coefficient :
Own-Elasticity (elasticity of with respect to ):
Using the chain rule and averaging over draws:
Cross-Elasticity (elasticity of with respect to where ):
6.3 Elasticity for Random Coefficients (W Variables)
For a variable in the design matrix with random coefficient, the effective coefficient for individual and draw is:
where: - For normal distribution: , - For log-normal distribution: ,
Own-Elasticity:
Cross-Elasticity:
6.4 Weighted Average of Individual Elasticities
The implementation computes weighted average individual probability elasticities:
This is not generally the elasticity of an aggregate share under a common market-level perturbation. Rows index responding alternatives and columns perturbed alternatives. The kernel sets a contribution to zero when and divides the accumulated matrix by total weight over all situations; with ordinary finite utilities, the threshold is only a numerical guard.
Code reference: mxlogit.cpp:mxl_elasticities_parallel
7. Diversion Ratios
7.1 Definition
The attribute-based diversion ratio from alternative to alternative with respect to attribute is
where is the aggregate share. It is the fraction of demand lost by that is captured by when a marginal change in ’s attribute reduces .
7.2 MNL Special Case (β cancels)
For multinomial logit, the per-individual derivatives of the choice probability are
Letting , the aggregate share derivatives are
Because is a scalar constant, it pulls out of both weighted sums. Forming the ratio,
with and cancelling. The result is independent of which attribute is perturbed — this is a special property of MNL.
7.3 MXL: β Does Not Cancel
For mixed logit the realized coefficient on a random variable for individual at draw is
with the same distribution transforms as in §6.3. The derivatives evaluated at draw are
Integrating over draws gives and similarly for the cross term. Aggregating over individuals, the diversion ratio is
Because varies across , it cannot be pulled out of the sums and does not cancel. The MXL diversion ratio therefore depends on the perturbed variable. For a variable with a fixed coefficient the dependence again vanishes ( is a constant scalar); for a random-coefficient variable it does not.
7.4 Properties
Column-sum identity. For each , . This follows from , which holds inside the draw sum and is preserved through the same weight on both sides.
Sign of
.
If
is constant negative (e.g. a fixed price coefficient), both numerator
and denominator change sign together and the ratio is unchanged — DR is
non-negative. With a random coefficient of mixed sign across
,
terms can partially cancel; the aggregate ratio is still well-defined
but can be numerically sensitive. The implementation guards against this
with an abs(denominator) > 1e-15 check.
Implementation. Cross-products and must be accumulated inside the per-draw loop, multiplied by at that point, and only then averaged across draws and weighted by . Computing or -weighted averages computed outside the draw loop is biased.
Code reference: mxlogit.cpp:mxl_diversion_ratios_parallel
8. BLP Share Inversion
8.1 Problem Statement
Given observed market shares , find the ASC parameters such that the model-predicted shares match the observed shares:
where is the predicted market share for alternative computed using simulated probabilities.
8.2 Simulated Market Shares
The predicted market share for alternative is:
where:
and is the probability for individual , alternative , and draw , which depends on through the utility specification.
8.3 The Iteration
The inversion is the multinomial logit’s (§7 of the multinomial logit article), with the simulated probabilities: its identification, its checks of the targets, its step and its stopping rule are the same. With ( the targets), the outside option or, without one, the reference of ’s component, and , each iteration shifts the component’s free constants together by , then takes the exact diagonal on the rest:
where
,
,
is the exact rate at which
responds to the common shift and
solves
.
The denominator is the exact diagonal of the derivative of
:
the logit’s terms, draw by draw, then averaged. Within a draw the shares
are a logit’s, so the simulated share Jacobian is symmetric with rows
summing to zero, which makes
exact, and every alternative is a substitute for every other, so
.
Berry, Levinsohn and Pakes’s (1995) contraction,
method = "original", takes
itself
(
without an outside option, the reference held). The safeguards are the
logit’s: a step is at most
in magnitude; where a component’s outside share underflows to zero the
step drops the outside correction and the common shift for that
iteration; a step whose shares are not finite is halved; under
method = "simple", an iteration whose best residual has not
improved for 30 iterations (a stall) halves its later steps, returning
to its best point first only where its residual at the stall exceeds
twice the best (once per best point), and otherwise doubling the
iterations the next stall waits for; and once 100 iterations fail to
halve the best residual, the contraction races the step from the start
(stopping when it is behind and slow, and going on whenever the step
alone fails to halve its best residual within 200 iterations), the first
to reach the tolerance returning. method = "anderson", the
default, and method = "squarem" accelerate the step as in
the logit (Anderson acceleration and SQUAREM; §7.3 of the multinomial logit article).
The iteration stops at the first evaluation whose largest absolute
residual (relative to each component’s reference without an outside
option; with one, each component’s outside share’s included) is at most
tol, and returns that point; max_iter counts
evaluations of the shares. When it stops otherwise it returns the
evaluated point of smallest residual and warns with class
choicer_blp_unconverged. A start at which some predicted
share underflows to zero is such a stop (status
"non_finite_start"), not an error.
8.4 Implementation Details
-
No outside option.
deltamay be the full length- vector or the free length- block; the latter is padded with a leading zero. The start is normalized by subtracting its first element, each component’s reference is held there, and the returned vector has length with its first entry zero. -
Outside option.
deltahas length and contains inside ASCs only;target_shareshas entries, the outside option’s first. Every target share, the outside option’s included, must be positive, which is checked before any evaluation. - The draws. is the largest alternative code. An integer or logical cube of draws is converted to double first.
The public blp.choicer_mxl() method resolves the fitted
draw metadata through .mxl_pred_draws(): store-mode fits
have the kernel form the plain-Halton points on the fly (§5.5), while
generate-mode fits pass the original seed, permutation mode, and
to the inversion. Share inversion therefore draws from the same
deterministic Halton sequence as the fit, one block per choice situation
(for a cross-sectional fit, the estimation draws themselves; a panel
fit’s estimation draws are per decision maker instead, §5.5). Neither
the draws nor
change across iterations, so blp() keeps each situation’s
,
with its log-normal rows exponentiated, from the first evaluation of the
shares on, when the draws are formed on the fly (stored draws with up to
128 random coefficients, or generated ones), the
blocks take at most keep_draws_bytes
(
bytes; 4 GiB by default) and the allocation succeeds; otherwise every
evaluation forms them again. The kept blocks are the values each
evaluation would compute, so by themselves they leave the shares, and
the returned
,
as they are. What they leave of keep_draws_bytes (all of it
where the draws are read from a cube) keeps, as in the logit (§7.6 of
the multinomial logit
article), each draw’s exponentials of the utilities at an
evaluation’s
,
shifted by the draw’s largest, for as many choice situations as fit
(
bytes per row, and per situation with an outside option) within half the
memory limit less what the call holds. A later evaluation at
forms those situations’
as the kept values times
over their sum, without the draws,
,
or any exponential; with every situation kept, an evaluation takes about
a third of the time. These probabilities agree with those formed afresh
to within rounding, so the budget can move the returned
as two solutions within tol differ (by about
tol times the conditioning). The exported
mxl_blp_contraction() keeps nothing.
On the estimation draws. blp() and the
exports draw one block per choice situation, the prediction’s draws.
Given each decision maker’s number of situations (Ti,
internal), each situation instead reads its decision maker’s block, cube
slice
or the Halton block the estimation kernels form for
,
so that the shares integrate over the panel likelihood’s own draws:
concentrate_out_asc = "blp" solves its share equations so
(§5.9). The Gamma cache stays per situation, a decision maker’s held
once for each of its situations within the budget.
Code reference: MxlBlpModel and
mxl_blp_solve() in src/mxlogit.cpp,
over src/blp_engine.h.
9. Choice-Based Sampling and WESML Weighting
9.1 Endogenous Stratified (Choice-Based) Sampling
In 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 the few individuals who chose a rare alternative. Let
Maximum simulated likelihood applied naively to such a sample is generally inconsistent for the population parameters. (A known special case: in a pure multinomial logit with a full set of alternative-specific constants, choice-based sampling biases only the constants; in general – and for the mixed logit – both the slopes and the constants are affected.)
9.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,
which yields the weighted simulated log-likelihood already defined in $$2.3,
The maximizer is invariant to multiplying every by a common positive constant (the objective is merely rescaled), so the weights may be normalized to mean 1 without changing the estimates.
9.3 Robust (Sandwich) Variance: the Meat
WESML is a weighted M-estimator solving , where is the per-situation score ($$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 the variance of that contribution involves .
This is exactly why the two naive variances are wrong under weighting:
- the inverse-Hessian assumes the information-matrix equality , which fails once the are non-degenerate;
- the ordinary BHHH/OPG uses the weight to the first power, not the second.
A consistency check: rescaling all weights by a constant sends and , so – the sandwich is invariant to the weight scale, whereas is not.
9.4 Scope: Robust vs. Design-Based Variance
The estimator implemented here is the robust weighted-M-estimator (Huber–White) variance, whose meat 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 – a prescribed number drawn from each choice stratum, i.e. standard stratified sampling – the design-based variance centers the scores within strata and may be smaller; that stratum-centered (design-based) 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.
9.5 Implementation and Cluster-Robust Extension
The variance routes never form the matrix of the units’ weight-free scores: two million decision makers by 2,620 parameters would take 42 GB. With the bread , the robust meat is the BHHH kernel with squared weights, summed over each unit’s compact block (§4.4.6),
and vcov(type = "bhhh") is the same kernel with weights
.
One set of draws, stored or generated from the fit’s draw metadata,
serves both matrices, which are combined as
,
computed equilibrated by two solves against the
factors of the equilibrated bread, without forming an inverse (§5.6).
For clusters
,
the meat
is mxl_cluster_meat_parallel: the units are sorted by
cluster and cut into chunks of similar numbers of rows, about four per
thread; each cluster’s weighted scores are summed over the parameters
they touch, and a cluster that a chunk boundary cuts is summed in parts,
added after the parallel region, so a few large clusters still keep
every thread busy. There is no finite-cluster correction.
mxl_scores_parallel (internal; no variance route of the
mixed logit calls it) still returns
for small problems and refuses a matrix above 2 GiB. Clustering changes
inference, not the estimand of whichever likelihood was fit (§1.6):
cross-sectional by default, or the panel likelihood of §2.6 under
person_col, where cluster labels must nest decision makers.
It is only §9.1–§9.2’s WESML weighting that is defined solely for the
cross-sectional likelihood:
is a weight that varies with the alternative chosen in situation
,
whereas the panel objective of §2.6 requires one weight
per decision maker, constant across their situations, so a choice-based
weight cannot enter it — run_mxlogit(..., person_col = )
therefore rejects choice-based-sampling provenance. The sandwich
variance of §9.3 and its cluster-robust extension here in §9.5 carry no
such restriction: both are built from whichever likelihood unit’s score
was actually fit (a decision maker under person_col, a
choice situation otherwise), so they apply to panel fits too, with
cluster labels then nesting decision makers exactly as above. The
variance is computed in natural units and inverted equilibrated (§5.6);
the
Cholesky-to-
delta method (§5.2) applies on top, exactly as for any stored
vcov. User-facing entry points:
wesml_weights() and sample_by_choice() build
the weights; run_mxlogit(..., se_method = "sandwich")
estimates with the robust variance; wesml_vcov() returns it
post hoc.
Code reference: mxl_bhhh_parallel(),
mxl_cluster_meat_parallel() and
mxl_scores_parallel() in src/mxlogit.cpp;
.assemble_score_vcov(), .mxl_score_meat() (the
multinomial and nested logits’ .logit_meat();
.score_meat() forms the same meats from the score matrix,
as the tests’ reference) and .sandwich_combine() in R/classes.R;
equilibrated_sandwich() in src/vcov.cpp;
wesml_weights() / sample_by_choice() in R/sampling.R.
10. Willingness to Pay
10.1 Fixed Coefficients
When the price variable has a fixed coefficient (a column of ), the WTP for any fixed attribute is the usual marginal rate of substitution, with the same analytic delta-method SE as in the MNL case (§8 of the MNL document):
10.2 Random Coefficients
For a random attribute coefficient the WTP is itself a random variable , and a scalar summary must be chosen. The summaries reported follow the package’s parameterization (§1.3):
Normal RC with estimated mean
(rc_mean = TRUE, rc_dist[k] = 0):
has mean
,
so the mean WTP is
with the linear-ratio gradient of §10.1 applied to .
Shifted log-normal RC with estimated location
(rc_mean = TRUE, rc_dist[k] = 1):
.
Since
is monotone in the normal draw
and the median of
is
,
the population median is
and the median WTP is
The median is preferred to the mean, with , because the mean is highly sensitive to the estimated variance (a thin right tail dominates it).
Shifted log-normal RC without location
(rc_mean = FALSE, rc_dist[k] = 1):
has median exactly 1, so the median WTP is
with
— uncertainty comes solely from
.
Normal RC without mean
(rc_mean = FALSE, rc_dist[k] = 0): the mean is
0 by construction; no WTP row is reported.
10.3 Random Price Coefficients Are Rejected
The implementation requires price_var to be a
fixed-coefficient column of
and rejects every random price coefficient. For a normally distributed
denominator this is substantively important: positive density
arbitrarily close to zero generally makes
diverge. That no-moment argument does not cover every
possible mixing distribution—for example, inverse moments of a
sign-constrained log-normal can be finite—but wtp() still
does not simulate the joint ratio distribution, account for its
correlation, or report its quantiles. Thus the rejection is both a
specification guard for normal price mixing and an implementation
boundary for other distributions. WTP-space estimation (Train and Weeks
2005) is not implemented in choicer v0.2.0.
Code reference: R/wtp.R
11. Consumer Surplus and the Simulated Logsum
11.1 Expected Logsum
Conditional on a coefficient realization
,
expected maximum utility over the iid type-I extreme-value errors is
,
where
is Euler’s constant. As in the other package methods,
logsum() omits this scenario-invariant additive constant.
The mixed-logit logsum integrates over the mixing distribution:
simulated over the fit’s Halton sequence, one block per choice situation (regenerated from the stored draw metadata; for a cross-sectional fit, the estimation draws themselves; a panel fit’s estimation draws are per decision maker instead), with the outside option contributing in each draw’s sum when present, and the max-subtraction trick applied per draw.
Order of operations matters. The log-sum-exp function is convex, so by Jensen’s inequality
with strict inequality when the draws induce non-common variation in
utilities. A nondegenerate
alone is not sufficient for strictness: if the random contribution is
the same additive shift for every available alternative, log-sum-exp is
affine in that direction and equality holds. A dedicated C++ kernel
(mxl_logsum) computes the per-draw logsum and then averages
across draws.
11.2 Expected Consumer Surplus
With a fixed price coefficient (the marginal utility of income is then nonrandom):
A random price coefficient is rejected for the capability and specification reasons in §10.3; the divergence argument applies directly to normal price mixing but not to every sign-constrained distribution. As in MNL, the formula assumes no income effects. The routine does not enforce ; the economic interpretation as positive marginal utility of income requires the analyst to verify that sign. CS levels inherit the ASC normalization, so only differences across counterfactual scenarios are meaningful. The implementation reports point estimates for MXL (the delta-method SE of mean CS is currently provided for MNL only); Krinsky–Robb resampling is a practical interval method.
Code reference: R/surplus.R;
kernel in src/mxlogit.cpp
(mxl_logsum)
12. Goodness of Fit
The measures are model-agnostic and identical to §10 of the MNL document, computed from the simulated log-likelihood and simulated choice probabilities:
- McFadden pseudo R²: , adjusted , with counting all estimated parameters (, , Cholesky block, ASCs).
- Equal-shares null (default; exact for unbalanced choice sets and weights): .
- Market-shares null (constants-only closed form): , where is the common weight, valid only for identical choice-set composition and uniform weights. The constants-only model contains no random coefficients, so the MNL closed form applies unchanged.
- Hit rate: weighted share of choice situations whose observed choice has the highest simulated probability ; with an outside option, the kernel returns the simulated outside probability directly and the outside good competes for the maximum.
Code reference: R/gof.R
13. Conditional (Individual-Level) Tastes
conditional_tastes() recovers, for each likelihood unit,
the mean and standard deviation of the random coefficients
conditional on the choices observed — the same posterior draw
weights
that build the panel score and Hessian (§2.6, §3.5, §4.5), now applied
to the realized taste draws themselves rather than to the score:
with the taste at draw on the scale it enters utility (§1.1–1.3), the conditional mean above, and the sequence of choices observed across ’s situations (Revelt and Train 2000; Train 2009, ch. 11). defines the same object for the default cross-sectional fit, one choice situation at a time; a single choice reveals comparatively little, so its conditional mean sits closer to the population mean than a panel decision maker’s typically does.
Not
itself.
is the average taste among decision makers who would make
’s
choices, not
’s
own realized
— it shrinks toward the population mean, more so the fewer situations
contributes. Consequently the variance across decision makers
of the conditional means understates
:
by the law of total variance,
so the revealed share
(-weighted
variance of the conditional means) and the residual share
(-weighted
average of the conditional variances) should sum to about one. These are
numerical checks, not specification tests: for normal random
coefficients with free means, both this identity and
are the likelihood’s first-order conditions for
and
— the population mean and variance are exactly the
-weighted
mean and variance the estimating equations set to zero at
— so they hold at a converged maximum whatever the true taste
distribution. A departure points to too few draws
or an unconverged
;
when a coefficient’s mean is fixed at zero (rc_mean = FALSE
and no fixed coefficient on the same variable), a mean_cond
far from zero can also flag that restriction. For log-normal
coefficients the variance identity holds on the underlying normal scale
,
not the utility scale
reported here, so expect departures of a few percent in either direction
at moderate
.
print.choicer_tastes() reports these alongside
model_mean/model_sd (the moments of
itself, §1.2–1.3) and mean_cond/sd_cond (the
weighted mean and SD of the conditional means across units).
Implementation.
mxl_conditional_tastes_parallel() reuses
mxl_unit_load() and mxl_unit_simulate() (§3.5)
to obtain
per unit, then forms
over the unit’s
realized-deviation block
(the same
values already used to build
,
§1.1) and adds back the mean block,
;
the SD uses the analogous weighted second moment of
around
.
Both are matrix-vector products — no second pass is needed, since
neither quantity is an outer product. Units whose log-likelihood is
non-finite — possible only when their utilities overflow (§4.5, §5.4) —
return NA and are dropped from the population summary.
Code reference: mxl_conditional_tastes_parallel() in
src/mxlogit.cpp;
R/conditional_tastes.R.
References
- Train, K. E. (2009). Discrete Choice Methods with Simulation. Cambridge University Press.
- Revelt, D., & Train, K. (1998). Mixed logit with repeated choices: households’ choices of appliance efficiency level. Review of Economics and Statistics, 80(4), 647-657.
- Revelt, D., & Train, K. (2000). Customer-specific taste parameters and mixed logit: households’ choice of electricity supplier. Working Paper E00-274, Department of Economics, University of California, Berkeley.
- Louis, T. A. (1982). Finding the observed information matrix when using the EM algorithm. Journal of the Royal Statistical Society: Series B, 44(2), 226-233.
- Bertsekas, D. P. (1982). Projected Newton methods for optimization problems with simple constraints. SIAM Journal on Control and Optimization, 20(2), 221-246.
- Dennis, J. E., & Schnabel, R. B. (1983). Numerical Methods for Unconstrained Optimization and Nonlinear Equations. Prentice-Hall.
- Hager, W. W., & Zhang, H. (2005). A new conjugate gradient method with guaranteed descent and an efficient line search. SIAM Journal on Optimization, 16(1), 170-192.
- Levenberg, K. (1944). A method for the solution of certain non-linear problems in least squares. Quarterly of Applied Mathematics, 2(2), 164-168.
- Marquardt, D. W. (1963). An algorithm for least-squares estimation of nonlinear parameters. Journal of the Society for Industrial and Applied Mathematics, 11(2), 431-441.
- Train, K., & Weeks, M. (2005). Discrete choice models in preference space and willingness-to-pay space. In R. Scarpa & A. Alberini (Eds.), Applications of Simulation Methods in Environmental and Resource Economics (pp. 1-16). Springer.
- McFadden, D., & Train, K. (2000). Mixed MNL models for discrete response. Journal of Applied Econometrics, 15(5), 447-470.
- Berry, S., Levinsohn, J., & Pakes, A. (1995). Automobile prices in market equilibrium. Econometrica, 63(4), 841-890.
- Berry, S. (1994). Estimating discrete-choice models of product differentiation. RAND Journal of Economics, 25(2), 242-262.
- Berry, S., Levinsohn, J., & Pakes, A. (2004). Differentiated products demand systems from a combination of micro and macro data: the new car market. Journal of Political Economy, 112(1), 68-105.
- Petrin, A. (2002). Quantifying the benefits of new products: the case of the minivan. Journal of Political Economy, 110(4), 705-729.
- Train, K. E., & Winston, C. (2007). Vehicle choice behavior and the declining market share of U.S. automakers. International Economic Review, 48(4), 1469-1496.
- Imbens, G. W., & Lancaster, T. (1994). Combining micro and macro data in microeconometric models. Review of Economic Studies, 61(4), 655-680.
- Dubé, J.-P., Fox, J. T., & Su, C.-L. (2012). Improving the numerical performance of static and dynamic aggregate discrete choice random coefficients demand estimation. Econometrica, 80(5), 2231-2267.
- Grieco, P. L. E., Murry, C., Pinkse, J., & Sagl, S. (2025). Optimal estimation of discrete choice demand models with consumer and product data. NBER Working Paper 33397.
- Bhat, C. R. (2003). Simulation estimation of mixed discrete choice models using randomized and scrambled Halton sequences. Transportation Research Part B, 37(9), 837-855.
- Gouriéroux, C., & Monfort, A. (1996). Simulation-Based Econometric Methods. Oxford University Press.
- Hajivassiliou, V. A., & Ruud, P. A. (1994). Classical estimation methods for LDV models using simulation. In R. F. Engle & D. L. McFadden (Eds.), Handbook of Econometrics, Vol. 4 (pp. 2383-2441). North-Holland.
- Lee, L.-F. (1995). Asymptotic bias in simulated maximum likelihood estimation of discrete choice models. Econometric Theory, 11(3), 437-483.
- 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 Structural Analysis of Discrete Data with Econometric Applications. MIT Press.
- Cosslett, S. R. (1981). Maximum likelihood estimator for choice-based samples. Econometrica, 49(5), 1289-1316.
- Wooldridge, J. M. (2010). Econometric Analysis of Cross Section and Panel Data (2nd ed.), Section 13.8. MIT Press.