Coverage for src/logit_encode/logit_encoder.py: 97%

466 statements  

« prev     ^ index     » next       coverage.py v7.18.0, created at 2026-12-02 00:41 +0000

1"""Logit encoding of categorical features. 

2 

3Contents: 

4 LogitEncoder: encodes categories with the coefficients, marginal effects, 

5 or log odds from a logit model of a categorical outcome. 

6 

7""" 

8 

9from __future__ import annotations 

10 

11import dataclasses 

12import numbers 

13import warnings 

14from typing import TYPE_CHECKING, Any, cast 

15 

16import category_encoders.utils as ce_utils 

17import numpy as np 

18import pandas as pd 

19from category_encoders.ordinal import OrdinalEncoder 

20from joblib import Parallel, delayed 

21from sklearn.model_selection import StratifiedKFold 

22from sklearn.utils.multiclass import type_of_target 

23from sklearn.utils.validation import check_is_fitted 

24 

25from . import _logit_models, utils 

26 

27if TYPE_CHECKING: 

28 from collections.abc import Hashable 

29 

30# Cross-fitting needs two folds, an outcome needs two classes, and an 

31# interaction or composite column needs two columns. 

32_MIN_FOLDS: int = 2 

33_MIN_CLASSES: int = 2 

34_MIN_MEMBERS: int = 2 

35# Labels of the rows that `get_mapping` adds for categories not seen in 

36# fitting and for missing values when none were seen in fitting. 

37_UNKNOWN_LABEL: str = '<unknown>' 

38_MISSING_LABEL: str = '<missing>' 

39# Tolerances for matching encoded values to categories in 

40# `inverse_transform`, loose enough for a round trip through float32. 

41_MATCH_RTOL: float = 1e-6 

42_MATCH_ATOL: float = 1e-9 

43# Largest number of comparisons in one block of `inverse_transform`. 

44_MAX_BLOCK_CELLS: int = 4_000_000 

45_COMBINE_OPTIONS: tuple[Any, ...] = (None, True, False, 'force') 

46 

47 

48@dataclasses.dataclass(frozen = True) 

49class _Group: 

50 """A combination of columns that is encoded as one more column. 

51 

52 Args: 

53 name: the combined column's name: its members' names joined by '|'. 

54 members: the columns it is made from. 

55 composite: whether it comes from `composite_cols` (whose members are 

56 dropped from the output unless `keep_components` is True) rather 

57 than from `interactions` (whose members are kept). 

58 

59 """ 

60 

61 name: str 

62 members: tuple[Any, ...] 

63 composite: bool 

64 

65 

66class LogitEncoder(utils.SupervisedTransformerMixin, utils.BaseEncoder): 

67 """Encodes categories with values from a logit model of the outcome. 

68 

69 Each categorical column is dummy-coded and a logit model of the outcome 

70 is fit on the dummies. Each category is then replaced by one of three 

71 values from that model (see `encoding`): 

72 

73 * 'coefficient': the level's coefficient, which is the log odds ratio of 

74 the outcome for that level against the column's reference level. 

75 * 'log_odds': the average log odds of the outcome when the column is set 

76 to that level. In a univariate model, it is the intercept plus the 

77 coefficient. 

78 * 'marginal_effect': the average change in the probability of the 

79 outcome from moving the column from the reference level to that level, 

80 holding the other columns as observed (a discrete change, since the 

81 level is a dummy). 

82 

83 The model can be one logit with every column's dummies ('joint', the 

84 default), whose values are adjusted for the other columns, or a separate 

85 logit for each column ('univariate'). Either sklearn or statsmodels can 

86 fit it. Both minimize the same penalized log loss, so they agree up to 

87 solver tolerances. 

88 

89 An outcome with more than two classes is modeled with a logit for each 

90 class against a reference class (the most frequent class), so each 

91 categorical column becomes one column per other class, named 

92 '<column>_<class>'. With two classes, the first (in sorted order) is the 

93 reference class and each column stays one column. 

94 

95 `interactions` adds a column for each listed combination of columns, 

96 encoded like any other categorical column, and `return_uncertainty` adds 

97 each value's standard error ('<column>_se') and each category's number 

98 of training rows ('<column>_count'), so that a model can trust the 

99 values of rare categories less. 

100 

101 Encoding training rows with a model fit on those same rows leaks the 

102 outcome into the features. So, like sklearn's `TargetEncoder`, 

103 `fit_transform` (and `transform` given `y`) cross-fits: each training 

104 row is encoded by a model fit on the other folds. `transform` without 

105 `y` uses the model fit on all of the training data. Set `cv` to None to 

106 turn cross-fitting off. 

107 

108 `LogitEncoder` is a drop-in replacement for the supervised 

109 `category_encoders` encoders: it takes the same parameters (`cols`, 

110 `drop_invariant`, `return_df`, `handle_missing`, `handle_unknown`, 

111 `min_group_size`, `min_group_name`, `combine_min_nan_groups`, 

112 `composite_cols`, and `keep_components`, in the same order as 

113 `TargetEncoder`'s), has the same `mapping`, `ordinal_encoder`, 

114 `invariant_cols`, and `feature_names_out_` attributes and 

115 `get_feature_names_out` and `get_feature_names_in` methods, and passes 

116 extra DataFrame columns through `transform`. It is also a full sklearn 

117 transformer: it works in pipelines, column transformers, 

118 cross-validation, and grid searches, supports `set_output`, and passes 

119 sklearn's `check_estimator`. The one difference is that `cols` keeps the 

120 value it was given; the columns that were encoded are in `cols_`. 

121 

122 `LogitEncoder` is not a dataclass because sklearn reads an estimator's 

123 parameters from its `__init__` signature and requires that `__init__` 

124 only store them. 

125 

126 Attributes: 

127 mapping_: for each encoded column (including interactions and 

128 composite columns), the encoded value of each category's ordinal 

129 code, fit on all of the training data: a series for a binary 

130 outcome, or a DataFrame with a column per modeled class. The 

131 codes are in `ordinal_encoder_.category_mapping`. `get_mapping` 

132 gives the same values by category. 

133 error_mapping_: the standard errors of `mapping_`'s values, if 

134 `return_uncertainty` is True. 

135 count_mapping_: for each encoded column, the number of training rows 

136 with each category's ordinal code, if `return_uncertainty` is 

137 True. 

138 ordinal_encoder_: the fitted `category_encoders.OrdinalEncoder` that 

139 turns categories into ordinal codes. 

140 classes_: the outcome's classes, in sorted order. 

141 reference_class_: the class that the others are compared with. 

142 modeled_classes_: the other classes, which each get a column. 

143 interaction_cols_: the names of the interaction columns. 

144 composite_members_: for each composite column, its member columns. 

145 min_group_lumping_: for each column with categories lumped together 

146 by `min_group_size`, the group that each lumped category joined. 

147 n_iter_: largest number of solver iterations that any of the models 

148 fit on all of the training data used. 

149 cols_: the input columns that were encoded on their own. 

150 invariant_cols_: the output columns dropped by `drop_invariant`. 

151 feature_names_out_: names of the output columns. 

152 n_features_in_: number of columns seen in fitting. 

153 feature_names_in_: names of the columns seen in fitting, if they 

154 were all strings. 

155 

156 Examples: 

157 >>> import pandas as pd 

158 >>> from logit_encode import LogitEncoder 

159 >>> X = pd.DataFrame({'color': ['red', 'blue', 'red', 'green'] * 25}) 

160 >>> y = pd.Series([1, 0, 0, 1] * 25) 

161 >>> encoder = LogitEncoder(encoding = 'log_odds', cv = None) 

162 >>> encoded = encoder.fit_transform(X, y) 

163 >>> encoded['color'].round(2).abs().unique().tolist() 

164 [0.0, 2.29] 

165 >>> table = encoder.get_mapping('color').round(2) + 0.0 

166 >>> table # doctest: +NORMALIZE_WHITESPACE 

167 color 

168 category 

169 red 0.00 

170 blue -2.29 

171 green 2.29 

172 <missing> 0.00 

173 <unknown> 0.00 

174 >>> recovered = encoder.inverse_transform(encoder.transform(X)) 

175 >>> recovered['color'][:4].tolist() 

176 ['red', 'blue', 'red', 'green'] 

177 

178 """ 

