-
Notifications
You must be signed in to change notification settings - Fork 29
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
Xgboost #405
Draft
s0nicboOm
wants to merge
9
commits into
main
Choose a base branch
from
xgboost
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Xgboost #405
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
090c490
feat: force retrain
s0nicboOm 8680f8d
feat: add xgboost
s0nicboOm 9258881
fix: refactor
s0nicboOm 67dee23
fix: refactor
s0nicboOm 7331c29
fix: typing
s0nicboOm dcff815
fix: add ClassVar
s0nicboOm 4007e19
fix : typing
s0nicboOm d042aab
add args
s0nicboOm 32bd2e2
fix: change dependency to u8darts
s0nicboOm File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,7 @@ | ||
from numalogic.models.forecast.variants.naive import BaselineForecaster, SeasonalNaiveForecaster | ||
from numalogic.models.forecast.variants.naive import ( | ||
BaselineForecaster, | ||
SeasonalNaiveForecaster, | ||
) | ||
from numalogic.models.forecast.variants.xgboost import XGBoostForecaster | ||
|
||
__all__ = ["BaselineForecaster", "SeasonalNaiveForecaster"] | ||
__all__ = ["BaselineForecaster", "SeasonalNaiveForecaster", "XGBoostForecaster"] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,150 @@ | ||
import logging | ||
|
||
import numpy as np | ||
import pandas as pd | ||
import torch | ||
from torch.utils.data import DataLoader | ||
from xgboost import XGBRegressor, callback | ||
|
||
from numalogic.tools.data import ForecastDataset | ||
from numalogic.transforms._covariates import CovariatesGenerator | ||
|
||
_LOGGER = logging.getLogger(__name__) | ||
|
||
|
||
def _check_data_format(df) -> bool: | ||
if not isinstance(df, pd.DataFrame): | ||
raise TypeError("df should be of type pd.DataFrame") | ||
if not df.shape[1] > 0: | ||
raise ValueError("df should have more than 0 column") | ||
if not isinstance(df.index, pd.DatetimeIndex): | ||
raise TypeError("df index should be of type pd.DatetimeIndex") | ||
return True | ||
|
||
|
||
class XGBoostForecaster: | ||
""" | ||
A forecaster that uses XGBoost regressor to predict future values. | ||
|
||
Args: | ||
____ | ||
horizon: number of time steps to predict into the future | ||
seq_len: number of time steps to consider for prediction | ||
l_rate: learning rate for the XGBoost regress | ||
regressor_params: additional parameters for the XGBoost regressor | ||
""" | ||
|
||
__slots__ = ( | ||
"_horizon", | ||
"_seq_len", | ||
"_val_split", | ||
"_model", | ||
"_early_stop_callback", | ||
"_early_stopping", | ||
) | ||
|
||
def __init__( | ||
self, | ||
horizon: int, | ||
seq_len: int, | ||
early_stopping=True, | ||
val_split: float = 0.1, | ||
**regressor_params, | ||
): | ||
self._horizon = horizon | ||
self._seq_len = seq_len | ||
self._val_split = 0 | ||
self._early_stopping = early_stopping | ||
if early_stopping: | ||
self._val_split = val_split | ||
early_stop_callback = callback.EarlyStopping( | ||
rounds=20, metric_name="rmse", save_best=True, maximize=False, min_delta=1e-4 | ||
) | ||
default_params = { | ||
"learning_rate": 0.1, | ||
"n_estimators": 1000, | ||
"booster": "gbtree", | ||
"max_depth": 7, | ||
"min_child_weight": 1, | ||
"gamma": 0.0, | ||
"subsample": 0.9, | ||
"colsample_bytree": 0.8, | ||
"reg_alpha": 0.1, | ||
"nthread": 4, | ||
"seed": 27, | ||
"objective": "reg:squarederror", | ||
"random_state": 42, | ||
} | ||
if early_stopping: | ||
default_params.update({"callbacks": [early_stop_callback]}) | ||
if regressor_params: | ||
default_params.update(default_params) | ||
|
||
self._model = XGBRegressor(**default_params) | ||
|
||
def prepare_data(self, x: np.array): | ||
""" | ||
Prepare data in the format required for forecasting. | ||
|
||
Args: | ||
---- | ||
x: np.array: input data | ||
seq_len: int: sequence length | ||
horizon: int: forecast horizon | ||
""" | ||
ds = ForecastDataset(x, seq_len=self._seq_len, horizon=self._horizon) | ||
dataloaders = DataLoader(ds, batch_size=1) | ||
|
||
X = np.empty((0, self._seq_len, x.shape[1])) | ||
Y = np.empty((0, self._horizon, 1)) | ||
for x, y in dataloaders: | ||
X = np.concatenate([X, x.numpy()], axis=0) | ||
Y = np.concatenate([Y, y[:, :, 0].unsqueeze(-1).numpy()], axis=0) | ||
X = X.reshape(X.shape[0], -1) | ||
Y = Y.reshape(Y.shape[0], -1) | ||
return X, Y | ||
|
||
def fit(self, df: pd.DataFrame): | ||
_check_data_format(df) | ||
|
||
# Split the data into training and validation sets | ||
train_df = df.iloc[: int(len(df) * (1 - self._val_split)), :] | ||
val_df = df.iloc[int(len(df) * (1 - self._val_split)) :, :] if self._val_split else None | ||
|
||
# Transform and prepare the training data | ||
transformed_train_data = CovariatesGenerator().transform(train_df) | ||
x_train, y_train = self.prepare_data(transformed_train_data) | ||
|
||
# Fit the model with or without validation data | ||
if val_df is not None: | ||
transformed_val_data = CovariatesGenerator().transform(val_df) | ||
x_val, y_val = self.prepare_data(transformed_val_data) | ||
_LOGGER.info("Fitting the model with validation data") | ||
self._model.fit(x_train, y_train, eval_set=[(x_val, y_val)], verbose=True) | ||
else: | ||
_LOGGER.info("Fitting the model without validation data") | ||
self._model.fit(x_train, y_train, verbose=False) | ||
|
||
def predict_horizon(self, df: pd.DataFrame) -> np.ndarray: | ||
_check_data_format(df) | ||
transformed_test_data = CovariatesGenerator().transform(df) | ||
_LOGGER.info("Predicting the horizon") | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. remove log There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. or maybe use debug |
||
x_test, y_test = self.prepare_data(transformed_test_data) | ||
return self._model.predict(x_test) | ||
|
||
def predict_last(self, df: pd.DataFrame) -> np.ndarray: | ||
_check_data_format(df) | ||
transformed_test_data = CovariatesGenerator().transform(df) | ||
_LOGGER.info("Predicting the last value") | ||
x_test, y_test = self.prepare_data(transformed_test_data) | ||
return self._model.predict(x_test[-1].reshape(1, -1)) | ||
|
||
def save_artifacts(self, path: str) -> None: | ||
artifact = {"model": self._model} | ||
torch.save(artifact, path) | ||
_LOGGER.info("Model saved at %s", path) | ||
|
||
def load_artifacts(self, path: str) -> None: | ||
artifact = torch.load(path) | ||
self._model = artifact["model"] | ||
_LOGGER.info(f"Model loaded from {path}") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
import logging | ||
from typing import Union | ||
|
||
import numpy as np | ||
import pandas as pd | ||
from darts import TimeSeries | ||
from darts.utils.timeseries_generation import datetime_attribute_timeseries | ||
|
||
from numalogic.base import StatelessTransformer | ||
|
||
_LOGGER = logging.getLogger(__name__) | ||
|
||
|
||
class CovariatesGenerator(StatelessTransformer): | ||
"""A transformer/generator that generates covariates for a timeseries dataset. | ||
|
||
Args: | ||
---- | ||
timestamp_column_name: The name of the timestamp column | ||
columns_to_preserve: The columns to preserve in the dataset | ||
*covariate_attributes: The tuple of attributes to consider for generating covariates | ||
""" | ||
|
||
def __init__( | ||
self, | ||
timestamp_column_name: str = "timestamp", | ||
columns_to_preserve: Union[str, list[str]] = "value", | ||
*covariate_attributes: tuple[str], | ||
): | ||
self.covariate_attributes = ( | ||
covariate_attributes if covariate_attributes else ("dayofweek", "month", "dayofyear") | ||
) | ||
self.timestamp_column_name = timestamp_column_name | ||
self.columns_to_preserve = columns_to_preserve | ||
|
||
def _get_covariates(self, df: pd.DataFrame): | ||
covariates = [] | ||
_LOGGER.info("Generating covariates for %s", self.covariate_attributes) | ||
for attribute in self.covariate_attributes: | ||
day_series = datetime_attribute_timeseries( | ||
TimeSeries.from_dataframe( | ||
df.reset_index(), self.timestamp_column_name, self.columns_to_preserve | ||
), | ||
attribute=attribute, | ||
one_hot=False, | ||
cyclic=True, | ||
).values() | ||
covariates.append(day_series) | ||
return np.concatenate(covariates, axis=1) | ||
|
||
def transform(self, input_: pd.DataFrame, **__): | ||
""" | ||
Generate covariates for a timeseries dataset. | ||
|
||
Args: | ||
---- | ||
data: np.array: input data | ||
""" | ||
covariates = self._get_covariates(input_) | ||
return np.concatenate([input_.to_numpy(), covariates], axis=1) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can you cover these lines with tests?