-
Notifications
You must be signed in to change notification settings - Fork 60
XGBoost Support for Forecast Operator #1311
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
Merged
Merged
Changes from 12 commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
63b826e
support for xgboost forecast
prasankh 638971a
test update
prasankh 293ad52
doc update
prasankh 8680f7e
support for xgboost forecast
prasankh 47ddd5e
Merge branch 'main' into feature/xgboost-forecast
prasankh 4f0ecec
adding xgboost dependency
prasankh 4a27b25
infer freq fix
prasankh 0c81f74
pinning xgboost to avoid nvidia nccl
prasankh 80c8201
disk space github issue fix
prasankh 794180d
disk space fix
prasankh 6d5742b
Merge branch 'main' into feature/xgboost-forecast
prasankh 6e99e9b
test cases fixed
prasankh 46f3c4c
auto-select fix
prasankh c5d5741
support for lightgbm recursive_models
prasankh 62c5079
dummy commit to retrigger oca bot
prasankh 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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
179 changes: 179 additions & 0 deletions
179
ads/opctl/operator/lowcode/forecast/model/lgbforecast.py
This file contains hidden or 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,179 @@ | ||
| #!/usr/bin/env python | ||
|
|
||
| # Copyright (c) 2024 Oracle and/or its affiliates. | ||
| # Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/ | ||
| import logging | ||
| import traceback | ||
|
|
||
| import pandas as pd | ||
|
|
||
| from ads.common.decorator import runtime_dependency | ||
| from ads.opctl import logger | ||
| from .forecast_datasets import ForecastDatasets, ForecastOutput | ||
| from .ml_forecast import MLForecastBaseModel | ||
| from ..const import ForecastOutputColumns, SupportedModels | ||
| from ..operator_config import ForecastOperatorConfig | ||
|
|
||
|
|
||
| class LGBForecastOperatorModel(MLForecastBaseModel): | ||
| """Class representing MLForecast operator model.""" | ||
|
|
||
| def __init__(self, config: ForecastOperatorConfig, datasets: ForecastDatasets): | ||
| super().__init__(config=config, datasets=datasets) | ||
|
|
||
| def get_model_kwargs(self): | ||
| """ | ||
| Returns the model parameters. | ||
| """ | ||
| model_kwargs = self.spec.model_kwargs | ||
|
|
||
| upper_quantile = round(0.5 + self.spec.confidence_interval_width / 2, 2) | ||
| lower_quantile = round(0.5 - self.spec.confidence_interval_width / 2, 2) | ||
|
|
||
| model_kwargs["lower_quantile"] = lower_quantile | ||
| model_kwargs["upper_quantile"] = upper_quantile | ||
| return model_kwargs | ||
|
|
||
|
|
||
| def preprocess(self, df, series_id): | ||
| pass | ||
|
|
||
| @runtime_dependency( | ||
| module="mlforecast", | ||
| err_msg="MLForecast is not installed, please install it with 'pip install mlforecast'", | ||
| ) | ||
| @runtime_dependency( | ||
| module="lightgbm", | ||
| err_msg="lightgbm is not installed, please install it with 'pip install lightgbm'", | ||
| ) | ||
| def _train_model(self, data_train, data_test, model_kwargs): | ||
| import lightgbm as lgb | ||
| from mlforecast import MLForecast | ||
| try: | ||
|
|
||
| lgb_params = { | ||
| "verbosity": model_kwargs.get("verbosity", -1), | ||
| "num_leaves": model_kwargs.get("num_leaves", 512), | ||
| } | ||
|
|
||
| data_freq = self.datasets.get_datetime_frequency() | ||
|
|
||
| additional_data_params = self.set_model_config(data_freq, model_kwargs) | ||
|
|
||
| fcst = MLForecast( | ||
| models={ | ||
| "forecast": lgb.LGBMRegressor(**lgb_params), | ||
| "upper": lgb.LGBMRegressor( | ||
| **lgb_params, | ||
| objective="quantile", | ||
| alpha=model_kwargs["upper_quantile"], | ||
| ), | ||
| "lower": lgb.LGBMRegressor( | ||
| **lgb_params, | ||
| objective="quantile", | ||
| alpha=model_kwargs["lower_quantile"], | ||
| ), | ||
| }, | ||
| freq=data_freq, | ||
| date_features=['year', 'month', 'day', 'dayofweek', 'dayofyear'], | ||
| **additional_data_params, | ||
| ) | ||
|
|
||
| num_models = model_kwargs.get("recursive_models", False) | ||
|
|
||
| self.model_columns = [ | ||
| ForecastOutputColumns.SERIES | ||
| ] + data_train.select_dtypes(exclude=["object"]).columns.to_list() | ||
| fcst.fit( | ||
| data_train[self.model_columns], | ||
| static_features=model_kwargs.get("static_features", []), | ||
| id_col=ForecastOutputColumns.SERIES, | ||
| time_col=self.date_col, | ||
| target_col=self.spec.target_column, | ||
| fitted=True, | ||
| max_horizon=None if num_models is False else self.spec.horizon, | ||
| ) | ||
|
|
||
| self.outputs = fcst.predict( | ||
| h=self.spec.horizon, | ||
| X_df=pd.concat( | ||
| [ | ||
| data_test[self.model_columns], | ||
| fcst.get_missing_future( | ||
| h=self.spec.horizon, X_df=data_test[self.model_columns] | ||
| ), | ||
| ], | ||
| axis=0, | ||
| ignore_index=True, | ||
| ).fillna(0), | ||
| ) | ||
| self.fitted_values = fcst.forecast_fitted_values() | ||
| for s_id in self.datasets.list_series_ids(): | ||
| self.forecast_output.init_series_output( | ||
| series_id=s_id, | ||
| data_at_series=self.datasets.get_data_at_series(s_id), | ||
| ) | ||
|
|
||
| self.forecast_output.populate_series_output( | ||
| series_id=s_id, | ||
| fit_val=self.fitted_values[ | ||
| self.fitted_values[ForecastOutputColumns.SERIES] == s_id | ||
| ].forecast.values, | ||
| forecast_val=self.outputs[ | ||
| self.outputs[ForecastOutputColumns.SERIES] == s_id | ||
| ].forecast.values, | ||
| upper_bound=self.outputs[ | ||
| self.outputs[ForecastOutputColumns.SERIES] == s_id | ||
| ].upper.values, | ||
| lower_bound=self.outputs[ | ||
| self.outputs[ForecastOutputColumns.SERIES] == s_id | ||
| ].lower.values, | ||
| ) | ||
|
|
||
| self.model_parameters[s_id] = { | ||
| "framework": SupportedModels.LGBForecast, | ||
| **lgb_params, | ||
| **fcst.models_['forecast'].get_params(), | ||
| } | ||
|
|
||
| logger.debug("===========Done===========") | ||
|
|
||
| except Exception as e: | ||
| self.errors_dict[self.spec.model] = { | ||
| "model_name": self.spec.model, | ||
| "error": str(e), | ||
| "error_trace": traceback.format_exc(), | ||
| } | ||
| logger.warning(f"Encountered Error: {e}. Skipping.") | ||
| logger.warning(traceback.format_exc()) | ||
| raise e | ||
|
|
||
|
|
||
| def _generate_report(self): | ||
| """ | ||
| Generates the report for the model | ||
| """ | ||
| import report_creator as rc | ||
|
|
||
| logging.getLogger("report_creator").setLevel(logging.WARNING) | ||
|
|
||
| # Section 2: LGBForecast Model Parameters | ||
| sec2_text = rc.Block( | ||
| rc.Heading("LGBForecast Model Parameters", level=2), | ||
| rc.Text("These are the parameters used for the LGBForecast model."), | ||
| ) | ||
|
|
||
| k, v = next(iter(self.model_parameters.items())) | ||
| sec_2 = rc.Html( | ||
| pd.DataFrame(list(v.items())).to_html(index=False, header=False), | ||
| ) | ||
|
|
||
| all_sections = [sec2_text, sec_2] | ||
| model_description = rc.Text( | ||
| "LGBForecast uses mlforecast framework to perform time series forecasting using machine learning models" | ||
| "with the option to scale to massive amounts of data using remote clusters." | ||
| "Fastest implementations of feature engineering for time series forecasting in Python." | ||
| "Support for exogenous variables and static covariates." | ||
| ) | ||
|
|
||
| return model_description, all_sections | ||
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.
Uh oh!
There was an error while loading. Please reload this page.