API Reference / features / generation /

mathematical.py

Mathematical feature transformations.

This module provides mathematical transformations for feature construction.

Classes

MathematicalFeaturesGenerator

class features.generation.mathematical.MathematicalFeaturesGenerator(FeatureConstructor)

Apply mathematical transformations to create new features.

Applies one or more mathematical functions (log, sqrt, square, etc.) to each input feature, creating derived non-linear features.
Constructor
__init__(
    self,
    transformations: List[str] = None,
    include_original: bool = True,
    handle_invalid: str = 'nan',
)

Overview

Mathematical transformations are often used to:
  • Linearize non-linear relationships.
  • Normalize distribution of skewed features (e.g., via log transform).
  • Create interaction-like terms for a single feature (e.g., polynomial).

Parameters

transformations
list of str, 'sqrt', 'square'] = ['

List of transformations to apply. Supported options:

  • "log", "log1p", "log10", "log2"
  • "sqrt", "cbrt" (cube root)
  • "exp", "expm1"
  • "square", "reciprocal", "abs"
  • "sin", "cos", "tan", "tanh", "sigmoid"
include_original
bool = True
If True, the original features are preserved in the output.
handle_invalid
{"raise", "nan", "clip"} = "nan"

Strategy to handle math errors (like log of negative):

  • "raise": Stop and raise ValueError.
  • "nan": Produce NaN for invalid values.
  • "clip": Clip input to a valid range (e.g., :math:`x > 0` for log).

Attributes

n_input_features_
int
Number of features in the input data.
n_output_features_
int
Number of features in the transformed data.

Construct square and square-root features:

python
>>> from tuiml.features.generation import MathematicalFeaturesGenerator
>>> import numpy as np
>>> X = np.array([[1, 4], [9, 16]])
>>> math_feat = MathematicalFeaturesGenerator(transformations=['sqrt', 'square'])
>>> X_new = math_feat.fit_transform(X)
>>> print(X_new.shape)
(2, 6)

Methods

fit (self, X: np.ndarray, y: Optional[np.ndarray]=None) -> 'MathematicalFeaturesGenerator'

Validate transformations and compute output shape.

Parameters
X
ndarray of shape (n_samples, n_features)
Training data.
y
Ignored
Not used, present for API consistency.
Returns
self
MathematicalFeaturesGenerator
The fitted transformer.
transform (self, X: np.ndarray) -> np.ndarray

Apply mathematical transformations.

Parameters
X
ndarray of shape (n_samples, n_features)
Data to transform.
Returns
X_new
ndarray of shape (n_samples, n_output_features)
Transformed data with new features.
get_feature_names_out (self, input_features: Optional[List[str]]=None) -> np.ndarray

Get output feature names for mathematical transformations.

Parameters
input_features
list of str
Input feature names. If None, uses x0, x1, etc.
Returns
feature_names
ndarray of str
Output feature names.
get_parameter_schema (cls) -> Dict[str, Any]

Return JSON Schema for constructor parameters.

BinningFeaturesGenerator

class features.generation.mathematical.BinningFeaturesGenerator(FeatureConstructor)

Create binned (discretized) versions of continuous features.

Converts continuous features into categorical bins, which can capture non-linear relationships that a linear model might miss.
Constructor
__init__(
    self,
    n_bins: int = 5,
    strategy: str = 'quantile',
    encode: str = 'ordinal',
    include_original: bool = False,
)

Overview

Binning divides the range of a continuous variable into intervals (bins). It can be configured to use equal-width bins, equal-frequency bins (quantiles), or bins determined by k-means clustering.

Parameters

n_bins
int = 5
Number of bins for each feature.
strategy
{"uniform", "quantile", "kmeans"} = "quantile"

Binning strategy:

  • "uniform": All bins have identical widths.
  • "quantile": All bins have approximately same number of samples.
  • "kmeans": Bin edges are determined by 1D k-means clustering.
encode
{"onehot", "ordinal"} = "ordinal"

How to represent binned features:

  • "ordinal": Integer representing the bin index (0, 1, 2, ...).
  • "onehot": Vector representing bin membership.
include_original
bool = False
If True, include original continuous features in output along with binned ones.

Attributes

n_input_features_
int
Number of input features observed.
bin_edges_
list of np.ndarray
Array of bin edges for each feature.

Notes

When to use:
  • To linearize non-linear relationships in generalized linear models.
  • To handle outliers (by grouping them into the first or last bin).
  • To simplify a complex distribution into categories.

Discretize into 4 equal-frequency bins:

python
>>> from tuiml.features.generation import BinningFeaturesGenerator
>>> import numpy as np
>>> X = np.random.randn(100, 2)
>>> binner = BinningFeaturesGenerator(n_bins=4, strategy='quantile')
>>> X_binned = binner.fit_transform(X)
>>> print(np.unique(X_binned))
[0. 1. 2. 3.]

Methods

fit (self, X: np.ndarray, y: Optional[np.ndarray]=None) -> 'BinningFeaturesGenerator'

Compute bin edges for each feature.

Parameters
X
ndarray of shape (n_samples, n_features)
Training data.
y
Ignored
Not used.
Returns
self
BinningFeaturesGenerator
The fitted transformer.
transform (self, X: np.ndarray) -> np.ndarray

Apply binning transformation.

Parameters
X
ndarray of shape (n_samples, n_features)
Data to transform.
Returns
X_binned
ndarray
Binned features.
get_feature_names_out (self, input_features: Optional[List[str]]=None) -> np.ndarray

Get output feature names for binned features.

Parameters
input_features
list of str
Input feature names. If None, uses x0, x1, etc.
Returns
feature_names
ndarray of str
Output feature names.
get_parameter_schema (cls) -> Dict[str, Any]

Return JSON Schema for constructor parameters.