Estimates a nested logit model via maximum likelihood.
Usage
run_nestlogit(
data = NULL,
id_col = NULL,
alt_col = NULL,
choice_col = NULL,
covariate_cols = NULL,
nest_col = NULL,
input_data = NULL,
use_asc = TRUE,
theta_init = NULL,
param_names = NULL,
optimizer = NULL,
control = list(),
weights = NULL,
weights_col = NULL,
outside_opt_label = NULL,
include_outside_option = FALSE,
keep_data = TRUE,
se_method = c("hessian", "numeric", "bhhh", "sandwich", "cluster"),
cluster_col = NULL,
nloptr_opts = NULL,
scale_vars = c("bhhh", "none", "sd", "mad", "iqr"),
polish = c("none", "newton", "bhhh"),
polish_control = list()
)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 covariates. None may be named like a generated parameter:
Lambda_<k>, orASC_<label>withuse_asc = TRUE.- nest_col
Name of the column mapping each alternative to its nest (convenience workflow).
- input_data
List containing prepared input data for estimation (advanced workflow). Mutually exclusive with
data. Its weights must be finite and strictly positive and itsXfinite, whichprepare_nl_data()ensures; the fit checks them again, in case the list was edited or built by hand, before it first evaluates the likelihood (integer64 weights are converted to double).- use_asc
Logical indicating whether to include alternative specific constants (ASCs). An alternative's constant has no finite maximum-likelihood estimate when the alternative is chosen in every choice situation that offers it, or is never chosen in the data (the likelihood keeps rising as the constant grows, or falls); when the outside option or the base alternative is chosen wherever it is offered, or never chosen, the other constants have none together. For a never-chosen alternative, the base included, this holds while the parameter of its nest is at most 1. The fit then warns (class
choicer_unbounded_constants) before the optimizer runs, naming them. It counts rows (alt_mapping), so an alternative listed twice in a choice situation can hide being chosen wherever it is offered.- theta_init
Optional initial parameter vector in natural units, ordered as the coefficients, the nest parameters (
Lambda_<k>, one per nest of two or more alternatives) and the constants. IfNULL: 0 for the coefficients and constants, 0.5 for each nest parameter. A nest parameter started below \(10^{-4}\) warns: from there the optimizer can stop far from the maximum whatever its code says.- param_names
Optional vector of parameter names, which must be unique. If
NULL, default names are generated.- 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.- weights
Optional weight vector (convenience workflow). If
NULL, equal weights are used. All weights must be finite and strictly positive.- weights_col
Optional name of a column in
dataholding per-row weights (convenience workflow only). The column must be constant within eachid_col(one weight per choice situation) and is collapsed accordingly. Mutually exclusive withweights. All weights must be finite and strictly positive. Used for choice-based / WESML weighting; pair withse_method = "sandwich"for valid inference.- 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 labels the outside option, which the model adds: rows of the data that carry it are dropped, and it names the outside option's row ofalt_mapping. 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).
- keep_data
Logical. If
TRUE(default), stores prepared data in the returned object for post-estimation functions.- se_method
Method for computing standard errors:
"hessian"(default, analytical Hessian vianl_loglik_hessian_parallel),"numeric"(finite-difference oracle vianl_loglik_numeric_hessian),"bhhh"(outer product of gradients vianl_bhhh_parallel),"sandwich"(robust Huber–White / WESML variance \(A^{-1} B A^{-1}\)), or"cluster"(cluster-robust sandwich; requirescluster_color a preparedinput_datawith aclusterfield). Use"sandwich"under choice-based / WESML weighting. Any of these can also be recomputed post hoc viavcov(fit, type = ).- 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). Must be constant within eachid_col. Supplyingcluster_colwithout an explicitse_methodselectsse_method = "cluster".- nloptr_opts
Deprecated. Use
optimizerandcontrolinstead.- 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. One of
"bhhh"(default),"none","sd"(sample standard deviation),"mad"(stats::mad), or"iqr"(stats::IQR(x) / 1.349)."bhhh"scales every parameter, nest parameters included, 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, which reads each nest parameter at 0.01 at least. Its scales are fixed at the start values, so when the nest parameters end far from their start (0.5) they can slow the optimizer. With"sd","mad"or"iqr", the optimizer works on the coefficientsXwould have with every column divided by the chosen scale (each coefficient times its column's scale), to improve the conditioning of its problem; the nest parameters and constants keep their scale, and the data are not divided. Under"none"the optimizer works in the parameters' own units, where its line search can give up on the first step: on a mode-choice design whose covariates span units to hundreds, it returned the start values, with a warning, in 100 of 180 choice-based samples of 2,000 and all 8 random samples of 50,000, where"bhhh"reached the maximum in about 50 evaluations. Where the diagonal is unusable (no finite, positive entry), the parameters are left unscaled, with a message, as where the likelihood overflows at the start values. With any choice but"none"(so by default), the optimizer, a custom one included, works in the scaled coordinates (theta_init, in natural units, and the nest parameters' lower bound of 1e-16 are 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.- polish
A Newton phase after the optimizer (see the section below):
"none"(default) has none;"newton"steps on the analytic Hessian of the log-likelihood,"bhhh"on the BHHH (outer product of the gradients) matrix, both with the fit's 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) andtol_step(\(10^{-12}\): a step shorter than this, relative to the parameters' magnitudes plus their scales, stops the polish unconverged).
Value
A choicer_nl object (inherits from choicer_fit).
Standard S3 methods available: summary(), coef(),
vcov(), logLik(), AIC(), BIC(),
nobs(). The variance is computed once the optimizer has stopped.
If that step fails with an error (an allocation in R, 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 compiled
analytical Hessian, BHHH and cluster-meat routines check their memory
before allocating (see set_num_threads); only small
per-situation buffers are allocated inside their parallel loops, where
an allocation that fails still terminates R.
With polish, fit$optimizer$polish records the Newton
phase, as run_mxlogit's does: method,
converged, iterations and damped, decrement
(over the mean weight; NA where the curvature on the parameters
moved was not positive definite, or none was evaluated) and
lambda, message,
evaluations, active, held, flat,
improvement, error, elapsed_time (which
fit$optimizer$elapsed_time includes) and optimizer, the
optimizer's own convergence, message, iterations 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. A point no polish 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
phase checks its point, one pass of the Hessian that the variance reuses
except under se_method = "bhhh" or "numeric", and a point
nothing certified keeps its code and warns (class
choicer_optimizer_capped). A nested logit can stay far from the
maximum until its last evaluations; where the Hessian is positive definite
the warning gives the Newton decrement, roughly the log-likelihood still to
gain under weights of mean one, and far off it mostly is not.
suppressWarnings(classes = "choicer_optimizer_capped") silences a
deliberate short run.
Details
Two workflows are supported:
- Convenience
Supply
dataand column names (includingnest_col). Data preparation (prepare_nl_data) is handled automatically.- Advanced
Call
prepare_nl_data(or build the input list manually) and pass it viainput_data.
Newton phase (polish)
The polish does not change the estimator. From wherever the optimizer
stopped, it takes Newton steps on the curvature of the log-likelihood and
certifies the maximum: 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, falls below tol_decrement. On a positive definite
Hessian (of the weights scaled to mean one) every linear combination of
the estimates then lies within
\(\sqrt{2\nu}\) of its standard error of the maximum of the
log-likelihood's quadratic model (\(1.4 \times 10^{-4}\) at the
default). "bhhh" is cheaper per step but converges linearly, its
decrement on its own shows only a stationary point, and it needs at least
as many choice situations as the parameters it moves. A trial point at
which the likelihood kernel replaces a value (a log probability clamped
to \(-10^{10}\), a total or gradient entry that is not finite,
as where an unchosen nest drops out of the denominator) is rejected.
The nested logit's log-likelihood is concave in the coefficients and
constants for given dissimilarities of at most 1, but not jointly with the
dissimilarities, so its curvature can be indefinite away from the
maximum, where the steps are damped, and a maximum the polish certifies
can be local; the steps keep the dissimilarities at or above their bound
of \(10^{-16}\). Where they drive one to it, they are damped at
nearly every iteration and the polish does not report convergence: refit
from other starts, and where they all end there the likelihood's supremum
is at the bound, the dissimilarity has no interior estimate, and the nest
is to be revised. A dissimilarity that no
choice situation identifies (a nest never offered with two of its
alternatives) has a gradient and a curvature of rounding size: the Newton
polish can move it and certify the other parameters, its standard error
then huge or NA. In a study on census-style designs (2,500
alternatives in 50 nests, 25,000 and 245,000 choice situations), with
scale_vars = "none" the optimizer reached its 1,000-evaluation limit
0.35 and 15.8 log-likelihood units short (up to 6.7 standard errors), and
polish = "newton" certified the maximum in 3 and 5 steps, for about a
tenth of the fit's time; on claims-style designs (500 alternatives) it
stopped closer, and one step certified it. With scale_vars = "bhhh"
the optimizer stopped at the maximum in 50 to 66 evaluations on three of the
four. For a reportable fit with many constants, polish = "newton"
after the optimizer's own stop is the recommended check. Under
scale_vars = "none", whose coordinates are the parameters' own units,
the steps' scales come from one BHHH pass at the optimizer's solution
projected onto the bound (one gradient evaluation).
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: a never-chosen alternative's
only where its nest is a singleton or its dissimilarity is at most 1 at
the optimizer's solution, since above 1 that constant can have a finite
estimate, which the polish then seeks. A polish whose held constant's
nest ends above 1, or whose moved constant's nest ends at or below 1,
does not report convergence. A moved constant that has no finite estimate
even so falls until its share of the decrement is below the tolerance:
its value, and its standard error, are then set by tol_decrement.
Where the base alternative or the outside option is the one without, the
other constants diverge together and the polish does not report
convergence (for a never-chosen base alternative, where its nest's
dissimilarity ends at or below 1), unless the reference is never chosen
and the held constants (of alternatives chosen wherever offered) anchor
all the others, which stops their rise: each other constant's alternative
is offered in a choice situation that chooses a held alternative, or one
anchored so. The polish's last curvature serves the variance where
se_method needs it, unless the polish fell back to the optimizer's
solution, its curvature failed, or its start could not be evaluated:
after "newton", the analytic Hessian of "hessian" and the
bread of "sandwich" and "cluster" (not of
"numeric", whose Hessian is numerical); after "bhhh", the
BHHH matrix of "bhhh". run_mxlogit describes the
steps, the damping, the bounds and the line search.
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.
Examples
# \donttest{
library(data.table)
set.seed(42)
N <- 100; J <- 4
dt <- data.table(id = rep(1:N, each = J), alt = rep(1:J, N))
dt[, `:=`(x1 = rnorm(.N), x2 = rnorm(.N))]
#> id alt x1 x2
#> <int> <int> <num> <num>
#> 1: 1 1 1.3709584 1.33491259
#> 2: 1 2 -0.5646982 -0.86927176
#> 3: 1 3 0.3631284 0.05548695
#> 4: 1 4 0.6328626 0.04906691
#> 5: 2 1 0.4042683 -0.57835573
#> ---
#> 396: 99 4 1.0965134 -1.07287540
#> 397: 100 1 0.4420131 -2.29297143
#> 398: 100 2 0.2410163 -1.20720685
#> 399: 100 3 -0.2556077 0.11410943
#> 400: 100 4 0.9310329 -1.03329708
dt[, nest := ifelse(alt <= 2, "A", "B")]
#> id alt x1 x2 nest
#> <int> <int> <num> <num> <char>
#> 1: 1 1 1.3709584 1.33491259 A
#> 2: 1 2 -0.5646982 -0.86927176 A
#> 3: 1 3 0.3631284 0.05548695 B
#> 4: 1 4 0.6328626 0.04906691 B
#> 5: 2 1 0.4042683 -0.57835573 A
#> ---
#> 396: 99 4 1.0965134 -1.07287540 B
#> 397: 100 1 0.4420131 -2.29297143 A
#> 398: 100 2 0.2410163 -1.20720685 A
#> 399: 100 3 -0.2556077 0.11410943 B
#> 400: 100 4 0.9310329 -1.03329708 B
dt[, choice := 0L]
#> id alt x1 x2 nest choice
#> <int> <int> <num> <num> <char> <int>
#> 1: 1 1 1.3709584 1.33491259 A 0
#> 2: 1 2 -0.5646982 -0.86927176 A 0
#> 3: 1 3 0.3631284 0.05548695 B 0
#> 4: 1 4 0.6328626 0.04906691 B 0
#> 5: 2 1 0.4042683 -0.57835573 A 0
#> ---
#> 396: 99 4 1.0965134 -1.07287540 B 0
#> 397: 100 1 0.4420131 -2.29297143 A 0
#> 398: 100 2 0.2410163 -1.20720685 A 0
#> 399: 100 3 -0.2556077 0.11410943 B 0
#> 400: 100 4 0.9310329 -1.03329708 B 0
dt[, choice := sample(c(1L, rep(0L, J - 1))), by = id]
#> id alt x1 x2 nest choice
#> <int> <int> <num> <num> <char> <int>
#> 1: 1 1 1.3709584 1.33491259 A 1
#> 2: 1 2 -0.5646982 -0.86927176 A 0
#> 3: 1 3 0.3631284 0.05548695 B 0
#> 4: 1 4 0.6328626 0.04906691 B 0
#> 5: 2 1 0.4042683 -0.57835573 A 0
#> ---
#> 396: 99 4 1.0965134 -1.07287540 B 0
#> 397: 100 1 0.4420131 -2.29297143 A 0
#> 398: 100 2 0.2410163 -1.20720685 A 0
#> 399: 100 3 -0.2556077 0.11410943 B 1
#> 400: 100 4 0.9310329 -1.03329708 B 0
fit <- run_nestlogit(
data = dt, id_col = "id", alt_col = "alt", choice_col = "choice",
covariate_cols = c("x1", "x2"), nest_col = "nest"
)
#> Optimization run time 0h:0m:0s
summary(fit)
#> Nested Logit (NL) model
#>
#> Parameter Estimate Std.Error z-value Pr(>|z|)
#> x1 -0.135699 0.188113 -0.7214 4.71e-01
#> x2 0.295655 0.222668 1.3278 1.84e-01
#> Lambda_1 6.296863 23.550214 0.2674 7.89e-01
#> Lambda_2 1.640148 1.813470 0.9044 3.66e-01
#> ASC_2 -2.778324 10.488956 -0.2649 7.91e-01
#> ASC_3 2.033850 11.737696 0.1733 8.62e-01
#> ASC_4 1.520384 11.782281 0.1290 8.97e-01
#> ---
#> Signif. codes: '***' 0.001 '**' 0.01 '*' 0.05
#>
#> Std. Errors: Analytical Hessian
#> Log-likelihood: -134.492
#> AIC: 282.983 | BIC: 301.219
#> McFadden R2: 0.030 (adj: -0.021) | Hit rate: 0.380
#> N: 100 | Parameters: 7
#> Optimization time: 0 s
#> Convergence: 1 ( NLOPT_SUCCESS: Generic success return value. )
# }