OneHotEncoder transformer.

One-hot encoding for categorical features.

Classes

OneHotEncoder

class preprocessing.encoding.one_hot.OneHotEncoder(Transformer)

One-hot encoding for categorical (nominal) features.

Transforms categorical features into a binary vector representation where each category is represented by a separate column.
Constructor
__init__(
    self,
    categories: Optional[List[List]] = None,
    drop: Optional[str] = None,
    columns: Optional[List[int]] = None,
)

Overview

One-hot encoding is essential for algorithms that cannot handle categorical data directly. It creates N binary columns for a feature with N unique categories (or N-1 if dropping a category).

Parameters

categories
list of list
Manually specified categories for each column. If None, categories are inferred from the training data.
drop
{"first", "if_binary"}

Strategy to drop one category per feature to avoid multicollinearity:

  • None: Keep all categories.
  • "first": Drop the first category.
  • "if_binary": Drop the first category only if the feature is binary.
columns
list of int
Indices of columns to encode. If None, all columns are encoded.

Attributes

categories_
list of np.ndarray
The categories determined during fitting for each encoded column.

Encode a single categorical feature:

python
>>> from tuiml.preprocessing.encoding import OneHotEncoder
>>> import numpy as np
>>> X = np.array([[0], [1], [2], [0]])
>>> encoder = OneHotEncoder()
>>> X_encoded = encoder.fit_transform(X)
>>> print(X_encoded.shape)
(4, 3)

Methods

get_parameter_schema (cls)
fit (self, X: np.ndarray, y: Optional[np.ndarray]=None, feature_names: Optional[List[str]]=None) -> 'OneHotEncoder'
transform (self, X: np.ndarray) -> np.ndarray
get_feature_names_out (self, input_features: Optional[List[str]]=None) -> List[str]
__repr__ (self) -> str