Coverage for src/logit_encode/_logit_models.py: 99%
239 statements
« prev ^ index » next coverage.py v7.18.0, created at 2026-12-02 00:41 +0000
« prev ^ index » next coverage.py v7.18.0, created at 2026-12-02 00:41 +0000
1"""Logit models fit on dummy-coded categories and the encodings they imply.
3The models are fit on aggregated data: every distinct combination of category
4codes and outcome becomes one row, weighted by how often it occurs. Because a
5logit model's likelihood is a sum over rows, this gives the same estimates as
6fitting on the raw rows, but it is far faster when the categories repeat
7(which is the point of encoding them).
9An outcome with K classes is modeled with K - 1 baseline-category logits,
10one for each class against a reference class. Each is fit as a binary logit
11on the rows with that class or the reference class (Begg and Gray, 1984),
12which estimates the same coefficients as a multinomial logit and lets both
13backends fit every model the same way. With two classes, this is the usual
14binary logit.
16Contents:
17 ENCODINGS: the encodings that a fitted model can produce.
18 MODELS: the ways the categorical columns can enter the logit model.
19 BACKENDS: the libraries that can fit the logit model.
20 REFERENCES: the ways a column's reference level can be chosen.
21 AggregatedData: distinct rows of category codes and outcomes, with counts.
22 DummyDesign: dummy-coded design matrix for aggregated category codes.
23 ColumnEncoding: one column's encoded values, errors, and counts.
24 LogitEncodings: the encodings of every column.
25 aggregate: collapses category codes and outcomes into weighted rows.
26 build_design: dummy-codes aggregated category codes.
27 fit_logit: fits a (penalized) binary logit with sklearn or statsmodels.
28 compute_encodings: turns fitted logit models into encoded values.
29 fit_encodings: fits the logit models and returns the encodings.
31"""
33from __future__ import annotations
35import dataclasses
36import warnings
37from typing import Literal
39import numpy as np
40import pandas as pd
41import statsmodels.api as sm
42from scipy import sparse
43from scipy.special import expit
44from sklearn.exceptions import ConvergenceWarning
45from sklearn.linear_model import LogisticRegression
47Encoding = Literal['coefficient', 'log_odds', 'marginal_effect']
48Model = Literal['univariate', 'joint']
49Backend = Literal['sklearn', 'statsmodels']
50Reference = Literal['most_frequent', 'first'] | None
52ENCODINGS: tuple[str, ...] = ('coefficient', 'log_odds', 'marginal_effect')
53MODELS: tuple[str, ...] = ('univariate', 'joint')
54BACKENDS: tuple[str, ...] = ('sklearn', 'statsmodels')
55REFERENCES: tuple[str | None, ...] = ('most_frequent', 'first', None)
57# Largest number of cells in one block of the marginal effect computation. It
58# bounds memory use (8 bytes per cell) without slowing the computation much.
59_MAX_BLOCK_CELLS: int = 2_000_000
62""" Data Containers """
65@dataclasses.dataclass
66class AggregatedData:
67 """Distinct rows of category codes and outcomes, with their counts.
69 Args:
70 codes: integer category codes, one row per distinct combination of
71 codes and outcome, one column per categorical column.
72 target: outcome class index (0 to K - 1) of each distinct row.
73 weights: number of raw rows that each distinct row stands for.
75 """
77 codes: np.ndarray
78 target: np.ndarray
79 weights: np.ndarray
82@dataclasses.dataclass
83class DummyDesign:
84 """Dummy-coded design matrix for aggregated category codes.
86 Args:
87 matrix: sparse matrix with one row per distinct row of the data and
88 one column per non-reference level of every categorical column.
89 levels: for each categorical column, its sorted level codes.
90 positions: for each categorical column, the index into `levels` of
91 the level that each distinct row has.
92 dummy_columns: for each categorical column, the column of `matrix`
93 that holds each level's dummy, or -1 for the reference level.
95 """
97 matrix: sparse.csr_matrix
98 levels: list[np.ndarray]
99 positions: list[np.ndarray]
100 dummy_columns: list[np.ndarray]
103@dataclasses.dataclass
104class _FittedLogit:
105 """One fitted binary logit: a class against the reference class.
107 Args:
108 intercept: fitted intercept.
109 coefficients: fitted dummy coefficients.
110 n_iter: number of solver iterations.
111 curvature: for the intercept and each dummy, the sum over the
112 model's rows of `weight * p * (1 - p)`, the diagonal of the log
113 likelihood's information matrix (used for standard errors).
115 """
117 intercept: float
118 coefficients: np.ndarray
119 n_iter: int
120 curvature: np.ndarray
123@dataclasses.dataclass
124class ColumnEncoding:
125 """One column's encoded values, standard errors, and counts.
127 Args:
128 estimates: encoded values, indexed by category code, with one column
129 per modeled class (every class but the reference class).
130 errors: standard errors of `estimates`, or None if they were not
131 computed.
132 counts: number of rows with each category code.
133 prior: for each modeled class, the encoded value for a category the
134 model did not see: the average encoded value over the rows.
135 prior_error: for each modeled class, the standard error of the
136 encoded value of a category with no rows, or None.
138 """
140 estimates: pd.DataFrame
141 errors: pd.DataFrame | None
142 counts: pd.Series
143 prior: np.ndarray
144 prior_error: np.ndarray | None
147@dataclasses.dataclass
148class LogitEncodings:
149 """The encodings of every column.
151 Args:
152 columns: the encoding of each categorical column.
153 n_iter: largest number of solver iterations that any model used.
155 """
157 columns: list[ColumnEncoding]
158 n_iter: int = 0
161""" Public Functions """
164def aggregate(codes: np.ndarray, target: np.ndarray) -> AggregatedData:
165 """Collapses category codes and outcomes into weighted distinct rows.
167 Args:
168 codes: integer category codes with one row per observation and one
169 column per categorical column.
170 target: outcome class index of each observation.
172 Returns:
173 The distinct rows of `codes` and `target`, with their counts.
175 """
176 frame = pd.DataFrame(codes)
177 frame.columns = list(range(codes.shape[1]))
178 frame['__target__'] = target
179 counts = frame.groupby(list(frame.columns), sort = False).size()
180 distinct = counts.index.to_frame(index = False).to_numpy(dtype = np.int64)
181 return AggregatedData(
182 codes = distinct[:, :-1],
183 target = distinct[:, -1],
184 weights = counts.to_numpy(dtype = np.float64))
187def build_design(data: AggregatedData, reference: Reference) -> DummyDesign:
188 """Dummy-codes aggregated category codes.
190 Args:
191 data: aggregated category codes and outcomes.
192 reference: how to choose each column's reference level, which gets no
193 dummy: 'most_frequent' (the level with the most rows), 'first'
194 (the lowest code), or None (every level gets a dummy).
196 Raises:
197 ValueError: if `reference` is not one of `REFERENCES`.
199 Returns:
200 The dummy-coded design.
202 """
203 if reference not in REFERENCES:
204 raise ValueError(
205 f'reference must be one of {REFERENCES}, not {reference!r}')
206 blocks: list[sparse.csr_matrix] = []
207 levels: list[np.ndarray] = []
208 positions: list[np.ndarray] = []
209 dummy_columns: list[np.ndarray] = []
210 offset = 0
211 n_rows = data.codes.shape[0]
212 for column in range(data.codes.shape[1]):
213 column_levels, column_positions = np.unique(
214 data.codes[:, column], return_inverse = True)
215 n_levels = column_levels.size
216 has_dummy = np.ones(n_levels, dtype = bool)
217 if reference is not None:
218 has_dummy[_reference_position(
219 positions = column_positions,
220 weights = data.weights,
221 n_levels = n_levels,
222 reference = reference)] = False
223 n_dummies = int(has_dummy.sum())
224 columns = np.full(n_levels, -1, dtype = np.int64)
225 columns[has_dummy] = offset + np.arange(n_dummies)
226 rows = np.flatnonzero(has_dummy[column_positions])
227 block = sparse.csr_matrix(
228 (np.ones(rows.size),
229 (rows, columns[column_positions[rows]] - offset)),
230 shape = (n_rows, n_dummies))
231 blocks.append(block)
232 levels.append(column_levels)
233 positions.append(column_positions)
234 dummy_columns.append(columns)
235 offset += n_dummies
236 if blocks:
237 matrix = sparse.hstack(blocks, format = 'csr')
238 else:
239 matrix = sparse.csr_matrix((n_rows, 0))
240 return DummyDesign(
241 matrix = matrix,
242 levels = levels,
243 positions = positions,
244 dummy_columns = dummy_columns)
247def fit_logit(
248 *,
249 matrix: sparse.csr_matrix,
250 target: np.ndarray,
251 weights: np.ndarray,
252 backend: Backend,
253 C: float | None,
254 l1_ratio: float,
255 max_iter: int) -> tuple[float, np.ndarray, int]:
256 """Fits a (penalized) binary logit with sklearn or statsmodels.
258 Both backends minimize the same objective, so they give the same
259 estimates up to the solvers' tolerances: the summed log loss plus
260 `1 / C` times the elastic net penalty
261 `l1_ratio * |b| + (1 - l1_ratio) / 2 * b'b` on the dummy coefficients.
262 The intercept is never penalized.
264 Args:
265 matrix: dummy-coded design matrix.
266 target: binary (0 or 1) outcome of each row of `matrix`.
267 weights: frequency weight of each row of `matrix`.
268 backend: 'sklearn' (`sklearn.linear_model.LogisticRegression`) or
269 'statsmodels' (`statsmodels.api.GLM` with a binomial family and
270 logit link, which is the same model as `statsmodels.api.Logit`
271 but accepts the frequency weights of aggregated data).
272 C: inverse strength of the penalty, or None for no penalty.
273 l1_ratio: share of the penalty that is L1 (lasso) rather than L2
274 (ridge), from 0 to 1.
275 max_iter: largest number of solver iterations.
277 Raises:
278 ValueError: if `backend` is not one of `BACKENDS`.
280 Returns:
281 The intercept, the dummy coefficients (in the order of the columns of
282 `matrix`), and the number of solver iterations. statsmodels' elastic
283 net does not report its iterations, so `max_iter` is returned for
284 it.
286 """
287 if backend not in BACKENDS:
288 raise ValueError(
289 f'backend must be one of {BACKENDS}, not {backend!r}')
290 if matrix.shape[1] == 0:
291 intercept = _logit(float(_weighted_mean(target, weights)))
292 return intercept, np.zeros(0), 1
293 fit = _fit_sklearn if backend == 'sklearn' else _fit_statsmodels
294 return fit(
295 matrix = matrix,
296 target = target,
297 weights = weights,
298 C = C,
299 l1_ratio = l1_ratio,
300 max_iter = max_iter)
303def compute_encodings(
304 *,
305 design: DummyDesign,
306 data: AggregatedData,
307 fits: list[_FittedLogit],
308 encoding: Encoding,
309 ridge: float,
310 uncertainty: bool) -> list[ColumnEncoding]:
311 """Turns fitted logit models into encoded values for every level.
313 With one fitted model per modeled class k, for a column j and level l,
314 with b(k, l) the level's coefficient (0 for the reference level) and
315 base(k, i) the linear predictor of class k for row i without column j's
316 contribution:
318 * 'coefficient' is b(k, l), the log odds ratio of class k (against the
319 reference class) for level l against the reference level.
320 * 'log_odds' is b(k, l) plus the average of base(k, i): the average log
321 odds of class k (against the reference class) when column j is set to
322 level l. In a univariate model, it is the intercept plus b(k, l).
323 * 'marginal_effect' is the average over rows of
324 P(class k | base(i) + b(l)) - P(class k | base(i)): the average
325 discrete change in the probability of class k from moving column j
326 from the reference level to level l, holding the other columns as
327 observed. The probabilities come from all of the classes' predictors
328 together, so they are multinomial probabilities.
330 The standard errors come from the inverse of each model's penalized
331 information matrix. For a univariate model, this has a closed form,
332 since every dummy only shares rows with the intercept. For a joint
333 model, the information that dummies of different columns share is
334 ignored, which is an approximation. The L1 part of an elastic net
335 penalty is also ignored. The marginal effects' errors use the delta
336 method.
338 Args:
339 design: dummy-coded design matrix used to fit the models.
340 data: aggregated data used to fit the models.
341 fits: the fitted model of each modeled class.
342 encoding: one of `ENCODINGS`.
343 ridge: the L2 penalty on each coefficient, `(1 - l1_ratio) / C`.
344 uncertainty: whether to compute standard errors.
346 Raises:
347 ValueError: if `encoding` is not one of `ENCODINGS`.
349 Returns:
350 The encoding of every categorical column.
352 """
353 if encoding not in ENCODINGS:
354 raise ValueError(
355 f'encoding must be one of {ENCODINGS}, not {encoding!r}')
356 predictors = np.column_stack(
357 [fit.intercept + design.matrix @ fit.coefficients for fit in fits])
358 columns = []
359 for column, column_levels in enumerate(design.levels):
360 positions = design.positions[column]
361 dummy_columns = design.dummy_columns[column]
362 # A last, virtual level with no rows and a coefficient of 0 gives
363 # the standard error of a category that the model did not see.
364 coefficients = np.column_stack([
365 np.append(_level_values(fit.coefficients, dummy_columns), 0.0)
366 for fit in fits])
367 base = predictors - coefficients[positions]
368 if encoding == 'coefficient':
369 values = coefficients
370 elif encoding == 'log_odds':
371 values = coefficients + _weighted_mean(base, data.weights)
372 else:
373 values, gradients = _marginal_effects(
374 base = base,
375 weights = data.weights,
376 coefficients = coefficients,
377 gradients = uncertainty)
378 errors = None
379 if uncertainty:
380 variances = np.column_stack([
381 _coefficient_variances(
382 fit = fit,
383 dummy_columns = dummy_columns,
384 ridge = ridge,
385 with_intercept = encoding == 'log_odds')
386 for fit in fits])
387 if encoding == 'marginal_effect':
388 variances = np.einsum(
389 'lkj,lj->lk', gradients ** 2, variances)
390 errors = np.sqrt(variances)
391 errors[~np.isfinite(errors)] = np.nan
392 counts = np.bincount(
393 positions,
394 weights = data.weights,
395 minlength = column_levels.size)
396 frame = pd.DataFrame(values[:-1], index = column_levels)
397 columns.append(ColumnEncoding(
398 estimates = frame,
399 errors = (
400 None if errors is None
401 else pd.DataFrame(errors[:-1], index = column_levels)),
402 counts = pd.Series(counts, index = column_levels),
403 prior = np.array([
404 _weighted_mean(values[:-1, k], counts)
405 for k in range(len(fits))]),
406 prior_error = None if errors is None else errors[-1]))
407 return columns
410def fit_encodings(
411 *,
412 codes: np.ndarray,
413 target: np.ndarray,
414 reference_class: int,
415 n_classes: int,
416 encoding: Encoding,
417 model: Model,
418 backend: Backend,
419 C: float | None,
420 l1_ratio: float,
421 reference: Reference,
422 max_iter: int,
423 uncertainty: bool) -> LogitEncodings:
424 """Fits the logit models and returns the encodings they imply.
426 Args:
427 codes: integer category codes with one row per observation and one
428 column per categorical column.
429 target: outcome class index (0 to K - 1) of each observation.
430 reference_class: index of the reference class.
431 n_classes: number of classes of the outcome (every class gets a
432 model but the reference class, even if `target` lacks it).
433 encoding: one of `ENCODINGS`.
434 model: 'univariate' (separate logit models for each column) or
435 'joint' (logit models with every column's dummies, so each
436 column's values are adjusted for the other columns).
437 backend: one of `BACKENDS`.
438 C: inverse strength of the penalty, or None for no penalty.
439 l1_ratio: share of the penalty that is L1 rather than L2.
440 reference: how to choose each column's reference level.
441 max_iter: largest number of solver iterations.
442 uncertainty: whether to compute standard errors.
444 Raises:
445 ValueError: if `model` is not one of `MODELS`.
447 Returns:
448 The encodings of every column of `codes`.
450 """
451 if model == 'joint':
452 column_sets = [list(range(codes.shape[1]))]
453 elif model == 'univariate':
454 column_sets = [[column] for column in range(codes.shape[1])]
455 else:
456 raise ValueError(f'model must be one of {MODELS}, not {model!r}')
457 classes = [k for k in range(n_classes) if k != reference_class]
458 ridge = 0.0 if C is None else (1 - l1_ratio) / C
459 columns: list[ColumnEncoding] = []
460 # With no columns to encode, the model is intercept-only, whose estimate
461 # has a closed form that counts as one iteration.
462 n_iter = 1
463 for column_set in column_sets:
464 data = aggregate(codes = codes[:, column_set], target = target)
465 design = build_design(data = data, reference = reference)
466 fits = []
467 for k in classes:
468 rows = np.isin(data.target, [reference_class, k])
469 binary = (data.target[rows] == k).astype(np.int64)
470 matrix = design.matrix[rows]
471 intercept, coefficients, iterations = fit_logit(
472 matrix = matrix,
473 target = binary,
474 weights = data.weights[rows],
475 backend = backend,
476 C = C,
477 l1_ratio = l1_ratio,
478 max_iter = max_iter)
479 fits.append(_FittedLogit(
480 intercept = intercept,
481 coefficients = coefficients,
482 n_iter = iterations,
483 curvature = _curvature(
484 matrix = matrix,
485 weights = data.weights[rows],
486 intercept = intercept,
487 coefficients = coefficients)))
488 n_iter = max(n_iter, iterations)
489 columns.extend(compute_encodings(
490 design = design,
491 data = data,
492 fits = fits,
493 encoding = encoding,
494 ridge = ridge,
495 uncertainty = uncertainty))
496 return LogitEncodings(columns = columns, n_iter = n_iter)
499""" Private Functions """
502def _class_probabilities(predictors: np.ndarray) -> np.ndarray:
503 """Returns the probabilities of the modeled classes.
505 Args:
506 predictors: linear predictors of the modeled classes (against the
507 reference class) in the last axis.
509 Returns:
510 The probability of each modeled class: `expit` of the predictor with
511 one modeled class, and the softmax with the reference class's
512 predictor fixed at 0 with more.
514 """
515 if predictors.shape[-1] == 1:
516 probabilities: np.ndarray = expit(predictors)
517 return probabilities
518 largest = np.maximum(predictors.max(axis = -1, keepdims = True), 0.0)
519 exponents = np.exp(predictors - largest)
520 total = np.exp(-largest) + exponents.sum(axis = -1, keepdims = True)
521 return np.asarray(exponents / total)
524def _coefficient_variances(
525 fit: _FittedLogit,
526 dummy_columns: np.ndarray,
527 ridge: float,
528 with_intercept: bool) -> np.ndarray:
529 """Returns the variances of one column's coefficients in one model.
531 The information matrix is restricted to the intercept and this column's
532 dummies, holding the other columns' coefficients fixed. Since a column's
533 dummies never share rows, this is an "arrowhead" matrix, whose inverse
534 has a closed form. With `a` the intercept's information, `u` a dummy's
535 information (which it shares with the intercept), `d = u + ridge` the
536 dummy's penalized information, and `s = a - sum(u^2 / d)` over the
537 column's dummies:
539 * the variance of the dummy's coefficient is `1 / d + u^2 / (d^2 s)`,
540 * the variance of the intercept plus the coefficient is
541 `1 / d + (1 - u / d)^2 / s`, and
542 * the variance of the intercept is `1 / s`.
544 Args:
545 fit: the fitted model.
546 dummy_columns: the dummy column of each level of the column, or -1
547 for the reference level.
548 ridge: the L2 penalty on each coefficient.
549 with_intercept: whether to return the variances of the intercept
550 plus each coefficient (the log odds) rather than of the
551 coefficients alone.
553 Returns:
554 The variance of each level's value, plus a last value for a level
555 with no rows.
557 """
558 intercept_information = fit.curvature[0]
559 has_dummy = dummy_columns >= 0
560 shared = fit.curvature[1:][dummy_columns[has_dummy]]
561 penalized = shared + ridge
562 with np.errstate(divide = 'ignore', invalid = 'ignore'):
563 ratio = np.where(penalized > 0, shared / penalized, 0.0)
564 schur = intercept_information - np.sum(shared * ratio)
565 level_shared = np.zeros(dummy_columns.size + 1)
566 level_penalized = np.full(dummy_columns.size + 1, ridge)
567 level_shared[:-1][has_dummy] = shared
568 level_penalized[:-1][has_dummy] = penalized
569 is_reference = np.append(~has_dummy, False)
570 inverse = 1 / level_penalized
571 if with_intercept:
572 variances = (
573 inverse + (1 - level_shared * inverse) ** 2 / schur)
574 variances[is_reference] = 1 / schur
575 else:
576 variances = inverse + level_shared ** 2 * inverse ** 2 / schur
577 variances[is_reference] = 0.0
578 result: np.ndarray = variances
579 return result
582def _curvature(
583 *,
584 matrix: sparse.csr_matrix,
585 weights: np.ndarray,
586 intercept: float,
587 coefficients: np.ndarray) -> np.ndarray:
588 """Returns the diagonal of a fitted logit's information matrix.
590 Args:
591 matrix: dummy-coded design matrix of the model's rows.
592 weights: frequency weight of each row.
593 intercept: fitted intercept.
594 coefficients: fitted dummy coefficients.
596 Returns:
597 The sum of `weight * p * (1 - p)` over all rows (for the intercept)
598 and over the rows of each dummy.
600 """
601 probabilities = expit(intercept + matrix @ coefficients)
602 information = weights * probabilities * (1 - probabilities)
603 return np.concatenate(
604 [[information.sum()], matrix.T @ information])
607def _fit_sklearn(
608 *,
609 matrix: sparse.csr_matrix,
610 target: np.ndarray,
611 weights: np.ndarray,
612 C: float | None,
613 l1_ratio: float,
614 max_iter: int) -> tuple[float, np.ndarray, int]:
615 """Fits the logit model with `sklearn.linear_model.LogisticRegression`.
617 The L-BFGS solver fits L2-penalized and unpenalized models, and SAGA fits
618 models with an L1 penalty. SAGA's step size shrinks with the largest
619 sample weight, so it diverges on aggregated data whose frequency weights
620 are large. The weights are therefore divided by their largest value and
621 `C` is multiplied by it, which leaves the objective unchanged.
623 Args:
624 matrix: dummy-coded design matrix.
625 target: binary outcome of each row.
626 weights: frequency weight of each row.
627 C: inverse strength of the penalty, or None for no penalty.
628 l1_ratio: share of the penalty that is L1 rather than L2.
629 max_iter: largest number of solver iterations.
631 Returns:
632 The intercept, the dummy coefficients, and the number of solver
633 iterations.
635 """
636 scale = float(weights.max())
637 solver = 'lbfgs' if l1_ratio == 0 or C is None else 'saga'
638 estimator = LogisticRegression(
639 C = np.inf if C is None else C * scale,
640 l1_ratio = l1_ratio,
641 solver = solver,
642 max_iter = max_iter,
643 tol = 1e-6)
644 with warnings.catch_warnings():
645 # An unpenalized model of a level that has only one outcome does not
646 # converge, since its coefficient grows without bound.
647 warnings.simplefilter('ignore', category = ConvergenceWarning)
648 estimator.fit(matrix, target, sample_weight = weights / scale)
649 return (
650 float(estimator.intercept_[0]),
651 estimator.coef_[0].copy(),
652 int(np.max(estimator.n_iter_)))
655def _fit_statsmodels(
656 *,
657 matrix: sparse.csr_matrix,
658 target: np.ndarray,
659 weights: np.ndarray,
660 C: float | None,
661 l1_ratio: float,
662 max_iter: int) -> tuple[float, np.ndarray, int]:
663 """Fits the logit model with `statsmodels.api.GLM`.
665 statsmodels' elastic net divides the log likelihood by the number of rows
666 in the model (here, the distinct rows) rather than by the summed
667 frequency weights, so the penalty is scaled by that number to match
668 sklearn's objective.
670 Args:
671 matrix: dummy-coded design matrix.
672 target: binary outcome of each row.
673 weights: frequency weight of each row.
674 C: inverse strength of the penalty, or None for no penalty.
675 l1_ratio: share of the penalty that is L1 rather than L2.
676 max_iter: largest number of solver iterations.
678 Returns:
679 The intercept, the dummy coefficients, and the number of solver
680 iterations (`max_iter` for the elastic net, which does not report
681 them).
683 """
684 exog = np.column_stack([np.ones(matrix.shape[0]), matrix.toarray()])
685 glm = sm.GLM(
686 target,
687 exog,
688 family = sm.families.Binomial(),
689 freq_weights = weights)
690 with warnings.catch_warnings():
691 # Unpenalized models of levels that have only one outcome warn about
692 # perfect separation, which the penalty is there to prevent.
693 warnings.simplefilter('ignore')
694 if C is None:
695 results = glm.fit(maxiter = max_iter)
696 params = results.params
697 n_iter = int(results.fit_history['iteration'])
698 else:
699 alpha = np.full(exog.shape[1], 1 / (C * glm.nobs))
700 alpha[0] = 0.0
701 params = glm.fit_regularized(
702 method = 'elastic_net',
703 alpha = alpha,
704 L1_wt = l1_ratio,
705 maxiter = max_iter).params
706 n_iter = max_iter
707 params = np.asarray(params, dtype = np.float64)
708 return float(params[0]), params[1:], max(n_iter, 1)
711def _level_values(
712 coefficients: np.ndarray,
713 dummy_columns: np.ndarray) -> np.ndarray:
714 """Returns the coefficient of every level of one column.
716 Args:
717 coefficients: fitted dummy coefficients.
718 dummy_columns: the dummy column of each level, or -1 for the
719 reference level.
721 Returns:
722 Each level's coefficient, with 0 for the reference level.
724 """
725 has_dummy = dummy_columns >= 0
726 values = np.zeros(dummy_columns.size)
727 values[has_dummy] = coefficients[dummy_columns[has_dummy]]
728 return values
731def _logit(probability: float) -> float:
732 """Returns the log odds of a probability, kept finite.
734 Args:
735 probability: a probability from 0 to 1.
737 Returns:
738 The log odds of `probability`, clipped away from 0 and 1.
740 """
741 clipped = min(max(probability, 1e-12), 1 - 1e-12)
742 return float(np.log(clipped / (1 - clipped)))
745def _marginal_effects(
746 *,
747 base: np.ndarray,
748 weights: np.ndarray,
749 coefficients: np.ndarray,
750 gradients: bool) -> tuple[np.ndarray, np.ndarray]:
751 """Returns each level's average discrete change in class probabilities.
753 The rows are handled in blocks so that the arrays of probabilities never
754 hold more than `_MAX_BLOCK_CELLS` cells.
756 Args:
757 base: linear predictors of each distinct row (one column per modeled
758 class) without the column's contribution.
759 weights: number of raw rows that each distinct row stands for.
760 coefficients: coefficient of each level (rows) for each modeled
761 class (columns).
762 gradients: whether to also return the effects' derivatives with
763 respect to the coefficients, for the delta method.
765 Returns:
766 The effects, with one row per level and one column per modeled
767 class, and their derivatives (levels by effect class by coefficient
768 class), which are empty if `gradients` is False.
770 """
771 # Rows that share base values contribute the same terms, so they are
772 # combined first. In a univariate model, every row shares one value.
773 unique_base, inverse = np.unique(base, axis = 0, return_inverse = True)
774 unique_weights = np.bincount(inverse.ravel(), weights = weights)
775 n_levels, n_classes = coefficients.shape
776 cells = n_levels * n_classes * (n_classes if gradients else 1)
777 block_size = max(1, _MAX_BLOCK_CELLS // max(1, cells))
778 totals = np.zeros((n_levels, n_classes))
779 slopes = np.zeros((n_levels, n_classes, n_classes) if gradients else 0)
780 for start in range(0, unique_base.shape[0], block_size):
781 block = unique_base[start:start + block_size]
782 block_weights = unique_weights[start:start + block_size]
783 shifted = _class_probabilities(
784 block[:, None, :] + coefficients[None, :, :])
785 current = _class_probabilities(block)
786 totals += np.einsum(
787 'r,rlk->lk', block_weights, shifted - current[:, None, :])
788 if gradients:
789 outer = shifted[..., :, None] * shifted[..., None, :]
790 diagonal = np.einsum('rlk,kj->rlkj', shifted, np.eye(n_classes))
791 slopes += np.einsum('r,rlkj->lkj', block_weights, diagonal - outer)
792 total_weight = weights.sum()
793 return totals / total_weight, slopes / total_weight
796def _reference_position(
797 positions: np.ndarray,
798 weights: np.ndarray,
799 n_levels: int,
800 reference: str) -> int:
801 """Returns the index of a column's reference level.
803 Args:
804 positions: the index of the level that each distinct row has.
805 weights: number of raw rows that each distinct row stands for.
806 n_levels: number of levels in the column.
807 reference: 'most_frequent' or 'first'.
809 Returns:
810 The index (into the column's sorted levels) of the reference level.
812 """
813 if reference == 'first':
814 return 0
815 counts = np.bincount(positions, weights = weights, minlength = n_levels)
816 return int(np.argmax(counts))
819def _weighted_mean(values: np.ndarray, weights: np.ndarray) -> np.ndarray:
820 """Returns the weighted mean of `values` over its first axis.
822 Args:
823 values: values to average.
824 weights: weight of each value (or row of values).
826 Returns:
827 The weighted mean, or 0 if the weights sum to 0.
829 """
830 total = weights.sum()
831 if total == 0: 831 ↛ 832line 831 didn't jump to line 832 because the condition on line 831 was never true
832 return np.zeros(values.shape[1:])
833 mean: np.ndarray = np.tensordot(weights, values, axes = 1) / total
834 return mean