Latent-class conditional logit
The headline estimator: a finite mixture of conditional logits, fit by expectation-maximization, with optional class-membership demographic regression. Class-specific taste vectors are recovered via maximum likelihood at each M-step; class probabilities are updated either as aggregate shares or, when demographics are present, using a fractional-response multinomial logit model.
Most users reach this estimator through the declarative LCLSpec + lcl.fit workflow; the class below is what lcl.fit constructs and fits under the hood, and it can also be driven directly.
Model
lcl.latent_class_conditional_logit.LatentClassConditionalLogit(num_classes=5, numeraire=None, *, spec=None, numeraire_min_abs=DEFAULT_NEGATIVE_MIN_ABS)
Bases: ChoiceModel
Specification and estimation for latent-class conditional logit models.
This class provides the interface for defining and fitting a latent-class
conditional logit model using an Expectation-Maximization (EM) algorithm. It
inherits from the abstract base class ChoiceModel and manages the data
ingestion, initialization, and iterative optimization of latent taste
parameters and class membership probabilities.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_classes
|
int
|
The number of discrete latent classes to estimate. |
5
|
numeraire
|
str | None
|
The name of the variable to be used as the numeraire (e.g., price or cost). If specified, its taste parameter is mathematically constrained to be strictly negative across all latent classes via a softplus transformation to ensure theoretically consistent willingness-to-pay calculations. |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
num_classes |
int
|
The number of discrete latent classes. |
numeraire |
str | None
|
The name of the numeraire variable. |
numeraire_idx |
int | None
|
The column index of the numeraire variable in the expanded design matrix,
resolved during the |
num_vars |
int
|
The total number of alternative-specific variables (taste parameters),
resolved during the |
num_dem_vars |
int
|
The total number of demographic variables, resolved during the |
Create an unfitted latent-class conditional-logit model specification.
Source code in src/lcl/latent_class_conditional_logit.py
fit(data, alts_col=None, cases_col=None, panels_col=None, formula=None, utility_formula=None, membership_formula=None, choice_col=None, case_varnames=None, dem_varnames=None, dems_data=None, em_alg_config=None, mle_config=None, error_config=None, fit_options=None, optimization_options=None, inference=None, diagnostics=None, progress_callback=None)
Fit the latent-class conditional logit model using an EM algorithm.
This method ingests raw data, translates it into strictly contiguous, zero-indexed JAX arrays (PyTrees), and executes the hardware-accelerated EM optimization routine.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Any
|
The main dataset containing choice situations. Accepts a Polars DataFrame, Pandas DataFrame, or dictionary of arrays. |
required |
alts_col
|
str
|
The name of the column identifying specific alternatives within a choice situation. |
None
|
cases_col
|
str
|
The name of the column grouping observations into distinct choice situations. |
None
|
panels_col
|
str
|
The name of the column mapping choice situations to specific decision-makers (panels). |
None
|
formula
|
str | None
|
Backward-compatible combined Formulaic string, for example
|
None
|
utility_formula
|
str | None
|
Formulaic string for the alternative-specific utility specification.
Examples include |
None
|
membership_formula
|
str | None
|
Right-hand-side Formulaic string for class-membership demographics,
for example |
None
|
choice_col
|
str | None
|
The name of the boolean or binary column indicating chosen alternatives.
Required if |
None
|
case_varnames
|
Sequence[str] | None
|
A list of alternative-specific variables to include in the utility
specification. Required if |
None
|
dem_varnames
|
Sequence[str] | None
|
A list of demographic variables used to predict latent class membership. |
None
|
dems_data
|
Any | None
|
An optional, separate panel-level dataset containing demographics. If
provided, it will be merged with the main |
None
|
em_alg_config
|
:class:`~lcl._struct.EMAlgConfig`
|
A dataclass (PyTree) containing configuration options for the overall EM algorithm (e.g., maximum iterations, tolerance, hardware distribution). |
EMAlgConfig()
|
mle_config
|
:class:`~lcl._struct.MleConfig`
|
A dataclass (PyTree) containing optimization settings for the M-step's internal L-BFGS solver. |
MleConfig()
|
Returns:
| Type | Description |
|---|---|
class:`~lcl._results.LCLResults`
|
A container holding the estimated parameters, optimization metadata, information criteria, and methods for inference (standard errors, predictions). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a |
Source code in src/lcl/latent_class_conditional_logit.py
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 | |
Results
lcl._results.LCLResults(model_spec, em_vars, estimation_data, em_recursion, em_alg_config, error_config, estim_time_sec, diagnostics_config=None, em_history=None, optimization_history=None)
Post-estimation results and inference container.
Computes robust sandwich covariance matrices (clustered at the decision-maker level) and handles the extraction of population-level moments via the Delta Method.
Attributes:
| Name | Type | Description |
|---|---|---|
cov_matrix |
Float64[Array, 'all_params all_params']
|
Robust cluster-adjusted covariance matrix, strictly aligned with the Stata
finite-sample correction multiplier :math: |
caic |
float
|
Consistent Akaike Information Criterion (Bozdogan, 1987). |
bic |
float
|
Bayesian Information Criterion (Schwarz, 1978). |
adjusted_bic |
float
|
Sample-size adjusted BIC (Sclove, 1987). |
Build a latent-class results object and compute inference artifacts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_spec
|
Any
|
Fitted model specification. Kept broad to avoid a runtime circular import
with :class: |
required |
em_vars
|
:class:`~lcl._struct.EMVars`
|
Final EM state containing parameters, probabilities, and log likelihood. |
required |
estimation_data
|
:class:`~lcl._struct.Data`
|
Encoded estimation data. |
required |
em_recursion
|
int
|
Number of EM recursions completed before termination. |
required |
em_alg_config
|
:class:`~lcl._struct.EMAlgConfig`
|
EM convergence and iteration configuration. |
required |
error_config
|
:class:`~lcl._struct.ErrorConfig` | None
|
Covariance and standard-error configuration. |
required |
estim_time_sec
|
float
|
Wall-clock estimation time in seconds. |
required |
diagnostics_config
|
:class:`~lcl._struct.DiagnosticsOptions` | None
|
Thresholds and switches for public diagnostics. |
None
|
em_history
|
list[dict[str, Any]] | None
|
EM log-likelihood and class-share history. |
None
|
optimization_history
|
list[dict[str, Any]] | None
|
Final class-level M-step diagnostics. |
None
|
Source code in src/lcl/_results.py
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 | |
__repr__()
Return a compact, human-readable summary of fit quality.
Source code in src/lcl/_results.py
audit_report()
Return a text audit report for replication materials.
Source code in src/lcl/_results.py
beta_summary()
Return population-level coefficient moments with Delta-method SEs.
Returns:
| Type | Description |
|---|---|
DataFrame
|
Variables, mean coefficients, standard deviations across classes, Delta-method standard errors, and class-specific extrema. |
Source code in src/lcl/_results.py
class_coefficients()
Return class-specific structural coefficients.
Returns:
| Type | Description |
|---|---|
DataFrame
|
Long-format table with one row per variable and latent class. |
Source code in src/lcl/_results.py
class_shares()
Return aggregate latent-class shares.
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per latent class with aggregate class share and effective panel mass. |
Source code in src/lcl/_results.py
convergence_report()
Return a compact convergence and diagnostic report.
Source code in src/lcl/_results.py
diagnose()
diagnostics()
Return structured model diagnostics.
Source code in src/lcl/_results.py
654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 | |
predict(X=None, alts=None, cases=None, panels=None, dems=None, past_choices=None, data=None, dems_data=None, past_choices_dems_data=None)
Generate out-of-sample latent-class predictions.
Prediction can be requested either with raw tabular data, which is encoded
using the fitted model specification, or with already-constructed arrays.
When historical choices are supplied through past_choices, class
membership probabilities are updated with Bayes' rule before computing
counterfactual choice probabilities, consumer surplus, and willingness to pay.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ArrayLike | None
|
Alternative-specific design matrix for array-style prediction. Ignored
when |
None
|
alts
|
ArrayLike | None
|
Alternative identifiers aligned to rows of |
None
|
cases
|
ArrayLike | None
|
Choice-situation identifiers aligned to rows of |
None
|
panels
|
ArrayLike | None
|
Decision-maker identifiers aligned to rows of |
None
|
dems
|
ArrayLike | None
|
Panel-level demographics for array-style prediction. |
None
|
past_choices
|
PastChoicesData or tabular data
|
Historical choices used to condition latent-class membership probabilities.
Pass a :class: |
None
|
data
|
object | None
|
Long-format prediction data. If provided, the fitted encoder parses this data using the original empirical specification. |
None
|
dems_data
|
object | None
|
Optional panel-level demographics to merge into |
None
|
past_choices_dems_data
|
object | None
|
Optional panel-level demographics to merge into tabular |
None
|
Returns:
| Type | Description |
|---|---|
class:`~lcl._prediction.LCLPrediction`
|
Prediction results, including choice probabilities, consumer surplus, panel-level WTP values, and the class probabilities used for prediction. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If required prediction identifiers are missing, if fitted latent-class
parameters are unavailable, or if |
Source code in src/lcl/_results.py
806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 | |
spec_summary()
Return a human-readable model specification summary.
Source code in src/lcl/_results.py
summarize(num_decimals=3)
summarize_betas(header=('Variable', "Means (\\beta's)", "Standard deviations (\\sigma's)"), num_decimals=3)
Print and return population-level moments with Delta-method SEs.
Source code in src/lcl/_results.py
Diagnostics
lcl._diagnostics.LCLDiagnostics(frame)
Structured diagnostics for a fitted latent-class model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frame
|
DataFrame
|
Diagnostic checks with at least |
required |
Store diagnostic checks.
Source code in src/lcl/_diagnostics.py
__repr__()
print()
Print a compact diagnostics table.
Prediction and counterfactuals
lcl._prediction.LCLPrediction(predicted_probs_df, surplus_df, wtp_alt_vars_by_panel_df, predict_data, results, class_probs_by_panel=None, class_probabilities_source='prior', partition_data_df=None)
Container for counterfactual inference, consumer surplus, and willingness-to-pay (WTP).
Provides methods to analyze decision-maker behavior under new choice sets or policy changes. Utilizes the Delta Method to compute rigorous analytical standard errors for non-linear combinations of parameters (e.g., marginal WTP) across dynamically defined demographic partitions.
Attributes:
| Name | Type | Description |
|---|---|---|
predicted_probs |
DataFrame
|
DataFrame of out-of-sample choice probabilities for each alternative. |
surplus |
DataFrame
|
DataFrame of expected consumer surplus (inclusive value) per choice situation. |
wtp_alt_vars_by_panel |
DataFrame
|
DataFrame of expected marginal WTP for each alternative-specific characteristic, calculated at the individual decision-maker level. |
predict_data |
:class:`~lcl._struct.Data`
|
The parsed design matrices corresponding to the counterfactual scenarios. |
results |
:class:`~lcl._results.LCLResults`
|
Reference to the parent estimation results, required for Delta Method covariance calculations and parameter unpacking. |
class_probs_by_panel |
Array | None
|
Posterior (or prior) probabilities of latent class membership used to generate these predictions. If historical choices were provided during prediction, these represent the Bayesian-updated posteriors. |
partition_data |
DataFrame | None
|
Panel-level columns from raw prediction data that are constant within panel and can be used for WTP partitions. |
Store prediction outputs and references needed for post-processing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
predicted_probs_df
|
DataFrame
|
Long-format alternative choice probabilities. |
required |
surplus_df
|
DataFrame
|
Case-level consumer surplus estimates. |
required |
wtp_alt_vars_by_panel_df
|
DataFrame
|
Panel-level marginal WTP values for non-numeraire variables. |
required |
predict_data
|
:class:`~lcl._struct.Data`
|
Encoded data used to generate the predictions. |
required |
results
|
Any
|
Parent results object. Kept broad to support both latent-class and conditional-logit result containers without a circular import. |
required |
class_probs_by_panel
|
Float64[Array, 'panels classes'] | None
|
Class probabilities used to marginalize class-specific predictions. |
None
|
class_probabilities_source
|
str
|
|
"prior"
|
partition_data_df
|
DataFrame | None
|
Panel-level raw prediction columns available for WTP partitions. |
None
|
Source code in src/lcl/_prediction.py
compute_wtp(*wtp_requests, partition_data=None, panel_col='panels', num_decimals=4, class_probabilities='stored', se='delta')
Compute the Marginal Willingness-to-Pay (WTP) across demographic partitions.
Evaluates the ratio of the target parameter to the negative cost parameter (marginal utility of income) for dynamically defined subsets of decision-makers. Outputs formatted LaTeX and terminal summary tables, including analytical standard errors derived via the Delta Method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*wtp_requests
|
WTPRequest | Iterable[WTPRequest]
|
One or more configuration objects specifying the target variable, the demographic partitioning variable, and the binning strategy (e.g., quintiles, categorical, custom breaks, or a dummy-coded categorical factor). |
()
|
partition_data
|
object | None
|
Optional panel-level or long-format tabular data containing partitioning variables that were not included in the fitted class-membership specification. Values must be constant within each panel. |
None
|
panel_col
|
str
|
Panel identifier column in |
"panels"
|
num_decimals
|
int
|
Number of decimal places used in printed WTP tables. |
4
|
class_probabilities
|
(stored, prior, posterior)
|
Class-membership probabilities used for WTP/tradeoff point estimates.
|
"stored"
|
se
|
(delta, none)
|
Standard-error method. Delta-method standard errors are available for
prior class probabilities. Posterior-updated WTP through
|
"delta"
|
Returns:
| Type | Description |
|---|---|
dict[str, DataFrame]
|
Summary tables keyed by their printed titles. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the parent model was not estimated with a specified numeraire constraint. |
Source code in src/lcl/_prediction.py
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 | |
denominator_diagnostics()
Return denominator diagnostics for WTP/tradeoff ratios.
Source code in src/lcl/_prediction.py
elasticities(vars)
Compute full matrices of own- and cross-elasticities for continuous features.
Analytically calculates the percentage change in the probability of choosing alternative J given a one-percent change in a continuous attribute of alternative K. The method handles both conditional (latent class) and unconditional (standard conditional logit) probability matrices via a vectorized cartesian expansion across choice situations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vars
|
str | Iterable[str]
|
The name(s) of the continuous variable(s) for which to compute the elasticities (e.g., "price", ["price", "travel_time"]). |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
A DataFrame in long format mapping the target alternative ( |
Raises:
| Type | Description |
|---|---|
ValueError
|
If latent class probabilities are missing, or if a requested variable is not found in the estimated model specification. |
Source code in src/lcl/_prediction.py
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 | |
tradeoff(*wtp_requests, **kwargs)
Alias for :meth:compute_wtp with more neutral terminology.
wtp_by_class(target=None)
Return class-specific WTP/tradeoff ratios.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target
|
str | None
|
Optional target variable to filter. By default, all non-numeraire alternative-specific variables are returned. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Class-specific ratios |
Source code in src/lcl/_prediction.py
lcl._struct.WTPRequest(alt_var, demographic_var, partition_type, bins=None, dummy_vars=None, dummy_labels=None, base_category='base')
dataclass
Configuration object for calculating Marginal Willingness-to-Pay (WTP).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
alt_var
|
str
|
The target alternative-specific variable for the WTP numerator. |
required |
demographic_var
|
str
|
The demographic variable used to partition the decision-makers. When
|
required |
partition_type
|
PartitionType | str
|
The strategy for grouping |
required |
bins
|
list[float] | None
|
Custom breakpoints if |
None
|
dummy_vars
|
list[str] | None
|
One-hot dummy columns that jointly represent a categorical variable. The all-zero row is treated as the base category. |
None
|
dummy_labels
|
list[str] | None
|
Display labels for |
None
|
base_category
|
str
|
Display label for the all-zero base category when |
"base"
|
__post_init__()
Validate and normalize WTP request options.
Source code in src/lcl/_struct.py
lcl._struct.PartitionType
Bases: StrEnum
Supported binning strategies for marginal Willingness-To-Pay (WTP) analysis.
lcl._struct.PastChoicesData(X, y, alts, cases, panels, dems=None)
dataclass
Array-style container for historical choices used during prediction.
Pass to LCLResults.predict(past_choices=...) to update latent-class
membership probabilities with observed choices before scoring counterfactual
choice sets. Users with tabular historical-choice data can pass that DataFrame
directly to past_choices; this wrapper is intended for callers that already
manage design matrices and ID arrays.
Attributes:
| Name | Type | Description |
|---|---|---|
X |
ArrayLike
|
Alternative-specific design matrix in long format. |
y |
ArrayLike
|
Boolean or binary choice indicators aligned to rows of |
alts |
ArrayLike
|
Alternative identifiers aligned to rows of |
cases |
ArrayLike
|
Choice-situation identifiers aligned to rows of |
panels |
ArrayLike
|
Decision-maker identifiers aligned to rows of |
dems |
(ArrayLike | None, optional)
|
Panel-level demographic matrix, one row per unique panel, when the fitted latent-class membership model includes demographics. |