Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ENH] hcrystalball forecaster adapter #4040

Merged
merged 8 commits into from Jan 9, 2023
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions CODEOWNERS
Validating CODEOWNERS rules …
Expand Up @@ -72,6 +72,7 @@ sktime/forecasting/fbprophet.py @aiwalter
sktime/forecasting/bats.py @aiwalter
sktime/forecasting/tbats.py @aiwalter
sktime/forecasting/arima.py @HYang1996
sktime/forecasting/adapters/_hcrystalball.py @MichalChromcak
sktime/forecasting/statsforecast.py @FedericoGarza
sktime/forecasting/structural.py @juanitorduz
sktime/forecasting/model_selection/_split @koralturkk
Expand Down
13 changes: 13 additions & 0 deletions docs/source/api_reference/forecasting.rst
Expand Up @@ -309,6 +309,19 @@ Online and stream forecasting
UpdateRefitsEvery
DontUpdate

Adapters to other forecasting framework packages
------------------------------------------------

Generic framework adapters that expose other frameworks in the ``sktime`` interface.

.. currentmodule:: sktime.forecasting.adapters

.. autosummary::
:toctree: auto_generated/
:template: class.rst

HCrystalBallAdapter

Model selection and tuning
--------------------------

Expand Down
7 changes: 7 additions & 0 deletions sktime/forecasting/adapters/__init__.py
@@ -0,0 +1,7 @@
# -*- coding: utf-8 -*-
"""Module containing adapters to other forecasting framework packages."""
# copyright: sktime developers, BSD-3-Clause License (see LICENSE file)

__all__ = ["HCrystalBallAdapter"]

from sktime.forecasting.adapters._hcrystalball import HCrystalBallAdapter
186 changes: 186 additions & 0 deletions sktime/forecasting/adapters/_hcrystalball.py
@@ -0,0 +1,186 @@
# -*- coding: utf-8 -*-
# !/usr/bin/env python3 -u
# copyright: sktime developers, BSD-3-Clause License (see LICENSE file)
"""Adapter for using HCrystalBall forecastsers in sktime."""

__author__ = ["MichalChromcak"]

import pandas as pd
from sklearn.base import clone

from sktime.forecasting.base import BaseForecaster
from sktime.utils.validation._dependencies import _check_soft_dependencies

_check_soft_dependencies("hcrystalball", severity="warning")
fkiraly marked this conversation as resolved.
Show resolved Hide resolved


def _check_fh(fh, cutoff):
if fh is not None:
if not fh.is_all_out_of_sample(cutoff):
raise NotImplementedError(
"in-sample prediction are currently not implemented"
)


def _check_index(index):
if not isinstance(index, pd.DatetimeIndex):
raise NotImplementedError(
"`HCrystalBallForecaster` currently only supports `pd.DatetimeIndex`. "
"Please convert the data index to `pd.DatetimeIndex`."
)
return index


def _adapt_y_X(y, X):
"""Adapt fit data to HCB compliant format.

Parameters
----------
y : pd.Series
Target variable
X : pd.Series, pd.DataFrame
Exogenous variables

Returns
-------
tuple
y_train - pd.Series with datetime index
X_train - pd.DataFrame with datetime index
and optionally exogenous variables in columns

Raises
------
ValueError
When neither of the argument has Datetime or Period index
"""
index = _check_index(y.index)
X = pd.DataFrame(index=index) if X is None else X
return y, X


def _get_X_pred(X_pred, index):
"""Translate forecast horizon interface to HCB native dataframe.

Parameters
----------
X_pred : pd.DataFrame
Exogenous data for predictions
index : pd.DatetimeIndex
Index generated from the forecasting horizon

Returns
-------
pd.DataFrame
index - datetime
columns - exogenous variables (optional)
"""
if X_pred is not None:
_check_index(X_pred.index)

X_pred = pd.DataFrame(index=index) if X_pred is None else X_pred
return X_pred


def _adapt_y_pred(y_pred):
"""Translate wrapper prediction to sktime format.

From Dataframe to series.

Parameters
----------
y_pred : pd.DataFrame

Returns
-------
pd.Series : Predictions in form of series
"""
return y_pred.iloc[:, 0]


class HCrystalBallAdapter(BaseForecaster):
"""Adapter for using `hcrystalball` forecasters in sktime.

Adapter class - wraps any forecaster from `hcrystalball`
and allows using it as an `sktime` `BaseForecaster`.

Parameters
----------
model : The HCrystalBall forecasting model to use.
"""

_tags = {
"ignores-exogeneous-X": True,
"requires-fh-in-fit": False,
"handles-missing-data": False,
"python_dependencies": "hcrystalball",
}

def __init__(self, model):

self.model = model
super(HCrystalBallAdapter, self).__init__()

def _fit(self, y, X=None, fh=None):
"""Fit to training data.

Parameters
----------
y : pd.Series
Target time series with which to fit the forecaster.
fh : int, list or np.array, optional (default=None)
The forecast horizon with the steps ahead to predict.
X : pd.DataFrame, optional (default=None)
Exogenous variables are ignored

Returns
-------
self : returns an instance of self.
"""
y, X = _adapt_y_X(y, X)
self.model_ = clone(self.model)
self.model_.fit(X, y)

return self

def _predict(self, fh=None, X=None):
"""Make forecasts for the given forecast horizon.

Parameters
----------
fh : int, list or np.array
The forecast horizon with the steps ahead to predict
X : pd.DataFrame, optional (default=None)
Exogenous variables (ignored)

Returns
-------
y_pred : pd.Series
Point predictions for the forecast
"""
X_pred = _get_X_pred(X, index=fh.to_absolute(self.cutoff).to_pandas())
y_pred = self.model_.predict(X=X_pred)
return _adapt_y_pred(y_pred)

@classmethod
def get_test_params(cls, parameter_set="default"):
"""Return testing parameter settings for the estimator.

Parameters
----------
parameter_set : str, default="default"
Name of the set of test parameters to return, for use in tests. If no
special parameters are defined for a value, will return `"default"` set.

Returns
-------
params : dict or list of dict
"""
if _check_soft_dependencies("hcrystalball", severity="none"):
from hcrystalball.wrappers import HoltSmoothingWrapper

params = {"model": HoltSmoothingWrapper()}

else:
params = {"model": 42}

return params
5 changes: 4 additions & 1 deletion sktime/tests/test_softdeps.py
Expand Up @@ -46,7 +46,10 @@
# estimators excepted from checking that get_test_params does not import soft deps
# this is ok, in general, for adapters to soft dependency frameworks
# since such adapters will import estimators from the adapted framework
EXCEPTED_FROM_GET_PARAMS_CHECK = ["PyODAnnotator"]
EXCEPTED_FROM_GET_PARAMS_CHECK = [
"PyODAnnotator", # adapters always require soft dep. Here: pyod
"HCrystalBallAdapter", # adapters always require soft dep. Here: hcrystalball
]


def _is_test(module):
Expand Down