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
141 changes: 132 additions & 9 deletions docs/user_guide/timeseries/forecasting/WindowFeatures.rst
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ by executing:

.. code:: python

X[["var_1", "var_2"].rolling(window=3).agg(["max", "mean"])
X[["var_1", "var_2"]].rolling(window=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 the current and 2 previous rows of data.
Expand All @@ -43,7 +43,7 @@ algorithms, we also need to shift the window forward with pandas method `shift`:

.. code:: python

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

Shifting is important to ensure that we are using values strictly in the past, with
respect to the point that we want to forecast.
Expand Down Expand Up @@ -72,16 +72,17 @@ weeks data, leaving a gap of a window in between the window feature and the fore
WindowFeatures: under the hood
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:class:`WindowFeatures` works on top of `pandas.rolling`, `pandas.aggregate` and
With pandas, :class:`WindowFeatures` works on top of `pandas.rolling` and
`pandas.shift`. With `pandas.rolling`, :class:`WindowFeatures` determines the size
of the windows for the operations. With `pandas.rolling` we can specify the window size
with an integer, a string or a function. With :class:`WindowFeatures`, in addition, we
can pass a list of integers, strings or functions, to perform computations over multiple
window sizes.

:class:`WindowFeatures` uses `pandas.aggregate` to perform the mathematical operations
over the windows. Therefore, you can use any operation supported
by pandas. For supported aggregation functions, see Rolling Window
:class:`WindowFeatures` performs the mathematical operations over the windows with the
methods of `pandas.rolling`. 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 Rolling Window
`Functions <https://pandas.pydata.org/docs/reference/window.html>`_.

With `pandas.shift`, :class:`WindowFeatures` places the value derived from the past
Expand All @@ -94,8 +95,10 @@ forward the value 2 weeks forward.
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:`WindowFeatures` only works with dataframes whose index,
containing the time series timestamp, contains unique values and no NaN.
:class:`WindowFeatures` works with pandas and polars dataframes. With pandas, the rows are
ordered in time by the dataframe's index, which should contain the time series timestamp,
with unique values and no NaN. Polars dataframes have no index, so the rows are used in the
order given. See :ref:`Window features with polars <window_features_polars>` below.

.. attention::

Expand Down Expand Up @@ -504,7 +507,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:`WindowFeatures` to create, for example, 2 new window features by finding
the mean and maximum value within a 45 minute windows of a pandas Series if we convert it
Expand Down Expand Up @@ -604,6 +607,126 @@ We obtain the names of the original variables plus the new window features:
'module_temp_window_3_mean',
'irradiation_window_3_mean']

.. _window_features_polars:

Window features with polars
~~~~~~~~~~~~~~~~~~~~~~~~~~~

:class:`WindowFeatures` also creates window features from polars dataframes. Polars
dataframes have no index, so the rows are used in the order given: make sure they are
sorted in time before creating the features. For the same reason, with polars:

- `window` takes the number of rows in each window, as an integer or a list of integers.
Time spans, like `"30min"`, are not supported.
- `freq` is not supported: the window features are shifted by `periods` rows.
- `functions` takes `"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.
- `min_periods` must be greater than 0.
- `sort_index` does not apply.

Let's create a polars dataframe with the ambient temperature and irradiation of our
previous example, which were recorded every 15 minutes:

.. code:: python

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

X = pl.DataFrame({
"ambient_temp": [31.31, 31.51, 32.15, 32.39, 32.62, 32.5, 32.52, 32.68],
"irradiation": [0.51, 0.79, 0.65, 0.76, 0.42, 0.49, 0.57, 0.56],
})

Windows of 2 and 4 rows cover 30 and 60 minutes of data:

.. code:: python

win_f = WindowFeatures(window=[2, 4], functions="mean")

X_tr = win_f.fit_transform(X)

print(X_tr)

We see the window features on the right of the dataframe. The first rows, which don't
have enough past data to fill the window, contain null values:

.. code:: text

shape: (8, 6)
┌──────────────┬─────────────┬─────────────────┬─────────────────┬────────────────┬────────────────┐
│ ambient_temp ┆ irradiation ┆ ambient_temp_wi ┆ irradiation_win ┆ ambient_temp_w ┆ irradiation_wi │
│ --- ┆ --- ┆ ndow_2_mean ┆ dow_2_mean ┆ indow_4_mean ┆ ndow_4_mean │
│ f64 ┆ f64 ┆ --- ┆ --- ┆ --- ┆ --- │
│ ┆ ┆ f64 ┆ f64 ┆ f64 ┆ f64 │
╞══════════════╪═════════════╪═════════════════╪═════════════════╪════════════════╪════════════════╡
│ 31.31 ┆ 0.51 ┆ null ┆ null ┆ null ┆ null │
│ 31.51 ┆ 0.79 ┆ null ┆ null ┆ null ┆ null │
│ 32.15 ┆ 0.65 ┆ 31.41 ┆ 0.65 ┆ null ┆ null │
│ 32.39 ┆ 0.76 ┆ 31.83 ┆ 0.72 ┆ null ┆ null │
│ 32.62 ┆ 0.42 ┆ 32.27 ┆ 0.705 ┆ 31.84 ┆ 0.6775 │
│ 32.5 ┆ 0.49 ┆ 32.505 ┆ 0.59 ┆ 32.1675 ┆ 0.655 │
│ 32.52 ┆ 0.57 ┆ 32.56 ┆ 0.455 ┆ 32.415 ┆ 0.58 │
│ 32.68 ┆ 0.56 ┆ 32.51 ┆ 0.53 ┆ 32.5075 ┆ 0.56 │
└──────────────┴─────────────┴─────────────────┴─────────────────┴────────────────┴────────────────┘

To take windows with fewer rows at the start of the series, set `min_periods`.

Besides statistics like the mean, we can take the first and last values of each window,
and the rank of the last value within the window:

.. code:: python

win_f = WindowFeatures(
variables="irradiation", window=4, functions=["first", "last", "rank"]
)

X_tr = win_f.fit_transform(X)

print(X_tr)

In the fifth row, the window holds the irradiation of the first 4 rows. Its last value,
0.76, is the third smallest of the window:

.. code:: text

shape: (8, 5)
┌──────────────┬─────────────┬───────────────────────┬──────────────────────┬──────────────────────┐
│ ambient_temp ┆ irradiation ┆ irradiation_window_4_ ┆ irradiation_window_4 ┆ irradiation_window_4 │
│ --- ┆ --- ┆ first ┆ _last ┆ _rank │
│ f64 ┆ f64 ┆ --- ┆ --- ┆ --- │
│ ┆ ┆ f64 ┆ f64 ┆ f64 │
╞══════════════╪═════════════╪═══════════════════════╪══════════════════════╪══════════════════════╡
│ 31.31 ┆ 0.51 ┆ null ┆ null ┆ null │
│ 31.51 ┆ 0.79 ┆ null ┆ null ┆ null │
│ 32.15 ┆ 0.65 ┆ null ┆ null ┆ null │
│ 32.39 ┆ 0.76 ┆ null ┆ null ┆ null │
│ 32.62 ┆ 0.42 ┆ 0.51 ┆ 0.76 ┆ 3.0 │
│ 32.5 ┆ 0.49 ┆ 0.79 ┆ 0.42 ┆ 1.0 │
│ 32.52 ┆ 0.57 ┆ 0.65 ┆ 0.49 ┆ 2.0 │
│ 32.68 ┆ 0.56 ┆ 0.76 ┆ 0.57 ┆ 3.0 │
└──────────────┴─────────────┴───────────────────────┴──────────────────────┴──────────────────────┘

We can also drop the rows with null values in the window features from the dataframe and
the target:

.. code:: python

y = pl.Series("y", [1, 2, 3, 4, 5, 6, 7, 8])

win_f = WindowFeatures(window=[2, 4], functions=["mean", "max"], drop_na=True)

X_tr, y_tr = win_f.fit(X).transform_x_y(X, y)

print(X.shape, y.shape, X_tr.shape, y_tr.shape)

The first 4 rows were removed from both:

.. code:: python

(8, 2) (8,) (4, 10) (4,)


Windows from the target vs windows from predictor variables
-----------------------------------------------------------
Expand Down
186 changes: 186 additions & 0 deletions feature_engine/timeseries/forecasting/_forecasting_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,54 @@
narwhals dataframe for the other libraries.
"""

from itertools import product
from typing import Any, List, Optional, Sequence, Union

import narwhals as nw
from narwhals.typing import IntoDataFrame

DataFrame = Union[IntoDataFrame, nw.DataFrame]

# pandas' rolling functions that other dataframes support: with narwhals, with
# polars' rolling expressions when narwhals has none (they are faster than numpy),
# and with polars aggregations over the rows of each window when polars has none.
_NW_ROLLING = {
"count": lambda col, win, min_samples: (~col.is_null())
.cast(nw.Float64)
.rolling_sum(win, min_samples=min_samples),
"mean": lambda col, win, min_samples: col.rolling_mean(
win, min_samples=min_samples
),
"sem": lambda col, win, min_samples: col.rolling_std(win, min_samples=min_samples)
/ (~col.is_null()).cast(nw.Float64).rolling_sum(win, min_samples=1).sqrt(),
"std": lambda col, win, min_samples: col.rolling_std(win, min_samples=min_samples),
"sum": lambda col, win, min_samples: col.rolling_sum(win, min_samples=min_samples),
"var": lambda col, win, min_samples: col.rolling_var(win, min_samples=min_samples),
}
_POLARS_ROLLING = {
# bias=False gives the sample skewness and kurtosis, as pandas.
"kurt": lambda col, win, min_samples: col.rolling_kurtosis(
win, bias=False, min_samples=min_samples
),
"max": lambda col, win, min_samples: col.rolling_max(win, min_samples=min_samples),
"median": lambda col, win, min_samples: col.rolling_median(
win, min_samples=min_samples
),
"min": lambda col, win, min_samples: col.rolling_min(win, min_samples=min_samples),
"rank": lambda col, win, min_samples: col.rolling_rank(
win, min_samples=min_samples
),
"skew": lambda col, win, min_samples: col.rolling_skew(
win, bias=False, min_samples=min_samples
),
}
# like pandas, they skip missing values.
_POLARS_ROW_WINDOWS = {
"first": lambda col: col.drop_nulls().first(),
"last": lambda col: col.drop_nulls().last(),
"nunique": lambda col: col.drop_nulls().n_unique(),
}


def check_index(X: DataFrame, freq: Any = None) -> None:
"""
Expand Down Expand Up @@ -155,3 +196,148 @@ def add_lag_features(
)

return X


def check_window_parameters(
X: DataFrame,
window: Any,
functions: Union[str, List[str]],
min_periods: Optional[int],
) -> None:
"""
Checks that dataframes without an index use windows of rows, and functions and
min_periods that they support.

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

window : int, str or list
The `window` parameter of WindowFeatures.

functions : str or list
The `functions` parameter of WindowFeatures.

min_periods : int or None
The minimum number of values in a window to return a value.
"""
# only pandas has an index, and pandas supports every window.
if isinstance(X, nw.DataFrame):
windows = window if isinstance(window, list) else [window]
if not all(isinstance(win, int) for win in windows):
raise NotImplementedError(
"Time spans in window, like '3D', are only supported with pandas "
"dataframes, because they use the dataframe's DatetimeIndex. With "
"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."
)
if min_periods == 0:
raise NotImplementedError(
"min_periods=0 is only supported with pandas dataframes. With "
"other dataframes, min_periods takes integers greater than 0 or "
f"None. Got {min_periods} instead."
)


def add_window_features(
X: DataFrame,
variables: Sequence[Union[str, int]],
windows: List[Any],
functions: List[str],
min_periods: Optional[int],
periods: int,
freq: Optional[str],
names: List[str],
) -> DataFrame:
"""
Adds functions of the values in a window of past rows, 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.

windows : list
The window sizes: numbers of rows, or time spans with pandas.

functions : list
The functions to apply to each window.

min_periods : int or None
The minimum number of values in a window to return a value. If None, the
window size.

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

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

names : list
The names of the new features: for each window, variable and function.

Returns
-------
X : pandas or narwhals dataframe
The dataframe with the new features.
"""
# pandas is faster than narwhals, and time spans and freq need its index.
name_of = dict(zip(product(windows, variables, functions), names))
if not isinstance(X, nw.DataFrame):
tmp = []
for win in windows:
rolling = X[list(variables)].rolling(window=win, min_periods=min_periods)
for function in functions:
# the rolling methods are faster than agg() with many variables.
rolled = getattr(rolling, function)().shift(periods=periods, freq=freq)
rolled.columns = [name_of[(win, var, function)] for var in variables]
tmp.append(rolled)
# with freq, the index of the features moves: merge aligns them to X.
X = X.merge(
tmp[0].join(tmp[1:])[names], left_index=True, right_index=True, how="left"
)
else:
plx = nw.get_native_namespace(X)
nw_exprs, native_exprs = [], []
for (win, var, function), name in name_of.items():
# like pandas, windows of integers need all their rows by default.
min_samples = win if min_periods is None else min_periods
if function in _NW_ROLLING:
rolled = _NW_ROLLING[function](nw.col(var), win, min_samples)
nw_exprs.append(rolled.shift(periods).alias(name))
elif function in _POLARS_ROLLING:
rolled = _POLARS_ROLLING[function](plx.col(var), win, min_samples)
native_exprs.append(rolled.shift(periods).alias(name))
else:
# like pandas, a window needs min_samples values that are not missing.
not_missing = plx.col(var).is_not_null().cast(plx.UInt32)
rolled = plx.when(
not_missing.rolling_sum(win, min_samples=1) >= min_samples
).then(
_POLARS_ROW_WINDOWS[function](plx.col(var)).rolling(
index_column="__row__", period=f"{win}i"
)
)
native_exprs.append(rolled.shift(periods).alias(name))

columns = X.columns
X = X.with_columns(nw_exprs)
if len(native_exprs) > 0:
# the polars features were added last: restore the order of the names,
# which also drops the row numbers that the windows of rows need.
X_pl = X.to_native().with_row_index("__row__").with_columns(native_exprs)
X = nw.from_native(X_pl, eager_only=True).select(columns + names)

return X
Loading