Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 57 additions & 9 deletions docs/user_guide/wrappers/Wrapper.rst
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ The :class:`SklearnWrapper()` offers similar functionality to the
class available in scikit-learn. They differ in the implementation to select the
variables and the output.

The :class:`SklearnWrapper()` returns a pandas dataframe with the variables
in the order of the original data. The
The :class:`SklearnWrapper()` returns a dataframe of the same library as the input,
for example pandas or polars, with the variables in the order of the original data. The
`ColumnTransformer <https://scikit-learn.org/stable/modules/generated/sklearn.compose.ColumnTransformer.html>`_
returns a Numpy array, and the order of the variables may not coincide with that of the
original dataset.
Expand Down Expand Up @@ -170,7 +170,9 @@ list:

.. code:: python

cols = [var for var in X_train.columns if X_train[var].dtypes !='O']
from feature_engine.variable_handling import find_numerical_variables

cols = find_numerical_variables(X_train)

Now, we set up the wrapper with the SelectKBest, and fit it to the train set:

Expand Down Expand Up @@ -211,7 +213,7 @@ imports and a function to load and clean the Titanic dataset:
data = data.replace('?', np.nan)
data['cabin'] = data['cabin'].astype(str).str[0]
data['pclass'] = data['pclass'].astype('O')
data['embarked'].fillna('C', inplace=True)
data['embarked'] = data['embarked'].fillna('C')
data.drop(["name", "home.dest", "ticket", "boat", "body"], axis=1, inplace=True)
return data

Expand All @@ -234,7 +236,7 @@ to transform the train and test sets:
.. code:: python

ohe = SklearnWrapper(
OneHotEncoder(sparse=False, drop='first'),
OneHotEncoder(sparse_output=False, drop='first'),
variables = ['pclass','sex'])

ohe.fit(X_train)
Expand All @@ -253,11 +255,11 @@ The resulting dataframe is:
.. code:: python

age sibsp parch fare cabin embarked pclass_2 pclass_3 sex_male
772 17 0 0 7.8958 n S 0.0 1.0 1.0
543 36 0 0 10.5 n S 1.0 0.0 1.0
772 17 0 0 7.8958 NaN S 0.0 1.0 1.0
543 36 0 0 10.5 NaN S 1.0 0.0 1.0
289 18 0 2 79.65 E S 0.0 0.0 0.0
10 47 1 0 227.525 C C 0.0 0.0 1.0
147 NaN 0 0 42.4 n S 0.0 0.0 1.0
147 NaN 0 0 42.4 NaN S 0.0 0.0 1.0


Let's say you want to use :class:`SklearnWrapper()` in a more complex
Expand Down Expand Up @@ -323,7 +325,7 @@ We see the resulting dataframe, with the new interaction features at the end:
772 17.000000 0 0 7.8958 0 0 3.0 0.0
543 36.000000 0 0 10.5000 0 0 2.0 0.0
289 18.000000 0 2 79.6500 1 0 1.0 1.0
10 47.000000 1 0 227.5250 2 1 1.0 0.0
10 47.000000 1 0 227.5250 0 1 1.0 0.0
147 29.532738 0 0 42.4000 0 0 1.0 0.0

pclass sex
Expand All @@ -334,6 +336,52 @@ We see the resulting dataframe, with the new interaction features at the end:
147 0.0


With polars
^^^^^^^^^^^

:class:`SklearnWrapper()` works in the same way with a polars dataframe, and returns a
polars dataframe:

.. code:: python

import polars as pl
from sklearn.preprocessing import StandardScaler
from feature_engine.wrappers import SklearnWrapper

X = pl.DataFrame({
"city": ["London", "Madrid", "Paris", "London"],
"age": [20, 30, None, 40],
"income": [1000.0, 2000.0, 1500.0, None],
})

scaler = SklearnWrapper(transformer=StandardScaler())
X_t = scaler.fit_transform(X)

print(X_t)

The scaler standardised the numerical variables and left the text variable as it was:

.. code:: text

shape: (4, 3)
┌────────┬───────────┬───────────┐
│ city ┆ age ┆ income │
│ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 │
╞════════╪═══════════╪═══════════╡
│ London ┆ -1.224745 ┆ -1.224745 │
│ Madrid ┆ 0.0 ┆ 1.224745 │
│ Paris ┆ NaN ┆ 0.0 │
│ London ┆ 1.224745 ┆ NaN │
└────────┴───────────┴───────────┘

The wrapper returns the values that the scikit-learn transformer returns. scikit-learn
marks missing values with `NaN`, so the missing values of the numerical variables come
back as `NaN` instead of `null`. scikit-learn also does not recognise `null` in polars
text variables as a missing value: imputers don't replace it, and encoders treat it as
one more category.


