| Title: | Hybrid Machine Learning and Random-Utility Workflow for Latent Class Multinomial Logit Model Specification |
|---|---|
| Description: | Implements the three-step workflow of Frings (2026, working paper) for specifying latent class multinomial logit (LCMNL) models. The maximum-likelihood multi-start is initialised from six clusterings of respondents' revealed-preference signatures (k-means, Gaussian mixture, hierarchical clustering with Ward, complete and average linkage, and partitioning around medoids). LCMNL models are estimated across a user-specified range of class counts, and a mixed multinomial logit (MMNL) benchmark, estimated with 'apollo', is reported alongside BIC, AIC, ICL and a classification-entropy diagnostic. For large samples the clustering starts are computed on a capped respondent subsample, and all starts are screened at a loose optimiser tolerance before the best is refined. Accepts long- or wide-format discrete-choice data with optional availability columns. |
| Authors: | Oliver Frings [aut, cre] |
| Maintainer: | Oliver Frings <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.10.0 |
| Built: | 2026-10-27 15:02:00 UTC |
| Source: | https://github.com/o-frings/klue |
Deletes the apollo_* objects that Apollo requires in the global environment, so a session can mix klue and Apollo runs.
cleanup_apollo()cleanup_apollo()
BFGS on the full parameter vector with analytic gradients. Bypasses Apollo entirely: LCMNL involves only discrete mixing.
estimate_lcmnl( database, C, start_betas = NULL, start_shares = NULL, dgp = DGP_DEFAULT, maxit = MAX_ITER, reltol = 1e-10, start_par = NULL, vcov = TRUE )estimate_lcmnl( database, C, start_betas = NULL, start_shares = NULL, dgp = DGP_DEFAULT, maxit = MAX_ITER, reltol = 1e-10, start_par = NULL, vcov = TRUE )
database |
Data frame in long format, sorted by respondent in blocks of
|
C |
Integer number of latent classes. |
start_betas |
Optional |
start_shares |
Optional length- |
dgp |
Data-generating-process specification list giving the design
dimensions ( |
maxit, reltol
|
BFGS iteration cap and relative tolerance. The defaults fit to full precision; the multistart screen passes looser values. |
start_par |
Optional full starting parameter vector (betas, ASCs, and
share deltas as one vector), used to warm-start from a previous fit.
Overrides |
vcov |
If |
A list with the fit. converged (logical) flags a successful
optimisation; C is the number of classes; LL the maximised
log-likelihood; BIC, AIC, and ICL the corresponding
information criteria (ICL_BIC is the entropy penalty
ICL - BIC); k the number of free parameters; betas a
C x n_beta matrix of estimated taste coefficients;
class_probs the length-C class shares; posteriors
the N x C matrix of posterior class-membership
probabilities; and par the full parameter vector (reusable as
start_par). When vcov = TRUE, vcov (inverse observed
information) and robust_vcov (sandwich estimator clustered on
respondent) give the covariance of par for any C; if the
observed information is rank-deficient both are set to NA,
singular is TRUE and aliased names the parameters
that are not separately identified (estimates, LL and class
assignment are unaffected, but k still counts every parameter, so
the information criteria are penalised for parameters the design cannot
identify). For
C = 1 the parameters are labelled b1..b{n_beta} (taste
coefficients, price last) and asc1..asc{n_asc}; for C >= 2
each class c contributes b1_class{c}..b{n_beta}_class{c} and
asc1_class{c}..asc{n_asc}_class{c}, followed by the C - 1
share parameters delta1..delta{C-1} (last class is the reference).
model_type is "MNL" when
C = 1 and "LCMNL" otherwise. A fit that hits maxit returns its
(finite) values with converged = FALSE; an optimiser error returns
the failure skeleton with LL = -Inf.
Direct-MLE LCMNL in which the class-membership probabilities depend on
respondent-level covariates, pi_{nc} = softmax_c(t(Z_n) gamma_c) with the
last class as reference (gamma_C = 0). The class-specific taste model
is identical to estimate_lcmnl; only the share model changes.
With no covariates this reduces exactly to the constant-share LCMNL.
estimate_lcmnl_cov( database, C, membership = character(0), start_betas = NULL, start_shares = NULL, dgp = DGP_DEFAULT, maxit = MAX_ITER, reltol = 1e-10, start_par = NULL, vcov = TRUE )estimate_lcmnl_cov( database, C, membership = character(0), start_betas = NULL, start_shares = NULL, dgp = DGP_DEFAULT, maxit = MAX_ITER, reltol = 1e-10, start_par = NULL, vcov = TRUE )
database |
Long-format choice data (as for |
C |
Integer number of latent classes. |
membership |
Character vector of covariate column names entering the class-membership model (an intercept is always included). Default none (recovers the constant-share model). |
start_betas, start_shares
|
Optional taste and share starting values; if
|
dgp, maxit, reltol, start_par, vcov
|
As in |
A list like estimate_lcmnl with, additionally, gamma
(a p x (C-1) matrix of membership coefficients, rows named by
Z's columns) and shares the N x C matrix of
respondent-level class probabilities (class_probs is their mean).
vcov/robust_vcov cover taste params then the membership
parameters {cov}_class{c}.
E-step: posterior class weights; M-step: shares + per-class weighted MNL
(warm-started at the class's current parameters). From identical starts,
EM and direct ML should reach the same optimum. C = 1 delegates to
estimate_lcmnl so the two estimators agree exactly there.
estimate_lcmnl_em( database, C, start_betas = NULL, start_shares = NULL, dgp = DGP_DEFAULT, max_em_iter = 500L, tol = 1e-06, verbose = FALSE )estimate_lcmnl_em( database, C, start_betas = NULL, start_shares = NULL, dgp = DGP_DEFAULT, max_em_iter = 500L, tol = 1e-06, verbose = FALSE )
database |
Data frame in long format, sorted by respondent in blocks of
|
C |
Integer number of latent classes. |
start_betas |
Optional |
start_shares |
Optional length- |
dgp |
Data-generating-process specification list giving the design
dimensions ( |
max_em_iter |
Maximum number of EM iterations. Default 500. |
tol |
Convergence tolerance on the change in log-likelihood between successive EM iterations. Default 1e-6. |
verbose |
If |
A list with the fit. converged (logical) flags a successful
run; C is the number of classes; LL the maximised
log-likelihood; BIC, AIC, and ICL the corresponding
information criteria (ICL_BIC is the entropy penalty
ICL - BIC); k the number of free parameters; betas a
C x n_beta matrix of estimated taste coefficients;
class_probs the length-C class shares; posteriors the
N x C matrix of posterior class-membership probabilities;
em_iters the number of EM iterations run; and estimator the
string "em". model_type is "MNL" when C = 1 and
"LCMNL" otherwise. A failed fit returns the same fields with
converged set to FALSE.
Starting taste coefficients and class shares for C classes from every clustering method in KLUE_CLUSTER_METHODS, as used by the multistart in klue_lcmnl.
get_all_starts( database, C, dgp = DGP_DEFAULT, feature_type = c("rp", "onehot"), cluster_cap = 2000L, screen = getOption("klue.screen", TRUE) )get_all_starts( database, C, dgp = DGP_DEFAULT, feature_type = c("rp", "onehot"), cluster_cap = 2000L, screen = getOption("klue.screen", TRUE) )
database |
Canonical wide database. |
C |
Number of latent classes. |
dgp |
DGP specification from |
feature_type |
Feature space for clustering: "rp" (revealed-preference signatures) or "onehot". |
cluster_cap |
Maximum respondents clustered (a fixed-seed subsample above it). |
screen |
See |
A list of starting values: betas (C x n_beta) and shares, or a list of such lists.
Random starts around the pooled-MNL solution, used in the initialisation ablations.
get_mnl_perturbation_starts( database, C, n_starts = 50L, jitter_sd = 0.5, seed = 1L, dgp = DGP_DEFAULT )get_mnl_perturbation_starts( database, C, n_starts = 50L, jitter_sd = 0.5, seed = 1L, dgp = DGP_DEFAULT )
database |
Canonical wide database. |
C |
Number of latent classes. |
n_starts |
Number of random starts. |
jitter_sd |
See |
seed |
Integer seed. |
dgp |
DGP specification from |
A list of starting values: betas (C x n_beta) and shares, or a list of such lists.
Class-specific MNL fits on random respondent partitions, used in the initialisation ablations.
get_random_partition_starts( database, C, n_starts = 50L, seed = 1L, dgp = DGP_DEFAULT )get_random_partition_starts( database, C, n_starts = 50L, seed = 1L, dgp = DGP_DEFAULT )
database |
Canonical wide database. |
C |
Number of latent classes. |
n_starts |
Number of random partitions. |
seed |
Integer seed. |
dgp |
DGP specification from |
A list of starting values: betas (C x n_beta) and shares, or a list of such lists.
Three calling conventions: (1) 'database =' canonical wide format;
(2) 'data =' + long-format column mapping; (3) 'data =' + wide-format
column mapping (both forwarded to klue_database). Loops over
'C_cands', optionally estimates the MMNL benchmarks, prints and writes
summary CSVs, and returns the full results list invisibly.
klue( database = NULL, data = NULL, format = c("auto", "long", "wide"), C_cands = 1:6, asc_map = NULL, run_mmnl = TRUE, run_mmnl_corr = FALSE, mmnl_opts = list(), attr_labels = NULL, output_prefix = "workflow", output_dir = NULL, write_csv = TRUE, verbose = TRUE, n_cores = 1L, ... )klue( database = NULL, data = NULL, format = c("auto", "long", "wide"), C_cands = 1:6, asc_map = NULL, run_mmnl = TRUE, run_mmnl_corr = FALSE, mmnl_opts = list(), attr_labels = NULL, output_prefix = "workflow", output_dir = NULL, write_csv = TRUE, verbose = TRUE, n_cores = 1L, ... )
database |
canonical wide-format data frame with columns ID, TASK, CHOICE plus attribute columns. Supply this or 'data', not both. |
data |
raw data frame passed to |
format |
one of "auto", "long", "wide": the layout of 'data', forwarded
to |
C_cands |
integer vector of class counts to estimate. Default 1:6. |
asc_map |
optional integer vector of length 'n_alternatives' mapping
each alternative to an ASC group (0 = reference / no ASC; alternatives
sharing a group share one ASC), forwarded to |
run_mmnl |
logical; if TRUE estimate the independent-normals MMNL benchmark. Default TRUE. |
run_mmnl_corr |
logical; if TRUE estimate the correlated-normals MMNL benchmark. Default FALSE. |
mmnl_opts |
named list of extra arguments forwarded to |
attr_labels |
character vector of length 'n_generic + 1' naming the attribute coefficients (the last entry is price). If NULL, taken from the database attribute or generated as x1, x2, ..., price. |
output_prefix |
character prefix for the written CSV file names. Default "workflow". |
output_dir |
directory for the written CSVs. If NULL, uses OUTPUT_DIR. |
write_csv |
logical; if TRUE write the summary, class-coefficient and model-comparison CSVs. Default TRUE. |
verbose |
logical; if TRUE print progress and result tables. Default TRUE. |
n_cores |
cores for the per-start LCMNL fits within each C (forwarded
to |
... |
column-mapping and scaling arguments forwarded to
|
Invisibly, a list with elements 'database', 'dgp', 'lcmnl' (the per-C fits), 'mmnl', 'mmnl_corr', 'summary', 'class_betas', 'comparison', 'best_C' (the BIC-best class count) and 'best_lcmnl' (the BIC-best fit).
'format = "auto"' infers: named-list 'attribute_cols' -> wide; 'alt_col' present -> long.
klue_database(data, format = c("auto", "long", "wide"), ...)klue_database(data, format = c("auto", "long", "wide"), ...)
data |
A data.frame, or a single file path to a '.dat' (whitespace-delimited, header) or '.csv' file to read. |
format |
One of "auto", "long", or "wide". With "auto", a named-list 'attribute_cols' selects the wide builder and an 'alt_col' argument selects the long builder. |
... |
Further arguments passed to [klue_database_long()] or [klue_database_wide()] according to the resolved format. |
A data.frame in the canonical wide format with columns 'ID', 'TASK', the generic attribute blocks 'x1_1..xN_J', the price columns 'price_1..price_J', and 'CHOICE' (the chosen alternative index in '1..J'). The last alternative is the reference. Attributes 'attr_labels', 'n_alternatives', and 'n_generic' are attached.
One row per (respondent, task, alternative). 'choice_format' is "indicator" (0/1 on the chosen row) or "alt_index" (chosen alt repeated on every row of the task). 'scalings' is a named list of divisors keyed by attribute/price column name; 'price_scaling' is a shortcut for the price column. Tasks where any alternative is unavailable (avail_col == 0) and respondents with fewer tasks than the panel maximum are dropped.
klue_database_long( data, id_col, task_col, alt_col, choice_col, attribute_cols, price_col, choice_format = c("indicator", "alt_index"), avail_col = NULL, keep_unavailable = FALSE, scalings = NULL, price_scaling = 1, covariate_cols = NULL, verbose = TRUE )klue_database_long( data, id_col, task_col, alt_col, choice_col, attribute_cols, price_col, choice_format = c("indicator", "alt_index"), avail_col = NULL, keep_unavailable = FALSE, scalings = NULL, price_scaling = 1, covariate_cols = NULL, verbose = TRUE )
data |
A data.frame, or a single file path to a '.dat' (whitespace-delimited, header) or '.csv' file to read. |
id_col |
Name of the respondent identifier column. |
task_col |
Name of the choice-task identifier column (unique within respondent). |
alt_col |
Name of the alternative identifier column within a task. |
choice_col |
Name of the choice column, interpreted per 'choice_format'. |
attribute_cols |
Character vector of generic attribute column names; each becomes the 'x*_*' block in the order supplied. |
price_col |
Length-one name of the price column. |
choice_format |
Either "indicator" (0/1, one chosen row per task) or "alt_index" (the chosen alternative index repeated on every row of the task). |
avail_col |
Optional name of an availability column (0/1). By default, tasks where not all alternatives are available are dropped. |
keep_unavailable |
If 'TRUE' (with 'avail_col' supplied), keep those tasks and emit per-alternative 'av_1..av_J' columns instead of dropping them; the estimator then masks unavailable alternatives out of each task's choice set. Default 'FALSE' (drop, the historical behaviour). |
scalings |
Optional named list of positive divisors keyed by attribute or price column name; matching columns are divided before use. |
price_scaling |
Positive divisor applied to the price column; shortcut for adding the price column to 'scalings'. |
covariate_cols |
Optional character vector of respondent-level columns
(constant within respondent, e.g. class-membership covariates for
|
verbose |
Logical; if 'TRUE', print drop counts and a build summary. |
A data.frame in the canonical wide format with columns 'ID', 'TASK', the generic attribute blocks 'x1_1..xN_J', the price columns 'price_1..price_J', 'CHOICE' (the chosen alternative index in '1..J') and any 'covariate_cols'. Respondents are numbered in the sorted order of 'id_col' (attribute 'ids' maps 'ID = k' back to the k-th sorted id) and tasks in the sorted order of 'task_col' within respondent. The last alternative is the reference. Attributes 'attr_labels' (attribute and price labels, suffixed by scaling where applicable), 'n_alternatives' (J), and 'n_generic' (number of generic attributes) are attached.
One row per (respondent, task). 'attribute_cols' is a named list; each entry is a length-J character vector of column names (NA = structural zero on that alternative). 'price_col' is a length-J vector; 'avail_col' optionally too. 'scalings' is keyed by attribute name or "price".
klue_database_wide( data, id_col, task_col = NULL, choice_col, attribute_cols = NULL, price_col = NULL, avail_col = NULL, keep_unavailable = FALSE, scalings = NULL, attributes = NULL, price = NULL, availability = NULL, verbose = TRUE )klue_database_wide( data, id_col, task_col = NULL, choice_col, attribute_cols = NULL, price_col = NULL, avail_col = NULL, keep_unavailable = FALSE, scalings = NULL, attributes = NULL, price = NULL, availability = NULL, verbose = TRUE )
data |
A data.frame, or a single file path to a '.dat' (whitespace-delimited, header) or '.csv' file to read. |
id_col |
Name of the respondent identifier column. |
task_col |
Optional name of the choice-task identifier column; if 'NULL', tasks are numbered sequentially within each respondent. |
choice_col |
Name of the column holding the chosen alternative index in '1..J'. |
attribute_cols |
Named list of length-J character vectors of column names, one vector per generic attribute; 'NA' marks a structural zero for that alternative. The list element names become attribute labels. |
price_col |
Length-J character vector of per-alternative price column names. |
avail_col |
Optional length-J character vector of per-alternative availability column names (0/1). By default, tasks where not all alternatives are available are dropped. |
keep_unavailable |
If 'TRUE' (with 'avail_col' supplied), keep those tasks and emit per-alternative 'av_1..av_J' columns instead of dropping them; the estimator then masks unavailable alternatives out of each task's choice set. Default 'FALSE' (drop, the historical behaviour). |
scalings |
Optional named list of positive divisors keyed by attribute name or "price"; matching columns are divided before use. |
attributes |
Deprecated alias for 'attribute_cols'. |
price |
Deprecated alias for 'price_col'. |
availability |
Deprecated alias for 'avail_col'. |
verbose |
Logical; if 'TRUE', print drop counts and a build summary. |
A data.frame in the canonical wide format with columns 'ID', 'TASK', the generic attribute blocks 'x1_1..xN_J', the price columns 'price_1..price_J', and 'CHOICE' (the chosen alternative index in '1..J'). The last alternative is the reference. Attributes 'attr_labels' (attribute and price labels, suffixed by scaling where applicable), 'n_alternatives' (J), and 'n_generic' (number of generic attributes) are attached.
'full = FALSE' (default): C = 1..2, no MMNL (~3 sec). 'full = TRUE': C = 1..6 + MMNL benchmark with 500 MLHS draws (a few minutes on one core).
klue_demo(full = FALSE, verbose = TRUE)klue_demo(full = FALSE, verbose = TRUE)
full |
logical; if TRUE estimate C = 1..6 with the MMNL benchmark, otherwise C = 1..2 without MMNL. Default FALSE. |
verbose |
logical; if TRUE print progress and result tables. Default TRUE. |
Invisibly, the list returned by klue for the Swiss
route-choice data.
MNL D-error of the task rows of a canonical
database (one row per choice task; ID and CHOICE are not
used), with the constants among the K = npc parameters (Ngene's
;con). The information sums over the rows, so the value matches
Ngene's D-error for one respondent answering every row.
klue_derror(database, dgp, par = NULL, draws = NULL, tol = 1e-10)klue_derror(database, dgp, par = NULL, draws = NULL, tol = 1e-10)
database |
Canonical database of the design's tasks. |
dgp |
Its dgp ( |
par |
Optional prior vector (taste coefficients, then constants); default zeros. |
draws |
Optional matrix of prior draws (one per row); the D-error is then their mean (Bayesian D-error). |
tol |
Relative eigenvalue tolerance of the rank. |
A list: derror, rank and full_rank of the
information at the first prior, and K.
One locally-D-efficient design is constructed for the whole study (the analyst designs around population means, NOT the unknown latent classes), then split into blocks. Each respondent answers one block, so all respondents in a block face identical cards. This is the realistic-DCE baseline. Requires the idefix package.
klue_design( n_cards = 48L, n_blocks = 4L, dgp = DGP_DEFAULT, priors = NULL, n_lvls = 4L, n_start = 8L, seed = 20240601L )klue_design( n_cards = 48L, n_blocks = 4L, dgp = DGP_DEFAULT, priors = NULL, n_lvls = 4L, n_start = 8L, seed = 20240601L )
n_cards |
Total number of choice cards (sets) in the design. Must be a
multiple of |
n_blocks |
Number of blocks the cards are split into. Each respondent answers one block. |
dgp |
Data-generating-process specification supplying
|
priors |
Prior coefficients: a numeric vector gives a locally
D-efficient design at that point; a matrix (rows = prior draws, columns =
coefficients) gives a Bayesian D-efficient design with the D-error
averaged over the draws. Defaults to |
n_lvls |
Number of attribute levels per attribute. |
n_start |
Number of random starting designs for the Modfed search. |
seed |
Integer seed for reproducible design construction and blocking. |
A list with elements cards (an n_cards by
n_alternatives by n_beta array of attribute values),
blocks (a list mapping each block to its card indices), T
(cards per block), n_cards, n_blocks, dgp, and
Derror (the D-error of the chosen design: Bayesian when
priors is a matrix of draws, local otherwise).
Builds the problem-dimension specification shared by the estimators, simulators, and study drivers, so they work with a variable number of generic attributes and alternatives.
klue_dgp( n_generic = 4, n_alternatives = 3, asc_map = NULL, labels = NULL, asc_labels = NULL, common = NULL )klue_dgp( n_generic = 4, n_alternatives = 3, asc_map = NULL, labels = NULL, asc_labels = NULL, common = NULL )
n_generic |
number of generic attributes (the price attribute is added on top of these). |
n_alternatives |
number of alternatives per choice task; the last alternative is the reference (no ASC). |
asc_map |
optional integer vector of length |
labels |
optional names of the |
asc_labels |
optional names of the |
common |
optional coefficients shared by all latent classes, as labels
or as positions in the per-class vector (taste coefficients, then
constants). A latent class fit then estimates one value for each, and its
|
A named list with n_generic, n_alternatives,
n_beta (generic + price), n_asc (number of ASC groups),
npc (parameters per class), asc_map, beta_bar
(population-mean coefficients), attr_names, price_idx,
par_labels (the per-class parameter names) and common
(positions of the common coefficients).
Returns an N x npc matrix of coefficients (taste
coefficients, then constants, named by label) for
klue_simulate_choices: the MNL vector repeated, or for a
latent class fit each row the coefficients of a class drawn with the class
shares (common coefficients share their one value). Uses the caller's RNG;
the drawn classes are in attr(, "class_draw").
klue_draw_betas(fit, N)klue_draw_betas(fit, N)
fit |
An MNL or constant-share LCMNL klue fit. |
N |
Number of respondents. |
95%-by-default CI for . Returns NA bounds when
the denominator is not significantly different from zero (unbounded CI).
klue_fieller(fit, num, den, level = 0.95, robust = TRUE)klue_fieller(fit, num, den, level = 0.95, robust = TRUE)
fit |
A klue fit. |
num, den
|
Named weight vectors for the numerator and denominator, or
functions of the parameter vector (a generalised Fieller interval from
their delta-method covariance), e.g. from |
level |
Confidence level. Default |
robust |
Use the cluster-robust covariance (default |
Named vector: ratio, lo, hi.
For C = 1 (MNL) a single run suffices; for C >= 2 the model is estimated
from all six clustering starts and the best log-likelihood wins. With the
"ml" estimator the starts are screened at a loose tolerance
(maxit = 200, reltol = 1e-6; fits hitting the cap still
count) and only the winner is polished to full precision, warm-started
from its own solution. Set screen = FALSE (or session-wide
options(klue.screen = FALSE)) to fit every start at full precision
with no polish step – the pre-0.9.1 code path, kept for exact
reproduction of results produced with it. Each start logs its LL and
elapsed time via message().
klue_lcmnl( database, C, dgp = DGP_DEFAULT, estimator = c("ml", "em"), feature_type = c("rp", "onehot"), n_cores = 1L, screen = getOption("klue.screen", TRUE), clean = FALSE, maxit = MAX_ITER, reltol = 1e-10, cluster_cap = 2000L )klue_lcmnl( database, C, dgp = DGP_DEFAULT, estimator = c("ml", "em"), feature_type = c("rp", "onehot"), n_cores = 1L, screen = getOption("klue.screen", TRUE), clean = FALSE, maxit = MAX_ITER, reltol = 1e-10, cluster_cap = 2000L )
database |
Data frame in long format, sorted by respondent in blocks of
|
C |
Integer number of latent classes. |
dgp |
Data-generating-process specification list giving the design
dimensions ( |
estimator |
"ml" (direct BFGS, default) or "em". |
feature_type |
"rp" (default) or "onehot" clustering features. |
n_cores |
number of cores for the six per-start fits. Default 1
(sequential). With |
screen |
logical; the 0.9.1 fast-screening behaviour (default). With
the |
clean |
logical; fit every start at full precision with its covariance
and return the highest-LL start whose fit has not |
maxit, reltol
|
BFGS settings of the full-precision fits. |
cluster_cap |
maximum respondents clustered for the starts (see
|
The best-fitting per-start result, a list with the same fields as
the chosen estimator (estimate_lcmnl for "ml",
estimate_lcmnl_em for "em"): converged, C,
LL, BIC, AIC, ICL (and ICL_BIC),
k, betas, class_probs, posteriors, and for the
EM estimator em_iters and estimator. Two extra fields are
added: best_method, the name of the winning clustering start, and
method_results, a named list of the individual fits from every
start. If no start converges, the failure result is returned with
converged = FALSE and best_method = NA.
Linear combination of coefficients from a klue fit
klue_lincom(fit, weights, robust = TRUE)klue_lincom(fit, weights, robust = TRUE)
fit |
A klue fit (from |
weights |
Named numeric vector |
robust |
Use the cluster-robust covariance (default |
Named vector: estimate, se, z, two-sided p.
Returns function(par) giving the share-weighted mean of a labelled
coefficient over the latent classes, (the
coefficient itself in an MNL). Pass it to klue_nlcom, or as
numerator and denominator to klue_fieller for a ratio of means.
klue_mean_fn(fit, label)klue_mean_fn(fit, label)
fit |
An MNL or constant-share LCMNL klue fit. |
label |
Coefficient label. |
Estimates a mixed logit with Apollo the way Apollo's own example scripts
do: random coefficients with
unconstrained, a negative log-normal price, ‘apollo_estimate' at Apollo’s
default estimation settings, and convergence as Apollo reports it. The
departures from the examples (pooled-MNL starts, zero starting
correlations, 3000 MLHS draws, BIC on respondents, and utilities measured
from the chosen alternative on data with availability columns) are listed
in the source file's header.
By default every generic attribute is a random normal, the price a negative
log-normal, and the constants fixed; 'random' and 'price' change that.
Correlated flavour ('correlation = TRUE'): a full lower-triangular Cholesky
covariance over the random parameters, started from the independent
estimates (Apollo's 'apollo_readBeta' step: the same means, the independent
standard deviations on the diagonal, zero correlations).
klue_mmnl( database, correlation = FALSE, n_draws = NULL, draws_type = NULL, estimation_routine = NULL, n_cores = NULL, quiet = NULL, start = c("informed", "zero", "sign"), random = NULL, price = c("lognormal", "normal", "fixed"), warm_start = NULL, dgp = DGP_DEFAULT, memory_saver = NULL, n_draws_stage1 = NULL, mu_price_bounds = NULL, sigma_price_bounds = NULL ) klue_mmnl_corr(database, ...)klue_mmnl( database, correlation = FALSE, n_draws = NULL, draws_type = NULL, estimation_routine = NULL, n_cores = NULL, quiet = NULL, start = c("informed", "zero", "sign"), random = NULL, price = c("lognormal", "normal", "fixed"), warm_start = NULL, dgp = DGP_DEFAULT, memory_saver = NULL, n_draws_stage1 = NULL, mu_price_bounds = NULL, sigma_price_bounds = NULL ) klue_mmnl_corr(database, ...)
database |
Data frame in klue's canonical wide format (one row per task) with an 'ID' column and the attribute and choice columns expected by the data-generating process. |
correlation |
Logical; if 'TRUE', estimate the correlated specification with a full lower-triangular Cholesky covariance instead of independent normals. |
n_draws |
Number of inter-individual draws. 'NULL' uses the package default. |
draws_type |
Apollo inter-draws type (for example Halton or MLHS). 'NULL' uses the package default. |
estimation_routine |
Apollo estimation routine passed to ‘apollo_estimate'. 'NULL' uses the package default (Apollo’s default, BGW). |
n_cores |
Number of cores for Apollo. 'NULL' uses the package default (Apollo's default, 1). |
quiet |
Logical; if 'TRUE', redirect Apollo output to a temporary log file whose tail is attached to a failing result. 'NULL' uses the package default. |
start |
Starting-value scheme. '"informed"' (default) starts the
independent model from the pooled MNL estimates (means, fixed
coefficients and constants; a log-normal price at
|
random |
Character vector naming the random parameters among 'x1..xN', 'price' and 'asc1..ascK', where 'ascK' indexes the ASC groups of 'dgp$asc_map' (with the default map, one per non-reference alternative). 'NULL' (default) makes every generic attribute and the price random and the constants fixed. Parameters not named are fixed coefficients. Random constants are normal, with the reference alternative's constant fixed at zero, so an independent random-constant model depends on which alternative is the reference. |
price |
Distribution of a random price coefficient: '"lognormal"' (default; negative log-normal), '"normal"', or '"fixed"' (the price is not random, whatever 'random' says by default). |
warm_start |
Optional earlier 'klue_mmnl' fit (klue >= 0.10.0) of the same data, 'random' set and 'price' distribution to start from. An independent fit given to a correlated call is mapped to the point where the two models coincide (same means, its standard deviations on the Cholesky diagonal, zero correlations), so with the same draws the correlated fit cannot end below it; the result's 'nested_ok' reports whether it did not. A fit of the same flavour is copied by name. |
dgp |
Data-generating-process specification giving the number of alternatives, generic attributes, parameters and the ASC groups. |
memory_saver |
Logical; Apollo's 'apollo_control$memorySaver'. 'TRUE' computes the analytic gradient in chunks of about two respondents, which cuts its memory (about one observations-by-draws array per parameter) without changing the estimates. ‘NULL' uses the package default (Apollo’s default, 'FALSE'; set 'options(klue.mmnl.memory_saver = TRUE)' or the environment variable 'KLUE_MMNL_MEMORY_SAVER=TRUE' to change it). |
n_draws_stage1, mu_price_bounds, sigma_price_bounds
|
Deprecated and ignored (with a warning). Since klue 0.10.0 there is no coarse-draw first stage, and Apollo 0.3.5 has no 'bounds' setting, so the price box of earlier versions was never applied. |
... |
For |
A list describing the fit. ‘converged' is Apollo’s ‘successfulEstimation'. On success: the log-likelihood 'LL' (Apollo’s final log-likelihood), information criteria 'BIC' and 'AIC' (with 'N' = respondents, as for the LCMNL; Apollo's own BIC, on observations, is 'BIC_apollo'), the number of free parameters 'k', 'reason = "ok"', the resolved 'settings', Apollo's status ('apollo_status': 'successfulEstimation', 'code', 'message', 'nIter'), the starting values 'start_values' and their source 'start_used', the full estimate vector 'par' with its classical and respondent-clustered covariances ‘vcov' and 'robust_vcov' (Apollo’s 'varcov' and 'robvarcov'; all 'NA' when Apollo could not invert the Hessian), the resolved 'random' set and 'price' distribution, 'sd_scale = "linear"', and, for the independent specification, the means 'mu' and standard deviations 'sigma = |sigma_p|' of the random parameters (for a log-normal price, of the underlying normal). A correlated fit that fitted its own independent start also returns it as 'independent_fit'. On failure: 'converged = FALSE' with 'LL', 'BIC', 'AIC', and 'k' set to non-informative values, a ‘reason' string, Apollo’s status and the estimates where Apollo returned them ('LL_at_stop', 'par'), the 'independent_fit' where there was one, and the Apollo log tail and path when 'quiet' is 'TRUE'.
Side effects: during estimation the Apollo objects live in the global environment, as Apollo requires; any 'apollo_*' objects the caller had there are restored afterwards, and so is the random-number stream, which Apollo reseeds when it makes its draws.
Returns the active MMNL defaults as a named list. Values can be overridden
per-call (arguments to klue_mmnl / klue) or globally via
options() entries klue.mmnl.<name>.
klue_mmnl_defaults()klue_mmnl_defaults()
A named list of the currently active defaults.
Delta-method inference on a function of a klue fit's parameters
klue_nlcom(fit, fn, robust = TRUE, level = 0.95)klue_nlcom(fit, fn, robust = TRUE, level = 0.95)
fit |
A klue fit carrying |
fn |
Function of the full parameter vector returning one number, e.g.
from |
robust |
Use the cluster-robust covariance (default |
level |
Confidence level of |
Named vector: estimate, se, z, two-sided
p, lo, hi. The gradient is a central difference with
step 1e-6 * max(|par_i|, 1).
Resolves a coefficient label (see the labels of klue_dgp)
to the name it carries in fit$par: the label itself in an MNL, and
<label>_class<c> in a latent class fit. A coefficient common to all
classes resolves to its class-1 entry when class is not given (every
class holds the same value). Use the result as weight names in
klue_lincom, klue_wtp and the other tests.
klue_par(fit, label, class = NULL)klue_par(fit, label, class = NULL)
fit |
A klue fit. |
label |
Coefficient label. |
class |
Optional class number(s) for a latent class fit. |
Character vector of parameter names.
Returns the n_obs x J matrix of choice probabilities of every
task row of database: the MNL probabilities, or for a latent class
fit their mixture over the classes with the class shares.
klue_predict(fit, database, dgp)klue_predict(fit, database, dgp)
fit |
An MNL or constant-share LCMNL klue fit. |
database |
Canonical database ( |
dgp |
The dgp of the fit. |
Fits the same model class to database, starting from the fit's
estimates matched by label: an MNL, or a constant-share LCMNL at
fit$C (with the common coefficients of dgp), or with
membership the concomitant model at fit$C. Labels new to
dgp start at 0, labels it drops are ignored, and start
overrides any start value. A common coefficient starts at the mean of its
class values.
klue_refit( fit, database, dgp, start = NULL, multistart = FALSE, membership = NULL, maxit = MAX_ITER, reltol = 1e-10, n_cores = 1L )klue_refit( fit, database, dgp, start = NULL, multistart = FALSE, membership = NULL, maxit = MAX_ITER, reltol = 1e-10, n_cores = 1L )
fit |
An MNL or constant-share LCMNL klue fit. |
database |
Canonical database. |
dgp |
The dgp of the model to fit ( |
start |
Optional named start values: full parameter names, or labels (set in every class). |
multistart |
Latent class only: also run
|
membership |
Optional respondent-level covariate columns: fit the
concomitant model ( |
maxit, reltol
|
BFGS settings. |
n_cores |
Cores of the multistart. |
The fit, with failed.
One entry point for the plain DGP and the concomitant-covariate DGP
(covariates = TRUE; class membership driven by Z1 ~ N(0,1) and a
binary Z2). With design from klue_design(), respondents share
their block's cards; otherwise attributes are drawn fresh per row,
optionally correlated via attr_corr.
klue_simulate( N_per_class = 150, T_tasks = 20, true_K = 2, separation = 1, heterogeneity = 0.25, seed = 12345, class_proportions = NULL, dgp = DGP_DEFAULT, sep_profile = NULL, attr_corr = NULL, design = NULL, seg_scale = NULL, covariates = FALSE, covariate_strength = 1 )klue_simulate( N_per_class = 150, T_tasks = 20, true_K = 2, separation = 1, heterogeneity = 0.25, seed = 12345, class_proportions = NULL, dgp = DGP_DEFAULT, sep_profile = NULL, attr_corr = NULL, design = NULL, seg_scale = NULL, covariates = FALSE, covariate_strength = 1 )
N_per_class |
Number of respondents per latent class. |
T_tasks |
Number of choice tasks per respondent. Overridden by the
block size when |
true_K |
Number of latent classes. |
separation |
Scalar controlling the distance of class means from the
grand mean |
heterogeneity |
Within-class standard deviation of the individual coefficients. |
seed |
Integer seed for reproducible simulation. |
class_proportions |
Optional numeric vector of class shares summing to
one. When |
dgp |
Data-generating-process specification supplying |
sep_profile |
Optional numeric vector of per-attribute separation
weights. When |
attr_corr |
Optional attribute correlation: |
design |
Optional blocked design from |
seg_scale |
Optional per-class scale (recycled to length
|
covariates |
Logical; when |
covariate_strength |
Scalar scaling the covariate effect on class
membership when |
A list with elements database (the simulated panel with a
CHOICE column), true_betas, true_class,
individual_betas, N, T, K, and dgp;
when covariates = TRUE it also contains Z1 and Z2
(and adds these columns to database).
Draws type-1 extreme-value choices for every (respondent, task) row of a
canonical wide database from the utilities . There is
no separate ASC block: alternative-specific constants and framing shifts are
carried as indicator attributes of the database.
klue_simulate_choices(database, betas, dgp)klue_simulate_choices(database, betas, dgp)
database |
Canonical wide database (e.g. from
|
betas |
Numeric vector of length |
dgp |
Data-generating-process specification giving
|
The database with a simulated CHOICE column.
Clusters respondents by their choice features, then fits a class-wise MNL to produce starting coefficients and class shares for the latent-class estimator.
klue_starts( database, C, method = "kmeans", features = NULL, feature_type = c("rp", "onehot"), dgp = DGP_DEFAULT, cluster_cap = 2000L, screen = getOption("klue.screen", TRUE) )klue_starts( database, C, method = "kmeans", features = NULL, feature_type = c("rp", "onehot"), dgp = DGP_DEFAULT, cluster_cap = 2000L, screen = getOption("klue.screen", TRUE) )
database |
choice data frame with respondent ID, CHOICE, and attribute columns, as consumed by the estimator. |
C |
number of latent classes (number of clusters to form). With C = 1 the data are treated as a single class and no clustering is performed. |
method |
clustering method, one of "kmeans", "gmm", "hc_ward", "hc_complete", "hc_average", "pam". |
features |
optional pre-computed N-by-p feature matrix. When NULL, the features are computed from 'database' according to 'feature_type'. |
feature_type |
"rp" (revealed-preference contrasts, the default) or "onehot" (choice indicators; the ablation arm). |
dgp |
data-generating-process specification supplying dimensions such as the number of alternatives, coefficients, and generic coefficients. |
cluster_cap |
maximum number of respondents used for clustering and the cluster-wise MNL start fits; larger samples are subsampled with a fixed seed. Ignored when 'features' is supplied. |
screen |
logical; fit the cluster-wise MNLs at a loose tolerance,
keeping non-converged finite-LL fits (the default, since 0.9.1).
|
A list with 'betas' (a C-by-n_beta matrix of class-wise starting coefficients) and 'shares' (a length-C vector of class shares), or NULL if the chosen clustering method failed to return labels.
Tests whether lies within margin. A small
p_tost rejects non-equivalence (i.e. supports equivalence).
klue_tost(fit, weights, margin, robust = TRUE)klue_tost(fit, weights, margin, robust = TRUE)
fit |
A klue fit. |
weights |
Named weight vector defining the contrast |
margin |
Positive equivalence margin. |
robust |
Use the cluster-robust covariance (default |
Named vector: estimate, se, margin, p_tost.
Joint Wald test that a set of coefficients equals a value
klue_wald(fit, terms = NULL, value = 0, robust = TRUE, fn = NULL, tol = 1e-08)klue_wald(fit, terms = NULL, value = 0, robust = TRUE, fn = NULL, tol = 1e-08)
fit |
A klue fit. |
terms |
Character vector of parameter names to test jointly. |
value |
Null value(s) (recycled). Default |
robust |
Use the cluster-robust covariance (default |
fn |
Optional function of the parameter vector returning the vector
tested against |
tol |
Relative eigenvalue tolerance of the rank (with |
Named vector: chisq, df, p.
Returns with a Delta-method
standard error and 95% interval. For a plain WTP pass num = c(attr = 1),
den = c(cost = 1).
klue_wtp(fit, num, den, scale = 1, robust = TRUE)klue_wtp(fit, num, den, scale = 1, robust = TRUE)
fit |
A klue fit. |
num, den
|
Named weight vectors for the numerator and denominator. |
scale |
Multiplier (e.g. currency scaling). Default |
robust |
Use the cluster-robust covariance (default |
Named vector: wtp, se, lo, hi.
Returns function(par) giving :
in an MNL the ratio, in an LCMNL its share-weighted mean over the classes
(the population mean), or one class's ratio with class. Common
coefficients enter every class with the same value.
klue_wtp_fn(fit, num, den = NULL, scale = 1, class = NULL)klue_wtp_fn(fit, num, den = NULL, scale = 1, class = NULL)
fit |
An MNL or constant-share LCMNL klue fit. |
num |
Named weights over coefficient labels (constants included). |
den |
Label of the denominator; default the fit's price coefficient. |
scale |
Multiplier (e.g. currency units). Default |
class |
Optional class number for that class's ratio. |