Conditional logit
The McFadden conditional logit estimates one taste vector for the full sample. It provides a useful homogeneous benchmark for latent-class specifications.
Use utility_formula for new formula-based specifications, and use the current
optimization and inference option objects:
from lcl import ConditionalLogit, InferenceOptions, OptimizationOptions, Options
results = ConditionalLogit(numeraire="price").fit(
data,
alts_col="alternative",
cases_col="choice_situation",
panels_col="respondent",
utility_formula="chosen ~ price + time + C(mode)",
weights="survey_weight",
options=Options(
optimization=OptimizationOptions(newton_decrement_tol=1e-6),
inference=InferenceOptions(covariance="clustered"),
),
)
coefficient_table = results.summarize_betas(show=False)
held_out_ll = results.loglik(test_data, weights="survey_weight")
Weights are case-level. Prefer a column name or case-keyed mapping because those
forms preserve identity when rows are reordered. If case IDs repeat across panels,
key a mapping by (panel_id, case_id). A sequence is interpreted in
first-case-appearance order and realigned after encoding. loglik accepts the
same weights forms; omitting scoring weights gives equal weight to every case.
loglik(data, per_case=True) includes both panel and case IDs.
With panels_col, BIC, CAIC, and adjusted BIC use the number of panels as their
sample size; otherwise they use the number of choice situations. A
negatively constrained numeraire does not have an ordinary zero-null p-value, so its
reported p-value is NaN.
covariance="clustered" clusters at the panel level when panels_col is
provided. covariance="robust" always requests case-level Huber–White inference;
the two labels are not aliases. The result also reports the null log likelihood,
McFadden rho-squared, final score, and information diagnostics.
Prediction returns a CLPrediction rather than a bare
frame. Probabilities remain in prediction.predicted_probs, with WTP,
elasticities, market shares, aggregate elasticities, denominator diagnostics,
and surplus methods shared with latent-class prediction. CL wtp(target),
compute_wtp(target), and tradeoff(target) return the same mean-WTP table;
LCL compute_wtp accepts partition requests. See the
API contracts guide for the complete comparison.
prediction = results.predict(counterfactual_data, panel_weights="survey_weight")
wtp = prediction.wtp("time", se="bootstrap", bootstrap_draws=1_000)
elasticities = prediction.elasticities(["price", "time"])
market_shares = prediction.market_shares()
prediction.marginal_wtp("time") evaluates each offered profile;
prediction.wtp("time") averages equally over profiles within occasions, then
occasions within consumers, and uses panel_weights across consumers. Both
include raw-attribute interactions and transformations. Monetary WTP and welfare
require a numeraire that enters once, linearly, without additional price terms.
See the prediction and welfare guide for
the estimands, interpretation, and inference assumptions.
Model
lcl.ConditionalLogit(numeraire=None, numeraire_min_abs=DEFAULT_NEGATIVE_MIN_ABS)
Bases: ChoiceModel
Specification and estimation for standard Multinomial Conditional Logit models.
Unlike the Latent Class variant, this model estimates a single vector of homogeneous taste parameters across the entire sample.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
numeraire
|
str | None
|
The name of the variable (e.g., 'price') to use as the numeraire. If provided, its coefficient is bounded to be strictly negative to ensure logically consistent utility scaling and willingness-to-pay calculations. |
None
|
numeraire_min_abs
|
float
|
Positive minimum absolute magnitude of the constrained coefficient. |
1e-5
|
Attributes:
| Name | Type | Description |
|---|---|---|
numeraire_idx |
int | None
|
The column index of the numeraire variable in the expanded design matrix. |
Create an unfitted conditional-logit model specification.
Source code in src/lcl/conditional_logit.py
fit(data, alts_col, cases_col, panels_col=None, utility_formula=None, choice_col=None, case_varnames=None, variable_labels=None, weights=None, weight_type='probability', init_beta=None, options=None, optimization_options=None, inference=None, diagnostics=None)
Fit the conditional logit model via Maximum Likelihood Estimation.
Supports both R-style formulas (via formulaic) and explicit lists of variables.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
pandas.DataFrame, polars.DataFrame, or mapping
|
The main dataset containing choice situations and alternatives in long format. |
required |
alts_col
|
str
|
Name of the column containing alternative identifiers. |
required |
cases_col
|
str
|
Name of the column grouping observations into distinct choice situations. |
required |
panels_col
|
str | None
|
Name of the column mapping observations to specific decision-makers. If provided, the covariance matrix is automatically clustered at the panel level. If omitted, standard Huber-White robust standard errors are computed. |
None
|
utility_formula
|
str | None
|
Preferred Formulaic string for the alternative-specific utility
specification. If it includes a left-hand side, that outcome is used
as the choice indicator; otherwise |
None
|
choice_col
|
str | None
|
Name of the boolean/binary column indicating chosen alternatives. |
None
|
case_varnames
|
Sequence[str] | None
|
List of alternative-specific variables. |
None
|
variable_labels
|
Mapping[str, str] | None
|
Optional mapping from raw DataFrame/model variable names to human-readable labels used in printed coefficient tables. |
None
|
weights
|
str, Mapping, ArrayLike, or None
|
Case-level weights. A string names a data column that must be constant
within case; a mapping is keyed by case ID (or |
None
|
weight_type
|
(probability, frequency)
|
How |
"probability"
|
init_beta
|
ArrayLike | None
|
|
None
|
options
|
Options | None
|
Complete configuration. Conditional logit uses |
None
|
optimization_options
|
OptimizationOptions | None
|
Preferred safeguarded exact-Newton settings. |
None
|
inference
|
InferenceOptions | None
|
Preferred covariance and standard-error settings. |
None
|
diagnostics
|
DiagnosticsOptions | None
|
Controls information-rank reporting through |
None
|
Returns:
| Type | Description |
|---|---|
class:`~lcl.conditional_logit.CLResults`
|
Results container housing coefficients, robust standard errors, and fit statistics. |
Source code in src/lcl/conditional_logit.py
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 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 | |
Results
lcl.results.CLResults(model_spec, optim_res, data_struct, inference, estim_time_sec, has_panels, case_weights, weight_type='probability', cluster_of_cases=None, num_clusters=None, diagnostics_config=None)
Post-estimation results and inference container for Conditional Logit.
Coefficients, covariance, and prediction derivatives share one parameterization. Ordinary covariance is unavailable when a coefficient bound is binding.
Compute inference summaries from a fitted conditional-logit model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_spec
|
:class:`~lcl.conditional_logit.ConditionalLogit`
|
Fitted model specification and variable metadata. |
required |
optim_res
|
:class:`~lcl._struct.OptimizeResult`
|
Optimizer output containing parameters, gradients, and Hessian inverse. |
required |
data_struct
|
:class:`~lcl._struct.Data`
|
Encoded estimation data. |
required |
inference
|
:class:`~lcl.options.InferenceOptions`
|
Covariance and standard-error configuration. |
required |
estim_time_sec
|
float
|
Wall-clock estimation time in seconds. |
required |
has_panels
|
bool
|
Whether robust covariance should cluster scores at the panel level. |
required |
case_weights
|
ArrayLike
|
Case weights aligned with encoded choice situations. |
required |
weight_type
|
(probability, frequency)
|
Interpretation of |
"probability"
|
cluster_of_cases
|
ArrayLike | None
|
Zero-indexed cluster identifier per case, for clustering coarser than the panel. |
None
|
num_clusters
|
int | None
|
Number of distinct clusters implied by |
None
|
diagnostics_config
|
DiagnosticsOptions | None
|
Diagnostic reporting switches; copied when results are constructed. |
None
|
Source code in src/lcl/conditional_logit.py
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 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 | |
abic
property
Deprecated alias for :attr:adjusted_bic.
convergence
property
Deprecated alias for :attr:converged.
covariance
property
Deprecated alias for :attr:cov_matrix.
covariance_available
property
Report whether a usable covariance matrix was estimated.
flat_params
property
Coefficient vector, aligned with :attr:cov_matrix.
coefficient_table()
Return conditional-logit coefficients with presentation labels.
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per alternative-specific variable with raw variable names, display labels, estimates, standard errors, z-values, and p-values. |
Source code in src/lcl/conditional_logit.py
diagnostics()
Return convergence, fit, score, and information diagnostics.
Source code in src/lcl/conditional_logit.py
loglik(data, *, per_case=False, weights=None)
Score observed choices with the fitted encoder.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
object
|
Long-format observed choices using the fitted column names. |
required |
per_case
|
bool
|
Return weighted contributions with original panel and case IDs. |
False
|
weights
|
str, mapping, array-like, or None
|
Scoring weights with the same alignment rules as :meth: |
None
|
Returns:
| Type | Description |
|---|---|
float or DataFrame
|
Total log likelihood, or a table with |
Source code in src/lcl/conditional_logit.py
parameter_names()
predict(data, *, alts_col=None, cases_col=None, panels_col=None, panel_weights=None)
Predict conditional choice probabilities for a given set of alternatives.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
pandas.DataFrame, polars.DataFrame, or mapping
|
Counterfactual raw data. The fitted encoder reuses formula transforms and categorical levels; expanded dummy columns need not be supplied. |
required |
alts_col
|
str | None
|
Deprecated redundant identifiers. If supplied, they must match the fitted encoder; rename input columns to predict with the fitted names. |
None
|
cases_col
|
str | None
|
Deprecated redundant identifiers. If supplied, they must match the fitted encoder; rename input columns to predict with the fitted names. |
None
|
panels_col
|
str | None
|
Deprecated redundant identifiers. If supplied, they must match the fitted encoder; rename input columns to predict with the fitted names. |
None
|
panel_weights
|
str, mapping, sequence, or array
|
Panel aggregation weights: a constant-per-panel data column, mapping by panel ID, or vector in sorted unique prediction-panel order. These weights affect aggregate summaries, not individual probabilities. |
None
|
Returns:
| Type | Description |
|---|---|
CLPrediction
|
Probabilities in |
Source code in src/lcl/conditional_logit.py
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 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 | |
summarize(num_decimals=3, *, show=True)
summarize_betas(header=('Variable', 'Estimate', 'Std. Error'), num_decimals=3, *, show=True)
Print and return a table of parameter estimates and standard errors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
header
|
tuple[str, str, str]
|
Column labels used for printed LaTeX and terminal tables. |
("Variable", "Estimate", "Std. Error")
|
num_decimals
|
int
|
Number of decimal places used in printed tables. |
3
|
show
|
bool
|
Emit LaTeX and terminal renderings. Set to |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Tidy coefficient table. The |
Source code in src/lcl/conditional_logit.py
lcl.results.CLPrediction(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, original_alts=None, original_cases=None, original_panels=None, raw_prediction_data=None, panel_weights=None, past_diff_unchosen_chosen=None, past_data=None)
Bases: _PredictionBase
Conditional-logit prediction with WTP and elasticity diagnostics.
Source code in src/lcl/_prediction.py
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 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 | |
compute_wtp(target=None, **kwargs)
denominator_diagnostics()
Report the WTP denominator, floor, SE, and Gaussian crossing probabilities.
The probability above the coefficient bound drives the 0.001 bootstrap screen; the probability above zero describes sign uncertainty. Neither establishes finite ratio moments. Unavailable covariance gives NaNs.
Source code in src/lcl/_prediction.py
tradeoff(target=None, **kwargs)
wtp(target=None, *, se='delta', bootstrap_draws=500, bootstrap_seed=0)
Return mean marginal WTP with delta or parametric-bootstrap SEs.
Both methods use the coefficient vector and its covariance directly. Gaussian simulation screens the fitted probability above the numeraire bound at 0.001, independently of seed and draw count. Passing this screen does not guarantee finite ratio moments or boundary-aware inference.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target
|
str | None
|
Restrict the table to one non-numeraire variable. |
None
|
se
|
(delta, bootstrap, none)
|
Standard-error method. |
"delta"
|
bootstrap_draws
|
int
|
Number of asymptotic parameter draws for |
500
|
bootstrap_seed
|
int
|
Reproducible seed for those draws. |
0
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per requested variable with mean marginal WTP and its SE. Raw variables include interactions and transforms. Values average equally over available profiles within cases, cases within consumers, and by panel weights over consumers. Expanded-column targets instead hold other design columns fixed. |
Source code in src/lcl/_prediction.py
1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 | |