179 

180 """ Initialization Methods """ 

181 

182 def __init__( # noqa: PLR0917 

183 self, 

184 verbose: int = 0, 

185 cols: list[Any] | str | None = None, 

186 drop_invariant: bool = False, 

187 return_df: bool = True, 

188 handle_missing: Any = 'value', 

189 handle_unknown: Any = 'value', 

190 encoding: _logit_models.Encoding = 'log_odds', 

191 model: _logit_models.Model = 'joint', 

192 backend: _logit_models.Backend = 'sklearn', 

193 C: float | None = 1.0, 

194 l1_ratio: float = 0.0, 

195 cv: int | None = 5, 

196 reference: _logit_models.Reference = 'most_frequent', 

197 interactions: list[tuple[Any, ...]] | None = None, 

198 return_uncertainty: bool = False, 

199 max_iter: int = 5000, 

200 n_jobs: int | None = None, 

201 random_state: int | np.random.RandomState | None = None, 

202 min_group_size: float | None = None, 

203 min_group_name: str | None = None, 

204 combine_min_nan_groups: bool | str | None = None, 

205 composite_cols: list[tuple[Any, ...]] | None = None, 

206 keep_components: bool = False) -> None: 

207 """Stores the parameters without validating them, as sklearn requires. 

208 

209 The parameters are checked when the encoder is fit. They can be 

210 passed by position, in the same order as `category_encoders`' 

211 `TargetEncoder` for the parameters the two share. 

212 

213 Args: 

214 verbose: verbosity of the output. 0 for none. 

215 cols: columns to encode. If None, every object, string, and 

216 categorical column is encoded, as in `category_encoders`. If 

217 'all', every column is encoded. 

218 drop_invariant: whether to drop encoded columns with no variance. 

219 return_df: whether `transform` returns a pandas DataFrame 

220 (otherwise, a numpy array). 

221 handle_missing: how to encode missing values: 'value' (treat them 

222 as a category, or use the prior if none were seen in 

223 fitting), 'return_nan', 'error', a number, or a callable as 

224 in `category_encoders`. 

225 handle_unknown: how to encode categories not seen in fitting: 

226 'value' (the prior), 'return_nan', 'error', a number, or a 

227 callable as in `category_encoders`. The prior is the column's 

228 average encoded value over the training rows. 

229 encoding: 'log_odds', 'coefficient', or 'marginal_effect'. 

230 model: 'joint' (one logit model with every column) or 

231 'univariate' (a logit model for each column). 

232 backend: 'sklearn' or 'statsmodels'. statsmodels builds a dense 

233 design matrix, so sklearn is much faster for columns with 

234 many categories. 

235 C: inverse strength of the penalty on the coefficients, as in 

236 `sklearn.linear_model.LogisticRegression`. Smaller values 

237 shrink rare categories more toward the reference level. None 

238 fits an unpenalized model, whose coefficients for categories 

239 with only one outcome grow without bound. 

240 l1_ratio: share of the penalty that is L1 (lasso) rather than L2 

241 (ridge), from 0 to 1. 

242 cv: number of folds for cross-fitting the training rows, or None 

243 to encode them with the model fit on all of them. 

244 reference: how to choose each column's reference level, which has 

245 a coefficient of 0: 'most_frequent', 'first' (the first 

246 category seen), or None (no reference level, so every 

247 category gets a dummy and coefficients are relative to the 

248 intercept). 

249 interactions: combinations of columns (any columns of X) to 

250 encode as one more categorical column each, such as 

251 [('state', 'county')], keeping their member columns. Each is 

252 named by joining its columns' names with '|', and a row with 

253 a missing value in any of them has a missing value in the 

254 combination. 

255 return_uncertainty: whether to add each encoded value's standard 

256 error ('<column>_se') and each category's number of training 

257 rows ('<column>_count'). The standard errors are exact (up to 

258 the L1 part of the penalty) for univariate models and ignore 

259 the information that columns share in joint models. 

260 max_iter: largest number of solver iterations. 

261 n_jobs: number of parallel jobs for fitting the univariate models 

262 and the cross-fitting folds, as in joblib. None means 1 

263 unless in a `joblib.parallel_config` context. 

264 random_state: seed for shuffling the cross-fitting folds. 

265 min_group_size: as in `category_encoders`, the smallest number 

266 (an int) or share of the rows (a float) that a category needs 

267 to be encoded on its own. Smaller categories are lumped into 

268 one group before fitting. None turns lumping off. 

269 min_group_name: name of the lumped group. If None, the lumped 

270 categories' names are joined (in sorted order) with '_'. 

271 combine_min_nan_groups: whether missing values join the lumped 

272 group: True (if they are themselves too few, the default for 

273 None), 'force' (always), or False (never). 

274 composite_cols: as in `category_encoders`, combinations of 

275 columns to encode as one column each, named by joining their 

276 names with '|'. Unlike `interactions`, their member columns 

277 are dropped from the output unless `keep_components` is True. 

278 keep_components: whether the members of `composite_cols` are also 

279 encoded on their own and kept in the output. 

280 

281 """ 

282 super().__init__( 

283 verbose = verbose, 

284 cols = cols, 

285 drop_invariant = drop_invariant, 

286 return_df = return_df, 

287 handle_missing = handle_missing, 

288 handle_unknown = handle_unknown) 

289 self.encoding = encoding 

290 self.model = model 

291 self.backend = backend 

292 self.C = C 

293 self.l1_ratio = l1_ratio 

294 self.cv = cv 

295 self.reference = reference 

296 self.interactions = interactions 

297 self.return_uncertainty = return_uncertainty 

298 self.max_iter = max_iter 

299 self.n_jobs = n_jobs 

300 self.random_state = random_state 

301 self.min_group_size = min_group_size 

302 self.min_group_name = min_group_name 

303 self.combine_min_nan_groups = combine_min_nan_groups 

304 self.composite_cols = composite_cols 

305 self.keep_components = keep_components 

306 

307 """ Required Methods """ 

308 

309 def _fit(self, X: pd.DataFrame, y: pd.Series | None) -> None: 

310 """Fits the logit models on all of the training data. 

311 

312 Args: 

313 X: validated training data. 

314 y: validated training outcome. 

315 

316 Raises: 

317 ValueError: if a parameter is invalid or `y` is continuous or has 

318 fewer than two classes. 

319 TypeError: if a column to encode has unhashable values. 

320 

321 """ 

322 self._validate_parameters() 

323 if y is None: 323 ↛ 324line 323 didn't jump to line 324 because the condition on line 323 was never true

324 raise ValueError('LogitEncoder requires y to be passed.') 

325 self._set_classes(y) 

326 target = self._class_indices(y) 

327 self._groups = self._build_groups(X) 

328 self.interaction_cols_ = [ 

329 group.name for group in self._groups if not group.composite] 

