Skip to content
Open
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
112 changes: 101 additions & 11 deletions docs/user_guide/timeseries/forecasting/ExpandingWindowFeatures.rst
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ For example, by executing:

.. code:: python

X[["var_1", "var_2"].expanding(min_periods=3).agg(["max", "mean"])
X[["var_1", "var_2"]].expanding(min_periods=3).agg(["max", "mean"])

With the previous command, we create 2 window features for each variable, `var_1` and
`var_2`, by taking the maximum and average value of all observations up to (and including)
Expand All @@ -43,7 +43,7 @@ we would also shift the window forward with pandas method `shift`:

.. code:: python

X[["var_1", "var_2"].expanding(min_periods=3).agg(["max", "mean"]).shift(period=1)
X[["var_1", "var_2"]].expanding(min_periods=3).agg(["max", "mean"]).shift(periods=1)


Expanding window features with feature-engine
Expand All @@ -59,15 +59,23 @@ likely to be predictive. To capitalise on the past values of a variable, we can
lag features with :class:`LagFeatures`. We can also create features that summarise the
past values into a single quantity utilising :class:`ExpandingWindowFeatures`.

:class:`ExpandingWindowFeatures` works on top of `pandas.expanding`, `pandas.aggregate`
and `pandas.shift`.
:class:`ExpandingWindowFeatures` works with pandas and polars dataframes, and returns
the same type of dataframe it receives.

:class:`ExpandingWindowFeatures` uses `pandas.aggregate` to perform the mathematical
operations over the expanding window. Therefore, you can use any operation supported
by pandas. For supported aggregation functions, see Expanding Window
With pandas dataframes, :class:`ExpandingWindowFeatures` works on top of `pandas.expanding`,
`pandas.aggregate` and `pandas.shift`. It uses `pandas.aggregate` to perform the
mathematical operations over the expanding window. Therefore, you can use any method that
aggregates the values of one variable, like `"mean"`, `"max"` or `"std"`. For the
functions of your pandas version, see Expanding Window
`Functions <https://pandas.pydata.org/docs/reference/window.html>`_.

With `pandas.shift`, :class:`ExpandingWindowFeatures` lags the result of the expanding
With polars dataframes, :class:`ExpandingWindowFeatures` takes the functions `"count"`,
`"first"`, `"kurt"`, `"last"`, `"max"`, `"mean"`, `"median"`, `"min"`, `"nunique"`,
`"rank"`, `"sem"`, `"skew"`, `"std"`, `"sum"` and `"var"`. They compute the same
statistics as the pandas functions with the same name. `"rank"` needs polars 1.35 or
later.

:class:`ExpandingWindowFeatures` lags the result of the expanding
window operation. This is useful to ensure that only the information known at predict
time is used to compute the window feature. So if at predict time we only know
the value of a feature at the previous time period and before that, then we should lag the
Expand All @@ -80,8 +88,10 @@ name to the original dataframe. It also has the methods `fit()` and `transform()
that make it compatible with the scikit-learn's `Pipeline` and cross-validation
functions.

Note that, in the current implementation, :class:`ExpandingWindowFeatures` only works with
dataframes whose index, containing the time series timestamp, contains unique values and no NaN.
With pandas, :class:`ExpandingWindowFeatures` uses the dataframe's index, containing the
time series timestamp, to order the rows in time. The index must contain unique values
and no NaN. polars dataframes have no index, so the rows need to be in time order before
the transformation. See the section "With polars" below.

.. attention::

Expand Down Expand Up @@ -366,7 +376,7 @@ This is the resulting output:
2020-05-15 13:15:00 32.50
2020-05-15 13:30:00 32.52
2020-05-15 13:45:00 32.68
Freq: 15T, Name: ambient_temp, dtype: float64
Freq: 15min, Name: ambient_temp, dtype: float64

We can use :class:`ExpandingWindowFeatures` to create, for example, 2 new expanding window
features by finding the mean and maximum value of a pandas Series if we convert
Expand Down Expand Up @@ -450,6 +460,86 @@ We obtain the names of the original variables plus the new expanding window feat
'module_temp_expanding_mean',
'irradiation_expanding_mean']

With polars
~~~~~~~~~~~

:class:`ExpandingWindowFeatures` also works with polars dataframes. polars dataframes have
no index, so the transformer takes the rows in the order in which they are in the
dataframe. Make sure the rows are sorted in time before creating the features. The
parameters `freq` and `sort_index` are only used with pandas.

Let's create a polars dataframe whose rows are not in time order, and sort it by date:

.. code:: python

import polars as pl
from feature_engine.timeseries.forecasting import ExpandingWindowFeatures

X = pl.DataFrame({
"date": ["2020-05-15 12:30", "2020-05-15 12:00", "2020-05-15 13:00",
"2020-05-15 12:15", "2020-05-15 12:45"],
"ambient_temp": [32.15, 31.31, 32.62, 31.51, 32.39],
})

X = X.sort("date")

Now we create the expanding mean and maximum of the temperature:

.. code:: python

win_f = ExpandingWindowFeatures(functions=["mean", "max"])

X_tr = win_f.fit_transform(X)

print(X_tr)

We obtain a polars dataframe with the new features. The first row has no past values,
so its expanding window features are null:

.. code:: text

shape: (5, 4)
┌──────────────────┬──────────────┬─────────────────────────────┬────────────────────────────┐
│ date ┆ ambient_temp ┆ ambient_temp_expanding_mean ┆ ambient_temp_expanding_max │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 ┆ f64 │
╞══════════════════╪══════════════╪═════════════════════════════╪════════════════════════════╡
│ 2020-05-15 12:00 ┆ 31.31 ┆ null ┆ null │
│ 2020-05-15 12:15 ┆ 31.51 ┆ 31.31 ┆ 31.31 │
│ 2020-05-15 12:30 ┆ 32.15 ┆ 31.41 ┆ 31.51 │
│ 2020-05-15 12:45 ┆ 32.39 ┆ 31.656667 ┆ 32.15 │
│ 2020-05-15 13:00 ┆ 32.62 ┆ 31.84 ┆ 32.39 │
└──────────────────┴──────────────┴─────────────────────────────┴────────────────────────────┘

Besides statistics like the mean, we can take the rank of the last past value among all
the past values, and the standard error of their mean:

.. code:: python

win_f = ExpandingWindowFeatures(functions=["rank", "sem"])

X_tr = win_f.fit_transform(X)

print(X_tr)

The temperature rises over time, so each past value is the highest so far, and its rank
is the number of past values:

.. code:: text

shape: (5, 4)
┌──────────────────┬──────────────┬─────────────────────────────┬────────────────────────────┐
│ date ┆ ambient_temp ┆ ambient_temp_expanding_rank ┆ ambient_temp_expanding_sem │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 ┆ f64 │
╞══════════════════╪══════════════╪═════════════════════════════╪════════════════════════════╡
│ 2020-05-15 12:00 ┆ 31.31 ┆ null ┆ null │
│ 2020-05-15 12:15 ┆ 31.51 ┆ 1.0 ┆ null │
│ 2020-05-15 12:30 ┆ 32.15 ┆ 2.0 ┆ 0.1 │
│ 2020-05-15 12:45 ┆ 32.39 ┆ 3.0 ┆ 0.253333 │
│ 2020-05-15 13:00 ┆ 32.62 ┆ 4.0 ┆ 0.25632 │
└──────────────────┴──────────────┴─────────────────────────────┴────────────────────────────┘

See also
--------

Expand Down
159 changes: 152 additions & 7 deletions feature_engine/timeseries/forecasting/_forecasting_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,31 @@ def add_lag_features(
return X


def check_functions_supported(
X: DataFrame, functions: Union[str, List[str]]
) -> None:
"""
Checks that dataframes other than pandas use functions that they support.

Parameters
----------
X : pandas or narwhals dataframe
The dataframe returned by `check_X`.

functions : str or list
The `functions` parameter of the transformer.
"""
# pandas supports every function.
if isinstance(X, nw.DataFrame):
function_list = functions if isinstance(functions, list) else [functions]
supported = sorted([*_NW_ROLLING, *_POLARS_ROLLING, *_POLARS_ROW_WINDOWS])
if not all(function in supported for function in function_list):
raise NotImplementedError(
"With dataframes other than pandas, functions takes only "
f"{supported}. Got {functions} instead."
)


def check_window_parameters(
X: DataFrame,
window: Any,
Expand Down Expand Up @@ -232,13 +257,7 @@ def check_window_parameters(
"other dataframes, window takes integers, the number of rows in "
f"each window. Got {window} instead."
)
function_list = functions if isinstance(functions, list) else [functions]
supported = sorted([*_NW_ROLLING, *_POLARS_ROLLING, *_POLARS_ROW_WINDOWS])
if not all(function in supported for function in function_list):
raise NotImplementedError(
"With dataframes other than pandas, functions takes only "
f"{supported}. Got {functions} instead."
)
check_functions_supported(X, functions)
if min_periods == 0:
raise NotImplementedError(
"min_periods=0 is only supported with pandas dataframes. With "
Expand Down Expand Up @@ -341,3 +360,129 @@ def add_window_features(
X = nw.from_native(X_pl, eager_only=True).select(columns + names)

return X


def add_expanding_window_features(
X: DataFrame,
variables: Sequence[Union[str, int]],
functions: Union[str, List[str]],
min_periods: Optional[int],
periods: int,
freq: Optional[str],
ignore_missing: bool,
names: List[str],
) -> DataFrame:
"""
Adds functions of all the past values of the variables, after the columns of the
dataframe.

Parameters
----------
X : pandas or narwhals dataframe
The dataframe returned by `check_X`.

variables : list
The names of the variables.

functions : str or list
The functions to apply to the past values.

min_periods : int or None
The minimum number of values to return a value. If None, 0.

periods : int
The number of rows to shift the features by, so they hold past values only.

freq : str or None
The time span to shift the pandas index by, instead of `periods`.

ignore_missing : bool
Whether the variables can have missing values, NaN and inf.

names : list
The names of the new features: for each variable, one per function.

Returns
-------
X : pandas or narwhals dataframe
The dataframe with the new features.
"""
# pandas is faster than narwhals, and freq shifts the pandas index. agg() is
# faster with one function as a string than as a list.
if not isinstance(X, nw.DataFrame):
tmp = (
X[list(variables)]
.expanding(min_periods=min_periods)
.agg(functions)
.shift(periods=periods, freq=freq)
)
tmp.columns = names
X = X.merge(tmp, left_index=True, right_index=True, how="left")
else:
# pandas treats min_periods=None as 0. narwhals' rolling functions need at
# least 1, and 0 only changes count and sum, done below.
min_periods = 0 if min_periods is None else min_periods
min_samples = max(min_periods, 1)
# a rolling window as long as the dataframe is an expanding window.
window = max(len(X), min_samples)
function_list = functions if isinstance(functions, list) else [functions]
new_features = []
for var in variables:
# pandas computes in float and treats NaN as missing data, and inf too,
# except when counting.
x = nw.col(var).cast(nw.Float64)
if ignore_missing is True:
n_values = x.fill_nan(None).cum_count()
x = nw.when(x.is_finite()).then(x)
else:
n_values = x.cum_count()
count = x.cum_count()
# cumulative functions are faster than rolling ones, but they are null
# in the rows with missing data.
cumulative = {
"first": nw.when(~x.is_null() & (count == 1)).then(x),
"last": x,
"max": x.cum_max(),
"min": x.cum_min(),
}
for func in function_list:
if func == "count":
# pandas compares min_periods with the number of rows for count.
feature = nw.when(x.is_null().cum_count() >= min_periods).then(
n_values.cast(nw.Float64)
)
elif func == "nunique":
# like the sum, it is 0 before the first value if min_periods=0.
feature = nw.when(count >= min_periods).then(
(x.is_first_distinct() & ~x.is_null())
.cum_sum()
.cast(nw.Float64)
)
elif func == "sem":
# pandas divides by the number of values, inf included.
feature = x.rolling_std(
window, min_samples=min_samples
) / n_values.cast(nw.Float64).sqrt()
elif func in cumulative:
feature = nw.when(count >= min_samples).then(
cumulative[func].fill_null(strategy="forward")
)
elif func in _NW_ROLLING:
feature = _NW_ROLLING[func](x, window, min_samples)
if func == "sum" and min_periods == 0:
feature = feature.fill_null(0)
else:
# narwhals has no rolling function for these: use polars' own
# on the series.
values = X.select(x).get_column(var).to_native()
feature = nw.from_native(
_POLARS_ROLLING[func](values, window, min_samples),
series_only=True,
)
new_features.append(feature.shift(periods))

X = X.with_columns(
feature.alias(name) for feature, name in zip(new_features, names)
)

return X
Loading