Auto Ml Forecasting Hierarchical Timeseries
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License.
![]()
!Important!
This notebook is outdated and is not supported by the AutoML Team. Please use the supported version (link).
Hierarchical Time Series - Automated ML
Generate hierarchical time series forecasts with Automated Machine Learning
For this notebook we are using a synthetic dataset portraying sales data to predict the the quantity of a vartiety of product skus across several states, stores, and product categories.
NOTE: There are limits on how many runs we can do in parallel per workspace, and we currently recommend to set the parallelism to maximum of 320 runs per experiment per workspace. If users want to have more parallelism and increase this limit they might encounter Too Many Requests errors (HTTP 429).
Prerequisites
You'll need to create a compute Instance by following these instructions.
1.0 Set up workspace, datastore, experiment
Choose an experiment
2.0 Data
Upload local csv files to datastore
You can upload your train and inference csv files to the default datastore in your workspace.
A Datastore is a place where data can be stored that is then made accessible to a compute either by means of mounting or copying the data to the compute target. Please refer to Datastore documentation on how to access data from Datastore.
Create the TabularDatasets
Datasets in Azure Machine Learning are references to specific data in a Datastore. The data can be retrieved as a TabularDatasets. We will read in the data as a pandas DataFrame, upload to the data store and register them to your Workspace using register_pandas_dataframe so they can be called as an input into the training pipeline. We will use the inference dataset as part of the forecasting pipeline. The step need only be completed once.
3.0 Build the training pipeline
Now that the dataset, WorkSpace, and datastore are set up, we can put together a pipeline for training.
Note that if you have an AzureML Data Scientist role, you will not have permission to create compute resources. Talk to your workspace or IT admin to create the compute targets described in this section, if they do not already exist.
Choose a compute target
You will need to create a compute target for your AutoML run. In this tutorial, you create AmlCompute as your training compute resource.
**Creation of AmlCompute takes approximately 5 minutes.**
If the AmlCompute with that name is already in your workspace this code will skip the creation process. As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read this article on the default limits and how to request more quota.
Set up training parameters
We need to provide ForecastingParameters, AutoMLConfig and HTSTrainParameters objects. For the forecasting task we need to define several settings including the name of the time column, the maximum forecast horizon, the hierarchy definition, and the level of the hierarchy at which to train.
ForecastingParameters arguments
| Property | Description |
|---|---|
| forecast_horizon | The forecast horizon is how many periods forward you would like to forecast. This integer horizon is in units of the timeseries frequency (e.g. daily, weekly). Periods are inferred from your data. |
| time_column_name | The name of your time column. |
| time_series_id_column_names | The column names used to uniquely identify timeseries in data that has multiple rows with the same timestamp. |
| cv_step_size | Number of periods between two consecutive cross-validation folds. The default value is "auto", in which case AutoMl determines the cross-validation step size automatically, if a validation set is not provided. Or users could specify an integer value. |
AutoMLConfig arguments
| Property | Description |
|---|---|
| task | forecasting |
| primary_metric | This is the metric that you want to optimize. Forecasting supports the following primary metrics spearman_correlation normalized_root_mean_squared_error r2_score normalized_mean_absolute_error |
| blocked_models | Blocked models won't be used by AutoML. |
| iteration_timeout_minutes | Maximum amount of time in minutes that the model can train. This is optional but provides customers with greater control on exit criteria. |
| iterations | Number of models to train. This is optional but provides customers with greater control on exit criteria. |
| experiment_timeout_hours | Maximum amount of time in hours that each experiment can take before it terminates. This is optional but provides customers with greater control on exit criteria. It does not control the overall timeout for the pipeline run, instead controls the timeout for each training run per partitioned time series. |
| label_column_name | The name of the label column. |
| n_cross_validations | Number of cross validation splits. The default value is "auto", in which case AutoMl determines the number of cross-validations automatically, if a validation set is not provided. Or users could specify an integer value. Rolling Origin Validation is used to split time-series in a temporally consistent way. |
| enable_early_stopping | Flag to enable early termination if the primary metric is no longer improving. |
| enable_engineered_explanations | Engineered feature explanations will be downloaded if enable_engineered_explanations flag is set to True. By default it is set to False to save storage space. |
| track_child_runs | Flag to disable tracking of child runs. Only best run is tracked if the flag is set to False (this includes the model and metrics of the run). |
| pipeline_fetch_max_batch_size | Determines how many pipelines (training algorithms) to fetch at a time for training, this helps reduce throttling when training at large scale. |
| model_explainability | Flag to disable explaining the best automated ML model at the end of all training iterations. The default is True and will block non-explainable models which may impact the forecast accuracy. For more information, see Interpretability: model explanations in automated machine learning. |
HTSTrainParameters arguments
| Property | Description |
|---|---|
| automl_settings | The AutoMLConfig object defined above. |
| hierarchy_column_names | The names of columns that define the hierarchical structure of the data from highest level to most granular. |
| training_level | The level of the hierarchy to be used for training models. |
| enable_engineered_explanations | The switch controls engineered explanations. |
Set up hierarchy training pipeline
Parallel run step is leveraged to train multiple models at once. To configure the ParallelRunConfig you will need to determine the appropriate number of workers and nodes for your use case. The process_count_per_node is based off the number of cores of the compute VM. The node_count will determine the number of master nodes to use, increasing the node count will speed up the training process.
| Property | Description |
|---|---|
| experiment | The experiment used for training. |
| train_data | The file dataset to be used as input to the training run. |
| node_count | The number of compute nodes to be used for running the user script. We recommend to start with 3 and increase the node_count if the training time is taking too long. |
| process_count_per_node | Process count per node, we recommend 2:1 ratio for number of cores: number of processes per node. eg. If node has 16 cores then configure 8 or less process count per node for optimal performance. |
| train_pipeline_parameters | The set of configuration parameters defined in the previous section. |
| run_invocation_timeout | Maximum amount of time in seconds that the ParallelRunStep class is allowed. This is optional but provides customers with greater control on exit criteria. This must be greater than experiment_timeout_hours by at least 300 seconds. |
Calling this method will create a new aggregated dataset which is generated dynamically on pipeline execution.
Note: Total time taken for the training step in the pipeline to complete = $ \frac{t}{ p \times n } \times ts $ where,
- $ t $ is time taken for training one partition (can be viewed in the training logs)
- $ p $ is
process_count_per_node - $ n $ is
node_count - $ ts $ is total number of partitions in time series based on
partition_column_names
Submit the pipeline to run
Next we submit our pipeline to run. The whole training pipeline takes about 1h using a Standard_D16_V3 VM with our current ParallelRunConfig setting.
Check the run status, if training_run is in completed state, continue to forecasting. If training_run is in another state, check the portal for failures.
[Optional] Get the explanations
First we need to download the explanations to the local disk.
The explanations are downloaded to the "training_explanations/azureml" directory.
View the explanations on "state" level.
5.0 Forecasting
For hierarchical forecasting we need to provide the HTSInferenceParameters object.
HTSInferenceParameters arguments
| Property | Description |
|---|---|
| hierarchy_forecast_level: | The default level of the hierarchy to produce prediction/forecast on. |
| allocation_method: | [Optional] The disaggregation method to use if the hierarchy forecast level specified is below the define hierarchy training level. (average historical proportions) 'average_historical_proportions' (proportions of the historical averages) 'proportions_of_historical_average' |
get_many_models_batch_inference_steps arguments
| Property | Description |
|---|---|
| experiment | The experiment used for inference run. |
| inference_data | The data to use for inferencing. It should be the same schema as used for training. |
| compute_target | The compute target that runs the inference pipeline. |
| node_count | The number of compute nodes to be used for running the user script. We recommend to start with the number of cores per node (varies by compute sku). |
| process_count_per_node | [Optional] The number of processes per node. By default it's 2 (should be at most half of the number of cores in a single node of the compute cluster that will be used for the experiment). |
| inference_pipeline_parameters | [Optional] The HTSInferenceParameters object defined above. |
| train_run_id | [Optional] The run id of the training pipeline. By default it is the latest successful training pipeline run in the experiment. |
| train_experiment_name | [Optional] The train experiment that contains the train pipeline. This one is only needed when the train pipeline is not in the same experiement as the inference pipeline. |
| run_invocation_timeout | [Optional] Maximum amount of time in seconds that the ParallelRunStep class is allowed. This is optional but provides customers with greater control on exit criteria. |
Retrieve results
Forecast results can be retrieved through the following code. The prediction results summary and the actual predictions are downloaded in forecast_results folder
Resbumit the Pipeline
The inference pipeline can be submitted with different configurations.