330 self.composite_members_ = { 

331 group.name: group.members 

332 for group in self._groups if group.composite} 

333 self.cols_ = self._own_columns(X) 

334 X = self._add_groups(X) 

335 self.min_group_lumping_ = self._fit_lumping(X) 

336 X = self._apply_lumping(X) 

337 self.ordinal_encoder_ = OrdinalEncoder( 

338 verbose = self.verbose, 

339 cols = self._encoded_columns, 

340 handle_unknown = 'value', 

341 handle_missing = 'value') 

342 try: 

343 self.ordinal_encoder_.fit(X) 

344 except TypeError as error: 

345 raise TypeError( 

346 'Each category must be hashable: the argument must be a ' 

347 f'string or a number ({error}).') from error 

348 X_ordinal = self.ordinal_encoder_.transform(X) 

349 encodings = self._fit_encodings( 

350 codes = self._codes(X_ordinal), 

351 target = target) 

352 self.n_iter_ = encodings.n_iter 

353 self._store_mappings(encodings) 

354 

355 def _encode( 

356 self, 

357 X: pd.DataFrame, 

358 y: pd.Series | None = None) -> pd.DataFrame: 

359 """Encodes `X`, cross-fitting it if its outcome `y` is given. 

360 

361 Args: 

362 X: validated data to encode. 

363 y: outcome of `X` if `X` is training data, or None. 

364 

365 Raises: 

366 ValueError: if `handle_unknown` is 'error' and `X` has categories 

367 not seen in fitting, or if `handle_missing` is 'error' and a 

368 combined column is missing. 

369 

370 Returns: 

371 The encoded data, with the columns of `_output_columns`. 

372 

373 """ 

374 X = self._apply_lumping(self._add_groups(X)) 

375 names = [group.name for group in self._groups] 

376 if ( 

377 names 

378 and isinstance(self.handle_missing, str) 

379 and self.handle_missing == 'error' 

380 and X[names].isna().to_numpy().any()): 

381 raise ValueError('Columns to be encoded cannot contain null') 

382 codes = self._codes(self.ordinal_encoder_.transform(X)) 

383 if ( 

384 isinstance(self.handle_unknown, str) 

385 and self.handle_unknown == 'error' 

386 and (codes == ce_utils.UNKNOWN_SENTINEL).any()): 

387 raise ValueError('Unexpected categories found in dataframe') 

388 if y is not None and self.cv is not None: 

389 values, errors = self._cross_fit(codes = codes, y = y) 

390 else: 

391 values, errors = self._look_up(codes) 

392 encoded: dict[Hashable, Any] = {} 

393 positions = { 

394 column: index 

395 for index, column in enumerate(self._encoded_columns)} 

396 for output in self._output_spec: 

397 if not output.encoded: 

398 # A series keeps the column's dtype (such as 'category'). 

399 encoded[output.label] = X[output.label] 

400 continue 

401 position = positions[self._source_name(output.sources)] 

402 encoded[output.label] = self._output_values( 

403 output = output, 

404 codes = codes[:, position], 

405 values = values[:, position], 

406 errors = errors[:, position]) 

407 return pd.DataFrame(encoded, index = X.index) 

408 

409 def _output_columns(self) -> list[utils.OutputColumn]: 

410 """Returns the encoder's output columns, in order. 

411 

412 Each encoded column is replaced, in place, by its value columns (one 

413 per modeled class), then its standard error columns and count column 

414 if `return_uncertainty` is True. The members of `composite_cols` are 

415 left out unless `keep_components` is True. Interaction and composite 

416 columns follow the input columns. 

417 

418 Returns: 

419 The output columns. 

420 

421 """ 

422 encoded = set(self.cols_) 

423 dropped = set() if self.keep_components else { 

424 member 

425 for group in self._groups if group.composite 

426 for member in group.members} 

427 columns: list[utils.OutputColumn] = [] 

428 for column in self._columns: 

429 if column in dropped: 

430 continue 

431 if column in encoded: 

432 columns.extend(self._encoded_outputs(column, (column,))) 

433 else: 

434 columns.append(utils.OutputColumn( 

435 label = column, 

436 sources = (column,), 

437 encoded = False)) 

438 for group in self._groups: 

439 columns.extend(self._encoded_outputs(group.name, group.members)) 

440 return columns 

441 

442 """ Public Methods """ 

443 

444 def get_mapping( 

445 self, 

446 column: Any = None) -> dict[Any, pd.DataFrame] | pd.DataFrame: 

447 """Returns tables of each category's encoded values. 

448 

449 Each table is indexed by a column's categories as they appear in the 

450 data (a missing value seen in fitting is its own category, NaN, and 

451 categories lumped by `min_group_size` appear as their group). Its 

452 columns are the output columns that `transform` makes from that 

453 column, with the same names: one value column per modeled class and, 

454 if `return_uncertainty` is True, their standard errors and the 

455 category's number of training rows. Unless `handle_unknown` or 

456 `handle_missing` is 'error', a row labeled '<unknown>' gives the 

457 encoding of a category not seen in fitting, and a row labeled 

458 '<missing>' the encoding of a missing value if none were seen in 

459 fitting. 

460 

461 Args: 

462 column: an encoded column (or the name of an interaction or 

463 composite column), or None for every one. 

464 

465 Raises: 

466 KeyError: if `column` is not an encoded column. 

467 

468 Returns: 

469 The table for `column`, or a dict of every encoded column's 

470 table. 

471 

472 """ 

473 check_is_fitted(self, 'mapping_') 

474 if column is None: 

475 return { 

476 name: self._lookup_table(name) 

477 for name in self._encoded_columns} 

478 if column not in self._encoded_columns: 

479 raise KeyError( 

480 f'{column!r} is not an encoded column. The encoded columns ' 

481 f'are {self._encoded_columns}.') 

482 return self._lookup_table(column) 

483 

484 def inverse_transform(self, X: Any) -> pd.DataFrame | np.ndarray: 

485 """Converts encoded data back to its categories. 

486 

487 Each row's encoded values for a column are matched to the category 

488 with the same values (see `get_mapping`). This works for the output 

489 of `transform` without `y`. It cannot recover training rows encoded 

490 by `fit_transform` (or `transform` with `y`), which are cross-fitted 

491 and so have values that no category has, nor categories that were 

492 unknown in fitting or lumped by `min_group_size` (which come back as 

493 their group). Values that match no category, or more than one, come 

494 back missing, with a warning. Columns that `composite_cols` dropped 

495 are recovered from their composite column. 

496 

497 Args: 

498 X: encoded data, with the columns that `transform` returns. 

499 

500 Raises: 

501 ValueError: if `X` does not have the columns that `transform` 

502 returns, or if `drop_invariant` dropped an encoded column's 

503 values. 

504 

505 Returns: 

506 The data with its original columns: categories for the encoded 

507 columns, and the other columns unchanged. 

508 

509 """ 

510 check_is_fitted(self, 'mapping_') 

511 dropped = set(self.invariant_cols_) 

512 lost = [ 

513 output.label for output in self._output_spec 

514 if output.label in dropped and output.role == 'value'] 

515 if lost: 

516 raise ValueError( 

517 'inverse_transform cannot recover columns whose values ' 

518 f'drop_invariant dropped: {lost}') 

519 labels = [ 

520 output.label for output in self._output_spec 

521 if output.label not in dropped] 

522 frame = self._inverse_input(X, labels) 

523 decoded: dict[Any, pd.Series] = {} 

524 for group in self._groups: 

