Coverage for src/logit_encode/utils.py: 97%
227 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"""Base classes for encoders, following `category_encoders.utils`.
3The classes mirror `category_encoders`' `BaseEncoder` and
4`SupervisedTransformerMixin`: the same `cols`, `drop_invariant`,
5`return_df`, `handle_missing`, and `handle_unknown` parameters, the same
6split between a public `fit`/`transform` and the `_fit`/`_transform` that
7each encoder implements, and the same convention that passing `y` to
8`transform` marks the data as training data. Unlike `category_encoders`'
9classes, they meet sklearn's estimator contract: `fit` does not change the
10parameters, fitted attributes end with an underscore, inputs are validated
11the way sklearn validates them, and the encoders pass
12`sklearn.utils.estimator_checks.check_estimator`.
14Contents:
15 BaseEncoder: base class with the parameters and fitting logic that every
16 encoder shares.
17 OutputColumn: one column of an encoder's output and where it comes from.
18 SupervisedTransformerMixin: mixin for encoders that need an outcome to
19 fit and that transform training data with it.
21"""
23from __future__ import annotations
25import abc
26import dataclasses
27import numbers
28import warnings
29from typing import Any, cast
31import numpy as np
32import pandas as pd
33from scipy import sparse
34from sklearn.base import BaseEstimator, TransformerMixin
35from sklearn.utils._tags import Tags
36from sklearn.utils.validation import (
37 _check_feature_names_in,
38 check_is_fitted,
39 validate_data,
40)
42_HANDLE_OPTIONS: tuple[str, ...] = ('error', 'return_nan', 'value')
43# Inputs are tables, and a one-column target may arrive as a table.
44_TABLE_DIMENSIONS: int = 2
47@dataclasses.dataclass(frozen = True)
48class OutputColumn:
49 """One column of an encoder's output and where it comes from.
51 Args:
52 label: the column's label in the transformed DataFrame.
53 sources: labels of the input columns it is made from (more than one
54 for a column made from a combination of columns).
55 suffix: text added after the input columns' names in
56 `get_feature_names_out`, such as '_se'.
57 encoded: whether the encoder makes the column (rather than passing
58 an input column through).
59 role: what an encoded column holds, such as 'value', 'se', or
60 'count', so that encoders never have to parse it from the label.
61 class_index: for a column that belongs to one class of the outcome,
62 the class's position among the modeled classes.
64 """
66 label: Any
67 sources: tuple[Any, ...]
68 suffix: str = ''
69 encoded: bool = True
70 role: str = 'value'
71 class_index: int = 0
74class BaseEncoder(BaseEstimator, abc.ABC):
75 """Base class with the parameters and fitting logic of every encoder.
77 Attributes:
78 cols_: the columns that were encoded.
79 invariant_cols_: the encoded columns dropped by `drop_invariant`.
80 feature_names_out_: names of the output columns, as in
81 `category_encoders`.
82 n_features_in_: number of columns seen in fitting.
83 feature_names_in_: names of the columns seen in fitting, if they
84 were all strings.
86 """
88 # Fitted state that the public methods share.
89 _columns: list[Any]
90 _dtypes: dict[Any, Any]
91 _output_spec: list[OutputColumn]
93 """ Initialization Methods """
95 def __init__( # noqa: PLR0917
96 self,
97 verbose: int = 0,
98 cols: list[Any] | str | None = None,
99 drop_invariant: bool = False,
100 return_df: bool = True,
101 handle_missing: Any = 'value',
102 handle_unknown: Any = 'value') -> None:
103 """Stores the parameters without validating them, as sklearn requires.
105 The parameters can be passed by position, in `category_encoders`'
106 order, so that the encoders are drop-in replacements.
108 Args:
109 verbose: verbosity of the output. 0 for none.
110 cols: columns to encode. If None, every object, string, and
111 categorical column is encoded, as in `category_encoders`. If
112 'all', every column is encoded.
113 drop_invariant: whether to drop encoded columns with no variance in
114 the training data.
115 return_df: whether `transform` returns a pandas DataFrame
116 (otherwise, a numpy array).
117 handle_missing: how to encode missing values: 'value', 'return_nan',
118 'error', a number, or a callable, as in `category_encoders`.
119 handle_unknown: how to encode categories not seen in fitting:
120 'value', 'return_nan', 'error', a number, or a callable, as in
121 `category_encoders`.
123 """
124 self.verbose = verbose
125 self.cols = cols
126 self.drop_invariant = drop_invariant
127 self.return_df = return_df
128 self.handle_missing = handle_missing
129 self.handle_unknown = handle_unknown
131 """ Required Methods """
133 @abc.abstractmethod
134 def _fit(self, X: pd.DataFrame, y: pd.Series | None) -> None:
135 """Fits the encoder on validated data.
137 Args:
138 X: training data, with the columns in `cols_` to encode.
139 y: training outcome, or None for unsupervised encoders.
141 """
143 @abc.abstractmethod
144 def _encode(
145 self,
146 X: pd.DataFrame,
147 y: pd.Series | None = None) -> pd.DataFrame:
148 """Encodes the columns in `cols_` of validated data.
150 Args:
151 X: data to encode. It may be changed in place.
152 y: outcome of `X` if `X` is training data, or None.
154 Returns:
155 `X` with the columns in `cols_` encoded.
157 """
159 def _output_columns(self) -> list[OutputColumn]:
160 """Returns the columns of the encoder's output, in order.
162 Encoders that make more than one column from an input column (or a
163 column from several input columns) override this. By default, each
164 input column gives one output column with the same label.
166 Returns:
167 The output columns.
169 """
170 encoded = set(self.cols_)
171 return [
172 OutputColumn(
173 label = column,
174 sources = (column,),
175 encoded = column in encoded)
176 for column in self._columns]
178 """ Public Methods """
180 def fit(self, X: Any, y: Any = None, **fit_params: Any) -> BaseEncoder:
181 """Fits the encoder.
183 Args:
184 X: training data, as a DataFrame or a two-dimensional array.
185 y: training outcome.
186 **fit_params: unused; accepted for sklearn compatibility.
188 Raises:
189 ValueError: if the inputs are invalid.
191 Returns:
192 The fitted encoder.
194 """
195 y_series = self._validate_fit_target(y)
196 X_frame = self._validate_input(X, reset = True)
197 y_series = self._align_target(y_series, X_frame)
198 self._validate_handle_strategies()
199 self.cols_ = self._select_columns(X_frame)
200 self._check_missing(X_frame)
201 self._fit(X_frame, y_series)
202 self._output_spec = self._output_columns()
203 labels = pd.Index([column.label for column in self._output_spec])
204 if labels.has_duplicates:
205 duplicates = sorted(set(labels[labels.duplicated()]), key = str)
206 raise ValueError(
207 f'The output would have duplicate columns {duplicates}. '
208 'Rename the input columns (or outcome classes) that make '
209 'them.')
210 self.invariant_cols_: list[Any] = []
211 if self.drop_invariant:
212 encoded = self._encode(X_frame.copy())
213 self.invariant_cols_ = [
214 column.label for column in self._output_spec
215 if column.encoded
216 and len(pd.unique(encoded[column.label])) <= 1]
217 self.feature_names_out_ = self.get_feature_names_out()
218 return self
220 def get_feature_names(self) -> np.ndarray:
221 """Returns the output column names (deprecated, as in sklearn).
223 Kept for code written for `category_encoders`, which also deprecates
224 it.
226 Returns:
227 The same names as `get_feature_names_out`.
229 """
230 warnings.warn(
231 '`get_feature_names` is deprecated in all of sklearn. Use '
232 '`get_feature_names_out` instead.',
233 FutureWarning,
234 stacklevel = 2)
235 return self.get_feature_names_out()
237 def get_feature_names_in(self) -> np.ndarray:
238 """Returns the names of the columns seen in fitting.
240 As in `category_encoders`, these are the DataFrame's column labels,
241 or 0, 1, ... for an array.
243 Returns:
244 The input columns' labels.
246 """
247 check_is_fitted(self, 'cols_')
248 return np.asarray(self._columns, dtype = object)
250 def get_feature_names_out(
251 self,
252 input_features: Any = None) -> np.ndarray:
253 """Returns the names of the transformed columns.
255 Args:
256 input_features: names of the input columns, or None to use the
257 output's column labels, as `category_encoders` does (the
258 input's column names, or 0, 1, ... for an array).
260 Returns:
261 The output column names, without the columns dropped by
262 `drop_invariant`.
264 """
265 check_is_fitted(self, 'cols_')
266 dropped = set(self.invariant_cols_)
267 if input_features is None:
268 # As in `category_encoders`, the names are the output's column
269 # labels (integers for an array's pass-through columns).
270 return np.asarray(
271 [column.label for column in self._output_spec
272 if column.label not in dropped],
273 dtype = object)
274 names = dict(zip(
275 self._columns,
276 _check_feature_names_in(self, input_features),
277 strict = True))
278 return np.asarray(
279 ['|'.join(str(names[source]) for source in column.sources)
280 + column.suffix
281 for column in self._output_spec if column.label not in dropped],
282 dtype = object)
284 """ Private Methods """
286 def _align_target(self, y: pd.Series, X: pd.DataFrame) -> pd.Series:
287 """Checks that `y` matches `X` and gives it `X`'s index.
289 Args:
290 y: outcome.
291 X: data that `y` belongs to.
293 Raises:
294 ValueError: if `y` and `X` have different numbers of rows.
296 Returns:
297 `y` with `X`'s index.
299 """
300 if len(y) != len(X):
301 raise ValueError(
302 'Found input variables with inconsistent numbers of samples: '
303 f'[{len(X)}, {len(y)}]')
304 return pd.Series(y.to_numpy(), index = X.index, name = y.name)
306 def _check_missing(self, X: pd.DataFrame) -> None:
307 """Raises an error for missing values if `handle_missing` is 'error'.
309 Args:
310 X: data to check.
312 Raises:
313 ValueError: if `handle_missing` is 'error' and a column to encode
314 has missing values.
316 """
317 if (
318 isinstance(self.handle_missing, str)
319 and self.handle_missing == 'error'
320 and X[self.cols_].isna().to_numpy().any()):
321 raise ValueError('Columns to be encoded cannot contain null')
323 def _finish(
324 self,
325 X: pd.DataFrame,
326 override_return_df: bool = False) -> pd.DataFrame | np.ndarray:
327 """Drops invariant columns and converts the output if needed.
329 Args:
330 X: encoded data.
331 override_return_df: whether to return a DataFrame regardless of
332 `return_df`.
334 Returns:
335 The encoded data as a DataFrame or numpy array.
337 """
338 if self.invariant_cols_:
339 X = X.drop(columns = self.invariant_cols_)
340 if self.return_df or override_return_df:
341 return X
342 return X.to_numpy()
344 def _select_columns(self, X: pd.DataFrame) -> list[Any]:
345 """Returns the columns to encode, from `cols` and `X`.
347 Args:
348 X: training data.
350 Raises:
351 ValueError: if `cols` names columns that `X` does not have.
353 Returns:
354 The columns to encode.
356 """
357 if self.cols is None:
358 # The same columns that `category_encoders` selects.
359 return [
360 column for column, dtype in X.dtypes.items()
361 if pd.api.types.is_object_dtype(dtype)
362 or pd.api.types.is_string_dtype(dtype)
363 or isinstance(dtype, pd.CategoricalDtype)]
364 if isinstance(self.cols, str) and self.cols.lower() == 'all':
365 return X.columns.tolist()
366 if isinstance(self.cols, (str, numbers.Integral)):
367 cols = [self.cols]
368 else:
369 cols = list(self.cols)
370 missing = [col for col in cols if col not in X.columns]
371 if missing:
372 raise ValueError(
373 f'X does not contain the columns listed in cols: {missing}')
374 return cols
376 def _validate_fit_target(self, y: Any) -> pd.Series:
377 """Checks the training outcome.
379 Args:
380 y: training outcome.
382 Raises:
383 ValueError: if `y` is None, not one-dimensional, or has missing
384 values.
386 Returns:
387 `y` as a pandas Series.
389 """
390 if y is None:
391 raise ValueError(
392 f'{type(self).__name__} requires y to be passed, but the '
393 'target y is None.')
394 return self._validate_target(y)
396 def _validate_handle_strategies(self) -> None:
397 """Checks `handle_missing` and `handle_unknown`.
399 Raises:
400 ValueError: if either is an unrecognized string or neither a
401 string, a number, nor a callable.
403 """
404 for name in ('handle_missing', 'handle_unknown'):
405 value = getattr(self, name)
406 valid = (
407 (isinstance(value, str) and value in _HANDLE_OPTIONS)
408 or callable(value)
409 or (isinstance(value, numbers.Real)
410 and not isinstance(value, bool)))
411 if not valid:
412 raise ValueError(
413 f'{name} must be one of {_HANDLE_OPTIONS}, a number, or '
414 f'a callable, not {value!r}')
416 def _validate_input(self, X: Any, reset: bool) -> pd.DataFrame:
417 """Checks `X` and converts it to a DataFrame.
419 Arrays get integer column names, as in `category_encoders`. If the
420 encoder was fit on a DataFrame and `X` is an array, the fitted column
421 names are attached to it by position.
423 Args:
424 X: data, as a DataFrame, Series, or two-dimensional array.
425 reset: whether `X` is training data (so its shape and names are
426 stored) rather than data to transform (so they are checked).
428 Raises:
429 TypeError: if `X` is sparse.
430 ValueError: if `X` is not two-dimensional, is empty, has
431 duplicate columns, or has complex numbers.
433 Returns:
434 `X` as a DataFrame.
436 """
437 if sparse.issparse(X):
438 raise TypeError(
439 f'{type(self).__name__} does not support sparse input. '
440 'Convert the data to a dense DataFrame or array.')
441 if isinstance(X, pd.Series):
442 frame = X.to_frame()
443 elif isinstance(X, pd.DataFrame):
444 frame = X.copy()
445 else:
446 array = np.asarray(X)
447 if isinstance(X, (list, tuple)) and array.ndim == 1:
448 # As in `category_encoders`, a flat list is one column.
449 array = array.reshape(-1, 1)
450 if array.ndim != _TABLE_DIMENSIONS:
451 raise ValueError(
452 f'Expected 2D array, got {array.ndim}D array instead. '
453 'Reshape your data either using array.reshape(-1, 1) if '
454 'your data has a single feature or array.reshape(1, -1) '
455 'if it contains a single sample.')
456 frame = pd.DataFrame(array)
457 if frame.shape[0] == 0 or frame.shape[1] == 0:
458 kind = 'sample(s)' if frame.shape[0] == 0 else 'feature(s)'
459 raise ValueError(
460 f'Found array with 0 {kind} (shape={frame.shape}) while a '
461 'minimum of 1 is required.')
462 if frame.columns.has_duplicates:
463 duplicates = sorted(
464 set(frame.columns[frame.columns.duplicated()]), key = str)
465 raise ValueError(f'X has duplicate columns {duplicates}')
466 for dtype in frame.dtypes:
467 if pd.api.types.is_complex_dtype(dtype):
468 raise ValueError('Complex data not supported')
469 checked = frame
470 if not reset and self._extra_columns(frame):
471 checked = frame[self._columns]
472 validate_data(
473 self, X = checked, reset = reset, skip_check_array = True)
474 if reset:
475 self._columns = frame.columns.tolist()
476 self._dtypes = frame.dtypes.to_dict()
477 elif not isinstance(X, (pd.DataFrame, pd.Series)):
478 frame.columns = self._columns
479 return frame
481 def _extra_columns(self, frame: pd.DataFrame) -> list[Any]:
482 """Returns a DataFrame's columns that were not seen in fitting.
484 As in `category_encoders` (GH #367), a DataFrame to transform may
485 have extra columns, which pass through, as long as it has every
486 column seen in fitting, in the same order.
488 Args:
489 frame: data to transform.
491 Returns:
492 The extra columns, or an empty list if there are none or the
493 fitted columns are missing or out of order (which validation
494 then reports).
496 """
497 fitted = set(self._columns)
498 if len(frame.columns) <= len(self._columns):
499 return []
500 present = [column for column in frame.columns if column in fitted]
501 if present != self._columns:
502 return []
503 return [column for column in frame.columns if column not in fitted]
505 def _place_extra_columns(
506 self,
507 encoded: pd.DataFrame,
508 frame: pd.DataFrame,
509 extras: list[Any]) -> pd.DataFrame:
510 """Adds extra input columns to the output, where they were in the input.
512 Args:
513 encoded: the encoded data.
514 frame: the input data, with the extra columns.
515 extras: the extra columns.
517 Returns:
518 `encoded` with the extra columns, each placed among the encoded
519 columns as it was among the input columns. Columns made from
520 several input columns stay at the end.
522 """
523 by_source: dict[Any, list[Any]] = {}
524 combined = []
525 for column in self._output_spec:
526 if column.label not in encoded.columns: 526 ↛ 527line 526 didn't jump to line 527 because the condition on line 526 was never true
527 continue
528 if len(column.sources) == 1: 528 ↛ 532line 528 didn't jump to line 532 because the condition on line 528 was always true
529 by_source.setdefault(column.sources[0], []).append(
530 column.label)
531 else:
532 combined.append(column.label)
533 order: list[Any] = []
534 for label in frame.columns:
535 if label in extras:
536 order.append(label)
537 else:
538 order.extend(by_source.get(label, []))
539 result = encoded.copy()
540 for label in extras:
541 result[label] = frame[label]
542 return result[order + combined]
544 def _validate_target(self, y: Any) -> pd.Series:
545 """Checks an outcome and converts it to a Series.
547 Args:
548 y: outcome.
550 Raises:
551 ValueError: if `y` is not one-dimensional or has missing values.
553 Returns:
554 `y` as a pandas Series.
556 """
557 if isinstance(y, pd.DataFrame):
558 if y.shape[1] != 1:
559 raise ValueError('y must be one-dimensional')
560 y = y.iloc[:, 0]
561 if not isinstance(y, pd.Series):
562 array = np.asarray(y)
563 if array.ndim == _TABLE_DIMENSIONS and array.shape[1] == 1:
564 array = array.ravel()
565 if array.ndim != 1:
566 raise ValueError('y must be one-dimensional')
567 y = pd.Series(array)
568 series = cast('pd.Series', y)
569 if series.isna().any():
570 raise ValueError(
571 'The target column y must not contain missing values.')
572 return series
574 """ Properties """
576 @property
577 def invariant_cols(self) -> list[Any]:
578 """Returns `invariant_cols_`, under `category_encoders`' name.
580 Returns:
581 The output columns dropped by `drop_invariant`.
583 """
584 return self.invariant_cols_
586 """ Dunder Methods """
588 def __sklearn_tags__(self) -> Tags:
589 """Returns the encoder's sklearn tags.
591 Encoders accept strings, categories, and missing values (which are a
592 category of their own), but not sparse data.
594 Returns:
595 The sklearn tags.
597 """
598 tags = cast('Tags', super().__sklearn_tags__())
599 tags.input_tags.allow_nan = True
600 tags.input_tags.categorical = True
601 tags.input_tags.string = True
602 tags.input_tags.sparse = False
603 return tags
606class SupervisedTransformerMixin(TransformerMixin):
607 """Mixin for encoders that need an outcome to fit.
609 As in `category_encoders`, passing `y` to `transform` marks the data as
610 training data, which an encoder may encode differently (for example, by
611 cross-fitting). `fit_transform` passes `y` on to `transform`.
613 """
615 """ Public Methods """
617 def fit_transform(
618 self,
619 X: Any,
620 y: Any = None,
621 **fit_params: Any) -> pd.DataFrame | np.ndarray:
622 """Fits the encoder and encodes the training data with its outcome.
624 Args:
625 X: training data.
626 y: training outcome.
627 **fit_params: passed to `fit`.
629 Raises:
630 ValueError: if `y` is None.
632 Returns:
633 The encoded training data.
635 """
636 if y is None: 636 ↛ 637line 636 didn't jump to line 637 because the condition on line 636 was never true
637 raise ValueError(
638 f'{type(self).__name__} requires y to be passed, but the '
639 'target y is None.')
640 encoder = cast('BaseEncoder', self)
641 encoder.fit(X, y, **fit_params)
642 return self.transform(X, y)
644 def transform(
645 self,
646 X: Any,
647 y: Any = None,
648 override_return_df: bool = False) -> pd.DataFrame | np.ndarray:
649 """Encodes data.
651 Args:
652 X: data to encode.
653 y: outcome of `X` if `X` is the training data, or None for new
654 data.
655 override_return_df: whether to return a DataFrame regardless of
656 `return_df`.
658 Returns:
659 The encoded data.
661 """
662 # The mixin is only used with `BaseEncoder`, which has these methods.
663 encoder = cast('BaseEncoder', self)
664 check_is_fitted(encoder, 'cols_')
665 X_frame = encoder._validate_input(X, reset = False)
666 y_series = None
667 if y is not None:
668 y_series = encoder._align_target(
669 encoder._validate_target(y),
670 X_frame)
671 encoder._check_missing(X_frame)
672 if any(column.encoded for column in encoder._output_spec):
673 extras = encoder._extra_columns(X_frame)
674 encoded = encoder._encode(X_frame, y_series)
675 if extras:
676 encoded = encoder._place_extra_columns(
677 encoded, X_frame, extras)
678 X_frame = encoded
679 return encoder._finish(
680 X_frame,
681 override_return_df = override_return_df)
683 """ Dunder Methods """
685 def __sklearn_tags__(self) -> Tags:
686 """Returns the tags of an encoder that needs an outcome.
688 The output is float64 whatever the input type was, so the encoder
689 does not preserve any dtype.
691 Returns:
692 The sklearn tags.
694 """
695 tags = cast('Tags', super().__sklearn_tags__())
696 tags.target_tags.required = True
697 if tags.transformer_tags is not None: 697 ↛ 699line 697 didn't jump to line 699 because the condition on line 697 was always true
698 tags.transformer_tags.preserves_dtype = []
699 return tags