Estimates a mixed logit model via simulated maximum likelihood.
Usage
run_mxlogit(
data = NULL,
id_col = NULL,
alt_col = NULL,
choice_col = NULL,
covariate_cols = NULL,
random_var_cols = NULL,
input_data = NULL,
eta_draws = NULL,
S = 100L,
rc_dist = NULL,
rc_mean = FALSE,
rc_correlation = FALSE,
use_asc = TRUE,
theta_init = NULL,
lower = NULL,
upper = NULL,
optimizer = NULL,
control = list(),
se_method = c("hessian", "bhhh", "sandwich", "cluster"),
scale_vars = c("bhhh", "none", "sd", "mad", "iqr"),
weights = NULL,
outside_opt_label = NULL,
include_outside_option = FALSE,
draws = c("store", "generate"),
seed = NULL,
scramble = c("permuted", "none", "owen"),
keep_data = TRUE,
nloptr_opts = NULL,
weights_col = NULL,
cluster_col = NULL,
person_col = NULL,
polish = c("none", "newton", "bhhh"),
polish_control = list(),
concentrate_out_asc = c("none", "profile_likelihood", "blp"),
concentrate_control = list(),
target_shares = NULL,
target_vcov = NULL
)Arguments
- data
Data frame containing choice data (convenience workflow). Mutually exclusive with
input_data.- id_col
Name of the column identifying choice situations.
- alt_col
Name of the column identifying alternatives.
- choice_col
Name of the column indicating chosen alternative (1/0).
- covariate_cols
Vector of column names for fixed covariates;
NULLwhere every coefficient is random. None may take a name the model gives its parameters, or prints for them insummary():L_<i><j>andSigma_<i><j>, withuse_asc = TRUEASC_<label>, and withrc_mean = TRUEMu_<variable>and, for a log-normal coefficient,exp(Mu_<variable>).- random_var_cols
Vector of column names for random coefficients.
- input_data
List output from
prepare_mxl_data(advanced workflow). Mutually exclusive withdata. Its weights must be finite and strictly positive and itsXandWfinite, whichprepare_mxl_data()ensures; the fit checks them again, in case the object was edited, before it first evaluates the likelihood (integer64 weights are converted to double).- eta_draws
Array of shape K_w x S x U with standard normal draws, one K_w x S block per likelihood unit: U is the number of decision makers when
input_datawas prepared withperson_col(length(input_data$Ti)), and the number of choice situations otherwise. Required for the advanced workflow, where its values must be finite; auto-generated fromSin the convenience workflow. Post-hoc methods (vcov(fit, type = ),wesml_vcov,conditional_tastes, prediction) regenerate the Halton drawsget_halton_normalsbuilds from the recorded draw count, so buildeta_drawswith it for them to reproduce the estimation draws.- S
Integer number of Halton draws per decision maker, or per choice situation without
person_col(convenience workflow only). Default 100.- rc_dist
Integer vector indicating distribution of random coefficients (0 = normal, 1 = log-normal). Default: all normal.
- rc_mean
Logical indicating whether to estimate means for random coefficients.
- rc_correlation
Logical indicating whether random coefficients are correlated (convenience workflow). Ignored when
input_datais used (taken from the prepared data).- use_asc
Logical indicating whether to include alternative-specific constants: one per inside alternative with the outside option, otherwise one per alternative but the first (
outside_opt_labelwhen it is given, else the first label insort()order, which for a factor is the first of its levels present), whose constant is normalized to 0. WithFALSEthe utilities have no constants, so alternatives differ only through their covariates. An alternative's constant has no finite maximum-likelihood estimate when the alternative is never chosen in the data, or is chosen in every choice situation that offers it (the likelihood keeps rising as the constant falls, or grows); when the outside option or the base alternative is never chosen, or chosen wherever it is offered, the other constants have none together. The fit then warns (classchoicer_unbounded_constants) before the optimizer runs, naming them; a finite bound in the direction a constant diverges (lowerfor a never-chosen alternative's,upperfor an always-chosen one's) holds it, and that alternative is not named (the outside option's and the base's cases, which move every constant together, are named whatever the bounds). It counts rows (alt_mapping), so an alternative listed twice in a choice situation can hide being chosen wherever it is offered.- theta_init
Initial parameter vector in natural-scale units. If
NULL(default), the start is in the columns' units: zero for the \(\beta\), \(\mu\) and ASC blocks and the Cholesky factor's off-diagonal entries; on its diagonal, \(L_{pp} = 1 / h_p\) for a normal random coefficient, where \(h_p\) is the typical step of its column of \(W\): the distance between its values for a column with two (a dummy: 1), the mean distance from a value that fills more than half of the column over the other rows (a mostly-zero column), and the standard deviation otherwise; a column with no variation starts at \(L_{pp} = 1\). At the start, a step of \(h_p\) in the column then moves the utility by a random amount with standard deviation 1, whatever the column's units of measurement. A log-normal coefficient starts at \(L_{pp} = 0.5\), the standard deviation of the logarithm of its random part, which has no units (that random part has median 1 in the column's units, so a log-normal covariate belongs in units where its coefficient is of order one). Where the default start falls outsidelower/upper, it is moved to the nearest bound, with a message. A suppliedtheta_initis used as given. Withconcentrate_out_asc = "profile_likelihood"the constants start instead at the first inner solve's solution, from the log ratios of the alternatives' weighted chosen counts to the reference's (default start) or fromtheta_init's constants.- lower, upper
Optional parameter bounds for the optimizer, in natural-scale units (mapped to the optimizer's coordinates when
scale_vars != "none");lowermust not exceedupper, nor beInf(norupper-Inf). Each accepts three forms:NULL(default) Unbounded (
-Inf/Inf).- Unnamed numeric vector of length
n_params Full-length vector ordered exactly like
theta_init(the nloptr-native form).- Named numeric vector
Names must be a subset of the parameter names (\(\beta\) block: column names of
X; \(\mu\) block:Mu_<col>(ifrc_mean = TRUE); Cholesky block:L_<i><j>for \(i \ge j\); ASC block:ASC_<level>). Unlisted parameters default to \(\pm\infty\). This is the recommended form for typical use, e.g.lower = c(L_11 = -5, L_22 = -5)to clip Cholesky diagonals.
- optimizer
Optimizer to use:
"nloptr"(default),"optim", or a custom function. Seerun_mnlogitfor details.- control
List of optimizer-specific control parameters. With
scale_varsother than"none", settings in parameter units apply to the scaled coordinates.- se_method
Method for computing standard errors. One of
"hessian"(default) for the analytical Hessian of the simulated log-likelihood,"bhhh"for the BHHH/outer-product-of-gradients (OPG) estimator,"sandwich"for the robust (Huber-White) variance \(V = A^{-1} B A^{-1}\) (bread \(A\) = weighted negated Hessian, meat \(B\) = weight-squared OPG), or"cluster"for the cluster-robust sandwich (requirescluster_color a preparedinput_datawith aclusterfield). Use"sandwich"for valid inference under choice-based / WESML weighting, where the inverse-Hessian and ordinary BHHH are invalid; it reduces to the usual robust variance under uniform weights. BHHH needs no second derivatives and so costs less than the Hessian. For both, the work per decision maker involves only the parameters that enter that decision maker's likelihood (the fixed coefficients, the random coefficients' means and Cholesky factor, and the constants of the alternatives they faced), so it does not grow with the number of alternatives in the data; the parameters-by-parameters matrix and its inversion do. BHHH may underestimate standard errors in finite samples or away from the optimum. Any of these variances can also be recomputed post hoc viavcov(fit, type = ). Withoutperson_col, clustering repairs the inference, not the likelihood: the cross-sectional likelihood still treats each choice situation as an independent draw from the mixing distribution, and on panel data is a less efficient composite likelihood for the same taste distribution. Withperson_colthe likelihood unit is the decision maker, so scores are per decision maker and"sandwich"is already robust to dependence across a decision maker's choice situations;"cluster"is then needed only for coarser groups (e.g. households or markets) that nest decision makers.- scale_vars
How the optimizer's coordinates are scaled. The choice does not change the estimator; it changes how fast, and whether, the optimizer reaches the maximum.
"bhhh"(default) scales each parameter by the inverse square root of the diagonal of the BHHH (outer product of gradients) matrix at the start values, rounded to a power of two, from one extra gradient pass, so that the BHHH diagonal, an estimate of the curvature, is near one at the start values in every coordinate: it reaches the constants and the Cholesky factor, whose curvatures can differ by orders of magnitude that no column scale reaches (the constants of large and small alternatives, say). A start near the estimates (theta_init) gives it a better diagonal. Where the diagonal is unusable (no finite, positive entry, as when the likelihood overflows at the start values), the parameters are left unscaled, with a message."none"hands the optimizer the parameters as they are (the default in choicer 0.2.x). With"sd"(sample standard deviation),"mad"(stats::mad, i.e. 1.4826 \(\times\) median absolute deviation; SD-equivalent under normality) or"iqr"(stats::IQR(x) / 1.349; also SD-equivalent under normality), the optimizer works on the parameters the design would have with every column ofXandWdivided by the chosen scale; the constants keep their scale, the data are not divided, and the fit holds no scaled copy of them. Robust scales ("mad"/"iqr") better capture the bulk for heavy-tailed columns where SD is dominated by outliers, butstats::madcan return zero when more than half of a column's entries are identical (e.g., a sparse 0/1 dummy) and will then trigger the same near-constant-column error as"sd". The parameters of log-normal random coefficients (rc_dist == 1) keep their scale under these three, since the shifted log-normal parameterization does not admit a closed-form rescaling under multiplicative column scaling. With any choice but"none"(so by default), the optimizer, a custom one included, works in the scaled coordinates (theta_init,lowerandupperare given in natural units and mapped), so settings in parameter units incontrol(nloptr'sxtol_abs; optim'sparscale, andpgtol, which then applies to the scaled gradient) apply to the scaled coordinates;"none"keeps the parameters' units. Coefficients are reported in natural units and the standard errors computed in them, from the information matrix equilibrated before it is inverted, whatever the choice, so, where the likelihood is well identified and every choice reaches its maximum, reported quantities do not depend on this choice beyond the optimizer's tolerance.- weights
Optional weight vector (convenience workflow), one weight per choice situation in ascending-id order (see
prepare_mxl_data). Withperson_col, situations are reordered by decision maker, so a positional vector is accepted only when that leaves the id order unchanged; otherwise supplyweights_col. IfNULL, equal weights are used. All weights must be finite and strictly positive. Withperson_colthey are decision-maker weights, constant within each decision maker: the objective is \(\sum_n w_n \log L_n\).- outside_opt_label
(Convenience workflow.) The label of the outside option or of the base alternative, given in the class of the alternative column. With
include_outside_option = TRUEit names the outside option's row ofalt_mapping; rows of the data that carry it are kept, unlike inprepare_mnl_data(), as an inside alternative, so drop them first. Without the outside option it names the base alternative, coded first (with constants, its constant is normalized to 0); it must be one of the alternatives, andNULL(the default) makes the first alternative in sort order the base.- include_outside_option
Logical whether to include an outside option (convenience workflow).
- draws
Draw storage mode. One of
"store"(default) or"generate"."store"pre-materializes the full \(K_w \times S \times U\) Halton cube (\(8 K_w S U\) bytes), one block per likelihood unit (Udecision makers withperson_col, choice situations otherwise; existing behavior, exact reproducibility). It supports at most \(2^{31} - 1\) points (\(S \times U\)).predict(),logsum(),consumer_surplus(),elasticities(),diversion_ratios(),blp()andgof()(hencesummary()'s fit statistics) integrate over one block per choice situation instead (seeget_halton_normals). With up to 128 random coefficients they form each block on the fly, in parallel, from the pointsget_halton_normals(S, N, K_w)would hold for the \(N\) choice situations, mapped by R'sqnorm(), so they never hold that cube and have no limit on the number of points; with more, they build the cube. Their draws, and so their results, are the cube's, bit for bit where randtoolbox and choicer are compiled with the same floating-point contraction, as on CRAN's platforms (otherwise some of the underlying uniforms differ in their last bit, which moves those draws by at most a few parts in \(10^9\), in the far tails); sums over choice situations are bit for bit at one thread, and at more threads vary in their last bits with the threads' order, as they always did.blp()may keep the draws it forms across its iterations, within itskeep_draws_bytes(4 GiB by default), with either storage mode. In the convenience workflow,run_mxlogit()warns before it builds an estimation cube above 1 GiB: the cube is held while the model is fitted, andvcov(type = ),wesml_vcovandconditional_tastesrebuild it whole."generate"computes each unit's draws on-the-fly in C++ from a stored seed, eliminating the O(U) cube; recommended for memory-constrained or large-N settings. Withscramble = "permuted", each base-\(b\) digit position in each dimension receives a seeded permutation shared across sequence indices. This is not Owen's nested-uniform scramble and does not carry standard randomized-QMC unbiasedness or error-estimation guarantees. Only supported in the convenience workflow.- seed
Integer master seed for the on-the-fly generator. Used only when
draws = "generate". IfNULL(default), a seed is drawn from R's RNG at call time (soset.seed()governs reproducibility). Ignored whendraws = "store".- scramble
Scrambling mode for on-the-fly Halton draws. One of
"permuted"(default) for seeded position-wise digit permutations or"none"for plain Halton (identity permutations). The historical value"owen"is accepted with a deprecation warning as an alias for"permuted"; the implementation is not Owen's nested-uniform scramble."none"uses the points of the randtoolbox sequence, mapped to normals by choicer's own inverse normal CDF, which is within about \(10^{-14}\) ofqnorm(): its draws agree with store mode's to that precision, not bit for bit. Simulation-draw sensitivity should be assessed by increasingSand, for"permuted", varyingseed. Used only whendraws = "generate".- keep_data
Logical. If
TRUE(default), stores prepared data in the returned object for post-estimation functions.- nloptr_opts
Deprecated. Use
optimizerandcontrolinstead.- weights_col
Optional name of a column in
dataholding a per-row weight (constant within each choice situation, finite and strictly positive). Mutually exclusive withweights; the recommended way to pass WESML weights fromsample_by_choice/wesml_weights, since alignment is by id rather than by position. Convenience workflow only. Ifdatacarries choice-based-sampling provenance (a"choice_sampling"attribute, as attached bysample_by_choice/wesml_weights) and neitherweightsnorweights_colis supplied, the recorded weight column is auto-detected and applied (with a message); if that column is absent the call errors rather than silently fitting an unweighted model under a WESML label. Withperson_colthe weight must also be constant within each decision maker, and WESML is not supported: choice-based weights vary with the chosen alternative across a decision maker's situations, so they cannot weight the panel likelihood.- cluster_col
Optional name of a column in
dataholding cluster labels for cluster-robust standard errors (e.g. a person id when the same decision maker contributes several choice situations to a cross-sectional fit). Must be constant within eachid_col, and within each decision maker whenperson_colis used (clusters must nest decision makers). Supplyingcluster_colwithout an explicitse_methodselectsse_method = "cluster".- person_col
Optional name of the column in
dataidentifying decision makers (respondents). When supplied, all choice situations of a decision maker share one draw of the random coefficients (panel likelihood);id_colmust still identify choice situations uniquely across the data set: an id under two decision makers is an error, even where a missing or infinite value would drop it, and a choice situation whose decision maker is missing is dropped like one with any other missing value. That drop goes by id, so a shared id one of whose copies has no decision maker in any row is dropped whole rather than reported.NULL(default) makes each choice situation its own decision maker (cross-sectional likelihood). Convenience workflow only; in the advanced workflow passperson_coltoprepare_mxl_data.- polish
A Newton phase after the optimizer (see the section below):
"none"(default) has none;"newton"steps on the analytic Hessian of the simulated log-likelihood,"bhhh"on the BHHH (outer product of the gradients) matrix, both with the fit's draws and weights.- polish_control
List of settings of the Newton phase, any of
max_iter(20; 0 evaluates the decrement at the optimizer's solution without stepping),tol_decrement(\(10^{-8}\), in log-likelihood units of weights with mean one: the decrement is taken over the mean weight, so that the rule does not depend on the weights' scale),tol_step(\(10^{-12}\): a step shorter than this, relative to the parameters' magnitudes plus their scales in the optimizer's coordinates, stops the polish unconverged) andrestart(TRUE: run the optimizer and the polish once more from a zero-variance plateau; see the section below).- concentrate_out_asc
How the alternative-specific constants are estimated (see the section below).
"none"(default): with the other parameters, by the optimizer."profile_likelihood": the optimizer moves the other parameters only, and at each of its points the constants are solved from their first-order condition; the estimator, and so the estimates and their standard errors, are the same, to the optimizers' tolerance."blp": the constants are held at the solution of the share equations, the model's shares on the estimation draws equal totarget_shares(the sample's own shares by default), and the other parameters maximize the likelihood given them: a different estimator, with its own standard errors.- concentrate_control
List of settings of the constants' inner solve. For
concentrate_out_asc = "blp":max_iter(1000 evaluations of the shares per solve; the first may take four times as many),tol_shares(\(10^{-12}\): the largest absolute log-share residual accepted) andmax_dense(10000: the most constants whose share Jacobian is formed and factored densely). Otherwise any ofmax_iter(25 Newton steps per solve; the first, from the start values, may take four times as many),tol_residual(\(10^{-10}\): the solve stops when every constant's score, and the reference's, is below it relative to its alternative's weighted chosen count plus the mean weight),tol_decrement(\(10^{-12}\): or when the Newton decrement over the mean weight falls below it, in log-likelihood units of weights with mean one, so that neither rule depends on the weights' scale) andmax_dense(10000: the most constants whose block of the information is formed and factored densely, more being an error before the draws; for \(J\) constants a solve holds two \(J \times J\) matrices, \(8 J^2\) bytes each (0.8 GB at \(J = 10^4\)), besides the kernel's accumulators, and each Newton step factors one, about \(J^3 / 3\) operations).For
concentrate_out_asc = "blp": the shares the constants match, each inside alternative's share within its market (a group of alternatives that share choice situations), named by the alternatives' labels or in their order; with an outside option and one market, alsoblp()'s convention, the outside option's share first. NULL (default): the sample's own weighted shares, or a choice-based sample's population shares (itsQ).- target_vcov
For
concentrate_out_asc = "blp"withtarget_shares: their sampling covariance, a positive semi-definite matrix over the inside alternatives intarget_shares' order, or in the order of its row and column names when it has them, the alternatives' labels (for shares from \(n\) independent choices in a market, \((\mathrm{diag}(s) - s s') / n\) on that market's block). NULL (default): the targets are exact.
Value
A choicer_mxl object (inherits from choicer_fit).
Standard S3 methods available: summary(), coef(),
vcov(), logLik(), AIC(), BIC(),
nobs(). A panel fit (person_col) also carries
n_persons, the number of decision makers; nobs() remains
the number of choice situations, which is also the \(n\) in BIC's
\(\log n\) penalty. The variance is computed once the optimizer has
stopped. If that step fails with an error (the kernels' memory check,
see set_num_threads, say), the fit returns its estimates
without it (vcov NULL, NA standard errors, the
error's message in variance_error) and warns, naming the
vcov(fit, type = ) that computes the variance later from a fit
that keeps its data (keep_data = TRUE); the memory check's message
names the threads that fit or how to lift its limit. With polish,
fit$optimizer$polish records the Newton phase: method,
converged, iterations (steps taken) and damped,
decrement (over the mean weight; NA where the curvature
on the parameters moved was not positive definite) and lambda
(its damping) at the last
curvature evaluated, message (why it stopped),
evaluations (of the objective and the curvature), active,
held and flat (the parameters on a bound, held, and left
out of the last steps for want of usable curvature), improvement
(the log-likelihood gained), error, elapsed_time (the
polish's seconds, which fit$optimizer$elapsed_time includes), and
optimizer, the optimizer's own convergence,
message, iterations and elapsed_time. Where the
polish restarted from a zero-variance plateau (see the section), the
record, of the point that stands, also has restart:
parameters, adopted, gain (the log-likelihood
gained by the restart, negative where it ended lower), converged,
optimizer_iterations and polish_iterations (the restart's),
error and elapsed_time. A converged
polish sets convergence to the optimizer's success code (1 for
nloptr, 0 for optim and a custom optimizer) and leads message
with its verdict; otherwise both keep the optimizer's, the polish's
reason appended to the message. A polish that stops with an error (the
Hessian's memory check, say) keeps its last accepted point and warns
(class choicer_polish_failed). An optimizer that reports a failure
(nloptr's negative codes, such as NLOPT_FAILURE where L-BFGS's line
search gives up, and optim's 10, 51 and 52) may have returned its start
values or stopped at the maximum, which its code cannot tell. Without a
polish, a Newton phase of no steps then checks its point:
fit$optimizer$polish records it (iterations 0), and a point
it certifies takes the success code as above; under
concentrate_out_asc = "blp", which takes no polish, the outer
decrement below polish_control's tol_decrement does, in the
outer objective's own curvature (below). A point
nothing certified keeps the failure code and warns (class
choicer_optimizer_failed). So too an optimizer stopped at its cap,
whoever set it (nloptr's 5, maxeval, and 6, maxtime; optim's
1, maxit; no custom optimizer): the same check reads its point (a
pass of the Hessian that the variance reuses except under
se_method = "bhhh"; under "blp", the outer decrement), and a
point nothing certified keeps its code and warns (class
choicer_optimizer_capped), giving the Newton decrement where the
Hessian is positive definite, roughly the log-likelihood still to gain under
weights of mean one.
suppressWarnings(classes = "choicer_optimizer_capped") silences a
deliberate short run. With
concentrate_out_asc = "profile_likelihood", fit$optimizer
describes the optimizer over the other parameters, and
fit$optimizer$concentration records the inner solves:
method, evaluations (the optimizer's calls of the
profile, the start's and the cached point's included; the optimizer's own
count is fit$optimizer$iterations), solves,
failed (solves at the points the optimizer tried that did not
converge; the final solve, at its solution, is reported below),
inner_iterations (Newton steps), passes (of the
constants' kernel), max_residual (the largest relative score of
the constants at a converged solve, above tol_residual where the
decrement stopped the solve), residual and decrement (over
the mean weight; NA where the residual rule stopped the solve) at the
profile's solution, before any polish, and elapsed_time (the
optimizer's seconds, its solves and the first one included, as in
fit$optimizer$elapsed_time without a polish). Failed solves after
the optimizer's best point, and a failed solve at its solution, are
reported in the warning and appended to fit$message.
With concentrate_out_asc = "blp", fit$share_targets
holds the targets: source ("sample", "supplied"
or "wesml"), shares (each inside alternative's target
within its market, named by label), market (each inside
alternative's market, the markets numbered by their smallest codes),
market_weight (each market's weight), vcov
(target_vcov in the alternatives' order, or NULL), and
the share inversion's engine targets, the free constants'
target counts and each likelihood unit's market
(unit_market); it is NULL on other fits. Its
fit$optimizer$concentration records method,
evaluations, solves and failed as the profile
likelihood's do, inner_iterations (evaluations of the shares),
jacobians (passes of the share Jacobian, one per solve whose
share inversion converged), max_residual (the largest log-share
residual of a converged solve) and residual (at the estimate),
lambda (\(C_\delta^{-1} g_\delta\) at the
estimate, by constant, \(C_\delta\) the Jacobian of the weighted
predicted counts in the constants and
\(g_\delta\) the gradient of the negated log-likelihood in the
constants: the derivative of the negated log-likelihood with respect to
each free constant's target count, positive where the micro data would
put that alternative's share below its target), decrement
(\(g^\top \tilde I^{-1} g / 2\) over the mean
weight, \(g\) the total gradient in \(\theta_c\) and
\(\tilde I\) the curvature along the share constraint, from the
fit's variance: the BHHH matrix's under se_method = "bhhh";
NA without a variance, or where that curvature is not positive
definite. Where the optimizer reports a failure or stops at its cap, it
is the decrement in the outer objective's own Hessian whatever se_method, from central
differences of the outer gradient, two solves of the constants per
continuous parameter: \(\tilde I\) omits the constants' score times
the curvature of the constants in \(\theta_c\), a score that is
not zero where the shares match (the share equations average the choice
probabilities over the draws, the score weights each draw by its
posterior), so it can be positive definite at a minimum, and the BHHH
matrix is positive semidefinite at any point) and elapsed_time.
Details
Two workflows are supported:
- Convenience
Supply
dataand column names. Data preparation (prepare_mxl_data) and Halton draw generation (get_halton_normals) are handled automatically.- Advanced
Call
prepare_mxl_dataandget_halton_normalsyourself, then pass the results viainput_dataandeta_draws.
Cross-section vs panel. With person_col, each decision
maker \(n\) draws one taste vector \(\beta_n\) from the mixing
distribution \(f(\beta \mid \theta)\) and keeps it in all of their choice
situations \(t = 1, \dots, T_n\). The likelihood integrates the product
of their conditional logit probabilities (Revelt and Train 1998),
$$L_n(\theta) = \int \prod_{t=1}^{T_n} P_{nt}(j_{nt} \mid \beta)
f(\beta \mid \theta) \, d\beta,$$
simulated with S draws per decision maker, so repeated choices
speak to each decision maker's tastes, and
conditional_tastes recovers what they reveal. Without
person_col (the default), each choice situation is an independent
draw from the mixing distribution: \(L_i(\theta) = \int P_i(j_i \mid
\beta) f(\beta \mid \theta) \, d\beta\). That is the right model when tastes
are redrawn in every situation (or each decision maker chooses once). On
panel data with stable tastes it is a composite (pseudo-) likelihood: it
still targets the population mixing distribution, but it ignores the
within-person correlation of choices, so it is less efficient, its
standard errors must be clustered by decision maker (cluster_col),
and its log-likelihood, AIC and BIC are not comparable with those of the
panel fit.
Newton phase (polish)
The polish does not change the estimator. From wherever the optimizer
stopped (at its tolerance or at maxeval), it finishes the climb to
the maximum the optimizer approached, which first-order methods such as
L-BFGS reach slowly when curvatures differ by orders of magnitude
(thousands of constants, say), and certifies it. It converges when the
Newton decrement
\(\nu = \frac{1}{2} g^\top C^{-1} g\), with \(g\)
the gradient and \(C\) the curvature on the parameters it moves, over
the mean weight (as if the weights had mean one, whatever their scale),
falls below tol_decrement. On a positive definite Hessian (of the
weights scaled to mean one),
\(\sqrt{2\nu}\) is the distance from the estimates to the
maximum of the log-likelihood's quadratic model in Hessian standard
errors: at the default \(10^{-8}\), every linear combination of
the estimates lies within \(1.4 \times 10^{-4}\) of its standard
error of that maximum. BHHH is positive semi-definite everywhere and
cheaper per step, but converges linearly; where the Hessian \(H\) is
positive definite, its \(\sqrt{2\nu}\) is that distance in
the standard errors of the sandwich \(H^{-1} B H^{-1}\)
(the robust standard errors of an unweighted fit), but on its own it shows
a stationary point, not a maximum. "bhhh" needs at least as many
likelihood units as the parameters it moves.
In a validation study on census- and claims-style designs (see
news(package = "choicer")), the default optimizer stopped within
\(1.1 \times 10^{-4}\) standard errors of the maximum, and
polish = "newton" after it certified that maximum at once, or in
one step, for 0 to 20% of the fit's time, its Hessian then serving the
variance. Handing over to it earlier (a small maxeval) rarely paid:
one of ten hand-overs was faster, and one certified another local maximum.
For a reportable fit with many constants, polish = "newton" after
the optimizer's own stop is the recommended check.
Where the curvature is not positive definite the steps are damped
(Levenberg-Marquardt); they respect lower/upper and pass a
line search. The constants of inside alternatives without a finite
estimate (see use_asc) are held at the optimizer's values, and the
certificate concerns the other parameters given them. Where the base
alternative or the outside option is the one without, the other constants
diverge together, and the polish does not report convergence, unless the
reference is never chosen and the constants held or bounded above anchor
all the others, which stops their rise: each other constant's alternative
is offered in a choice situation that chooses an alternative whose
constant is held or bounded above, or one anchored so. A random coefficient
whose variance's local maximum is at zero drives its log-Cholesky diagonal
toward \(-\infty\) by Newton steps of \(\frac{1}{2}\) to 1, each
shrinking the decrement by a factor of about \(e\): "newton" may
certify a point where the variance is negligible but that diagonal, and
its standard error, depend on tol_decrement; "bhhh", whose
curvature in that direction vanishes faster, comes to hold the diagonal
and stops unconverged. Such a point (a standard deviation below
\(10^{-4}\) of the default start's) can be a false stop: the first
derivative of a simulated likelihood in a standard deviation at zero is not
zero with finitely many draws, and where it is negative, zero is a local
maximum, often below a higher one. So the polish restarts once from there:
the optimizer and the polish again from the same point with those standard
deviations raised, a normal coefficient's to the default start's (one over
its column's typical step), a log-normal's to 1, in coordinates taken afresh.
The higher likelihood stands. On a stated-preference panel of 200 persons, 4
of 40 fits 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 it fell from 47 to 6. On logit
data, whose variances are zero, 23 of 40 stopped so and all 23 ended at zero
again. Where a variance ends at zero the fit warns (class
choicer_variance_plateau), with or without a polish: the standard
error of that diagonal says nothing (a clustered one is of order one where
the Hessian's reads \(10^4\)). 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
concentrate_out_asc = "profile_likelihood" the fit warns without
restarting. A parameter without usable curvature (no
information at the point, or a curvature that has all but vanished, giving
a step more than 100 times its scale in the optimizer's coordinates) is
held for the step and stops the polish unconverged. Under
scale_vars = "none", whose coordinates are the parameters' natural
units, those scales come from one BHHH pass at the optimizer's solution
(one gradient evaluation), so that a badly scaled column far from its
maximum is not held as if its curvature had vanished. The
standard errors are computed at the polished estimates, by
se_method. The polish evaluates its curvature at the point it
returns before it stops (unless it falls back to the optimizer's solution
after steps that ended worse, the curvature itself failed, or the start
could not be evaluated), so that matrix serves the variance whenever it is
the one
se_method needs, instead of being evaluated again: after
"newton", the Hessian of "hessian" and the bread of
"sandwich" and "cluster"; after "bhhh", the BHHH
matrix of "bhhh" (the sandwich's meat squares the weights, so it is
computed). Where it serves so, a polish that certifies the optimizer's
solution at once costs one evaluation of the log-likelihood and its
gradient and one factorization of the curvature more than the fit without
it.
Each step costs a curvature evaluation and a line search. A smaller
maxeval (nloptr) or maxit (optim) in control hands
the polish a point sooner, but from farther away its steps are shortened
(and damped where the curvature is not positive definite) and more of them
are needed: in the study above that rarely paid, which is why the polish
is recommended after the optimizer's own stop.
Profile likelihood of the constants (concentrate_out_asc)
With many alternatives the constants \(\delta\) are most of the
parameters. concentrate_out_asc = "profile_likelihood" maximizes the
profile log-likelihood
\(\ell^*(\theta_c) = \max_\delta \ell(\theta_c, \delta)\) over the other parameters \(\theta_c\),
so the optimizer works on those alone. The estimator does not change: the
profile's maximizer is the joint one, and the variance is the joint fit's,
computed at \((\hat\theta_c, \hat\delta)\)
from the full matrices. The full Hessian's inverse gives
\(\theta_c\) the inverse of the Schur complement
\(H_{cc} - H_{c\delta} H_{\delta\delta}^{-1} H_{\delta c}\), the curvature of the profile; the inverse of
\(H_{cc}\) alone would treat the constants as known and
understate the standard errors. At each point the optimizer tries, the
constants solve their first-order condition: each alternative's weighted
chosen count equals its predicted count, the probabilities weighted by
each decision maker's posterior over the draws given their choices (not
the unconditional shares that BLP share matching equates). The solve takes
damped Newton steps on the constants' block of the information,
warm-started from the best point the optimizer has reached, and the
optimizer's gradient is the joint gradient at the solution (the envelope
theorem). The optimizer, its control and a custom optimizer see the
other parameters only. Where the constants cannot be solved at the start
values the fit stops there (class choicer_profile_unconverged; an
error inside that solve is reported as itself). A
later solve that does not converge is an overflow to the optimizer, which
then backtracks, and is counted; the fit warns (the same class) when such
solves come after the optimizer's best point, which may have stopped it,
or when the constants cannot be solved at its solution.
Every constant needs a finite maximum-likelihood estimate: with an
alternative never chosen, or chosen wherever it is offered, or such a
reference (see use_asc), the fit stops before the draws (class
choicer_unbounded_constants). Bounds on the constants are an error
too; bounds on the other parameters go to the optimizer. The counts
do not reveal every such pattern (a group of alternatives chosen only
where nothing outside the group is offered, say): the constants then drift
as in a joint fit, and their standard errors are huge or missing.
It is an expert option. Each of the optimizer's evaluations costs an inner
solve, whose Newton steps each take a pass of the constants' kernel (about
three gradient passes) and a dense factorization of their block. On the
study's census- and claims-style designs the profile reached the joint
fit's maximum, and ended closer to it, in 21 to 49 evaluations of the
optimizer, 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 default
coordinates needing 46 to 224 evaluations of the joint problem;
polish = "newton" certifies either.
Share-matching constants (concentrate_out_asc = "blp")
concentrate_out_asc = "blp" holds the constants at the solution of
the share equations and maximizes the likelihood over the other parameters
\(\theta_c\) given them (Train and Winston 2007): at every
\(\theta_c\), the constants \(\delta(\theta_c)\)
(unique where a solution exists, Berry 1994) make each inside
alternative's predicted share in its market equal its target, the
predicted share averaging the probabilities over the weighted
sample and over each decision maker's own estimation draws with equal
weights (unconditional shares, not the posterior-weighted counts of
"profile_likelihood"). It is a different estimator from maximum
likelihood. It coincides with it in the logit with the sample's shares as
targets, and with the maximum-likelihood fit's own predicted shares on its
estimation draws as targets; with external shares known more precisely
than the sample's it
can estimate the constants more precisely than maximum likelihood.
The targets (target_shares) are each inside alternative's share
within its market, a market being a group of alternatives that share
choice situations (most data have one): with an outside option a market's
outside share is one minus its inside targets; without one, a market's
targets sum to one, and data with more than one market are an error, the
groups' constants having no common level. By default the targets are the
sample's own weighted shares, which the fit then reproduces, or, for a
choice-based sample (wesml_weights), its population shares
Q, taken as exact. The targets are checked before the draws by the
share inversion's rules (each alternative offered in some situation of
positive weight; each target below the weight of the situations that offer
it and, without an outside option, above that of the situations that offer
it alone; each market's outside share positive). The sample's own shares
must be attainable, checked on the exact chosen counts: an alternative
never chosen, or chosen wherever it is offered, a market where no one
chooses the outside option, or, without one, an alternative chosen only
where it is offered alone, is an error (class
choicer_unbounded_constants). The constants may not be bounded,
polish must be "none" (a Newton phase on the likelihood
would move the estimate to maximum likelihood's), and
concentrate_control's max_dense (10,000) bounds their count.
At each point the optimizer tries, the share inversion of blp
runs on the estimation draws to a log-share residual of
tol_shares, from the best point's constants advanced along the
implicit function's tangent; the optimizer's gradient adds the
implicit-function term, from one dense factorization of the share
Jacobian, and its objective is corrected to second order in the inner
solve's error (fit$loglik is the log-likelihood at the estimate). A
solve that does not converge is an overflow to the optimizer. One at the
start values stops the fit (an error inside that solve is reported as
itself); ones after the optimizer's best point, or at its solution, make
the fit warn. Both conditions have class choicer_blp_unconverged.
On the census- and claims-style designs of the profile likelihood's study
a fit took about as long as the profile likelihood's, half (census) to
two-thirds (claims) of it in the passes of the share Jacobian.
The standard errors are the share-constrained estimator's, for every
se_method: the stacked equations of the score projected along the
share constraint and the share residuals, including the targets' sampling
error (the sample's: under "hessian" and "bhhh" the model's
variance of the chosen counts; target_vcov for supplied
targets, for shares from \(n\) independent choices in a market
\((\mathrm{diag}(s) - s s^\top)/n\) on its block, not
its diagonal alone). Every type assumes correctly specified choice
probabilities; "sandwich" and "cluster" relax the
information equality (sampling weights, dependence within clusters), and
with targets other than the sample's over several markets each decision
maker, and each cluster, must lie in one market. In a Monte Carlo
(vignette("mxl")) exact targets cut the constants' standard
deviations to about half of maximum likelihood's, while targets estimated
from as many choices as the sample's made them noisier and moved the other
parameters toward zero (the largest bias 0.29 standard deviations, 0.13
with exact targets), the intervals still covering; fewer choices bias them
more.
logLik(), AIC and BIC are the likelihood at the constrained
estimate (likelihood-ratio tests between such fits are not
\(\chi^2\)), conditional_tastes's identities
do not hold, and predict(type = "shares") and blp
reproduce the targets (as shares of the whole sample,
fit$share_targets$engine) and the constants only on a
cross-section.
Column names
No column the model uses (the id, alternative, choice, covariate, weight,
cluster, nest or decision-maker column) may have a name starting with
.choicer_, which choicer reserves for its working columns, and the
alternative column may not be named alt_int, N_OBS, N_CHOICES,
TAKE_RATE or MKT_SHARE, the names of the other columns of
alt_mapping. Either is an error that names the column. Columns the model
does not use may have any name.
Missing and non-finite values
A choice situation with a missing value (NA or NaN) in a covariate is
dropped, with a warning that counts the situations dropped, and so is one
with an infinite value (Inf or -Inf), with a warning that also names
the covariates that hold such values. A preparation that would drop every
choice situation stops instead. Infinite values usually come from a
transformation such as log(0); dropping their situations selects the
sample on that covariate, so they are often better fixed before the data
are prepared. Prepared data passed to a fitting function as input_data
are not filtered again: such values in them are an error.
References
Revelt, D. and Train, K. (1998). Mixed logit with repeated choices: households' choices of appliance efficiency level. Review of Economics and Statistics 80(4), 647-657.
Train, K. E. and Winston, C. (2007). Vehicle choice behavior and the declining market share of U.S. automakers. International Economic Review 48(4), 1469-1496.
Berry, S. (1994). Estimating discrete-choice models of product differentiation. RAND Journal of Economics 25(2), 242-262.
See also
conditional_tastes, run_hmnlogit (the
hierarchical Bayes counterpart), set_num_threads (threads
and the memory check of the compiled routines),
vignette("mxl") (many alternatives: constants, convergence and
standard errors)
Examples
# \donttest{
library(data.table)
set.seed(42)
N <- 100; J <- 3
dt <- data.table(id = rep(1:N, each = J), alt = rep(1:J, N))
dt[, `:=`(x1 = rnorm(.N), w1 = rnorm(.N), w2 = rnorm(.N))]
#> id alt x1 w1 w2
#> <int> <int> <num> <num> <num>
#> 1: 1 1 1.37095845 -0.004620768 -0.2484829
#> 2: 1 2 -0.56469817 0.760242168 0.4223204
#> 3: 1 3 0.36312841 0.038990913 0.9876533
#> 4: 2 1 0.63286260 0.735072142 0.8355682
#> 5: 2 2 0.40426832 -0.146472627 -0.6605219
#> ---
#> 296: 99 2 -0.47733551 0.160327395 0.1704735
#> 297: 99 3 -0.16626149 -0.433641942 1.2006682
#> 298: 100 1 0.86256338 1.537412419 -0.1634059
#> 299: 100 2 0.09734049 -2.170246577 1.2824759
#> 300: 100 3 -1.62561674 1.027004619 2.7271964
dt[, choice := 0L]
#> id alt x1 w1 w2 choice
#> <int> <int> <num> <num> <num> <int>
#> 1: 1 1 1.37095845 -0.004620768 -0.2484829 0
#> 2: 1 2 -0.56469817 0.760242168 0.4223204 0
#> 3: 1 3 0.36312841 0.038990913 0.9876533 0
#> 4: 2 1 0.63286260 0.735072142 0.8355682 0
#> 5: 2 2 0.40426832 -0.146472627 -0.6605219 0
#> ---
#> 296: 99 2 -0.47733551 0.160327395 0.1704735 0
#> 297: 99 3 -0.16626149 -0.433641942 1.2006682 0
#> 298: 100 1 0.86256338 1.537412419 -0.1634059 0
#> 299: 100 2 0.09734049 -2.170246577 1.2824759 0
#> 300: 100 3 -1.62561674 1.027004619 2.7271964 0
dt[, choice := sample(c(1L, rep(0L, J - 1))), by = id]
#> id alt x1 w1 w2 choice
#> <int> <int> <num> <num> <num> <int>
#> 1: 1 1 1.37095845 -0.004620768 -0.2484829 0
#> 2: 1 2 -0.56469817 0.760242168 0.4223204 1
#> 3: 1 3 0.36312841 0.038990913 0.9876533 0
#> 4: 2 1 0.63286260 0.735072142 0.8355682 0
#> 5: 2 2 0.40426832 -0.146472627 -0.6605219 0
#> ---
#> 296: 99 2 -0.47733551 0.160327395 0.1704735 1
#> 297: 99 3 -0.16626149 -0.433641942 1.2006682 0
#> 298: 100 1 0.86256338 1.537412419 -0.1634059 0
#> 299: 100 2 0.09734049 -2.170246577 1.2824759 0
#> 300: 100 3 -1.62561674 1.027004619 2.7271964 1
fit <- run_mxlogit(
data = dt, id_col = "id", alt_col = "alt", choice_col = "choice",
covariate_cols = "x1", random_var_cols = c("w1", "w2"), S = 50L
)
#> Optimization run time 0h:0m:0.02s
#> Warning: The log-Cholesky diagonals L_11 (-22.4), L_22 (-19.5) have gone to minus infinity: the variance of those random coefficients, given those before them, is numerically zero. The score of such a diagonal vanishes with it, so its standard error says nothing and the Newton decrement cannot tell this point from a maximum. It can be a local maximum below a higher one: fit with polish = "newton", which restarts once from it, or start elsewhere (theta_init).
summary(fit)
#> Mixed Logit (MXL) model
#>
#> Parameter Estimate Std.Error z-value Pr(>|z|)
#> x1 0.005704 0.121525 0.0469 9.63e-01
#> Sigma_11 0.000000 0.000000 0.0000 1.00e+00
#> Sigma_22 0.000000 0.000000 0.0000 1.00e+00
#> ASC_2 0.031083 0.248189 0.1252 9.00e-01
#> ASC_3 0.089236 0.244715 0.3647 7.15e-01
#> ---
#> Signif. codes: '***' 0.001 '**' 0.01 '*' 0.05
#>
#> Random coefficient covariance (Sigma):
#> w1 w2
#> w1 3.768717e-20 0.00000e+00
#> w2 0.000000e+00 1.04647e-17
#>
#> Std. Errors: Analytical Hessian
#> Log-likelihood: -109.79
#> AIC: 229.581 | BIC: 242.607
#> McFadden R2: 0.001 (adj: -0.045) | Hit rate: 0.350
#> N: 100 | Parameters: 5
#> Optimization time: 0.02 s
#> Convergence: 3 ( NLOPT_FTOL_REACHED: Optimization stopped because ftol_rel or ftol_abs (above) was reached. )
# }