More details
^^^^^^^^^^^^

Expand Down
156 changes: 88 additions & 68 deletions feature_engine/wrappers/wrappers.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import warnings
from typing import List, Optional, Union

import pandas as pd
import narwhals as nw
import numpy as np
from narwhals.typing import IntoDataFrame, IntoSeries
from sklearn.base import BaseEstimator, TransformerMixin, clone
from sklearn.utils.validation import check_is_fitted

Expand All @@ -12,6 +14,11 @@
_check_variables_input_value,
)
from feature_engine.dataframe_checks import _check_X_matches_training_df, check_X
from feature_engine.dataframe_helpers import (
add_columns_to_df,
replace_columns_in_df,
subset_df,
)
from feature_engine.tags import _return_tags
from feature_engine.variable_handling import (
check_numerical_variables,
Expand Down Expand Up @@ -150,7 +157,8 @@ class SklearnWrapper(TransformerMixin, BaseEstimator):
-----
This transformer offers similar functionality to the ColumnTransformer from
scikit-learn, but it allows entering the transformations directly into a
Pipeline and returns pandas dataframes.
Pipeline and returns a dataframe of the same library as the input, for
example, pandas or polars.

See Also
--------
Expand Down Expand Up @@ -195,6 +203,27 @@ class SklearnWrapper(TransformerMixin, BaseEstimator):
0 a 1.0 4.0 1.0 4.0 16.0
1 b 2.0 5.0 4.0 10.0 25.0
2 c 3.0 6.0 9.0 18.0 36.0

With polars:

>>> import polars as pl
>>> from feature_engine.wrappers import SklearnWrapper
>>> from sklearn.preprocessing import OneHotEncoder
>>> X = pl.DataFrame(dict(x1 = ["a","b","c"], x2 = [1,2,3], x3 = [4,5,6]))
>>> skw = SklearnWrapper(
>>> OneHotEncoder(sparse_output = False), variables = "x1")
>>> skw.fit(X)
>>> skw.transform(X)
shape: (3, 5)
┌─────┬─────┬──────┬──────┬──────┐
│ x2 ┆ x3 ┆ x1_a ┆ x1_b ┆ x1_c │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ f64 ┆ f64 ┆ f64 │
╞═════╪═════╪══════╪══════╪══════╡
│ 1 ┆ 4 ┆ 1.0 ┆ 0.0 ┆ 0.0 │
│ 2 ┆ 5 ┆ 0.0 ┆ 1.0 ┆ 0.0 │
│ 3 ┆ 6 ┆ 0.0 ┆ 0.0 ┆ 1.0 │
└─────┴─────┴──────┴──────┴──────┘
"""

def __init__(
Expand All @@ -204,10 +233,10 @@ def __init__(
return_empty: bool = False,
) -> None:

if not issubclass(transformer.__class__, TransformerMixin):
if not isinstance(transformer, TransformerMixin):
raise TypeError(
"transformer expected a Scikit-learn transformer. "
f"got {transformer} instead. "
f"Got {transformer} instead."
)

if transformer.__class__.__name__ not in _ALL_TRANSFORMERS:
Expand Down Expand Up @@ -251,20 +280,21 @@ def __init__(
self.variables = _check_variables_input_value(variables)
self.return_empty = return_empty

def fit(self, X: pd.DataFrame, y: Optional[str] = None):
def fit(self, X: IntoDataFrame, y: Optional[IntoSeries] = None):
"""
Fits the scikit-learn transformer to the selected variables.

Parameters
----------
X: pandas DataFrame
The dataset to fit the transformer.
X: dataframe of shape = [n_samples, n_features]
The dataset to fit the transformer. Can be a pandas, polars, or any other
dataframe supported by narwhals.

y: pandas Series, default=None
The target variable.
y: Series, default=None
The target variable. Only needed by the transformers that use it, like
the feature selectors.
"""

# check input dataframe
X = check_X(X)

self.transformer_ = clone(self.transformer)
Expand All @@ -290,27 +320,27 @@ def fit(self, X: pd.DataFrame, y: Optional[str] = None):
else:
self.variables_ = check_numerical_variables(X, self.variables)

self.feature_names_in_ = list(X.columns)
self.n_features_in_ = X.shape[1]

if len(self.variables_) == 0:
# save input features
self.feature_names_in_ = X.columns.tolist()
self.n_features_in_ = X.shape[1]
return self

self.transformer_.fit(X[self.variables_], y)
# a global scikit-learn output config would change what transform() receives.
self.transformer_.set_output(transform="default")
self.transformer_.fit(
nw.to_native(subset_df(X, self.variables_), pass_through=True), y
)

if self.transformer_.__class__.__name__ in _SELECTORS:
# Find features to drop.
selected = X[self.variables_].columns[self.transformer_.get_support()]
selected = [
self.variables_[i] for i in self.transformer_.get_support(indices=True)
]
self.features_to_drop_ = [f for f in self.variables_ if f not in selected]

# save input features
self.feature_names_in_ = X.columns.tolist()

self.n_features_in_ = X.shape[1]

return self

def transform(self, X: pd.DataFrame) -> pd.DataFrame:
def transform(self, X: IntoDataFrame) -> IntoDataFrame:
"""
Apply the transformation to the dataframe. Only the selected variables will be
modified.
Expand All @@ -326,56 +356,54 @@ def transform(self, X: pd.DataFrame) -> pd.DataFrame:

Parameters
----------
X: pandas DataFrame
X: dataframe of shape = [n_samples, n_features]
The data to transform.

Returns
-------
X_new: pandas DataFrame
X_new: dataframe
The transformed dataset.
"""
check_is_fitted(self)

# check that input is a dataframe
X = check_X(X)

# Check that input data contains same number of columns than
# the dataframe used to fit the imputer.

_check_X_matches_training_df(X, self.n_features_in_)

# reorder df to match train set
X = X[self.feature_names_in_]

# nothing to transform, e.g. when return_empty selected no variables
if len(self.variables_) == 0:
return X

# Transformers that add features: creators
if self.transformer_.__class__.__name__ in [
"OneHotEncoder",
"PolynomialFeatures",
]:
new_features_df = pd.DataFrame(
data=self.transformer_.transform(X[self.variables_]),
columns=self.transformer_.get_feature_names_out(self.variables_),
index=X.index,
)
X = pd.concat([X.drop(columns=self.variables_), new_features_df], axis=1)
X = subset_df(X, self.feature_names_in_)

# Feature selection: transformers that remove features
elif self.transformer_.__class__.__name__ in _SELECTORS:
X = subset_df(X, self.get_feature_names_out())

# return the dataframe with the selected features
X.drop(columns=self.features_to_drop_, inplace=True)
# Transformers that add features: creators
elif self.transformer_.__class__.__name__ in _CREATORS:
X_new = self.transformer_.transform(
nw.to_native(subset_df(X, self.variables_), pass_through=True)
)
columns = self.transformer_.get_feature_names_out(self.variables_)
X = add_columns_to_df(
subset_df(
X, [f for f in self.feature_names_in_ if f not in self.variables_]
),
dict(zip(columns, X_new.T)),
)

# Transformers that modify existing features
else:
X[self.variables_] = self.transformer_.transform(X[self.variables_])
# the function in a FunctionTransformer may return a dataframe.
X_new = np.asarray(
self.transformer_.transform(
nw.to_native(subset_df(X, self.variables_), pass_through=True)
)
)
X = replace_columns_in_df(
subset_df(X, self.feature_names_in_),
dict(zip(self.variables_, X_new.T)),
)

return X
return nw.to_native(X, pass_through=True)

def inverse_transform(self, X: pd.DataFrame) -> pd.DataFrame:
def inverse_transform(self, X: IntoDataFrame) -> IntoDataFrame:
"""Convert the transformed variables back to the original values. Only
implemented for the following scikit-learn transformers:

Expand All @@ -388,18 +416,15 @@ def inverse_transform(self, X: pd.DataFrame) -> pd.DataFrame:

Parameters
----------
X: pandas dataframe of shape = [n_samples, n_features].
X: dataframe of shape = [n_samples, n_features].
The transformed dataframe.

Returns
-------
X_tr: pandas dataframe of shape = [n_samples, n_features].
X_tr: dataframe of shape = [n_samples, n_features].
The dataframe with the original values.
"""
# Check method fit has been called
check_is_fitted(self)

# check that input is a dataframe
X = check_X(X)

if self.transformer_.__class__.__name__ not in _INVERSE_TRANSFORM:
Expand All @@ -409,17 +434,12 @@ def inverse_transform(self, X: pd.DataFrame) -> pd.DataFrame:
", ".join(_INVERSE_TRANSFORM)
)
)
# For safety, we check that the transformer has the method implemented.
if hasattr(self.transformer_, "inverse_transform") and callable(
self.transformer_.inverse_transform
):
X[self.variables_] = self.transformer_.inverse_transform(X[self.variables_])
else:
raise NotImplementedError(
"This Scikit-learn transformer does not have the method "
"`inverse_transform` implemented."
)
return X

X_inv = self.transformer_.inverse_transform(
nw.to_native(subset_df(X, self.variables_), pass_through=True)
)
X = replace_columns_in_df(X, dict(zip(self.variables_, X_inv.T)))
return nw.to_native(X, pass_through=True)

def get_feature_names_out(
self, input_features: Optional[List[Union[str, int]]] = None
Expand Down
Loading