525 decoded[group.name] = self._decode(group.name, frame) 

526 result: dict[Hashable, Any] = {} 

527 for column in self._columns: 

528 if column in frame.columns and column not in self.cols_: 

529 values = frame[column] 

530 elif column in self.cols_: 

531 values = self._decode(column, frame) 

532 else: 

533 values = self._split_member(column, decoded) 

534 result[column] = self._restore_dtype(column, values) 

535 output = pd.DataFrame(result, index = frame.index) 

536 if self.return_df: 

537 return output 

538 return output.to_numpy() 

539 

540 """ Private Methods """ 

541 

542 def _add_groups(self, X: pd.DataFrame) -> pd.DataFrame: 

543 """Adds the interaction and composite columns to `X`. 

544 

545 Each is its members' values as text joined by '|' (missing if any 

546 member is missing), made with `category_encoders`' own joining. 

547 

548 Args: 

549 X: validated data. 

550 

551 Raises: 

552 ValueError: if '|' in the data makes different combinations of 

553 values join to the same text. 

554 

555 Returns: 

556 `X` with a column for each interaction and composite column. 

557 

558 """ 

559 if not self._groups: 

560 return X 

561 X = X.copy() 

562 for group in self._groups: 

563 X[group.name] = ce_utils.BaseEncoder._join_composite( 

564 X, group.members, group.name).astype(object) 

565 return X 

566 

567 def _apply_lumping(self, X: pd.DataFrame) -> pd.DataFrame: 

568 """Replaces categories lumped by `min_group_size` with their group. 

569 

570 Args: 

571 X: data with the encoded columns. 

572 

573 Returns: 

574 `X` (copied if anything changed) with lumped categories replaced. 

575 

576 """ 

577 if not self.min_group_lumping_: 

578 return X 

579 X = X.copy() 

580 for column, lumping in self.min_group_lumping_.items(): 

581 # As in `category_encoders`, None and NaN are one missing group. 

582 values = X[column].astype(object).where(X[column].notna(), np.nan) 

583 X[column] = values.map(lumping).fillna(values).astype(object) 

584 return X 

585 

586 def _build_groups(self, X: pd.DataFrame) -> list[_Group]: 

587 """Checks `interactions` and `composite_cols` and returns the groups. 

588 

589 Args: 

590 X: validated training data. 

591 

592 Raises: 

593 TypeError: if `interactions` or `composite_cols` is not a list or 

594 tuple. 

595 ValueError: if a group is not a sequence of at least two columns 

596 of `X`, or its name is already a column of `X`. 

597 

598 Returns: 

599 The interactions, then the composite columns. 

600 

601 """ 

602 groups: list[_Group] = [] 

603 taken = set(X.columns) 

604 for parameter, composite in ( 

605 ('interactions', False), 

606 ('composite_cols', True)): 

607 value = getattr(self, parameter) 

608 if not value: 

609 continue 

610 if not isinstance(value, (list, tuple)): 

611 raise TypeError( 

612 f'{parameter} must be a list of tuples of column names, ' 

613 f"such as [('state', 'county')], not {value!r}") 

614 for members in value: 

615 if ( 

616 isinstance(members, str) 

617 or not isinstance(members, (list, tuple)) 

618 or len(members) < _MIN_MEMBERS): 

619 raise ValueError( 

620 f'Each group in {parameter} must be a sequence of at ' 

621 f'least two columns, not {members!r}') 

622 missing = [member for member in members if member not in X] 

623 if missing: 

624 raise ValueError( 

625 f'X does not contain the {parameter} columns ' 

626 f'{missing}') 

627 name = '|'.join(str(member) for member in members) 

628 if name in taken: 

629 raise ValueError( 

630 f'The {parameter} name {name!r} is already a column') 

631 taken.add(name) 

632 groups.append(_Group( 

633 name = name, 

634 members = tuple(members), 

635 composite = composite)) 

636 return groups 

637 

638 def _category_rows( 

639 self, 

640 column: Any) -> tuple[list[Any], np.ndarray, np.ndarray]: 

641 """Returns a column's categories, their codes, and which are real. 

642 

643 Args: 

644 column: an encoded column (or combined column) name. 

645 

646 Returns: 

647 The category labels (with '<missing>' and '<unknown>' rows for 

648 missing values not seen in fitting and unknown categories, when 

649 they have an encoding), their ordinal codes, and whether each is 

650 a category seen in fitting. 

651 

652 """ 

653 ordinal = self._ordinal_mapping(column) 

654 seen = ordinal[ordinal > 0] 

655 labels: list[Any] = list(seen.index) 

656 codes = list(seen.to_numpy()) 

657 real = [True] * len(labels) 

658 index = self._values[column].index 

659 if ( 

660 ce_utils.MISSING_SENTINEL in index 

661 and not seen.index.isna().any()): 

662 labels.append(_MISSING_LABEL) 

663 codes.append(ce_utils.MISSING_SENTINEL) 

664 real.append(False) 

665 if ce_utils.UNKNOWN_SENTINEL in index: 

666 labels.append(_UNKNOWN_LABEL) 

667 codes.append(ce_utils.UNKNOWN_SENTINEL) 

668 real.append(False) 

669 return ( 

670 labels, 

671 np.asarray(codes, dtype = np.int64), 

672 np.asarray(real, dtype = bool)) 

673 

674 def _class_indices(self, y: pd.Series) -> np.ndarray: 

675 """Returns each outcome's index in `classes_`. 

676 

677 Args: 

678 y: outcome with the values in `classes_`. 

679 

680 Raises: 

681 ValueError: if `y` has values not in `classes_`. 

682 

683 Returns: 

684 The index of each row's class. 

685 

686 """ 

687 values = y.to_numpy() 

688 if not np.isin(values, self.classes_).all(): 

689 raise ValueError( 

690 f'y has values other than the fitted classes {self.classes_}') 

691 indices: np.ndarray = np.searchsorted(self.classes_, values) 

692 return indices 

693 

694 def _codes(self, X_ordinal: pd.DataFrame) -> np.ndarray: 

695 """Returns the ordinal codes of the encoded columns. 

696 

697 Args: 

698 X_ordinal: data transformed by `ordinal_encoder_`. 

699 

700 Returns: 

701 Integer codes with one column per encoded column. 

702 

703 """ 

704 return X_ordinal[self._encoded_columns].to_numpy(dtype = np.int64) 

705 

706 def _cross_fit( 

707 self, 

708 codes: np.ndarray, 

709 y: pd.Series) -> tuple[np.ndarray, np.ndarray]: 

710 """Encodes each row with a model fit on the other folds. 

711 

712 Categories not in a fold's training rows get that fold's prior. 

713 Categories that `mapping_` encodes as missing (because of 

714 `handle_missing` or `handle_unknown`) stay missing. If the rarest 

715 class has fewer rows than two folds need, the rows are encoded with 

716 the model fit on all of the training data instead. 

717 

718 Args: 

719 codes: ordinal codes of the training data's encoded columns. 

720 y: outcome of the training data. 

721 

722 Returns: 

723 The values and standard errors (NaN unless `return_uncertainty` 

724 is True), each with one row per row of `codes`, one column per 

725 encoded column, and one layer per modeled class. 

726 

727 """ 

728 target = self._class_indices(y) 

729 smallest = int(np.bincount(target, minlength = self.classes_.size) 

730 .min()) 

731 n_splits = min(int(self.cv or 0), smallest) 

732 if n_splits < _MIN_FOLDS: 

733 return self._look_up(codes) 

