Note
Click here to download the full example code
Simple Forecast¶
You can create and evaluate a forecast with just a few lines of code.
Provide your timeseries as a pandas dataframe with timestamp and value.
For example, to forecast daily sessions data, your dataframe could look like this:
import pandas as pd
df = pd.DataFrame({
"date": ["2020-01-08-00", "2020-01-09-00", "2020-01-10-00"],
"sessions": [10231.0, 12309.0, 12104.0]
})
The time column can be any format recognized by pandas.to_datetime.
In this example, we’ll load a dataset representing log(daily page views)
on the Wikipedia page for Peyton Manning.
It contains values from 2007-12-10 to 2016-01-20. More dataset info
here.
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | from collections import defaultdict
import warnings
warnings.filterwarnings("ignore")
import pandas as pd
import plotly
from greykite.common.data_loader import DataLoader
from greykite.framework.templates.autogen.forecast_config import ForecastConfig
from greykite.framework.templates.autogen.forecast_config import MetadataParam
from greykite.framework.templates.forecaster import Forecaster
from greykite.framework.templates.model_templates import ModelTemplateEnum
from greykite.framework.utils.result_summary import summarize_grid_search_results
# Loads dataset into pandas DataFrame
dl = DataLoader()
df = dl.load_peyton_manning()
# specify dataset information
metadata = MetadataParam(
time_col="ts", # name of the time column ("date" in example above)
value_col="y", # name of the value column ("sessions" in example above)
freq="D" # "H" for hourly, "D" for daily, "W" for weekly, etc.
# Any format accepted by `pandas.date_range`
)
|
Create a forecast¶
You can pick the PROPHET or SILVERKITE
forecasting model template. (see Choose a Model).
In this example, we use SILVERKITE.
You may also use PROPHET to see how a third-party library
is leveraged in the same framework.
63 64 65 66 67 68 69 70 71 72 | forecaster = Forecaster() # Creates forecasts and stores the result
result = forecaster.run_forecast_config( # result is also stored as `forecaster.forecast_result`.
df=df,
config=ForecastConfig(
model_template=ModelTemplateEnum.SILVERKITE.name,
forecast_horizon=365, # forecasts 365 steps ahead
coverage=0.95, # 95% prediction intervals
metadata_param=metadata
)
)
|
Out:
Fitting 3 folds for each of 1 candidates, totalling 3 fits
Check results¶
The output of run_forecast_config is a dictionary that contains
the future forecast, historical forecast performance, and
the original timeseries.
Timeseries¶
Let’s plot the original timeseries.
run_forecast_config returns this as ts.
(The interactive plot is generated by plotly: click to zoom!)
88 89 90 | ts = result.timeseries
fig = ts.plot()
plotly.io.show(fig)
|
Cross-validation¶
By default, run_forecast_config provides historical evaluation,
so you can see how the forecast performs on past data.
This is stored in grid_search (cross-validation splits)
and backtest (holdout test set).
Let’s check the cross-validation results.
By default, all metrics in ElementwiseEvaluationMetricEnum
are computed on each CV train/test split.
The configuration of CV evaluation metrics can be found at
Evaluation Metric.
Below, we show the Mean Absolute Percentage Error (MAPE)
across splits (see summarize_grid_search_results
to control what to show and for details on the output columns).
108 109 110 111 112 113 114 115 116 117 118 | grid_search = result.grid_search
cv_results = summarize_grid_search_results(
grid_search=grid_search,
decimals=2,
# The below saves space in the printed output. Remove to show all available metrics and columns.
cv_report_metrics=None,
column_order=["rank", "mean_test", "split_test", "mean_train", "split_train", "mean_fit_time", "mean_score_time", "params"])
# Transposes to save space in the printed output
cv_results["params"] = cv_results["params"].astype(str)
cv_results.set_index("params", drop=True, inplace=True)
cv_results.transpose()
|
| params | [] |
|---|---|
| rank_test_MAPE | 1 |
| mean_test_MAPE | 7.31 |
| split_test_MAPE | (5.02, 8.53, 8.39) |
| mean_train_MAPE | 4.2 |
| split_train_MAPE | (3.82, 4.25, 4.54) |
| mean_fit_time | 6.32 |
| mean_score_time | 0.76 |
Backtest¶
Let’s plot the historical forecast on the holdout test set. You can zoom in to see how it performed in any given period.
125 126 127 | backtest = result.backtest
fig = backtest.plot()
plotly.io.show(fig)
|