shredx.utils.pytorch_polynomial_features.PolynomialFeatures#

class shredx.utils.pytorch_polynomial_features.PolynomialFeatures(degree: int, interaction_only: bool = False, include_bias: bool = True)#

Bases: Module

PyTorch implementation of polynomial features that supports backpropagation.

Drop-in replacement for sklearn.preprocessing.PolynomialFeatures with gradient computation support for use in neural network training.

Parameters:
degreeint

Maximum degree of polynomial features (must be >= 1).

interaction_onlybool, optional

If True, only include interaction features (products of distinct features), not powers. Default is False.

include_biasbool, optional

If True, include a bias column of ones. Default is True.

Methods

fit(X)

Fit the polynomial features transformer to the data.

fit_transform(X)

Fit to data, then transform it.

get_feature_names_out()

Get the feature names of the polynomial features.

transform(x)

Transform data to polynomial features.

Raises:
ValueError

If degree is less than 1.

Notes

Class Methods:

fit(X):

  • Computes and stores the number of input features and output features based on the polynomial degree and settings.

  • Parameters:
    • X : Float[torch.Tensor, "n_samples n_features_in"]. Input tensor.

  • Returns:
    • self. For method chaining.

transform(x):

  • Transform data to polynomial features.

  • Parameters:
    • x : Float[torch.Tensor, "n_samples n_features_in"]. Input tensor.

  • Returns:
    • Float[torch.Tensor, "n_samples n_output_features_"]. Transformed tensor.

fit_transform(X):

  • Convenience method that calls fit() followed by transform().

  • Parameters:
    • X : Float[torch.Tensor, "n_samples n_features_in"]. Input tensor.

  • Returns:
    • Float[torch.Tensor, "n_samples n_output_features_"]. Transformed tensor.

get_feature_names_out():

  • Must be called after fit() to access the number of input features. Returns feature name strings.

  • Returns:
    • list[str]. Feature names, e.g. ["1", "x0", "x1", "x0^2", "x0 x1", "x1^2"].

_combo_to_dict(combo):

  • Helper for get_feature_names_out(). Counts occurrences of each feature index to determine its power. Example: (0, 0, 1, 3) -> {0: 2, 1: 1, 3: 1} (x0^2 * x1 * x3).

  • Parameters:
    • combo : tuple of int. Tuple of feature indices representing a polynomial term.

  • Returns:
    • dict[int, int]. Mapping of feature indices to their powers.