734 splitter = StratifiedKFold( 

735 n_splits = n_splits, 

736 shuffle = True, 

737 random_state = self.random_state) 

738 folds = list(splitter.split(codes, target)) 

739 settings = self._settings() 

740 results = Parallel(n_jobs = self.n_jobs)( 

741 delayed(_encode_fold)( 

742 codes = codes, 

743 target = target, 

744 train = train, 

745 test = test, 

746 settings = settings) 

747 for train, test in folds) 

748 shape = (*codes.shape, self.modeled_classes_.size) 

749 values = np.empty(shape) 

750 errors = np.empty(shape) 

751 for (_, test), (fold_values, fold_errors) in zip( 

752 folds, results, strict = True): 

753 values[test] = fold_values 

754 errors[test] = fold_errors 

755 full_values, _ = self._look_up(codes) 

756 missing = np.isnan(full_values) 

757 values[missing] = np.nan 

758 errors[missing] = np.nan 

759 return values, errors 

760 

761 def _decode(self, column: Any, frame: pd.DataFrame) -> pd.Series: 

762 """Matches one column's encoded values to its categories. 

763 

764 Args: 

765 column: an encoded column (or combined column) name. 

766 frame: encoded data with the column's value columns. 

767 

768 Returns: 

769 Each row's category, or NaN where the values are missing, match 

770 no category, or match more than one (with a warning for the last 

771 two). 

772 

773 """ 

774 labels, codes, real = self._category_rows(column) 

775 categories = np.asarray(labels, dtype = object)[real] 

776 targets, _ = self._look_up_column(column, codes[real]) 

777 value_labels = [ 

778 output.label for output in self._output_spec 

779 if output.encoded and output.role == 'value' 

780 and self._source_name(output.sources) == column] 

781 observed = frame[value_labels].to_numpy(dtype = np.float64) 

782 n_rows = observed.shape[0] 

783 matches = np.zeros(n_rows, dtype = np.int64) 

784 first = np.zeros(n_rows, dtype = np.int64) 

785 block = max(1, _MAX_BLOCK_CELLS // max(1, targets.size)) 

786 for start in range(0, n_rows, block): 

787 rows = observed[start:start + block] 

788 close = np.isclose( 

789 rows[:, None, :], 

790 targets[None, :, :], 

791 rtol = _MATCH_RTOL, 

792 atol = _MATCH_ATOL).all(axis = 2) 

793 matches[start:start + block] = close.sum(axis = 1) 

794 first[start:start + block] = close.argmax(axis = 1) 

795 decoded = np.full(n_rows, np.nan, dtype = object) 

796 single = matches == 1 

797 decoded[single] = categories[first[single]] 

798 missing = np.isnan(observed).any(axis = 1) 

799 ambiguous = int((matches > 1).sum()) 

800 unmatched = int(((matches == 0) & ~missing).sum()) 

801 if ambiguous: 

802 warnings.warn( 

803 f'{ambiguous} rows of {column!r} match more than one ' 

804 'category (whose encoded values are the same) and were set ' 

805 'to missing.', 

806 UserWarning, 

807 stacklevel = 3) 

808 if unmatched: 

809 warnings.warn( 

810 f'{unmatched} rows of {column!r} match no category and were ' 

811 'set to missing. They may be unknown categories or ' 

812 'cross-fitted training rows.', 

813 UserWarning, 

814 stacklevel = 3) 

815 return pd.Series(decoded, index = frame.index) 

816 

817 def _encoded_outputs( 

818 self, 

819 label: Any, 

820 sources: tuple[Any, ...]) -> list[utils.OutputColumn]: 

821 """Returns the output columns of one encoded column. 

822 

823 Args: 

824 label: the encoded column's label. 

825 sources: the input columns it is made from. 

826 

827 Returns: 

828 Its value columns, then (if `return_uncertainty` is True) its 

829 standard error columns and count column. 

830 

831 """ 

832 if self.modeled_classes_.size == 1: 

833 class_suffixes = [''] 

834 else: 

835 class_suffixes = [f'_{name}' for name in self.modeled_classes_] 

836 roles = [ 

837 ('value', index, suffix) 

838 for index, suffix in enumerate(class_suffixes)] 

839 if self.return_uncertainty: 

840 roles += [ 

841 ('se', index, f'{suffix}_se') 

842 for index, suffix in enumerate(class_suffixes)] 

843 roles.append(('count', 0, '_count')) 

844 return [ 

845 utils.OutputColumn( 

846 label = label if suffix == '' else f'{label}{suffix}', 

847 sources = sources, 

848 suffix = suffix, 

849 role = role, 

850 class_index = index) 

851 for role, index, suffix in roles] 

852 

853 def _fit_encodings( 

854 self, 

855 codes: np.ndarray, 

856 target: np.ndarray) -> _logit_models.LogitEncodings: 

857 """Fits the logit models, in parallel for univariate models. 

858 

859 Args: 

860 codes: ordinal codes of the encoded columns. 

861 target: index of each row's class. 

862 

863 Returns: 

864 The encodings of every encoded column. 

865 

866 """ 

867 settings = self._settings() 

868 if self.model != 'univariate' or codes.shape[1] <= 1: 

869 return settings.fit(codes = codes, target = target) 

870 results = Parallel(n_jobs = self.n_jobs)( 

871 delayed(settings.fit)(codes = codes[:, [column]], target = target) 

872 for column in range(codes.shape[1])) 

873 return _logit_models.LogitEncodings( 

874 columns = [result.columns[0] for result in results], 

875 n_iter = max(result.n_iter for result in results)) 

876 

877 def _fit_lumping(self, X: pd.DataFrame) -> dict[Any, dict[Any, Any]]: 

878 """Finds the categories that `min_group_size` lumps together. 

879 

880 Uses `category_encoders`' own rule (`build_min_group_map`), so the 

881 groups are the same as its encoders'. 

882 

883 Args: 

884 X: training data with the encoded columns. 

885 

886 Returns: 

887 For each encoded column with lumped categories, the group that 

888 each lumped category joins. 

889 

890 """ 

891 if self.min_group_size is None: 

892 return {} 

893 threshold = float(self.min_group_size) 

894 if isinstance(self.min_group_size, float): 

895 threshold = self.min_group_size * len(X) 

896 combine = ( 

897 True if self.combine_min_nan_groups is None 

898 else self.combine_min_nan_groups) 

899 lumping: dict[Any, dict[Any, Any]] = {} 

900 for column in self._encoded_columns: 

901 sizes = X[column].astype(object).where( 

902 X[column].notna(), np.nan).value_counts(dropna = False) 

903 _, groups = ce_utils.build_min_group_map( 

904 sizes, threshold, self.min_group_name, combine) 

905 if groups: 905 ↛ 900line 905 didn't jump to line 900 because the condition on line 905 was always true

906 lumping[column] = groups 

907 return lumping 

908 

909 def _finalize_errors( 

910 self, 

911 errors: pd.DataFrame, 

912 ordinal: pd.Series, 

913 prior_error: np.ndarray) -> pd.DataFrame: 

914 """Adds the standard errors of missing and unknown categories. 

915 

916 Args: 

917 errors: standard errors of the categories seen in fitting. 

918 ordinal: the column's mapping from categories to ordinal codes. 

919 prior_error: standard error of a category with no rows. 

920 

921 Returns: 

922 `errors` with rows for unknown and unseen missing categories: the 

923 prior's error where they get the prior, and NaN otherwise. 

924 

925 """ 

926 unknown = prior_error if self.handle_unknown == 'value' else np.nan 

927 errors.loc[ce_utils.UNKNOWN_SENTINEL] = unknown 

928 missing = prior_error if self.handle_missing == 'value' else np.nan 

929 errors.loc[ce_utils.MISSING_SENTINEL] = missing 

930 if self.handle_missing == 'return_nan': 930 ↛ 931line 930 didn't jump to line 931 because the condition on line 930 was never true

931 nan_codes = ordinal[ordinal.index.isna()] 

932 errors.loc[nan_codes.to_numpy()] = np.nan 

933 return errors 

934 

935 def _inverse_input(self, X: Any, labels: list[Any]) -> pd.DataFrame: 

936 """Checks the input of `inverse_transform` and makes it a DataFrame. 

937 

938 Args: 

939 X: encoded data, as a DataFrame or two-dimensional array. 

940 labels: the columns that `transform` returns. 

941 

942 Raises: 

943 ValueError: if `X` does not have those columns. 

944 

945 Returns: 

946 `X` as a DataFrame with those columns. 

947 

948 """ 

949 if isinstance(X, pd.DataFrame): 

950 missing = [label for label in labels if label not in X.columns] 

951 if missing: 

952 raise ValueError( 

953 f'X is missing the transformed columns {missing}') 

954 return X 

955 array = np.asarray(X, dtype = object) 

956 if array.ndim != 2 or array.shape[1] != len(labels): # noqa: PLR2004 

957 raise ValueError( 

958 f'X must have the {len(labels)} columns that transform ' 

959 f'returns, not shape {array.shape}') 

960 return pd.DataFrame(array, columns = labels) 

961 

962 def _look_up(self, codes: np.ndarray) -> tuple[np.ndarray, np.ndarray]: 

963 """Encodes ordinal codes with the model fit on all of the data. 

964 

965 Args: 

966 codes: ordinal codes of the encoded columns. 

967 

968 Returns: 

969 The values and standard errors (NaN unless `return_uncertainty` 

970 is True), each with one row per row of `codes`, one column per 

971 encoded column, and one layer per modeled class. 

972 

973 """ 

974 shape = (*codes.shape, self.modeled_classes_.size) 

975 values = np.full(shape, np.nan) 

976 errors = np.full(shape, np.nan) 

977 for position, column in enumerate(self._encoded_columns): 

978 values[:, position], errors[:, position] = self._look_up_column( 

979 column, codes[:, position]) 

980 return values, errors 

981 

982 def _look_up_column( 

983 self, 

984 column: Any, 

985 codes: np.ndarray) -> tuple[np.ndarray, np.ndarray]: 

986 """Encodes one column's ordinal codes with the model fit on all data. 

987 

988 Args: 

989 column: the encoded column (or combined column) name. 

990 codes: the column's ordinal codes. 

991 

992 Returns: 

993 The values and standard errors (NaN unless `return_uncertainty` 

994 is True), with one row per code and one column per modeled 

995 class. Codes without a mapping are NaN. 

996 

997 """ 

998 shape = (codes.size, self.modeled_classes_.size) 

999 values = np.full(shape, np.nan) 

1000 errors = np.full(shape, np.nan) 

1001 frame = self._values[column] 

1002 locations = frame.index.get_indexer(pd.Index(codes)) 

1003 found = locations >= 0 

1004 values[found] = frame.to_numpy()[locations[found]] 

1005 error_frame = self._errors.get(column) 

1006 if error_frame is not None: 

1007 errors[found] = error_frame.to_numpy()[locations[found]] 

1008 return values, errors 

1009 

1010 def _lookup_table(self, column: Any) -> pd.DataFrame: 

1011 """Makes one column's table for `get_mapping`. 

1012 

1013 Args: 

1014 column: an encoded column (or combined column) name. 

1015 

1016 Returns: 

1017 The column's categories with their encoded values (and, if 

1018 `return_uncertainty` is True, standard errors and counts). 

1019 

1020 """ 

1021 labels, codes, _ = self._category_rows(column) 

1022 values, errors = self._look_up_column(column, codes) 

1023 data = { 

1024 output.label: self._output_values( 

1025 output = output, 

1026 codes = codes, 

1027 values = values, 

1028 errors = errors) 

1029 for output in self._output_spec 

1030 if output.encoded and self._source_name(output.sources) == column} 

1031 index = pd.Index(labels, dtype = object, name = 'category') 

1032 return pd.DataFrame(data, index = index) 

1033 

1034 def _ordinal_mapping(self, column: Any) -> pd.Series: 

1035 """Returns a column's mapping from categories to ordinal codes. 

1036 

1037 Args: 

1038 column: an encoded column (or combined column) name. 

1039 

1040 Returns: 

1041 The fitted `ordinal_encoder_`'s mapping for `column`. 

1042 

1043 """ 

1044 for switch in cast( 1044 ↛ 1049line 1044 didn't jump to line 1049 because the loop on line 1044 didn't complete

1045 'list[dict[str, Any]]', 

1046 self.ordinal_encoder_.category_mapping): 

1047 if switch['col'] == column: 

1048 return cast('pd.Series', switch['mapping']) 

1049 raise KeyError(column) 

1050 

1051 def _output_values( 

1052 self, 

1053 output: utils.OutputColumn, 

1054 codes: np.ndarray, 

1055 values: np.ndarray, 

1056 errors: np.ndarray) -> np.ndarray: 

1057 """Returns one output column's values. 

1058 

1059 Args: 

1060 output: the output column. 

1061 codes: ordinal codes of the column it comes from. 

1062 values: encoded values, with one column per modeled class. 

1063 errors: standard errors, with one column per modeled class. 

1064 

1065 Returns: 

1066 The counts, standard errors, or values that `output` holds. 

1067 

1068 """ 

1069 if output.role == 'count': 

1070 name = self._source_name(output.sources) 

1071 counts: np.ndarray = self._counts[name].reindex(codes).fillna( 

1072 0.0).to_numpy(dtype = np.float64) 

1073 return counts 

1074 if output.role == 'se': 

1075 return errors[:, output.class_index] 

1076 return values[:, output.class_index] 

1077 

1078 def _own_columns(self, X: pd.DataFrame) -> list[Any]: 

1079 """Returns the input columns that are encoded on their own. 

1080 

1081 These are the columns that `cols` selects, without the members of 

1082 `composite_cols` unless `keep_components` is True, in which case all 

1083 of the members are encoded on their own, as in `category_encoders`. 

1084 

1085 Args: 

1086 X: validated training data. 

1087 

1088 Returns: 

1089 The columns, in the order of `X`. 

1090 

1091 """ 

1092 selected = set(self.cols_) 

1093 members = { 

1094 member 

1095 for group in self._groups if group.composite 

1096 for member in group.members} 

1097 if self.keep_components: 

1098 selected |= members 

1099 else: 

1100 selected -= members 

1101 return [column for column in X.columns if column in selected] 

1102 

1103 def _restore_dtype(self, column: Any, values: pd.Series) -> pd.Series: 

1104 """Converts recovered values back to their column's original dtype. 

1105 

1106 Args: 

1107 column: an input column. 

1108 values: its recovered values. 

1109 

1110 Returns: 

1111 `values` with the column's dtype from fitting, or unchanged if 

1112 they cannot be converted (such as integers with missing values). 

1113 

1114 """ 

1115 dtype = self._dtypes.get(column) 

1116 if dtype is None: 1116 ↛ 1117line 1116 didn't jump to line 1117 because the condition on line 1116 was never true

1117 return values 

1118 try: 

1119 return values.astype(dtype) 

1120 except (TypeError, ValueError): 

1121 return values 

1122 

1123 def _set_classes(self, y: pd.Series) -> None: 

1124 """Stores the outcome's classes and chooses the reference class. 

1125 

1126 Args: 

1127 y: training outcome. 

1128 

1129 Raises: 

1130 ValueError: if `y` is continuous or has fewer than two classes. 

1131 

1132 """ 

1133 if type_of_target(y.to_numpy()) == 'continuous': 

1134 raise ValueError( 

1135 'LogitEncoder needs a categorical outcome (binary or ' 

1136 'multiclass), but y is continuous. Use a target encoder for ' 

1137 'a continuous outcome.') 

1138 self.classes_ = np.unique(y.to_numpy()) 

1139 if self.classes_.size < _MIN_CLASSES: 

1140 plural = '' if self.classes_.size == 1 else 'es' 

1141 raise ValueError( 

1142 'LogitEncoder needs an outcome with at least two classes, ' 

1143 f'but y has {self.classes_.size} class{plural}.') 

1144 if self.classes_.size == _MIN_CLASSES: 

1145 reference = 0 

1146 else: 

1147 counts = pd.Series(y.to_numpy()).value_counts() 

1148 reference = int(np.searchsorted( 

1149 self.classes_, 

1150 counts[counts == counts.max()].index.min())) 

1151 self._reference_index = reference 

1152 self.reference_class_ = self.classes_[reference] 

1153 self.modeled_classes_ = np.delete(self.classes_, reference) 

1154 

1155 def _settings(self) -> _ModelSettings: 

1156 """Returns the encoder's model settings. 

1157 

1158 Returns: 

1159 The settings that `_logit_models.fit_encodings` needs. 

1160 

1161 """ 

1162 return _ModelSettings( 

1163 encoding = self.encoding, 

1164 model = self.model, 

1165 backend = self.backend, 

1166 C = self.C, 

1167 l1_ratio = self.l1_ratio, 

1168 reference = self.reference, 

1169 max_iter = self.max_iter, 

1170 reference_class = self._reference_index, 

1171 n_classes = self.classes_.size, 

1172 uncertainty = bool(self.return_uncertainty)) 

1173 

1174 def _source_name(self, sources: tuple[Any, ...]) -> Any: 

1175 """Returns the encoded column that an output column comes from. 

1176 

1177 Args: 

1178 sources: the output column's input columns. 

1179 

1180 Returns: 

1181 The input column, or the combined column's name for several. 

1182 

1183 """ 

1184 if len(sources) == 1: 

1185 return sources[0] 

1186 return '|'.join(str(source) for source in sources) 

1187 

1188 def _split_member( 

1189 self, 

1190 column: Any, 

1191 decoded: dict[Any, pd.Series]) -> pd.Series: 

1192 """Recovers a composite member that is not in the output. 

1193 

1194 Args: 

1195 column: a member of a composite column. 

1196 decoded: each combined column's recovered categories. 

1197 

1198 Raises: 

1199 ValueError: if `column` is not a member of a composite column. 

1200 

1201 Returns: 

1202 The member's values, split from its composite column's 

1203 categories (as text). 

1204 

1205 """ 

1206 for group in self._groups: 1206 ↛ 1213line 1206 didn't jump to line 1213 because the loop on line 1206 didn't complete

1207 if group.composite and column in group.members: 1207 ↛ 1206line 1207 didn't jump to line 1206 because the condition on line 1207 was always true

1208 position = group.members.index(column) 

1209 combined = decoded[group.name] 

1210 return combined.map( 

1211 lambda value, at = position: value.split('|')[at] 

1212 if isinstance(value, str) else np.nan) 

1213 raise ValueError(f'Cannot recover the column {column!r}') 

1214 

1215 def _store_mappings(self, encodings: _logit_models.LogitEncodings) -> None: 

1216 """Stores the fitted encodings, with missing and unknown categories. 

1217 

1218 Args: 

1219 encodings: encodings fit on all of the training data. 

1220 

1221 """ 

1222 category_mapping = cast( 

1223 'list[dict[str, Any]]', 

1224 self.ordinal_encoder_.category_mapping) 

1225 self._values: dict[Any, pd.DataFrame] = {} 

1226 self._errors: dict[Any, pd.DataFrame | None] = {} 

1227 self._counts: dict[Any, pd.Series] = {} 

1228 self.mapping_: dict[Any, pd.Series | pd.DataFrame] = {} 

1229 if self.return_uncertainty: 

1230 self.error_mapping_: dict[Any, pd.Series | pd.DataFrame] = {} 

1231 self.count_mapping_: dict[Any, pd.Series] = {} 

1232 for switch, column in zip( 

1233 category_mapping, 

1234 encodings.columns, 

1235 strict = True): 

1236 name = switch['col'] 

1237 ordinal = switch['mapping'] 

1238 values = cast('pd.DataFrame', ce_utils.finalize_encoding_mapping( 

1239 column.estimates.copy(), 

1240 ordinal, 

1241 self.handle_unknown, 

1242 self.handle_missing, 

1243 cast('Any', column.prior))) 

1244 self._values[name] = values 

1245 self.mapping_[name] = self._public(values) 

1246 sentinels = [ 

1247 sentinel 

1248 for sentinel in ( 

1249 ce_utils.UNKNOWN_SENTINEL, 

1250 ce_utils.MISSING_SENTINEL) 

1251 if sentinel not in column.counts.index] 

1252 counts = pd.concat( 

1253 [column.counts, pd.Series(0.0, index = sentinels)]) 

1254 self._counts[name] = counts 

1255 errors = None 

1256 if column.errors is not None and column.prior_error is not None: 

1257 errors = self._finalize_errors( 

1258 errors = column.errors.copy(), 

1259 ordinal = ordinal, 

1260 prior_error = column.prior_error) 

1261 self.error_mapping_[name] = self._public(errors) 

1262 self.count_mapping_[name] = counts 

1263 self._errors[name] = errors 

1264 

1265 def _public(self, frame: pd.DataFrame) -> pd.Series | pd.DataFrame: 

1266 """Returns a mapping in its public form. 

1267 

1268 Args: 

1269 frame: values with one column per modeled class. 

1270 

1271 Returns: 

1272 A series for a binary outcome, or a DataFrame whose columns are 

1273 the modeled classes. 

1274 

1275 """ 

1276 if self.modeled_classes_.size == 1: 

1277 return frame.iloc[:, 0].rename(None) 

1278 public = frame.copy() 

1279 public.columns = list(self.modeled_classes_) 

1280 return public 

1281 

1282 def _validate_parameters(self) -> None: 

1283 """Checks the encoder's logit-specific and lumping parameters. 

1284 

1285 Raises: 

1286 ValueError: if a parameter has an invalid value. 

1287 

1288 """ 

1289 choices: dict[str, tuple[str | None, ...]] = { 

1290 'encoding': _logit_models.ENCODINGS, 

1291 'model': _logit_models.MODELS, 

1292 'backend': _logit_models.BACKENDS, 

1293 'reference': _logit_models.REFERENCES} 

1294 for name, options in choices.items(): 

1295 if getattr(self, name) not in options: 

1296 raise ValueError( 

1297 f'{name} must be one of {options}, not ' 

1298 f'{getattr(self, name)!r}') 

1299 if self.C is not None and not ( 

1300 _is_number(self.C) and self.C > 0): 

1301 raise ValueError(f'C must be positive or None, not {self.C!r}') 

1302 if not (_is_number(self.l1_ratio) and 0 <= self.l1_ratio <= 1): 

1303 raise ValueError( 

1304 f'l1_ratio must be from 0 to 1, not {self.l1_ratio!r}') 

1305 if self.cv is not None and ( 

1306 isinstance(self.cv, bool) 

1307 or not isinstance(self.cv, (int, np.integer)) 

1308 or self.cv < _MIN_FOLDS): 

1309 raise ValueError( 

1310 f'cv must be an integer of at least 2 or None, not ' 

1311 f'{self.cv!r}') 

1312 if ( 

1313 isinstance(self.max_iter, bool) 

1314 or not isinstance(self.max_iter, (int, np.integer)) 

1315 or self.max_iter < 1): 

1316 raise ValueError( 

1317 f'max_iter must be a positive integer, not {self.max_iter!r}') 

1318 self._validate_lumping_parameters() 

1319 

1320 def _validate_lumping_parameters(self) -> None: 

1321 """Checks the `min_group_size` parameters, as `category_encoders` does. 

1322 

1323 Raises: 

1324 ValueError: if a lumping parameter has an invalid value or they 

1325 conflict. 

1326 

1327 """ 

1328 if self.min_group_size is not None and not ( 

1329 _is_number(self.min_group_size) and self.min_group_size > 0): 

1330 raise ValueError( 

1331 'min_group_size must be a positive number or None, not ' 

1332 f'{self.min_group_size!r}') 

1333 if self.min_group_name is not None and self.min_group_size is None: 

1334 raise ValueError( 

1335 '`min_group_name` only works when `min_group_size` is set.') 

1336 if self.combine_min_nan_groups not in _COMBINE_OPTIONS: 

1337 raise ValueError( 

1338 "'combine_min_nan_groups' should be one of: ['force', True, " 

1339 'False, None].') 

1340 if ( 

1341 self.combine_min_nan_groups == 'force' 

1342 and self.handle_missing == 'return_nan'): 

1343 raise ValueError( 

1344 "Cannot have `handle_missing` == 'return_nan' and " 

1345 "'combine_min_nan_groups' == 'force'.") 

1346 

1347 """ Properties """ 

1348 

1349 @property 

1350 def mapping(self) -> dict[Any, pd.Series | pd.DataFrame]: 

1351 """Returns `mapping_`, under `category_encoders`' name. 

1352 

1353 Returns: 

1354 The fitted mapping from ordinal codes to encoded values. 

1355 

1356 """ 

1357 return self.mapping_ 

1358 

1359 @property 

1360 def ordinal_encoder(self) -> OrdinalEncoder: 

1361 """Returns `ordinal_encoder_`, under `category_encoders`' name. 

1362 

1363 Returns: 

1364 The fitted ordinal encoder. 

1365 

1366 """ 

1367 return self.ordinal_encoder_ 

1368 

1369 @property 

1370 def _encoded_columns(self) -> list[Any]: 

1371 """Returns every column that is encoded, including combined columns. 

1372 

1373 Returns: 

1374 `cols_` followed by the interaction and composite columns. 

1375 

1376 """ 

1377 return [*self.cols_, *(group.name for group in self._groups)] 

1378 

1379 

1380@dataclasses.dataclass(frozen = True) 

1381class _ModelSettings: 

1382 """Settings for fitting the logit models and choosing the encoding. 

1383 

1384 A small frozen dataclass is sent to parallel jobs instead of the encoder 

1385 so that the jobs do not copy the encoder's fitted state. 

1386 

1387 Args: 

1388 encoding: one of `_logit_models.ENCODINGS`. 

1389 model: one of `_logit_models.MODELS`. 

1390 backend: one of `_logit_models.BACKENDS`. 

1391 C: inverse strength of the penalty, or None for no penalty. 

1392 l1_ratio: share of the penalty that is L1 rather than L2. 

1393 reference: one of `_logit_models.REFERENCES`. 

1394 max_iter: largest number of solver iterations. 

1395 reference_class: index of the reference class. 

1396 n_classes: number of classes of the outcome. 

1397 uncertainty: whether to compute standard errors. 

1398 

1399 """ 

1400 

1401 encoding: _logit_models.Encoding 

1402 model: _logit_models.Model 

1403 backend: _logit_models.Backend 

1404 C: float | None 

1405 l1_ratio: float 

1406 reference: _logit_models.Reference 

1407 max_iter: int 

1408 reference_class: int 

1409 n_classes: int 

1410 uncertainty: bool 

1411 

1412 """ Public Methods """ 

1413 

1414 def fit( 

1415 self, 

1416 codes: np.ndarray, 

1417 target: np.ndarray) -> _logit_models.LogitEncodings: 

1418 """Fits the logit models on `codes` and `target`. 

1419 

1420 Args: 

1421 codes: ordinal codes with one column per encoded column. 

1422 target: index of each row's class. 

1423 

1424 Returns: 

1425 The encodings of every column of `codes`. 

1426 

1427 """ 

1428 return _logit_models.fit_encodings( 

1429 codes = codes, 

1430 target = target, 

1431 reference_class = self.reference_class, 

1432 n_classes = self.n_classes, 

1433 encoding = self.encoding, 

1434 model = self.model, 

1435 backend = self.backend, 

1436 C = self.C, 

1437 l1_ratio = self.l1_ratio, 

1438 reference = self.reference, 

1439 max_iter = self.max_iter, 

1440 uncertainty = self.uncertainty) 

1441 

1442 

1443def _is_number(value: Any) -> bool: 

1444 """Returns whether `value` is a real number (and not a boolean). 

1445 

1446 Args: 

1447 value: value to check. 

1448 

1449 Returns: 

1450 Whether `value` is an int or float (of Python or numpy) other than a 

1451 boolean. 

1452 

1453 """ 

1454 return isinstance(value, numbers.Real) and not isinstance( 

1455 value, (bool, np.bool_)) 

1456 

1457 

1458def _encode_fold( 

1459 *, 

1460 codes: np.ndarray, 

1461 target: np.ndarray, 

1462 train: np.ndarray, 

1463 test: np.ndarray, 

1464 settings: _ModelSettings) -> tuple[np.ndarray, np.ndarray]: 

1465 """Encodes one fold's rows with a model fit on the other folds. 

1466 

1467 Args: 

1468 codes: ordinal codes of every training row. 

1469 target: index of every training row's class. 

1470 train: indices of the rows to fit the model on. 

1471 test: indices of the rows to encode. 

1472 settings: model settings. 

1473 

1474 Returns: 

1475 The values and standard errors (NaN if they were not computed) of the 

1476 `test` rows, with one column per column of `codes` and one layer per 

1477 modeled class. Categories not in the `train` rows get the prior. 

1478 

1479 """ 

1480 encodings = settings.fit(codes = codes[train], target = target[train]) 

1481 shape = (test.size, codes.shape[1], settings.n_classes - 1) 

1482 values = np.empty(shape) 

1483 errors = np.full(shape, np.nan) 

1484 for position, column in enumerate(encodings.columns): 

1485 locations = column.estimates.index.get_indexer( 

1486 pd.Index(codes[test, position])) 

1487 found = locations >= 0 

1488 values[:, position] = column.prior 

1489 values[found, position] = column.estimates.to_numpy()[ 

1490 locations[found]] 

1491 if column.errors is not None and column.prior_error is not None: 1491 ↛ 1492line 1491 didn't jump to line 1492 because the condition on line 1491 was never true

1492 errors[:, position] = column.prior_error 

1493 errors[found, position] = column.errors.to_numpy()[ 

1494 locations[found]] 

1495 return values, errors