Compare commits
152 Commits
azureml-sd
...
azureml-sd
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dd494e9cac | ||
|
|
352adb7487 | ||
|
|
aebe34b4e8 | ||
|
|
c7e1241e20 | ||
|
|
6529298c24 | ||
|
|
e2dddfde85 | ||
|
|
36d96f96ec | ||
|
|
7ebcfea5a3 | ||
|
|
b20bfed33a | ||
|
|
a66a92e338 | ||
|
|
c56c2c3525 | ||
|
|
4cac072fa4 | ||
|
|
aeab6b3e28 | ||
|
|
015e261f29 | ||
|
|
d2a423dde9 | ||
|
|
3ecbfd6532 | ||
|
|
02ecb2d755 | ||
|
|
122df6e846 | ||
|
|
7d6a0a2051 | ||
|
|
6cc8af80a2 | ||
|
|
f61898f718 | ||
|
|
5cb465171e | ||
|
|
0ce37dd18f | ||
|
|
d835b183a5 | ||
|
|
d3cafebff9 | ||
|
|
354b194a25 | ||
|
|
a52d67bb84 | ||
|
|
421ea3d920 | ||
|
|
24f53f1aa1 | ||
|
|
6fc5d11de2 | ||
|
|
d17547d890 | ||
|
|
928e0d4327 | ||
|
|
05327cfbb9 | ||
|
|
8f7717014b | ||
|
|
a47e50b79a | ||
|
|
8f89d88def | ||
|
|
ec97207bb1 | ||
|
|
a2d20b0f47 | ||
|
|
8180cebd75 | ||
|
|
700ab2d782 | ||
|
|
ec9a5a061d | ||
|
|
467630f955 | ||
|
|
eac6b69bae | ||
|
|
441a5b0141 | ||
|
|
70902df6da | ||
|
|
6f893ff0b4 | ||
|
|
bda592a236 | ||
|
|
8b32e8d5ad | ||
|
|
54a065c698 | ||
|
|
b9718678b3 | ||
|
|
3fa40d2c6d | ||
|
|
883e4a4c59 | ||
|
|
e90826b331 | ||
|
|
ac04172f6d | ||
|
|
8c0000beb4 | ||
|
|
35287ab0d8 | ||
|
|
3fe4f8b038 | ||
|
|
1722678469 | ||
|
|
17da7e8706 | ||
|
|
d2e7213ff3 | ||
|
|
882cb76e8a | ||
|
|
37f37a46c1 | ||
|
|
0cd1412421 | ||
|
|
c3ae9f00f6 | ||
|
|
11b02c650c | ||
|
|
606048c71f | ||
|
|
cb1c354d44 | ||
|
|
c868fff5a2 | ||
|
|
bc4e6611c4 | ||
|
|
0a58881b70 | ||
|
|
2544e85c5f | ||
|
|
7fe27501d1 | ||
|
|
624c46e7f9 | ||
|
|
40fbadd85c | ||
|
|
0c1fc25542 | ||
|
|
e8e1357229 | ||
|
|
ad44f8fa2b | ||
|
|
ee63e759f0 | ||
|
|
b81d97ebbf | ||
|
|
249fb6bbb5 | ||
|
|
cda1f3e4cf | ||
|
|
1d05efaac2 | ||
|
|
3adebd1127 | ||
|
|
a6817063df | ||
|
|
a79f8c254a | ||
|
|
fb4f287458 | ||
|
|
41366a4af0 | ||
|
|
74deb14fac | ||
|
|
4ed1d445ae | ||
|
|
b5c15db0b4 | ||
|
|
91d43bade6 | ||
|
|
bd750f5817 | ||
|
|
637bcc5973 | ||
|
|
ba741fb18d | ||
|
|
ac0ad8d487 | ||
|
|
5019ad6c5a | ||
|
|
41a2ebd2b3 | ||
|
|
53e3283d1d | ||
|
|
ba9c4c5465 | ||
|
|
a6c65f00ec | ||
|
|
95072eabc2 | ||
|
|
12905ef254 | ||
|
|
4cf56eee91 | ||
|
|
d345ff6c37 | ||
|
|
560dcac0a0 | ||
|
|
322087a58c | ||
|
|
e255c000ab | ||
|
|
7871e37ec0 | ||
|
|
58e584e7eb | ||
|
|
1b0d75cb45 | ||
|
|
5c38272fb4 | ||
|
|
e026c56f19 | ||
|
|
4aad830f1c | ||
|
|
c1b125025a | ||
|
|
9f364f7638 | ||
|
|
4beb749a76 | ||
|
|
04fe8c4580 | ||
|
|
498018451a | ||
|
|
04305e33f0 | ||
|
|
d22e76d5e0 | ||
|
|
d71c482f75 | ||
|
|
5775f8a78f | ||
|
|
aae823ecd8 | ||
|
|
f1126e07f9 | ||
|
|
0e4b27a233 | ||
|
|
0a3d5f68a1 | ||
|
|
a6fe2affcb | ||
|
|
ce469ddf6a | ||
|
|
9fe459be79 | ||
|
|
89c35c8ed6 | ||
|
|
33168c7f5d | ||
|
|
1d0766bd46 | ||
|
|
9903e56882 | ||
|
|
a039166b90 | ||
|
|
4e4bf48013 | ||
|
|
0a2408300a | ||
|
|
d99c3f5470 | ||
|
|
3f62fe7d47 | ||
|
|
6059c1dc0c | ||
|
|
8e2032fcde | ||
|
|
824d844cd7 | ||
|
|
bb1c7db690 | ||
|
|
8dad09a42f | ||
|
|
db2bf8ae93 | ||
|
|
820c09734f | ||
|
|
a2a33c70a6 | ||
|
|
2ff791968a | ||
|
|
7186127804 | ||
|
|
b01c52bfd6 | ||
|
|
28be7bcf58 | ||
|
|
37a9350fde | ||
|
|
5080053a35 |
9
CODE_OF_CONDUCT.md
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
# Microsoft Open Source Code of Conduct
|
||||||
|
|
||||||
|
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
|
||||||
|
|
||||||
|
Resources:
|
||||||
|
|
||||||
|
- [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/)
|
||||||
|
- [Microsoft Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/)
|
||||||
|
- Contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with questions or concerns
|
||||||
@@ -28,7 +28,7 @@ git clone https://github.com/Azure/MachineLearningNotebooks.git
|
|||||||
pip install azureml-sdk[notebooks,tensorboard]
|
pip install azureml-sdk[notebooks,tensorboard]
|
||||||
|
|
||||||
# install model explainability component
|
# install model explainability component
|
||||||
pip install azureml-sdk[explain]
|
pip install azureml-sdk[interpret]
|
||||||
|
|
||||||
# install automated ml components
|
# install automated ml components
|
||||||
pip install azureml-sdk[automl]
|
pip install azureml-sdk[automl]
|
||||||
@@ -86,7 +86,7 @@ If you need additional Azure ML SDK components, you can either modify the Docker
|
|||||||
pip install azureml-sdk[automl]
|
pip install azureml-sdk[automl]
|
||||||
|
|
||||||
# install the core SDK and model explainability component
|
# install the core SDK and model explainability component
|
||||||
pip install azureml-sdk[explain]
|
pip install azureml-sdk[interpret]
|
||||||
|
|
||||||
# install the core SDK and experimental components
|
# install the core SDK and experimental components
|
||||||
pip install azureml-sdk[contrib]
|
pip install azureml-sdk[contrib]
|
||||||
|
|||||||
100
README.md
@@ -1,77 +1,43 @@
|
|||||||
# Azure Machine Learning service example notebooks
|
# Azure Machine Learning Python SDK notebooks
|
||||||
|
|
||||||
This repository contains example notebooks demonstrating the [Azure Machine Learning](https://azure.microsoft.com/en-us/services/machine-learning-service/) Python SDK which allows you to build, train, deploy and manage machine learning solutions using Azure. The AML SDK allows you the choice of using local or cloud compute resources, while managing and maintaining the complete data science workflow from the cloud.
|
> a community-driven repository of examples using mlflow for tracking can be found at https://github.com/Azure/azureml-examples
|
||||||
|
|
||||||

|
Welcome to the Azure Machine Learning Python SDK notebooks repository!
|
||||||
|
|
||||||
|
## Getting started
|
||||||
|
|
||||||
## Quick installation
|
These notebooks are recommended for use in an Azure Machine Learning [Compute Instance](https://docs.microsoft.com/azure/machine-learning/concept-compute-instance), where you can run them without any additional set up.
|
||||||
```sh
|
|
||||||
pip install azureml-sdk
|
|
||||||
```
|
|
||||||
Read more detailed instructions on [how to set up your environment](./NBSETUP.md) using Azure Notebook service, your own Jupyter notebook server, or Docker.
|
|
||||||
|
|
||||||
## How to navigate and use the example notebooks?
|
However, the notebooks can be run in any development environment with the correct `azureml` packages installed.
|
||||||
If you are using an Azure Machine Learning Notebook VM, you are all set. Otherwise, you should always run the [Configuration](./configuration.ipynb) notebook first when setting up a notebook library on a new machine or in a new environment. It configures your notebook library to connect to an Azure Machine Learning workspace, and sets up your workspace and compute to be used by many of the other examples.
|
|
||||||
This [index](./index.md) should assist in navigating the Azure Machine Learning notebook samples and encourage efficient retrieval of topics and content.
|
|
||||||
|
|
||||||
If you want to...
|
Install the `azureml.core` Python package:
|
||||||
|
|
||||||
* ...try out and explore Azure ML, start with image classification tutorials: [Part 1 (Training)](./tutorials/image-classification-mnist-data/img-classification-part1-training.ipynb) and [Part 2 (Deployment)](./tutorials/image-classification-mnist-data/img-classification-part2-deploy.ipynb).
|
|
||||||
* ...learn about experimentation and tracking run history, first [train within Notebook](./how-to-use-azureml/training/train-within-notebook/train-within-notebook.ipynb), then try [training on remote VM](./how-to-use-azureml/training/train-on-remote-vm/train-on-remote-vm.ipynb) and [using logging APIs](./how-to-use-azureml/training/logging-api/logging-api.ipynb).
|
|
||||||
* ...train deep learning models at scale, first learn about [Machine Learning Compute](./how-to-use-azureml/training/train-on-amlcompute/train-on-amlcompute.ipynb), and then try [distributed hyperparameter tuning](./how-to-use-azureml/training-with-deep-learning/train-hyperparameter-tune-deploy-with-pytorch/train-hyperparameter-tune-deploy-with-pytorch.ipynb) and [distributed training](./how-to-use-azureml/training-with-deep-learning/distributed-pytorch-with-horovod/distributed-pytorch-with-horovod.ipynb).
|
|
||||||
* ...deploy models as a realtime scoring service, first learn the basics by [training within Notebook and deploying to Azure Container Instance](./how-to-use-azureml/training/train-within-notebook/train-within-notebook.ipynb), then learn how to [production deploy models on Azure Kubernetes Cluster](./how-to-use-azureml/deployment/production-deploy-to-aks/production-deploy-to-aks.ipynb).
|
|
||||||
* ...deploy models as a batch scoring service, first [train a model within Notebook](./how-to-use-azureml/training/train-within-notebook/train-within-notebook.ipynb), then [create Machine Learning Compute for scoring compute](./how-to-use-azureml/training/train-on-amlcompute/train-on-amlcompute.ipynb), and [use Machine Learning Pipelines to deploy your model](https://aka.ms/pl-batch-scoring).
|
|
||||||
* ...monitor your deployed models, learn about using [App Insights](./how-to-use-azureml/deployment/enable-app-insights-in-production-service/enable-app-insights-in-production-service.ipynb).
|
|
||||||
|
|
||||||
## Tutorials
|
|
||||||
|
|
||||||
The [Tutorials](./tutorials) folder contains notebooks for the tutorials described in the [Azure Machine Learning documentation](https://aka.ms/aml-docs).
|
|
||||||
|
|
||||||
## How to use Azure ML
|
|
||||||
|
|
||||||
The [How to use Azure ML](./how-to-use-azureml) folder contains specific examples demonstrating the features of the Azure Machine Learning SDK
|
|
||||||
|
|
||||||
- [Training](./how-to-use-azureml/training) - Examples of how to build models using Azure ML's logging and execution capabilities on local and remote compute targets
|
|
||||||
- [Training with Deep Learning](./how-to-use-azureml/training-with-deep-learning) - Examples demonstrating how to build deep learning models using estimators and parameter sweeps
|
|
||||||
- [Manage Azure ML Service](./how-to-use-azureml/manage-azureml-service) - Examples how to perform tasks, such as authenticate against Azure ML service in different ways.
|
|
||||||
- [Automated Machine Learning](./how-to-use-azureml/automated-machine-learning) - Examples using Automated Machine Learning to automatically generate optimal machine learning pipelines and models
|
|
||||||
- [Machine Learning Pipelines](./how-to-use-azureml/machine-learning-pipelines) - Examples showing how to create and use reusable pipelines for training and batch scoring
|
|
||||||
- [Deployment](./how-to-use-azureml/deployment) - Examples showing how to deploy and manage machine learning models and solutions
|
|
||||||
- [Azure Databricks](./how-to-use-azureml/azure-databricks) - Examples showing how to use Azure ML with Azure Databricks
|
|
||||||
- [Monitor Models](./how-to-use-azureml/monitor-models) - Examples showing how to enable model monitoring services such as DataDrift
|
|
||||||
- [Reinforcement Learning](./how-to-use-azureml/reinforcement-learning) - Examples showing how to train reinforcement learning agents
|
|
||||||
|
|
||||||
---
|
|
||||||
## Documentation
|
|
||||||
|
|
||||||
* Quickstarts, end-to-end tutorials, and how-tos on the [official documentation site for Azure Machine Learning service](https://docs.microsoft.com/en-us/azure/machine-learning/service/).
|
|
||||||
* [Python SDK reference](https://docs.microsoft.com/en-us/python/api/overview/azure/ml/intro?view=azure-ml-py)
|
|
||||||
* Azure ML Data Prep SDK [overview](https://aka.ms/data-prep-sdk), [Python SDK reference](https://aka.ms/aml-data-prep-apiref), and [tutorials and how-tos](https://aka.ms/aml-data-prep-notebooks).
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
|
|
||||||
## Community Repository
|
|
||||||
Visit this [community repository](https://github.com/microsoft/MLOps/tree/master/examples) to find useful end-to-end sample notebooks. Also, please follow these [contribution guidelines](https://github.com/microsoft/MLOps/blob/master/contributing.md) when contributing to this repository.
|
|
||||||
|
|
||||||
## Projects using Azure Machine Learning
|
|
||||||
|
|
||||||
Visit following repos to see projects contributed by Azure ML users:
|
|
||||||
- [AMLSamples](https://github.com/Azure/AMLSamples) Number of end-to-end examples, including face recognition, predictive maintenance, customer churn and sentiment analysis.
|
|
||||||
- [Learn about Natural Language Processing best practices using Azure Machine Learning service](https://github.com/microsoft/nlp)
|
|
||||||
- [Pre-Train BERT models using Azure Machine Learning service](https://github.com/Microsoft/AzureML-BERT)
|
|
||||||
- [Fashion MNIST with Azure ML SDK](https://github.com/amynic/azureml-sdk-fashion)
|
|
||||||
- [UMass Amherst Student Samples](https://github.com/katiehouse3/microsoft-azure-ml-notebooks) - A number of end-to-end machine learning notebooks, including machine translation, image classification, and customer churn, created by students in the 696DS course at UMass Amherst.
|
|
||||||
|
|
||||||
## Data/Telemetry
|
|
||||||
This repository collects usage data and sends it to Mircosoft to help improve our products and services. Read Microsoft's [privacy statement to learn more](https://privacy.microsoft.com/en-US/privacystatement)
|
|
||||||
|
|
||||||
To opt out of tracking, please go to the raw markdown or .ipynb files and remove the following line of code:
|
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
""
|
pip install azureml-core
|
||||||
```
|
```
|
||||||
This URL will be slightly different depending on the file.
|
|
||||||
|
|
||||||

|
Install additional packages as needed:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pip install azureml-mlflow
|
||||||
|
pip install azureml-dataset-runtime
|
||||||
|
pip install azureml-automl-runtime
|
||||||
|
pip install azureml-pipeline
|
||||||
|
pip install azureml-pipeline-steps
|
||||||
|
...
|
||||||
|
```
|
||||||
|
|
||||||
|
We recommend starting with one of the [quickstarts](tutorials/compute-instance-quickstarts).
|
||||||
|
|
||||||
|
## Contributing
|
||||||
|
|
||||||
|
This repository is a push-only mirror. Pull requests are ignored.
|
||||||
|
|
||||||
|
## Code of Conduct
|
||||||
|
|
||||||
|
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). Please see the [code of conduct](CODE_OF_CONDUCT.md) for details.
|
||||||
|
|
||||||
|
## Reference
|
||||||
|
|
||||||
|
- [Documentation](https://docs.microsoft.com/azure/machine-learning)
|
||||||
|
|
||||||
|
|||||||
@@ -103,7 +103,7 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"import azureml.core\n",
|
"import azureml.core\n",
|
||||||
"\n",
|
"\n",
|
||||||
"print(\"This notebook was created using version 1.12.0 of the Azure ML SDK\")\n",
|
"print(\"This notebook was created using version 1.37.0 of the Azure ML SDK\")\n",
|
||||||
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -254,6 +254,8 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"Many of the sample notebooks use Azure ML managed compute (AmlCompute) to train models using a dynamically scalable pool of compute. In this section you will create default compute clusters for use by the other notebooks and any other operations you choose.\n",
|
"Many of the sample notebooks use Azure ML managed compute (AmlCompute) to train models using a dynamically scalable pool of compute. In this section you will create default compute clusters for use by the other notebooks and any other operations you choose.\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"> 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.\n",
|
||||||
|
"\n",
|
||||||
"To create a cluster, you need to specify a compute configuration that specifies the type of machine to be used and the scalability behaviors. Then you choose a name for the cluster that is unique within the workspace that can be used to address the cluster later.\n",
|
"To create a cluster, you need to specify a compute configuration that specifies the type of machine to be used and the scalability behaviors. Then you choose a name for the cluster that is unique within the workspace that can be used to address the cluster later.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"The cluster parameters are:\n",
|
"The cluster parameters are:\n",
|
||||||
|
|||||||
@@ -36,9 +36,9 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"<a id=\"Introduction\"></a>\n",
|
"<a id=\"Introduction\"></a>\n",
|
||||||
"## Introduction\n",
|
"## Introduction\n",
|
||||||
"This notebook shows how to use [Fairlearn (an open source fairness assessment and unfairness mitigation package)](http://fairlearn.github.io) and Azure Machine Learning Studio for a binary classification problem. This example uses the well-known adult census dataset. For the purposes of this notebook, we shall treat this as a loan decision problem. We will pretend that the label indicates whether or not each individual repaid a loan in the past. We will use the data to train a predictor to predict whether previously unseen individuals will repay a loan or not. The assumption is that the model predictions are used to decide whether an individual should be offered a loan. Its purpose is purely illustrative of a workflow including a fairness dashboard - in particular, we do **not** include a full discussion of the detailed issues which arise when considering fairness in machine learning. For such discussions, please [refer to the Fairlearn website](http://fairlearn.github.io/).\n",
|
"This notebook shows how to use [Fairlearn (an open source fairness assessment and unfairness mitigation package)](http://fairlearn.org) and Azure Machine Learning Studio for a binary classification problem. This example uses the well-known adult census dataset. For the purposes of this notebook, we shall treat this as a loan decision problem. We will pretend that the label indicates whether or not each individual repaid a loan in the past. We will use the data to train a predictor to predict whether previously unseen individuals will repay a loan or not. The assumption is that the model predictions are used to decide whether an individual should be offered a loan. Its purpose is purely illustrative of a workflow including a fairness dashboard - in particular, we do **not** include a full discussion of the detailed issues which arise when considering fairness in machine learning. For such discussions, please [refer to the Fairlearn website](http://fairlearn.org/).\n",
|
||||||
"\n",
|
"\n",
|
||||||
"We will apply the [grid search algorithm](https://fairlearn.github.io/api_reference/fairlearn.reductions.html#fairlearn.reductions.GridSearch) from the Fairlearn package using a specific notion of fairness called Demographic Parity. This produces a set of models, and we will view these in a dashboard both locally and in the Azure Machine Learning Studio.\n",
|
"We will apply the [grid search algorithm](https://fairlearn.org/v0.4.6/api_reference/fairlearn.reductions.html#fairlearn.reductions.GridSearch) from the Fairlearn package using a specific notion of fairness called Demographic Parity. This produces a set of models, and we will view these in a dashboard both locally and in the Azure Machine Learning Studio.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"### Setup\n",
|
"### Setup\n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -46,9 +46,10 @@
|
|||||||
"Please see the [configuration notebook](../../configuration.ipynb) for information about creating one, if required.\n",
|
"Please see the [configuration notebook](../../configuration.ipynb) for information about creating one, if required.\n",
|
||||||
"This notebook also requires the following packages:\n",
|
"This notebook also requires the following packages:\n",
|
||||||
"* `azureml-contrib-fairness`\n",
|
"* `azureml-contrib-fairness`\n",
|
||||||
"* `fairlearn==0.4.6`\n",
|
"* `fairlearn>=0.6.2` (pre-v0.5.0 will work with minor modifications)\n",
|
||||||
"* `joblib`\n",
|
"* `joblib`\n",
|
||||||
"* `shap`\n",
|
"* `liac-arff`\n",
|
||||||
|
"* `raiwidgets~=0.7.0`\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Fairlearn relies on features introduced in v0.22.1 of `scikit-learn`. If you have an older version already installed, please uncomment and run the following cell:"
|
"Fairlearn relies on features introduced in v0.22.1 of `scikit-learn`. If you have an older version already installed, please uncomment and run the following cell:"
|
||||||
]
|
]
|
||||||
@@ -62,13 +63,20 @@
|
|||||||
"# !pip install --upgrade scikit-learn>=0.22.1"
|
"# !pip install --upgrade scikit-learn>=0.22.1"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Finally, please ensure that when you downloaded this notebook, you also downloaded the `fairness_nb_utils.py` file from the same location, and placed it in the same directory as this notebook."
|
||||||
|
]
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"<a id=\"LoadingData\"></a>\n",
|
"<a id=\"LoadingData\"></a>\n",
|
||||||
"## Loading the Data\n",
|
"## Loading the Data\n",
|
||||||
"We use the well-known `adult` census dataset, which we load using `shap` (for convenience). We start with a fairly unremarkable set of imports:"
|
"We use the well-known `adult` census dataset, which we will fetch from the OpenML website. We start with a fairly unremarkable set of imports:"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -78,90 +86,141 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from fairlearn.reductions import GridSearch, DemographicParity, ErrorRate\n",
|
"from fairlearn.reductions import GridSearch, DemographicParity, ErrorRate\n",
|
||||||
"from fairlearn.widget import FairlearnDashboard\n",
|
"from raiwidgets import FairnessDashboard\n",
|
||||||
"from sklearn import svm\n",
|
"\n",
|
||||||
"from sklearn.preprocessing import LabelEncoder, StandardScaler\n",
|
"from sklearn.compose import ColumnTransformer\n",
|
||||||
|
"from sklearn.impute import SimpleImputer\n",
|
||||||
"from sklearn.linear_model import LogisticRegression\n",
|
"from sklearn.linear_model import LogisticRegression\n",
|
||||||
"import pandas as pd\n",
|
|
||||||
"import shap"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"We can now load and inspect the data from the `shap` package:"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"X_raw, Y = shap.datasets.adult()\n",
|
|
||||||
"X_raw[\"Race\"].value_counts().to_dict()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"We are going to treat the sex of each individual as a protected attribute (where 0 indicates female and 1 indicates male), and in this particular case we are going separate this attribute out and drop it from the main data (this is not always the best option - see the [Fairlearn website](http://fairlearn.github.io/) for further discussion). We also separate out the Race column, but we will not perform any mitigation based on it. Finally, we perform some standard data preprocessing steps to convert the data into a format suitable for the ML algorithms"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"A = X_raw[['Sex','Race']]\n",
|
|
||||||
"X = X_raw.drop(labels=['Sex', 'Race'],axis = 1)\n",
|
|
||||||
"X = pd.get_dummies(X)\n",
|
|
||||||
"\n",
|
|
||||||
"\n",
|
|
||||||
"le = LabelEncoder()\n",
|
|
||||||
"Y = le.fit_transform(Y)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"With our data prepared, we can make the conventional split in to 'test' and 'train' subsets:"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from sklearn.model_selection import train_test_split\n",
|
"from sklearn.model_selection import train_test_split\n",
|
||||||
"X_train, X_test, Y_train, Y_test, A_train, A_test = train_test_split(X_raw, \n",
|
"from sklearn.preprocessing import StandardScaler, OneHotEncoder\n",
|
||||||
" Y, \n",
|
"from sklearn.compose import make_column_selector as selector\n",
|
||||||
" A,\n",
|
"from sklearn.pipeline import Pipeline\n",
|
||||||
" test_size = 0.2,\n",
|
"\n",
|
||||||
" random_state=0,\n",
|
"import pandas as pd"
|
||||||
" stratify=Y)\n",
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"We can now load and inspect the data:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from fairness_nb_utils import fetch_census_dataset\n",
|
||||||
|
"\n",
|
||||||
|
"data = fetch_census_dataset()\n",
|
||||||
|
" \n",
|
||||||
|
"# Extract the items we want\n",
|
||||||
|
"X_raw = data.data\n",
|
||||||
|
"y = (data.target == '>50K') * 1\n",
|
||||||
|
"\n",
|
||||||
|
"X_raw[\"race\"].value_counts().to_dict()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"We are going to treat the sex and race of each individual as protected attributes, and in this particular case we are going to remove these attributes from the main data (this is not always the best option - see the [Fairlearn website](http://fairlearn.github.io/) for further discussion). Protected attributes are often denoted by 'A' in the literature, and we follow that convention here:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"A = X_raw[['sex','race']]\n",
|
||||||
|
"X_raw = X_raw.drop(labels=['sex', 'race'], axis = 1)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"We now preprocess our data. To avoid the problem of data leakage, we split our data into training and test sets before performing any other transformations. Subsequent transformations (such as scalings) will be fit to the training data set, and then applied to the test dataset."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"(X_train, X_test, y_train, y_test, A_train, A_test) = train_test_split(\n",
|
||||||
|
" X_raw, y, A, test_size=0.3, random_state=12345, stratify=y\n",
|
||||||
|
")\n",
|
||||||
|
"\n",
|
||||||
|
"# Ensure indices are aligned between X, y and A,\n",
|
||||||
|
"# after all the slicing and splitting of DataFrames\n",
|
||||||
|
"# and Series\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# Work around indexing issue\n",
|
|
||||||
"X_train = X_train.reset_index(drop=True)\n",
|
"X_train = X_train.reset_index(drop=True)\n",
|
||||||
"A_train = A_train.reset_index(drop=True)\n",
|
|
||||||
"X_test = X_test.reset_index(drop=True)\n",
|
"X_test = X_test.reset_index(drop=True)\n",
|
||||||
"A_test = A_test.reset_index(drop=True)\n",
|
"y_train = y_train.reset_index(drop=True)\n",
|
||||||
|
"y_test = y_test.reset_index(drop=True)\n",
|
||||||
|
"A_train = A_train.reset_index(drop=True)\n",
|
||||||
|
"A_test = A_test.reset_index(drop=True)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"We have two types of column in the dataset - categorical columns which will need to be one-hot encoded, and numeric ones which will need to be rescaled. We also need to take care of missing values. We use a simple approach here, but please bear in mind that this is another way that bias could be introduced (especially if one subgroup tends to have more missing values).\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# Improve labels\n",
|
"For this preprocessing, we make use of `Pipeline` objects from `sklearn`:"
|
||||||
"A_test.Sex.loc[(A_test['Sex'] == 0)] = 'female'\n",
|
]
|
||||||
"A_test.Sex.loc[(A_test['Sex'] == 1)] = 'male'\n",
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"numeric_transformer = Pipeline(\n",
|
||||||
|
" steps=[\n",
|
||||||
|
" (\"impute\", SimpleImputer()),\n",
|
||||||
|
" (\"scaler\", StandardScaler()),\n",
|
||||||
|
" ]\n",
|
||||||
|
")\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"categorical_transformer = Pipeline(\n",
|
||||||
|
" [\n",
|
||||||
|
" (\"impute\", SimpleImputer(strategy=\"most_frequent\")),\n",
|
||||||
|
" (\"ohe\", OneHotEncoder(handle_unknown=\"ignore\", sparse=False)),\n",
|
||||||
|
" ]\n",
|
||||||
|
")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"A_test.Race.loc[(A_test['Race'] == 0)] = 'Amer-Indian-Eskimo'\n",
|
"preprocessor = ColumnTransformer(\n",
|
||||||
"A_test.Race.loc[(A_test['Race'] == 1)] = 'Asian-Pac-Islander'\n",
|
" transformers=[\n",
|
||||||
"A_test.Race.loc[(A_test['Race'] == 2)] = 'Black'\n",
|
" (\"num\", numeric_transformer, selector(dtype_exclude=\"category\")),\n",
|
||||||
"A_test.Race.loc[(A_test['Race'] == 3)] = 'Other'\n",
|
" (\"cat\", categorical_transformer, selector(dtype_include=\"category\")),\n",
|
||||||
"A_test.Race.loc[(A_test['Race'] == 4)] = 'White'"
|
" ]\n",
|
||||||
|
")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Now, the preprocessing pipeline is defined, we can run it on our training data, and apply the generated transform to our test data:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"X_train = preprocessor.fit_transform(X_train)\n",
|
||||||
|
"X_test = preprocessor.transform(X_test)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -182,7 +241,7 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"unmitigated_predictor = LogisticRegression(solver='liblinear', fit_intercept=True)\n",
|
"unmitigated_predictor = LogisticRegression(solver='liblinear', fit_intercept=True)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"unmitigated_predictor.fit(X_train, Y_train)"
|
"unmitigated_predictor.fit(X_train, y_train)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -198,9 +257,9 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"FairlearnDashboard(sensitive_features=A_test, sensitive_feature_names=['Sex', 'Race'],\n",
|
"FairnessDashboard(sensitive_features=A_test,\n",
|
||||||
" y_true=Y_test,\n",
|
" y_true=y_test,\n",
|
||||||
" y_pred={\"unmitigated\": unmitigated_predictor.predict(X_test)})"
|
" y_pred={\"unmitigated\": unmitigated_predictor.predict(X_test)})"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -250,10 +309,11 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"sweep.fit(X_train, Y_train,\n",
|
"sweep.fit(X_train, y_train,\n",
|
||||||
" sensitive_features=A_train.Sex)\n",
|
" sensitive_features=A_train.sex)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"predictors = sweep._predictors"
|
"# For Fairlearn pre-v0.5.0, need sweep._predictors\n",
|
||||||
|
"predictors = sweep.predictors_"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -270,16 +330,14 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"errors, disparities = [], []\n",
|
"errors, disparities = [], []\n",
|
||||||
"for m in predictors:\n",
|
"for predictor in predictors:\n",
|
||||||
" classifier = lambda X: m.predict(X)\n",
|
|
||||||
" \n",
|
|
||||||
" error = ErrorRate()\n",
|
" error = ErrorRate()\n",
|
||||||
" error.load_data(X_train, pd.Series(Y_train), sensitive_features=A_train.Sex)\n",
|
" error.load_data(X_train, pd.Series(y_train), sensitive_features=A_train.sex)\n",
|
||||||
" disparity = DemographicParity()\n",
|
" disparity = DemographicParity()\n",
|
||||||
" disparity.load_data(X_train, pd.Series(Y_train), sensitive_features=A_train.Sex)\n",
|
" disparity.load_data(X_train, pd.Series(y_train), sensitive_features=A_train.sex)\n",
|
||||||
" \n",
|
" \n",
|
||||||
" errors.append(error.gamma(classifier)[0])\n",
|
" errors.append(error.gamma(predictor.predict)[0])\n",
|
||||||
" disparities.append(disparity.gamma(classifier).max())\n",
|
" disparities.append(disparity.gamma(predictor.predict).max())\n",
|
||||||
" \n",
|
" \n",
|
||||||
"all_results = pd.DataFrame( {\"predictor\": predictors, \"error\": errors, \"disparity\": disparities})\n",
|
"all_results = pd.DataFrame( {\"predictor\": predictors, \"error\": errors, \"disparity\": disparities})\n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -328,17 +386,16 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"FairlearnDashboard(sensitive_features=A_test, \n",
|
"FairnessDashboard(sensitive_features=A_test, \n",
|
||||||
" sensitive_feature_names=['Sex', 'Race'],\n",
|
" y_true=y_test.tolist(),\n",
|
||||||
" y_true=Y_test.tolist(),\n",
|
" y_pred=predictions_dominant)"
|
||||||
" y_pred=predictions_dominant)"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"When using sex as the sensitive feature, we see a Pareto front forming - the set of predictors which represent optimal tradeoffs between accuracy and disparity in predictions. In the ideal case, we would have a predictor at (1,0) - perfectly accurate and without any unfairness under demographic parity (with respect to the protected attribute \"sex\"). The Pareto front represents the closest we can come to this ideal based on our data and choice of estimator. Note the range of the axes - the disparity axis covers more values than the accuracy, so we can reduce disparity substantially for a small loss in accuracy. Finally, we also see that the unmitigated model is towards the top right of the plot, with high accuracy, but worst disparity.\n",
|
"When using sex as the sensitive feature and accuracy as the metric, we see a Pareto front forming - the set of predictors which represent optimal tradeoffs between accuracy and disparity in predictions. In the ideal case, we would have a predictor at (1,0) - perfectly accurate and without any unfairness under demographic parity (with respect to the protected attribute \"sex\"). The Pareto front represents the closest we can come to this ideal based on our data and choice of estimator. Note the range of the axes - the disparity axis covers more values than the accuracy, so we can reduce disparity substantially for a small loss in accuracy. Finally, we also see that the unmitigated model is towards the top right of the plot, with high accuracy, but worst disparity.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"By clicking on individual models on the plot, we can inspect their metrics for disparity and accuracy in greater detail. In a real example, we would then pick the model which represented the best trade-off between accuracy and disparity given the relevant business constraints."
|
"By clicking on individual models on the plot, we can inspect their metrics for disparity and accuracy in greater detail. In a real example, we would then pick the model which represented the best trade-off between accuracy and disparity given the relevant business constraints."
|
||||||
]
|
]
|
||||||
@@ -350,7 +407,7 @@
|
|||||||
"<a id=\"AzureUpload\"></a>\n",
|
"<a id=\"AzureUpload\"></a>\n",
|
||||||
"## Uploading a Fairness Dashboard to Azure\n",
|
"## Uploading a Fairness Dashboard to Azure\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Uploading a fairness dashboard to Azure is a two stage process. The `FairlearnDashboard` invoked in the previous section relies on the underlying Python kernel to compute metrics on demand. This is obviously not available when the fairness dashboard is rendered in AzureML Studio. By default, the dashboard in Azure Machine Learning Studio also requires the models to be registered. The required stages are therefore:\n",
|
"Uploading a fairness dashboard to Azure is a two stage process. The `FairnessDashboard` invoked in the previous section relies on the underlying Python kernel to compute metrics on demand. This is obviously not available when the fairness dashboard is rendered in AzureML Studio. By default, the dashboard in Azure Machine Learning Studio also requires the models to be registered. The required stages are therefore:\n",
|
||||||
"1. Register the dominant models\n",
|
"1. Register the dominant models\n",
|
||||||
"1. Precompute all the required metrics\n",
|
"1. Precompute all the required metrics\n",
|
||||||
"1. Upload to Azure\n",
|
"1. Upload to Azure\n",
|
||||||
@@ -440,12 +497,12 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"sf = { 'sex': A_test.Sex, 'race': A_test.Race }\n",
|
"sf = { 'sex': A_test.sex, 'race': A_test.race }\n",
|
||||||
"\n",
|
"\n",
|
||||||
"from fairlearn.metrics._group_metric_set import _create_group_metric_set\n",
|
"from fairlearn.metrics._group_metric_set import _create_group_metric_set\n",
|
||||||
"\n",
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"dash_dict = _create_group_metric_set(y_true=Y_test,\n",
|
"dash_dict = _create_group_metric_set(y_true=y_test,\n",
|
||||||
" predictions=predictions_dominant_ids,\n",
|
" predictions=predictions_dominant_ids,\n",
|
||||||
" sensitive_features=sf,\n",
|
" sensitive_features=sf,\n",
|
||||||
" prediction_type='binary_classification')"
|
" prediction_type='binary_classification')"
|
||||||
@@ -524,7 +581,7 @@
|
|||||||
"<a id=\"Conclusion\"></a>\n",
|
"<a id=\"Conclusion\"></a>\n",
|
||||||
"## Conclusion\n",
|
"## Conclusion\n",
|
||||||
"\n",
|
"\n",
|
||||||
"In this notebook we have demonstrated how to use the `GridSearch` algorithm from Fairlearn to generate a collection of models, and then present them in the fairness dashboard in Azure Machine Learning Studio. Please remember that this notebook has not attempted to discuss the many considerations which should be part of any approach to unfairness mitigation. The [Fairlearn website](http://fairlearn.github.io/) provides that discussion"
|
"In this notebook we have demonstrated how to use the `GridSearch` algorithm from Fairlearn to generate a collection of models, and then present them in the fairness dashboard in Azure Machine Learning Studio. Please remember that this notebook has not attempted to discuss the many considerations which should be part of any approach to unfairness mitigation. The [Fairlearn website](http://fairlearn.org/) provides that discussion"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
9
contrib/fairness/fairlearn-azureml-mitigation.yml
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
name: fairlearn-azureml-mitigation
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
|
- azureml-contrib-fairness
|
||||||
|
- fairlearn>=0.6.2
|
||||||
|
- joblib
|
||||||
|
- liac-arff
|
||||||
|
- raiwidgets~=0.15.0
|
||||||
111
contrib/fairness/fairness_nb_utils.py
Normal file
@@ -0,0 +1,111 @@
|
|||||||
|
# ---------------------------------------------------------
|
||||||
|
# Copyright (c) Microsoft Corporation. All rights reserved.
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
|
||||||
|
"""Utilities for azureml-contrib-fairness notebooks."""
|
||||||
|
|
||||||
|
import arff
|
||||||
|
from collections import OrderedDict
|
||||||
|
from contextlib import closing
|
||||||
|
import gzip
|
||||||
|
import pandas as pd
|
||||||
|
from sklearn.datasets import fetch_openml
|
||||||
|
from sklearn.utils import Bunch
|
||||||
|
import time
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_openml_with_retries(data_id, max_retries=4, retry_delay=60):
|
||||||
|
"""Fetch a given dataset from OpenML with retries as specified."""
|
||||||
|
for i in range(max_retries):
|
||||||
|
try:
|
||||||
|
print("Download attempt {0} of {1}".format(i + 1, max_retries))
|
||||||
|
data = fetch_openml(data_id=data_id, as_frame=True)
|
||||||
|
break
|
||||||
|
except Exception as e: # noqa: B902
|
||||||
|
print("Download attempt failed with exception:")
|
||||||
|
print(e)
|
||||||
|
if i + 1 != max_retries:
|
||||||
|
print("Will retry after {0} seconds".format(retry_delay))
|
||||||
|
time.sleep(retry_delay)
|
||||||
|
retry_delay = retry_delay * 2
|
||||||
|
else:
|
||||||
|
raise RuntimeError("Unable to download dataset from OpenML")
|
||||||
|
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
_categorical_columns = [
|
||||||
|
'workclass',
|
||||||
|
'education',
|
||||||
|
'marital-status',
|
||||||
|
'occupation',
|
||||||
|
'relationship',
|
||||||
|
'race',
|
||||||
|
'sex',
|
||||||
|
'native-country'
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_census_dataset():
|
||||||
|
"""Fetch the Adult Census Dataset.
|
||||||
|
|
||||||
|
This uses a particular URL for the Adult Census dataset. The code
|
||||||
|
is a simplified version of fetch_openml() in sklearn.
|
||||||
|
|
||||||
|
The data are copied from:
|
||||||
|
https://openml.org/data/v1/download/1595261.gz
|
||||||
|
(as of 2021-03-31)
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
from urllib import urlretrieve
|
||||||
|
except ImportError:
|
||||||
|
from urllib.request import urlretrieve
|
||||||
|
|
||||||
|
filename = "1595261.gz"
|
||||||
|
data_url = "https://rainotebookscdn.blob.core.windows.net/datasets/"
|
||||||
|
|
||||||
|
remaining_attempts = 5
|
||||||
|
sleep_duration = 10
|
||||||
|
while remaining_attempts > 0:
|
||||||
|
try:
|
||||||
|
urlretrieve(data_url + filename, filename)
|
||||||
|
|
||||||
|
http_stream = gzip.GzipFile(filename=filename, mode='rb')
|
||||||
|
|
||||||
|
with closing(http_stream):
|
||||||
|
def _stream_generator(response):
|
||||||
|
for line in response:
|
||||||
|
yield line.decode('utf-8')
|
||||||
|
|
||||||
|
stream = _stream_generator(http_stream)
|
||||||
|
data = arff.load(stream)
|
||||||
|
except Exception as exc: # noqa: B902
|
||||||
|
remaining_attempts -= 1
|
||||||
|
print("Error downloading dataset from {} ({} attempt(s) remaining)"
|
||||||
|
.format(data_url, remaining_attempts))
|
||||||
|
print(exc)
|
||||||
|
time.sleep(sleep_duration)
|
||||||
|
sleep_duration *= 2
|
||||||
|
continue
|
||||||
|
else:
|
||||||
|
# dataset successfully downloaded
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
raise Exception("Could not retrieve dataset from {}.".format(data_url))
|
||||||
|
|
||||||
|
attributes = OrderedDict(data['attributes'])
|
||||||
|
arff_columns = list(attributes)
|
||||||
|
|
||||||
|
raw_df = pd.DataFrame(data=data['data'], columns=arff_columns)
|
||||||
|
|
||||||
|
target_column_name = 'class'
|
||||||
|
target = raw_df.pop(target_column_name)
|
||||||
|
for col_name in _categorical_columns:
|
||||||
|
dtype = pd.api.types.CategoricalDtype(attributes[col_name])
|
||||||
|
raw_df[col_name] = raw_df[col_name].astype(dtype, copy=False)
|
||||||
|
|
||||||
|
result = Bunch()
|
||||||
|
result.data = raw_df
|
||||||
|
result.target = target
|
||||||
|
|
||||||
|
return result
|
||||||
@@ -30,7 +30,7 @@
|
|||||||
"1. [Training Models](#TrainingModels)\n",
|
"1. [Training Models](#TrainingModels)\n",
|
||||||
"1. [Logging in to AzureML](#LoginAzureML)\n",
|
"1. [Logging in to AzureML](#LoginAzureML)\n",
|
||||||
"1. [Registering the Models](#RegisterModels)\n",
|
"1. [Registering the Models](#RegisterModels)\n",
|
||||||
"1. [Using the Fairlearn Dashboard](#LocalDashboard)\n",
|
"1. [Using the Fairness Dashboard](#LocalDashboard)\n",
|
||||||
"1. [Uploading a Fairness Dashboard to Azure](#AzureUpload)\n",
|
"1. [Uploading a Fairness Dashboard to Azure](#AzureUpload)\n",
|
||||||
" 1. Computing Fairness Metrics\n",
|
" 1. Computing Fairness Metrics\n",
|
||||||
" 1. Uploading to Azure\n",
|
" 1. Uploading to Azure\n",
|
||||||
@@ -48,9 +48,10 @@
|
|||||||
"Please see the [configuration notebook](../../configuration.ipynb) for information about creating one, if required.\n",
|
"Please see the [configuration notebook](../../configuration.ipynb) for information about creating one, if required.\n",
|
||||||
"This notebook also requires the following packages:\n",
|
"This notebook also requires the following packages:\n",
|
||||||
"* `azureml-contrib-fairness`\n",
|
"* `azureml-contrib-fairness`\n",
|
||||||
"* `fairlearn==0.4.6`\n",
|
"* `fairlearn>=0.6.2` (also works for pre-v0.5.0 with slight modifications)\n",
|
||||||
"* `joblib`\n",
|
"* `joblib`\n",
|
||||||
"* `shap`\n",
|
"* `liac-arff`\n",
|
||||||
|
"* `raiwidgets~=0.7.0`\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Fairlearn relies on features introduced in v0.22.1 of `scikit-learn`. If you have an older version already installed, please uncomment and run the following cell:"
|
"Fairlearn relies on features introduced in v0.22.1 of `scikit-learn`. If you have an older version already installed, please uncomment and run the following cell:"
|
||||||
]
|
]
|
||||||
@@ -64,13 +65,20 @@
|
|||||||
"# !pip install --upgrade scikit-learn>=0.22.1"
|
"# !pip install --upgrade scikit-learn>=0.22.1"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Finally, please ensure that when you downloaded this notebook, you also downloaded the `fairness_nb_utils.py` file from the same location, and placed it in the same directory as this notebook."
|
||||||
|
]
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"<a id=\"LoadingData\"></a>\n",
|
"<a id=\"LoadingData\"></a>\n",
|
||||||
"## Loading the Data\n",
|
"## Loading the Data\n",
|
||||||
"We use the well-known `adult` census dataset, which we load using `shap` (for convenience). We start with a fairly unremarkable set of imports:"
|
"We use the well-known `adult` census dataset, which we fetch from the OpenML website. We start with a fairly unremarkable set of imports:"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -80,10 +88,13 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from sklearn import svm\n",
|
"from sklearn import svm\n",
|
||||||
"from sklearn.preprocessing import LabelEncoder, StandardScaler\n",
|
"from sklearn.compose import ColumnTransformer\n",
|
||||||
|
"from sklearn.impute import SimpleImputer\n",
|
||||||
"from sklearn.linear_model import LogisticRegression\n",
|
"from sklearn.linear_model import LogisticRegression\n",
|
||||||
"import pandas as pd\n",
|
"from sklearn.model_selection import train_test_split\n",
|
||||||
"import shap"
|
"from sklearn.preprocessing import StandardScaler, OneHotEncoder\n",
|
||||||
|
"from sklearn.compose import make_column_selector as selector\n",
|
||||||
|
"from sklearn.pipeline import Pipeline"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -99,7 +110,13 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"X_raw, Y = shap.datasets.adult()"
|
"from fairness_nb_utils import fetch_census_dataset\n",
|
||||||
|
"\n",
|
||||||
|
"data = fetch_census_dataset()\n",
|
||||||
|
" \n",
|
||||||
|
"# Extract the items we want\n",
|
||||||
|
"X_raw = data.data\n",
|
||||||
|
"y = (data.target == '>50K') * 1"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -115,7 +132,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"print(X_raw[\"Race\"].value_counts().to_dict())"
|
"print(X_raw[\"race\"].value_counts().to_dict())"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -125,7 +142,7 @@
|
|||||||
"<a id=\"ProcessingData\"></a>\n",
|
"<a id=\"ProcessingData\"></a>\n",
|
||||||
"## Processing the Data\n",
|
"## Processing the Data\n",
|
||||||
"\n",
|
"\n",
|
||||||
"With the data loaded, we process it for our needs. First, we extract the sensitive features of interest into `A` (conventionally used in the literature) and put the rest of the feature data into `X`:"
|
"With the data loaded, we process it for our needs. First, we extract the sensitive features of interest into `A` (conventionally used in the literature) and leave the rest of the feature data in `X_raw`:"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -134,16 +151,15 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"A = X_raw[['Sex','Race']]\n",
|
"A = X_raw[['sex','race']]\n",
|
||||||
"X = X_raw.drop(labels=['Sex', 'Race'],axis = 1)\n",
|
"X_raw = X_raw.drop(labels=['sex', 'race'],axis = 1)"
|
||||||
"X = pd.get_dummies(X)"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"Next, we apply a standard set of scalings:"
|
"We now preprocess our data. To avoid the problem of data leakage, we split our data into training and test sets before performing any other transformations. Subsequent transformations (such as scalings) will be fit to the training data set, and then applied to the test dataset."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -152,51 +168,74 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"sc = StandardScaler()\n",
|
"(X_train, X_test, y_train, y_test, A_train, A_test) = train_test_split(\n",
|
||||||
"X_scaled = sc.fit_transform(X)\n",
|
" X_raw, y, A, test_size=0.3, random_state=12345, stratify=y\n",
|
||||||
"X_scaled = pd.DataFrame(X_scaled, columns=X.columns)\n",
|
")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"le = LabelEncoder()\n",
|
"# Ensure indices are aligned between X, y and A,\n",
|
||||||
"Y = le.fit_transform(Y)"
|
"# after all the slicing and splitting of DataFrames\n",
|
||||||
]
|
"# and Series\n",
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Finally, we can then split our data into training and test sets, and also make the labels on our test portion of `A` human-readable:"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from sklearn.model_selection import train_test_split\n",
|
|
||||||
"X_train, X_test, Y_train, Y_test, A_train, A_test = train_test_split(X_scaled, \n",
|
|
||||||
" Y, \n",
|
|
||||||
" A,\n",
|
|
||||||
" test_size = 0.2,\n",
|
|
||||||
" random_state=0,\n",
|
|
||||||
" stratify=Y)\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
"# Work around indexing issue\n",
|
|
||||||
"X_train = X_train.reset_index(drop=True)\n",
|
"X_train = X_train.reset_index(drop=True)\n",
|
||||||
"A_train = A_train.reset_index(drop=True)\n",
|
|
||||||
"X_test = X_test.reset_index(drop=True)\n",
|
"X_test = X_test.reset_index(drop=True)\n",
|
||||||
"A_test = A_test.reset_index(drop=True)\n",
|
"y_train = y_train.reset_index(drop=True)\n",
|
||||||
|
"y_test = y_test.reset_index(drop=True)\n",
|
||||||
|
"A_train = A_train.reset_index(drop=True)\n",
|
||||||
|
"A_test = A_test.reset_index(drop=True)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"We have two types of column in the dataset - categorical columns which will need to be one-hot encoded, and numeric ones which will need to be rescaled. We also need to take care of missing values. We use a simple approach here, but please bear in mind that this is another way that bias could be introduced (especially if one subgroup tends to have more missing values).\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# Improve labels\n",
|
"For this preprocessing, we make use of `Pipeline` objects from `sklearn`:"
|
||||||
"A_test.Sex.loc[(A_test['Sex'] == 0)] = 'female'\n",
|
]
|
||||||
"A_test.Sex.loc[(A_test['Sex'] == 1)] = 'male'\n",
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"numeric_transformer = Pipeline(\n",
|
||||||
|
" steps=[\n",
|
||||||
|
" (\"impute\", SimpleImputer()),\n",
|
||||||
|
" (\"scaler\", StandardScaler()),\n",
|
||||||
|
" ]\n",
|
||||||
|
")\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"categorical_transformer = Pipeline(\n",
|
||||||
|
" [\n",
|
||||||
|
" (\"impute\", SimpleImputer(strategy=\"most_frequent\")),\n",
|
||||||
|
" (\"ohe\", OneHotEncoder(handle_unknown=\"ignore\", sparse=False)),\n",
|
||||||
|
" ]\n",
|
||||||
|
")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"A_test.Race.loc[(A_test['Race'] == 0)] = 'Amer-Indian-Eskimo'\n",
|
"preprocessor = ColumnTransformer(\n",
|
||||||
"A_test.Race.loc[(A_test['Race'] == 1)] = 'Asian-Pac-Islander'\n",
|
" transformers=[\n",
|
||||||
"A_test.Race.loc[(A_test['Race'] == 2)] = 'Black'\n",
|
" (\"num\", numeric_transformer, selector(dtype_exclude=\"category\")),\n",
|
||||||
"A_test.Race.loc[(A_test['Race'] == 3)] = 'Other'\n",
|
" (\"cat\", categorical_transformer, selector(dtype_include=\"category\")),\n",
|
||||||
"A_test.Race.loc[(A_test['Race'] == 4)] = 'White'"
|
" ]\n",
|
||||||
|
")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Now, the preprocessing pipeline is defined, we can run it on our training data, and apply the generated transform to our test data:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"X_train = preprocessor.fit_transform(X_train)\n",
|
||||||
|
"X_test = preprocessor.transform(X_test)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -217,7 +256,7 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"lr_predictor = LogisticRegression(solver='liblinear', fit_intercept=True)\n",
|
"lr_predictor = LogisticRegression(solver='liblinear', fit_intercept=True)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"lr_predictor.fit(X_train, Y_train)"
|
"lr_predictor.fit(X_train, y_train)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -235,7 +274,7 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"svm_predictor = svm.SVC()\n",
|
"svm_predictor = svm.SVC()\n",
|
||||||
"\n",
|
"\n",
|
||||||
"svm_predictor.fit(X_train, Y_train)"
|
"svm_predictor.fit(X_train, y_train)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -350,12 +389,11 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from fairlearn.widget import FairlearnDashboard\n",
|
"from raiwidgets import FairnessDashboard\n",
|
||||||
"\n",
|
"\n",
|
||||||
"FairlearnDashboard(sensitive_features=A_test, \n",
|
"FairnessDashboard(sensitive_features=A_test, \n",
|
||||||
" sensitive_feature_names=['Sex', 'Race'],\n",
|
" y_true=y_test.tolist(),\n",
|
||||||
" y_true=Y_test.tolist(),\n",
|
" y_pred=ys_pred)"
|
||||||
" y_pred=ys_pred)"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -365,7 +403,7 @@
|
|||||||
"<a id=\"AzureUpload\"></a>\n",
|
"<a id=\"AzureUpload\"></a>\n",
|
||||||
"## Uploading a Fairness Dashboard to Azure\n",
|
"## Uploading a Fairness Dashboard to Azure\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Uploading a fairness dashboard to Azure is a two stage process. The `FairlearnDashboard` invoked in the previous section relies on the underlying Python kernel to compute metrics on demand. This is obviously not available when the fairness dashboard is rendered in AzureML Studio. The required stages are therefore:\n",
|
"Uploading a fairness dashboard to Azure is a two stage process. The `FairnessDashboard` invoked in the previous section relies on the underlying Python kernel to compute metrics on demand. This is obviously not available when the fairness dashboard is rendered in AzureML Studio. The required stages are therefore:\n",
|
||||||
"1. Precompute all the required metrics\n",
|
"1. Precompute all the required metrics\n",
|
||||||
"1. Upload to Azure\n",
|
"1. Upload to Azure\n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -380,11 +418,11 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"sf = { 'Race': A_test.Race, 'Sex': A_test.Sex }\n",
|
"sf = { 'Race': A_test.race, 'Sex': A_test.sex }\n",
|
||||||
"\n",
|
"\n",
|
||||||
"from fairlearn.metrics._group_metric_set import _create_group_metric_set\n",
|
"from fairlearn.metrics._group_metric_set import _create_group_metric_set\n",
|
||||||
"\n",
|
"\n",
|
||||||
"dash_dict = _create_group_metric_set(y_true=Y_test,\n",
|
"dash_dict = _create_group_metric_set(y_true=y_test,\n",
|
||||||
" predictions=ys_pred,\n",
|
" predictions=ys_pred,\n",
|
||||||
" sensitive_features=sf,\n",
|
" sensitive_features=sf,\n",
|
||||||
" prediction_type='binary_classification')"
|
" prediction_type='binary_classification')"
|
||||||
@@ -499,7 +537,7 @@
|
|||||||
"name": "python",
|
"name": "python",
|
||||||
"nbconvert_exporter": "python",
|
"nbconvert_exporter": "python",
|
||||||
"pygments_lexer": "ipython3",
|
"pygments_lexer": "ipython3",
|
||||||
"version": "3.6.8"
|
"version": "3.6.10"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"nbformat": 4,
|
"nbformat": 4,
|
||||||
|
|||||||
9
contrib/fairness/upload-fairness-dashboard.yml
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
name: upload-fairness-dashboard
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
|
- azureml-contrib-fairness
|
||||||
|
- fairlearn>=0.6.2
|
||||||
|
- joblib
|
||||||
|
- liac-arff
|
||||||
|
- raiwidgets~=0.15.0
|
||||||
@@ -4,7 +4,7 @@ Learn how to use Azure Machine Learning services for experimentation and model m
|
|||||||
|
|
||||||
As a pre-requisite, run the [configuration Notebook](../configuration.ipynb) notebook first to set up your Azure ML Workspace. Then, run the notebooks in following recommended order.
|
As a pre-requisite, run the [configuration Notebook](../configuration.ipynb) notebook first to set up your Azure ML Workspace. Then, run the notebooks in following recommended order.
|
||||||
|
|
||||||
* [train-within-notebook](./training/train-within-notebook): Train a model hile tracking run history, and learn how to deploy the model as web service to Azure Container Instance.
|
* [train-within-notebook](./training/train-within-notebook): Train a model while tracking run history, and learn how to deploy the model as web service to Azure Container Instance.
|
||||||
* [train-on-local](./training/train-on-local): Learn how to submit a run to local computer and use Azure ML managed run configuration.
|
* [train-on-local](./training/train-on-local): Learn how to submit a run to local computer and use Azure ML managed run configuration.
|
||||||
* [train-on-amlcompute](./training/train-on-amlcompute): Use a 1-n node Azure ML managed compute cluster for remote runs on Azure CPU or GPU infrastructure.
|
* [train-on-amlcompute](./training/train-on-amlcompute): Use a 1-n node Azure ML managed compute cluster for remote runs on Azure CPU or GPU infrastructure.
|
||||||
* [train-on-remote-vm](./training/train-on-remote-vm): Use Data Science Virtual Machine as a target for remote runs.
|
* [train-on-remote-vm](./training/train-on-remote-vm): Use Data Science Virtual Machine as a target for remote runs.
|
||||||
|
|||||||
@@ -97,68 +97,96 @@ jupyter notebook
|
|||||||
<a name="databricks"></a>
|
<a name="databricks"></a>
|
||||||
## Setup using Azure Databricks
|
## Setup using Azure Databricks
|
||||||
|
|
||||||
**NOTE**: Please create your Azure Databricks cluster as v6.0 (high concurrency preferred) with **Python 3** (dropdown).
|
**NOTE**: Please create your Azure Databricks cluster as v7.1 (high concurrency preferred) with **Python 3** (dropdown).
|
||||||
**NOTE**: You should at least have contributor access to your Azure subcription to run the notebook.
|
**NOTE**: You should at least have contributor access to your Azure subcription to run the notebook.
|
||||||
- Please remove the previous SDK version if there is any and install the latest SDK by installing **azureml-sdk[automl]** as a PyPi library in Azure Databricks workspace.
|
- You can find the detail Readme instructions at [GitHub](https://github.com/Azure/MachineLearningNotebooks/tree/master/how-to-use-azureml/azure-databricks/automl).
|
||||||
- You can find the detail Readme instructions at [GitHub](https://github.com/Azure/MachineLearningNotebooks/tree/master/how-to-use-azureml/azure-databricks).
|
- Download the sample notebook automl-databricks-local-01.ipynb from [GitHub](https://github.com/Azure/MachineLearningNotebooks/tree/master/how-to-use-azureml/azure-databricks/automl) and import into the Azure databricks workspace.
|
||||||
- Download the sample notebook automl-databricks-local-01.ipynb from [GitHub](https://github.com/Azure/MachineLearningNotebooks/tree/master/how-to-use-azureml/azure-databricks) and import into the Azure databricks workspace.
|
|
||||||
- Attach the notebook to the cluster.
|
- Attach the notebook to the cluster.
|
||||||
|
|
||||||
<a name="samples"></a>
|
<a name="samples"></a>
|
||||||
# Automated ML SDK Sample Notebooks
|
# Automated ML SDK Sample Notebooks
|
||||||
|
|
||||||
- [auto-ml-classification-credit-card-fraud.ipynb](classification-credit-card-fraud/auto-ml-classification-credit-card-fraud.ipynb)
|
## Classification
|
||||||
- Dataset: Kaggle's [credit card fraud detection dataset](https://www.kaggle.com/mlg-ulb/creditcardfraud)
|
- **Classify Credit Card Fraud**
|
||||||
- Simple example of using automated ML for classification to fraudulent credit card transactions
|
- Dataset: [Kaggle's credit card fraud detection dataset](https://www.kaggle.com/mlg-ulb/creditcardfraud)
|
||||||
- Uses azure compute for training
|
- **[Jupyter Notebook (remote run)](classification-credit-card-fraud/auto-ml-classification-credit-card-fraud.ipynb)**
|
||||||
|
- run the experiment remotely on AML Compute cluster
|
||||||
|
- test the performance of the best model in the local environment
|
||||||
|
- **[Jupyter Notebook (local run)](local-run-classification-credit-card-fraud/auto-ml-classification-credit-card-fraud-local.ipynb)**
|
||||||
|
- run experiment in the local environment
|
||||||
|
- use Mimic Explainer for computing feature importance
|
||||||
|
- deploy the best model along with the explainer to an Azure Kubernetes (AKS) cluster, which will compute the raw and engineered feature importances at inference time
|
||||||
|
- **Predict Term Deposit Subscriptions in a Bank**
|
||||||
|
- Dataset: [UCI's bank marketing dataset](https://www.kaggle.com/janiobachmann/bank-marketing-dataset)
|
||||||
|
- **[Jupyter Notebook](classification-bank-marketing-all-features/auto-ml-classification-bank-marketing-all-features.ipynb)**
|
||||||
|
- run experiment remotely on AML Compute cluster to generate ONNX compatible models
|
||||||
|
- view the featurization steps that were applied during training
|
||||||
|
- view feature importance for the best model
|
||||||
|
- download the best model in ONNX format and use it for inferencing using ONNXRuntime
|
||||||
|
- deploy the best model in PKL format to Azure Container Instance (ACI)
|
||||||
|
- **Predict Newsgroup based on Text from News Article**
|
||||||
|
- Dataset: [20 newsgroups text dataset](https://scikit-learn.org/0.19/datasets/twenty_newsgroups.html)
|
||||||
|
- **[Jupyter Notebook](classification-text-dnn/auto-ml-classification-text-dnn.ipynb)**
|
||||||
|
- AutoML highlights here include using deep neural networks (DNNs) to create embedded features from text data
|
||||||
|
- AutoML will use Bidirectional Encoder Representations from Transformers (BERT) when a GPU compute is used
|
||||||
|
- Bidirectional Long-Short Term neural network (BiLSTM) will be utilized when a CPU compute is used, thereby optimizing the choice of DNN
|
||||||
|
|
||||||
- [auto-ml-regression.ipynb](regression/auto-ml-regression.ipynb)
|
## Regression
|
||||||
|
- **Predict Performance of Hardware Parts**
|
||||||
- Dataset: Hardware Performance Dataset
|
- Dataset: Hardware Performance Dataset
|
||||||
- Simple example of using automated ML for regression
|
- **[Jupyter Notebook](regression/auto-ml-regression.ipynb)**
|
||||||
- Uses azure compute for training
|
- run the experiment remotely on AML Compute cluster
|
||||||
|
- get best trained model for a different metric than the one the experiment was optimized for
|
||||||
|
- test the performance of the best model in the local environment
|
||||||
|
- **[Jupyter Notebook (advanced)](regression/auto-ml-regression.ipynb)**
|
||||||
|
- run the experiment remotely on AML Compute cluster
|
||||||
|
- customize featurization: override column purpose within the dataset, configure transformer parameters
|
||||||
|
- get best trained model for a different metric than the one the experiment was optimized for
|
||||||
|
- run a model explanation experiment on the remote cluster
|
||||||
|
- deploy the model along the explainer and run online inferencing
|
||||||
|
|
||||||
- [auto-ml-regression-explanation-featurization.ipynb](regression-explanation-featurization/auto-ml-regression-explanation-featurization.ipynb)
|
## Time Series Forecasting
|
||||||
- Dataset: Hardware Performance Dataset
|
- **Forecast Energy Demand**
|
||||||
- Shows featurization and excplanation
|
- Dataset: [NYC energy demand data](http://mis.nyiso.com/public/P-58Blist.htm)
|
||||||
- Uses azure compute for training
|
- **[Jupyter Notebook](forecasting-energy-demand/auto-ml-forecasting-energy-demand.ipynb)**
|
||||||
|
- run experiment remotely on AML Compute cluster
|
||||||
- [auto-ml-forecasting-energy-demand.ipynb](forecasting-energy-demand/auto-ml-forecasting-energy-demand.ipynb)
|
- use lags and rolling window features
|
||||||
- Dataset: [NYC energy demand data](forecasting-a/nyc_energy.csv)
|
- view the featurization steps that were applied during training
|
||||||
- Example of using automated ML for training a forecasting model
|
- get the best model, use it to forecast on test data and compare the accuracy of predictions against real data
|
||||||
|
- **Forecast Orange Juice Sales (Multi-Series)**
|
||||||
- [auto-ml-classification-credit-card-fraud-local.ipynb](local-run-classification-credit-card-fraud/auto-ml-classification-credit-card-fraud-local.ipynb)
|
- Dataset: [Dominick's grocery sales of orange juice](forecasting-orange-juice-sales/dominicks_OJ.csv)
|
||||||
- Dataset: Kaggle's [credit card fraud detection dataset](https://www.kaggle.com/mlg-ulb/creditcardfraud)
|
- **[Jupyter Notebook](forecasting-orange-juice-sales/dominicks_OJ.csv)**
|
||||||
- Simple example of using automated ML for classification to fraudulent credit card transactions
|
- run experiment remotely on AML Compute cluster
|
||||||
- Uses local compute for training
|
- customize time-series featurization, change column purpose and override transformer hyper parameters
|
||||||
|
- evaluate locally the performance of the generated best model
|
||||||
- [auto-ml-classification-bank-marketing-all-features.ipynb](classification-bank-marketing-all-features/auto-ml-classification-bank-marketing-all-features.ipynb)
|
- deploy the best model as a webservice on Azure Container Instance (ACI)
|
||||||
- Dataset: UCI's [bank marketing dataset](https://www.kaggle.com/janiobachmann/bank-marketing-dataset)
|
- get online predictions from the deployed model
|
||||||
- Simple example of using automated ML for classification to predict term deposit subscriptions for a bank
|
- **Forecast Demand of a Bike-Sharing Service**
|
||||||
- Uses azure compute for training
|
- Dataset: [Bike demand data](forecasting-bike-share/bike-no.csv)
|
||||||
|
- **[Jupyter Notebook](forecasting-bike-share/auto-ml-forecasting-bike-share.ipynb)**
|
||||||
- [auto-ml-forecasting-orange-juice-sales.ipynb](forecasting-orange-juice-sales/auto-ml-forecasting-orange-juice-sales.ipynb)
|
- run experiment remotely on AML Compute cluster
|
||||||
- Dataset: [Dominick's grocery sales of orange juice](forecasting-b/dominicks_OJ.csv)
|
- integrate holiday features
|
||||||
- Example of training an automated ML forecasting model on multiple time-series
|
- run rolling forecast for test set that is longer than the forecast horizon
|
||||||
|
- compute metrics on the predictions from the remote forecast
|
||||||
- [auto-ml-forecasting-bike-share.ipynb](forecasting-bike-share/auto-ml-forecasting-bike-share.ipynb)
|
- **The Forecast Function Interface**
|
||||||
- Dataset: forecasting for a bike-sharing
|
- Dataset: Generated for sample purposes
|
||||||
- Example of training an automated ML forecasting model on multiple time-series
|
- **[Jupyter Notebook](forecasting-forecast-function/auto-ml-forecasting-function.ipynb)**
|
||||||
|
- train a forecaster using a remote AML Compute cluster
|
||||||
- [auto-ml-forecasting-function.ipynb](forecasting-forecast-function/auto-ml-forecasting-function.ipynb)
|
- capabilities of forecast function (e.g. forecast farther into the horizon)
|
||||||
- Example of training an automated ML forecasting model on multiple time-series
|
- generate confidence intervals
|
||||||
|
- **Forecast Beverage Production**
|
||||||
- [auto-ml-forecasting-beer-remote.ipynb](forecasting-beer-remote/auto-ml-forecasting-beer-remote.ipynb)
|
- Dataset: [Monthly beer production data](forecasting-beer-remote/Beer_no_valid_split_train.csv)
|
||||||
- Example of training an automated ML forecasting model on multiple time-series
|
- **[Jupyter Notebook](forecasting-beer-remote/auto-ml-forecasting-beer-remote.ipynb)**
|
||||||
- Beer Production Forecasting
|
- train using a remote AML Compute cluster
|
||||||
|
- enable the DNN learning model
|
||||||
- [auto-ml-continuous-retraining.ipynb](continuous-retraining/auto-ml-continuous-retraining.ipynb)
|
- forecast on a remote compute cluster and compare different model performance
|
||||||
- Continuous retraining using Pipelines and Time-Series TabularDataset
|
- **Continuous Retraining with NOAA Weather Data**
|
||||||
|
- Dataset: [NOAA weather data from Azure Open Datasets](https://azure.microsoft.com/en-us/services/open-datasets/)
|
||||||
- [auto-ml-classification-text-dnn.ipynb](classification-text-dnn/auto-ml-classification-text-dnn.ipynb)
|
- **[Jupyter Notebook](continuous-retraining/auto-ml-continuous-retraining.ipynb)**
|
||||||
- Classification with text data using deep learning in AutoML
|
- continuously retrain a model using Pipelines and AutoML
|
||||||
- AutoML highlights here include using deep neural networks (DNNs) to create embedded features from text data.
|
- create a Pipeline to upload a time series dataset to an Azure blob
|
||||||
- Depending on the compute cluster the user provides, AutoML tried out Bidirectional Encoder Representations from Transformers (BERT) when a GPU compute is used.
|
- create a Pipeline to run an AutoML experiment and register the best resulting model in the Workspace
|
||||||
- Bidirectional Long-Short Term neural network (BiLSTM) when a CPU compute is used, thereby optimizing the choice of DNN for the uesr's setup.
|
- publish the training pipeline created and schedule it to run daily
|
||||||
|
|
||||||
<a name="documentation"></a>
|
<a name="documentation"></a>
|
||||||
See [Configure automated machine learning experiments](https://docs.microsoft.com/azure/machine-learning/service/how-to-configure-auto-train) to learn how more about the the settings and features available for automated machine learning experiments.
|
See [Configure automated machine learning experiments](https://docs.microsoft.com/azure/machine-learning/service/how-to-configure-auto-train) to learn how more about the the settings and features available for automated machine learning experiments.
|
||||||
@@ -179,7 +207,7 @@ The main code of the file must be indented so that it is under this condition.
|
|||||||
## automl_setup fails
|
## automl_setup fails
|
||||||
1. On Windows, make sure that you are running automl_setup from an Anconda Prompt window rather than a regular cmd window. You can launch the "Anaconda Prompt" window by hitting the Start button and typing "Anaconda Prompt". If you don't see the application "Anaconda Prompt", you might not have conda or mini conda installed. In that case, you can install it [here](https://conda.io/miniconda.html)
|
1. On Windows, make sure that you are running automl_setup from an Anconda Prompt window rather than a regular cmd window. You can launch the "Anaconda Prompt" window by hitting the Start button and typing "Anaconda Prompt". If you don't see the application "Anaconda Prompt", you might not have conda or mini conda installed. In that case, you can install it [here](https://conda.io/miniconda.html)
|
||||||
2. Check that you have conda 64-bit installed rather than 32-bit. You can check this with the command `conda info`. The `platform` should be `win-64` for Windows or `osx-64` for Mac.
|
2. Check that you have conda 64-bit installed rather than 32-bit. You can check this with the command `conda info`. The `platform` should be `win-64` for Windows or `osx-64` for Mac.
|
||||||
3. Check that you have conda 4.4.10 or later. You can check the version with the command `conda -V`. If you have a previous version installed, you can update it using the command: `conda update conda`.
|
3. Check that you have conda 4.7.8 or later. You can check the version with the command `conda -V`. If you have a previous version installed, you can update it using the command: `conda update conda`.
|
||||||
4. On Linux, if the error is `gcc: error trying to exec 'cc1plus': execvp: No such file or directory`, install build essentials using the command `sudo apt-get install build-essential`.
|
4. On Linux, if the error is `gcc: error trying to exec 'cc1plus': execvp: No such file or directory`, install build essentials using the command `sudo apt-get install build-essential`.
|
||||||
5. Pass a new name as the first parameter to automl_setup so that it creates a new conda environment. You can view existing conda environments using `conda env list` and remove them with `conda env remove -n <environmentname>`.
|
5. Pass a new name as the first parameter to automl_setup so that it creates a new conda environment. You can view existing conda environments using `conda env list` and remove them with `conda env remove -n <environmentname>`.
|
||||||
|
|
||||||
|
|||||||
@@ -2,30 +2,28 @@ name: azure_automl
|
|||||||
dependencies:
|
dependencies:
|
||||||
# The python interpreter version.
|
# The python interpreter version.
|
||||||
# Currently Azure ML only supports 3.5.2 and later.
|
# Currently Azure ML only supports 3.5.2 and later.
|
||||||
- pip<=19.3.1
|
- pip==21.1.2
|
||||||
- python>=3.5.2,<3.6.8
|
- python>=3.5.2,<3.8
|
||||||
- nb_conda
|
- boto3==1.15.18
|
||||||
- matplotlib==2.1.0
|
- matplotlib==2.1.0
|
||||||
- numpy~=1.16.0
|
- numpy==1.18.5
|
||||||
- cython
|
- cython
|
||||||
- urllib3<1.24
|
- urllib3<1.24
|
||||||
- scipy==1.4.1
|
- scipy>=1.4.1,<=1.5.2
|
||||||
- scikit-learn>=0.19.0,<=0.20.3
|
- scikit-learn==0.22.1
|
||||||
- pandas>=0.22.0,<=0.23.4
|
- pandas==0.25.1
|
||||||
- py-xgboost<=0.90
|
- py-xgboost<=0.90
|
||||||
- conda-forge::fbprophet==0.5
|
- conda-forge::fbprophet==0.5
|
||||||
- holidays==0.9.11
|
- holidays==0.9.11
|
||||||
- pytorch::pytorch=1.4.0
|
- pytorch::pytorch=1.4.0
|
||||||
- cudatoolkit=10.1.243
|
- cudatoolkit=10.1.243
|
||||||
|
- tornado==6.1.0
|
||||||
|
|
||||||
- pip:
|
- pip:
|
||||||
# Required packages for AzureML execution, history, and data preparation.
|
# Required packages for AzureML execution, history, and data preparation.
|
||||||
- azureml-defaults
|
- azureml-widgets~=1.37.0
|
||||||
- azureml-train-automl
|
|
||||||
- azureml-train
|
|
||||||
- azureml-widgets
|
|
||||||
- azureml-pipeline
|
|
||||||
- pytorch-transformers==1.0.0
|
- pytorch-transformers==1.0.0
|
||||||
- spacy==2.1.8
|
- spacy==2.1.8
|
||||||
- https://aka.ms/automl-resources/packages/en_core_web_sm-2.1.0.tar.gz
|
- https://aka.ms/automl-resources/packages/en_core_web_sm-2.1.0.tar.gz
|
||||||
|
- -r https://automlsdkdataresources.blob.core.windows.net/validated-requirements/1.37.0/validated_win32_requirements.txt [--no-deps]
|
||||||
|
- arch==4.14
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
name: azure_automl
|
||||||
|
dependencies:
|
||||||
|
# The python interpreter version.
|
||||||
|
# Currently Azure ML only supports 3.5.2 and later.
|
||||||
|
- pip==21.1.2
|
||||||
|
- python>=3.5.2,<3.8
|
||||||
|
- nb_conda
|
||||||
|
- boto3==1.15.18
|
||||||
|
- matplotlib==2.1.0
|
||||||
|
- numpy==1.18.5
|
||||||
|
- cython
|
||||||
|
- urllib3<1.24
|
||||||
|
- scipy>=1.4.1,<=1.5.2
|
||||||
|
- scikit-learn==0.22.1
|
||||||
|
- pandas==0.25.1
|
||||||
|
- py-xgboost<=0.90
|
||||||
|
- conda-forge::fbprophet==0.5
|
||||||
|
- holidays==0.9.11
|
||||||
|
- pytorch::pytorch=1.4.0
|
||||||
|
- cudatoolkit=10.1.243
|
||||||
|
- tornado==6.1.0
|
||||||
|
|
||||||
|
- pip:
|
||||||
|
# Required packages for AzureML execution, history, and data preparation.
|
||||||
|
- azureml-widgets~=1.37.0
|
||||||
|
- pytorch-transformers==1.0.0
|
||||||
|
- spacy==2.1.8
|
||||||
|
- https://aka.ms/automl-resources/packages/en_core_web_sm-2.1.0.tar.gz
|
||||||
|
- -r https://automlsdkdataresources.blob.core.windows.net/validated-requirements/1.37.0/validated_linux_requirements.txt [--no-deps]
|
||||||
|
- arch==4.14
|
||||||
@@ -2,30 +2,30 @@ name: azure_automl
|
|||||||
dependencies:
|
dependencies:
|
||||||
# The python interpreter version.
|
# The python interpreter version.
|
||||||
# Currently Azure ML only supports 3.5.2 and later.
|
# Currently Azure ML only supports 3.5.2 and later.
|
||||||
- pip<=19.3.1
|
- pip==21.1.2
|
||||||
- nomkl
|
- nomkl
|
||||||
- python>=3.5.2,<3.6.8
|
- python>=3.5.2,<3.8
|
||||||
- nb_conda
|
- nb_conda
|
||||||
|
- boto3==1.15.18
|
||||||
- matplotlib==2.1.0
|
- matplotlib==2.1.0
|
||||||
- numpy~=1.16.0
|
- numpy==1.18.5
|
||||||
- cython
|
- cython
|
||||||
- urllib3<1.24
|
- urllib3<1.24
|
||||||
- scipy==1.4.1
|
- scipy>=1.4.1,<=1.5.2
|
||||||
- scikit-learn>=0.19.0,<=0.20.3
|
- scikit-learn==0.22.1
|
||||||
- pandas>=0.22.0,<=0.23.4
|
- pandas==0.25.1
|
||||||
- py-xgboost<=0.90
|
- py-xgboost<=0.90
|
||||||
- conda-forge::fbprophet==0.5
|
- conda-forge::fbprophet==0.5
|
||||||
- holidays==0.9.11
|
- holidays==0.9.11
|
||||||
- pytorch::pytorch=1.4.0
|
- pytorch::pytorch=1.4.0
|
||||||
- cudatoolkit=9.0
|
- cudatoolkit=9.0
|
||||||
|
- tornado==6.1.0
|
||||||
|
|
||||||
- pip:
|
- pip:
|
||||||
# Required packages for AzureML execution, history, and data preparation.
|
# Required packages for AzureML execution, history, and data preparation.
|
||||||
- azureml-defaults
|
- azureml-widgets~=1.37.0
|
||||||
- azureml-train-automl
|
|
||||||
- azureml-train
|
|
||||||
- azureml-widgets
|
|
||||||
- azureml-pipeline
|
|
||||||
- pytorch-transformers==1.0.0
|
- pytorch-transformers==1.0.0
|
||||||
- spacy==2.1.8
|
- spacy==2.1.8
|
||||||
- https://aka.ms/automl-resources/packages/en_core_web_sm-2.1.0.tar.gz
|
- https://aka.ms/automl-resources/packages/en_core_web_sm-2.1.0.tar.gz
|
||||||
|
- -r https://automlsdkdataresources.blob.core.windows.net/validated-requirements/1.37.0/validated_darwin_requirements.txt [--no-deps]
|
||||||
|
- arch==4.14
|
||||||
|
|||||||
@@ -6,11 +6,22 @@ set PIP_NO_WARN_SCRIPT_LOCATION=0
|
|||||||
|
|
||||||
IF "%conda_env_name%"=="" SET conda_env_name="azure_automl"
|
IF "%conda_env_name%"=="" SET conda_env_name="azure_automl"
|
||||||
IF "%automl_env_file%"=="" SET automl_env_file="automl_env.yml"
|
IF "%automl_env_file%"=="" SET automl_env_file="automl_env.yml"
|
||||||
|
SET check_conda_version_script="check_conda_version.py"
|
||||||
|
|
||||||
IF NOT EXIST %automl_env_file% GOTO YmlMissing
|
IF NOT EXIST %automl_env_file% GOTO YmlMissing
|
||||||
|
|
||||||
IF "%CONDA_EXE%"=="" GOTO CondaMissing
|
IF "%CONDA_EXE%"=="" GOTO CondaMissing
|
||||||
|
|
||||||
|
IF NOT EXIST %check_conda_version_script% GOTO VersionCheckMissing
|
||||||
|
|
||||||
|
python "%check_conda_version_script%"
|
||||||
|
IF errorlevel 1 GOTO ErrorExit:
|
||||||
|
|
||||||
|
SET replace_version_script="replace_latest_version.ps1"
|
||||||
|
IF EXIST %replace_version_script% (
|
||||||
|
powershell -file %replace_version_script% %automl_env_file%
|
||||||
|
)
|
||||||
|
|
||||||
call conda activate %conda_env_name% 2>nul:
|
call conda activate %conda_env_name% 2>nul:
|
||||||
|
|
||||||
if not errorlevel 1 (
|
if not errorlevel 1 (
|
||||||
@@ -54,6 +65,10 @@ echo If you are running an older version of Miniconda or Anaconda,
|
|||||||
echo you can upgrade using the command: conda update conda
|
echo you can upgrade using the command: conda update conda
|
||||||
goto End
|
goto End
|
||||||
|
|
||||||
|
:VersionCheckMissing
|
||||||
|
echo File %check_conda_version_script% not found.
|
||||||
|
goto End
|
||||||
|
|
||||||
:YmlMissing
|
:YmlMissing
|
||||||
echo File %automl_env_file% not found.
|
echo File %automl_env_file% not found.
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ CONDA_ENV_NAME=$1
|
|||||||
AUTOML_ENV_FILE=$2
|
AUTOML_ENV_FILE=$2
|
||||||
OPTIONS=$3
|
OPTIONS=$3
|
||||||
PIP_NO_WARN_SCRIPT_LOCATION=0
|
PIP_NO_WARN_SCRIPT_LOCATION=0
|
||||||
|
CHECK_CONDA_VERSION_SCRIPT="check_conda_version.py"
|
||||||
|
|
||||||
if [ "$CONDA_ENV_NAME" == "" ]
|
if [ "$CONDA_ENV_NAME" == "" ]
|
||||||
then
|
then
|
||||||
@@ -12,7 +13,7 @@ fi
|
|||||||
|
|
||||||
if [ "$AUTOML_ENV_FILE" == "" ]
|
if [ "$AUTOML_ENV_FILE" == "" ]
|
||||||
then
|
then
|
||||||
AUTOML_ENV_FILE="automl_env.yml"
|
AUTOML_ENV_FILE="automl_env_linux.yml"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if [ ! -f $AUTOML_ENV_FILE ]; then
|
if [ ! -f $AUTOML_ENV_FILE ]; then
|
||||||
@@ -20,6 +21,18 @@ if [ ! -f $AUTOML_ENV_FILE ]; then
|
|||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
if [ ! -f $CHECK_CONDA_VERSION_SCRIPT ]; then
|
||||||
|
echo "File $CHECK_CONDA_VERSION_SCRIPT not found"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
python "$CHECK_CONDA_VERSION_SCRIPT"
|
||||||
|
if [ $? -ne 0 ]; then
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
sed -i 's/AZUREML-SDK-VERSION/latest/' $AUTOML_ENV_FILE
|
||||||
|
|
||||||
if source activate $CONDA_ENV_NAME 2> /dev/null
|
if source activate $CONDA_ENV_NAME 2> /dev/null
|
||||||
then
|
then
|
||||||
echo "Upgrading existing conda environment" $CONDA_ENV_NAME
|
echo "Upgrading existing conda environment" $CONDA_ENV_NAME
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ CONDA_ENV_NAME=$1
|
|||||||
AUTOML_ENV_FILE=$2
|
AUTOML_ENV_FILE=$2
|
||||||
OPTIONS=$3
|
OPTIONS=$3
|
||||||
PIP_NO_WARN_SCRIPT_LOCATION=0
|
PIP_NO_WARN_SCRIPT_LOCATION=0
|
||||||
|
CHECK_CONDA_VERSION_SCRIPT="check_conda_version.py"
|
||||||
|
|
||||||
if [ "$CONDA_ENV_NAME" == "" ]
|
if [ "$CONDA_ENV_NAME" == "" ]
|
||||||
then
|
then
|
||||||
@@ -20,6 +21,19 @@ if [ ! -f $AUTOML_ENV_FILE ]; then
|
|||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
if [ ! -f $CHECK_CONDA_VERSION_SCRIPT ]; then
|
||||||
|
echo "File $CHECK_CONDA_VERSION_SCRIPT not found"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
python "$CHECK_CONDA_VERSION_SCRIPT"
|
||||||
|
if [ $? -ne 0 ]; then
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
sed -i '' 's/AZUREML-SDK-VERSION/latest/' $AUTOML_ENV_FILE
|
||||||
|
brew install libomp
|
||||||
|
|
||||||
if source activate $CONDA_ENV_NAME 2> /dev/null
|
if source activate $CONDA_ENV_NAME 2> /dev/null
|
||||||
then
|
then
|
||||||
echo "Upgrading existing conda environment" $CONDA_ENV_NAME
|
echo "Upgrading existing conda environment" $CONDA_ENV_NAME
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
from distutils.version import LooseVersion
|
||||||
|
import platform
|
||||||
|
|
||||||
|
try:
|
||||||
|
import conda
|
||||||
|
except Exception:
|
||||||
|
print('Failed to import conda.')
|
||||||
|
print('This setup is usually run from the base conda environment.')
|
||||||
|
print('You can activate the base environment using the command "conda activate base"')
|
||||||
|
exit(1)
|
||||||
|
|
||||||
|
architecture = platform.architecture()[0]
|
||||||
|
|
||||||
|
if architecture != "64bit":
|
||||||
|
print('This setup requires 64bit Anaconda or Miniconda. Found: ' + architecture)
|
||||||
|
exit(1)
|
||||||
|
|
||||||
|
minimumVersion = "4.7.8"
|
||||||
|
|
||||||
|
versionInvalid = (LooseVersion(conda.__version__) < LooseVersion(minimumVersion))
|
||||||
|
|
||||||
|
if versionInvalid:
|
||||||
|
print('Setup requires conda version ' + minimumVersion + ' or higher.')
|
||||||
|
print('You can use the command "conda update conda" to upgrade conda.')
|
||||||
|
|
||||||
|
exit(versionInvalid)
|
||||||
@@ -77,6 +77,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
|
"import json\n",
|
||||||
"import logging\n",
|
"import logging\n",
|
||||||
"\n",
|
"\n",
|
||||||
"from matplotlib import pyplot as plt\n",
|
"from matplotlib import pyplot as plt\n",
|
||||||
@@ -86,10 +87,9 @@
|
|||||||
"import azureml.core\n",
|
"import azureml.core\n",
|
||||||
"from azureml.core.experiment import Experiment\n",
|
"from azureml.core.experiment import Experiment\n",
|
||||||
"from azureml.core.workspace import Workspace\n",
|
"from azureml.core.workspace import Workspace\n",
|
||||||
"from azureml.automl.core.featurization import FeaturizationConfig\n",
|
|
||||||
"from azureml.core.dataset import Dataset\n",
|
"from azureml.core.dataset import Dataset\n",
|
||||||
"from azureml.train.automl import AutoMLConfig\n",
|
"from azureml.train.automl import AutoMLConfig\n",
|
||||||
"from azureml.interpret._internal.explanation_client import ExplanationClient"
|
"from azureml.interpret import ExplanationClient"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -105,7 +105,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"print(\"This notebook was created using version 1.12.0 of the Azure ML SDK\")\n",
|
"print(\"This notebook was created using version 1.37.0 of the Azure ML SDK\")\n",
|
||||||
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -165,9 +165,12 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"## Create or Attach existing AmlCompute\n",
|
"## Create or Attach existing AmlCompute\n",
|
||||||
"You will need to create a compute target for your AutoML run. In this tutorial, you create AmlCompute as your training compute resource.\n",
|
"You will need to create a compute target for your AutoML run. In this tutorial, you create AmlCompute as your training compute resource.\n",
|
||||||
|
"\n",
|
||||||
|
"> 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.\n",
|
||||||
|
"\n",
|
||||||
"#### Creation of AmlCompute takes approximately 5 minutes. \n",
|
"#### Creation of AmlCompute takes approximately 5 minutes. \n",
|
||||||
"If the AmlCompute with that name is already in your workspace this code will skip the creation process.\n",
|
"If the AmlCompute with that name is already in your workspace this code will skip the creation process.\n",
|
||||||
"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."
|
"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](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -187,7 +190,7 @@
|
|||||||
" compute_target = ComputeTarget(workspace=ws, name=cpu_cluster_name)\n",
|
" compute_target = ComputeTarget(workspace=ws, name=cpu_cluster_name)\n",
|
||||||
" print('Found existing cluster, use it.')\n",
|
" print('Found existing cluster, use it.')\n",
|
||||||
"except ComputeTargetException:\n",
|
"except ComputeTargetException:\n",
|
||||||
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_D2_V2',\n",
|
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_DS12_V2',\n",
|
||||||
" max_nodes=6)\n",
|
" max_nodes=6)\n",
|
||||||
" compute_target = ComputeTarget.create(ws, cpu_cluster_name, compute_config)\n",
|
" compute_target = ComputeTarget.create(ws, cpu_cluster_name, compute_config)\n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -374,15 +377,6 @@
|
|||||||
"remote_run = experiment.submit(automl_config, show_output = False)"
|
"remote_run = experiment.submit(automl_config, show_output = False)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"remote_run"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
@@ -417,7 +411,8 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"best_run_customized, fitted_model_customized = remote_run.get_output()"
|
"# Retrieve the best Run object\n",
|
||||||
|
"best_run = remote_run.get_best_child()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -426,7 +421,7 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"## Transparency\n",
|
"## Transparency\n",
|
||||||
"\n",
|
"\n",
|
||||||
"View updated featurization summary"
|
"View featurization summary for the best model - to study how different features were transformed. This is stored as a JSON file in the outputs directory for the run."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -435,36 +430,14 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"custom_featurizer = fitted_model_customized.named_steps['datatransformer']\n",
|
"# Download the featuurization summary JSON file locally\n",
|
||||||
"df = custom_featurizer.get_featurization_summary()\n",
|
"best_run.download_file(\"outputs/featurization_summary.json\", \"featurization_summary.json\")\n",
|
||||||
"pd.DataFrame(data=df)"
|
"\n",
|
||||||
]
|
"# Render the JSON as a pandas DataFrame\n",
|
||||||
},
|
"with open(\"featurization_summary.json\", \"r\") as f:\n",
|
||||||
{
|
" records = json.load(f)\n",
|
||||||
"cell_type": "markdown",
|
"\n",
|
||||||
"metadata": {},
|
"pd.DataFrame.from_records(records)"
|
||||||
"source": [
|
|
||||||
"Set `is_user_friendly=False` to get a more detailed summary for the transforms being applied."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"df = custom_featurizer.get_featurization_summary(is_user_friendly=False)\n",
|
|
||||||
"pd.DataFrame(data=df)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"df = custom_featurizer.get_stats_feature_type_summary()\n",
|
|
||||||
"pd.DataFrame(data=df)"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -500,14 +473,13 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"# Wait for the best model explanation run to complete\n",
|
"# Wait for the best model explanation run to complete\n",
|
||||||
"from azureml.core.run import Run\n",
|
"from azureml.core.run import Run\n",
|
||||||
"model_explainability_run_id = remote_run.get_properties().get('ModelExplainRunId')\n",
|
"model_explainability_run_id = remote_run.id + \"_\" + \"ModelExplain\"\n",
|
||||||
"print(model_explainability_run_id)\n",
|
"print(model_explainability_run_id)\n",
|
||||||
"if model_explainability_run_id is not None:\n",
|
"model_explainability_run = Run(experiment=experiment, run_id=model_explainability_run_id)\n",
|
||||||
" model_explainability_run = Run(experiment=experiment, run_id=model_explainability_run_id)\n",
|
"model_explainability_run.wait_for_completion()\n",
|
||||||
" model_explainability_run.wait_for_completion()\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
"# Get the best run object\n",
|
"# Get the best run object\n",
|
||||||
"best_run, fitted_model = remote_run.get_output()"
|
"best_run = remote_run.get_best_child()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -606,27 +578,21 @@
|
|||||||
"from azureml.automl.core.onnx_convert import OnnxConvertConstants\n",
|
"from azureml.automl.core.onnx_convert import OnnxConvertConstants\n",
|
||||||
"from azureml.train.automl import constants\n",
|
"from azureml.train.automl import constants\n",
|
||||||
"\n",
|
"\n",
|
||||||
"if sys.version_info < OnnxConvertConstants.OnnxIncompatiblePythonVersion:\n",
|
|
||||||
" python_version_compatible = True\n",
|
|
||||||
"else:\n",
|
|
||||||
" python_version_compatible = False\n",
|
|
||||||
"\n",
|
|
||||||
"import onnxruntime\n",
|
|
||||||
"from azureml.automl.runtime.onnx_convert import OnnxInferenceHelper\n",
|
"from azureml.automl.runtime.onnx_convert import OnnxInferenceHelper\n",
|
||||||
"\n",
|
"\n",
|
||||||
"def get_onnx_res(run):\n",
|
"def get_onnx_res(run):\n",
|
||||||
" res_path = 'onnx_resource.json'\n",
|
" res_path = 'onnx_resource.json'\n",
|
||||||
" run.download_file(name=constants.MODEL_RESOURCE_PATH_ONNX, output_file_path=res_path)\n",
|
" run.download_file(name=constants.MODEL_RESOURCE_PATH_ONNX, output_file_path=res_path)\n",
|
||||||
" with open(res_path) as f:\n",
|
" with open(res_path) as f:\n",
|
||||||
" onnx_res = json.load(f)\n",
|
" result = json.load(f)\n",
|
||||||
" return onnx_res\n",
|
" return result\n",
|
||||||
"\n",
|
"\n",
|
||||||
"if python_version_compatible:\n",
|
"if sys.version_info < OnnxConvertConstants.OnnxIncompatiblePythonVersion:\n",
|
||||||
" test_df = test_dataset.to_pandas_dataframe()\n",
|
" test_df = test_dataset.to_pandas_dataframe()\n",
|
||||||
" mdl_bytes = onnx_mdl.SerializeToString()\n",
|
" mdl_bytes = onnx_mdl.SerializeToString()\n",
|
||||||
" onnx_res = get_onnx_res(best_run)\n",
|
" onnx_result = get_onnx_res(best_run)\n",
|
||||||
"\n",
|
"\n",
|
||||||
" onnxrt_helper = OnnxInferenceHelper(mdl_bytes, onnx_res)\n",
|
" onnxrt_helper = OnnxInferenceHelper(mdl_bytes, onnx_result)\n",
|
||||||
" pred_onnx, pred_prob_onnx = onnxrt_helper.predict(test_df)\n",
|
" pred_onnx, pred_prob_onnx = onnxrt_helper.predict(test_df)\n",
|
||||||
"\n",
|
"\n",
|
||||||
" print(pred_onnx)\n",
|
" print(pred_onnx)\n",
|
||||||
@@ -643,7 +609,16 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"### Retrieve the Best Model\n",
|
"### Retrieve the Best Model\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Below we select the best pipeline from our iterations. The `get_output` method returns the best run and the fitted model. Overloads on `get_output` allow you to retrieve the best run and fitted model for *any* logged metric or for a particular *iteration*."
|
"Below we select the best pipeline from our iterations. The `get_best_child` method returns the Run object for the best model based on the default primary metric. There are additional flags that can be passed to the method if we want to retrieve the best Run based on any of the other supported metrics, or if we are just interested in the best run among the ONNX compatible runs. As always, you can execute `remote_run.get_best_child??` in a new cell to view the source or docs for the function."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"remote_run.get_best_child??"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -663,7 +638,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"best_run, fitted_model = remote_run.get_output()"
|
"best_run = remote_run.get_best_child()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -715,14 +690,12 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"from azureml.core.model import InferenceConfig\n",
|
"from azureml.core.model import InferenceConfig\n",
|
||||||
"from azureml.core.webservice import AciWebservice\n",
|
"from azureml.core.webservice import AciWebservice\n",
|
||||||
"from azureml.core.webservice import Webservice\n",
|
|
||||||
"from azureml.core.model import Model\n",
|
"from azureml.core.model import Model\n",
|
||||||
"from azureml.core.environment import Environment\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
"inference_config = InferenceConfig(entry_script=script_file_name)\n",
|
"inference_config = InferenceConfig(environment = best_run.get_environment(), entry_script=script_file_name)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"aciconfig = AciWebservice.deploy_configuration(cpu_cores = 1, \n",
|
"aciconfig = AciWebservice.deploy_configuration(cpu_cores = 2, \n",
|
||||||
" memory_gb = 1, \n",
|
" memory_gb = 2, \n",
|
||||||
" tags = {'area': \"bmData\", 'type': \"automl_classification\"}, \n",
|
" tags = {'area': \"bmData\", 'type': \"automl_classification\"}, \n",
|
||||||
" description = 'sample service for Automl Classification')\n",
|
" description = 'sample service for Automl Classification')\n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -799,7 +772,6 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"import json\n",
|
|
||||||
"import requests\n",
|
"import requests\n",
|
||||||
"\n",
|
"\n",
|
||||||
"X_test_json = X_test.to_json(orient='records')\n",
|
"X_test_json = X_test.to_json(orient='records')\n",
|
||||||
@@ -839,7 +811,6 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"%matplotlib notebook\n",
|
"%matplotlib notebook\n",
|
||||||
"from sklearn.metrics import confusion_matrix\n",
|
"from sklearn.metrics import confusion_matrix\n",
|
||||||
"import numpy as np\n",
|
|
||||||
"import itertools\n",
|
"import itertools\n",
|
||||||
"\n",
|
"\n",
|
||||||
"cf =confusion_matrix(actual,y_pred)\n",
|
"cf =confusion_matrix(actual,y_pred)\n",
|
||||||
@@ -900,7 +871,7 @@
|
|||||||
"metadata": {
|
"metadata": {
|
||||||
"authors": [
|
"authors": [
|
||||||
{
|
{
|
||||||
"name": "anumamah"
|
"name": "ratanase"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"category": "tutorial",
|
"category": "tutorial",
|
||||||
|
|||||||
@@ -93,7 +93,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"print(\"This notebook was created using version 1.12.0 of the Azure ML SDK\")\n",
|
"print(\"This notebook was created using version 1.37.0 of the Azure ML SDK\")\n",
|
||||||
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -127,6 +127,9 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"## Create or Attach existing AmlCompute\n",
|
"## Create or Attach existing AmlCompute\n",
|
||||||
"A compute target is required to execute the Automated ML run. In this tutorial, you create AmlCompute as your training compute resource.\n",
|
"A compute target is required to execute the Automated ML run. In this tutorial, you create AmlCompute as your training compute resource.\n",
|
||||||
|
"\n",
|
||||||
|
"> 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.\n",
|
||||||
|
"\n",
|
||||||
"#### Creation of AmlCompute takes approximately 5 minutes. \n",
|
"#### Creation of AmlCompute takes approximately 5 minutes. \n",
|
||||||
"If the AmlCompute with that name is already in your workspace this code will skip the creation process.\n",
|
"If the AmlCompute with that name is already in your workspace this code will skip the creation process.\n",
|
||||||
"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](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
"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](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
||||||
@@ -212,7 +215,7 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"automl_settings = {\n",
|
"automl_settings = {\n",
|
||||||
" \"n_cross_validations\": 3,\n",
|
" \"n_cross_validations\": 3,\n",
|
||||||
" \"primary_metric\": 'average_precision_score_weighted',\n",
|
" \"primary_metric\": 'AUC_weighted',\n",
|
||||||
" \"enable_early_stopping\": True,\n",
|
" \"enable_early_stopping\": True,\n",
|
||||||
" \"max_concurrent_iterations\": 2, # This is a limit for testing purpose, please increase it as per cluster size\n",
|
" \"max_concurrent_iterations\": 2, # This is a limit for testing purpose, please increase it as per cluster size\n",
|
||||||
" \"experiment_timeout_hours\": 0.25, # This is a time limit for testing purposes, remove it for real use cases, this will drastically limit ablity to find the best model possible\n",
|
" \"experiment_timeout_hours\": 0.25, # This is a time limit for testing purposes, remove it for real use cases, this will drastically limit ablity to find the best model possible\n",
|
||||||
@@ -255,15 +258,6 @@
|
|||||||
"#remote_run = AutoMLRun(experiment = experiment, run_id = '<replace with your run id>')"
|
"#remote_run = AutoMLRun(experiment = experiment, run_id = '<replace with your run id>')"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"remote_run"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
@@ -424,22 +418,33 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"This Credit Card fraud Detection dataset is made available under the Open Database License: http://opendatacommons.org/licenses/odbl/1.0/. Any rights in individual contents of the database are licensed under the Database Contents License: http://opendatacommons.org/licenses/dbcl/1.0/ and is available at: https://www.kaggle.com/mlg-ulb/creditcardfraud\n",
|
"This Credit Card fraud Detection dataset is made available under the Open Database License: http://opendatacommons.org/licenses/odbl/1.0/. Any rights in individual contents of the database are licensed under the Database Contents License: http://opendatacommons.org/licenses/dbcl/1.0/ and is available at: https://www.kaggle.com/mlg-ulb/creditcardfraud\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"The dataset has been collected and analysed during a research collaboration of Worldline and the Machine Learning Group (http://mlg.ulb.ac.be) of ULB (Universit\u00c3\u00a9 Libre de Bruxelles) on big data mining and fraud detection.\n",
|
||||||
|
"More details on current and past projects on related topics are available on https://www.researchgate.net/project/Fraud-detection-5 and the page of the DefeatFraud project\n",
|
||||||
"\n",
|
"\n",
|
||||||
"The dataset has been collected and analysed during a research collaboration of Worldline and the Machine Learning Group (http://mlg.ulb.ac.be) of ULB (Universit\u00c3\u0192\u00c2\u00a9 Libre de Bruxelles) on big data mining and fraud detection. More details on current and past projects on related topics are available on https://www.researchgate.net/project/Fraud-detection-5 and the page of the DefeatFraud project\n",
|
"Please cite the following works:\n",
|
||||||
"Please cite the following works: \n",
|
"\n",
|
||||||
"\u00c3\u00a2\u00e2\u201a\u00ac\u00c2\u00a2\tAndrea Dal Pozzolo, Olivier Caelen, Reid A. Johnson and Gianluca Bontempi. Calibrating Probability with Undersampling for Unbalanced Classification. In Symposium on Computational Intelligence and Data Mining (CIDM), IEEE, 2015\n",
|
"Andrea Dal Pozzolo, Olivier Caelen, Reid A. Johnson and Gianluca Bontempi. Calibrating Probability with Undersampling for Unbalanced Classification. In Symposium on Computational Intelligence and Data Mining (CIDM), IEEE, 2015\n",
|
||||||
"\u00c3\u00a2\u00e2\u201a\u00ac\u00c2\u00a2\tDal Pozzolo, Andrea; Caelen, Olivier; Le Borgne, Yann-Ael; Waterschoot, Serge; Bontempi, Gianluca. Learned lessons in credit card fraud detection from a practitioner perspective, Expert systems with applications,41,10,4915-4928,2014, Pergamon\n",
|
"\n",
|
||||||
"\u00c3\u00a2\u00e2\u201a\u00ac\u00c2\u00a2\tDal Pozzolo, Andrea; Boracchi, Giacomo; Caelen, Olivier; Alippi, Cesare; Bontempi, Gianluca. Credit card fraud detection: a realistic modeling and a novel learning strategy, IEEE transactions on neural networks and learning systems,29,8,3784-3797,2018,IEEE\n",
|
"Dal Pozzolo, Andrea; Caelen, Olivier; Le Borgne, Yann-Ael; Waterschoot, Serge; Bontempi, Gianluca. Learned lessons in credit card fraud detection from a practitioner perspective, Expert systems with applications,41,10,4915-4928,2014, Pergamon\n",
|
||||||
"o\tDal Pozzolo, Andrea Adaptive Machine learning for credit card fraud detection ULB MLG PhD thesis (supervised by G. Bontempi)\n",
|
"\n",
|
||||||
"\u00c3\u00a2\u00e2\u201a\u00ac\u00c2\u00a2\tCarcillo, Fabrizio; Dal Pozzolo, Andrea; Le Borgne, Yann-A\u00c3\u0192\u00c2\u00abl; Caelen, Olivier; Mazzer, Yannis; Bontempi, Gianluca. Scarff: a scalable framework for streaming credit card fraud detection with Spark, Information fusion,41, 182-194,2018,Elsevier\n",
|
"Dal Pozzolo, Andrea; Boracchi, Giacomo; Caelen, Olivier; Alippi, Cesare; Bontempi, Gianluca. Credit card fraud detection: a realistic modeling and a novel learning strategy, IEEE transactions on neural networks and learning systems,29,8,3784-3797,2018,IEEE\n",
|
||||||
"\u00c3\u00a2\u00e2\u201a\u00ac\u00c2\u00a2\tCarcillo, Fabrizio; Le Borgne, Yann-A\u00c3\u0192\u00c2\u00abl; Caelen, Olivier; Bontempi, Gianluca. Streaming active learning strategies for real-life credit card fraud detection: assessment and visualization, International Journal of Data Science and Analytics, 5,4,285-300,2018,Springer International Publishing"
|
"\n",
|
||||||
|
"Dal Pozzolo, Andrea Adaptive Machine learning for credit card fraud detection ULB MLG PhD thesis (supervised by G. Bontempi)\n",
|
||||||
|
"\n",
|
||||||
|
"Carcillo, Fabrizio; Dal Pozzolo, Andrea; Le Borgne, Yann-A\u00c3\u00abl; Caelen, Olivier; Mazzer, Yannis; Bontempi, Gianluca. Scarff: a scalable framework for streaming credit card fraud detection with Spark, Information fusion,41, 182-194,2018,Elsevier\n",
|
||||||
|
"\n",
|
||||||
|
"Carcillo, Fabrizio; Le Borgne, Yann-A\u00c3\u00abl; Caelen, Olivier; Bontempi, Gianluca. Streaming active learning strategies for real-life credit card fraud detection: assessment and visualization, International Journal of Data Science and Analytics, 5,4,285-300,2018,Springer International Publishing\n",
|
||||||
|
"\n",
|
||||||
|
"Bertrand Lebichot, Yann-A\u00c3\u00abl Le Borgne, Liyun He, Frederic Obl\u00c3\u00a9, Gianluca Bontempi Deep-Learning Domain Adaptation Techniques for Credit Cards Fraud Detection, INNSBDDL 2019: Recent Advances in Big Data and Deep Learning, pp 78-88, 2019\n",
|
||||||
|
"\n",
|
||||||
|
"Fabrizio Carcillo, Yann-A\u00c3\u00abl Le Borgne, Olivier Caelen, Frederic Obl\u00c3\u00a9, Gianluca Bontempi Combining Unsupervised and Supervised Learning in Credit Card Fraud Detection Information Sciences, 2019"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"authors": [
|
"authors": [
|
||||||
{
|
{
|
||||||
"name": "tzvikei"
|
"name": "ratanase"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"category": "tutorial",
|
"category": "tutorial",
|
||||||
|
|||||||
@@ -42,9 +42,8 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
|
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"An Enterprise workspace is required for this notebook. To learn more about creating an Enterprise workspace or upgrading to an Enterprise workspace from the Azure portal, please visit our [Workspace page](https://docs.microsoft.com/azure/machine-learning/service/concept-workspace#upgrade).\n",
|
|
||||||
"\n",
|
|
||||||
"Notebook synopsis:\n",
|
"Notebook synopsis:\n",
|
||||||
|
"\n",
|
||||||
"1. Creating an Experiment in an existing Workspace\n",
|
"1. Creating an Experiment in an existing Workspace\n",
|
||||||
"2. Configuration and remote run of AutoML for a text dataset (20 Newsgroups dataset from scikit-learn) for classification\n",
|
"2. Configuration and remote run of AutoML for a text dataset (20 Newsgroups dataset from scikit-learn) for classification\n",
|
||||||
"3. Registering the best model for future use\n",
|
"3. Registering the best model for future use\n",
|
||||||
@@ -64,6 +63,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
|
"import json\n",
|
||||||
"import logging\n",
|
"import logging\n",
|
||||||
"import os\n",
|
"import os\n",
|
||||||
"import shutil\n",
|
"import shutil\n",
|
||||||
@@ -97,7 +97,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"print(\"This notebook was created using version 1.12.0 of the Azure ML SDK\")\n",
|
"print(\"This notebook was created using version 1.37.0 of the Azure ML SDK\")\n",
|
||||||
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -139,6 +139,8 @@
|
|||||||
"## Set up a compute cluster\n",
|
"## Set up a compute cluster\n",
|
||||||
"This section uses a user-provided compute cluster (named \"dnntext-cluster\" in this example). If a cluster with this name does not exist in the user's workspace, the below code will create a new cluster. You can choose the parameters of the cluster as mentioned in the comments.\n",
|
"This section uses a user-provided compute cluster (named \"dnntext-cluster\" in this example). If a cluster with this name does not exist in the user's workspace, the below code will create a new cluster. You can choose the parameters of the cluster as mentioned in the comments.\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"> 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.\n",
|
||||||
|
"\n",
|
||||||
"Whether you provide/select a CPU or GPU cluster, AutoML will choose the appropriate DNN for that setup - BiLSTM or BERT text featurizer will be included in the candidate featurizers on CPU and GPU respectively. If your goal is to obtain the most accurate model, we recommend you use GPU clusters since BERT featurizers usually outperform BiLSTM featurizers."
|
"Whether you provide/select a CPU or GPU cluster, AutoML will choose the appropriate DNN for that setup - BiLSTM or BERT text featurizer will be included in the candidate featurizers on CPU and GPU respectively. If your goal is to obtain the most accurate model, we recommend you use GPU clusters since BERT featurizers usually outperform BiLSTM featurizers."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -151,6 +153,8 @@
|
|||||||
"from azureml.core.compute import ComputeTarget, AmlCompute\n",
|
"from azureml.core.compute import ComputeTarget, AmlCompute\n",
|
||||||
"from azureml.core.compute_target import ComputeTargetException\n",
|
"from azureml.core.compute_target import ComputeTargetException\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"num_nodes = 2\n",
|
||||||
|
"\n",
|
||||||
"# Choose a name for your cluster.\n",
|
"# Choose a name for your cluster.\n",
|
||||||
"amlcompute_cluster_name = \"dnntext-cluster\"\n",
|
"amlcompute_cluster_name = \"dnntext-cluster\"\n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -159,11 +163,11 @@
|
|||||||
" compute_target = ComputeTarget(workspace=ws, name=amlcompute_cluster_name)\n",
|
" compute_target = ComputeTarget(workspace=ws, name=amlcompute_cluster_name)\n",
|
||||||
" print('Found existing cluster, use it.')\n",
|
" print('Found existing cluster, use it.')\n",
|
||||||
"except ComputeTargetException:\n",
|
"except ComputeTargetException:\n",
|
||||||
" compute_config = AmlCompute.provisioning_configuration(vm_size = \"STANDARD_NC6\", # CPU for BiLSTM, such as \"STANDARD_D2_V2\" \n",
|
" compute_config = AmlCompute.provisioning_configuration(vm_size = \"STANDARD_NC6\", # CPU for BiLSTM, such as \"STANDARD_DS12_V2\" \n",
|
||||||
" # To use BERT (this is recommended for best performance), select a GPU such as \"STANDARD_NC6\" \n",
|
" # To use BERT (this is recommended for best performance), select a GPU such as \"STANDARD_NC6\" \n",
|
||||||
" # or similar GPU option\n",
|
" # or similar GPU option\n",
|
||||||
" # available in your workspace\n",
|
" # available in your workspace\n",
|
||||||
" max_nodes = 1)\n",
|
" max_nodes = num_nodes)\n",
|
||||||
" compute_target = ComputeTarget.create(ws, amlcompute_cluster_name, compute_config)\n",
|
" compute_target = ComputeTarget.create(ws, amlcompute_cluster_name, compute_config)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"compute_target.wait_for_completion(show_output=True)"
|
"compute_target.wait_for_completion(show_output=True)"
|
||||||
@@ -270,7 +274,7 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"This step requires an Enterprise workspace to gain access to this feature. To learn more about creating an Enterprise workspace or upgrading to an Enterprise workspace from the Azure portal, please visit our [Workspace page](https://docs.microsoft.com/azure/machine-learning/service/concept-workspace#upgrade)."
|
"This notebook uses the blocked_models parameter to exclude some models that can take a longer time to train on some text datasets. You can choose to remove models from the blocked_models list but you may need to increase the experiment_timeout_hours parameter value to get results."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -280,9 +284,9 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"automl_settings = {\n",
|
"automl_settings = {\n",
|
||||||
" \"experiment_timeout_minutes\": 20,\n",
|
" \"experiment_timeout_minutes\": 30,\n",
|
||||||
" \"primary_metric\": 'accuracy',\n",
|
" \"primary_metric\": 'AUC_weighted',\n",
|
||||||
" \"max_concurrent_iterations\": 4, \n",
|
" \"max_concurrent_iterations\": num_nodes, \n",
|
||||||
" \"max_cores_per_iteration\": -1,\n",
|
" \"max_cores_per_iteration\": -1,\n",
|
||||||
" \"enable_dnn\": True,\n",
|
" \"enable_dnn\": True,\n",
|
||||||
" \"enable_early_stopping\": True,\n",
|
" \"enable_early_stopping\": True,\n",
|
||||||
@@ -297,6 +301,7 @@
|
|||||||
" compute_target=compute_target,\n",
|
" compute_target=compute_target,\n",
|
||||||
" training_data=train_dataset,\n",
|
" training_data=train_dataset,\n",
|
||||||
" label_column_name=target_column_name,\n",
|
" label_column_name=target_column_name,\n",
|
||||||
|
" blocked_models = ['LightGBM', 'XGBoostClassifier'],\n",
|
||||||
" **automl_settings\n",
|
" **automl_settings\n",
|
||||||
" )"
|
" )"
|
||||||
]
|
]
|
||||||
@@ -317,15 +322,6 @@
|
|||||||
"automl_run = experiment.submit(automl_config, show_output=True)"
|
"automl_run = experiment.submit(automl_config, show_output=True)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"automl_run"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
@@ -345,8 +341,9 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"You can test the model locally to get a feel of the input/output. When the model contains BERT, this step will require pytorch and pytorch-transformers installed in your local environment. The exact versions of these packages can be found in the **automl_env.yml** file located in the local copy of your MachineLearningNotebooks folder here:\n",
|
"For local inferencing, you can load the model locally via. the method `remote_run.get_output()`. For more information on the arguments expected by this method, you can run `remote_run.get_output??`.\n",
|
||||||
"MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/automl_env.yml"
|
"Note that when the model contains BERT, this step will require pytorch and pytorch-transformers installed in your local environment. The exact versions of these packages can be found in the **automl_env.yml** file located in the local copy of your MachineLearningNotebooks folder here:\n",
|
||||||
|
"MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/automl_env.yml\n"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -355,7 +352,8 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"best_run, fitted_model = automl_run.get_output()"
|
"# Retrieve the best Run object\n",
|
||||||
|
"best_run = automl_run.get_best_child()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -371,10 +369,15 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"text_transformations_used = []\n",
|
"# Download the featuurization summary JSON file locally\n",
|
||||||
"for column_group in fitted_model.named_steps['datatransformer'].get_featurization_summary():\n",
|
"best_run.download_file(\"outputs/featurization_summary.json\", \"featurization_summary.json\")\n",
|
||||||
" text_transformations_used.extend(column_group['Transformations'])\n",
|
"\n",
|
||||||
"text_transformations_used"
|
"# Render the JSON as a pandas DataFrame\n",
|
||||||
|
"with open(\"featurization_summary.json\", \"r\") as f:\n",
|
||||||
|
" records = json.load(f)\n",
|
||||||
|
"\n",
|
||||||
|
"featurization_summary = pd.DataFrame.from_records(records)\n",
|
||||||
|
"featurization_summary['Transformations'].tolist()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -492,7 +495,7 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"test_run = run_inference(test_experiment, compute_target, script_folder, best_dnn_run,\n",
|
"test_run = run_inference(test_experiment, compute_target, script_folder, best_dnn_run,\n",
|
||||||
" train_dataset, test_dataset, target_column_name, model_name)"
|
" test_dataset, target_column_name, model_name)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,20 +1,13 @@
|
|||||||
import pandas as pd
|
import pandas as pd
|
||||||
from azureml.core import Environment
|
from azureml.core import Environment
|
||||||
from azureml.core.conda_dependencies import CondaDependencies
|
|
||||||
from azureml.train.estimator import Estimator
|
from azureml.train.estimator import Estimator
|
||||||
from azureml.core.run import Run
|
from azureml.core.run import Run
|
||||||
|
|
||||||
|
|
||||||
def run_inference(test_experiment, compute_target, script_folder, train_run,
|
def run_inference(test_experiment, compute_target, script_folder, train_run,
|
||||||
train_dataset, test_dataset, target_column_name, model_name):
|
test_dataset, target_column_name, model_name):
|
||||||
|
|
||||||
train_run.download_file('outputs/conda_env_v_1_0_0.yml',
|
inference_env = train_run.get_environment()
|
||||||
'inference/condafile.yml')
|
|
||||||
|
|
||||||
inference_env = Environment("myenv")
|
|
||||||
inference_env.docker.enabled = True
|
|
||||||
inference_env.python.conda_dependencies = CondaDependencies(
|
|
||||||
conda_dependencies_file_path='inference/condafile.yml')
|
|
||||||
|
|
||||||
est = Estimator(source_directory=script_folder,
|
est = Estimator(source_directory=script_folder,
|
||||||
entry_script='infer.py',
|
entry_script='infer.py',
|
||||||
@@ -23,7 +16,6 @@ def run_inference(test_experiment, compute_target, script_folder, train_run,
|
|||||||
'--model_name': model_name
|
'--model_name': model_name
|
||||||
},
|
},
|
||||||
inputs=[
|
inputs=[
|
||||||
train_dataset.as_named_input('train_data'),
|
|
||||||
test_dataset.as_named_input('test_data')
|
test_dataset.as_named_input('test_data')
|
||||||
],
|
],
|
||||||
compute_target=compute_target,
|
compute_target=compute_target,
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import argparse
|
import argparse
|
||||||
|
|
||||||
|
import pandas as pd
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
||||||
from sklearn.externals import joblib
|
from sklearn.externals import joblib
|
||||||
@@ -32,22 +33,21 @@ model = joblib.load(model_path)
|
|||||||
run = Run.get_context()
|
run = Run.get_context()
|
||||||
# get input dataset by name
|
# get input dataset by name
|
||||||
test_dataset = run.input_datasets['test_data']
|
test_dataset = run.input_datasets['test_data']
|
||||||
train_dataset = run.input_datasets['train_data']
|
|
||||||
|
|
||||||
X_test_df = test_dataset.drop_columns(columns=[target_column_name]) \
|
X_test_df = test_dataset.drop_columns(columns=[target_column_name]) \
|
||||||
.to_pandas_dataframe()
|
.to_pandas_dataframe()
|
||||||
y_test_df = test_dataset.with_timestamp_columns(None) \
|
y_test_df = test_dataset.with_timestamp_columns(None) \
|
||||||
.keep_columns(columns=[target_column_name]) \
|
.keep_columns(columns=[target_column_name]) \
|
||||||
.to_pandas_dataframe()
|
.to_pandas_dataframe()
|
||||||
y_train_df = test_dataset.with_timestamp_columns(None) \
|
|
||||||
.keep_columns(columns=[target_column_name]) \
|
|
||||||
.to_pandas_dataframe()
|
|
||||||
|
|
||||||
predicted = model.predict_proba(X_test_df)
|
predicted = model.predict_proba(X_test_df)
|
||||||
|
|
||||||
|
if isinstance(predicted, pd.DataFrame):
|
||||||
|
predicted = predicted.values
|
||||||
|
|
||||||
# Use the AutoML scoring module
|
# Use the AutoML scoring module
|
||||||
class_labels = np.unique(np.concatenate((y_train_df.values, y_test_df.values)))
|
|
||||||
train_labels = model.classes_
|
train_labels = model.classes_
|
||||||
|
class_labels = np.unique(np.concatenate((y_test_df.values, np.reshape(train_labels, (-1, 1)))))
|
||||||
classification_metrics = list(constants.CLASSIFICATION_SCALAR_SET)
|
classification_metrics = list(constants.CLASSIFICATION_SCALAR_SET)
|
||||||
scores = scoring.score_classification(y_test_df.values, predicted,
|
scores = scoring.score_classification(y_test_df.values, predicted,
|
||||||
classification_metrics,
|
classification_metrics,
|
||||||
|
|||||||
@@ -32,13 +32,6 @@
|
|||||||
"8. [Test Retraining](#Test-Retraining)"
|
"8. [Test Retraining](#Test-Retraining)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"An Enterprise workspace is required for this notebook. To learn more about creating an Enterprise workspace or upgrading to an Enterprise workspace from the Azure portal, please visit our [Workspace page.](https://docs.microsoft.com/azure/machine-learning/service/concept-workspace#upgrade)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
@@ -88,7 +81,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"print(\"This notebook was created using version 1.12.0 of the Azure ML SDK\")\n",
|
"print(\"This notebook was created using version 1.37.0 of the Azure ML SDK\")\n",
|
||||||
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -148,9 +141,12 @@
|
|||||||
"#### Create or Attach existing AmlCompute\n",
|
"#### Create or Attach existing AmlCompute\n",
|
||||||
"\n",
|
"\n",
|
||||||
"You will need to create a compute target for your AutoML run. In this tutorial, you create AmlCompute as your training compute resource.\n",
|
"You will need to create a compute target for your AutoML run. In this tutorial, you create AmlCompute as your training compute resource.\n",
|
||||||
|
"\n",
|
||||||
|
"> 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.\n",
|
||||||
|
"\n",
|
||||||
"#### Creation of AmlCompute takes approximately 5 minutes. \n",
|
"#### Creation of AmlCompute takes approximately 5 minutes. \n",
|
||||||
"If the AmlCompute with that name is already in your workspace this code will skip the creation process.\n",
|
"If the AmlCompute with that name is already in your workspace this code will skip the creation process.\n",
|
||||||
"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."
|
"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](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -170,7 +166,7 @@
|
|||||||
" compute_target = ComputeTarget(workspace=ws, name=amlcompute_cluster_name)\n",
|
" compute_target = ComputeTarget(workspace=ws, name=amlcompute_cluster_name)\n",
|
||||||
" print('Found existing cluster, use it.')\n",
|
" print('Found existing cluster, use it.')\n",
|
||||||
"except ComputeTargetException:\n",
|
"except ComputeTargetException:\n",
|
||||||
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_D2_V2',\n",
|
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_DS12_V2',\n",
|
||||||
" max_nodes=4)\n",
|
" max_nodes=4)\n",
|
||||||
" compute_target = ComputeTarget.create(ws, amlcompute_cluster_name, compute_config)\n",
|
" compute_target = ComputeTarget.create(ws, amlcompute_cluster_name, compute_config)\n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -190,7 +186,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from azureml.core.runconfig import CondaDependencies, DEFAULT_CPU_IMAGE, RunConfiguration\n",
|
"from azureml.core.runconfig import CondaDependencies, RunConfiguration\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# create a new RunConfig object\n",
|
"# create a new RunConfig object\n",
|
||||||
"conda_run_config = RunConfiguration(framework=\"python\")\n",
|
"conda_run_config = RunConfiguration(framework=\"python\")\n",
|
||||||
@@ -199,7 +195,6 @@
|
|||||||
"conda_run_config.target = compute_target\n",
|
"conda_run_config.target = compute_target\n",
|
||||||
"\n",
|
"\n",
|
||||||
"conda_run_config.environment.docker.enabled = True\n",
|
"conda_run_config.environment.docker.enabled = True\n",
|
||||||
"conda_run_config.environment.docker.base_image = azureml.core.runconfig.DEFAULT_CPU_IMAGE\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
"cd = CondaDependencies.create(pip_packages=['azureml-sdk[automl]', 'applicationinsights', 'azureml-opendatasets', 'azureml-defaults'], \n",
|
"cd = CondaDependencies.create(pip_packages=['azureml-sdk[automl]', 'applicationinsights', 'azureml-opendatasets', 'azureml-defaults'], \n",
|
||||||
" conda_packages=['numpy==1.16.2'], \n",
|
" conda_packages=['numpy==1.16.2'], \n",
|
||||||
@@ -353,7 +348,7 @@
|
|||||||
" \"iteration_timeout_minutes\": 10,\n",
|
" \"iteration_timeout_minutes\": 10,\n",
|
||||||
" \"experiment_timeout_hours\": 0.25,\n",
|
" \"experiment_timeout_hours\": 0.25,\n",
|
||||||
" \"n_cross_validations\": 3,\n",
|
" \"n_cross_validations\": 3,\n",
|
||||||
" \"primary_metric\": 'r2_score',\n",
|
" \"primary_metric\": 'normalized_root_mean_squared_error',\n",
|
||||||
" \"max_concurrent_iterations\": 3,\n",
|
" \"max_concurrent_iterations\": 3,\n",
|
||||||
" \"max_cores_per_iteration\": -1,\n",
|
" \"max_cores_per_iteration\": -1,\n",
|
||||||
" \"verbosity\": logging.INFO,\n",
|
" \"verbosity\": logging.INFO,\n",
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ try:
|
|||||||
model = Model(ws, args.model_name)
|
model = Model(ws, args.model_name)
|
||||||
last_train_time = model.created_time
|
last_train_time = model.created_time
|
||||||
print("Model was last trained on {0}.".format(last_train_time))
|
print("Model was last trained on {0}.".format(last_train_time))
|
||||||
except Exception as e:
|
except Exception:
|
||||||
print("Could not get last model train time.")
|
print("Could not get last model train time.")
|
||||||
last_train_time = datetime.min.replace(tzinfo=pytz.UTC)
|
last_train_time = datetime.min.replace(tzinfo=pytz.UTC)
|
||||||
|
|
||||||
|
|||||||
@@ -49,22 +49,24 @@ print("Argument 1(ds_name): %s" % args.ds_name)
|
|||||||
|
|
||||||
dstor = ws.get_default_datastore()
|
dstor = ws.get_default_datastore()
|
||||||
register_dataset = False
|
register_dataset = False
|
||||||
|
end_time = datetime.utcnow()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
ds = Dataset.get_by_name(ws, args.ds_name)
|
ds = Dataset.get_by_name(ws, args.ds_name)
|
||||||
end_time_last_slice = ds.data_changed_time.replace(tzinfo=None)
|
end_time_last_slice = ds.data_changed_time.replace(tzinfo=None)
|
||||||
print("Dataset {0} last updated on {1}".format(args.ds_name,
|
print("Dataset {0} last updated on {1}".format(args.ds_name,
|
||||||
end_time_last_slice))
|
end_time_last_slice))
|
||||||
except Exception as e:
|
except Exception:
|
||||||
print(traceback.format_exc())
|
print(traceback.format_exc())
|
||||||
print("Dataset with name {0} not found, registering new dataset.".format(args.ds_name))
|
print("Dataset with name {0} not found, registering new dataset.".format(args.ds_name))
|
||||||
register_dataset = True
|
register_dataset = True
|
||||||
end_time_last_slice = datetime.today() - relativedelta(weeks=2)
|
end_time = datetime(2021, 5, 1, 0, 0)
|
||||||
|
end_time_last_slice = end_time - relativedelta(weeks=2)
|
||||||
|
|
||||||
end_time = datetime.utcnow()
|
|
||||||
train_df = get_noaa_data(end_time_last_slice, end_time)
|
train_df = get_noaa_data(end_time_last_slice, end_time)
|
||||||
|
|
||||||
if train_df.size > 0:
|
if train_df.size > 0:
|
||||||
print("Received {0} rows of new data after {0}.".format(
|
print("Received {0} rows of new data after {1}.".format(
|
||||||
train_df.shape[0], end_time_last_slice))
|
train_df.shape[0], end_time_last_slice))
|
||||||
folder_name = "{}/{:04d}/{:02d}/{:02d}/{:02d}/{:02d}/{:02d}".format(args.ds_name, end_time.year,
|
folder_name = "{}/{:04d}/{:02d}/{:02d}/{:02d}/{:02d}/{:02d}".format(args.ds_name, end_time.year,
|
||||||
end_time.month, end_time.day,
|
end_time.month, end_time.day,
|
||||||
|
|||||||
@@ -0,0 +1,92 @@
|
|||||||
|
# Experimental Notebooks for Automated ML
|
||||||
|
Notebooks listed in this folder are leveraging experimental features. Namespaces or function signitures may change in future SDK releases. The notebooks published here will reflect the latest supported APIs. All of these notebooks can run on a client-only installation of the Automated ML SDK.
|
||||||
|
The client only installation doesn't contain any of the machine learning libraries, such as scikit-learn, xgboost, or tensorflow, making it much faster to install and is less likely to conflict with any packages in an existing environment. However, since the ML libraries are not available locally, models cannot be downloaded and loaded directly in the client. To replace the functionality of having models locally, these notebooks also demonstrate the ModelProxy feature which will allow you to submit a predict/forecast to the training environment.
|
||||||
|
|
||||||
|
<a name="localconda"></a>
|
||||||
|
## Setup using a Local Conda environment
|
||||||
|
|
||||||
|
To run these notebook on your own notebook server, use these installation instructions.
|
||||||
|
The instructions below will install everything you need and then start a Jupyter notebook.
|
||||||
|
If you would like to use a lighter-weight version of the client that does not install all of the machine learning libraries locally, you can leverage the [experimental notebooks.](experimental/README.md)
|
||||||
|
|
||||||
|
### 1. Install mini-conda from [here](https://conda.io/miniconda.html), choose 64-bit Python 3.7 or higher.
|
||||||
|
- **Note**: if you already have conda installed, you can keep using it but it should be version 4.4.10 or later (as shown by: conda -V). If you have a previous version installed, you can update it using the command: conda update conda.
|
||||||
|
There's no need to install mini-conda specifically.
|
||||||
|
|
||||||
|
### 2. Downloading the sample notebooks
|
||||||
|
- Download the sample notebooks from [GitHub](https://github.com/Azure/MachineLearningNotebooks) as zip and extract the contents to a local directory. The automated ML sample notebooks are in the "automated-machine-learning" folder.
|
||||||
|
|
||||||
|
### 3. Setup a new conda environment
|
||||||
|
The **automl_setup_thin_client** script creates a new conda environment, installs the necessary packages, configures the widget and starts a jupyter notebook. It takes the conda environment name as an optional parameter. The default conda environment name is azure_automl_experimental. The exact command depends on the operating system. See the specific sections below for Windows, Mac and Linux. It can take about 10 minutes to execute.
|
||||||
|
|
||||||
|
Packages installed by the **automl_setup** script:
|
||||||
|
<ul><li>python</li><li>nb_conda</li><li>matplotlib</li><li>numpy</li><li>cython</li><li>urllib3</li><li>pandas</li><li>azureml-sdk</li><li>azureml-widgets</li><li>pandas-ml</li></ul>
|
||||||
|
|
||||||
|
For more details refer to the [automl_env_thin_client.yml](./automl_env_thin_client.yml)
|
||||||
|
## Windows
|
||||||
|
Start an **Anaconda Prompt** window, cd to the **how-to-use-azureml/automated-machine-learning/experimental** folder where the sample notebooks were extracted and then run:
|
||||||
|
```
|
||||||
|
automl_setup_thin_client
|
||||||
|
```
|
||||||
|
## Mac
|
||||||
|
Install "Command line developer tools" if it is not already installed (you can use the command: `xcode-select --install`).
|
||||||
|
|
||||||
|
Start a Terminal windows, cd to the **how-to-use-azureml/automated-machine-learning/experimental** folder where the sample notebooks were extracted and then run:
|
||||||
|
|
||||||
|
```
|
||||||
|
bash automl_setup_thin_client_mac.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
## Linux
|
||||||
|
cd to the **how-to-use-azureml/automated-machine-learning/experimental** folder where the sample notebooks were extracted and then run:
|
||||||
|
|
||||||
|
```
|
||||||
|
bash automl_setup_thin_client_linux.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. Running configuration.ipynb
|
||||||
|
- Before running any samples you next need to run the configuration notebook. Click on [configuration](../../configuration.ipynb) notebook
|
||||||
|
- Execute the cells in the notebook to Register Machine Learning Services Resource Provider and create a workspace. (*instructions in notebook*)
|
||||||
|
|
||||||
|
### 5. Running Samples
|
||||||
|
- Please make sure you use the Python [conda env:azure_automl_experimental] kernel when trying the sample Notebooks.
|
||||||
|
- Follow the instructions in the individual notebooks to explore various features in automated ML.
|
||||||
|
|
||||||
|
### 6. Starting jupyter notebook manually
|
||||||
|
To start your Jupyter notebook manually, use:
|
||||||
|
|
||||||
|
```
|
||||||
|
conda activate azure_automl
|
||||||
|
jupyter notebook
|
||||||
|
```
|
||||||
|
|
||||||
|
or on Mac or Linux:
|
||||||
|
|
||||||
|
```
|
||||||
|
source activate azure_automl
|
||||||
|
jupyter notebook
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
<a name="samples"></a>
|
||||||
|
# Automated ML SDK Sample Notebooks
|
||||||
|
|
||||||
|
- [auto-ml-regression-model-proxy.ipynb](regression-model-proxy/auto-ml-regression-model-proxy.ipynb)
|
||||||
|
- Dataset: Hardware Performance Dataset
|
||||||
|
- Simple example of using automated ML for regression
|
||||||
|
- Uses azure compute for training
|
||||||
|
- Uses ModelProxy for submitting prediction to training environment on azure compute
|
||||||
|
|
||||||
|
<a name="documentation"></a>
|
||||||
|
See [Configure automated machine learning experiments](https://docs.microsoft.com/azure/machine-learning/service/how-to-configure-auto-train) to learn how more about the the settings and features available for automated machine learning experiments.
|
||||||
|
|
||||||
|
<a name="pythoncommand"></a>
|
||||||
|
# Running using python command
|
||||||
|
Jupyter notebook provides a File / Download as / Python (.py) option for saving the notebook as a Python file.
|
||||||
|
You can then run this file using the python command.
|
||||||
|
However, on Windows the file needs to be modified before it can be run.
|
||||||
|
The following condition must be added to the main code in the file:
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
The main code of the file must be indented so that it is under this condition.
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
@echo off
|
||||||
|
set conda_env_name=%1
|
||||||
|
set automl_env_file=%2
|
||||||
|
set options=%3
|
||||||
|
set PIP_NO_WARN_SCRIPT_LOCATION=0
|
||||||
|
|
||||||
|
IF "%conda_env_name%"=="" SET conda_env_name="azure_automl_experimental"
|
||||||
|
IF "%automl_env_file%"=="" SET automl_env_file="automl_thin_client_env.yml"
|
||||||
|
|
||||||
|
IF NOT EXIST %automl_env_file% GOTO YmlMissing
|
||||||
|
|
||||||
|
IF "%CONDA_EXE%"=="" GOTO CondaMissing
|
||||||
|
|
||||||
|
call conda activate %conda_env_name% 2>nul:
|
||||||
|
|
||||||
|
if not errorlevel 1 (
|
||||||
|
echo Upgrading existing conda environment %conda_env_name%
|
||||||
|
call pip uninstall azureml-train-automl -y -q
|
||||||
|
call conda env update --name %conda_env_name% --file %automl_env_file%
|
||||||
|
if errorlevel 1 goto ErrorExit
|
||||||
|
) else (
|
||||||
|
call conda env create -f %automl_env_file% -n %conda_env_name%
|
||||||
|
)
|
||||||
|
|
||||||
|
call conda activate %conda_env_name% 2>nul:
|
||||||
|
if errorlevel 1 goto ErrorExit
|
||||||
|
|
||||||
|
call python -m ipykernel install --user --name %conda_env_name% --display-name "Python (%conda_env_name%)"
|
||||||
|
|
||||||
|
REM azureml.widgets is now installed as part of the pip install under the conda env.
|
||||||
|
REM Removing the old user install so that the notebooks will use the latest widget.
|
||||||
|
call jupyter nbextension uninstall --user --py azureml.widgets
|
||||||
|
|
||||||
|
echo.
|
||||||
|
echo.
|
||||||
|
echo ***************************************
|
||||||
|
echo * AutoML setup completed successfully *
|
||||||
|
echo ***************************************
|
||||||
|
IF NOT "%options%"=="nolaunch" (
|
||||||
|
echo.
|
||||||
|
echo Starting jupyter notebook - please run the configuration notebook
|
||||||
|
echo.
|
||||||
|
jupyter notebook --log-level=50 --notebook-dir='..\..'
|
||||||
|
)
|
||||||
|
|
||||||
|
goto End
|
||||||
|
|
||||||
|
:CondaMissing
|
||||||
|
echo Please run this script from an Anaconda Prompt window.
|
||||||
|
echo You can start an Anaconda Prompt window by
|
||||||
|
echo typing Anaconda Prompt on the Start menu.
|
||||||
|
echo If you don't see the Anaconda Prompt app, install Miniconda.
|
||||||
|
echo If you are running an older version of Miniconda or Anaconda,
|
||||||
|
echo you can upgrade using the command: conda update conda
|
||||||
|
goto End
|
||||||
|
|
||||||
|
:YmlMissing
|
||||||
|
echo File %automl_env_file% not found.
|
||||||
|
|
||||||
|
:ErrorExit
|
||||||
|
echo Install failed
|
||||||
|
|
||||||
|
:End
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
CONDA_ENV_NAME=$1
|
||||||
|
AUTOML_ENV_FILE=$2
|
||||||
|
OPTIONS=$3
|
||||||
|
PIP_NO_WARN_SCRIPT_LOCATION=0
|
||||||
|
|
||||||
|
if [ "$CONDA_ENV_NAME" == "" ]
|
||||||
|
then
|
||||||
|
CONDA_ENV_NAME="azure_automl_experimental"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ "$AUTOML_ENV_FILE" == "" ]
|
||||||
|
then
|
||||||
|
AUTOML_ENV_FILE="automl_thin_client_env.yml"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ ! -f $AUTOML_ENV_FILE ]; then
|
||||||
|
echo "File $AUTOML_ENV_FILE not found"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if source activate $CONDA_ENV_NAME 2> /dev/null
|
||||||
|
then
|
||||||
|
echo "Upgrading existing conda environment" $CONDA_ENV_NAME
|
||||||
|
pip uninstall azureml-train-automl -y -q
|
||||||
|
conda env update --name $CONDA_ENV_NAME --file $AUTOML_ENV_FILE &&
|
||||||
|
jupyter nbextension uninstall --user --py azureml.widgets
|
||||||
|
else
|
||||||
|
conda env create -f $AUTOML_ENV_FILE -n $CONDA_ENV_NAME &&
|
||||||
|
source activate $CONDA_ENV_NAME &&
|
||||||
|
python -m ipykernel install --user --name $CONDA_ENV_NAME --display-name "Python ($CONDA_ENV_NAME)" &&
|
||||||
|
jupyter nbextension uninstall --user --py azureml.widgets &&
|
||||||
|
echo "" &&
|
||||||
|
echo "" &&
|
||||||
|
echo "***************************************" &&
|
||||||
|
echo "* AutoML setup completed successfully *" &&
|
||||||
|
echo "***************************************" &&
|
||||||
|
if [ "$OPTIONS" != "nolaunch" ]
|
||||||
|
then
|
||||||
|
echo "" &&
|
||||||
|
echo "Starting jupyter notebook - please run the configuration notebook" &&
|
||||||
|
echo "" &&
|
||||||
|
jupyter notebook --log-level=50 --notebook-dir '../..'
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ $? -gt 0 ]
|
||||||
|
then
|
||||||
|
echo "Installation failed"
|
||||||
|
fi
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
CONDA_ENV_NAME=$1
|
||||||
|
AUTOML_ENV_FILE=$2
|
||||||
|
OPTIONS=$3
|
||||||
|
PIP_NO_WARN_SCRIPT_LOCATION=0
|
||||||
|
|
||||||
|
if [ "$CONDA_ENV_NAME" == "" ]
|
||||||
|
then
|
||||||
|
CONDA_ENV_NAME="azure_automl_experimental"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ "$AUTOML_ENV_FILE" == "" ]
|
||||||
|
then
|
||||||
|
AUTOML_ENV_FILE="automl_thin_client_env_mac.yml"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ ! -f $AUTOML_ENV_FILE ]; then
|
||||||
|
echo "File $AUTOML_ENV_FILE not found"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if source activate $CONDA_ENV_NAME 2> /dev/null
|
||||||
|
then
|
||||||
|
echo "Upgrading existing conda environment" $CONDA_ENV_NAME
|
||||||
|
pip uninstall azureml-train-automl -y -q
|
||||||
|
conda env update --name $CONDA_ENV_NAME --file $AUTOML_ENV_FILE &&
|
||||||
|
jupyter nbextension uninstall --user --py azureml.widgets
|
||||||
|
else
|
||||||
|
conda env create -f $AUTOML_ENV_FILE -n $CONDA_ENV_NAME &&
|
||||||
|
source activate $CONDA_ENV_NAME &&
|
||||||
|
conda install lightgbm -c conda-forge -y &&
|
||||||
|
python -m ipykernel install --user --name $CONDA_ENV_NAME --display-name "Python ($CONDA_ENV_NAME)" &&
|
||||||
|
jupyter nbextension uninstall --user --py azureml.widgets &&
|
||||||
|
echo "" &&
|
||||||
|
echo "" &&
|
||||||
|
echo "***************************************" &&
|
||||||
|
echo "* AutoML setup completed successfully *" &&
|
||||||
|
echo "***************************************" &&
|
||||||
|
if [ "$OPTIONS" != "nolaunch" ]
|
||||||
|
then
|
||||||
|
echo "" &&
|
||||||
|
echo "Starting jupyter notebook - please run the configuration notebook" &&
|
||||||
|
echo "" &&
|
||||||
|
jupyter notebook --log-level=50 --notebook-dir '../..'
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ $? -gt 0 ]
|
||||||
|
then
|
||||||
|
echo "Installation failed"
|
||||||
|
fi
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
name: azure_automl_experimental
|
||||||
|
dependencies:
|
||||||
|
# The python interpreter version.
|
||||||
|
# Currently Azure ML only supports 3.5.2 and later.
|
||||||
|
- pip<=19.3.1
|
||||||
|
- python>=3.5.2,<3.8
|
||||||
|
- nb_conda
|
||||||
|
- cython
|
||||||
|
- urllib3<1.24
|
||||||
|
- PyJWT < 2.0.0
|
||||||
|
- numpy==1.18.5
|
||||||
|
|
||||||
|
- pip:
|
||||||
|
# Required packages for AzureML execution, history, and data preparation.
|
||||||
|
- azureml-defaults
|
||||||
|
- azureml-sdk
|
||||||
|
- azureml-widgets
|
||||||
|
- pandas
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
name: azure_automl_experimental
|
||||||
|
dependencies:
|
||||||
|
# The python interpreter version.
|
||||||
|
# Currently Azure ML only supports 3.5.2 and later.
|
||||||
|
- pip<=19.3.1
|
||||||
|
- nomkl
|
||||||
|
- python>=3.5.2,<3.8
|
||||||
|
- nb_conda
|
||||||
|
- cython
|
||||||
|
- urllib3<1.24
|
||||||
|
- PyJWT < 2.0.0
|
||||||
|
- numpy==1.18.5
|
||||||
|
|
||||||
|
- pip:
|
||||||
|
# Required packages for AzureML execution, history, and data preparation.
|
||||||
|
- azureml-defaults
|
||||||
|
- azureml-sdk
|
||||||
|
- azureml-widgets
|
||||||
|
- pandas
|
||||||
@@ -0,0 +1,420 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
||||||
|
"\n",
|
||||||
|
"Licensed under the MIT License."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
""
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Automated Machine Learning\n",
|
||||||
|
"_**Classification of credit card fraudulent transactions on local managed compute **_\n",
|
||||||
|
"\n",
|
||||||
|
"## Contents\n",
|
||||||
|
"1. [Introduction](#Introduction)\n",
|
||||||
|
"1. [Setup](#Setup)\n",
|
||||||
|
"1. [Train](#Train)\n",
|
||||||
|
"1. [Results](#Results)\n",
|
||||||
|
"1. [Test](#Test)\n",
|
||||||
|
"1. [Acknowledgements](#Acknowledgements)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Introduction\n",
|
||||||
|
"\n",
|
||||||
|
"In this example we use the associated credit card dataset to showcase how you can use AutoML for a simple classification problem. The goal is to predict if a credit card transaction is considered a fraudulent charge.\n",
|
||||||
|
"\n",
|
||||||
|
"This notebook is using local managed compute to train the model.\n",
|
||||||
|
"\n",
|
||||||
|
"If you are using an Azure Machine Learning Compute Instance, you are all set. Otherwise, go through the [configuration](../../../configuration.ipynb) notebook first if you haven't already to establish your connection to the AzureML Workspace. \n",
|
||||||
|
"\n",
|
||||||
|
"In this notebook you will learn how to:\n",
|
||||||
|
"1. Create an experiment using an existing workspace.\n",
|
||||||
|
"2. Configure AutoML using `AutoMLConfig`.\n",
|
||||||
|
"3. Train the model using local managed compute.\n",
|
||||||
|
"4. Explore the results.\n",
|
||||||
|
"5. Test the fitted model."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Setup\n",
|
||||||
|
"\n",
|
||||||
|
"As part of the setup you have already created an Azure ML `Workspace` object. For Automated ML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"import logging\n",
|
||||||
|
"\n",
|
||||||
|
"import pandas as pd\n",
|
||||||
|
"\n",
|
||||||
|
"import azureml.core\n",
|
||||||
|
"from azureml.core.compute_target import LocalTarget\n",
|
||||||
|
"from azureml.core.experiment import Experiment\n",
|
||||||
|
"from azureml.core.workspace import Workspace\n",
|
||||||
|
"from azureml.core.dataset import Dataset\n",
|
||||||
|
"from azureml.train.automl import AutoMLConfig"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"This sample notebook may use features that are not available in previous versions of the Azure ML SDK."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"print(\"This notebook was created using version 1.37.0 of the Azure ML SDK\")\n",
|
||||||
|
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"ws = Workspace.from_config()\n",
|
||||||
|
"\n",
|
||||||
|
"# choose a name for experiment\n",
|
||||||
|
"experiment_name = 'automl-local-managed'\n",
|
||||||
|
"\n",
|
||||||
|
"experiment=Experiment(ws, experiment_name)\n",
|
||||||
|
"\n",
|
||||||
|
"output = {}\n",
|
||||||
|
"output['Subscription ID'] = ws.subscription_id\n",
|
||||||
|
"output['Workspace'] = ws.name\n",
|
||||||
|
"output['Resource Group'] = ws.resource_group\n",
|
||||||
|
"output['Location'] = ws.location\n",
|
||||||
|
"output['Experiment Name'] = experiment.name\n",
|
||||||
|
"pd.set_option('display.max_colwidth', -1)\n",
|
||||||
|
"outputDf = pd.DataFrame(data = output, index = [''])\n",
|
||||||
|
"outputDf.T"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Determine if local docker is configured for Linux images\n",
|
||||||
|
"\n",
|
||||||
|
"Local managed runs will leverage a Linux docker container to submit the run to. Due to this, the docker needs to be configured to use Linux containers."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Check if Docker is installed and Linux containers are enabled\n",
|
||||||
|
"import subprocess\n",
|
||||||
|
"from subprocess import CalledProcessError\n",
|
||||||
|
"try:\n",
|
||||||
|
" assert subprocess.run(\"docker -v\", shell=True).returncode == 0, 'Local Managed runs require docker to be installed.'\n",
|
||||||
|
" out = subprocess.check_output(\"docker system info\", shell=True).decode('ascii')\n",
|
||||||
|
" assert \"OSType: linux\" in out, 'Docker engine needs to be configured to use Linux containers.' \\\n",
|
||||||
|
" 'https://docs.docker.com/docker-for-windows/#switch-between-windows-and-linux-containers'\n",
|
||||||
|
"except CalledProcessError as ex:\n",
|
||||||
|
" raise Exception('Local Managed runs require docker to be installed.') from ex"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Data"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Load Data\n",
|
||||||
|
"\n",
|
||||||
|
"Load the credit card dataset from a csv file containing both training features and labels. The features are inputs to the model, while the training labels represent the expected output of the model. Next, we'll split the data using random_split and extract the training data for the model."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"data = \"https://automlsamplenotebookdata.blob.core.windows.net/automl-sample-notebook-data/creditcard.csv\"\n",
|
||||||
|
"dataset = Dataset.Tabular.from_delimited_files(data)\n",
|
||||||
|
"training_data, validation_data = dataset.random_split(percentage=0.8, seed=223)\n",
|
||||||
|
"label_column_name = 'Class'"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Train\n",
|
||||||
|
"\n",
|
||||||
|
"Instantiate a AutoMLConfig object. This defines the settings and data used to run the experiment.\n",
|
||||||
|
"\n",
|
||||||
|
"|Property|Description|\n",
|
||||||
|
"|-|-|\n",
|
||||||
|
"|**task**|classification or regression|\n",
|
||||||
|
"|**primary_metric**|This is the metric that you want to optimize. Classification supports the following primary metrics: <br><i>accuracy</i><br><i>AUC_weighted</i><br><i>average_precision_score_weighted</i><br><i>norm_macro_recall</i><br><i>precision_score_weighted</i>|\n",
|
||||||
|
"|**enable_early_stopping**|Stop the run if the metric score is not showing improvement.|\n",
|
||||||
|
"|**n_cross_validations**|Number of cross validation splits.|\n",
|
||||||
|
"|**training_data**|Input dataset, containing both features and label column.|\n",
|
||||||
|
"|**label_column_name**|The name of the label column.|\n",
|
||||||
|
"|**enable_local_managed**|Enable the experimental local-managed scenario.|\n",
|
||||||
|
"\n",
|
||||||
|
"**_You can find more information about primary metrics_** [here](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-configure-auto-train#primary-metric)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"automl_settings = {\n",
|
||||||
|
" \"n_cross_validations\": 3,\n",
|
||||||
|
" \"primary_metric\": 'average_precision_score_weighted',\n",
|
||||||
|
" \"enable_early_stopping\": True,\n",
|
||||||
|
" \"experiment_timeout_hours\": 0.3, #for real scenarios we recommend a timeout of at least one hour \n",
|
||||||
|
" \"verbosity\": logging.INFO,\n",
|
||||||
|
"}\n",
|
||||||
|
"\n",
|
||||||
|
"automl_config = AutoMLConfig(task = 'classification',\n",
|
||||||
|
" debug_log = 'automl_errors.log',\n",
|
||||||
|
" compute_target = LocalTarget(),\n",
|
||||||
|
" enable_local_managed = True,\n",
|
||||||
|
" training_data = training_data,\n",
|
||||||
|
" label_column_name = label_column_name,\n",
|
||||||
|
" **automl_settings\n",
|
||||||
|
" )"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Call the `submit` method on the experiment object and pass the run configuration. Depending on the data and the number of iterations this can run for a while. Validation errors and current status will be shown when setting `show_output=True` and the execution will be synchronous."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"parent_run = experiment.submit(automl_config, show_output = True)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# If you need to retrieve a run that already started, use the following code\n",
|
||||||
|
"#from azureml.train.automl.run import AutoMLRun\n",
|
||||||
|
"#parent_run = AutoMLRun(experiment = experiment, run_id = '<replace with your run id>')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"parent_run"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Results"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Explain model\n",
|
||||||
|
"\n",
|
||||||
|
"Automated ML models can be explained and visualized using the SDK Explainability library. "
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Analyze results\n",
|
||||||
|
"\n",
|
||||||
|
"### Retrieve the Best Child Run\n",
|
||||||
|
"\n",
|
||||||
|
"Below we select the best pipeline from our iterations. The `get_best_child` method returns the best run. Overloads on `get_best_child` allow you to retrieve the best run for *any* logged metric."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"best_run = parent_run.get_best_child()\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Test the fitted model\n",
|
||||||
|
"\n",
|
||||||
|
"Now that the model is trained, split the data in the same way the data was split for training (The difference here is the data is being split locally) and then run the test data through the trained model to get the predicted values."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"X_test_df = validation_data.drop_columns(columns=[label_column_name])\n",
|
||||||
|
"y_test_df = validation_data.keep_columns(columns=[label_column_name], validate=True)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Creating ModelProxy for submitting prediction runs to the training environment.\n",
|
||||||
|
"We will create a ModelProxy for the best child run, which will allow us to submit a run that does the prediction in the training environment. Unlike the local client, which can have different versions of some libraries, the training environment will have all the compatible libraries for the model already."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.train.automl.model_proxy import ModelProxy\n",
|
||||||
|
"best_model_proxy = ModelProxy(best_run)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# call the predict functions on the model proxy\n",
|
||||||
|
"y_pred = best_model_proxy.predict(X_test_df).to_pandas_dataframe()\n",
|
||||||
|
"y_pred"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Acknowledgements"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"This Credit Card fraud Detection dataset is made available under the Open Database License: http://opendatacommons.org/licenses/odbl/1.0/. Any rights in individual contents of the database are licensed under the Database Contents License: http://opendatacommons.org/licenses/dbcl/1.0/ and is available at: https://www.kaggle.com/mlg-ulb/creditcardfraud\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"The dataset has been collected and analysed during a research collaboration of Worldline and the Machine Learning Group (http://mlg.ulb.ac.be) of ULB (Universit\u00c3\u0192\u00c2\u00a9 Libre de Bruxelles) on big data mining and fraud detection. More details on current and past projects on related topics are available on https://www.researchgate.net/project/Fraud-detection-5 and the page of the DefeatFraud project\n",
|
||||||
|
"Please cite the following works: \n",
|
||||||
|
"\u00c3\u00a2\u00e2\u201a\u00ac\u00c2\u00a2\tAndrea Dal Pozzolo, Olivier Caelen, Reid A. Johnson and Gianluca Bontempi. Calibrating Probability with Undersampling for Unbalanced Classification. In Symposium on Computational Intelligence and Data Mining (CIDM), IEEE, 2015\n",
|
||||||
|
"\u00c3\u00a2\u00e2\u201a\u00ac\u00c2\u00a2\tDal Pozzolo, Andrea; Caelen, Olivier; Le Borgne, Yann-Ael; Waterschoot, Serge; Bontempi, Gianluca. Learned lessons in credit card fraud detection from a practitioner perspective, Expert systems with applications,41,10,4915-4928,2014, Pergamon\n",
|
||||||
|
"\u00c3\u00a2\u00e2\u201a\u00ac\u00c2\u00a2\tDal Pozzolo, Andrea; Boracchi, Giacomo; Caelen, Olivier; Alippi, Cesare; Bontempi, Gianluca. Credit card fraud detection: a realistic modeling and a novel learning strategy, IEEE transactions on neural networks and learning systems,29,8,3784-3797,2018,IEEE\n",
|
||||||
|
"o\tDal Pozzolo, Andrea Adaptive Machine learning for credit card fraud detection ULB MLG PhD thesis (supervised by G. Bontempi)\n",
|
||||||
|
"\u00c3\u00a2\u00e2\u201a\u00ac\u00c2\u00a2\tCarcillo, Fabrizio; Dal Pozzolo, Andrea; Le Borgne, Yann-A\u00c3\u0192\u00c2\u00abl; Caelen, Olivier; Mazzer, Yannis; Bontempi, Gianluca. Scarff: a scalable framework for streaming credit card fraud detection with Spark, Information fusion,41, 182-194,2018,Elsevier\n",
|
||||||
|
"\u00c3\u00a2\u00e2\u201a\u00ac\u00c2\u00a2\tCarcillo, Fabrizio; Le Borgne, Yann-A\u00c3\u0192\u00c2\u00abl; Caelen, Olivier; Bontempi, Gianluca. Streaming active learning strategies for real-life credit card fraud detection: assessment and visualization, International Journal of Data Science and Analytics, 5,4,285-300,2018,Springer International Publishing"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"authors": [
|
||||||
|
{
|
||||||
|
"name": "sekrupa"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"category": "tutorial",
|
||||||
|
"compute": [
|
||||||
|
"AML Compute"
|
||||||
|
],
|
||||||
|
"datasets": [
|
||||||
|
"Creditcard"
|
||||||
|
],
|
||||||
|
"deployment": [
|
||||||
|
"None"
|
||||||
|
],
|
||||||
|
"exclude_from_index": false,
|
||||||
|
"file_extension": ".py",
|
||||||
|
"framework": [
|
||||||
|
"None"
|
||||||
|
],
|
||||||
|
"friendly_name": "Classification of credit card fraudulent transactions using Automated ML",
|
||||||
|
"index_order": 5,
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 3.6",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python36"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"codemirror_mode": {
|
||||||
|
"name": "ipython",
|
||||||
|
"version": 3
|
||||||
|
},
|
||||||
|
"file_extension": ".py",
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython3",
|
||||||
|
"version": "3.6.7"
|
||||||
|
},
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython3",
|
||||||
|
"tags": [
|
||||||
|
"AutomatedML"
|
||||||
|
],
|
||||||
|
"task": "Classification",
|
||||||
|
"version": "3.6.7"
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 2
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
name: auto-ml-classification-credit-card-fraud-local-managed
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
@@ -0,0 +1,435 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
||||||
|
"\n",
|
||||||
|
"Licensed under the MIT License."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
""
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Automated Machine Learning\n",
|
||||||
|
"_**Regression with Aml Compute**_\n",
|
||||||
|
"\n",
|
||||||
|
"## Contents\n",
|
||||||
|
"1. [Introduction](#Introduction)\n",
|
||||||
|
"1. [Setup](#Setup)\n",
|
||||||
|
"1. [Data](#Data)\n",
|
||||||
|
"1. [Train](#Train)\n",
|
||||||
|
"1. [Results](#Results)\n",
|
||||||
|
"1. [Test](#Test)\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Introduction\n",
|
||||||
|
"In this example we use an experimental feature, Model Proxy, to do a predict on the best generated model without downloading the model locally. The prediction will happen on same compute and environment that was used to train the model. This feature is currently in the experimental state, which means that the API is prone to changing, please make sure to run on the latest version of this notebook if you face any issues.\n",
|
||||||
|
"This notebook will also leverage MLFlow for saving models, allowing for more portability of the resulting models. See https://docs.microsoft.com/en-us/azure/machine-learning/how-to-use-mlflow for more details around MLFlow is AzureML.\n",
|
||||||
|
"\n",
|
||||||
|
"If you are using an Azure Machine Learning Compute Instance, you are all set. Otherwise, go through the [configuration](../../../../configuration.ipynb) notebook first if you haven't already to establish your connection to the AzureML Workspace. \n",
|
||||||
|
"\n",
|
||||||
|
"In this notebook you will learn how to:\n",
|
||||||
|
"1. Create an `Experiment` in an existing `Workspace`.\n",
|
||||||
|
"2. Configure AutoML using `AutoMLConfig`.\n",
|
||||||
|
"3. Train the model using remote compute.\n",
|
||||||
|
"4. Explore the results.\n",
|
||||||
|
"5. Test the best fitted model."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Setup\n",
|
||||||
|
"\n",
|
||||||
|
"As part of the setup you have already created an Azure ML `Workspace` object. For Automated ML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"import logging\n",
|
||||||
|
"\n",
|
||||||
|
"import json\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"import azureml.core\n",
|
||||||
|
"from azureml.core.experiment import Experiment\n",
|
||||||
|
"from azureml.core.workspace import Workspace\n",
|
||||||
|
"from azureml.core.dataset import Dataset\n",
|
||||||
|
"from azureml.train.automl import AutoMLConfig"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"This sample notebook may use features that are not available in previous versions of the Azure ML SDK."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"print(\"This notebook was created using version 1.37.0 of the Azure ML SDK\")\n",
|
||||||
|
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"ws = Workspace.from_config()\n",
|
||||||
|
"\n",
|
||||||
|
"# Choose a name for the experiment.\n",
|
||||||
|
"experiment_name = 'automl-regression-model-proxy'\n",
|
||||||
|
"\n",
|
||||||
|
"experiment = Experiment(ws, experiment_name)\n",
|
||||||
|
"\n",
|
||||||
|
"output = {}\n",
|
||||||
|
"output['Subscription ID'] = ws.subscription_id\n",
|
||||||
|
"output['Workspace'] = ws.name\n",
|
||||||
|
"output['Resource Group'] = ws.resource_group\n",
|
||||||
|
"output['Location'] = ws.location\n",
|
||||||
|
"output['Run History Name'] = experiment_name\n",
|
||||||
|
"output"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Using AmlCompute\n",
|
||||||
|
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for your AutoML run. In this tutorial, you use `AmlCompute` as your training compute resource."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core.compute import ComputeTarget, AmlCompute\n",
|
||||||
|
"from azureml.core.compute_target import ComputeTargetException\n",
|
||||||
|
"\n",
|
||||||
|
"# Choose a name for your CPU cluster\n",
|
||||||
|
"# Try to ensure that the cluster name is unique across the notebooks\n",
|
||||||
|
"cpu_cluster_name = \"reg-model-proxy\"\n",
|
||||||
|
"\n",
|
||||||
|
"# Verify that cluster does not exist already\n",
|
||||||
|
"try:\n",
|
||||||
|
" compute_target = ComputeTarget(workspace=ws, name=cpu_cluster_name)\n",
|
||||||
|
" print('Found existing cluster, use it.')\n",
|
||||||
|
"except ComputeTargetException:\n",
|
||||||
|
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_DS12_V2',\n",
|
||||||
|
" max_nodes=4)\n",
|
||||||
|
" compute_target = ComputeTarget.create(ws, cpu_cluster_name, compute_config)\n",
|
||||||
|
"\n",
|
||||||
|
"compute_target.wait_for_completion(show_output=True)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Data\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Load Data\n",
|
||||||
|
"Load the hardware dataset from a csv file containing both training features and labels. The features are inputs to the model, while the training labels represent the expected output of the model. Next, we'll split the data using random_split and extract the training data for the model. "
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"data = \"https://automlsamplenotebookdata.blob.core.windows.net/automl-sample-notebook-data/machineData.csv\"\n",
|
||||||
|
"dataset = Dataset.Tabular.from_delimited_files(data)\n",
|
||||||
|
"\n",
|
||||||
|
"# Split the dataset into train and test datasets\n",
|
||||||
|
"train_data, test_data = dataset.random_split(percentage=0.8, seed=223)\n",
|
||||||
|
"\n",
|
||||||
|
"label = \"ERP\"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Train\n",
|
||||||
|
"\n",
|
||||||
|
"Instantiate an `AutoMLConfig` object to specify the settings and data used to run the experiment.\n",
|
||||||
|
"\n",
|
||||||
|
"|Property|Description|\n",
|
||||||
|
"|-|-|\n",
|
||||||
|
"|**task**|classification, regression or forecasting|\n",
|
||||||
|
"|**primary_metric**|This is the metric that you want to optimize. Regression supports the following primary metrics: <br><i>spearman_correlation</i><br><i>normalized_root_mean_squared_error</i><br><i>r2_score</i><br><i>normalized_mean_absolute_error</i>|\n",
|
||||||
|
"|**n_cross_validations**|Number of cross validation splits.|\n",
|
||||||
|
"|**training_data**|(sparse) array-like, shape = [n_samples, n_features]|\n",
|
||||||
|
"|**label_column_name**|(sparse) array-like, shape = [n_samples, ], targets values.|\n",
|
||||||
|
"\n",
|
||||||
|
"**_You can find more information about primary metrics_** [here](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-configure-auto-train#primary-metric)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {
|
||||||
|
"tags": [
|
||||||
|
"automlconfig-remarks-sample"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"automl_settings = {\n",
|
||||||
|
" \"n_cross_validations\": 3,\n",
|
||||||
|
" \"primary_metric\": 'r2_score',\n",
|
||||||
|
" \"enable_early_stopping\": True, \n",
|
||||||
|
" \"experiment_timeout_hours\": 0.3, #for real scenarios we recommend a timeout of at least one hour \n",
|
||||||
|
" \"max_concurrent_iterations\": 4,\n",
|
||||||
|
" \"max_cores_per_iteration\": -1,\n",
|
||||||
|
" \"verbosity\": logging.INFO,\n",
|
||||||
|
" \"save_mlflow\": True,\n",
|
||||||
|
"}\n",
|
||||||
|
"\n",
|
||||||
|
"automl_config = AutoMLConfig(task = 'regression',\n",
|
||||||
|
" compute_target = compute_target,\n",
|
||||||
|
" training_data = train_data,\n",
|
||||||
|
" label_column_name = label,\n",
|
||||||
|
" **automl_settings\n",
|
||||||
|
" )"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Call the `submit` method on the experiment object and pass the run configuration. Execution of remote runs is asynchronous. Depending on the data and the number of iterations this can run for a while. Validation errors and current status will be shown when setting `show_output=True` and the execution will be synchronous."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"remote_run = experiment.submit(automl_config, show_output = False)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# If you need to retrieve a run that already started, use the following code\n",
|
||||||
|
"#from azureml.train.automl.run import AutoMLRun\n",
|
||||||
|
"#remote_run = AutoMLRun(experiment = experiment, run_id = '<replace with your run id>')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"remote_run"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Results"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"remote_run.wait_for_completion(show_output=True)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Retrieve the Best Child Run\n",
|
||||||
|
"\n",
|
||||||
|
"Below we select the best pipeline from our iterations. The `get_best_child` method returns the best run. Overloads on `get_best_child` allow you to retrieve the best run for *any* logged metric."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"best_run = remote_run.get_best_child()\n",
|
||||||
|
"print(best_run)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Show hyperparameters\n",
|
||||||
|
"Show the model pipeline used for the best run with its hyperparameters."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"run_properties = json.loads(best_run.get_details()['properties']['pipeline_script'])\n",
|
||||||
|
"print(json.dumps(run_properties, indent = 1)) "
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Best Child Run Based on Any Other Metric\n",
|
||||||
|
"Show the run and the model that has the smallest `root_mean_squared_error` value (which turned out to be the same as the one with largest `spearman_correlation` value):"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"lookup_metric = \"root_mean_squared_error\"\n",
|
||||||
|
"best_run = remote_run.get_best_child(metric = lookup_metric)\n",
|
||||||
|
"print(best_run)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"y_test = test_data.keep_columns('ERP')\n",
|
||||||
|
"test_data = test_data.drop_columns('ERP')\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"y_train = train_data.keep_columns('ERP')\n",
|
||||||
|
"train_data = train_data.drop_columns('ERP')\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Creating ModelProxy for submitting prediction runs to the training environment.\n",
|
||||||
|
"We will create a ModelProxy for the best child run, which will allow us to submit a run that does the prediction in the training environment. Unlike the local client, which can have different versions of some libraries, the training environment will have all the compatible libraries for the model already."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.train.automl.model_proxy import ModelProxy\n",
|
||||||
|
"best_model_proxy = ModelProxy(best_run)\n",
|
||||||
|
"y_pred_train = best_model_proxy.predict(train_data)\n",
|
||||||
|
"y_pred_test = best_model_proxy.predict(test_data)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Exploring results"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"y_pred_train = y_pred_train.to_pandas_dataframe().values.flatten()\n",
|
||||||
|
"y_train = y_train.to_pandas_dataframe().values.flatten()\n",
|
||||||
|
"y_residual_train = y_train - y_pred_train\n",
|
||||||
|
"\n",
|
||||||
|
"y_pred_test = y_pred_test.to_pandas_dataframe().values.flatten()\n",
|
||||||
|
"y_test = y_test.to_pandas_dataframe().values.flatten()\n",
|
||||||
|
"y_residual_test = y_test - y_pred_test\n",
|
||||||
|
"print(y_residual_train)\n",
|
||||||
|
"print(y_residual_test)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"authors": [
|
||||||
|
{
|
||||||
|
"name": "sekrupa"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"categories": [
|
||||||
|
"how-to-use-azureml",
|
||||||
|
"automated-machine-learning"
|
||||||
|
],
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 3.6",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python36"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"codemirror_mode": {
|
||||||
|
"name": "ipython",
|
||||||
|
"version": 3
|
||||||
|
},
|
||||||
|
"file_extension": ".py",
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython3",
|
||||||
|
"version": "3.6.2"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 2
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
name: auto-ml-regression-model-proxy
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
|
After Width: | Height: | Size: 22 KiB |
@@ -0,0 +1,167 @@
|
|||||||
|
from typing import Any, Dict, Optional, List
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
|
||||||
|
import pandas as pd
|
||||||
|
|
||||||
|
from matplotlib import pyplot as plt
|
||||||
|
from matplotlib.backends.backend_pdf import PdfPages
|
||||||
|
|
||||||
|
from azureml.automl.core.shared import constants
|
||||||
|
from azureml.automl.core.shared.types import GrainType
|
||||||
|
from azureml.automl.runtime.shared.score import scoring
|
||||||
|
|
||||||
|
GRAIN = "time_series_id"
|
||||||
|
BACKTEST_ITER = "backtest_iteration"
|
||||||
|
ACTUALS = "actual_level"
|
||||||
|
PREDICTIONS = "predicted_level"
|
||||||
|
ALL_GRAINS = "all_sets"
|
||||||
|
|
||||||
|
FORECASTS_FILE = "forecast.csv"
|
||||||
|
SCORES_FILE = "scores.csv"
|
||||||
|
PLOTS_FILE = "plots_fcst_vs_actual.pdf"
|
||||||
|
RE_INVALID_SYMBOLS = re.compile("[: ]")
|
||||||
|
|
||||||
|
|
||||||
|
def _compute_metrics(df: pd.DataFrame, metrics: List[str]):
|
||||||
|
"""
|
||||||
|
Compute metrics for one data frame.
|
||||||
|
|
||||||
|
:param df: The data frame which contains actual_level and predicted_level columns.
|
||||||
|
:return: The data frame with two columns - metric_name and metric.
|
||||||
|
"""
|
||||||
|
scores = scoring.score_regression(
|
||||||
|
y_test=df[ACTUALS], y_pred=df[PREDICTIONS], metrics=metrics
|
||||||
|
)
|
||||||
|
metrics_df = pd.DataFrame(list(scores.items()), columns=["metric_name", "metric"])
|
||||||
|
metrics_df.sort_values(["metric_name"], inplace=True)
|
||||||
|
metrics_df.reset_index(drop=True, inplace=True)
|
||||||
|
return metrics_df
|
||||||
|
|
||||||
|
|
||||||
|
def _format_grain_name(grain: GrainType) -> str:
|
||||||
|
"""
|
||||||
|
Convert grain name to string.
|
||||||
|
|
||||||
|
:param grain: the grain name.
|
||||||
|
:return: the string representation of the given grain.
|
||||||
|
"""
|
||||||
|
if not isinstance(grain, tuple) and not isinstance(grain, list):
|
||||||
|
return str(grain)
|
||||||
|
grain = list(map(str, grain))
|
||||||
|
return "|".join(grain)
|
||||||
|
|
||||||
|
|
||||||
|
def compute_all_metrics(
|
||||||
|
fcst_df: pd.DataFrame,
|
||||||
|
ts_id_colnames: List[str],
|
||||||
|
metric_names: Optional[List[set]] = None,
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Calculate metrics per grain.
|
||||||
|
|
||||||
|
:param fcst_df: forecast data frame. Must contain 2 columns: 'actual_level' and 'predicted_level'
|
||||||
|
:param metric_names: (optional) the list of metric names to return
|
||||||
|
:param ts_id_colnames: (optional) list of grain column names
|
||||||
|
:return: dictionary of summary table for all tests and final decision on stationary vs nonstaionary
|
||||||
|
"""
|
||||||
|
if not metric_names:
|
||||||
|
metric_names = list(constants.Metric.SCALAR_REGRESSION_SET)
|
||||||
|
|
||||||
|
if ts_id_colnames is None:
|
||||||
|
ts_id_colnames = []
|
||||||
|
|
||||||
|
metrics_list = []
|
||||||
|
if ts_id_colnames:
|
||||||
|
for grain, df in fcst_df.groupby(ts_id_colnames):
|
||||||
|
one_grain_metrics_df = _compute_metrics(df, metric_names)
|
||||||
|
one_grain_metrics_df[GRAIN] = _format_grain_name(grain)
|
||||||
|
metrics_list.append(one_grain_metrics_df)
|
||||||
|
|
||||||
|
# overall metrics
|
||||||
|
one_grain_metrics_df = _compute_metrics(fcst_df, metric_names)
|
||||||
|
one_grain_metrics_df[GRAIN] = ALL_GRAINS
|
||||||
|
metrics_list.append(one_grain_metrics_df)
|
||||||
|
|
||||||
|
# collect into a data frame
|
||||||
|
return pd.concat(metrics_list)
|
||||||
|
|
||||||
|
|
||||||
|
def _draw_one_plot(
|
||||||
|
df: pd.DataFrame,
|
||||||
|
time_column_name: str,
|
||||||
|
grain_column_names: List[str],
|
||||||
|
pdf: PdfPages,
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
Draw the single plot.
|
||||||
|
|
||||||
|
:param df: The data frame with the data to build plot.
|
||||||
|
:param time_column_name: The name of a time column.
|
||||||
|
:param grain_column_names: The name of grain columns.
|
||||||
|
:param pdf: The pdf backend used to render the plot.
|
||||||
|
"""
|
||||||
|
fig, _ = plt.subplots(figsize=(20, 10))
|
||||||
|
df = df.set_index(time_column_name)
|
||||||
|
plt.plot(df[[ACTUALS, PREDICTIONS]])
|
||||||
|
plt.xticks(rotation=45)
|
||||||
|
iteration = df[BACKTEST_ITER].iloc[0]
|
||||||
|
if grain_column_names:
|
||||||
|
grain_name = [df[grain].iloc[0] for grain in grain_column_names]
|
||||||
|
plt.title(f"Time series ID: {_format_grain_name(grain_name)} {iteration}")
|
||||||
|
plt.legend(["actual", "forecast"])
|
||||||
|
plt.close(fig)
|
||||||
|
pdf.savefig(fig)
|
||||||
|
|
||||||
|
|
||||||
|
def calculate_scores_and_build_plots(
|
||||||
|
input_dir: str, output_dir: str, automl_settings: Dict[str, Any]
|
||||||
|
):
|
||||||
|
os.makedirs(output_dir, exist_ok=True)
|
||||||
|
grains = automl_settings.get(constants.TimeSeries.GRAIN_COLUMN_NAMES)
|
||||||
|
time_column_name = automl_settings.get(constants.TimeSeries.TIME_COLUMN_NAME)
|
||||||
|
if grains is None:
|
||||||
|
grains = []
|
||||||
|
if isinstance(grains, str):
|
||||||
|
grains = [grains]
|
||||||
|
while BACKTEST_ITER in grains:
|
||||||
|
grains.remove(BACKTEST_ITER)
|
||||||
|
|
||||||
|
dfs = []
|
||||||
|
for fle in os.listdir(input_dir):
|
||||||
|
file_path = os.path.join(input_dir, fle)
|
||||||
|
if os.path.isfile(file_path) and file_path.endswith(".csv"):
|
||||||
|
df_iter = pd.read_csv(file_path, parse_dates=[time_column_name])
|
||||||
|
for _, iteration in df_iter.groupby(BACKTEST_ITER):
|
||||||
|
dfs.append(iteration)
|
||||||
|
forecast_df = pd.concat(dfs, sort=False, ignore_index=True)
|
||||||
|
# To make sure plots are in order, sort the predictions by grain and iteration.
|
||||||
|
ts_index = grains + [BACKTEST_ITER]
|
||||||
|
forecast_df.sort_values(by=ts_index, inplace=True)
|
||||||
|
pdf = PdfPages(os.path.join(output_dir, PLOTS_FILE))
|
||||||
|
for _, one_forecast in forecast_df.groupby(ts_index):
|
||||||
|
_draw_one_plot(one_forecast, time_column_name, grains, pdf)
|
||||||
|
pdf.close()
|
||||||
|
forecast_df.to_csv(os.path.join(output_dir, FORECASTS_FILE), index=False)
|
||||||
|
metrics = compute_all_metrics(forecast_df, grains + [BACKTEST_ITER])
|
||||||
|
metrics.to_csv(os.path.join(output_dir, SCORES_FILE), index=False)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
args = {"forecasts": "--forecasts", "scores_out": "--output-dir"}
|
||||||
|
parser = argparse.ArgumentParser("Parsing input arguments.")
|
||||||
|
for argname, arg in args.items():
|
||||||
|
parser.add_argument(arg, dest=argname, required=True)
|
||||||
|
parsed_args, _ = parser.parse_known_args()
|
||||||
|
input_dir = parsed_args.forecasts
|
||||||
|
output_dir = parsed_args.scores_out
|
||||||
|
with open(
|
||||||
|
os.path.join(
|
||||||
|
os.path.dirname(os.path.realpath(__file__)), "automl_settings.json"
|
||||||
|
)
|
||||||
|
) as json_file:
|
||||||
|
automl_settings = json.load(json_file)
|
||||||
|
calculate_scores_and_build_plots(input_dir, output_dir, automl_settings)
|
||||||
@@ -0,0 +1,725 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
||||||
|
"\n",
|
||||||
|
"Licensed under the MIT License."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
""
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Many Models with Backtesting - Automated ML\n",
|
||||||
|
"**_Backtest many models time series forecasts with Automated Machine Learning_**\n",
|
||||||
|
"\n",
|
||||||
|
"---"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"For this notebook we are using a synthetic dataset to demonstrate the back testing in many model scenario. This allows us to check historical performance of AutoML on a historical data. To do that we step back on the backtesting period by the data set several times and split the data to train and test sets. Then these data sets are used for training and evaluation of model.<br>\n",
|
||||||
|
"\n",
|
||||||
|
"Thus, it is a quick way of evaluating AutoML as if it was in production. Here, we do not test historical performance of a particular model, for this see the [notebook](../forecasting-backtest-single-model/auto-ml-forecasting-backtest-single-model.ipynb). Instead, the best model for every backtest iteration can be different since AutoML chooses the best model for a given training set.\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"**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).**"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Prerequisites\n",
|
||||||
|
"You'll need to create a compute Instance by following the instructions in the [EnvironmentSetup.md](../Setup_Resources/EnvironmentSetup.md)."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## 1.0 Set up workspace, datastore, experiment"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {
|
||||||
|
"gather": {
|
||||||
|
"logged": 1613003526897
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"import os\n",
|
||||||
|
"\n",
|
||||||
|
"import azureml.core\n",
|
||||||
|
"from azureml.core import Workspace, Datastore\n",
|
||||||
|
"import numpy as np\n",
|
||||||
|
"import pandas as pd\n",
|
||||||
|
"\n",
|
||||||
|
"from pandas.tseries.frequencies import to_offset\n",
|
||||||
|
"\n",
|
||||||
|
"# Set up your workspace\n",
|
||||||
|
"ws = Workspace.from_config()\n",
|
||||||
|
"ws.get_details()\n",
|
||||||
|
"\n",
|
||||||
|
"# Set up your datastores\n",
|
||||||
|
"dstore = ws.get_default_datastore()\n",
|
||||||
|
"\n",
|
||||||
|
"output = {}\n",
|
||||||
|
"output[\"SDK version\"] = azureml.core.VERSION\n",
|
||||||
|
"output[\"Subscription ID\"] = ws.subscription_id\n",
|
||||||
|
"output[\"Workspace\"] = ws.name\n",
|
||||||
|
"output[\"Resource Group\"] = ws.resource_group\n",
|
||||||
|
"output[\"Location\"] = ws.location\n",
|
||||||
|
"output[\"Default datastore name\"] = dstore.name\n",
|
||||||
|
"pd.set_option(\"display.max_colwidth\", -1)\n",
|
||||||
|
"outputDf = pd.DataFrame(data=output, index=[\"\"])\n",
|
||||||
|
"outputDf.T"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"This notebook is compatible with Azure ML SDK version 1.35.1 or later."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Choose an experiment"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {
|
||||||
|
"gather": {
|
||||||
|
"logged": 1613003540729
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core import Experiment\n",
|
||||||
|
"\n",
|
||||||
|
"experiment = Experiment(ws, \"automl-many-models-backtest\")\n",
|
||||||
|
"\n",
|
||||||
|
"print(\"Experiment name: \" + experiment.name)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## 2.0 Data\n",
|
||||||
|
"\n",
|
||||||
|
"#### 2.1 Data generation\n",
|
||||||
|
"For this notebook we will generate the artificial data set with two [time series IDs](https://docs.microsoft.com/en-us/python/api/azureml-automl-core/azureml.automl.core.forecasting_parameters.forecastingparameters?view=azure-ml-py). Then we will generate backtest folds and will upload it to the default BLOB storage and create a [TabularDataset](https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.data.tabular_dataset.tabulardataset?view=azure-ml-py)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# simulate data: 2 grains - 700\n",
|
||||||
|
"TIME_COLNAME = \"date\"\n",
|
||||||
|
"TARGET_COLNAME = \"value\"\n",
|
||||||
|
"TIME_SERIES_ID_COLNAME = \"ts_id\"\n",
|
||||||
|
"\n",
|
||||||
|
"sample_size = 700\n",
|
||||||
|
"# Set the random seed for reproducibility of results.\n",
|
||||||
|
"np.random.seed(20)\n",
|
||||||
|
"X1 = pd.DataFrame(\n",
|
||||||
|
" {\n",
|
||||||
|
" TIME_COLNAME: pd.date_range(start=\"2018-01-01\", periods=sample_size),\n",
|
||||||
|
" TARGET_COLNAME: np.random.normal(loc=100, scale=20, size=sample_size),\n",
|
||||||
|
" TIME_SERIES_ID_COLNAME: \"ts_A\",\n",
|
||||||
|
" }\n",
|
||||||
|
")\n",
|
||||||
|
"X2 = pd.DataFrame(\n",
|
||||||
|
" {\n",
|
||||||
|
" TIME_COLNAME: pd.date_range(start=\"2018-01-01\", periods=sample_size),\n",
|
||||||
|
" TARGET_COLNAME: np.random.normal(loc=100, scale=20, size=sample_size),\n",
|
||||||
|
" TIME_SERIES_ID_COLNAME: \"ts_B\",\n",
|
||||||
|
" }\n",
|
||||||
|
")\n",
|
||||||
|
"\n",
|
||||||
|
"X = pd.concat([X1, X2], ignore_index=True, sort=False)\n",
|
||||||
|
"print(\"Simulated dataset contains {} rows \\n\".format(X.shape[0]))\n",
|
||||||
|
"X.head()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Now we will generate 8 backtesting folds with backtesting period of 7 days and with the same forecasting horizon. We will add the column \"backtest_iteration\", which will identify the backtesting period by the last training date."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"offset_type = \"7D\"\n",
|
||||||
|
"NUMBER_OF_BACKTESTS = 8 # number of train/test sets to generate\n",
|
||||||
|
"\n",
|
||||||
|
"dfs_train = []\n",
|
||||||
|
"dfs_test = []\n",
|
||||||
|
"for ts_id, df_one in X.groupby(TIME_SERIES_ID_COLNAME):\n",
|
||||||
|
"\n",
|
||||||
|
" data_end = df_one[TIME_COLNAME].max()\n",
|
||||||
|
"\n",
|
||||||
|
" for i in range(NUMBER_OF_BACKTESTS):\n",
|
||||||
|
" train_cutoff_date = data_end - to_offset(offset_type)\n",
|
||||||
|
" df_one = df_one.copy()\n",
|
||||||
|
" df_one[\"backtest_iteration\"] = \"iteration_\" + str(train_cutoff_date)\n",
|
||||||
|
" train = df_one[df_one[TIME_COLNAME] <= train_cutoff_date]\n",
|
||||||
|
" test = df_one[\n",
|
||||||
|
" (df_one[TIME_COLNAME] > train_cutoff_date)\n",
|
||||||
|
" & (df_one[TIME_COLNAME] <= data_end)\n",
|
||||||
|
" ]\n",
|
||||||
|
" data_end = train[TIME_COLNAME].max()\n",
|
||||||
|
" dfs_train.append(train)\n",
|
||||||
|
" dfs_test.append(test)\n",
|
||||||
|
"\n",
|
||||||
|
"X_train = pd.concat(dfs_train, sort=False, ignore_index=True)\n",
|
||||||
|
"X_test = pd.concat(dfs_test, sort=False, ignore_index=True)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### 2.2 Create the Tabular Data Set.\n",
|
||||||
|
"\n",
|
||||||
|
"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.\n",
|
||||||
|
"\n",
|
||||||
|
"Please refer to [Datastore](https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.datastore(class)?view=azure-ml-py) documentation on how to access data from Datastore.\n",
|
||||||
|
"\n",
|
||||||
|
"In this next step, we will upload the data and create a TabularDataset."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.data.dataset_factory import TabularDatasetFactory\n",
|
||||||
|
"\n",
|
||||||
|
"ds = ws.get_default_datastore()\n",
|
||||||
|
"# Upload saved data to the default data store.\n",
|
||||||
|
"train_data = TabularDatasetFactory.register_pandas_dataframe(\n",
|
||||||
|
" X_train, target=(ds, \"data_mm\"), name=\"data_train\"\n",
|
||||||
|
")\n",
|
||||||
|
"test_data = TabularDatasetFactory.register_pandas_dataframe(\n",
|
||||||
|
" X_test, target=(ds, \"data_mm\"), name=\"data_test\"\n",
|
||||||
|
")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## 3.0 Build the training pipeline\n",
|
||||||
|
"Now that the dataset, WorkSpace, and datastore are set up, we can put together a pipeline for training.\n",
|
||||||
|
"\n",
|
||||||
|
"> 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."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Choose a compute target\n",
|
||||||
|
"\n",
|
||||||
|
"You will need to create a [compute target](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-set-up-training-targets#amlcompute) for your AutoML run. In this tutorial, you create AmlCompute as your training compute resource.\n",
|
||||||
|
"\n",
|
||||||
|
"\\*\\*Creation of AmlCompute takes approximately 5 minutes.**\n",
|
||||||
|
"\n",
|
||||||
|
"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](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-manage-quotas) on the default limits and how to request more quota."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {
|
||||||
|
"gather": {
|
||||||
|
"logged": 1613007037308
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core.compute import ComputeTarget, AmlCompute\n",
|
||||||
|
"\n",
|
||||||
|
"# Name your cluster\n",
|
||||||
|
"compute_name = \"backtest-mm\"\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"if compute_name in ws.compute_targets:\n",
|
||||||
|
" compute_target = ws.compute_targets[compute_name]\n",
|
||||||
|
" if compute_target and type(compute_target) is AmlCompute:\n",
|
||||||
|
" print(\"Found compute target: \" + compute_name)\n",
|
||||||
|
"else:\n",
|
||||||
|
" print(\"Creating a new compute target...\")\n",
|
||||||
|
" provisioning_config = AmlCompute.provisioning_configuration(\n",
|
||||||
|
" vm_size=\"STANDARD_DS12_V2\", max_nodes=6\n",
|
||||||
|
" )\n",
|
||||||
|
" # Create the compute target\n",
|
||||||
|
" compute_target = ComputeTarget.create(ws, compute_name, provisioning_config)\n",
|
||||||
|
"\n",
|
||||||
|
" # Can poll for a minimum number of nodes and for a specific timeout.\n",
|
||||||
|
" # If no min node count is provided it will use the scale settings for the cluster\n",
|
||||||
|
" compute_target.wait_for_completion(\n",
|
||||||
|
" show_output=True, min_node_count=None, timeout_in_minutes=20\n",
|
||||||
|
" )\n",
|
||||||
|
"\n",
|
||||||
|
" # For a more detailed view of current cluster status, use the 'status' property\n",
|
||||||
|
" print(compute_target.status.serialize())"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Set up training parameters\n",
|
||||||
|
"\n",
|
||||||
|
"This dictionary defines the AutoML and many models settings. For this forecasting task we need to define several settings including the name of the time column, the maximum forecast horizon, and the partition column name definition. Please note, that in this case we are setting grain_column_names to be the time series ID column plus iteration, because we want to train a separate model for each time series and iteration.\n",
|
||||||
|
"\n",
|
||||||
|
"| Property | Description|\n",
|
||||||
|
"| :--------------- | :------------------- |\n",
|
||||||
|
"| **task** | forecasting |\n",
|
||||||
|
"| **primary_metric** | This is the metric that you want to optimize.<br> Forecasting supports the following primary metrics <br><i>normalized_root_mean_squared_error</i><br><i>normalized_mean_absolute_error</i> |\n",
|
||||||
|
"| **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. |\n",
|
||||||
|
"| **iterations** | Number of models to train. This is optional but provides customers with greater control on exit criteria. |\n",
|
||||||
|
"| **experiment_timeout_hours** | Maximum amount of time in hours that the experiment can take before it terminates. This is optional but provides customers with greater control on exit criteria. |\n",
|
||||||
|
"| **label_column_name** | The name of the label column. |\n",
|
||||||
|
"| **max_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. |\n",
|
||||||
|
"| **n_cross_validations** | Number of cross validation splits. Rolling Origin Validation is used to split time-series in a temporally consistent way. |\n",
|
||||||
|
"| **time_column_name** | The name of your time column. |\n",
|
||||||
|
"| **grain_column_names** | The column names used to uniquely identify timeseries in data that has multiple rows with the same timestamp. |\n",
|
||||||
|
"| **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). |\n",
|
||||||
|
"| **partition_column_names** | The names of columns used to group your models. For timeseries, the groups must not split up individual time-series. That is, each group must contain one or more whole time-series. |"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {
|
||||||
|
"gather": {
|
||||||
|
"logged": 1613007061544
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.train.automl.runtime._many_models.many_models_parameters import (\n",
|
||||||
|
" ManyModelsTrainParameters,\n",
|
||||||
|
")\n",
|
||||||
|
"\n",
|
||||||
|
"partition_column_names = [TIME_SERIES_ID_COLNAME, \"backtest_iteration\"]\n",
|
||||||
|
"automl_settings = {\n",
|
||||||
|
" \"task\": \"forecasting\",\n",
|
||||||
|
" \"primary_metric\": \"normalized_root_mean_squared_error\",\n",
|
||||||
|
" \"iteration_timeout_minutes\": 10, # This needs to be changed based on the dataset. We ask customer to explore how long training is taking before settings this value\n",
|
||||||
|
" \"iterations\": 15,\n",
|
||||||
|
" \"experiment_timeout_hours\": 0.25, # This also needs to be changed based on the dataset. For larger data set this number needs to be bigger.\n",
|
||||||
|
" \"label_column_name\": TARGET_COLNAME,\n",
|
||||||
|
" \"n_cross_validations\": 3,\n",
|
||||||
|
" \"time_column_name\": TIME_COLNAME,\n",
|
||||||
|
" \"max_horizon\": 6,\n",
|
||||||
|
" \"grain_column_names\": partition_column_names,\n",
|
||||||
|
" \"track_child_runs\": False,\n",
|
||||||
|
"}\n",
|
||||||
|
"\n",
|
||||||
|
"mm_paramters = ManyModelsTrainParameters(\n",
|
||||||
|
" automl_settings=automl_settings, partition_column_names=partition_column_names\n",
|
||||||
|
")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Set up many models pipeline"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"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.\n",
|
||||||
|
"\n",
|
||||||
|
"| Property | Description|\n",
|
||||||
|
"| :--------------- | :------------------- |\n",
|
||||||
|
"| **experiment** | The experiment used for training. |\n",
|
||||||
|
"| **train_data** | The file dataset to be used as input to the training run. |\n",
|
||||||
|
"| **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. |\n",
|
||||||
|
"| **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 or optimal performance. |\n",
|
||||||
|
"| **train_pipeline_parameters** | The set of configuration parameters defined in the previous section. |\n",
|
||||||
|
"\n",
|
||||||
|
"Calling this method will create a new aggregated dataset which is generated dynamically on pipeline execution."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.contrib.automl.pipeline.steps import AutoMLPipelineBuilder\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"training_pipeline_steps = AutoMLPipelineBuilder.get_many_models_train_steps(\n",
|
||||||
|
" experiment=experiment,\n",
|
||||||
|
" train_data=train_data,\n",
|
||||||
|
" compute_target=compute_target,\n",
|
||||||
|
" node_count=2,\n",
|
||||||
|
" process_count_per_node=2,\n",
|
||||||
|
" run_invocation_timeout=920,\n",
|
||||||
|
" train_pipeline_parameters=mm_paramters,\n",
|
||||||
|
")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.pipeline.core import Pipeline\n",
|
||||||
|
"\n",
|
||||||
|
"training_pipeline = Pipeline(ws, steps=training_pipeline_steps)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Submit the pipeline to run\n",
|
||||||
|
"Next we submit our pipeline to run. The whole training pipeline takes about 20 minutes using a STANDARD_DS12_V2 VM with our current ParallelRunConfig setting."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"training_run = experiment.submit(training_pipeline)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"training_run.wait_for_completion(show_output=False)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Check the run status, if training_run is in completed state, continue to next section. Otherwise, check the portal for failures."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## 4.0 Backtesting\n",
|
||||||
|
"Now that we selected the best AutoML model for each backtest fold, we will use these models to generate the forecasts and compare with the actuals."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Set up output dataset for inference data\n",
|
||||||
|
"Output of inference can be represented as [OutputFileDatasetConfig](https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.data.output_dataset_config.outputdatasetconfig?view=azure-ml-py) object and OutputFileDatasetConfig can be registered as a dataset. "
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.data import OutputFileDatasetConfig\n",
|
||||||
|
"\n",
|
||||||
|
"output_inference_data_ds = OutputFileDatasetConfig(\n",
|
||||||
|
" name=\"many_models_inference_output\",\n",
|
||||||
|
" destination=(dstore, \"backtesting/inference_data/\"),\n",
|
||||||
|
").register_on_complete(name=\"backtesting_data_ds\")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"For many models we need to provide the ManyModelsInferenceParameters object.\n",
|
||||||
|
"\n",
|
||||||
|
"#### ManyModelsInferenceParameters arguments\n",
|
||||||
|
"| Property | Description|\n",
|
||||||
|
"| :--------------- | :------------------- |\n",
|
||||||
|
"| **partition_column_names** | List of column names that identifies groups. |\n",
|
||||||
|
"| **target_column_name** | \\[Optional\\] Column name only if the inference dataset has the target. |\n",
|
||||||
|
"| **time_column_name** | Column name only if it is timeseries. |\n",
|
||||||
|
"| **many_models_run_id** | \\[Optional\\] Many models pipeline run id where models were trained. |\n",
|
||||||
|
"\n",
|
||||||
|
"#### get_many_models_batch_inference_steps arguments\n",
|
||||||
|
"| Property | Description|\n",
|
||||||
|
"| :--------------- | :------------------- |\n",
|
||||||
|
"| **experiment** | The experiment used for inference run. |\n",
|
||||||
|
"| **inference_data** | The data to use for inferencing. It should be the same schema as used for training.\n",
|
||||||
|
"| **compute_target** | The compute target that runs the inference pipeline.|\n",
|
||||||
|
"| **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). |\n",
|
||||||
|
"| **process_count_per_node** | The number of processes per node.\n",
|
||||||
|
"| **train_run_id** | \\[Optional\\] The run id of the hierarchy training, by default it is the latest successful training many model run in the experiment. |\n",
|
||||||
|
"| **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. |\n",
|
||||||
|
"| **process_count_per_node** | \\[Optional\\] The number of processes per node, by default it's 4. |"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.contrib.automl.pipeline.steps import AutoMLPipelineBuilder\n",
|
||||||
|
"from azureml.train.automl.runtime._many_models.many_models_parameters import (\n",
|
||||||
|
" ManyModelsInferenceParameters,\n",
|
||||||
|
")\n",
|
||||||
|
"\n",
|
||||||
|
"mm_parameters = ManyModelsInferenceParameters(\n",
|
||||||
|
" partition_column_names=partition_column_names,\n",
|
||||||
|
" time_column_name=TIME_COLNAME,\n",
|
||||||
|
" target_column_name=TARGET_COLNAME,\n",
|
||||||
|
")\n",
|
||||||
|
"\n",
|
||||||
|
"inference_steps = AutoMLPipelineBuilder.get_many_models_batch_inference_steps(\n",
|
||||||
|
" experiment=experiment,\n",
|
||||||
|
" inference_data=test_data,\n",
|
||||||
|
" node_count=2,\n",
|
||||||
|
" process_count_per_node=2,\n",
|
||||||
|
" compute_target=compute_target,\n",
|
||||||
|
" run_invocation_timeout=300,\n",
|
||||||
|
" output_datastore=output_inference_data_ds,\n",
|
||||||
|
" train_run_id=training_run.id,\n",
|
||||||
|
" train_experiment_name=training_run.experiment.name,\n",
|
||||||
|
" inference_pipeline_parameters=mm_parameters,\n",
|
||||||
|
")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.pipeline.core import Pipeline\n",
|
||||||
|
"\n",
|
||||||
|
"inference_pipeline = Pipeline(ws, steps=inference_steps)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"inference_run = experiment.submit(inference_pipeline)\n",
|
||||||
|
"inference_run.wait_for_completion(show_output=False)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## 5.0 Retrieve results and calculate metrics\n",
|
||||||
|
"\n",
|
||||||
|
"The pipeline returns one file with the predictions for each times series ID and outputs the result to the forecasting_output Blob container. The details of the blob container is listed in 'forecasting_output.txt' under Outputs+logs. \n",
|
||||||
|
"\n",
|
||||||
|
"The next code snippet does the following:\n",
|
||||||
|
"1. Downloads the contents of the output folder that is passed in the parallel run step \n",
|
||||||
|
"2. Reads the parallel_run_step.txt file that has the predictions as pandas dataframe \n",
|
||||||
|
"3. Saves the table in csv format and \n",
|
||||||
|
"4. Displays the top 10 rows of the predictions"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.contrib.automl.pipeline.steps.utilities import get_output_from_mm_pipeline\n",
|
||||||
|
"\n",
|
||||||
|
"forecasting_results_name = \"forecasting_results\"\n",
|
||||||
|
"forecasting_output_name = \"many_models_inference_output\"\n",
|
||||||
|
"forecast_file = get_output_from_mm_pipeline(\n",
|
||||||
|
" inference_run, forecasting_results_name, forecasting_output_name\n",
|
||||||
|
")\n",
|
||||||
|
"df = pd.read_csv(forecast_file, delimiter=\" \", header=None, parse_dates=[0])\n",
|
||||||
|
"df.columns = list(X_train.columns) + [\"predicted_level\"]\n",
|
||||||
|
"print(\n",
|
||||||
|
" \"Prediction has \", df.shape[0], \" rows. Here the first 10 rows are being displayed.\"\n",
|
||||||
|
")\n",
|
||||||
|
"# Save the scv file with header to read it in the next step.\n",
|
||||||
|
"df.rename(columns={TARGET_COLNAME: \"actual_level\"}, inplace=True)\n",
|
||||||
|
"df.to_csv(os.path.join(forecasting_results_name, \"forecast.csv\"), index=False)\n",
|
||||||
|
"df.head(10)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## View metrics\n",
|
||||||
|
"We will read in the obtained results and run the helper script, which will generate metrics and create the plots of predicted versus actual values."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from assets.score import calculate_scores_and_build_plots\n",
|
||||||
|
"\n",
|
||||||
|
"backtesting_results = \"backtesting_mm_results\"\n",
|
||||||
|
"os.makedirs(backtesting_results, exist_ok=True)\n",
|
||||||
|
"calculate_scores_and_build_plots(\n",
|
||||||
|
" forecasting_results_name, backtesting_results, automl_settings\n",
|
||||||
|
")\n",
|
||||||
|
"pd.DataFrame({\"File\": os.listdir(backtesting_results)})"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"The directory contains a set of files with results:\n",
|
||||||
|
"- forecast.csv contains forecasts for all backtest iterations. The backtest_iteration column contains iteration identifier with the last training date as a suffix\n",
|
||||||
|
"- scores.csv contains all metrics. If data set contains several time series, the metrics are given for all combinations of time series id and iterations, as well as scores for all iterations and time series ids, which are marked as \"all_sets\"\n",
|
||||||
|
"- plots_fcst_vs_actual.pdf contains the predictions vs forecast plots for each iteration and, eash time series is saved as separate plot.\n",
|
||||||
|
"\n",
|
||||||
|
"For demonstration purposes we will display the table of metrics for one of the time series with ID \"ts0\". We will create the utility function, which will build the table with metrics."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"def get_metrics_for_ts(all_metrics, ts):\n",
|
||||||
|
" \"\"\"\n",
|
||||||
|
" Get the metrics for the time series with ID ts and return it as pandas data frame.\n",
|
||||||
|
"\n",
|
||||||
|
" :param all_metrics: The table with all the metrics.\n",
|
||||||
|
" :param ts: The ID of a time series of interest.\n",
|
||||||
|
" :return: The pandas DataFrame with metrics for one time series.\n",
|
||||||
|
" \"\"\"\n",
|
||||||
|
" results_df = None\n",
|
||||||
|
" for ts_id, one_series in all_metrics.groupby(\"time_series_id\"):\n",
|
||||||
|
" if not ts_id.startswith(ts):\n",
|
||||||
|
" continue\n",
|
||||||
|
" iteration = ts_id.split(\"|\")[-1]\n",
|
||||||
|
" df = one_series[[\"metric_name\", \"metric\"]]\n",
|
||||||
|
" df.rename({\"metric\": iteration}, axis=1, inplace=True)\n",
|
||||||
|
" df.set_index(\"metric_name\", inplace=True)\n",
|
||||||
|
" if results_df is None:\n",
|
||||||
|
" results_df = df\n",
|
||||||
|
" else:\n",
|
||||||
|
" results_df = results_df.merge(\n",
|
||||||
|
" df, how=\"inner\", left_index=True, right_index=True\n",
|
||||||
|
" )\n",
|
||||||
|
" results_df.sort_index(axis=1, inplace=True)\n",
|
||||||
|
" return results_df\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"metrics_df = pd.read_csv(os.path.join(backtesting_results, \"scores.csv\"))\n",
|
||||||
|
"ts = \"ts_A\"\n",
|
||||||
|
"get_metrics_for_ts(metrics_df, ts)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Forecast vs actuals plots."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from IPython.display import IFrame\n",
|
||||||
|
"\n",
|
||||||
|
"IFrame(\"./backtesting_mm_results/plots_fcst_vs_actual.pdf\", width=800, height=300)"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"authors": [
|
||||||
|
{
|
||||||
|
"name": "jialiu"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"categories": [
|
||||||
|
"how-to-use-azureml",
|
||||||
|
"automated-machine-learning"
|
||||||
|
],
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 3.6",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python36"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"codemirror_mode": {
|
||||||
|
"name": "ipython",
|
||||||
|
"version": 3
|
||||||
|
},
|
||||||
|
"file_extension": ".py",
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython3",
|
||||||
|
"version": "3.6.9"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 4
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
name: auto-ml-forecasting-backtest-many-models
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
|
After Width: | Height: | Size: 22 KiB |
@@ -0,0 +1,45 @@
|
|||||||
|
import argparse
|
||||||
|
import os
|
||||||
|
|
||||||
|
import pandas as pd
|
||||||
|
|
||||||
|
import azureml.train.automl.runtime._hts.hts_runtime_utilities as hru
|
||||||
|
|
||||||
|
from azureml.core import Run
|
||||||
|
from azureml.core.dataset import Dataset
|
||||||
|
|
||||||
|
# Parse the arguments.
|
||||||
|
args = {
|
||||||
|
"step_size": "--step-size",
|
||||||
|
"step_number": "--step-number",
|
||||||
|
"time_column_name": "--time-column-name",
|
||||||
|
"time_series_id_column_names": "--time-series-id-column-names",
|
||||||
|
"out_dir": "--output-dir",
|
||||||
|
}
|
||||||
|
parser = argparse.ArgumentParser("Parsing input arguments.")
|
||||||
|
for argname, arg in args.items():
|
||||||
|
parser.add_argument(arg, dest=argname, required=True)
|
||||||
|
parsed_args, _ = parser.parse_known_args()
|
||||||
|
step_number = int(parsed_args.step_number)
|
||||||
|
step_size = int(parsed_args.step_size)
|
||||||
|
# Create the working dirrectory to store the temporary csv files.
|
||||||
|
working_dir = parsed_args.out_dir
|
||||||
|
os.makedirs(working_dir, exist_ok=True)
|
||||||
|
# Set input and output
|
||||||
|
script_run = Run.get_context()
|
||||||
|
input_dataset = script_run.input_datasets["training_data"]
|
||||||
|
X_train = input_dataset.to_pandas_dataframe()
|
||||||
|
# Split the data.
|
||||||
|
for i in range(step_number):
|
||||||
|
file_name = os.path.join(working_dir, "backtest_{}.csv".format(i))
|
||||||
|
if parsed_args.time_series_id_column_names:
|
||||||
|
dfs = []
|
||||||
|
for _, one_series in X_train.groupby([parsed_args.time_series_id_column_names]):
|
||||||
|
one_series = one_series.sort_values(
|
||||||
|
by=[parsed_args.time_column_name], inplace=False
|
||||||
|
)
|
||||||
|
dfs.append(one_series.iloc[: len(one_series) - step_size * i])
|
||||||
|
pd.concat(dfs, sort=False, ignore_index=True).to_csv(file_name, index=False)
|
||||||
|
else:
|
||||||
|
X_train.sort_values(by=[parsed_args.time_column_name], inplace=True)
|
||||||
|
X_train.iloc[: len(X_train) - step_size * i].to_csv(file_name, index=False)
|
||||||
@@ -0,0 +1,173 @@
|
|||||||
|
# ---------------------------------------------------------
|
||||||
|
# Copyright (c) Microsoft Corporation. All rights reserved.
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
"""The batch script needed for back testing of models using PRS."""
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import pickle
|
||||||
|
import re
|
||||||
|
|
||||||
|
import pandas as pd
|
||||||
|
|
||||||
|
from azureml.core.experiment import Experiment
|
||||||
|
from azureml.core.model import Model
|
||||||
|
from azureml.core.run import Run
|
||||||
|
from azureml.automl.core.shared import constants
|
||||||
|
from azureml.automl.runtime.shared.score import scoring
|
||||||
|
from azureml.train.automl import AutoMLConfig
|
||||||
|
|
||||||
|
RE_INVALID_SYMBOLS = re.compile(r"[:\s]")
|
||||||
|
|
||||||
|
model_name = None
|
||||||
|
target_column_name = None
|
||||||
|
current_step_run = None
|
||||||
|
output_dir = None
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def _get_automl_settings():
|
||||||
|
with open(
|
||||||
|
os.path.join(
|
||||||
|
os.path.dirname(os.path.realpath(__file__)), "automl_settings.json"
|
||||||
|
)
|
||||||
|
) as json_file:
|
||||||
|
return json.load(json_file)
|
||||||
|
|
||||||
|
|
||||||
|
def init():
|
||||||
|
global model_name
|
||||||
|
global target_column_name
|
||||||
|
global output_dir
|
||||||
|
global automl_settings
|
||||||
|
global model_uid
|
||||||
|
logger.info("Initialization of the run.")
|
||||||
|
parser = argparse.ArgumentParser("Parsing input arguments.")
|
||||||
|
parser.add_argument("--output-dir", dest="out", required=True)
|
||||||
|
parser.add_argument("--model-name", dest="model", default=None)
|
||||||
|
parser.add_argument("--model-uid", dest="model_uid", default=None)
|
||||||
|
|
||||||
|
parsed_args, _ = parser.parse_known_args()
|
||||||
|
model_name = parsed_args.model
|
||||||
|
automl_settings = _get_automl_settings()
|
||||||
|
target_column_name = automl_settings.get("label_column_name")
|
||||||
|
output_dir = parsed_args.out
|
||||||
|
model_uid = parsed_args.model_uid
|
||||||
|
os.makedirs(output_dir, exist_ok=True)
|
||||||
|
os.environ["AUTOML_IGNORE_PACKAGE_VERSION_INCOMPATIBILITIES".lower()] = "True"
|
||||||
|
|
||||||
|
|
||||||
|
def get_run():
|
||||||
|
global current_step_run
|
||||||
|
if current_step_run is None:
|
||||||
|
current_step_run = Run.get_context()
|
||||||
|
return current_step_run
|
||||||
|
|
||||||
|
|
||||||
|
def run_backtest(data_input_name: str, file_name: str, experiment: Experiment):
|
||||||
|
"""Re-train the model and return metrics."""
|
||||||
|
data_input = pd.read_csv(
|
||||||
|
data_input_name,
|
||||||
|
parse_dates=[automl_settings[constants.TimeSeries.TIME_COLUMN_NAME]],
|
||||||
|
)
|
||||||
|
print(data_input.head())
|
||||||
|
if not automl_settings.get(constants.TimeSeries.GRAIN_COLUMN_NAMES):
|
||||||
|
# There is no grains.
|
||||||
|
data_input.sort_values(
|
||||||
|
[automl_settings[constants.TimeSeries.TIME_COLUMN_NAME]], inplace=True
|
||||||
|
)
|
||||||
|
X_train = data_input.iloc[: -automl_settings["max_horizon"]]
|
||||||
|
y_train = X_train.pop(target_column_name).values
|
||||||
|
X_test = data_input.iloc[-automl_settings["max_horizon"] :]
|
||||||
|
y_test = X_test.pop(target_column_name).values
|
||||||
|
else:
|
||||||
|
# The data contain grains.
|
||||||
|
dfs_train = []
|
||||||
|
dfs_test = []
|
||||||
|
for _, one_series in data_input.groupby(
|
||||||
|
automl_settings.get(constants.TimeSeries.GRAIN_COLUMN_NAMES)
|
||||||
|
):
|
||||||
|
one_series.sort_values(
|
||||||
|
[automl_settings[constants.TimeSeries.TIME_COLUMN_NAME]], inplace=True
|
||||||
|
)
|
||||||
|
dfs_train.append(one_series.iloc[: -automl_settings["max_horizon"]])
|
||||||
|
dfs_test.append(one_series.iloc[-automl_settings["max_horizon"] :])
|
||||||
|
X_train = pd.concat(dfs_train, sort=False, ignore_index=True)
|
||||||
|
y_train = X_train.pop(target_column_name).values
|
||||||
|
X_test = pd.concat(dfs_test, sort=False, ignore_index=True)
|
||||||
|
y_test = X_test.pop(target_column_name).values
|
||||||
|
|
||||||
|
last_training_date = str(
|
||||||
|
X_train[automl_settings[constants.TimeSeries.TIME_COLUMN_NAME]].max()
|
||||||
|
)
|
||||||
|
|
||||||
|
if file_name:
|
||||||
|
# If file name is provided, we will load model and retrain it on backtest data.
|
||||||
|
with open(file_name, "rb") as fp:
|
||||||
|
fitted_model = pickle.load(fp)
|
||||||
|
fitted_model.fit(X_train, y_train)
|
||||||
|
else:
|
||||||
|
# We will run the experiment and select the best model.
|
||||||
|
X_train[target_column_name] = y_train
|
||||||
|
automl_config = AutoMLConfig(training_data=X_train, **automl_settings)
|
||||||
|
automl_run = current_step_run.submit_child(automl_config, show_output=True)
|
||||||
|
best_run, fitted_model = automl_run.get_output()
|
||||||
|
# As we have generated models, we need to register them for the future use.
|
||||||
|
description = "Backtest model example"
|
||||||
|
tags = {"last_training_date": last_training_date, "experiment": experiment.name}
|
||||||
|
if model_uid:
|
||||||
|
tags["model_uid"] = model_uid
|
||||||
|
automl_run.register_model(
|
||||||
|
model_name=best_run.properties["model_name"],
|
||||||
|
description=description,
|
||||||
|
tags=tags,
|
||||||
|
)
|
||||||
|
print(f"The model {best_run.properties['model_name']} was registered.")
|
||||||
|
|
||||||
|
_, x_pred = fitted_model.forecast(X_test)
|
||||||
|
x_pred.reset_index(inplace=True, drop=False)
|
||||||
|
columns = [automl_settings[constants.TimeSeries.TIME_COLUMN_NAME]]
|
||||||
|
if automl_settings.get(constants.TimeSeries.GRAIN_COLUMN_NAMES):
|
||||||
|
# We know that fitted_model.grain_column_names is a list.
|
||||||
|
columns.extend(fitted_model.grain_column_names)
|
||||||
|
columns.append(constants.TimeSeriesInternal.DUMMY_TARGET_COLUMN)
|
||||||
|
# Remove featurized columns.
|
||||||
|
x_pred = x_pred[columns]
|
||||||
|
x_pred.rename(
|
||||||
|
{constants.TimeSeriesInternal.DUMMY_TARGET_COLUMN: "predicted_level"},
|
||||||
|
axis=1,
|
||||||
|
inplace=True,
|
||||||
|
)
|
||||||
|
x_pred["actual_level"] = y_test
|
||||||
|
x_pred["backtest_iteration"] = f"iteration_{last_training_date}"
|
||||||
|
date_safe = RE_INVALID_SYMBOLS.sub("_", last_training_date)
|
||||||
|
x_pred.to_csv(os.path.join(output_dir, f"iteration_{date_safe}.csv"), index=False)
|
||||||
|
return x_pred
|
||||||
|
|
||||||
|
|
||||||
|
def run(input_files):
|
||||||
|
"""Run the script"""
|
||||||
|
logger.info("Running mini batch.")
|
||||||
|
ws = get_run().experiment.workspace
|
||||||
|
file_name = None
|
||||||
|
if model_name:
|
||||||
|
models = Model.list(ws, name=model_name)
|
||||||
|
cloud_model = None
|
||||||
|
if models:
|
||||||
|
for one_mod in models:
|
||||||
|
if cloud_model is None or one_mod.version > cloud_model.version:
|
||||||
|
logger.info(
|
||||||
|
"Using existing model from the workspace. Model version: {}".format(
|
||||||
|
one_mod.version
|
||||||
|
)
|
||||||
|
)
|
||||||
|
cloud_model = one_mod
|
||||||
|
file_name = cloud_model.download(exist_ok=True)
|
||||||
|
|
||||||
|
forecasts = []
|
||||||
|
logger.info("Running backtest.")
|
||||||
|
for input_file in input_files:
|
||||||
|
forecasts.append(run_backtest(input_file, file_name, get_run().experiment))
|
||||||
|
return pd.concat(forecasts)
|
||||||
@@ -0,0 +1,167 @@
|
|||||||
|
from typing import Any, Dict, Optional, List
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
|
||||||
|
import pandas as pd
|
||||||
|
|
||||||
|
from matplotlib import pyplot as plt
|
||||||
|
from matplotlib.backends.backend_pdf import PdfPages
|
||||||
|
|
||||||
|
from azureml.automl.core.shared import constants
|
||||||
|
from azureml.automl.core.shared.types import GrainType
|
||||||
|
from azureml.automl.runtime.shared.score import scoring
|
||||||
|
|
||||||
|
GRAIN = "time_series_id"
|
||||||
|
BACKTEST_ITER = "backtest_iteration"
|
||||||
|
ACTUALS = "actual_level"
|
||||||
|
PREDICTIONS = "predicted_level"
|
||||||
|
ALL_GRAINS = "all_sets"
|
||||||
|
|
||||||
|
FORECASTS_FILE = "forecast.csv"
|
||||||
|
SCORES_FILE = "scores.csv"
|
||||||
|
PLOTS_FILE = "plots_fcst_vs_actual.pdf"
|
||||||
|
RE_INVALID_SYMBOLS = re.compile("[: ]")
|
||||||
|
|
||||||
|
|
||||||
|
def _compute_metrics(df: pd.DataFrame, metrics: List[str]):
|
||||||
|
"""
|
||||||
|
Compute metrics for one data frame.
|
||||||
|
|
||||||
|
:param df: The data frame which contains actual_level and predicted_level columns.
|
||||||
|
:return: The data frame with two columns - metric_name and metric.
|
||||||
|
"""
|
||||||
|
scores = scoring.score_regression(
|
||||||
|
y_test=df[ACTUALS], y_pred=df[PREDICTIONS], metrics=metrics
|
||||||
|
)
|
||||||
|
metrics_df = pd.DataFrame(list(scores.items()), columns=["metric_name", "metric"])
|
||||||
|
metrics_df.sort_values(["metric_name"], inplace=True)
|
||||||
|
metrics_df.reset_index(drop=True, inplace=True)
|
||||||
|
return metrics_df
|
||||||
|
|
||||||
|
|
||||||
|
def _format_grain_name(grain: GrainType) -> str:
|
||||||
|
"""
|
||||||
|
Convert grain name to string.
|
||||||
|
|
||||||
|
:param grain: the grain name.
|
||||||
|
:return: the string representation of the given grain.
|
||||||
|
"""
|
||||||
|
if not isinstance(grain, tuple) and not isinstance(grain, list):
|
||||||
|
return str(grain)
|
||||||
|
grain = list(map(str, grain))
|
||||||
|
return "|".join(grain)
|
||||||
|
|
||||||
|
|
||||||
|
def compute_all_metrics(
|
||||||
|
fcst_df: pd.DataFrame,
|
||||||
|
ts_id_colnames: List[str],
|
||||||
|
metric_names: Optional[List[set]] = None,
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Calculate metrics per grain.
|
||||||
|
|
||||||
|
:param fcst_df: forecast data frame. Must contain 2 columns: 'actual_level' and 'predicted_level'
|
||||||
|
:param metric_names: (optional) the list of metric names to return
|
||||||
|
:param ts_id_colnames: (optional) list of grain column names
|
||||||
|
:return: dictionary of summary table for all tests and final decision on stationary vs nonstaionary
|
||||||
|
"""
|
||||||
|
if not metric_names:
|
||||||
|
metric_names = list(constants.Metric.SCALAR_REGRESSION_SET)
|
||||||
|
|
||||||
|
if ts_id_colnames is None:
|
||||||
|
ts_id_colnames = []
|
||||||
|
|
||||||
|
metrics_list = []
|
||||||
|
if ts_id_colnames:
|
||||||
|
for grain, df in fcst_df.groupby(ts_id_colnames):
|
||||||
|
one_grain_metrics_df = _compute_metrics(df, metric_names)
|
||||||
|
one_grain_metrics_df[GRAIN] = _format_grain_name(grain)
|
||||||
|
metrics_list.append(one_grain_metrics_df)
|
||||||
|
|
||||||
|
# overall metrics
|
||||||
|
one_grain_metrics_df = _compute_metrics(fcst_df, metric_names)
|
||||||
|
one_grain_metrics_df[GRAIN] = ALL_GRAINS
|
||||||
|
metrics_list.append(one_grain_metrics_df)
|
||||||
|
|
||||||
|
# collect into a data frame
|
||||||
|
return pd.concat(metrics_list)
|
||||||
|
|
||||||
|
|
||||||
|
def _draw_one_plot(
|
||||||
|
df: pd.DataFrame,
|
||||||
|
time_column_name: str,
|
||||||
|
grain_column_names: List[str],
|
||||||
|
pdf: PdfPages,
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
Draw the single plot.
|
||||||
|
|
||||||
|
:param df: The data frame with the data to build plot.
|
||||||
|
:param time_column_name: The name of a time column.
|
||||||
|
:param grain_column_names: The name of grain columns.
|
||||||
|
:param pdf: The pdf backend used to render the plot.
|
||||||
|
"""
|
||||||
|
fig, _ = plt.subplots(figsize=(20, 10))
|
||||||
|
df = df.set_index(time_column_name)
|
||||||
|
plt.plot(df[[ACTUALS, PREDICTIONS]])
|
||||||
|
plt.xticks(rotation=45)
|
||||||
|
iteration = df[BACKTEST_ITER].iloc[0]
|
||||||
|
if grain_column_names:
|
||||||
|
grain_name = [df[grain].iloc[0] for grain in grain_column_names]
|
||||||
|
plt.title(f"Time series ID: {_format_grain_name(grain_name)} {iteration}")
|
||||||
|
plt.legend(["actual", "forecast"])
|
||||||
|
plt.close(fig)
|
||||||
|
pdf.savefig(fig)
|
||||||
|
|
||||||
|
|
||||||
|
def calculate_scores_and_build_plots(
|
||||||
|
input_dir: str, output_dir: str, automl_settings: Dict[str, Any]
|
||||||
|
):
|
||||||
|
os.makedirs(output_dir, exist_ok=True)
|
||||||
|
grains = automl_settings.get(constants.TimeSeries.GRAIN_COLUMN_NAMES)
|
||||||
|
time_column_name = automl_settings.get(constants.TimeSeries.TIME_COLUMN_NAME)
|
||||||
|
if grains is None:
|
||||||
|
grains = []
|
||||||
|
if isinstance(grains, str):
|
||||||
|
grains = [grains]
|
||||||
|
while BACKTEST_ITER in grains:
|
||||||
|
grains.remove(BACKTEST_ITER)
|
||||||
|
|
||||||
|
dfs = []
|
||||||
|
for fle in os.listdir(input_dir):
|
||||||
|
file_path = os.path.join(input_dir, fle)
|
||||||
|
if os.path.isfile(file_path) and file_path.endswith(".csv"):
|
||||||
|
df_iter = pd.read_csv(file_path, parse_dates=[time_column_name])
|
||||||
|
for _, iteration in df_iter.groupby(BACKTEST_ITER):
|
||||||
|
dfs.append(iteration)
|
||||||
|
forecast_df = pd.concat(dfs, sort=False, ignore_index=True)
|
||||||
|
# To make sure plots are in order, sort the predictions by grain and iteration.
|
||||||
|
ts_index = grains + [BACKTEST_ITER]
|
||||||
|
forecast_df.sort_values(by=ts_index, inplace=True)
|
||||||
|
pdf = PdfPages(os.path.join(output_dir, PLOTS_FILE))
|
||||||
|
for _, one_forecast in forecast_df.groupby(ts_index):
|
||||||
|
_draw_one_plot(one_forecast, time_column_name, grains, pdf)
|
||||||
|
pdf.close()
|
||||||
|
forecast_df.to_csv(os.path.join(output_dir, FORECASTS_FILE), index=False)
|
||||||
|
metrics = compute_all_metrics(forecast_df, grains + [BACKTEST_ITER])
|
||||||
|
metrics.to_csv(os.path.join(output_dir, SCORES_FILE), index=False)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
args = {"forecasts": "--forecasts", "scores_out": "--output-dir"}
|
||||||
|
parser = argparse.ArgumentParser("Parsing input arguments.")
|
||||||
|
for argname, arg in args.items():
|
||||||
|
parser.add_argument(arg, dest=argname, required=True)
|
||||||
|
parsed_args, _ = parser.parse_known_args()
|
||||||
|
input_dir = parsed_args.forecasts
|
||||||
|
output_dir = parsed_args.scores_out
|
||||||
|
with open(
|
||||||
|
os.path.join(
|
||||||
|
os.path.dirname(os.path.realpath(__file__)), "automl_settings.json"
|
||||||
|
)
|
||||||
|
) as json_file:
|
||||||
|
automl_settings = json.load(json_file)
|
||||||
|
calculate_scores_and_build_plots(input_dir, output_dir, automl_settings)
|
||||||
@@ -0,0 +1,719 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
||||||
|
"\n",
|
||||||
|
"Licensed under the MIT License.\n",
|
||||||
|
""
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Automated MachineLearning\n",
|
||||||
|
"_**The model backtesting**_\n",
|
||||||
|
"\n",
|
||||||
|
"## Contents\n",
|
||||||
|
"1. [Introduction](#Introduction)\n",
|
||||||
|
"2. [Setup](#Setup)\n",
|
||||||
|
"3. [Data](#Data)\n",
|
||||||
|
"4. [Prepare remote compute and data.](#prepare_remote)\n",
|
||||||
|
"5. [Create the configuration for AutoML backtesting](#train)\n",
|
||||||
|
"6. [Backtest AutoML](#backtest_automl)\n",
|
||||||
|
"7. [View metrics](#Metrics)\n",
|
||||||
|
"8. [Backtest the best model](#backtest_model)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Introduction\n",
|
||||||
|
"Model backtesting is used to evaluate its performance on historical data. To do that we step back on the backtesting period by the data set several times and split the data to train and test sets. Then these data sets are used for training and evaluation of model.<br>\n",
|
||||||
|
"This notebook is intended to demonstrate backtesting on a single model, this is the best solution for small data sets with a few or one time series in it. For scenarios where we would like to choose the best AutoML model for every backtest iteration, please see [AutoML Forecasting Backtest Many Models Example](../forecasting-backtest-many-models/auto-ml-forecasting-backtest-many-models.ipynb) notebook.\n",
|
||||||
|
"\n",
|
||||||
|
"This notebook demonstrates two ways of backtesting:\n",
|
||||||
|
"- AutoML backtesting: we will train separate AutoML models for historical data\n",
|
||||||
|
"- Model backtesting: from the first run we will select the best model trained on the most recent data, retrain it on the past data and evaluate."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Setup"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"import os\n",
|
||||||
|
"import numpy as np\n",
|
||||||
|
"import pandas as pd\n",
|
||||||
|
"import shutil\n",
|
||||||
|
"\n",
|
||||||
|
"import azureml.core\n",
|
||||||
|
"from azureml.core import Experiment, Model, Workspace"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"This notebook is compatible with Azure ML SDK version 1.35.1 or later."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"As part of the setup you have already created a <b>Workspace</b>."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"ws = Workspace.from_config()\n",
|
||||||
|
"\n",
|
||||||
|
"output = {}\n",
|
||||||
|
"output[\"Subscription ID\"] = ws.subscription_id\n",
|
||||||
|
"output[\"Workspace\"] = ws.name\n",
|
||||||
|
"output[\"SKU\"] = ws.sku\n",
|
||||||
|
"output[\"Resource Group\"] = ws.resource_group\n",
|
||||||
|
"output[\"Location\"] = ws.location\n",
|
||||||
|
"pd.set_option(\"display.max_colwidth\", -1)\n",
|
||||||
|
"outputDf = pd.DataFrame(data=output, index=[\"\"])\n",
|
||||||
|
"outputDf.T"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Data\n",
|
||||||
|
"For the demonstration purposes we will simulate one year of daily data. To do this we need to specify the following parameters: time column name, time series ID column names and label column name. Our intention is to forecast for two weeks ahead."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"TIME_COLUMN_NAME = \"date\"\n",
|
||||||
|
"TIME_SERIES_ID_COLUMN_NAMES = \"time_series_id\"\n",
|
||||||
|
"LABEL_COLUMN_NAME = \"y\"\n",
|
||||||
|
"FORECAST_HORIZON = 14\n",
|
||||||
|
"FREQUENCY = \"D\"\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"def simulate_timeseries_data(\n",
|
||||||
|
" train_len: int,\n",
|
||||||
|
" test_len: int,\n",
|
||||||
|
" time_column_name: str,\n",
|
||||||
|
" target_column_name: str,\n",
|
||||||
|
" time_series_id_column_name: str,\n",
|
||||||
|
" time_series_number: int = 1,\n",
|
||||||
|
" freq: str = \"H\",\n",
|
||||||
|
"):\n",
|
||||||
|
" \"\"\"\n",
|
||||||
|
" Return the time series of designed length.\n",
|
||||||
|
"\n",
|
||||||
|
" :param train_len: The length of training data (one series).\n",
|
||||||
|
" :type train_len: int\n",
|
||||||
|
" :param test_len: The length of testing data (one series).\n",
|
||||||
|
" :type test_len: int\n",
|
||||||
|
" :param time_column_name: The desired name of a time column.\n",
|
||||||
|
" :type time_column_name: str\n",
|
||||||
|
" :param time_series_number: The number of time series in the data set.\n",
|
||||||
|
" :type time_series_number: int\n",
|
||||||
|
" :param freq: The frequency string representing pandas offset.\n",
|
||||||
|
" see https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html\n",
|
||||||
|
" :type freq: str\n",
|
||||||
|
" :returns: the tuple of train and test data sets.\n",
|
||||||
|
" :rtype: tuple\n",
|
||||||
|
"\n",
|
||||||
|
" \"\"\"\n",
|
||||||
|
" data_train = [] # type: List[pd.DataFrame]\n",
|
||||||
|
" data_test = [] # type: List[pd.DataFrame]\n",
|
||||||
|
" data_length = train_len + test_len\n",
|
||||||
|
" for i in range(time_series_number):\n",
|
||||||
|
" X = pd.DataFrame(\n",
|
||||||
|
" {\n",
|
||||||
|
" time_column_name: pd.date_range(\n",
|
||||||
|
" start=\"2000-01-01\", periods=data_length, freq=freq\n",
|
||||||
|
" ),\n",
|
||||||
|
" target_column_name: np.arange(data_length).astype(float)\n",
|
||||||
|
" + np.random.rand(data_length)\n",
|
||||||
|
" + i * 5,\n",
|
||||||
|
" \"ext_predictor\": np.asarray(range(42, 42 + data_length)),\n",
|
||||||
|
" time_series_id_column_name: np.repeat(\"ts{}\".format(i), data_length),\n",
|
||||||
|
" }\n",
|
||||||
|
" )\n",
|
||||||
|
" data_train.append(X[:train_len])\n",
|
||||||
|
" data_test.append(X[train_len:])\n",
|
||||||
|
" train = pd.concat(data_train)\n",
|
||||||
|
" label_train = train.pop(target_column_name).values\n",
|
||||||
|
" test = pd.concat(data_test)\n",
|
||||||
|
" label_test = test.pop(target_column_name).values\n",
|
||||||
|
" return train, label_train, test, label_test\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"n_test_periods = FORECAST_HORIZON\n",
|
||||||
|
"n_train_periods = 365\n",
|
||||||
|
"X_train, y_train, X_test, y_test = simulate_timeseries_data(\n",
|
||||||
|
" train_len=n_train_periods,\n",
|
||||||
|
" test_len=n_test_periods,\n",
|
||||||
|
" time_column_name=TIME_COLUMN_NAME,\n",
|
||||||
|
" target_column_name=LABEL_COLUMN_NAME,\n",
|
||||||
|
" time_series_id_column_name=TIME_SERIES_ID_COLUMN_NAMES,\n",
|
||||||
|
" time_series_number=2,\n",
|
||||||
|
" freq=FREQUENCY,\n",
|
||||||
|
")\n",
|
||||||
|
"X_train[LABEL_COLUMN_NAME] = y_train"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Let's see what the training data looks like."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"X_train.tail()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Prepare remote compute and data. <a id=\"prepare_remote\"></a>\n",
|
||||||
|
"The [Machine Learning service workspace](https://docs.microsoft.com/en-us/azure/machine-learning/service/concept-workspace), is paired with the storage account, which contains the default data store. We will use it to upload the artificial data and create [tabular dataset](https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.data.tabulardataset?view=azure-ml-py) for training. A tabular dataset defines a series of lazily-evaluated, immutable operations to load data from the data source into tabular representation."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.data.dataset_factory import TabularDatasetFactory\n",
|
||||||
|
"\n",
|
||||||
|
"ds = ws.get_default_datastore()\n",
|
||||||
|
"# Upload saved data to the default data store.\n",
|
||||||
|
"train_data = TabularDatasetFactory.register_pandas_dataframe(\n",
|
||||||
|
" X_train, target=(ds, \"data\"), name=\"data_backtest\"\n",
|
||||||
|
")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"You will need to create a compute target for backtesting. In this [tutorial](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-set-up-training-targets#amlcompute), you create AmlCompute as your training compute resource.\n",
|
||||||
|
"\n",
|
||||||
|
"> 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."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core.compute import ComputeTarget, AmlCompute\n",
|
||||||
|
"from azureml.core.compute_target import ComputeTargetException\n",
|
||||||
|
"\n",
|
||||||
|
"# Choose a name for your CPU cluster\n",
|
||||||
|
"amlcompute_cluster_name = \"backtest-cluster\"\n",
|
||||||
|
"\n",
|
||||||
|
"# Verify that cluster does not exist already\n",
|
||||||
|
"try:\n",
|
||||||
|
" compute_target = ComputeTarget(workspace=ws, name=amlcompute_cluster_name)\n",
|
||||||
|
" print(\"Found existing cluster, use it.\")\n",
|
||||||
|
"except ComputeTargetException:\n",
|
||||||
|
" compute_config = AmlCompute.provisioning_configuration(\n",
|
||||||
|
" vm_size=\"STANDARD_DS12_V2\", max_nodes=6\n",
|
||||||
|
" )\n",
|
||||||
|
" compute_target = ComputeTarget.create(ws, amlcompute_cluster_name, compute_config)\n",
|
||||||
|
"\n",
|
||||||
|
"compute_target.wait_for_completion(show_output=True)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Create the configuration for AutoML backtesting <a id=\"train\"></a>\n",
|
||||||
|
"\n",
|
||||||
|
"This dictionary defines the AutoML and many models settings. For this forecasting task we need to define several settings including the name of the time column, the maximum forecast horizon, and the partition column name definition.\n",
|
||||||
|
"\n",
|
||||||
|
"| Property | Description|\n",
|
||||||
|
"| :--------------- | :------------------- |\n",
|
||||||
|
"| **task** | forecasting |\n",
|
||||||
|
"| **primary_metric** | This is the metric that you want to optimize.<br> Forecasting supports the following primary metrics <br><i>normalized_root_mean_squared_error</i><br><i>normalized_mean_absolute_error</i> |\n",
|
||||||
|
"| **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. |\n",
|
||||||
|
"| **iterations** | Number of models to train. This is optional but provides customers with greater control on exit criteria. |\n",
|
||||||
|
"| **experiment_timeout_hours** | Maximum amount of time in hours that the experiment can take before it terminates. This is optional but provides customers with greater control on exit criteria. |\n",
|
||||||
|
"| **label_column_name** | The name of the label column. |\n",
|
||||||
|
"| **max_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. |\n",
|
||||||
|
"| **n_cross_validations** | Number of cross validation splits. Rolling Origin Validation is used to split time-series in a temporally consistent way. |\n",
|
||||||
|
"| **time_column_name** | The name of your time column. |\n",
|
||||||
|
"| **grain_column_names** | The column names used to uniquely identify timeseries in data that has multiple rows with the same timestamp. |"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"automl_settings = {\n",
|
||||||
|
" \"task\": \"forecasting\",\n",
|
||||||
|
" \"primary_metric\": \"normalized_root_mean_squared_error\",\n",
|
||||||
|
" \"iteration_timeout_minutes\": 10, # This needs to be changed based on the dataset. We ask customer to explore how long training is taking before settings this value\n",
|
||||||
|
" \"iterations\": 15,\n",
|
||||||
|
" \"experiment_timeout_hours\": 1, # This also needs to be changed based on the dataset. For larger data set this number needs to be bigger.\n",
|
||||||
|
" \"label_column_name\": LABEL_COLUMN_NAME,\n",
|
||||||
|
" \"n_cross_validations\": 3,\n",
|
||||||
|
" \"time_column_name\": TIME_COLUMN_NAME,\n",
|
||||||
|
" \"max_horizon\": FORECAST_HORIZON,\n",
|
||||||
|
" \"track_child_runs\": False,\n",
|
||||||
|
" \"grain_column_names\": TIME_SERIES_ID_COLUMN_NAMES,\n",
|
||||||
|
"}"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Backtest AutoML <a id=\"backtest_automl\"></a>\n",
|
||||||
|
"First we set backtesting parameters: we will step back by 30 days and will make 5 such steps; for each step we will forecast for next two weeks."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# The number of periods to step back on each backtest iteration.\n",
|
||||||
|
"BACKTESTING_PERIOD = 30\n",
|
||||||
|
"# The number of times we will back test the model.\n",
|
||||||
|
"NUMBER_OF_BACKTESTS = 5"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"To train AutoML on backtesting folds we will use the [Azure Machine Learning pipeline](https://docs.microsoft.com/en-us/azure/machine-learning/concept-ml-pipelines). It will generate backtest folds, then train model for each of them and calculate the accuracy metrics. To run pipeline, you also need to create an <b>Experiment</b>. An Experiment corresponds to a prediction problem you are trying to solve (here, it is a forecasting), while a Run corresponds to a specific approach to the problem."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from uuid import uuid1\n",
|
||||||
|
"\n",
|
||||||
|
"from pipeline_helper import get_backtest_pipeline\n",
|
||||||
|
"\n",
|
||||||
|
"pipeline_exp = Experiment(ws, \"automl-backtesting\")\n",
|
||||||
|
"\n",
|
||||||
|
"# We will create the unique identifier to mark our models.\n",
|
||||||
|
"model_uid = str(uuid1())\n",
|
||||||
|
"\n",
|
||||||
|
"pipeline = get_backtest_pipeline(\n",
|
||||||
|
" experiment=pipeline_exp,\n",
|
||||||
|
" dataset=train_data,\n",
|
||||||
|
" # The STANDARD_DS12_V2 has 4 vCPU per node, we will set 2 process per node to be safe.\n",
|
||||||
|
" process_per_node=2,\n",
|
||||||
|
" # The maximum number of nodes for our compute is 6.\n",
|
||||||
|
" node_count=6,\n",
|
||||||
|
" compute_target=compute_target,\n",
|
||||||
|
" automl_settings=automl_settings,\n",
|
||||||
|
" step_size=BACKTESTING_PERIOD,\n",
|
||||||
|
" step_number=NUMBER_OF_BACKTESTS,\n",
|
||||||
|
" model_uid=model_uid,\n",
|
||||||
|
")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Run the pipeline and wait for results."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"pipeline_run = pipeline_exp.submit(pipeline)\n",
|
||||||
|
"pipeline_run.wait_for_completion(show_output=False)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"After the run is complete, we can download the results. "
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"metrics_output = pipeline_run.get_pipeline_output(\"results\")\n",
|
||||||
|
"metrics_output.download(\"backtest_metrics\")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## View metrics<a id=\"Metrics\"></a>\n",
|
||||||
|
"To distinguish these metrics from the model backtest, which we will obtain in the next section, we will move the directory with metrics out of the backtest_metrics and will remove the parent folder. We will create the utility function for that."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"def copy_scoring_directory(new_name):\n",
|
||||||
|
" scores_path = os.path.join(\"backtest_metrics\", \"azureml\")\n",
|
||||||
|
" directory_list = [os.path.join(scores_path, d) for d in os.listdir(scores_path)]\n",
|
||||||
|
" latest_file = max(directory_list, key=os.path.getctime)\n",
|
||||||
|
" print(\n",
|
||||||
|
" f\"The output directory {latest_file} was created on {pd.Timestamp(os.path.getctime(latest_file), unit='s')} GMT.\"\n",
|
||||||
|
" )\n",
|
||||||
|
" shutil.move(os.path.join(latest_file, \"results\"), new_name)\n",
|
||||||
|
" shutil.rmtree(\"backtest_metrics\")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Move the directory and list its contents."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"copy_scoring_directory(\"automl_backtest\")\n",
|
||||||
|
"pd.DataFrame({\"File\": os.listdir(\"automl_backtest\")})"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"The directory contains a set of files with results:\n",
|
||||||
|
"- forecast.csv contains forecasts for all backtest iterations. The backtest_iteration column contains iteration identifier with the last training date as a suffix\n",
|
||||||
|
"- scores.csv contains all metrics. If data set contains several time series, the metrics are given for all combinations of time series id and iterations, as well as scores for all iterations and time series id are marked as \"all_sets\"\n",
|
||||||
|
"- plots_fcst_vs_actual.pdf contains the predictions vs forecast plots for each iteration and time series.\n",
|
||||||
|
"\n",
|
||||||
|
"For demonstration purposes we will display the table of metrics for one of the time series with ID \"ts0\". Again, we will create the utility function, which will be re used in model backtesting."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"def get_metrics_for_ts(all_metrics, ts):\n",
|
||||||
|
" \"\"\"\n",
|
||||||
|
" Get the metrics for the time series with ID ts and return it as pandas data frame.\n",
|
||||||
|
"\n",
|
||||||
|
" :param all_metrics: The table with all the metrics.\n",
|
||||||
|
" :param ts: The ID of a time series of interest.\n",
|
||||||
|
" :return: The pandas DataFrame with metrics for one time series.\n",
|
||||||
|
" \"\"\"\n",
|
||||||
|
" results_df = None\n",
|
||||||
|
" for ts_id, one_series in all_metrics.groupby(\"time_series_id\"):\n",
|
||||||
|
" if not ts_id.startswith(ts):\n",
|
||||||
|
" continue\n",
|
||||||
|
" iteration = ts_id.split(\"|\")[-1]\n",
|
||||||
|
" df = one_series[[\"metric_name\", \"metric\"]]\n",
|
||||||
|
" df.rename({\"metric\": iteration}, axis=1, inplace=True)\n",
|
||||||
|
" df.set_index(\"metric_name\", inplace=True)\n",
|
||||||
|
" if results_df is None:\n",
|
||||||
|
" results_df = df\n",
|
||||||
|
" else:\n",
|
||||||
|
" results_df = results_df.merge(\n",
|
||||||
|
" df, how=\"inner\", left_index=True, right_index=True\n",
|
||||||
|
" )\n",
|
||||||
|
" results_df.sort_index(axis=1, inplace=True)\n",
|
||||||
|
" return results_df\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"metrics_df = pd.read_csv(os.path.join(\"automl_backtest\", \"scores.csv\"))\n",
|
||||||
|
"ts_id = \"ts0\"\n",
|
||||||
|
"get_metrics_for_ts(metrics_df, ts_id)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Forecast vs actuals plots."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from IPython.display import IFrame\n",
|
||||||
|
"\n",
|
||||||
|
"IFrame(\"./automl_backtest/plots_fcst_vs_actual.pdf\", width=800, height=300)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# <font color='blue'>Backtest the best model</font> <a id=\"backtest_model\"></a>\n",
|
||||||
|
"\n",
|
||||||
|
"For model backtesting we will use the same parameters we used to backtest AutoML. All the models, we have obtained in the previous run were registered in our workspace. To identify the model, each was assigned a tag with the last trainig date."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"model_list = Model.list(ws, tags={\"experiment\": \"automl-backtesting\"})\n",
|
||||||
|
"model_data = {\"name\": [], \"last_training_date\": []}\n",
|
||||||
|
"for model in model_list:\n",
|
||||||
|
" if (\n",
|
||||||
|
" \"last_training_date\" not in model.tags\n",
|
||||||
|
" or \"model_uid\" not in model.tags\n",
|
||||||
|
" or model.tags[\"model_uid\"] != model_uid\n",
|
||||||
|
" ):\n",
|
||||||
|
" continue\n",
|
||||||
|
" model_data[\"name\"].append(model.name)\n",
|
||||||
|
" model_data[\"last_training_date\"].append(\n",
|
||||||
|
" pd.Timestamp(model.tags[\"last_training_date\"])\n",
|
||||||
|
" )\n",
|
||||||
|
"df_models = pd.DataFrame(model_data)\n",
|
||||||
|
"df_models.sort_values([\"last_training_date\"], inplace=True)\n",
|
||||||
|
"df_models.reset_index(inplace=True, drop=True)\n",
|
||||||
|
"df_models"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"We will backtest the model trained on the most recet data."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"model_name = df_models[\"name\"].iloc[-1]\n",
|
||||||
|
"model_name"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Retrain the models.\n",
|
||||||
|
"Assemble the pipeline, which will retrain the best model from AutoML run on historical data."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"pipeline_exp = Experiment(ws, \"model-backtesting\")\n",
|
||||||
|
"\n",
|
||||||
|
"pipeline = get_backtest_pipeline(\n",
|
||||||
|
" experiment=pipeline_exp,\n",
|
||||||
|
" dataset=train_data,\n",
|
||||||
|
" # The STANDARD_DS12_V2 has 4 vCPU per node, we will set 2 process per node to be safe.\n",
|
||||||
|
" process_per_node=2,\n",
|
||||||
|
" # The maximum number of nodes for our compute is 6.\n",
|
||||||
|
" node_count=6,\n",
|
||||||
|
" compute_target=compute_target,\n",
|
||||||
|
" automl_settings=automl_settings,\n",
|
||||||
|
" step_size=BACKTESTING_PERIOD,\n",
|
||||||
|
" step_number=NUMBER_OF_BACKTESTS,\n",
|
||||||
|
" model_name=model_name,\n",
|
||||||
|
")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Launch the backtesting pipeline."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"pipeline_run = pipeline_exp.submit(pipeline)\n",
|
||||||
|
"pipeline_run.wait_for_completion(show_output=False)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"The metrics are stored in the pipeline output named \"score\". The next code will download the table with metrics."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"metrics_output = pipeline_run.get_pipeline_output(\"results\")\n",
|
||||||
|
"metrics_output.download(\"backtest_metrics\")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Again, we will copy the data files from the downloaded directory, but in this case we will call the folder \"model_backtest\"; it will contain the same files as the one for AutoML backtesting."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"copy_scoring_directory(\"model_backtest\")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Finally, we will display the metrics."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"model_metrics_df = pd.read_csv(os.path.join(\"model_backtest\", \"scores.csv\"))\n",
|
||||||
|
"get_metrics_for_ts(model_metrics_df, ts_id)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Forecast vs actuals plots."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from IPython.display import IFrame\n",
|
||||||
|
"\n",
|
||||||
|
"IFrame(\"./model_backtest/plots_fcst_vs_actual.pdf\", width=800, height=300)"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"authors": [
|
||||||
|
{
|
||||||
|
"name": "jialiu"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"category": "tutorial",
|
||||||
|
"compute": [
|
||||||
|
"Remote"
|
||||||
|
],
|
||||||
|
"datasets": [
|
||||||
|
"None"
|
||||||
|
],
|
||||||
|
"deployment": [
|
||||||
|
"None"
|
||||||
|
],
|
||||||
|
"exclude_from_index": false,
|
||||||
|
"framework": [
|
||||||
|
"Azure ML AutoML"
|
||||||
|
],
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 3.6",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python36"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"codemirror_mode": {
|
||||||
|
"name": "ipython",
|
||||||
|
"version": 3
|
||||||
|
},
|
||||||
|
"file_extension": ".py",
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython3",
|
||||||
|
"version": "3.6.9"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 4
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
name: auto-ml-forecasting-backtest-single-model
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
@@ -0,0 +1,166 @@
|
|||||||
|
from typing import Any, Dict, Optional
|
||||||
|
|
||||||
|
import os
|
||||||
|
|
||||||
|
import azureml.train.automl.runtime._hts.hts_runtime_utilities as hru
|
||||||
|
|
||||||
|
from azureml._restclient.jasmine_client import JasmineClient
|
||||||
|
from azureml.contrib.automl.pipeline.steps import utilities
|
||||||
|
from azureml.core import RunConfiguration
|
||||||
|
from azureml.core.compute import ComputeTarget
|
||||||
|
from azureml.core.experiment import Experiment
|
||||||
|
from azureml.data import LinkTabularOutputDatasetConfig, TabularDataset
|
||||||
|
from azureml.pipeline.core import Pipeline, PipelineData, PipelineParameter
|
||||||
|
from azureml.pipeline.steps import ParallelRunConfig, ParallelRunStep, PythonScriptStep
|
||||||
|
from azureml.train.automl.constants import Scenarios
|
||||||
|
from azureml.data.dataset_consumption_config import DatasetConsumptionConfig
|
||||||
|
|
||||||
|
|
||||||
|
PROJECT_FOLDER = "assets"
|
||||||
|
SETTINGS_FILE = "automl_settings.json"
|
||||||
|
|
||||||
|
|
||||||
|
def get_backtest_pipeline(
|
||||||
|
experiment: Experiment,
|
||||||
|
dataset: TabularDataset,
|
||||||
|
process_per_node: int,
|
||||||
|
node_count: int,
|
||||||
|
compute_target: ComputeTarget,
|
||||||
|
automl_settings: Dict[str, Any],
|
||||||
|
step_size: int,
|
||||||
|
step_number: int,
|
||||||
|
model_name: Optional[str] = None,
|
||||||
|
model_uid: Optional[str] = None,
|
||||||
|
) -> Pipeline:
|
||||||
|
"""
|
||||||
|
:param experiment: The experiment used to run the pipeline.
|
||||||
|
:param dataset: Tabular data set to be used for model training.
|
||||||
|
:param process_per_node: The number of processes per node. Generally it should be the number of cores
|
||||||
|
on the node divided by two.
|
||||||
|
:param node_count: The number of nodes to be used.
|
||||||
|
:param compute_target: The compute target to be used to run the pipeline.
|
||||||
|
:param model_name: The name of a model to be back tested.
|
||||||
|
:param automl_settings: The dictionary with automl settings.
|
||||||
|
:param step_size: The number of periods to step back in backtesting.
|
||||||
|
:param step_number: The number of backtesting iterations.
|
||||||
|
:param model_uid: The uid to mark models from this run of the experiment.
|
||||||
|
:return: The pipeline to be used for model retraining.
|
||||||
|
**Note:** The output will be uploaded in the pipeline output
|
||||||
|
called 'score'.
|
||||||
|
"""
|
||||||
|
jasmine_client = JasmineClient(
|
||||||
|
service_context=experiment.workspace.service_context,
|
||||||
|
experiment_name=experiment.name,
|
||||||
|
experiment_id=experiment.id,
|
||||||
|
)
|
||||||
|
env = jasmine_client.get_curated_environment(
|
||||||
|
scenario=Scenarios.AUTOML,
|
||||||
|
enable_dnn=False,
|
||||||
|
enable_gpu=False,
|
||||||
|
compute=compute_target,
|
||||||
|
compute_sku=experiment.workspace.compute_targets.get(
|
||||||
|
compute_target.name
|
||||||
|
).vm_size,
|
||||||
|
)
|
||||||
|
data_results = PipelineData(
|
||||||
|
name="results", datastore=None, pipeline_output_name="results"
|
||||||
|
)
|
||||||
|
############################################################
|
||||||
|
# Split the data set using python script.
|
||||||
|
############################################################
|
||||||
|
run_config = RunConfiguration()
|
||||||
|
run_config.docker.use_docker = True
|
||||||
|
run_config.environment = env
|
||||||
|
|
||||||
|
split_data = PipelineData(name="split_data_output", datastore=None).as_dataset()
|
||||||
|
split_step = PythonScriptStep(
|
||||||
|
name="split_data_for_backtest",
|
||||||
|
script_name="data_split.py",
|
||||||
|
inputs=[dataset.as_named_input("training_data")],
|
||||||
|
outputs=[split_data],
|
||||||
|
source_directory=PROJECT_FOLDER,
|
||||||
|
arguments=[
|
||||||
|
"--step-size",
|
||||||
|
step_size,
|
||||||
|
"--step-number",
|
||||||
|
step_number,
|
||||||
|
"--time-column-name",
|
||||||
|
automl_settings.get("time_column_name"),
|
||||||
|
"--time-series-id-column-names",
|
||||||
|
automl_settings.get("grain_column_names"),
|
||||||
|
"--output-dir",
|
||||||
|
split_data,
|
||||||
|
],
|
||||||
|
runconfig=run_config,
|
||||||
|
compute_target=compute_target,
|
||||||
|
allow_reuse=False,
|
||||||
|
)
|
||||||
|
############################################################
|
||||||
|
# We will do the backtest the parallel run step.
|
||||||
|
############################################################
|
||||||
|
settings_path = os.path.join(PROJECT_FOLDER, SETTINGS_FILE)
|
||||||
|
hru.dump_object_to_json(automl_settings, settings_path)
|
||||||
|
mini_batch_size = PipelineParameter(name="batch_size_param", default_value=str(1))
|
||||||
|
back_test_config = ParallelRunConfig(
|
||||||
|
source_directory=PROJECT_FOLDER,
|
||||||
|
entry_script="retrain_models.py",
|
||||||
|
mini_batch_size=mini_batch_size,
|
||||||
|
error_threshold=-1,
|
||||||
|
output_action="append_row",
|
||||||
|
append_row_file_name="outputs.txt",
|
||||||
|
compute_target=compute_target,
|
||||||
|
environment=env,
|
||||||
|
process_count_per_node=process_per_node,
|
||||||
|
run_invocation_timeout=3600,
|
||||||
|
node_count=node_count,
|
||||||
|
)
|
||||||
|
forecasts = PipelineData(name="forecasts", datastore=None)
|
||||||
|
if model_name:
|
||||||
|
parallel_step_name = "{}-backtest".format(model_name.replace("_", "-"))
|
||||||
|
else:
|
||||||
|
parallel_step_name = "AutoML-backtest"
|
||||||
|
|
||||||
|
prs_args = [
|
||||||
|
"--target_column_name",
|
||||||
|
automl_settings.get("label_column_name"),
|
||||||
|
"--output-dir",
|
||||||
|
forecasts,
|
||||||
|
]
|
||||||
|
if model_name is not None:
|
||||||
|
prs_args.append("--model-name")
|
||||||
|
prs_args.append(model_name)
|
||||||
|
if model_uid is not None:
|
||||||
|
prs_args.append("--model-uid")
|
||||||
|
prs_args.append(model_uid)
|
||||||
|
backtest_prs = ParallelRunStep(
|
||||||
|
name=parallel_step_name,
|
||||||
|
parallel_run_config=back_test_config,
|
||||||
|
arguments=prs_args,
|
||||||
|
inputs=[split_data],
|
||||||
|
output=forecasts,
|
||||||
|
allow_reuse=False,
|
||||||
|
)
|
||||||
|
############################################################
|
||||||
|
# Then we collect the output and return it as scores output.
|
||||||
|
############################################################
|
||||||
|
collection_step = PythonScriptStep(
|
||||||
|
name="score",
|
||||||
|
script_name="score.py",
|
||||||
|
inputs=[forecasts.as_mount()],
|
||||||
|
outputs=[data_results],
|
||||||
|
source_directory=PROJECT_FOLDER,
|
||||||
|
arguments=[
|
||||||
|
"--forecasts",
|
||||||
|
forecasts,
|
||||||
|
"--output-dir",
|
||||||
|
data_results,
|
||||||
|
],
|
||||||
|
runconfig=run_config,
|
||||||
|
compute_target=compute_target,
|
||||||
|
allow_reuse=False,
|
||||||
|
)
|
||||||
|
# Build and return the pipeline.
|
||||||
|
return Pipeline(
|
||||||
|
workspace=experiment.workspace,
|
||||||
|
steps=[split_step, backtest_prs, collection_step],
|
||||||
|
)
|
||||||
@@ -54,9 +54,8 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
|
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"An Enterprise workspace is required for this notebook. To learn more about creating an Enterprise workspace or upgrading to an Enterprise workspace from the Azure portal, please visit our [Workspace page.](https://docs.microsoft.com/azure/machine-learning/service/concept-workspace#upgrade)\n",
|
|
||||||
"\n",
|
|
||||||
"Notebook synopsis:\n",
|
"Notebook synopsis:\n",
|
||||||
|
"\n",
|
||||||
"1. Creating an Experiment in an existing Workspace\n",
|
"1. Creating an Experiment in an existing Workspace\n",
|
||||||
"2. Configuration and remote run of AutoML for a time-series model exploring Regression learners, Arima, Prophet and DNNs\n",
|
"2. Configuration and remote run of AutoML for a time-series model exploring Regression learners, Arima, Prophet and DNNs\n",
|
||||||
"4. Evaluating the fitted model using a rolling test "
|
"4. Evaluating the fitted model using a rolling test "
|
||||||
@@ -114,7 +113,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"print(\"This notebook was created using version 1.12.0 of the Azure ML SDK\")\n",
|
"print(\"This notebook was created using version 1.37.0 of the Azure ML SDK\")\n",
|
||||||
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -140,18 +139,18 @@
|
|||||||
"ws = Workspace.from_config()\n",
|
"ws = Workspace.from_config()\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# choose a name for the run history container in the workspace\n",
|
"# choose a name for the run history container in the workspace\n",
|
||||||
"experiment_name = 'beer-remote-cpu'\n",
|
"experiment_name = \"beer-remote-cpu\"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"experiment = Experiment(ws, experiment_name)\n",
|
"experiment = Experiment(ws, experiment_name)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"output = {}\n",
|
"output = {}\n",
|
||||||
"output['Subscription ID'] = ws.subscription_id\n",
|
"output[\"Subscription ID\"] = ws.subscription_id\n",
|
||||||
"output['Workspace'] = ws.name\n",
|
"output[\"Workspace\"] = ws.name\n",
|
||||||
"output['Resource Group'] = ws.resource_group\n",
|
"output[\"Resource Group\"] = ws.resource_group\n",
|
||||||
"output['Location'] = ws.location\n",
|
"output[\"Location\"] = ws.location\n",
|
||||||
"output['Run History Name'] = experiment_name\n",
|
"output[\"Run History Name\"] = experiment_name\n",
|
||||||
"pd.set_option('display.max_colwidth', -1)\n",
|
"pd.set_option(\"display.max_colwidth\", -1)\n",
|
||||||
"outputDf = pd.DataFrame(data = output, index = [''])\n",
|
"outputDf = pd.DataFrame(data=output, index=[\"\"])\n",
|
||||||
"outputDf.T"
|
"outputDf.T"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -163,7 +162,9 @@
|
|||||||
},
|
},
|
||||||
"source": [
|
"source": [
|
||||||
"### Using AmlCompute\n",
|
"### Using AmlCompute\n",
|
||||||
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for your AutoML run. In this tutorial, you use `AmlCompute` as your training compute resource."
|
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for your AutoML run. In this tutorial, you use `AmlCompute` as your training compute resource.\n",
|
||||||
|
"\n",
|
||||||
|
"> 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."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -184,10 +185,11 @@
|
|||||||
"# Verify that cluster does not exist already\n",
|
"# Verify that cluster does not exist already\n",
|
||||||
"try:\n",
|
"try:\n",
|
||||||
" compute_target = ComputeTarget(workspace=ws, name=cpu_cluster_name)\n",
|
" compute_target = ComputeTarget(workspace=ws, name=cpu_cluster_name)\n",
|
||||||
" print('Found existing cluster, use it.')\n",
|
" print(\"Found existing cluster, use it.\")\n",
|
||||||
"except ComputeTargetException:\n",
|
"except ComputeTargetException:\n",
|
||||||
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_D2_V2',\n",
|
" compute_config = AmlCompute.provisioning_configuration(\n",
|
||||||
" max_nodes=4)\n",
|
" vm_size=\"STANDARD_DS12_V2\", max_nodes=4\n",
|
||||||
|
" )\n",
|
||||||
" compute_target = ComputeTarget.create(ws, cpu_cluster_name, compute_config)\n",
|
" compute_target = ComputeTarget.create(ws, cpu_cluster_name, compute_config)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"compute_target.wait_for_completion(show_output=True)"
|
"compute_target.wait_for_completion(show_output=True)"
|
||||||
@@ -219,6 +221,8 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"**Time series identifier columns** are identified by values of the columns listed `time_series_id_column_names`, for example \"store\" and \"item\" if your data has multiple time series of sales, one series for each combination of store and item sold.\n",
|
"**Time series identifier columns** are identified by values of the columns listed `time_series_id_column_names`, for example \"store\" and \"item\" if your data has multiple time series of sales, one series for each combination of store and item sold.\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"**Forecast frequency (freq)** This optional parameter represents the period with which the forecast is desired, for example, daily, weekly, yearly, etc. Use this parameter for the correction of time series containing irregular data points or for padding of short time series. The frequency needs to be a pandas offset alias. Please refer to [pandas documentation](https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#dateoffset-objects) for more information.\n",
|
||||||
|
"\n",
|
||||||
"This dataset has only one time series. Please see the [orange juice notebook](https://github.com/Azure/MachineLearningNotebooks/tree/master/how-to-use-azureml/automated-machine-learning/forecasting-orange-juice-sales) for an example of a multi-time series dataset."
|
"This dataset has only one time series. Please see the [orange juice notebook](https://github.com/Azure/MachineLearningNotebooks/tree/master/how-to-use-azureml/automated-machine-learning/forecasting-orange-juice-sales) for an example of a multi-time series dataset."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -242,17 +246,21 @@
|
|||||||
"plt.tight_layout()\n",
|
"plt.tight_layout()\n",
|
||||||
"\n",
|
"\n",
|
||||||
"plt.subplot(2, 1, 1)\n",
|
"plt.subplot(2, 1, 1)\n",
|
||||||
"plt.title('Beer Production By Year')\n",
|
"plt.title(\"Beer Production By Year\")\n",
|
||||||
"df = pd.read_csv(\"Beer_no_valid_split_train.csv\", parse_dates=True, index_col= 'DATE').drop(columns='grain')\n",
|
"df = pd.read_csv(\n",
|
||||||
"test_df = pd.read_csv(\"Beer_no_valid_split_test.csv\", parse_dates=True, index_col= 'DATE').drop(columns='grain')\n",
|
" \"Beer_no_valid_split_train.csv\", parse_dates=True, index_col=\"DATE\"\n",
|
||||||
|
").drop(columns=\"grain\")\n",
|
||||||
|
"test_df = pd.read_csv(\n",
|
||||||
|
" \"Beer_no_valid_split_test.csv\", parse_dates=True, index_col=\"DATE\"\n",
|
||||||
|
").drop(columns=\"grain\")\n",
|
||||||
"plt.plot(df)\n",
|
"plt.plot(df)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"plt.subplot(2, 1, 2)\n",
|
"plt.subplot(2, 1, 2)\n",
|
||||||
"plt.title('Beer Production By Month')\n",
|
"plt.title(\"Beer Production By Month\")\n",
|
||||||
"groups = df.groupby(df.index.month)\n",
|
"groups = df.groupby(df.index.month)\n",
|
||||||
"months = concat([DataFrame(x[1].values) for x in groups], axis=1)\n",
|
"months = concat([DataFrame(x[1].values) for x in groups], axis=1)\n",
|
||||||
"months = DataFrame(months)\n",
|
"months = DataFrame(months)\n",
|
||||||
"months.columns = range(1,13)\n",
|
"months.columns = range(1, 13)\n",
|
||||||
"months.boxplot()\n",
|
"months.boxplot()\n",
|
||||||
"\n",
|
"\n",
|
||||||
"plt.show()"
|
"plt.show()"
|
||||||
@@ -267,10 +275,10 @@
|
|||||||
},
|
},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"target_column_name = 'BeerProduction'\n",
|
"target_column_name = \"BeerProduction\"\n",
|
||||||
"time_column_name = 'DATE'\n",
|
"time_column_name = \"DATE\"\n",
|
||||||
"time_series_id_column_names = []\n",
|
"time_series_id_column_names = []\n",
|
||||||
"freq = 'M' #Monthly data"
|
"freq = \"M\" # Monthly data"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -298,14 +306,36 @@
|
|||||||
"test_df.to_csv(\"test.csv\")\n",
|
"test_df.to_csv(\"test.csv\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"datastore = ws.get_default_datastore()\n",
|
"datastore = ws.get_default_datastore()\n",
|
||||||
"datastore.upload_files(files = ['./train.csv'], target_path = 'beer-dataset/tabular/', overwrite = True,show_progress = True)\n",
|
"datastore.upload_files(\n",
|
||||||
"datastore.upload_files(files = ['./valid.csv'], target_path = 'beer-dataset/tabular/', overwrite = True,show_progress = True)\n",
|
" files=[\"./train.csv\"],\n",
|
||||||
"datastore.upload_files(files = ['./test.csv'], target_path = 'beer-dataset/tabular/', overwrite = True,show_progress = True)\n",
|
" target_path=\"beer-dataset/tabular/\",\n",
|
||||||
|
" overwrite=True,\n",
|
||||||
|
" show_progress=True,\n",
|
||||||
|
")\n",
|
||||||
|
"datastore.upload_files(\n",
|
||||||
|
" files=[\"./valid.csv\"],\n",
|
||||||
|
" target_path=\"beer-dataset/tabular/\",\n",
|
||||||
|
" overwrite=True,\n",
|
||||||
|
" show_progress=True,\n",
|
||||||
|
")\n",
|
||||||
|
"datastore.upload_files(\n",
|
||||||
|
" files=[\"./test.csv\"],\n",
|
||||||
|
" target_path=\"beer-dataset/tabular/\",\n",
|
||||||
|
" overwrite=True,\n",
|
||||||
|
" show_progress=True,\n",
|
||||||
|
")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"from azureml.core import Dataset\n",
|
"from azureml.core import Dataset\n",
|
||||||
"train_dataset = Dataset.Tabular.from_delimited_files(path = [(datastore, 'beer-dataset/tabular/train.csv')])\n",
|
"\n",
|
||||||
"valid_dataset = Dataset.Tabular.from_delimited_files(path = [(datastore, 'beer-dataset/tabular/valid.csv')])\n",
|
"train_dataset = Dataset.Tabular.from_delimited_files(\n",
|
||||||
"test_dataset = Dataset.Tabular.from_delimited_files(path = [(datastore, 'beer-dataset/tabular/test.csv')])"
|
" path=[(datastore, \"beer-dataset/tabular/train.csv\")]\n",
|
||||||
|
")\n",
|
||||||
|
"valid_dataset = Dataset.Tabular.from_delimited_files(\n",
|
||||||
|
" path=[(datastore, \"beer-dataset/tabular/valid.csv\")]\n",
|
||||||
|
")\n",
|
||||||
|
"test_dataset = Dataset.Tabular.from_delimited_files(\n",
|
||||||
|
" path=[(datastore, \"beer-dataset/tabular/test.csv\")]\n",
|
||||||
|
")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -350,9 +380,7 @@
|
|||||||
"|**iteration_timeout_minutes**|Time limit in minutes for each iteration.|\n",
|
"|**iteration_timeout_minutes**|Time limit in minutes for each iteration.|\n",
|
||||||
"|**training_data**|Input dataset, containing both features and label column.|\n",
|
"|**training_data**|Input dataset, containing both features and label column.|\n",
|
||||||
"|**label_column_name**|The name of the label column.|\n",
|
"|**label_column_name**|The name of the label column.|\n",
|
||||||
"|**enable_dnn**|Enable Forecasting DNNs|\n",
|
"|**enable_dnn**|Enable Forecasting DNNs|\n"
|
||||||
"\n",
|
|
||||||
"This step requires an Enterprise workspace to gain access to this feature. To learn more about creating an Enterprise workspace or upgrading to an Enterprise workspace from the Azure portal, please visit our [Workspace page.](https://docs.microsoft.com/azure/machine-learning/service/concept-workspace#upgrade)."
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -365,22 +393,29 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from azureml.automl.core.forecasting_parameters import ForecastingParameters\n",
|
"from azureml.automl.core.forecasting_parameters import ForecastingParameters\n",
|
||||||
|
"\n",
|
||||||
"forecasting_parameters = ForecastingParameters(\n",
|
"forecasting_parameters = ForecastingParameters(\n",
|
||||||
" time_column_name=time_column_name, forecast_horizon=forecast_horizon\n",
|
" time_column_name=time_column_name,\n",
|
||||||
|
" forecast_horizon=forecast_horizon,\n",
|
||||||
|
" freq=\"MS\", # Set the forecast frequency to be monthly (start of the month)\n",
|
||||||
")\n",
|
")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"automl_config = AutoMLConfig(task='forecasting', \n",
|
"# We will disable the enable_early_stopping flag to ensure the DNN model is recommended for demonstration purpose.\n",
|
||||||
" primary_metric='normalized_root_mean_squared_error',\n",
|
"automl_config = AutoMLConfig(\n",
|
||||||
" experiment_timeout_hours = 1,\n",
|
" task=\"forecasting\",\n",
|
||||||
" training_data=train_dataset,\n",
|
" primary_metric=\"normalized_root_mean_squared_error\",\n",
|
||||||
" label_column_name=target_column_name,\n",
|
" experiment_timeout_hours=1,\n",
|
||||||
" validation_data=valid_dataset, \n",
|
" training_data=train_dataset,\n",
|
||||||
" verbosity=logging.INFO,\n",
|
" label_column_name=target_column_name,\n",
|
||||||
" compute_target=compute_target,\n",
|
" validation_data=valid_dataset,\n",
|
||||||
" max_concurrent_iterations=4,\n",
|
" verbosity=logging.INFO,\n",
|
||||||
" max_cores_per_iteration=-1,\n",
|
" compute_target=compute_target,\n",
|
||||||
" enable_dnn=True,\n",
|
" max_concurrent_iterations=4,\n",
|
||||||
" forecasting_parameters=forecasting_parameters)"
|
" max_cores_per_iteration=-1,\n",
|
||||||
|
" enable_dnn=True,\n",
|
||||||
|
" enable_early_stopping=False,\n",
|
||||||
|
" forecasting_parameters=forecasting_parameters,\n",
|
||||||
|
")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -402,8 +437,7 @@
|
|||||||
},
|
},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"remote_run = experiment.submit(automl_config, show_output= False)\n",
|
"remote_run = experiment.submit(automl_config, show_output=True)"
|
||||||
"remote_run"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -420,15 +454,6 @@
|
|||||||
"# remote_run = AutoMLRun(experiment = experiment, run_id = '<replace with your run id>')"
|
"# remote_run = AutoMLRun(experiment = experiment, run_id = '<replace with your run id>')"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"remote_run.wait_for_completion()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {
|
"metadata": {
|
||||||
@@ -460,6 +485,7 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from helper import get_result_df\n",
|
"from helper import get_result_df\n",
|
||||||
|
"\n",
|
||||||
"summary_df = get_result_df(remote_run)\n",
|
"summary_df = get_result_df(remote_run)\n",
|
||||||
"summary_df"
|
"summary_df"
|
||||||
]
|
]
|
||||||
@@ -475,11 +501,12 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"from azureml.core.run import Run\n",
|
"from azureml.core.run import Run\n",
|
||||||
"from azureml.widgets import RunDetails\n",
|
"from azureml.widgets import RunDetails\n",
|
||||||
"forecast_model = 'TCNForecaster'\n",
|
"\n",
|
||||||
"if not forecast_model in summary_df['run_id']:\n",
|
"forecast_model = \"TCNForecaster\"\n",
|
||||||
" forecast_model = 'ForecastTCN'\n",
|
"if not forecast_model in summary_df[\"run_id\"]:\n",
|
||||||
" \n",
|
" forecast_model = \"ForecastTCN\"\n",
|
||||||
"best_dnn_run_id = summary_df['run_id'][forecast_model]\n",
|
"\n",
|
||||||
|
"best_dnn_run_id = summary_df[\"run_id\"][forecast_model]\n",
|
||||||
"best_dnn_run = Run(experiment, best_dnn_run_id)"
|
"best_dnn_run = Run(experiment, best_dnn_run_id)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -493,7 +520,7 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"best_dnn_run.parent\n",
|
"best_dnn_run.parent\n",
|
||||||
"RunDetails(best_dnn_run.parent).show() "
|
"RunDetails(best_dnn_run.parent).show()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -506,7 +533,7 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"best_dnn_run\n",
|
"best_dnn_run\n",
|
||||||
"RunDetails(best_dnn_run).show() "
|
"RunDetails(best_dnn_run).show()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -541,7 +568,10 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from azureml.core import Dataset\n",
|
"from azureml.core import Dataset\n",
|
||||||
"test_dataset = Dataset.Tabular.from_delimited_files(path = [(datastore, 'beer-dataset/tabular/test.csv')])\n",
|
"\n",
|
||||||
|
"test_dataset = Dataset.Tabular.from_delimited_files(\n",
|
||||||
|
" path=[(datastore, \"beer-dataset/tabular/test.csv\")]\n",
|
||||||
|
")\n",
|
||||||
"# preview the first 3 rows of the dataset\n",
|
"# preview the first 3 rows of the dataset\n",
|
||||||
"test_dataset.take(5).to_pandas_dataframe()"
|
"test_dataset.take(5).to_pandas_dataframe()"
|
||||||
]
|
]
|
||||||
@@ -552,7 +582,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"compute_target = ws.compute_targets['beer-cluster']\n",
|
"compute_target = ws.compute_targets[\"beer-cluster\"]\n",
|
||||||
"test_experiment = Experiment(ws, experiment_name + \"_test\")"
|
"test_experiment = Experiment(ws, experiment_name + \"_test\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -568,9 +598,9 @@
|
|||||||
"import os\n",
|
"import os\n",
|
||||||
"import shutil\n",
|
"import shutil\n",
|
||||||
"\n",
|
"\n",
|
||||||
"script_folder = os.path.join(os.getcwd(), 'inference')\n",
|
"script_folder = os.path.join(os.getcwd(), \"inference\")\n",
|
||||||
"os.makedirs(script_folder, exist_ok=True)\n",
|
"os.makedirs(script_folder, exist_ok=True)\n",
|
||||||
"shutil.copy('infer.py', script_folder)"
|
"shutil.copy(\"infer.py\", script_folder)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -581,8 +611,18 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"from helper import run_inference\n",
|
"from helper import run_inference\n",
|
||||||
"\n",
|
"\n",
|
||||||
"test_run = run_inference(test_experiment, compute_target, script_folder, best_dnn_run, test_dataset, valid_dataset, forecast_horizon,\n",
|
"test_run = run_inference(\n",
|
||||||
" target_column_name, time_column_name, freq)"
|
" test_experiment,\n",
|
||||||
|
" compute_target,\n",
|
||||||
|
" script_folder,\n",
|
||||||
|
" best_dnn_run,\n",
|
||||||
|
" test_dataset,\n",
|
||||||
|
" valid_dataset,\n",
|
||||||
|
" forecast_horizon,\n",
|
||||||
|
" target_column_name,\n",
|
||||||
|
" time_column_name,\n",
|
||||||
|
" freq,\n",
|
||||||
|
")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -602,8 +642,19 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"from helper import run_multiple_inferences\n",
|
"from helper import run_multiple_inferences\n",
|
||||||
"\n",
|
"\n",
|
||||||
"summary_df = run_multiple_inferences(summary_df, experiment, test_experiment, compute_target, script_folder, test_dataset, \n",
|
"summary_df = run_multiple_inferences(\n",
|
||||||
" valid_dataset, forecast_horizon, target_column_name, time_column_name, freq)"
|
" summary_df,\n",
|
||||||
|
" experiment,\n",
|
||||||
|
" test_experiment,\n",
|
||||||
|
" compute_target,\n",
|
||||||
|
" script_folder,\n",
|
||||||
|
" test_dataset,\n",
|
||||||
|
" valid_dataset,\n",
|
||||||
|
" forecast_horizon,\n",
|
||||||
|
" target_column_name,\n",
|
||||||
|
" time_column_name,\n",
|
||||||
|
" freq,\n",
|
||||||
|
")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -623,7 +674,7 @@
|
|||||||
" test_run = Run(test_experiment, test_run_id)\n",
|
" test_run = Run(test_experiment, test_run_id)\n",
|
||||||
" test_run.wait_for_completion()\n",
|
" test_run.wait_for_completion()\n",
|
||||||
" test_score = test_run.get_metrics()[run_summary.primary_metric]\n",
|
" test_score = test_run.get_metrics()[run_summary.primary_metric]\n",
|
||||||
" summary_df.loc[summary_df.run_id == run_id, 'Test Score'] = test_score\n",
|
" summary_df.loc[summary_df.run_id == run_id, \"Test Score\"] = test_score\n",
|
||||||
" print(\"Test Score: \", test_score)"
|
" print(\"Test Score: \", test_score)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -650,7 +701,7 @@
|
|||||||
"metadata": {
|
"metadata": {
|
||||||
"authors": [
|
"authors": [
|
||||||
{
|
{
|
||||||
"name": "omkarm"
|
"name": "jialiu"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"hide_code_all_hidden": false,
|
"hide_code_all_hidden": false,
|
||||||
@@ -669,7 +720,7 @@
|
|||||||
"name": "python",
|
"name": "python",
|
||||||
"nbconvert_exporter": "python",
|
"nbconvert_exporter": "python",
|
||||||
"pygments_lexer": "ipython3",
|
"pygments_lexer": "ipython3",
|
||||||
"version": "3.6.7"
|
"version": "3.6.9"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"nbformat": 4,
|
"nbformat": 4,
|
||||||
|
|||||||
@@ -3,122 +3,161 @@ from azureml.core import Environment
|
|||||||
from azureml.core.conda_dependencies import CondaDependencies
|
from azureml.core.conda_dependencies import CondaDependencies
|
||||||
from azureml.train.estimator import Estimator
|
from azureml.train.estimator import Estimator
|
||||||
from azureml.core.run import Run
|
from azureml.core.run import Run
|
||||||
|
from azureml.automl.core.shared import constants
|
||||||
|
|
||||||
|
|
||||||
def split_fraction_by_grain(df, fraction, time_column_name,
|
def split_fraction_by_grain(df, fraction, time_column_name, grain_column_names=None):
|
||||||
grain_column_names=None):
|
|
||||||
|
|
||||||
if not grain_column_names:
|
if not grain_column_names:
|
||||||
df['tmp_grain_column'] = 'grain'
|
df["tmp_grain_column"] = "grain"
|
||||||
grain_column_names = ['tmp_grain_column']
|
grain_column_names = ["tmp_grain_column"]
|
||||||
|
|
||||||
"""Group df by grain and split on last n rows for each group."""
|
"""Group df by grain and split on last n rows for each group."""
|
||||||
df_grouped = (df.sort_values(time_column_name)
|
df_grouped = df.sort_values(time_column_name).groupby(
|
||||||
.groupby(grain_column_names, group_keys=False))
|
grain_column_names, group_keys=False
|
||||||
|
)
|
||||||
|
|
||||||
df_head = df_grouped.apply(lambda dfg: dfg.iloc[:-int(len(dfg) *
|
df_head = df_grouped.apply(
|
||||||
fraction)] if fraction > 0 else dfg)
|
lambda dfg: dfg.iloc[: -int(len(dfg) * fraction)] if fraction > 0 else dfg
|
||||||
|
)
|
||||||
|
|
||||||
df_tail = df_grouped.apply(lambda dfg: dfg.iloc[-int(len(dfg) *
|
df_tail = df_grouped.apply(
|
||||||
fraction):] if fraction > 0 else dfg[:0])
|
lambda dfg: dfg.iloc[-int(len(dfg) * fraction) :] if fraction > 0 else dfg[:0]
|
||||||
|
)
|
||||||
|
|
||||||
if 'tmp_grain_column' in grain_column_names:
|
if "tmp_grain_column" in grain_column_names:
|
||||||
for df2 in (df, df_head, df_tail):
|
for df2 in (df, df_head, df_tail):
|
||||||
df2.drop('tmp_grain_column', axis=1, inplace=True)
|
df2.drop("tmp_grain_column", axis=1, inplace=True)
|
||||||
|
|
||||||
grain_column_names.remove('tmp_grain_column')
|
grain_column_names.remove("tmp_grain_column")
|
||||||
|
|
||||||
return df_head, df_tail
|
return df_head, df_tail
|
||||||
|
|
||||||
|
|
||||||
def split_full_for_forecasting(df, time_column_name,
|
def split_full_for_forecasting(
|
||||||
grain_column_names=None, test_split=0.2):
|
df, time_column_name, grain_column_names=None, test_split=0.2
|
||||||
|
):
|
||||||
index_name = df.index.name
|
index_name = df.index.name
|
||||||
|
|
||||||
# Assumes that there isn't already a column called tmpindex
|
# Assumes that there isn't already a column called tmpindex
|
||||||
|
|
||||||
df['tmpindex'] = df.index
|
df["tmpindex"] = df.index
|
||||||
|
|
||||||
train_df, test_df = split_fraction_by_grain(
|
train_df, test_df = split_fraction_by_grain(
|
||||||
df, test_split, time_column_name, grain_column_names)
|
df, test_split, time_column_name, grain_column_names
|
||||||
|
)
|
||||||
|
|
||||||
train_df = train_df.set_index('tmpindex')
|
train_df = train_df.set_index("tmpindex")
|
||||||
train_df.index.name = index_name
|
train_df.index.name = index_name
|
||||||
|
|
||||||
test_df = test_df.set_index('tmpindex')
|
test_df = test_df.set_index("tmpindex")
|
||||||
test_df.index.name = index_name
|
test_df.index.name = index_name
|
||||||
|
|
||||||
df.drop('tmpindex', axis=1, inplace=True)
|
df.drop("tmpindex", axis=1, inplace=True)
|
||||||
|
|
||||||
return train_df, test_df
|
return train_df, test_df
|
||||||
|
|
||||||
|
|
||||||
def get_result_df(remote_run):
|
def get_result_df(remote_run):
|
||||||
children = list(remote_run.get_children(recursive=True))
|
children = list(remote_run.get_children(recursive=True))
|
||||||
summary_df = pd.DataFrame(index=['run_id', 'run_algorithm',
|
summary_df = pd.DataFrame(
|
||||||
'primary_metric', 'Score'])
|
index=["run_id", "run_algorithm", "primary_metric", "Score"]
|
||||||
|
)
|
||||||
goal_minimize = False
|
goal_minimize = False
|
||||||
for run in children:
|
for run in children:
|
||||||
if('run_algorithm' in run.properties and 'score' in run.properties):
|
if (
|
||||||
summary_df[run.id] = [run.id, run.properties['run_algorithm'],
|
run.get_status().lower() == constants.RunState.COMPLETE_RUN
|
||||||
run.properties['primary_metric'],
|
and "run_algorithm" in run.properties
|
||||||
float(run.properties['score'])]
|
and "score" in run.properties
|
||||||
if('goal' in run.properties):
|
):
|
||||||
goal_minimize = run.properties['goal'].split('_')[-1] == 'min'
|
# We only count in the completed child runs.
|
||||||
|
summary_df[run.id] = [
|
||||||
|
run.id,
|
||||||
|
run.properties["run_algorithm"],
|
||||||
|
run.properties["primary_metric"],
|
||||||
|
float(run.properties["score"]),
|
||||||
|
]
|
||||||
|
if "goal" in run.properties:
|
||||||
|
goal_minimize = run.properties["goal"].split("_")[-1] == "min"
|
||||||
|
|
||||||
summary_df = summary_df.T.sort_values(
|
summary_df = summary_df.T.sort_values(
|
||||||
'Score',
|
"Score", ascending=goal_minimize
|
||||||
ascending=goal_minimize).drop_duplicates(['run_algorithm'])
|
).drop_duplicates(["run_algorithm"])
|
||||||
summary_df = summary_df.set_index('run_algorithm')
|
summary_df = summary_df.set_index("run_algorithm")
|
||||||
return summary_df
|
return summary_df
|
||||||
|
|
||||||
|
|
||||||
def run_inference(test_experiment, compute_target, script_folder, train_run,
|
def run_inference(
|
||||||
test_dataset, lookback_dataset, max_horizon,
|
test_experiment,
|
||||||
target_column_name, time_column_name, freq):
|
compute_target,
|
||||||
model_base_name = 'model.pkl'
|
script_folder,
|
||||||
if 'model_data_location' in train_run.properties:
|
train_run,
|
||||||
model_location = train_run.properties['model_data_location']
|
test_dataset,
|
||||||
_, model_base_name = model_location.rsplit('/', 1)
|
lookback_dataset,
|
||||||
train_run.download_file('outputs/{}'.format(model_base_name), 'inference/{}'.format(model_base_name))
|
max_horizon,
|
||||||
train_run.download_file('outputs/conda_env_v_1_0_0.yml', 'inference/condafile.yml')
|
target_column_name,
|
||||||
|
time_column_name,
|
||||||
|
freq,
|
||||||
|
):
|
||||||
|
model_base_name = "model.pkl"
|
||||||
|
if "model_data_location" in train_run.properties:
|
||||||
|
model_location = train_run.properties["model_data_location"]
|
||||||
|
_, model_base_name = model_location.rsplit("/", 1)
|
||||||
|
train_run.download_file(
|
||||||
|
"outputs/{}".format(model_base_name), "inference/{}".format(model_base_name)
|
||||||
|
)
|
||||||
|
train_run.download_file("outputs/conda_env_v_1_0_0.yml", "inference/condafile.yml")
|
||||||
|
|
||||||
inference_env = Environment("myenv")
|
inference_env = Environment("myenv")
|
||||||
inference_env.docker.enabled = True
|
inference_env.docker.enabled = True
|
||||||
inference_env.python.conda_dependencies = CondaDependencies(
|
inference_env.python.conda_dependencies = CondaDependencies(
|
||||||
conda_dependencies_file_path='inference/condafile.yml')
|
conda_dependencies_file_path="inference/condafile.yml"
|
||||||
|
)
|
||||||
|
|
||||||
est = Estimator(source_directory=script_folder,
|
est = Estimator(
|
||||||
entry_script='infer.py',
|
source_directory=script_folder,
|
||||||
script_params={
|
entry_script="infer.py",
|
||||||
'--max_horizon': max_horizon,
|
script_params={
|
||||||
'--target_column_name': target_column_name,
|
"--max_horizon": max_horizon,
|
||||||
'--time_column_name': time_column_name,
|
"--target_column_name": target_column_name,
|
||||||
'--frequency': freq,
|
"--time_column_name": time_column_name,
|
||||||
'--model_path': model_base_name
|
"--frequency": freq,
|
||||||
},
|
"--model_path": model_base_name,
|
||||||
inputs=[test_dataset.as_named_input('test_data'),
|
},
|
||||||
lookback_dataset.as_named_input('lookback_data')],
|
inputs=[
|
||||||
compute_target=compute_target,
|
test_dataset.as_named_input("test_data"),
|
||||||
environment_definition=inference_env)
|
lookback_dataset.as_named_input("lookback_data"),
|
||||||
|
],
|
||||||
|
compute_target=compute_target,
|
||||||
|
environment_definition=inference_env,
|
||||||
|
)
|
||||||
|
|
||||||
run = test_experiment.submit(
|
run = test_experiment.submit(
|
||||||
est, tags={
|
est,
|
||||||
'training_run_id': train_run.id,
|
tags={
|
||||||
'run_algorithm': train_run.properties['run_algorithm'],
|
"training_run_id": train_run.id,
|
||||||
'valid_score': train_run.properties['score'],
|
"run_algorithm": train_run.properties["run_algorithm"],
|
||||||
'primary_metric': train_run.properties['primary_metric']
|
"valid_score": train_run.properties["score"],
|
||||||
})
|
"primary_metric": train_run.properties["primary_metric"],
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
run.log("run_algorithm", run.tags['run_algorithm'])
|
run.log("run_algorithm", run.tags["run_algorithm"])
|
||||||
return run
|
return run
|
||||||
|
|
||||||
|
|
||||||
def run_multiple_inferences(summary_df, train_experiment, test_experiment,
|
def run_multiple_inferences(
|
||||||
compute_target, script_folder, test_dataset,
|
summary_df,
|
||||||
lookback_dataset, max_horizon, target_column_name,
|
train_experiment,
|
||||||
time_column_name, freq):
|
test_experiment,
|
||||||
|
compute_target,
|
||||||
|
script_folder,
|
||||||
|
test_dataset,
|
||||||
|
lookback_dataset,
|
||||||
|
max_horizon,
|
||||||
|
target_column_name,
|
||||||
|
time_column_name,
|
||||||
|
freq,
|
||||||
|
):
|
||||||
for run_name, run_summary in summary_df.iterrows():
|
for run_name, run_summary in summary_df.iterrows():
|
||||||
print(run_name)
|
print(run_name)
|
||||||
print(run_summary)
|
print(run_summary)
|
||||||
@@ -126,12 +165,19 @@ def run_multiple_inferences(summary_df, train_experiment, test_experiment,
|
|||||||
train_run = Run(train_experiment, run_id)
|
train_run = Run(train_experiment, run_id)
|
||||||
|
|
||||||
test_run = run_inference(
|
test_run = run_inference(
|
||||||
test_experiment, compute_target, script_folder, train_run,
|
test_experiment,
|
||||||
test_dataset, lookback_dataset, max_horizon, target_column_name,
|
compute_target,
|
||||||
time_column_name, freq)
|
script_folder,
|
||||||
|
train_run,
|
||||||
|
test_dataset,
|
||||||
|
lookback_dataset,
|
||||||
|
max_horizon,
|
||||||
|
target_column_name,
|
||||||
|
time_column_name,
|
||||||
|
freq,
|
||||||
|
)
|
||||||
|
|
||||||
print(test_run)
|
print(test_run)
|
||||||
summary_df.loc[summary_df.run_id == run_id,
|
summary_df.loc[summary_df.run_id == run_id, "test_run_id"] = test_run.id
|
||||||
'test_run_id'] = test_run.id
|
|
||||||
|
|
||||||
return summary_df
|
return summary_df
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import argparse
|
import argparse
|
||||||
|
import os
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
@@ -10,10 +11,22 @@ from sklearn.metrics import mean_absolute_error, mean_squared_error
|
|||||||
from azureml.automl.runtime.shared.score import scoring, constants
|
from azureml.automl.runtime.shared.score import scoring, constants
|
||||||
from azureml.core import Run
|
from azureml.core import Run
|
||||||
|
|
||||||
|
try:
|
||||||
|
import torch
|
||||||
|
|
||||||
def align_outputs(y_predicted, X_trans, X_test, y_test,
|
_torch_present = True
|
||||||
predicted_column_name='predicted',
|
except ImportError:
|
||||||
horizon_colname='horizon_origin'):
|
_torch_present = False
|
||||||
|
|
||||||
|
|
||||||
|
def align_outputs(
|
||||||
|
y_predicted,
|
||||||
|
X_trans,
|
||||||
|
X_test,
|
||||||
|
y_test,
|
||||||
|
predicted_column_name="predicted",
|
||||||
|
horizon_colname="horizon_origin",
|
||||||
|
):
|
||||||
"""
|
"""
|
||||||
Demonstrates how to get the output aligned to the inputs
|
Demonstrates how to get the output aligned to the inputs
|
||||||
using pandas indexes. Helps understand what happened if
|
using pandas indexes. Helps understand what happened if
|
||||||
@@ -25,9 +38,13 @@ def align_outputs(y_predicted, X_trans, X_test, y_test,
|
|||||||
* model was asked to predict past max_horizon -> increase max horizon
|
* model was asked to predict past max_horizon -> increase max horizon
|
||||||
* data at start of X_test was needed for lags -> provide previous periods
|
* data at start of X_test was needed for lags -> provide previous periods
|
||||||
"""
|
"""
|
||||||
if (horizon_colname in X_trans):
|
if horizon_colname in X_trans:
|
||||||
df_fcst = pd.DataFrame({predicted_column_name: y_predicted,
|
df_fcst = pd.DataFrame(
|
||||||
horizon_colname: X_trans[horizon_colname]})
|
{
|
||||||
|
predicted_column_name: y_predicted,
|
||||||
|
horizon_colname: X_trans[horizon_colname],
|
||||||
|
}
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
df_fcst = pd.DataFrame({predicted_column_name: y_predicted})
|
df_fcst = pd.DataFrame({predicted_column_name: y_predicted})
|
||||||
|
|
||||||
@@ -40,20 +57,21 @@ def align_outputs(y_predicted, X_trans, X_test, y_test,
|
|||||||
|
|
||||||
# X_test_full's index does not include origin, so reset for merge
|
# X_test_full's index does not include origin, so reset for merge
|
||||||
df_fcst.reset_index(inplace=True)
|
df_fcst.reset_index(inplace=True)
|
||||||
X_test_full = X_test_full.reset_index().drop(columns='index')
|
X_test_full = X_test_full.reset_index().drop(columns="index")
|
||||||
together = df_fcst.merge(X_test_full, how='right')
|
together = df_fcst.merge(X_test_full, how="right")
|
||||||
|
|
||||||
# drop rows where prediction or actuals are nan
|
# drop rows where prediction or actuals are nan
|
||||||
# happens because of missing actuals
|
# happens because of missing actuals
|
||||||
# or at edges of time due to lags/rolling windows
|
# or at edges of time due to lags/rolling windows
|
||||||
clean = together[together[[target_column_name,
|
clean = together[
|
||||||
predicted_column_name]].notnull().all(axis=1)]
|
together[[target_column_name, predicted_column_name]].notnull().all(axis=1)
|
||||||
return(clean)
|
]
|
||||||
|
return clean
|
||||||
|
|
||||||
|
|
||||||
def do_rolling_forecast_with_lookback(fitted_model, X_test, y_test,
|
def do_rolling_forecast_with_lookback(
|
||||||
max_horizon, X_lookback, y_lookback,
|
fitted_model, X_test, y_test, max_horizon, X_lookback, y_lookback, freq="D"
|
||||||
freq='D'):
|
):
|
||||||
"""
|
"""
|
||||||
Produce forecasts on a rolling origin over the given test set.
|
Produce forecasts on a rolling origin over the given test set.
|
||||||
|
|
||||||
@@ -64,7 +82,7 @@ def do_rolling_forecast_with_lookback(fitted_model, X_test, y_test,
|
|||||||
origin time for constructing lag features.
|
origin time for constructing lag features.
|
||||||
|
|
||||||
This function returns a concatenated DataFrame of rolling forecasts.
|
This function returns a concatenated DataFrame of rolling forecasts.
|
||||||
"""
|
"""
|
||||||
print("Using lookback of size: ", y_lookback.size)
|
print("Using lookback of size: ", y_lookback.size)
|
||||||
df_list = []
|
df_list = []
|
||||||
origin_time = X_test[time_column_name].min()
|
origin_time = X_test[time_column_name].min()
|
||||||
@@ -75,23 +93,28 @@ def do_rolling_forecast_with_lookback(fitted_model, X_test, y_test,
|
|||||||
horizon_time = origin_time + max_horizon * to_offset(freq)
|
horizon_time = origin_time + max_horizon * to_offset(freq)
|
||||||
|
|
||||||
# Extract test data from an expanding window up-to the horizon
|
# Extract test data from an expanding window up-to the horizon
|
||||||
expand_wind = (X[time_column_name] < horizon_time)
|
expand_wind = X[time_column_name] < horizon_time
|
||||||
X_test_expand = X[expand_wind]
|
X_test_expand = X[expand_wind]
|
||||||
y_query_expand = np.zeros(len(X_test_expand)).astype(np.float)
|
y_query_expand = np.zeros(len(X_test_expand)).astype(np.float)
|
||||||
y_query_expand.fill(np.NaN)
|
y_query_expand.fill(np.NaN)
|
||||||
|
|
||||||
if origin_time != X[time_column_name].min():
|
if origin_time != X[time_column_name].min():
|
||||||
# Set the context by including actuals up-to the origin time
|
# Set the context by including actuals up-to the origin time
|
||||||
test_context_expand_wind = (X[time_column_name] < origin_time)
|
test_context_expand_wind = X[time_column_name] < origin_time
|
||||||
context_expand_wind = (
|
context_expand_wind = X_test_expand[time_column_name] < origin_time
|
||||||
X_test_expand[time_column_name] < origin_time)
|
|
||||||
y_query_expand[context_expand_wind] = y[test_context_expand_wind]
|
y_query_expand[context_expand_wind] = y[test_context_expand_wind]
|
||||||
|
|
||||||
# Print some debug info
|
# Print some debug info
|
||||||
print("Horizon_time:", horizon_time,
|
print(
|
||||||
" origin_time: ", origin_time,
|
"Horizon_time:",
|
||||||
" max_horizon: ", max_horizon,
|
horizon_time,
|
||||||
" freq: ", freq)
|
" origin_time: ",
|
||||||
|
origin_time,
|
||||||
|
" max_horizon: ",
|
||||||
|
max_horizon,
|
||||||
|
" freq: ",
|
||||||
|
freq,
|
||||||
|
)
|
||||||
print("expand_wind: ", expand_wind)
|
print("expand_wind: ", expand_wind)
|
||||||
print("y_query_expand")
|
print("y_query_expand")
|
||||||
print(y_query_expand)
|
print(y_query_expand)
|
||||||
@@ -115,12 +138,16 @@ def do_rolling_forecast_with_lookback(fitted_model, X_test, y_test,
|
|||||||
# Align forecast with test set for dates within
|
# Align forecast with test set for dates within
|
||||||
# the current rolling window
|
# the current rolling window
|
||||||
trans_tindex = X_trans.index.get_level_values(time_column_name)
|
trans_tindex = X_trans.index.get_level_values(time_column_name)
|
||||||
trans_roll_wind = (trans_tindex >= origin_time) & (
|
trans_roll_wind = (trans_tindex >= origin_time) & (trans_tindex < horizon_time)
|
||||||
trans_tindex < horizon_time)
|
|
||||||
test_roll_wind = expand_wind & (X[time_column_name] >= origin_time)
|
test_roll_wind = expand_wind & (X[time_column_name] >= origin_time)
|
||||||
df_list.append(align_outputs(
|
df_list.append(
|
||||||
y_fcst[trans_roll_wind], X_trans[trans_roll_wind],
|
align_outputs(
|
||||||
X[test_roll_wind], y[test_roll_wind]))
|
y_fcst[trans_roll_wind],
|
||||||
|
X_trans[trans_roll_wind],
|
||||||
|
X[test_roll_wind],
|
||||||
|
y[test_roll_wind],
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
# Advance the origin time
|
# Advance the origin time
|
||||||
origin_time = horizon_time
|
origin_time = horizon_time
|
||||||
@@ -128,7 +155,7 @@ def do_rolling_forecast_with_lookback(fitted_model, X_test, y_test,
|
|||||||
return pd.concat(df_list, ignore_index=True)
|
return pd.concat(df_list, ignore_index=True)
|
||||||
|
|
||||||
|
|
||||||
def do_rolling_forecast(fitted_model, X_test, y_test, max_horizon, freq='D'):
|
def do_rolling_forecast(fitted_model, X_test, y_test, max_horizon, freq="D"):
|
||||||
"""
|
"""
|
||||||
Produce forecasts on a rolling origin over the given test set.
|
Produce forecasts on a rolling origin over the given test set.
|
||||||
|
|
||||||
@@ -139,7 +166,7 @@ def do_rolling_forecast(fitted_model, X_test, y_test, max_horizon, freq='D'):
|
|||||||
origin time for constructing lag features.
|
origin time for constructing lag features.
|
||||||
|
|
||||||
This function returns a concatenated DataFrame of rolling forecasts.
|
This function returns a concatenated DataFrame of rolling forecasts.
|
||||||
"""
|
"""
|
||||||
df_list = []
|
df_list = []
|
||||||
origin_time = X_test[time_column_name].min()
|
origin_time = X_test[time_column_name].min()
|
||||||
while origin_time <= X_test[time_column_name].max():
|
while origin_time <= X_test[time_column_name].max():
|
||||||
@@ -147,24 +174,28 @@ def do_rolling_forecast(fitted_model, X_test, y_test, max_horizon, freq='D'):
|
|||||||
horizon_time = origin_time + max_horizon * to_offset(freq)
|
horizon_time = origin_time + max_horizon * to_offset(freq)
|
||||||
|
|
||||||
# Extract test data from an expanding window up-to the horizon
|
# Extract test data from an expanding window up-to the horizon
|
||||||
expand_wind = (X_test[time_column_name] < horizon_time)
|
expand_wind = X_test[time_column_name] < horizon_time
|
||||||
X_test_expand = X_test[expand_wind]
|
X_test_expand = X_test[expand_wind]
|
||||||
y_query_expand = np.zeros(len(X_test_expand)).astype(np.float)
|
y_query_expand = np.zeros(len(X_test_expand)).astype(np.float)
|
||||||
y_query_expand.fill(np.NaN)
|
y_query_expand.fill(np.NaN)
|
||||||
|
|
||||||
if origin_time != X_test[time_column_name].min():
|
if origin_time != X_test[time_column_name].min():
|
||||||
# Set the context by including actuals up-to the origin time
|
# Set the context by including actuals up-to the origin time
|
||||||
test_context_expand_wind = (X_test[time_column_name] < origin_time)
|
test_context_expand_wind = X_test[time_column_name] < origin_time
|
||||||
context_expand_wind = (
|
context_expand_wind = X_test_expand[time_column_name] < origin_time
|
||||||
X_test_expand[time_column_name] < origin_time)
|
y_query_expand[context_expand_wind] = y_test[test_context_expand_wind]
|
||||||
y_query_expand[context_expand_wind] = y_test[
|
|
||||||
test_context_expand_wind]
|
|
||||||
|
|
||||||
# Print some debug info
|
# Print some debug info
|
||||||
print("Horizon_time:", horizon_time,
|
print(
|
||||||
" origin_time: ", origin_time,
|
"Horizon_time:",
|
||||||
" max_horizon: ", max_horizon,
|
horizon_time,
|
||||||
" freq: ", freq)
|
" origin_time: ",
|
||||||
|
origin_time,
|
||||||
|
" max_horizon: ",
|
||||||
|
max_horizon,
|
||||||
|
" freq: ",
|
||||||
|
freq,
|
||||||
|
)
|
||||||
print("expand_wind: ", expand_wind)
|
print("expand_wind: ", expand_wind)
|
||||||
print("y_query_expand")
|
print("y_query_expand")
|
||||||
print(y_query_expand)
|
print(y_query_expand)
|
||||||
@@ -186,14 +217,16 @@ def do_rolling_forecast(fitted_model, X_test, y_test, max_horizon, freq='D'):
|
|||||||
# Align forecast with test set for dates within the
|
# Align forecast with test set for dates within the
|
||||||
# current rolling window
|
# current rolling window
|
||||||
trans_tindex = X_trans.index.get_level_values(time_column_name)
|
trans_tindex = X_trans.index.get_level_values(time_column_name)
|
||||||
trans_roll_wind = (trans_tindex >= origin_time) & (
|
trans_roll_wind = (trans_tindex >= origin_time) & (trans_tindex < horizon_time)
|
||||||
trans_tindex < horizon_time)
|
test_roll_wind = expand_wind & (X_test[time_column_name] >= origin_time)
|
||||||
test_roll_wind = expand_wind & (
|
df_list.append(
|
||||||
X_test[time_column_name] >= origin_time)
|
align_outputs(
|
||||||
df_list.append(align_outputs(y_fcst[trans_roll_wind],
|
y_fcst[trans_roll_wind],
|
||||||
X_trans[trans_roll_wind],
|
X_trans[trans_roll_wind],
|
||||||
X_test[test_roll_wind],
|
X_test[test_roll_wind],
|
||||||
y_test[test_roll_wind]))
|
y_test[test_roll_wind],
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
# Advance the origin time
|
# Advance the origin time
|
||||||
origin_time = horizon_time
|
origin_time = horizon_time
|
||||||
@@ -221,23 +254,37 @@ def MAPE(actual, pred):
|
|||||||
return np.mean(APE(actual_safe, pred_safe))
|
return np.mean(APE(actual_safe, pred_safe))
|
||||||
|
|
||||||
|
|
||||||
|
def map_location_cuda(storage, loc):
|
||||||
|
return storage.cuda()
|
||||||
|
|
||||||
|
|
||||||
parser = argparse.ArgumentParser()
|
parser = argparse.ArgumentParser()
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
'--max_horizon', type=int, dest='max_horizon',
|
"--max_horizon",
|
||||||
default=10, help='Max Horizon for forecasting')
|
type=int,
|
||||||
|
dest="max_horizon",
|
||||||
|
default=10,
|
||||||
|
help="Max Horizon for forecasting",
|
||||||
|
)
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
'--target_column_name', type=str, dest='target_column_name',
|
"--target_column_name",
|
||||||
help='Target Column Name')
|
type=str,
|
||||||
|
dest="target_column_name",
|
||||||
|
help="Target Column Name",
|
||||||
|
)
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
'--time_column_name', type=str, dest='time_column_name',
|
"--time_column_name", type=str, dest="time_column_name", help="Time Column Name"
|
||||||
help='Time Column Name')
|
)
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
'--frequency', type=str, dest='freq',
|
"--frequency", type=str, dest="freq", help="Frequency of prediction"
|
||||||
help='Frequency of prediction')
|
)
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
'--model_path', type=str, dest='model_path',
|
"--model_path",
|
||||||
default='model.pkl', help='Filename of model to be loaded')
|
type=str,
|
||||||
|
dest="model_path",
|
||||||
|
default="model.pkl",
|
||||||
|
help="Filename of model to be loaded",
|
||||||
|
)
|
||||||
|
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
max_horizon = args.max_horizon
|
max_horizon = args.max_horizon
|
||||||
@@ -246,8 +293,7 @@ time_column_name = args.time_column_name
|
|||||||
freq = args.freq
|
freq = args.freq
|
||||||
model_path = args.model_path
|
model_path = args.model_path
|
||||||
|
|
||||||
|
print("args passed are: ")
|
||||||
print('args passed are: ')
|
|
||||||
print(max_horizon)
|
print(max_horizon)
|
||||||
print(target_column_name)
|
print(target_column_name)
|
||||||
print(time_column_name)
|
print(time_column_name)
|
||||||
@@ -256,28 +302,41 @@ print(model_path)
|
|||||||
|
|
||||||
run = Run.get_context()
|
run = Run.get_context()
|
||||||
# get input dataset by name
|
# get input dataset by name
|
||||||
test_dataset = run.input_datasets['test_data']
|
test_dataset = run.input_datasets["test_data"]
|
||||||
lookback_dataset = run.input_datasets['lookback_data']
|
lookback_dataset = run.input_datasets["lookback_data"]
|
||||||
|
|
||||||
grain_column_names = []
|
grain_column_names = []
|
||||||
|
|
||||||
df = test_dataset.to_pandas_dataframe()
|
df = test_dataset.to_pandas_dataframe()
|
||||||
|
|
||||||
print('Read df')
|
print("Read df")
|
||||||
print(df)
|
print(df)
|
||||||
|
|
||||||
X_test_df = test_dataset.drop_columns(columns=[target_column_name])
|
X_test_df = test_dataset.drop_columns(columns=[target_column_name])
|
||||||
y_test_df = test_dataset.with_timestamp_columns(
|
y_test_df = test_dataset.with_timestamp_columns(None).keep_columns(
|
||||||
None).keep_columns(columns=[target_column_name])
|
columns=[target_column_name]
|
||||||
|
)
|
||||||
|
|
||||||
X_lookback_df = lookback_dataset.drop_columns(columns=[target_column_name])
|
X_lookback_df = lookback_dataset.drop_columns(columns=[target_column_name])
|
||||||
y_lookback_df = lookback_dataset.with_timestamp_columns(
|
y_lookback_df = lookback_dataset.with_timestamp_columns(None).keep_columns(
|
||||||
None).keep_columns(columns=[target_column_name])
|
columns=[target_column_name]
|
||||||
|
)
|
||||||
|
|
||||||
fitted_model = joblib.load(model_path)
|
_, ext = os.path.splitext(model_path)
|
||||||
|
if ext == ".pt":
|
||||||
|
# Load the fc-tcn torch model.
|
||||||
|
assert _torch_present
|
||||||
|
if torch.cuda.is_available():
|
||||||
|
map_location = map_location_cuda
|
||||||
|
else:
|
||||||
|
map_location = "cpu"
|
||||||
|
with open(model_path, "rb") as fh:
|
||||||
|
fitted_model = torch.load(fh, map_location=map_location)
|
||||||
|
else:
|
||||||
|
# Load the sklearn pipeline.
|
||||||
|
fitted_model = joblib.load(model_path)
|
||||||
|
|
||||||
|
if hasattr(fitted_model, "get_lookback"):
|
||||||
if hasattr(fitted_model, 'get_lookback'):
|
|
||||||
lookback = fitted_model.get_lookback()
|
lookback = fitted_model.get_lookback()
|
||||||
df_all = do_rolling_forecast_with_lookback(
|
df_all = do_rolling_forecast_with_lookback(
|
||||||
fitted_model,
|
fitted_model,
|
||||||
@@ -286,26 +345,28 @@ if hasattr(fitted_model, 'get_lookback'):
|
|||||||
max_horizon,
|
max_horizon,
|
||||||
X_lookback_df.to_pandas_dataframe()[-lookback:],
|
X_lookback_df.to_pandas_dataframe()[-lookback:],
|
||||||
y_lookback_df.to_pandas_dataframe().values.T[0][-lookback:],
|
y_lookback_df.to_pandas_dataframe().values.T[0][-lookback:],
|
||||||
freq)
|
freq,
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
df_all = do_rolling_forecast(
|
df_all = do_rolling_forecast(
|
||||||
fitted_model,
|
fitted_model,
|
||||||
X_test_df.to_pandas_dataframe(),
|
X_test_df.to_pandas_dataframe(),
|
||||||
y_test_df.to_pandas_dataframe().values.T[0],
|
y_test_df.to_pandas_dataframe().values.T[0],
|
||||||
max_horizon,
|
max_horizon,
|
||||||
freq)
|
freq,
|
||||||
|
)
|
||||||
|
|
||||||
print(df_all)
|
print(df_all)
|
||||||
|
|
||||||
print("target values:::")
|
print("target values:::")
|
||||||
print(df_all[target_column_name])
|
print(df_all[target_column_name])
|
||||||
print("predicted values:::")
|
print("predicted values:::")
|
||||||
print(df_all['predicted'])
|
print(df_all["predicted"])
|
||||||
|
|
||||||
# Use the AutoML scoring module
|
# Use the AutoML scoring module
|
||||||
regression_metrics = list(constants.REGRESSION_SCALAR_SET)
|
regression_metrics = list(constants.REGRESSION_SCALAR_SET)
|
||||||
y_test = np.array(df_all[target_column_name])
|
y_test = np.array(df_all[target_column_name])
|
||||||
y_pred = np.array(df_all['predicted'])
|
y_pred = np.array(df_all["predicted"])
|
||||||
scores = scoring.score_regression(y_test, y_pred, regression_metrics)
|
scores = scoring.score_regression(y_test, y_pred, regression_metrics)
|
||||||
|
|
||||||
print("scores:")
|
print("scores:")
|
||||||
@@ -315,12 +376,11 @@ for key, value in scores.items():
|
|||||||
run.log(key, value)
|
run.log(key, value)
|
||||||
|
|
||||||
print("Simple forecasting model")
|
print("Simple forecasting model")
|
||||||
rmse = np.sqrt(mean_squared_error(
|
rmse = np.sqrt(mean_squared_error(df_all[target_column_name], df_all["predicted"]))
|
||||||
df_all[target_column_name], df_all['predicted']))
|
|
||||||
print("[Test Data] \nRoot Mean squared error: %.2f" % rmse)
|
print("[Test Data] \nRoot Mean squared error: %.2f" % rmse)
|
||||||
mae = mean_absolute_error(df_all[target_column_name], df_all['predicted'])
|
mae = mean_absolute_error(df_all[target_column_name], df_all["predicted"])
|
||||||
print('mean_absolute_error score: %.2f' % mae)
|
print("mean_absolute_error score: %.2f" % mae)
|
||||||
print('MAPE: %.2f' % MAPE(df_all[target_column_name], df_all['predicted']))
|
print("MAPE: %.2f" % MAPE(df_all[target_column_name], df_all["predicted"]))
|
||||||
|
|
||||||
run.log('rmse', rmse)
|
run.log("rmse", rmse)
|
||||||
run.log('mae', mae)
|
run.log("mae", mae)
|
||||||
|
|||||||
@@ -71,7 +71,8 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"from azureml.core import Workspace, Experiment, Dataset\n",
|
"from azureml.core import Workspace, Experiment, Dataset\n",
|
||||||
"from azureml.train.automl import AutoMLConfig\n",
|
"from azureml.train.automl import AutoMLConfig\n",
|
||||||
"from datetime import datetime"
|
"from datetime import datetime\n",
|
||||||
|
"from azureml.automl.core.featurization import FeaturizationConfig"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -87,7 +88,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"print(\"This notebook was created using version 1.12.0 of the Azure ML SDK\")\n",
|
"print(\"This notebook was created using version 1.37.0 of the Azure ML SDK\")\n",
|
||||||
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -107,19 +108,19 @@
|
|||||||
"ws = Workspace.from_config()\n",
|
"ws = Workspace.from_config()\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# choose a name for the run history container in the workspace\n",
|
"# choose a name for the run history container in the workspace\n",
|
||||||
"experiment_name = 'automl-bikeshareforecasting'\n",
|
"experiment_name = \"automl-bikeshareforecasting\"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"experiment = Experiment(ws, experiment_name)\n",
|
"experiment = Experiment(ws, experiment_name)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"output = {}\n",
|
"output = {}\n",
|
||||||
"output['Subscription ID'] = ws.subscription_id\n",
|
"output[\"Subscription ID\"] = ws.subscription_id\n",
|
||||||
"output['Workspace'] = ws.name\n",
|
"output[\"Workspace\"] = ws.name\n",
|
||||||
"output['SKU'] = ws.sku\n",
|
"output[\"SKU\"] = ws.sku\n",
|
||||||
"output['Resource Group'] = ws.resource_group\n",
|
"output[\"Resource Group\"] = ws.resource_group\n",
|
||||||
"output['Location'] = ws.location\n",
|
"output[\"Location\"] = ws.location\n",
|
||||||
"output['Run History Name'] = experiment_name\n",
|
"output[\"Run History Name\"] = experiment_name\n",
|
||||||
"pd.set_option('display.max_colwidth', -1)\n",
|
"pd.set_option(\"display.max_colwidth\", -1)\n",
|
||||||
"outputDf = pd.DataFrame(data = output, index = [''])\n",
|
"outputDf = pd.DataFrame(data=output, index=[\"\"])\n",
|
||||||
"outputDf.T"
|
"outputDf.T"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -129,9 +130,12 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"## Compute\n",
|
"## Compute\n",
|
||||||
"You will need to create a [compute target](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-set-up-training-targets#amlcompute) for your AutoML run. In this tutorial, you create AmlCompute as your training compute resource.\n",
|
"You will need to create a [compute target](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-set-up-training-targets#amlcompute) for your AutoML run. In this tutorial, you create AmlCompute as your training compute resource.\n",
|
||||||
|
"\n",
|
||||||
|
"> 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.\n",
|
||||||
|
"\n",
|
||||||
"#### Creation of AmlCompute takes approximately 5 minutes. \n",
|
"#### Creation of AmlCompute takes approximately 5 minutes. \n",
|
||||||
"If the AmlCompute with that name is already in your workspace this code will skip the creation process.\n",
|
"If the AmlCompute with that name is already in your workspace this code will skip the creation process.\n",
|
||||||
"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."
|
"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](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -149,10 +153,11 @@
|
|||||||
"# Verify that cluster does not exist already\n",
|
"# Verify that cluster does not exist already\n",
|
||||||
"try:\n",
|
"try:\n",
|
||||||
" compute_target = ComputeTarget(workspace=ws, name=amlcompute_cluster_name)\n",
|
" compute_target = ComputeTarget(workspace=ws, name=amlcompute_cluster_name)\n",
|
||||||
" print('Found existing cluster, use it.')\n",
|
" print(\"Found existing cluster, use it.\")\n",
|
||||||
"except ComputeTargetException:\n",
|
"except ComputeTargetException:\n",
|
||||||
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_D2_V2',\n",
|
" compute_config = AmlCompute.provisioning_configuration(\n",
|
||||||
" max_nodes=4)\n",
|
" vm_size=\"STANDARD_DS12_V2\", max_nodes=4\n",
|
||||||
|
" )\n",
|
||||||
" compute_target = ComputeTarget.create(ws, amlcompute_cluster_name, compute_config)\n",
|
" compute_target = ComputeTarget.create(ws, amlcompute_cluster_name, compute_config)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"compute_target.wait_for_completion(show_output=True)"
|
"compute_target.wait_for_completion(show_output=True)"
|
||||||
@@ -174,7 +179,9 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"datastore = ws.get_default_datastore()\n",
|
"datastore = ws.get_default_datastore()\n",
|
||||||
"datastore.upload_files(files = ['./bike-no.csv'], target_path = 'dataset/', overwrite = True,show_progress = True)"
|
"datastore.upload_files(\n",
|
||||||
|
" files=[\"./bike-no.csv\"], target_path=\"dataset/\", overwrite=True, show_progress=True\n",
|
||||||
|
")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -194,8 +201,8 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"target_column_name = 'cnt'\n",
|
"target_column_name = \"cnt\"\n",
|
||||||
"time_column_name = 'date'"
|
"time_column_name = \"date\""
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -204,7 +211,13 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"dataset = Dataset.Tabular.from_delimited_files(path = [(datastore, 'dataset/bike-no.csv')]).with_timestamp_columns(fine_grain_timestamp=time_column_name) \n",
|
"dataset = Dataset.Tabular.from_delimited_files(\n",
|
||||||
|
" path=[(datastore, \"dataset/bike-no.csv\")]\n",
|
||||||
|
").with_timestamp_columns(fine_grain_timestamp=time_column_name)\n",
|
||||||
|
"\n",
|
||||||
|
"# Drop the columns 'casual' and 'registered' as these columns are a breakdown of the total and therefore a leak.\n",
|
||||||
|
"dataset = dataset.drop_columns(columns=[\"casual\", \"registered\"])\n",
|
||||||
|
"\n",
|
||||||
"dataset.take(5).to_pandas_dataframe().reset_index(drop=True)"
|
"dataset.take(5).to_pandas_dataframe().reset_index(drop=True)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -251,7 +264,7 @@
|
|||||||
"|**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).|\n",
|
"|**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).|\n",
|
||||||
"|**country_or_region_for_holidays**|The country/region used to generate holiday features. These should be ISO 3166 two-letter country/region codes (i.e. 'US', 'GB').|\n",
|
"|**country_or_region_for_holidays**|The country/region used to generate holiday features. These should be ISO 3166 two-letter country/region codes (i.e. 'US', 'GB').|\n",
|
||||||
"|**target_lags**|The target_lags specifies how far back we will construct the lags of the target variable.|\n",
|
"|**target_lags**|The target_lags specifies how far back we will construct the lags of the target variable.|\n",
|
||||||
"|**drop_column_names**|Name(s) of columns to drop prior to modeling|"
|
"|**freq**|Forecast frequency. This optional parameter represents the period with which the forecast is desired, for example, daily, weekly, yearly, etc. Use this parameter for the correction of time series containing irregular data points or for padding of short time series. The frequency needs to be a pandas offset alias. Please refer to [pandas documentation](https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#dateoffset-objects) for more information."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -296,6 +309,25 @@
|
|||||||
"forecast_horizon = 14"
|
"forecast_horizon = 14"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Convert prediction type to integer\n",
|
||||||
|
"The featurization configuration can be used to change the default prediction type from decimal numbers to integer. This customization can be used in the scenario when the target column is expected to contain whole values as the number of rented bikes per day."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"featurization_config = FeaturizationConfig()\n",
|
||||||
|
"# Force the target column, to be integer type.\n",
|
||||||
|
"featurization_config.add_prediction_transform_type(\"Integer\")"
|
||||||
|
]
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
@@ -310,27 +342,31 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from azureml.automl.core.forecasting_parameters import ForecastingParameters\n",
|
"from azureml.automl.core.forecasting_parameters import ForecastingParameters\n",
|
||||||
|
"\n",
|
||||||
"forecasting_parameters = ForecastingParameters(\n",
|
"forecasting_parameters = ForecastingParameters(\n",
|
||||||
" time_column_name=time_column_name,\n",
|
" time_column_name=time_column_name,\n",
|
||||||
" forecast_horizon=forecast_horizon,\n",
|
" forecast_horizon=forecast_horizon,\n",
|
||||||
" country_or_region_for_holidays='US', # set country_or_region will trigger holiday featurizer\n",
|
" country_or_region_for_holidays=\"US\", # set country_or_region will trigger holiday featurizer\n",
|
||||||
" target_lags='auto', # use heuristic based lag setting \n",
|
" target_lags=\"auto\", # use heuristic based lag setting\n",
|
||||||
" drop_column_names=['casual', 'registered'] # these columns are a breakdown of the total and therefore a leak\n",
|
" freq=\"D\", # Set the forecast frequency to be daily\n",
|
||||||
")\n",
|
")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"automl_config = AutoMLConfig(task='forecasting', \n",
|
"automl_config = AutoMLConfig(\n",
|
||||||
" primary_metric='normalized_root_mean_squared_error',\n",
|
" task=\"forecasting\",\n",
|
||||||
" blocked_models = ['ExtremeRandomTrees'], \n",
|
" primary_metric=\"normalized_root_mean_squared_error\",\n",
|
||||||
" experiment_timeout_hours=0.3,\n",
|
" featurization=featurization_config,\n",
|
||||||
" training_data=train,\n",
|
" blocked_models=[\"ExtremeRandomTrees\"],\n",
|
||||||
" label_column_name=target_column_name,\n",
|
" experiment_timeout_hours=0.3,\n",
|
||||||
" compute_target=compute_target,\n",
|
" training_data=train,\n",
|
||||||
" enable_early_stopping=True,\n",
|
" label_column_name=target_column_name,\n",
|
||||||
" n_cross_validations=3, \n",
|
" compute_target=compute_target,\n",
|
||||||
" max_concurrent_iterations=4,\n",
|
" enable_early_stopping=True,\n",
|
||||||
" max_cores_per_iteration=-1,\n",
|
" n_cross_validations=3,\n",
|
||||||
" verbosity=logging.INFO,\n",
|
" max_concurrent_iterations=4,\n",
|
||||||
" forecasting_parameters=forecasting_parameters)"
|
" max_cores_per_iteration=-1,\n",
|
||||||
|
" verbosity=logging.INFO,\n",
|
||||||
|
" forecasting_parameters=forecasting_parameters,\n",
|
||||||
|
")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -346,8 +382,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"remote_run = experiment.submit(automl_config, show_output=False)\n",
|
"remote_run = experiment.submit(automl_config, show_output=False)"
|
||||||
"remote_run"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -392,7 +427,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"fitted_model.named_steps['timeseriestransformer'].get_engineered_feature_names()"
|
"fitted_model.named_steps[\"timeseriestransformer\"].get_engineered_feature_names()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -417,7 +452,9 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"# Get the featurization summary as a list of JSON\n",
|
"# Get the featurization summary as a list of JSON\n",
|
||||||
"featurization_summary = fitted_model.named_steps['timeseriestransformer'].get_featurization_summary()\n",
|
"featurization_summary = fitted_model.named_steps[\n",
|
||||||
|
" \"timeseriestransformer\"\n",
|
||||||
|
"].get_featurization_summary()\n",
|
||||||
"# View the featurization summary as a pandas dataframe\n",
|
"# View the featurization summary as a pandas dataframe\n",
|
||||||
"pd.DataFrame.from_records(featurization_summary)"
|
"pd.DataFrame.from_records(featurization_summary)"
|
||||||
]
|
]
|
||||||
@@ -464,9 +501,9 @@
|
|||||||
"import os\n",
|
"import os\n",
|
||||||
"import shutil\n",
|
"import shutil\n",
|
||||||
"\n",
|
"\n",
|
||||||
"script_folder = os.path.join(os.getcwd(), 'forecast')\n",
|
"script_folder = os.path.join(os.getcwd(), \"forecast\")\n",
|
||||||
"os.makedirs(script_folder, exist_ok=True)\n",
|
"os.makedirs(script_folder, exist_ok=True)\n",
|
||||||
"shutil.copy('forecasting_script.py', script_folder)"
|
"shutil.copy(\"forecasting_script.py\", script_folder)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -484,7 +521,9 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"from run_forecast import run_rolling_forecast\n",
|
"from run_forecast import run_rolling_forecast\n",
|
||||||
"\n",
|
"\n",
|
||||||
"remote_run = run_rolling_forecast(test_experiment, compute_target, best_run, test, target_column_name)\n",
|
"remote_run = run_rolling_forecast(\n",
|
||||||
|
" test_experiment, compute_target, best_run, test, target_column_name\n",
|
||||||
|
")\n",
|
||||||
"remote_run"
|
"remote_run"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -501,7 +540,7 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"### Download the prediction result for metrics calcuation\n",
|
"### Download the prediction result for metrics calculation\n",
|
||||||
"The test data with predictions are saved in artifact outputs/predictions.csv. You can download it and calculation some error metrics for the forecasts and vizualize the predictions vs. the actuals."
|
"The test data with predictions are saved in artifact outputs/predictions.csv. You can download it and calculation some error metrics for the forecasts and vizualize the predictions vs. the actuals."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -511,8 +550,8 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"remote_run.download_file('outputs/predictions.csv', 'predictions.csv')\n",
|
"remote_run.download_file(\"outputs/predictions.csv\", \"predictions.csv\")\n",
|
||||||
"df_all = pd.read_csv('predictions.csv')"
|
"df_all = pd.read_csv(\"predictions.csv\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -529,18 +568,23 @@
|
|||||||
"# use automl metrics module\n",
|
"# use automl metrics module\n",
|
||||||
"scores = scoring.score_regression(\n",
|
"scores = scoring.score_regression(\n",
|
||||||
" y_test=df_all[target_column_name],\n",
|
" y_test=df_all[target_column_name],\n",
|
||||||
" y_pred=df_all['predicted'],\n",
|
" y_pred=df_all[\"predicted\"],\n",
|
||||||
" metrics=list(constants.Metric.SCALAR_REGRESSION_SET))\n",
|
" metrics=list(constants.Metric.SCALAR_REGRESSION_SET),\n",
|
||||||
|
")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"print(\"[Test data scores]\\n\")\n",
|
"print(\"[Test data scores]\\n\")\n",
|
||||||
"for key, value in scores.items(): \n",
|
"for key, value in scores.items():\n",
|
||||||
" print('{}: {:.3f}'.format(key, value))\n",
|
" print(\"{}: {:.3f}\".format(key, value))\n",
|
||||||
" \n",
|
"\n",
|
||||||
"# Plot outputs\n",
|
"# Plot outputs\n",
|
||||||
"%matplotlib inline\n",
|
"%matplotlib inline\n",
|
||||||
"test_pred = plt.scatter(df_all[target_column_name], df_all['predicted'], color='b')\n",
|
"test_pred = plt.scatter(df_all[target_column_name], df_all[\"predicted\"], color=\"b\")\n",
|
||||||
"test_test = plt.scatter(df_all[target_column_name], df_all[target_column_name], color='g')\n",
|
"test_test = plt.scatter(\n",
|
||||||
"plt.legend((test_pred, test_test), ('prediction', 'truth'), loc='upper left', fontsize=8)\n",
|
" df_all[target_column_name], df_all[target_column_name], color=\"g\"\n",
|
||||||
|
")\n",
|
||||||
|
"plt.legend(\n",
|
||||||
|
" (test_pred, test_test), (\"prediction\", \"truth\"), loc=\"upper left\", fontsize=8\n",
|
||||||
|
")\n",
|
||||||
"plt.show()"
|
"plt.show()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -548,6 +592,9 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
|
"For more details on what metrics are included and how they are calculated, please refer to [supported metrics](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-understand-automated-ml#regressionforecasting-metrics). You could also calculate residuals, like described [here](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-understand-automated-ml#residuals).\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
"Since we did a rolling evaluation on the test set, we can analyze the predictions by their forecast horizon relative to the rolling origin. The model was initially trained at a forecast horizon of 14, so each prediction from the model is associated with a horizon value from 1 to 14. The horizon values are in a column named, \"horizon_origin,\" in the prediction set. For example, we can calculate some of the error metrics grouped by the horizon:"
|
"Since we did a rolling evaluation on the test set, we can analyze the predictions by their forecast horizon relative to the rolling origin. The model was initially trained at a forecast horizon of 14, so each prediction from the model is associated with a horizon value from 1 to 14. The horizon values are in a column named, \"horizon_origin,\" in the prediction set. For example, we can calculate some of the error metrics grouped by the horizon:"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -558,10 +605,18 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from metrics_helper import MAPE, APE\n",
|
"from metrics_helper import MAPE, APE\n",
|
||||||
"df_all.groupby('horizon_origin').apply(\n",
|
"\n",
|
||||||
" lambda df: pd.Series({'MAPE': MAPE(df[target_column_name], df['predicted']),\n",
|
"df_all.groupby(\"horizon_origin\").apply(\n",
|
||||||
" 'RMSE': np.sqrt(mean_squared_error(df[target_column_name], df['predicted'])),\n",
|
" lambda df: pd.Series(\n",
|
||||||
" 'MAE': mean_absolute_error(df[target_column_name], df['predicted'])}))"
|
" {\n",
|
||||||
|
" \"MAPE\": MAPE(df[target_column_name], df[\"predicted\"]),\n",
|
||||||
|
" \"RMSE\": np.sqrt(\n",
|
||||||
|
" mean_squared_error(df[target_column_name], df[\"predicted\"])\n",
|
||||||
|
" ),\n",
|
||||||
|
" \"MAE\": mean_absolute_error(df[target_column_name], df[\"predicted\"]),\n",
|
||||||
|
" }\n",
|
||||||
|
" )\n",
|
||||||
|
")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -577,15 +632,18 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"df_all_APE = df_all.assign(APE=APE(df_all[target_column_name], df_all['predicted']))\n",
|
"df_all_APE = df_all.assign(APE=APE(df_all[target_column_name], df_all[\"predicted\"]))\n",
|
||||||
"APEs = [df_all_APE[df_all['horizon_origin'] == h].APE.values for h in range(1, forecast_horizon + 1)]\n",
|
"APEs = [\n",
|
||||||
|
" df_all_APE[df_all[\"horizon_origin\"] == h].APE.values\n",
|
||||||
|
" for h in range(1, forecast_horizon + 1)\n",
|
||||||
|
"]\n",
|
||||||
"\n",
|
"\n",
|
||||||
"%matplotlib inline\n",
|
"%matplotlib inline\n",
|
||||||
"plt.boxplot(APEs)\n",
|
"plt.boxplot(APEs)\n",
|
||||||
"plt.yscale('log')\n",
|
"plt.yscale(\"log\")\n",
|
||||||
"plt.xlabel('horizon')\n",
|
"plt.xlabel(\"horizon\")\n",
|
||||||
"plt.ylabel('APE (%)')\n",
|
"plt.ylabel(\"APE (%)\")\n",
|
||||||
"plt.title('Absolute Percentage Errors by Forecast Horizon')\n",
|
"plt.title(\"Absolute Percentage Errors by Forecast Horizon\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"plt.show()"
|
"plt.show()"
|
||||||
]
|
]
|
||||||
@@ -594,7 +652,7 @@
|
|||||||
"metadata": {
|
"metadata": {
|
||||||
"authors": [
|
"authors": [
|
||||||
{
|
{
|
||||||
"name": "erwright"
|
"name": "jialiu"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"category": "tutorial",
|
"category": "tutorial",
|
||||||
|
|||||||
@@ -1,36 +1,52 @@
|
|||||||
import argparse
|
import argparse
|
||||||
import azureml.train.automl
|
from azureml.core import Dataset, Run
|
||||||
from azureml.core import Run
|
|
||||||
from sklearn.externals import joblib
|
from sklearn.externals import joblib
|
||||||
|
|
||||||
|
|
||||||
parser = argparse.ArgumentParser()
|
parser = argparse.ArgumentParser()
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
'--target_column_name', type=str, dest='target_column_name',
|
"--target_column_name",
|
||||||
help='Target Column Name')
|
type=str,
|
||||||
|
dest="target_column_name",
|
||||||
|
help="Target Column Name",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--test_dataset", type=str, dest="test_dataset", help="Test Dataset"
|
||||||
|
)
|
||||||
|
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
target_column_name = args.target_column_name
|
target_column_name = args.target_column_name
|
||||||
|
test_dataset_id = args.test_dataset
|
||||||
|
|
||||||
run = Run.get_context()
|
run = Run.get_context()
|
||||||
# get input dataset by name
|
ws = run.experiment.workspace
|
||||||
test_dataset = run.input_datasets['test_data']
|
|
||||||
|
|
||||||
df = test_dataset.to_pandas_dataframe().reset_index(drop=True)
|
# get the input dataset by id
|
||||||
|
test_dataset = Dataset.get_by_id(ws, id=test_dataset_id)
|
||||||
|
|
||||||
X_test_df = test_dataset.drop_columns(columns=[target_column_name]).to_pandas_dataframe().reset_index(drop=True)
|
X_test_df = (
|
||||||
y_test_df = test_dataset.with_timestamp_columns(None).keep_columns(columns=[target_column_name]).to_pandas_dataframe()
|
test_dataset.drop_columns(columns=[target_column_name])
|
||||||
|
.to_pandas_dataframe()
|
||||||
|
.reset_index(drop=True)
|
||||||
|
)
|
||||||
|
y_test_df = (
|
||||||
|
test_dataset.with_timestamp_columns(None)
|
||||||
|
.keep_columns(columns=[target_column_name])
|
||||||
|
.to_pandas_dataframe()
|
||||||
|
)
|
||||||
|
|
||||||
fitted_model = joblib.load('model.pkl')
|
fitted_model = joblib.load("model.pkl")
|
||||||
|
|
||||||
y_pred, X_trans = fitted_model.rolling_evaluation(X_test_df, y_test_df.values)
|
y_pred, X_trans = fitted_model.rolling_evaluation(X_test_df, y_test_df.values)
|
||||||
|
|
||||||
# Add predictions, actuals, and horizon relative to rolling origin to the test feature data
|
# Add predictions, actuals, and horizon relative to rolling origin to the test feature data
|
||||||
assign_dict = {'horizon_origin': X_trans['horizon_origin'].values, 'predicted': y_pred,
|
assign_dict = {
|
||||||
target_column_name: y_test_df[target_column_name].values}
|
"horizon_origin": X_trans["horizon_origin"].values,
|
||||||
|
"predicted": y_pred,
|
||||||
|
target_column_name: y_test_df[target_column_name].values,
|
||||||
|
}
|
||||||
df_all = X_test_df.assign(**assign_dict)
|
df_all = X_test_df.assign(**assign_dict)
|
||||||
|
|
||||||
file_name = 'outputs/predictions.csv'
|
file_name = "outputs/predictions.csv"
|
||||||
export_csv = df_all.to_csv(file_name, header=True)
|
export_csv = df_all.to_csv(file_name, header=True)
|
||||||
|
|
||||||
# Upload the predictions into artifacts
|
# Upload the predictions into artifacts
|
||||||
|
|||||||
@@ -1,37 +1,40 @@
|
|||||||
from azureml.core import Environment
|
from azureml.core import ScriptRunConfig
|
||||||
from azureml.core.conda_dependencies import CondaDependencies
|
|
||||||
from azureml.train.estimator import Estimator
|
|
||||||
from azureml.core.run import Run
|
|
||||||
|
|
||||||
|
|
||||||
def run_rolling_forecast(test_experiment, compute_target, train_run, test_dataset,
|
def run_rolling_forecast(
|
||||||
target_column_name, inference_folder='./forecast'):
|
test_experiment,
|
||||||
condafile = inference_folder + '/condafile.yml'
|
compute_target,
|
||||||
train_run.download_file('outputs/model.pkl',
|
train_run,
|
||||||
inference_folder + '/model.pkl')
|
test_dataset,
|
||||||
train_run.download_file('outputs/conda_env_v_1_0_0.yml', condafile)
|
target_column_name,
|
||||||
|
inference_folder="./forecast",
|
||||||
|
):
|
||||||
|
train_run.download_file("outputs/model.pkl", inference_folder + "/model.pkl")
|
||||||
|
|
||||||
inference_env = Environment("myenv")
|
inference_env = train_run.get_environment()
|
||||||
inference_env.docker.enabled = True
|
|
||||||
inference_env.python.conda_dependencies = CondaDependencies(
|
|
||||||
conda_dependencies_file_path=condafile)
|
|
||||||
|
|
||||||
est = Estimator(source_directory=inference_folder,
|
config = ScriptRunConfig(
|
||||||
entry_script='forecasting_script.py',
|
source_directory=inference_folder,
|
||||||
script_params={
|
script="forecasting_script.py",
|
||||||
'--target_column_name': target_column_name
|
arguments=[
|
||||||
},
|
"--target_column_name",
|
||||||
inputs=[test_dataset.as_named_input('test_data')],
|
target_column_name,
|
||||||
compute_target=compute_target,
|
"--test_dataset",
|
||||||
environment_definition=inference_env)
|
test_dataset.as_named_input(test_dataset.name),
|
||||||
|
],
|
||||||
|
compute_target=compute_target,
|
||||||
|
environment=inference_env,
|
||||||
|
)
|
||||||
|
|
||||||
run = test_experiment.submit(est,
|
run = test_experiment.submit(
|
||||||
tags={
|
config,
|
||||||
'training_run_id': train_run.id,
|
tags={
|
||||||
'run_algorithm': train_run.properties['run_algorithm'],
|
"training_run_id": train_run.id,
|
||||||
'valid_score': train_run.properties['score'],
|
"run_algorithm": train_run.properties["run_algorithm"],
|
||||||
'primary_metric': train_run.properties['primary_metric']
|
"valid_score": train_run.properties["score"],
|
||||||
})
|
"primary_metric": train_run.properties["primary_metric"],
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
run.log("run_algorithm", run.tags['run_algorithm'])
|
run.log("run_algorithm", run.tags["run_algorithm"])
|
||||||
return run
|
return run
|
||||||
|
|||||||
@@ -24,10 +24,11 @@
|
|||||||
"_**Forecasting using the Energy Demand Dataset**_\n",
|
"_**Forecasting using the Energy Demand Dataset**_\n",
|
||||||
"\n",
|
"\n",
|
||||||
"## Contents\n",
|
"## Contents\n",
|
||||||
"1. [Introduction](#Introduction)\n",
|
"1. [Introduction](#introduction)\n",
|
||||||
"1. [Setup](#Setup)\n",
|
"1. [Setup](#setup)\n",
|
||||||
"1. [Data and Forecasting Configurations](#Data)\n",
|
"1. [Data and Forecasting Configurations](#data)\n",
|
||||||
"1. [Train](#Train)\n",
|
"1. [Train](#train)\n",
|
||||||
|
"1. [Generate and Evaluate the Forecast](#forecast)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Advanced Forecasting\n",
|
"Advanced Forecasting\n",
|
||||||
"1. [Advanced Training](#advanced_training)\n",
|
"1. [Advanced Training](#advanced_training)\n",
|
||||||
@@ -38,7 +39,7 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Introduction\n",
|
"# Introduction<a id=\"introduction\"></a>\n",
|
||||||
"\n",
|
"\n",
|
||||||
"In this example we use the associated New York City energy demand dataset to showcase how you can use AutoML for a simple forecasting problem and explore the results. The goal is predict the energy demand for the next 48 hours based on historic time-series data.\n",
|
"In this example we use the associated New York City energy demand dataset to showcase how you can use AutoML for a simple forecasting problem and explore the results. The goal is predict the energy demand for the next 48 hours based on historic time-series data.\n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -49,15 +50,16 @@
|
|||||||
"1. Configure AutoML using 'AutoMLConfig'\n",
|
"1. Configure AutoML using 'AutoMLConfig'\n",
|
||||||
"1. Train the model using AmlCompute\n",
|
"1. Train the model using AmlCompute\n",
|
||||||
"1. Explore the engineered features and results\n",
|
"1. Explore the engineered features and results\n",
|
||||||
|
"1. Generate the forecast and compute the out-of-sample accuracy metrics\n",
|
||||||
"1. Configuration and remote run of AutoML for a time-series model with lag and rolling window features\n",
|
"1. Configuration and remote run of AutoML for a time-series model with lag and rolling window features\n",
|
||||||
"1. Run and explore the forecast"
|
"1. Run and explore the forecast with lagging features"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Setup"
|
"# Setup<a id=\"setup\"></a>"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -97,7 +99,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"print(\"This notebook was created using version 1.12.0 of the Azure ML SDK\")\n",
|
"print(\"This notebook was created using version 1.37.0 of the Azure ML SDK\")\n",
|
||||||
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -117,7 +119,7 @@
|
|||||||
"ws = Workspace.from_config()\n",
|
"ws = Workspace.from_config()\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# choose a name for the run history container in the workspace\n",
|
"# choose a name for the run history container in the workspace\n",
|
||||||
"experiment_name = 'automl-forecasting-energydemand'\n",
|
"experiment_name = \"automl-forecasting-energydemand\"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# # project folder\n",
|
"# # project folder\n",
|
||||||
"# project_folder = './sample_projects/automl-forecasting-energy-demand'\n",
|
"# project_folder = './sample_projects/automl-forecasting-energy-demand'\n",
|
||||||
@@ -125,13 +127,13 @@
|
|||||||
"experiment = Experiment(ws, experiment_name)\n",
|
"experiment = Experiment(ws, experiment_name)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"output = {}\n",
|
"output = {}\n",
|
||||||
"output['Subscription ID'] = ws.subscription_id\n",
|
"output[\"Subscription ID\"] = ws.subscription_id\n",
|
||||||
"output['Workspace'] = ws.name\n",
|
"output[\"Workspace\"] = ws.name\n",
|
||||||
"output['Resource Group'] = ws.resource_group\n",
|
"output[\"Resource Group\"] = ws.resource_group\n",
|
||||||
"output['Location'] = ws.location\n",
|
"output[\"Location\"] = ws.location\n",
|
||||||
"output['Run History Name'] = experiment_name\n",
|
"output[\"Run History Name\"] = experiment_name\n",
|
||||||
"pd.set_option('display.max_colwidth', -1)\n",
|
"pd.set_option(\"display.max_colwidth\", -1)\n",
|
||||||
"outputDf = pd.DataFrame(data = output, index = [''])\n",
|
"outputDf = pd.DataFrame(data=output, index=[\"\"])\n",
|
||||||
"outputDf.T"
|
"outputDf.T"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -164,10 +166,11 @@
|
|||||||
"# Verify that cluster does not exist already\n",
|
"# Verify that cluster does not exist already\n",
|
||||||
"try:\n",
|
"try:\n",
|
||||||
" compute_target = ComputeTarget(workspace=ws, name=amlcompute_cluster_name)\n",
|
" compute_target = ComputeTarget(workspace=ws, name=amlcompute_cluster_name)\n",
|
||||||
" print('Found existing cluster, use it.')\n",
|
" print(\"Found existing cluster, use it.\")\n",
|
||||||
"except ComputeTargetException:\n",
|
"except ComputeTargetException:\n",
|
||||||
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_DS12_V2',\n",
|
" compute_config = AmlCompute.provisioning_configuration(\n",
|
||||||
" max_nodes=6)\n",
|
" vm_size=\"STANDARD_DS12_V2\", max_nodes=6\n",
|
||||||
|
" )\n",
|
||||||
" compute_target = ComputeTarget.create(ws, amlcompute_cluster_name, compute_config)\n",
|
" compute_target = ComputeTarget.create(ws, amlcompute_cluster_name, compute_config)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"compute_target.wait_for_completion(show_output=True)"
|
"compute_target.wait_for_completion(show_output=True)"
|
||||||
@@ -177,7 +180,7 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"# Data\n",
|
"# Data<a id=\"data\"></a>\n",
|
||||||
"\n",
|
"\n",
|
||||||
"We will use energy consumption [data from New York City](http://mis.nyiso.com/public/P-58Blist.htm) for model training. The data is stored in a tabular format and includes energy demand and basic weather data at an hourly frequency. \n",
|
"We will use energy consumption [data from New York City](http://mis.nyiso.com/public/P-58Blist.htm) for model training. The data is stored in a tabular format and includes energy demand and basic weather data at an hourly frequency. \n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -202,8 +205,8 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"target_column_name = 'demand'\n",
|
"target_column_name = \"demand\"\n",
|
||||||
"time_column_name = 'timeStamp'"
|
"time_column_name = \"timeStamp\""
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -212,7 +215,9 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"dataset = Dataset.Tabular.from_delimited_files(path = \"https://automlsamplenotebookdata.blob.core.windows.net/automl-sample-notebook-data/nyc_energy.csv\").with_timestamp_columns(fine_grain_timestamp=time_column_name) \n",
|
"dataset = Dataset.Tabular.from_delimited_files(\n",
|
||||||
|
" path=\"https://automlsamplenotebookdata.blob.core.windows.net/automl-sample-notebook-data/nyc_energy.csv\"\n",
|
||||||
|
").with_timestamp_columns(fine_grain_timestamp=time_column_name)\n",
|
||||||
"dataset.take(5).to_pandas_dataframe().reset_index(drop=True)"
|
"dataset.take(5).to_pandas_dataframe().reset_index(drop=True)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -301,14 +306,15 @@
|
|||||||
"|Property|Description|\n",
|
"|Property|Description|\n",
|
||||||
"|-|-|\n",
|
"|-|-|\n",
|
||||||
"|**time_column_name**|The name of your time column.|\n",
|
"|**time_column_name**|The name of your time column.|\n",
|
||||||
"|**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).|"
|
"|**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).|\n",
|
||||||
|
"|**freq**|Forecast frequency. This optional parameter represents the period with which the forecast is desired, for example, daily, weekly, yearly, etc. Use this parameter for the correction of time series containing irregular data points or for padding of short time series. The frequency needs to be a pandas offset alias. Please refer to [pandas documentation](https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#dateoffset-objects) for more information."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Train\n",
|
"# Train<a id=\"train\"></a>\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Instantiate an AutoMLConfig object. This config defines the settings and data used to run the experiment. We can provide extra configurations within 'automl_settings', for this forecasting task we add the forecasting parameters to hold all the additional forecasting parameters.\n",
|
"Instantiate an AutoMLConfig object. This config defines the settings and data used to run the experiment. We can provide extra configurations within 'automl_settings', for this forecasting task we add the forecasting parameters to hold all the additional forecasting parameters.\n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -340,21 +346,26 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from azureml.automl.core.forecasting_parameters import ForecastingParameters\n",
|
"from azureml.automl.core.forecasting_parameters import ForecastingParameters\n",
|
||||||
|
"\n",
|
||||||
"forecasting_parameters = ForecastingParameters(\n",
|
"forecasting_parameters = ForecastingParameters(\n",
|
||||||
" time_column_name=time_column_name, forecast_horizon=forecast_horizon\n",
|
" time_column_name=time_column_name,\n",
|
||||||
|
" forecast_horizon=forecast_horizon,\n",
|
||||||
|
" freq=\"H\", # Set the forecast frequency to be hourly\n",
|
||||||
")\n",
|
")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"automl_config = AutoMLConfig(task='forecasting', \n",
|
"automl_config = AutoMLConfig(\n",
|
||||||
" primary_metric='normalized_root_mean_squared_error',\n",
|
" task=\"forecasting\",\n",
|
||||||
" blocked_models = ['ExtremeRandomTrees', 'AutoArima', 'Prophet'], \n",
|
" primary_metric=\"normalized_root_mean_squared_error\",\n",
|
||||||
" experiment_timeout_hours=0.3,\n",
|
" blocked_models=[\"ExtremeRandomTrees\", \"AutoArima\", \"Prophet\"],\n",
|
||||||
" training_data=train,\n",
|
" experiment_timeout_hours=0.3,\n",
|
||||||
" label_column_name=target_column_name,\n",
|
" training_data=train,\n",
|
||||||
" compute_target=compute_target,\n",
|
" label_column_name=target_column_name,\n",
|
||||||
" enable_early_stopping=True,\n",
|
" compute_target=compute_target,\n",
|
||||||
" n_cross_validations=3, \n",
|
" enable_early_stopping=True,\n",
|
||||||
" verbosity=logging.INFO,\n",
|
" n_cross_validations=3,\n",
|
||||||
" forecasting_parameters=forecasting_parameters)"
|
" verbosity=logging.INFO,\n",
|
||||||
|
" forecasting_parameters=forecasting_parameters,\n",
|
||||||
|
")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -374,15 +385,6 @@
|
|||||||
"remote_run = experiment.submit(automl_config, show_output=False)"
|
"remote_run = experiment.submit(automl_config, show_output=False)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"remote_run"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
@@ -424,7 +426,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"fitted_model.named_steps['timeseriestransformer'].get_engineered_feature_names()"
|
"fitted_model.named_steps[\"timeseriestransformer\"].get_engineered_feature_names()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -448,7 +450,9 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"# Get the featurization summary as a list of JSON\n",
|
"# Get the featurization summary as a list of JSON\n",
|
||||||
"featurization_summary = fitted_model.named_steps['timeseriestransformer'].get_featurization_summary()\n",
|
"featurization_summary = fitted_model.named_steps[\n",
|
||||||
|
" \"timeseriestransformer\"\n",
|
||||||
|
"].get_featurization_summary()\n",
|
||||||
"# View the featurization summary as a pandas dataframe\n",
|
"# View the featurization summary as a pandas dataframe\n",
|
||||||
"pd.DataFrame.from_records(featurization_summary)"
|
"pd.DataFrame.from_records(featurization_summary)"
|
||||||
]
|
]
|
||||||
@@ -457,9 +461,11 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Forecasting\n",
|
"# Forecasting<a id=\"forecast\"></a>\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Now that we have retrieved the best pipeline/model, it can be used to make predictions on test data. First, we remove the target values from the test set:"
|
"Now that we have retrieved the best pipeline/model, it can be used to make predictions on test data. We will do batch scoring on the test dataset which should have the same schema as training dataset.\n",
|
||||||
|
"\n",
|
||||||
|
"The inference will run on a remote compute. In this example, it will re-use the training compute."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -468,16 +474,15 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"X_test = test.to_pandas_dataframe().reset_index(drop=True)\n",
|
"test_experiment = Experiment(ws, experiment_name + \"_inference\")"
|
||||||
"y_test = X_test.pop(target_column_name).values"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"### Forecast Function\n",
|
"### Retreiving forecasts from the model\n",
|
||||||
"For forecasting, we will use the forecast function instead of the predict function. Using the predict method would result in getting predictions for EVERY horizon the forecaster can predict at. This is useful when training and evaluating the performance of the forecaster at various horizons, but the level of detail is excessive for normal use. Forecast function also can handle more complicated scenarios, see the [forecast function notebook](../forecasting-forecast-function/auto-ml-forecasting-function.ipynb)."
|
"We have created a function called `run_forecast` that submits the test data to the best model determined during the training run and retrieves forecasts. This function uses a helper script `forecasting_script` which is uploaded and expecuted on the remote compute."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -486,10 +491,19 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"# The featurized data, aligned to y, will also be returned.\n",
|
"from run_forecast import run_remote_inference\n",
|
||||||
"# This contains the assumptions that were made in the forecast\n",
|
"\n",
|
||||||
"# and helps align the forecast to the original data\n",
|
"remote_run_infer = run_remote_inference(\n",
|
||||||
"y_predictions, X_trans = fitted_model.forecast(X_test)"
|
" test_experiment=test_experiment,\n",
|
||||||
|
" compute_target=compute_target,\n",
|
||||||
|
" train_run=best_run,\n",
|
||||||
|
" test_dataset=test,\n",
|
||||||
|
" target_column_name=target_column_name,\n",
|
||||||
|
")\n",
|
||||||
|
"remote_run_infer.wait_for_completion(show_output=False)\n",
|
||||||
|
"\n",
|
||||||
|
"# download the inference output file to the local machine\n",
|
||||||
|
"remote_run_infer.download_file(\"outputs/predictions.csv\", \"predictions.csv\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -497,9 +511,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"### Evaluate\n",
|
"### Evaluate\n",
|
||||||
"To evaluate the accuracy of the forecast, we'll compare against the actual sales quantities for some select metrics, included the mean absolute percentage error (MAPE).\n",
|
"To evaluate the accuracy of the forecast, we'll compare against the actual sales quantities for some select metrics, included the mean absolute percentage error (MAPE). For more metrics that can be used for evaluation after training, please see [supported metrics](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-understand-automated-ml#regressionforecasting-metrics), and [how to calculate residuals](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-understand-automated-ml#residuals)."
|
||||||
"\n",
|
|
||||||
"It is a good practice to always align the output explicitly to the input, as the count and order of the rows may have changed during transformations that span multiple rows."
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -508,9 +520,9 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from forecasting_helper import align_outputs\n",
|
"# load forecast data frame\n",
|
||||||
"\n",
|
"fcst_df = pd.read_csv(\"predictions.csv\", parse_dates=[time_column_name])\n",
|
||||||
"df_all = align_outputs(y_predictions, X_trans, X_test, y_test, target_column_name)"
|
"fcst_df.head()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -525,19 +537,24 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"# use automl metrics module\n",
|
"# use automl metrics module\n",
|
||||||
"scores = scoring.score_regression(\n",
|
"scores = scoring.score_regression(\n",
|
||||||
" y_test=df_all[target_column_name],\n",
|
" y_test=fcst_df[target_column_name],\n",
|
||||||
" y_pred=df_all['predicted'],\n",
|
" y_pred=fcst_df[\"predicted\"],\n",
|
||||||
" metrics=list(constants.Metric.SCALAR_REGRESSION_SET))\n",
|
" metrics=list(constants.Metric.SCALAR_REGRESSION_SET),\n",
|
||||||
|
")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"print(\"[Test data scores]\\n\")\n",
|
"print(\"[Test data scores]\\n\")\n",
|
||||||
"for key, value in scores.items(): \n",
|
"for key, value in scores.items():\n",
|
||||||
" print('{}: {:.3f}'.format(key, value))\n",
|
" print(\"{}: {:.3f}\".format(key, value))\n",
|
||||||
" \n",
|
"\n",
|
||||||
"# Plot outputs\n",
|
"# Plot outputs\n",
|
||||||
"%matplotlib inline\n",
|
"%matplotlib inline\n",
|
||||||
"test_pred = plt.scatter(df_all[target_column_name], df_all['predicted'], color='b')\n",
|
"test_pred = plt.scatter(fcst_df[target_column_name], fcst_df[\"predicted\"], color=\"b\")\n",
|
||||||
"test_test = plt.scatter(df_all[target_column_name], df_all[target_column_name], color='g')\n",
|
"test_test = plt.scatter(\n",
|
||||||
"plt.legend((test_pred, test_test), ('prediction', 'truth'), loc='upper left', fontsize=8)\n",
|
" fcst_df[target_column_name], fcst_df[target_column_name], color=\"g\"\n",
|
||||||
|
")\n",
|
||||||
|
"plt.legend(\n",
|
||||||
|
" (test_pred, test_test), (\"prediction\", \"truth\"), loc=\"upper left\", fontsize=8\n",
|
||||||
|
")\n",
|
||||||
"plt.show()"
|
"plt.show()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -545,23 +562,7 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"Looking at `X_trans` is also useful to see what featurization happened to the data."
|
"# Advanced Training <a id=\"advanced_training\"></a>\n",
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"X_trans"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Advanced Training <a id=\"advanced_training\"></a>\n",
|
|
||||||
"We did not use lags in the previous model specification. In effect, the prediction was the result of a simple regression on date, time series identifier columns and any additional features. This is often a very good prediction as common time series patterns like seasonality and trends can be captured in this manner. Such simple regression is horizon-less: it doesn't matter how far into the future we are predicting, because we are not using past data. In the previous example, the horizon was only used to split the data for cross-validation."
|
"We did not use lags in the previous model specification. In effect, the prediction was the result of a simple regression on date, time series identifier columns and any additional features. This is often a very good prediction as common time series patterns like seasonality and trends can be captured in this manner. Such simple regression is horizon-less: it doesn't matter how far into the future we are predicting, because we are not using past data. In the previous example, the horizon was only used to split the data for cross-validation."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -582,21 +583,33 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"advanced_forecasting_parameters = ForecastingParameters(\n",
|
"advanced_forecasting_parameters = ForecastingParameters(\n",
|
||||||
" time_column_name=time_column_name, forecast_horizon=forecast_horizon,\n",
|
" time_column_name=time_column_name,\n",
|
||||||
" target_lags=12, target_rolling_window_size=4\n",
|
" forecast_horizon=forecast_horizon,\n",
|
||||||
|
" target_lags=12,\n",
|
||||||
|
" target_rolling_window_size=4,\n",
|
||||||
")\n",
|
")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"automl_config = AutoMLConfig(task='forecasting', \n",
|
"automl_config = AutoMLConfig(\n",
|
||||||
" primary_metric='normalized_root_mean_squared_error',\n",
|
" task=\"forecasting\",\n",
|
||||||
" blocked_models = ['ElasticNet','ExtremeRandomTrees','GradientBoosting','XGBoostRegressor','ExtremeRandomTrees', 'AutoArima', 'Prophet'], #These models are blocked for tutorial purposes, remove this for real use cases. \n",
|
" primary_metric=\"normalized_root_mean_squared_error\",\n",
|
||||||
" experiment_timeout_hours=0.3,\n",
|
" blocked_models=[\n",
|
||||||
" training_data=train,\n",
|
" \"ElasticNet\",\n",
|
||||||
" label_column_name=target_column_name,\n",
|
" \"ExtremeRandomTrees\",\n",
|
||||||
" compute_target=compute_target,\n",
|
" \"GradientBoosting\",\n",
|
||||||
" enable_early_stopping = True,\n",
|
" \"XGBoostRegressor\",\n",
|
||||||
" n_cross_validations=3, \n",
|
" \"ExtremeRandomTrees\",\n",
|
||||||
" verbosity=logging.INFO,\n",
|
" \"AutoArima\",\n",
|
||||||
" forecasting_parameters=advanced_forecasting_parameters)"
|
" \"Prophet\",\n",
|
||||||
|
" ], # These models are blocked for tutorial purposes, remove this for real use cases.\n",
|
||||||
|
" experiment_timeout_hours=0.3,\n",
|
||||||
|
" training_data=train,\n",
|
||||||
|
" label_column_name=target_column_name,\n",
|
||||||
|
" compute_target=compute_target,\n",
|
||||||
|
" enable_early_stopping=True,\n",
|
||||||
|
" n_cross_validations=3,\n",
|
||||||
|
" verbosity=logging.INFO,\n",
|
||||||
|
" forecasting_parameters=advanced_forecasting_parameters,\n",
|
||||||
|
")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -644,7 +657,7 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Advanced Results<a id=\"advanced_results\"></a>\n",
|
"# Advanced Results<a id=\"advanced_results\"></a>\n",
|
||||||
"We did not use lags in the previous model specification. In effect, the prediction was the result of a simple regression on date, time series identifier columns and any additional features. This is often a very good prediction as common time series patterns like seasonality and trends can be captured in this manner. Such simple regression is horizon-less: it doesn't matter how far into the future we are predicting, because we are not using past data. In the previous example, the horizon was only used to split the data for cross-validation."
|
"We did not use lags in the previous model specification. In effect, the prediction was the result of a simple regression on date, time series identifier columns and any additional features. This is often a very good prediction as common time series patterns like seasonality and trends can be captured in this manner. Such simple regression is horizon-less: it doesn't matter how far into the future we are predicting, because we are not using past data. In the previous example, the horizon was only used to split the data for cross-validation."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -654,10 +667,21 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"# The featurized data, aligned to y, will also be returned.\n",
|
"test_experiment_advanced = Experiment(ws, experiment_name + \"_inference_advanced\")\n",
|
||||||
"# This contains the assumptions that were made in the forecast\n",
|
"advanced_remote_run_infer = run_remote_inference(\n",
|
||||||
"# and helps align the forecast to the original data\n",
|
" test_experiment=test_experiment_advanced,\n",
|
||||||
"y_predictions, X_trans = fitted_model_lags.forecast(X_test)"
|
" compute_target=compute_target,\n",
|
||||||
|
" train_run=best_run_lags,\n",
|
||||||
|
" test_dataset=test,\n",
|
||||||
|
" target_column_name=target_column_name,\n",
|
||||||
|
" inference_folder=\"./forecast_advanced\",\n",
|
||||||
|
")\n",
|
||||||
|
"advanced_remote_run_infer.wait_for_completion(show_output=False)\n",
|
||||||
|
"\n",
|
||||||
|
"# download the inference output file to the local machine\n",
|
||||||
|
"advanced_remote_run_infer.download_file(\n",
|
||||||
|
" \"outputs/predictions.csv\", \"predictions_advanced.csv\"\n",
|
||||||
|
")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -666,9 +690,8 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from forecasting_helper import align_outputs\n",
|
"fcst_adv_df = pd.read_csv(\"predictions_advanced.csv\", parse_dates=[time_column_name])\n",
|
||||||
"\n",
|
"fcst_adv_df.head()"
|
||||||
"df_all = align_outputs(y_predictions, X_trans, X_test, y_test, target_column_name)"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -683,19 +706,26 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"# use automl metrics module\n",
|
"# use automl metrics module\n",
|
||||||
"scores = scoring.score_regression(\n",
|
"scores = scoring.score_regression(\n",
|
||||||
" y_test=df_all[target_column_name],\n",
|
" y_test=fcst_adv_df[target_column_name],\n",
|
||||||
" y_pred=df_all['predicted'],\n",
|
" y_pred=fcst_adv_df[\"predicted\"],\n",
|
||||||
" metrics=list(constants.Metric.SCALAR_REGRESSION_SET))\n",
|
" metrics=list(constants.Metric.SCALAR_REGRESSION_SET),\n",
|
||||||
|
")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"print(\"[Test data scores]\\n\")\n",
|
"print(\"[Test data scores]\\n\")\n",
|
||||||
"for key, value in scores.items(): \n",
|
"for key, value in scores.items():\n",
|
||||||
" print('{}: {:.3f}'.format(key, value))\n",
|
" print(\"{}: {:.3f}\".format(key, value))\n",
|
||||||
" \n",
|
"\n",
|
||||||
"# Plot outputs\n",
|
"# Plot outputs\n",
|
||||||
"%matplotlib inline\n",
|
"%matplotlib inline\n",
|
||||||
"test_pred = plt.scatter(df_all[target_column_name], df_all['predicted'], color='b')\n",
|
"test_pred = plt.scatter(\n",
|
||||||
"test_test = plt.scatter(df_all[target_column_name], df_all[target_column_name], color='g')\n",
|
" fcst_adv_df[target_column_name], fcst_adv_df[\"predicted\"], color=\"b\"\n",
|
||||||
"plt.legend((test_pred, test_test), ('prediction', 'truth'), loc='upper left', fontsize=8)\n",
|
")\n",
|
||||||
|
"test_test = plt.scatter(\n",
|
||||||
|
" fcst_adv_df[target_column_name], fcst_adv_df[target_column_name], color=\"g\"\n",
|
||||||
|
")\n",
|
||||||
|
"plt.legend(\n",
|
||||||
|
" (test_pred, test_test), (\"prediction\", \"truth\"), loc=\"upper left\", fontsize=8\n",
|
||||||
|
")\n",
|
||||||
"plt.show()"
|
"plt.show()"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -703,7 +733,7 @@
|
|||||||
"metadata": {
|
"metadata": {
|
||||||
"authors": [
|
"authors": [
|
||||||
{
|
{
|
||||||
"name": "erwright"
|
"name": "jialiu"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"categories": [
|
"categories": [
|
||||||
@@ -725,7 +755,7 @@
|
|||||||
"name": "python",
|
"name": "python",
|
||||||
"nbconvert_exporter": "python",
|
"nbconvert_exporter": "python",
|
||||||
"pygments_lexer": "ipython3",
|
"pygments_lexer": "ipython3",
|
||||||
"version": "3.6.8"
|
"version": "3.6.9"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"nbformat": 4,
|
"nbformat": 4,
|
||||||
|
|||||||
@@ -1,44 +0,0 @@
|
|||||||
import pandas as pd
|
|
||||||
import numpy as np
|
|
||||||
from pandas.tseries.frequencies import to_offset
|
|
||||||
|
|
||||||
|
|
||||||
def align_outputs(y_predicted, X_trans, X_test, y_test, target_column_name,
|
|
||||||
predicted_column_name='predicted',
|
|
||||||
horizon_colname='horizon_origin'):
|
|
||||||
"""
|
|
||||||
Demonstrates how to get the output aligned to the inputs
|
|
||||||
using pandas indexes. Helps understand what happened if
|
|
||||||
the output's shape differs from the input shape, or if
|
|
||||||
the data got re-sorted by time and grain during forecasting.
|
|
||||||
|
|
||||||
Typical causes of misalignment are:
|
|
||||||
* we predicted some periods that were missing in actuals -> drop from eval
|
|
||||||
* model was asked to predict past max_horizon -> increase max horizon
|
|
||||||
* data at start of X_test was needed for lags -> provide previous periods
|
|
||||||
"""
|
|
||||||
|
|
||||||
if (horizon_colname in X_trans):
|
|
||||||
df_fcst = pd.DataFrame({predicted_column_name: y_predicted,
|
|
||||||
horizon_colname: X_trans[horizon_colname]})
|
|
||||||
else:
|
|
||||||
df_fcst = pd.DataFrame({predicted_column_name: y_predicted})
|
|
||||||
|
|
||||||
# y and X outputs are aligned by forecast() function contract
|
|
||||||
df_fcst.index = X_trans.index
|
|
||||||
|
|
||||||
# align original X_test to y_test
|
|
||||||
X_test_full = X_test.copy()
|
|
||||||
X_test_full[target_column_name] = y_test
|
|
||||||
|
|
||||||
# X_test_full's index does not include origin, so reset for merge
|
|
||||||
df_fcst.reset_index(inplace=True)
|
|
||||||
X_test_full = X_test_full.reset_index().drop(columns='index')
|
|
||||||
together = df_fcst.merge(X_test_full, how='right')
|
|
||||||
|
|
||||||
# drop rows where prediction or actuals are nan
|
|
||||||
# happens because of missing actuals
|
|
||||||
# or at edges of time due to lags/rolling windows
|
|
||||||
clean = together[together[[target_column_name,
|
|
||||||
predicted_column_name]].notnull().all(axis=1)]
|
|
||||||
return(clean)
|
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
"""
|
||||||
|
This is the script that is executed on the compute instance. It relies
|
||||||
|
on the model.pkl file which is uploaded along with this script to the
|
||||||
|
compute instance.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
from azureml.core import Dataset, Run
|
||||||
|
from sklearn.externals import joblib
|
||||||
|
from pandas.tseries.frequencies import to_offset
|
||||||
|
|
||||||
|
parser = argparse.ArgumentParser()
|
||||||
|
parser.add_argument(
|
||||||
|
"--target_column_name",
|
||||||
|
type=str,
|
||||||
|
dest="target_column_name",
|
||||||
|
help="Target Column Name",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--test_dataset", type=str, dest="test_dataset", help="Test Dataset"
|
||||||
|
)
|
||||||
|
|
||||||
|
args = parser.parse_args()
|
||||||
|
target_column_name = args.target_column_name
|
||||||
|
test_dataset_id = args.test_dataset
|
||||||
|
|
||||||
|
run = Run.get_context()
|
||||||
|
ws = run.experiment.workspace
|
||||||
|
|
||||||
|
# get the input dataset by id
|
||||||
|
test_dataset = Dataset.get_by_id(ws, id=test_dataset_id)
|
||||||
|
|
||||||
|
X_test = test_dataset.to_pandas_dataframe().reset_index(drop=True)
|
||||||
|
y_test = X_test.pop(target_column_name).values
|
||||||
|
|
||||||
|
# generate forecast
|
||||||
|
fitted_model = joblib.load("model.pkl")
|
||||||
|
# We have default quantiles values set as below(95th percentile)
|
||||||
|
quantiles = [0.025, 0.5, 0.975]
|
||||||
|
predicted_column_name = "predicted"
|
||||||
|
PI = "prediction_interval"
|
||||||
|
fitted_model.quantiles = quantiles
|
||||||
|
pred_quantiles = fitted_model.forecast_quantiles(X_test)
|
||||||
|
pred_quantiles[PI] = pred_quantiles[[min(quantiles), max(quantiles)]].apply(
|
||||||
|
lambda x: "[{}, {}]".format(x[0], x[1]), axis=1
|
||||||
|
)
|
||||||
|
X_test[target_column_name] = y_test
|
||||||
|
X_test[PI] = pred_quantiles[PI]
|
||||||
|
X_test[predicted_column_name] = pred_quantiles[0.5]
|
||||||
|
# drop rows where prediction or actuals are nan
|
||||||
|
# happens because of missing actuals
|
||||||
|
# or at edges of time due to lags/rolling windows
|
||||||
|
clean = X_test[
|
||||||
|
X_test[[target_column_name, predicted_column_name]].notnull().all(axis=1)
|
||||||
|
]
|
||||||
|
|
||||||
|
file_name = "outputs/predictions.csv"
|
||||||
|
export_csv = clean.to_csv(file_name, header=True, index=False) # added Index
|
||||||
|
|
||||||
|
# Upload the predictions into artifacts
|
||||||
|
run.upload_file(name=file_name, path_or_stream=file_name)
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
import pandas as pd
|
|
||||||
import numpy as np
|
|
||||||
|
|
||||||
|
|
||||||
def APE(actual, pred):
|
|
||||||
"""
|
|
||||||
Calculate absolute percentage error.
|
|
||||||
Returns a vector of APE values with same length as actual/pred.
|
|
||||||
"""
|
|
||||||
return 100 * np.abs((actual - pred) / actual)
|
|
||||||
|
|
||||||
|
|
||||||
def MAPE(actual, pred):
|
|
||||||
"""
|
|
||||||
Calculate mean absolute percentage error.
|
|
||||||
Remove NA and values where actual is close to zero
|
|
||||||
"""
|
|
||||||
not_na = ~(np.isnan(actual) | np.isnan(pred))
|
|
||||||
not_zero = ~np.isclose(actual, 0.0)
|
|
||||||
actual_safe = actual[not_na & not_zero]
|
|
||||||
pred_safe = pred[not_na & not_zero]
|
|
||||||
return np.mean(APE(actual_safe, pred_safe))
|
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
from azureml.core import ScriptRunConfig
|
||||||
|
|
||||||
|
|
||||||
|
def run_remote_inference(
|
||||||
|
test_experiment,
|
||||||
|
compute_target,
|
||||||
|
train_run,
|
||||||
|
test_dataset,
|
||||||
|
target_column_name,
|
||||||
|
inference_folder="./forecast",
|
||||||
|
):
|
||||||
|
# Create local directory to copy the model.pkl and forecsting_script.py files into.
|
||||||
|
# These files will be uploaded to and executed on the compute instance.
|
||||||
|
os.makedirs(inference_folder, exist_ok=True)
|
||||||
|
shutil.copy("forecasting_script.py", inference_folder)
|
||||||
|
|
||||||
|
train_run.download_file(
|
||||||
|
"outputs/model.pkl", os.path.join(inference_folder, "model.pkl")
|
||||||
|
)
|
||||||
|
|
||||||
|
inference_env = train_run.get_environment()
|
||||||
|
|
||||||
|
config = ScriptRunConfig(
|
||||||
|
source_directory=inference_folder,
|
||||||
|
script="forecasting_script.py",
|
||||||
|
arguments=[
|
||||||
|
"--target_column_name",
|
||||||
|
target_column_name,
|
||||||
|
"--test_dataset",
|
||||||
|
test_dataset.as_named_input(test_dataset.name),
|
||||||
|
],
|
||||||
|
compute_target=compute_target,
|
||||||
|
environment=inference_env,
|
||||||
|
)
|
||||||
|
|
||||||
|
run = test_experiment.submit(
|
||||||
|
config,
|
||||||
|
tags={
|
||||||
|
"training_run_id": train_run.id,
|
||||||
|
"run_algorithm": train_run.properties["run_algorithm"],
|
||||||
|
"valid_score": train_run.properties["score"],
|
||||||
|
"primary_metric": train_run.properties["primary_metric"],
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
run.log("run_algorithm", run.tags["run_algorithm"])
|
||||||
|
return run
|
||||||
@@ -24,7 +24,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Introduction\n",
|
"## Introduction\n",
|
||||||
"This notebook demonstrates the full interface to the `forecast()` function. \n",
|
"This notebook demonstrates the full interface of the `forecast()` function. \n",
|
||||||
"\n",
|
"\n",
|
||||||
"The best known and most frequent usage of `forecast` enables forecasting on test sets that immediately follows training data. \n",
|
"The best known and most frequent usage of `forecast` enables forecasting on test sets that immediately follows training data. \n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -94,7 +94,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"print(\"This notebook was created using version 1.12.0 of the Azure ML SDK\")\n",
|
"print(\"This notebook was created using version 1.37.0 of the Azure ML SDK\")\n",
|
||||||
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -111,19 +111,19 @@
|
|||||||
"ws = Workspace.from_config()\n",
|
"ws = Workspace.from_config()\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# choose a name for the run history container in the workspace\n",
|
"# choose a name for the run history container in the workspace\n",
|
||||||
"experiment_name = 'automl-forecast-function-demo'\n",
|
"experiment_name = \"automl-forecast-function-demo\"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"experiment = Experiment(ws, experiment_name)\n",
|
"experiment = Experiment(ws, experiment_name)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"output = {}\n",
|
"output = {}\n",
|
||||||
"output['Subscription ID'] = ws.subscription_id\n",
|
"output[\"Subscription ID\"] = ws.subscription_id\n",
|
||||||
"output['Workspace'] = ws.name\n",
|
"output[\"Workspace\"] = ws.name\n",
|
||||||
"output['SKU'] = ws.sku\n",
|
"output[\"SKU\"] = ws.sku\n",
|
||||||
"output['Resource Group'] = ws.resource_group\n",
|
"output[\"Resource Group\"] = ws.resource_group\n",
|
||||||
"output['Location'] = ws.location\n",
|
"output[\"Location\"] = ws.location\n",
|
||||||
"output['Run History Name'] = experiment_name\n",
|
"output[\"Run History Name\"] = experiment_name\n",
|
||||||
"pd.set_option('display.max_colwidth', -1)\n",
|
"pd.set_option(\"display.max_colwidth\", -1)\n",
|
||||||
"outputDf = pd.DataFrame(data = output, index = [''])\n",
|
"outputDf = pd.DataFrame(data=output, index=[\"\"])\n",
|
||||||
"outputDf.T"
|
"outputDf.T"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -141,17 +141,20 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"TIME_COLUMN_NAME = 'date'\n",
|
"TIME_COLUMN_NAME = \"date\"\n",
|
||||||
"TIME_SERIES_ID_COLUMN_NAME = 'time_series_id'\n",
|
"TIME_SERIES_ID_COLUMN_NAME = \"time_series_id\"\n",
|
||||||
"TARGET_COLUMN_NAME = 'y'\n",
|
"TARGET_COLUMN_NAME = \"y\"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"def get_timeseries(train_len: int,\n",
|
"\n",
|
||||||
" test_len: int,\n",
|
"def get_timeseries(\n",
|
||||||
" time_column_name: str,\n",
|
" train_len: int,\n",
|
||||||
" target_column_name: str,\n",
|
" test_len: int,\n",
|
||||||
" time_series_id_column_name: str,\n",
|
" time_column_name: str,\n",
|
||||||
" time_series_number: int = 1,\n",
|
" target_column_name: str,\n",
|
||||||
" freq: str = 'H'):\n",
|
" time_series_id_column_name: str,\n",
|
||||||
|
" time_series_number: int = 1,\n",
|
||||||
|
" freq: str = \"H\",\n",
|
||||||
|
"):\n",
|
||||||
" \"\"\"\n",
|
" \"\"\"\n",
|
||||||
" Return the time series of designed length.\n",
|
" Return the time series of designed length.\n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -174,14 +177,18 @@
|
|||||||
" data_test = [] # type: List[pd.DataFrame]\n",
|
" data_test = [] # type: List[pd.DataFrame]\n",
|
||||||
" data_length = train_len + test_len\n",
|
" data_length = train_len + test_len\n",
|
||||||
" for i in range(time_series_number):\n",
|
" for i in range(time_series_number):\n",
|
||||||
" X = pd.DataFrame({\n",
|
" X = pd.DataFrame(\n",
|
||||||
" time_column_name: pd.date_range(start='2000-01-01',\n",
|
" {\n",
|
||||||
" periods=data_length,\n",
|
" time_column_name: pd.date_range(\n",
|
||||||
" freq=freq),\n",
|
" start=\"2000-01-01\", periods=data_length, freq=freq\n",
|
||||||
" target_column_name: np.arange(data_length).astype(float) + np.random.rand(data_length) + i*5,\n",
|
" ),\n",
|
||||||
" 'ext_predictor': np.asarray(range(42, 42 + data_length)),\n",
|
" target_column_name: np.arange(data_length).astype(float)\n",
|
||||||
" time_series_id_column_name: np.repeat('ts{}'.format(i), data_length)\n",
|
" + np.random.rand(data_length)\n",
|
||||||
" })\n",
|
" + i * 5,\n",
|
||||||
|
" \"ext_predictor\": np.asarray(range(42, 42 + data_length)),\n",
|
||||||
|
" time_series_id_column_name: np.repeat(\"ts{}\".format(i), data_length),\n",
|
||||||
|
" }\n",
|
||||||
|
" )\n",
|
||||||
" data_train.append(X[:train_len])\n",
|
" data_train.append(X[:train_len])\n",
|
||||||
" data_test.append(X[train_len:])\n",
|
" data_test.append(X[train_len:])\n",
|
||||||
" X_train = pd.concat(data_train)\n",
|
" X_train = pd.concat(data_train)\n",
|
||||||
@@ -190,14 +197,17 @@
|
|||||||
" y_test = X_test.pop(target_column_name).values\n",
|
" y_test = X_test.pop(target_column_name).values\n",
|
||||||
" return X_train, y_train, X_test, y_test\n",
|
" return X_train, y_train, X_test, y_test\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"n_test_periods = 6\n",
|
"n_test_periods = 6\n",
|
||||||
"n_train_periods = 30\n",
|
"n_train_periods = 30\n",
|
||||||
"X_train, y_train, X_test, y_test = get_timeseries(train_len=n_train_periods,\n",
|
"X_train, y_train, X_test, y_test = get_timeseries(\n",
|
||||||
" test_len=n_test_periods,\n",
|
" train_len=n_train_periods,\n",
|
||||||
" time_column_name=TIME_COLUMN_NAME,\n",
|
" test_len=n_test_periods,\n",
|
||||||
" target_column_name=TARGET_COLUMN_NAME,\n",
|
" time_column_name=TIME_COLUMN_NAME,\n",
|
||||||
" time_series_id_column_name=TIME_SERIES_ID_COLUMN_NAME,\n",
|
" target_column_name=TARGET_COLUMN_NAME,\n",
|
||||||
" time_series_number=2)"
|
" time_series_id_column_name=TIME_SERIES_ID_COLUMN_NAME,\n",
|
||||||
|
" time_series_number=2,\n",
|
||||||
|
")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -224,11 +234,12 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"# plot the example time series\n",
|
"# plot the example time series\n",
|
||||||
"import matplotlib.pyplot as plt\n",
|
"import matplotlib.pyplot as plt\n",
|
||||||
|
"\n",
|
||||||
"whole_data = X_train.copy()\n",
|
"whole_data = X_train.copy()\n",
|
||||||
"target_label = 'y'\n",
|
"target_label = \"y\"\n",
|
||||||
"whole_data[target_label] = y_train\n",
|
"whole_data[target_label] = y_train\n",
|
||||||
"for g in whole_data.groupby('time_series_id'): \n",
|
"for g in whole_data.groupby(\"time_series_id\"):\n",
|
||||||
" plt.plot(g[1]['date'].values, g[1]['y'].values, label=g[0])\n",
|
" plt.plot(g[1][\"date\"].values, g[1][\"y\"].values, label=g[0])\n",
|
||||||
"plt.legend()\n",
|
"plt.legend()\n",
|
||||||
"plt.show()"
|
"plt.show()"
|
||||||
]
|
]
|
||||||
@@ -250,12 +261,12 @@
|
|||||||
"# We need to save thw artificial data and then upload them to default workspace datastore.\n",
|
"# We need to save thw artificial data and then upload them to default workspace datastore.\n",
|
||||||
"DATA_PATH = \"fc_fn_data\"\n",
|
"DATA_PATH = \"fc_fn_data\"\n",
|
||||||
"DATA_PATH_X = \"{}/data_train.csv\".format(DATA_PATH)\n",
|
"DATA_PATH_X = \"{}/data_train.csv\".format(DATA_PATH)\n",
|
||||||
"if not os.path.isdir('data'):\n",
|
"if not os.path.isdir(\"data\"):\n",
|
||||||
" os.mkdir('data')\n",
|
" os.mkdir(\"data\")\n",
|
||||||
"pd.DataFrame(whole_data).to_csv(\"data/data_train.csv\", index=False)\n",
|
"pd.DataFrame(whole_data).to_csv(\"data/data_train.csv\", index=False)\n",
|
||||||
"# Upload saved data to the default data store.\n",
|
"# Upload saved data to the default data store.\n",
|
||||||
"ds = ws.get_default_datastore()\n",
|
"ds = ws.get_default_datastore()\n",
|
||||||
"ds.upload(src_dir='./data', target_path=DATA_PATH, overwrite=True, show_progress=True)\n",
|
"ds.upload(src_dir=\"./data\", target_path=DATA_PATH, overwrite=True, show_progress=True)\n",
|
||||||
"train_data = Dataset.Tabular.from_delimited_files(path=ds.path(DATA_PATH_X))"
|
"train_data = Dataset.Tabular.from_delimited_files(path=ds.path(DATA_PATH_X))"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -263,7 +274,9 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"You will need to create a [compute target](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-set-up-training-targets#amlcompute) for your AutoML run. In this tutorial, you create AmlCompute as your training compute resource."
|
"You will need to create a [compute target](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-set-up-training-targets#amlcompute) for your AutoML run. In this tutorial, you create AmlCompute as your training compute resource.\n",
|
||||||
|
"\n",
|
||||||
|
"> 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."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -281,10 +294,11 @@
|
|||||||
"# Verify that cluster does not exist already\n",
|
"# Verify that cluster does not exist already\n",
|
||||||
"try:\n",
|
"try:\n",
|
||||||
" compute_target = ComputeTarget(workspace=ws, name=amlcompute_cluster_name)\n",
|
" compute_target = ComputeTarget(workspace=ws, name=amlcompute_cluster_name)\n",
|
||||||
" print('Found existing cluster, use it.')\n",
|
" print(\"Found existing cluster, use it.\")\n",
|
||||||
"except ComputeTargetException:\n",
|
"except ComputeTargetException:\n",
|
||||||
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_D2_V2',\n",
|
" compute_config = AmlCompute.provisioning_configuration(\n",
|
||||||
" max_nodes=6)\n",
|
" vm_size=\"STANDARD_DS12_V2\", max_nodes=6\n",
|
||||||
|
" )\n",
|
||||||
" compute_target = ComputeTarget.create(ws, amlcompute_cluster_name, compute_config)\n",
|
" compute_target = ComputeTarget.create(ws, amlcompute_cluster_name, compute_config)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"compute_target.wait_for_completion(show_output=True)"
|
"compute_target.wait_for_completion(show_output=True)"
|
||||||
@@ -302,7 +316,8 @@
|
|||||||
"* Set early termination to True, so the iterations through the models will stop when no improvements in accuracy score will be made.\n",
|
"* Set early termination to True, so the iterations through the models will stop when no improvements in accuracy score will be made.\n",
|
||||||
"* Set limitations on the length of experiment run to 15 minutes.\n",
|
"* Set limitations on the length of experiment run to 15 minutes.\n",
|
||||||
"* Finally, we set the task to be forecasting.\n",
|
"* Finally, we set the task to be forecasting.\n",
|
||||||
"* We apply the lag lead operator to the target value i.e. we use the previous values as a predictor for the future ones."
|
"* We apply the lag lead operator to the target value i.e. we use the previous values as a predictor for the future ones.\n",
|
||||||
|
"* [Optional] Forecast frequency parameter (freq) represents the period with which the forecast is desired, for example, daily, weekly, yearly, etc. Use this parameter for the correction of time series containing irregular data points or for padding of short time series. The frequency needs to be a pandas offset alias. Please refer to [pandas documentation](https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#dateoffset-objects) for more information."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -312,13 +327,15 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from azureml.automl.core.forecasting_parameters import ForecastingParameters\n",
|
"from azureml.automl.core.forecasting_parameters import ForecastingParameters\n",
|
||||||
"lags = [1,2,3]\n",
|
"\n",
|
||||||
|
"lags = [1, 2, 3]\n",
|
||||||
"forecast_horizon = n_test_periods\n",
|
"forecast_horizon = n_test_periods\n",
|
||||||
"forecasting_parameters = ForecastingParameters(\n",
|
"forecasting_parameters = ForecastingParameters(\n",
|
||||||
" time_column_name=TIME_COLUMN_NAME,\n",
|
" time_column_name=TIME_COLUMN_NAME,\n",
|
||||||
" forecast_horizon=forecast_horizon,\n",
|
" forecast_horizon=forecast_horizon,\n",
|
||||||
" time_series_id_column_names=[ TIME_SERIES_ID_COLUMN_NAME ],\n",
|
" time_series_id_column_names=[TIME_SERIES_ID_COLUMN_NAME],\n",
|
||||||
" target_lags=lags\n",
|
" target_lags=lags,\n",
|
||||||
|
" freq=\"H\", # Set the forecast frequency to be hourly\n",
|
||||||
")"
|
")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -340,19 +357,21 @@
|
|||||||
"from azureml.train.automl import AutoMLConfig\n",
|
"from azureml.train.automl import AutoMLConfig\n",
|
||||||
"\n",
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"automl_config = AutoMLConfig(task='forecasting',\n",
|
"automl_config = AutoMLConfig(\n",
|
||||||
" debug_log='automl_forecasting_function.log',\n",
|
" task=\"forecasting\",\n",
|
||||||
" primary_metric='normalized_root_mean_squared_error',\n",
|
" debug_log=\"automl_forecasting_function.log\",\n",
|
||||||
" experiment_timeout_hours=0.25,\n",
|
" primary_metric=\"normalized_root_mean_squared_error\",\n",
|
||||||
" enable_early_stopping=True,\n",
|
" experiment_timeout_hours=0.25,\n",
|
||||||
" training_data=train_data,\n",
|
" enable_early_stopping=True,\n",
|
||||||
" compute_target=compute_target,\n",
|
" training_data=train_data,\n",
|
||||||
" n_cross_validations=3,\n",
|
" compute_target=compute_target,\n",
|
||||||
" verbosity = logging.INFO,\n",
|
" n_cross_validations=3,\n",
|
||||||
" max_concurrent_iterations=4,\n",
|
" verbosity=logging.INFO,\n",
|
||||||
" max_cores_per_iteration=-1,\n",
|
" max_concurrent_iterations=4,\n",
|
||||||
" label_column_name=target_label,\n",
|
" max_cores_per_iteration=-1,\n",
|
||||||
" forecasting_parameters=forecasting_parameters)\n",
|
" label_column_name=target_label,\n",
|
||||||
|
" forecasting_parameters=forecasting_parameters,\n",
|
||||||
|
")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"remote_run = experiment.submit(automl_config, show_output=False)"
|
"remote_run = experiment.submit(automl_config, show_output=False)"
|
||||||
]
|
]
|
||||||
@@ -429,7 +448,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"y_pred_no_gap, xy_nogap = fitted_model.forecast(X_test)\n",
|
"y_pred_no_gap, xy_nogap = fitted_model.forecast(X_test)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# xy_nogap contains the predictions in the _automl_target_col column.\n",
|
"# xy_nogap contains the predictions in the _automl_target_col column.\n",
|
||||||
"# Those same numbers are output in y_pred_no_gap\n",
|
"# Those same numbers are output in y_pred_no_gap\n",
|
||||||
@@ -457,7 +476,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"quantiles = fitted_model.forecast_quantiles(X_test)\n",
|
"quantiles = fitted_model.forecast_quantiles(X_test)\n",
|
||||||
"quantiles"
|
"quantiles"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -477,12 +496,12 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"# specify which quantiles you would like \n",
|
"# specify which quantiles you would like\n",
|
||||||
"fitted_model.quantiles = [0.01, 0.5, 0.95]\n",
|
"fitted_model.quantiles = [0.01, 0.5, 0.95]\n",
|
||||||
"# use forecast_quantiles function, not the forecast() one\n",
|
"# use forecast_quantiles function, not the forecast() one\n",
|
||||||
"y_pred_quantiles = fitted_model.forecast_quantiles(X_test)\n",
|
"y_pred_quantiles = fitted_model.forecast_quantiles(X_test)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# quantile forecasts returned in a Dataframe along with the time and time series id columns \n",
|
"# quantile forecasts returned in a Dataframe along with the time and time series id columns\n",
|
||||||
"y_pred_quantiles"
|
"y_pred_quantiles"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -530,14 +549,16 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"# generate the same kind of test data we trained on, \n",
|
"# generate the same kind of test data we trained on,\n",
|
||||||
"# but now make the train set much longer, so that the test set will be in the future\n",
|
"# but now make the train set much longer, so that the test set will be in the future\n",
|
||||||
"X_context, y_context, X_away, y_away = get_timeseries(train_len=42, # train data was 30 steps long\n",
|
"X_context, y_context, X_away, y_away = get_timeseries(\n",
|
||||||
" test_len=4,\n",
|
" train_len=42, # train data was 30 steps long\n",
|
||||||
" time_column_name=TIME_COLUMN_NAME,\n",
|
" test_len=4,\n",
|
||||||
" target_column_name=TARGET_COLUMN_NAME,\n",
|
" time_column_name=TIME_COLUMN_NAME,\n",
|
||||||
" time_series_id_column_name=TIME_SERIES_ID_COLUMN_NAME,\n",
|
" target_column_name=TARGET_COLUMN_NAME,\n",
|
||||||
" time_series_number=2)\n",
|
" time_series_id_column_name=TIME_SERIES_ID_COLUMN_NAME,\n",
|
||||||
|
" time_series_number=2,\n",
|
||||||
|
")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# end of the data we trained on\n",
|
"# end of the data we trained on\n",
|
||||||
"print(X_train.groupby(TIME_SERIES_ID_COLUMN_NAME)[TIME_COLUMN_NAME].max())\n",
|
"print(X_train.groupby(TIME_SERIES_ID_COLUMN_NAME)[TIME_COLUMN_NAME].max())\n",
|
||||||
@@ -558,7 +579,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"try: \n",
|
"try:\n",
|
||||||
" y_pred_away, xy_away = fitted_model.forecast(X_away)\n",
|
" y_pred_away, xy_away = fitted_model.forecast(X_away)\n",
|
||||||
" xy_away\n",
|
" xy_away\n",
|
||||||
"except Exception as e:\n",
|
"except Exception as e:\n",
|
||||||
@@ -580,7 +601,9 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"def make_forecasting_query(fulldata, time_column_name, target_column_name, forecast_origin, horizon, lookback):\n",
|
"def make_forecasting_query(\n",
|
||||||
|
" fulldata, time_column_name, target_column_name, forecast_origin, horizon, lookback\n",
|
||||||
|
"):\n",
|
||||||
"\n",
|
"\n",
|
||||||
" \"\"\"\n",
|
" \"\"\"\n",
|
||||||
" This function will take the full dataset, and create the query\n",
|
" This function will take the full dataset, and create the query\n",
|
||||||
@@ -588,24 +611,24 @@
|
|||||||
" forward for the next `horizon` horizons. Context from previous\n",
|
" forward for the next `horizon` horizons. Context from previous\n",
|
||||||
" `lookback` periods will be included.\n",
|
" `lookback` periods will be included.\n",
|
||||||
"\n",
|
"\n",
|
||||||
" \n",
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
" fulldata: pandas.DataFrame a time series dataset. Needs to contain X and y.\n",
|
" fulldata: pandas.DataFrame a time series dataset. Needs to contain X and y.\n",
|
||||||
" time_column_name: string which column (must be in fulldata) is the time axis\n",
|
" time_column_name: string which column (must be in fulldata) is the time axis\n",
|
||||||
" target_column_name: string which column (must be in fulldata) is to be forecast\n",
|
" target_column_name: string which column (must be in fulldata) is to be forecast\n",
|
||||||
" forecast_origin: datetime type the last time we (pretend to) have target values \n",
|
" forecast_origin: datetime type the last time we (pretend to) have target values\n",
|
||||||
" horizon: timedelta how far forward, in time units (not periods)\n",
|
" horizon: timedelta how far forward, in time units (not periods)\n",
|
||||||
" lookback: timedelta how far back does the model look?\n",
|
" lookback: timedelta how far back does the model look\n",
|
||||||
"\n",
|
"\n",
|
||||||
" Example:\n",
|
" Example:\n",
|
||||||
"\n",
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
" ```\n",
|
" ```\n",
|
||||||
"\n",
|
"\n",
|
||||||
" forecast_origin = pd.to_datetime('2012-09-01') + pd.DateOffset(days=5) # forecast 5 days after end of training\n",
|
" forecast_origin = pd.to_datetime(\"2012-09-01\") + pd.DateOffset(days=5) # forecast 5 days after end of training\n",
|
||||||
" print(forecast_origin)\n",
|
" print(forecast_origin)\n",
|
||||||
"\n",
|
"\n",
|
||||||
" X_query, y_query = make_forecasting_query(data, \n",
|
" X_query, y_query = make_forecasting_query(data,\n",
|
||||||
" forecast_origin = forecast_origin,\n",
|
" forecast_origin = forecast_origin,\n",
|
||||||
" horizon = pd.DateOffset(days=7), # 7 days into the future\n",
|
" horizon = pd.DateOffset(days=7), # 7 days into the future\n",
|
||||||
" lookback = pd.DateOffset(days=1), # model has lag 1 period (day)\n",
|
" lookback = pd.DateOffset(days=1), # model has lag 1 period (day)\n",
|
||||||
@@ -614,28 +637,30 @@
|
|||||||
" ```\n",
|
" ```\n",
|
||||||
" \"\"\"\n",
|
" \"\"\"\n",
|
||||||
"\n",
|
"\n",
|
||||||
" X_past = fulldata[ (fulldata[ time_column_name ] > forecast_origin - lookback) &\n",
|
" X_past = fulldata[\n",
|
||||||
" (fulldata[ time_column_name ] <= forecast_origin)\n",
|
" (fulldata[time_column_name] > forecast_origin - lookback)\n",
|
||||||
" ]\n",
|
" & (fulldata[time_column_name] <= forecast_origin)\n",
|
||||||
|
" ]\n",
|
||||||
"\n",
|
"\n",
|
||||||
" X_future = fulldata[ (fulldata[ time_column_name ] > forecast_origin) &\n",
|
" X_future = fulldata[\n",
|
||||||
" (fulldata[ time_column_name ] <= forecast_origin + horizon)\n",
|
" (fulldata[time_column_name] > forecast_origin)\n",
|
||||||
" ]\n",
|
" & (fulldata[time_column_name] <= forecast_origin + horizon)\n",
|
||||||
|
" ]\n",
|
||||||
"\n",
|
"\n",
|
||||||
" y_past = X_past.pop(target_column_name).values.astype(np.float)\n",
|
" y_past = X_past.pop(target_column_name).values.astype(np.float)\n",
|
||||||
" y_future = X_future.pop(target_column_name).values.astype(np.float)\n",
|
" y_future = X_future.pop(target_column_name).values.astype(np.float)\n",
|
||||||
"\n",
|
"\n",
|
||||||
" # Now take y_future and turn it into question marks\n",
|
" # Now take y_future and turn it into question marks\n",
|
||||||
" y_query = y_future.copy().astype(np.float) # because sometimes life hands you an int\n",
|
" y_query = y_future.copy().astype(\n",
|
||||||
|
" np.float\n",
|
||||||
|
" ) # because sometimes life hands you an int\n",
|
||||||
" y_query.fill(np.NaN)\n",
|
" y_query.fill(np.NaN)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"\n",
|
|
||||||
" print(\"X_past is \" + str(X_past.shape) + \" - shaped\")\n",
|
" print(\"X_past is \" + str(X_past.shape) + \" - shaped\")\n",
|
||||||
" print(\"X_future is \" + str(X_future.shape) + \" - shaped\")\n",
|
" print(\"X_future is \" + str(X_future.shape) + \" - shaped\")\n",
|
||||||
" print(\"y_past is \" + str(y_past.shape) + \" - shaped\")\n",
|
" print(\"y_past is \" + str(y_past.shape) + \" - shaped\")\n",
|
||||||
" print(\"y_query is \" + str(y_query.shape) + \" - shaped\")\n",
|
" print(\"y_query is \" + str(y_query.shape) + \" - shaped\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"\n",
|
|
||||||
" X_pred = pd.concat([X_past, X_future])\n",
|
" X_pred = pd.concat([X_past, X_future])\n",
|
||||||
" y_pred = np.concatenate([y_past, y_query])\n",
|
" y_pred = np.concatenate([y_past, y_query])\n",
|
||||||
" return X_pred, y_pred"
|
" return X_pred, y_pred"
|
||||||
@@ -654,8 +679,16 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"print(X_context.groupby(TIME_SERIES_ID_COLUMN_NAME)[TIME_COLUMN_NAME].agg(['min','max','count']))\n",
|
"print(\n",
|
||||||
"print(X_away.groupby(TIME_SERIES_ID_COLUMN_NAME)[TIME_COLUMN_NAME].agg(['min','max','count']))\n",
|
" X_context.groupby(TIME_SERIES_ID_COLUMN_NAME)[TIME_COLUMN_NAME].agg(\n",
|
||||||
|
" [\"min\", \"max\", \"count\"]\n",
|
||||||
|
" )\n",
|
||||||
|
")\n",
|
||||||
|
"print(\n",
|
||||||
|
" X_away.groupby(TIME_SERIES_ID_COLUMN_NAME)[TIME_COLUMN_NAME].agg(\n",
|
||||||
|
" [\"min\", \"max\", \"count\"]\n",
|
||||||
|
" )\n",
|
||||||
|
")\n",
|
||||||
"X_context.tail(5)"
|
"X_context.tail(5)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -665,11 +698,11 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"# Since the length of the lookback is 3, \n",
|
"# Since the length of the lookback is 3,\n",
|
||||||
"# we need to add 3 periods from the context to the request\n",
|
"# we need to add 3 periods from the context to the request\n",
|
||||||
"# so that the model has the data it needs\n",
|
"# so that the model has the data it needs\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# Put the X and y back together for a while. \n",
|
"# Put the X and y back together for a while.\n",
|
||||||
"# They like each other and it makes them happy.\n",
|
"# They like each other and it makes them happy.\n",
|
||||||
"X_context[TARGET_COLUMN_NAME] = y_context\n",
|
"X_context[TARGET_COLUMN_NAME] = y_context\n",
|
||||||
"X_away[TARGET_COLUMN_NAME] = y_away\n",
|
"X_away[TARGET_COLUMN_NAME] = y_away\n",
|
||||||
@@ -680,7 +713,7 @@
|
|||||||
"# it is indeed the last point of the context\n",
|
"# it is indeed the last point of the context\n",
|
||||||
"assert forecast_origin == X_context[TIME_COLUMN_NAME].max()\n",
|
"assert forecast_origin == X_context[TIME_COLUMN_NAME].max()\n",
|
||||||
"print(\"Forecast origin: \" + str(forecast_origin))\n",
|
"print(\"Forecast origin: \" + str(forecast_origin))\n",
|
||||||
" \n",
|
"\n",
|
||||||
"# the model uses lags and rolling windows to look back in time\n",
|
"# the model uses lags and rolling windows to look back in time\n",
|
||||||
"n_lookback_periods = max(lags)\n",
|
"n_lookback_periods = max(lags)\n",
|
||||||
"lookback = pd.DateOffset(hours=n_lookback_periods)\n",
|
"lookback = pd.DateOffset(hours=n_lookback_periods)\n",
|
||||||
@@ -688,8 +721,9 @@
|
|||||||
"horizon = pd.DateOffset(hours=forecast_horizon)\n",
|
"horizon = pd.DateOffset(hours=forecast_horizon)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# now make the forecast query from context (refer to figure)\n",
|
"# now make the forecast query from context (refer to figure)\n",
|
||||||
"X_pred, y_pred = make_forecasting_query(fulldata, TIME_COLUMN_NAME, TARGET_COLUMN_NAME,\n",
|
"X_pred, y_pred = make_forecasting_query(\n",
|
||||||
" forecast_origin, horizon, lookback)\n",
|
" fulldata, TIME_COLUMN_NAME, TARGET_COLUMN_NAME, forecast_origin, horizon, lookback\n",
|
||||||
|
")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# show the forecast request aligned\n",
|
"# show the forecast request aligned\n",
|
||||||
"X_show = X_pred.copy()\n",
|
"X_show = X_pred.copy()\n",
|
||||||
@@ -716,7 +750,7 @@
|
|||||||
"# show the forecast aligned\n",
|
"# show the forecast aligned\n",
|
||||||
"X_show = xy_away.reset_index()\n",
|
"X_show = xy_away.reset_index()\n",
|
||||||
"# without the generated features\n",
|
"# without the generated features\n",
|
||||||
"X_show[['date', 'time_series_id', 'ext_predictor', '_automl_target_col']]\n",
|
"X_show[[\"date\", \"time_series_id\", \"ext_predictor\", \"_automl_target_col\"]]\n",
|
||||||
"# prediction is in _automl_target_col"
|
"# prediction is in _automl_target_col"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -747,12 +781,14 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"# generate the same kind of test data we trained on, but with a single time-series and test period twice as long\n",
|
"# generate the same kind of test data we trained on, but with a single time-series and test period twice as long\n",
|
||||||
"# as the forecast_horizon.\n",
|
"# as the forecast_horizon.\n",
|
||||||
"_, _, X_test_long, y_test_long = get_timeseries(train_len=n_train_periods,\n",
|
"_, _, X_test_long, y_test_long = get_timeseries(\n",
|
||||||
" test_len=forecast_horizon*2,\n",
|
" train_len=n_train_periods,\n",
|
||||||
" time_column_name=TIME_COLUMN_NAME,\n",
|
" test_len=forecast_horizon * 2,\n",
|
||||||
" target_column_name=TARGET_COLUMN_NAME,\n",
|
" time_column_name=TIME_COLUMN_NAME,\n",
|
||||||
" time_series_id_column_name=TIME_SERIES_ID_COLUMN_NAME,\n",
|
" target_column_name=TARGET_COLUMN_NAME,\n",
|
||||||
" time_series_number=1)\n",
|
" time_series_id_column_name=TIME_SERIES_ID_COLUMN_NAME,\n",
|
||||||
|
" time_series_number=1,\n",
|
||||||
|
")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"print(X_test_long.groupby(TIME_SERIES_ID_COLUMN_NAME)[TIME_COLUMN_NAME].min())\n",
|
"print(X_test_long.groupby(TIME_SERIES_ID_COLUMN_NAME)[TIME_COLUMN_NAME].min())\n",
|
||||||
"print(X_test_long.groupby(TIME_SERIES_ID_COLUMN_NAME)[TIME_COLUMN_NAME].max())"
|
"print(X_test_long.groupby(TIME_SERIES_ID_COLUMN_NAME)[TIME_COLUMN_NAME].max())"
|
||||||
@@ -775,9 +811,11 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"# What forecast() function does in this case is equivalent to iterating it twice over the test set as the following. \n",
|
"# What forecast() function does in this case is equivalent to iterating it twice over the test set as the following.\n",
|
||||||
"y_pred1, _ = fitted_model.forecast(X_test_long[:forecast_horizon])\n",
|
"y_pred1, _ = fitted_model.forecast(X_test_long[:forecast_horizon])\n",
|
||||||
"y_pred_all, _ = fitted_model.forecast(X_test_long, np.concatenate((y_pred1, np.full(forecast_horizon, np.nan))))\n",
|
"y_pred_all, _ = fitted_model.forecast(\n",
|
||||||
|
" X_test_long, np.concatenate((y_pred1, np.full(forecast_horizon, np.nan)))\n",
|
||||||
|
")\n",
|
||||||
"np.array_equal(y_pred_all, y_pred_long)"
|
"np.array_equal(y_pred_all, y_pred_long)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -809,7 +847,7 @@
|
|||||||
"metadata": {
|
"metadata": {
|
||||||
"authors": [
|
"authors": [
|
||||||
{
|
{
|
||||||
"name": "erwright"
|
"name": "jialiu"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"category": "tutorial",
|
"category": "tutorial",
|
||||||
|
|||||||
@@ -0,0 +1,639 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
||||||
|
"\n",
|
||||||
|
"Licensed under the MIT License."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
""
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Hierarchical Time Series - Automated ML\n",
|
||||||
|
"**_Generate hierarchical time series forecasts with Automated Machine Learning_**\n",
|
||||||
|
"\n",
|
||||||
|
"---"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"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.\n",
|
||||||
|
"\n",
|
||||||
|
"**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).**"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Prerequisites\n",
|
||||||
|
"You'll need to create a compute Instance by following the instructions in the [EnvironmentSetup.md](../Setup_Resources/EnvironmentSetup.md)."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## 1.0 Set up workspace, datastore, experiment"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {
|
||||||
|
"gather": {
|
||||||
|
"logged": 1613003526897
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"import azureml.core\n",
|
||||||
|
"from azureml.core import Workspace, Datastore\n",
|
||||||
|
"import pandas as pd\n",
|
||||||
|
"\n",
|
||||||
|
"# Set up your workspace\n",
|
||||||
|
"ws = Workspace.from_config()\n",
|
||||||
|
"ws.get_details()\n",
|
||||||
|
"\n",
|
||||||
|
"# Set up your datastores\n",
|
||||||
|
"dstore = ws.get_default_datastore()\n",
|
||||||
|
"\n",
|
||||||
|
"output = {}\n",
|
||||||
|
"output[\"SDK version\"] = azureml.core.VERSION\n",
|
||||||
|
"output[\"Subscription ID\"] = ws.subscription_id\n",
|
||||||
|
"output[\"Workspace\"] = ws.name\n",
|
||||||
|
"output[\"Resource Group\"] = ws.resource_group\n",
|
||||||
|
"output[\"Location\"] = ws.location\n",
|
||||||
|
"output[\"Default datastore name\"] = dstore.name\n",
|
||||||
|
"pd.set_option(\"display.max_colwidth\", -1)\n",
|
||||||
|
"outputDf = pd.DataFrame(data=output, index=[\"\"])\n",
|
||||||
|
"outputDf.T"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Choose an experiment"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {
|
||||||
|
"gather": {
|
||||||
|
"logged": 1613003540729
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core import Experiment\n",
|
||||||
|
"\n",
|
||||||
|
"experiment = Experiment(ws, \"automl-hts\")\n",
|
||||||
|
"\n",
|
||||||
|
"print(\"Experiment name: \" + experiment.name)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## 2.0 Data\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"nteract": {
|
||||||
|
"transient": {
|
||||||
|
"deleting": false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"### Upload local csv files to datastore\n",
|
||||||
|
"You can upload your train and inference csv files to the default datastore in your workspace. \n",
|
||||||
|
"\n",
|
||||||
|
"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.\n",
|
||||||
|
"Please refer to [Datastore](https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.datastore.datastore?view=azure-ml-py) documentation on how to access data from Datastore."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"datastore_path = \"hts-sample\""
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"datastore = ws.get_default_datastore()\n",
|
||||||
|
"datastore"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Create the TabularDatasets \n",
|
||||||
|
"\n",
|
||||||
|
"Datasets in Azure Machine Learning are references to specific data in a Datastore. The data can be retrieved as a [TabularDatasets](https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.data.tabulardataset?view=azure-ml-py). 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."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {
|
||||||
|
"gather": {
|
||||||
|
"logged": 1613007017296
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.data.dataset_factory import TabularDatasetFactory\n",
|
||||||
|
"\n",
|
||||||
|
"registered_train = TabularDatasetFactory.register_pandas_dataframe(\n",
|
||||||
|
" pd.read_csv(\"Data/hts-sample-train.csv\"),\n",
|
||||||
|
" target=(datastore, \"hts-sample\"),\n",
|
||||||
|
" name=\"hts-sales-train\",\n",
|
||||||
|
")\n",
|
||||||
|
"registered_inference = TabularDatasetFactory.register_pandas_dataframe(\n",
|
||||||
|
" pd.read_csv(\"Data/hts-sample-test.csv\"),\n",
|
||||||
|
" target=(datastore, \"hts-sample\"),\n",
|
||||||
|
" name=\"hts-sales-test\",\n",
|
||||||
|
")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## 3.0 Build the training pipeline\n",
|
||||||
|
"Now that the dataset, WorkSpace, and datastore are set up, we can put together a pipeline for training.\n",
|
||||||
|
"\n",
|
||||||
|
"> 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."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Choose a compute target\n",
|
||||||
|
"\n",
|
||||||
|
"You will need to create a [compute target](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-set-up-training-targets#amlcompute) for your AutoML run. In this tutorial, you create AmlCompute as your training compute resource.\n",
|
||||||
|
"\n",
|
||||||
|
"\\*\\*Creation of AmlCompute takes approximately 5 minutes.**\n",
|
||||||
|
"\n",
|
||||||
|
"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](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-manage-quotas) on the default limits and how to request more quota."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {
|
||||||
|
"gather": {
|
||||||
|
"logged": 1613007037308
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core.compute import ComputeTarget, AmlCompute\n",
|
||||||
|
"\n",
|
||||||
|
"# Name your cluster\n",
|
||||||
|
"compute_name = \"hts-compute\"\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"if compute_name in ws.compute_targets:\n",
|
||||||
|
" compute_target = ws.compute_targets[compute_name]\n",
|
||||||
|
" if compute_target and type(compute_target) is AmlCompute:\n",
|
||||||
|
" print(\"Found compute target: \" + compute_name)\n",
|
||||||
|
"else:\n",
|
||||||
|
" print(\"Creating a new compute target...\")\n",
|
||||||
|
" provisioning_config = AmlCompute.provisioning_configuration(\n",
|
||||||
|
" vm_size=\"STANDARD_D16S_V3\", max_nodes=20\n",
|
||||||
|
" )\n",
|
||||||
|
" # Create the compute target\n",
|
||||||
|
" compute_target = ComputeTarget.create(ws, compute_name, provisioning_config)\n",
|
||||||
|
"\n",
|
||||||
|
" # Can poll for a minimum number of nodes and for a specific timeout.\n",
|
||||||
|
" # If no min node count is provided it will use the scale settings for the cluster\n",
|
||||||
|
" compute_target.wait_for_completion(\n",
|
||||||
|
" show_output=True, min_node_count=None, timeout_in_minutes=20\n",
|
||||||
|
" )\n",
|
||||||
|
"\n",
|
||||||
|
" # For a more detailed view of current cluster status, use the 'status' property\n",
|
||||||
|
" print(compute_target.status.serialize())"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Set up training parameters\n",
|
||||||
|
"\n",
|
||||||
|
"This dictionary defines the AutoML and hierarchy settings. For this forecasting task we need to define several settings inncluding the name of the time column, the maximum forecast horizon, the hierarchy definition, and the level of the hierarchy at which to train.\n",
|
||||||
|
"\n",
|
||||||
|
"| Property | Description|\n",
|
||||||
|
"| :--------------- | :------------------- |\n",
|
||||||
|
"| **task** | forecasting |\n",
|
||||||
|
"| **primary_metric** | This is the metric that you want to optimize.<br> Forecasting supports the following primary metrics <br><i>spearman_correlation</i><br><i>normalized_root_mean_squared_error</i><br><i>r2_score</i><br><i>normalized_mean_absolute_error</i> |\n",
|
||||||
|
"| **blocked_models** | Blocked models won't be used by AutoML. |\n",
|
||||||
|
"| **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. |\n",
|
||||||
|
"| **iterations** | Number of models to train. This is optional but provides customers with greater control on exit criteria. |\n",
|
||||||
|
"| **experiment_timeout_hours** | Maximum amount of time in hours that the experiment can take before it terminates. This is optional but provides customers with greater control on exit criteria. |\n",
|
||||||
|
"| **label_column_name** | The name of the label column. |\n",
|
||||||
|
"| **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. |\n",
|
||||||
|
"| **n_cross_validations** | Number of cross validation splits. Rolling Origin Validation is used to split time-series in a temporally consistent way. |\n",
|
||||||
|
"| **enable_early_stopping** | Flag to enable early termination if the score is not improving in the short term. |\n",
|
||||||
|
"| **time_column_name** | The name of your time column. |\n",
|
||||||
|
"| **hierarchy_column_names** | The names of columns that define the hierarchical structure of the data from highest level to most granular. |\n",
|
||||||
|
"| **training_level** | The level of the hierarchy to be used for training models. |\n",
|
||||||
|
"| **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. |\n",
|
||||||
|
"| **time_series_id_column_name** | The column names used to uniquely identify timeseries in data that has multiple rows with the same timestamp. |\n",
|
||||||
|
"| **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). |\n",
|
||||||
|
"| **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. |\n",
|
||||||
|
"| **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](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-machine-learning-interpretability-automl). |"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {
|
||||||
|
"gather": {
|
||||||
|
"logged": 1613007061544
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.train.automl.runtime._hts.hts_parameters import HTSTrainParameters\n",
|
||||||
|
"\n",
|
||||||
|
"model_explainability = True\n",
|
||||||
|
"\n",
|
||||||
|
"engineered_explanations = False\n",
|
||||||
|
"# Define your hierarchy. Adjust the settings below based on your dataset.\n",
|
||||||
|
"hierarchy = [\"state\", \"store_id\", \"product_category\", \"SKU\"]\n",
|
||||||
|
"training_level = \"SKU\"\n",
|
||||||
|
"\n",
|
||||||
|
"# Set your forecast parameters. Adjust the settings below based on your dataset.\n",
|
||||||
|
"time_column_name = \"date\"\n",
|
||||||
|
"label_column_name = \"quantity\"\n",
|
||||||
|
"forecast_horizon = 7\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"automl_settings = {\n",
|
||||||
|
" \"task\": \"forecasting\",\n",
|
||||||
|
" \"primary_metric\": \"normalized_root_mean_squared_error\",\n",
|
||||||
|
" \"label_column_name\": label_column_name,\n",
|
||||||
|
" \"time_column_name\": time_column_name,\n",
|
||||||
|
" \"forecast_horizon\": forecast_horizon,\n",
|
||||||
|
" \"hierarchy_column_names\": hierarchy,\n",
|
||||||
|
" \"hierarchy_training_level\": training_level,\n",
|
||||||
|
" \"track_child_runs\": False,\n",
|
||||||
|
" \"pipeline_fetch_max_batch_size\": 15,\n",
|
||||||
|
" \"model_explainability\": model_explainability,\n",
|
||||||
|
" # The following settings are specific to this sample and should be adjusted according to your own needs.\n",
|
||||||
|
" \"iteration_timeout_minutes\": 10,\n",
|
||||||
|
" \"iterations\": 10,\n",
|
||||||
|
" \"n_cross_validations\": 2,\n",
|
||||||
|
"}\n",
|
||||||
|
"\n",
|
||||||
|
"hts_parameters = HTSTrainParameters(\n",
|
||||||
|
" automl_settings=automl_settings,\n",
|
||||||
|
" hierarchy_column_names=hierarchy,\n",
|
||||||
|
" training_level=training_level,\n",
|
||||||
|
" enable_engineered_explanations=engineered_explanations,\n",
|
||||||
|
")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Set up hierarchy training pipeline"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Parallel run step is leveraged to train the hierarchy. 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.\n",
|
||||||
|
"\n",
|
||||||
|
"* **experiment:** The experiment used for training.\n",
|
||||||
|
"* **train_data:** The tabular dataset to be used as input to the training run.\n",
|
||||||
|
"* **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.\n",
|
||||||
|
"* **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 or optimal performance.\n",
|
||||||
|
"* **train_pipeline_parameters:** The set of configuration parameters defined in the previous section. \n",
|
||||||
|
"\n",
|
||||||
|
"Calling this method will create a new aggregated dataset which is generated dynamically on pipeline execution."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.contrib.automl.pipeline.steps import AutoMLPipelineBuilder\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"training_pipeline_steps = AutoMLPipelineBuilder.get_many_models_train_steps(\n",
|
||||||
|
" experiment=experiment,\n",
|
||||||
|
" train_data=registered_train,\n",
|
||||||
|
" compute_target=compute_target,\n",
|
||||||
|
" node_count=2,\n",
|
||||||
|
" process_count_per_node=8,\n",
|
||||||
|
" train_pipeline_parameters=hts_parameters,\n",
|
||||||
|
")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.pipeline.core import Pipeline\n",
|
||||||
|
"\n",
|
||||||
|
"training_pipeline = Pipeline(ws, steps=training_pipeline_steps)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Submit the pipeline to run\n",
|
||||||
|
"Next we submit our pipeline to run. The whole training pipeline takes about 1h 11m using a Standard_D12_V2 VM with our current ParallelRunConfig setting."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"training_run = experiment.submit(training_pipeline)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"training_run.wait_for_completion(show_output=False)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"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."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### [Optional] Get the explanations\n",
|
||||||
|
"First we need to download the explanations to the local disk."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"if model_explainability:\n",
|
||||||
|
" expl_output = training_run.get_pipeline_output(\"explanations\")\n",
|
||||||
|
" expl_output.download(\"training_explanations\")\n",
|
||||||
|
"else:\n",
|
||||||
|
" print(\n",
|
||||||
|
" \"Model explanations are available only if model_explainability is set to True.\"\n",
|
||||||
|
" )"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"The explanations are downloaded to the \"training_explanations/azureml\" directory."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"import os\n",
|
||||||
|
"\n",
|
||||||
|
"if model_explainability:\n",
|
||||||
|
" explanations_dirrectory = os.listdir(\n",
|
||||||
|
" os.path.join(\"training_explanations\", \"azureml\")\n",
|
||||||
|
" )\n",
|
||||||
|
" if len(explanations_dirrectory) > 1:\n",
|
||||||
|
" print(\n",
|
||||||
|
" \"Warning! The directory contains multiple explanations, only the first one will be displayed.\"\n",
|
||||||
|
" )\n",
|
||||||
|
" print(\"The explanations are located at {}.\".format(explanations_dirrectory[0]))\n",
|
||||||
|
" # Now we will list all the explanations.\n",
|
||||||
|
" explanation_path = os.path.join(\n",
|
||||||
|
" \"training_explanations\",\n",
|
||||||
|
" \"azureml\",\n",
|
||||||
|
" explanations_dirrectory[0],\n",
|
||||||
|
" \"training_explanations\",\n",
|
||||||
|
" )\n",
|
||||||
|
" print(\"Available explanations\")\n",
|
||||||
|
" print(\"==============================\")\n",
|
||||||
|
" print(\"\\n\".join(os.listdir(explanation_path)))\n",
|
||||||
|
"else:\n",
|
||||||
|
" print(\n",
|
||||||
|
" \"Model explanations are available only if model_explainability is set to True.\"\n",
|
||||||
|
" )"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"View the explanations on \"state\" level."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from IPython.display import display\n",
|
||||||
|
"\n",
|
||||||
|
"explanation_type = \"raw\"\n",
|
||||||
|
"level = \"state\"\n",
|
||||||
|
"\n",
|
||||||
|
"if model_explainability:\n",
|
||||||
|
" display(\n",
|
||||||
|
" pd.read_csv(\n",
|
||||||
|
" os.path.join(explanation_path, \"{}_explanations_{}.csv\").format(\n",
|
||||||
|
" explanation_type, level\n",
|
||||||
|
" )\n",
|
||||||
|
" )\n",
|
||||||
|
" )"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## 5.0 Forecasting\n",
|
||||||
|
"For hierarchical forecasting we need to provide the HTSInferenceParameters object.\n",
|
||||||
|
"#### HTSInferenceParameters arguments\n",
|
||||||
|
"* **hierarchy_forecast_level:** The default level of the hierarchy to produce prediction/forecast on.\n",
|
||||||
|
"* **allocation_method:** \\[Optional] The disaggregation method to use if the hierarchy forecast level specified is below the define hierarchy training level. <br><i>(average historical proportions) 'average_historical_proportions'</i><br><i>(proportions of the historical averages) 'proportions_of_historical_average'</i>\n",
|
||||||
|
"\n",
|
||||||
|
"#### get_many_models_batch_inference_steps arguments\n",
|
||||||
|
"* **experiment:** The experiment used for inference run.\n",
|
||||||
|
"* **inference_data:** The data to use for inferencing. It should be the same schema as used for training.\n",
|
||||||
|
"* **compute_target:** The compute target that runs the inference pipeline.\n",
|
||||||
|
"* **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).\n",
|
||||||
|
"* **process_count_per_node:** The number of processes per node.\n",
|
||||||
|
"* **train_run_id:** \\[Optional] The run id of the hierarchy training, by default it is the latest successful training hts run in the experiment.\n",
|
||||||
|
"* **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.\n",
|
||||||
|
"* **process_count_per_node:** \\[Optional] The number of processes per node, by default it's 4."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.train.automl.runtime._hts.hts_parameters import HTSInferenceParameters\n",
|
||||||
|
"\n",
|
||||||
|
"inference_parameters = HTSInferenceParameters(\n",
|
||||||
|
" hierarchy_forecast_level=\"store_id\", # The setting is specific to this dataset and should be changed based on your dataset.\n",
|
||||||
|
" allocation_method=\"proportions_of_historical_average\",\n",
|
||||||
|
")\n",
|
||||||
|
"\n",
|
||||||
|
"steps = AutoMLPipelineBuilder.get_many_models_batch_inference_steps(\n",
|
||||||
|
" experiment=experiment,\n",
|
||||||
|
" inference_data=registered_inference,\n",
|
||||||
|
" compute_target=compute_target,\n",
|
||||||
|
" inference_pipeline_parameters=inference_parameters,\n",
|
||||||
|
" node_count=2,\n",
|
||||||
|
" process_count_per_node=8,\n",
|
||||||
|
")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.pipeline.core import Pipeline\n",
|
||||||
|
"\n",
|
||||||
|
"inference_pipeline = Pipeline(ws, steps=steps)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"inference_run = experiment.submit(inference_pipeline)\n",
|
||||||
|
"inference_run.wait_for_completion(show_output=False)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Retrieve results\n",
|
||||||
|
"\n",
|
||||||
|
"Forecast results can be retrieved through the following code. The prediction results summary and the actual predictions are downloaded the \"forecast_results\" folder"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"forecasts = inference_run.get_pipeline_output(\"forecasts\")\n",
|
||||||
|
"forecasts.download(\"forecast_results\")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Resbumit the Pipeline\n",
|
||||||
|
"\n",
|
||||||
|
"The inference pipeline can be submitted with different configurations."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"inference_run = experiment.submit(\n",
|
||||||
|
" inference_pipeline, pipeline_parameters={\"hierarchy_forecast_level\": \"state\"}\n",
|
||||||
|
")\n",
|
||||||
|
"inference_run.wait_for_completion(show_output=False)"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"authors": [
|
||||||
|
{
|
||||||
|
"name": "jialiu"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"categories": [
|
||||||
|
"how-to-use-azureml",
|
||||||
|
"automated-machine-learning"
|
||||||
|
],
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 3.6",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python36"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"codemirror_mode": {
|
||||||
|
"name": "ipython",
|
||||||
|
"version": 3
|
||||||
|
},
|
||||||
|
"file_extension": ".py",
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython3",
|
||||||
|
"version": "3.6.8"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 4
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
name: auto-ml-forecasting-hierarchical-timeseries
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
@@ -0,0 +1,746 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
||||||
|
"\n",
|
||||||
|
"Licensed under the MIT License."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
""
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Many Models - Automated ML\n",
|
||||||
|
"**_Generate many models time series forecasts with Automated Machine Learning_**\n",
|
||||||
|
"\n",
|
||||||
|
"---"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"For this notebook we are using a synthetic dataset portraying sales data to predict the quantity of a vartiety of product SKUs across several states, stores, and product categories.\n",
|
||||||
|
"\n",
|
||||||
|
"**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).**"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Prerequisites\n",
|
||||||
|
"You'll need to create a compute Instance by following the instructions in the [EnvironmentSetup.md](../Setup_Resources/EnvironmentSetup.md)."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## 1.0 Set up workspace, datastore, experiment"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {
|
||||||
|
"gather": {
|
||||||
|
"logged": 1613003526897
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"import azureml.core\n",
|
||||||
|
"from azureml.core import Workspace, Datastore\n",
|
||||||
|
"import pandas as pd\n",
|
||||||
|
"\n",
|
||||||
|
"# Set up your workspace\n",
|
||||||
|
"ws = Workspace.from_config()\n",
|
||||||
|
"ws.get_details()\n",
|
||||||
|
"\n",
|
||||||
|
"# Set up your datastores\n",
|
||||||
|
"dstore = ws.get_default_datastore()\n",
|
||||||
|
"\n",
|
||||||
|
"output = {}\n",
|
||||||
|
"output[\"SDK version\"] = azureml.core.VERSION\n",
|
||||||
|
"output[\"Subscription ID\"] = ws.subscription_id\n",
|
||||||
|
"output[\"Workspace\"] = ws.name\n",
|
||||||
|
"output[\"Resource Group\"] = ws.resource_group\n",
|
||||||
|
"output[\"Location\"] = ws.location\n",
|
||||||
|
"output[\"Default datastore name\"] = dstore.name\n",
|
||||||
|
"pd.set_option(\"display.max_colwidth\", -1)\n",
|
||||||
|
"outputDf = pd.DataFrame(data=output, index=[\"\"])\n",
|
||||||
|
"outputDf.T"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Choose an experiment"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {
|
||||||
|
"gather": {
|
||||||
|
"logged": 1613003540729
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core import Experiment\n",
|
||||||
|
"\n",
|
||||||
|
"experiment = Experiment(ws, \"automl-many-models\")\n",
|
||||||
|
"\n",
|
||||||
|
"print(\"Experiment name: \" + experiment.name)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## 2.0 Data\n",
|
||||||
|
"\n",
|
||||||
|
"This notebook uses simulated orange juice sales data to walk you through the process of training many models on Azure Machine Learning using Automated ML. \n",
|
||||||
|
"\n",
|
||||||
|
"The time series data used in this example was simulated based on the University of Chicago's Dominick's Finer Foods dataset which featured two years of sales of 3 different orange juice brands for individual stores. The full simulated dataset includes 3,991 stores with 3 orange juice brands each thus allowing 11,973 models to be trained to showcase the power of the many models pattern.\n",
|
||||||
|
"\n",
|
||||||
|
" \n",
|
||||||
|
"In this notebook, two datasets will be created: one with all 11,973 files and one with only 10 files that can be used to quickly test and debug. For each dataset, you'll be walked through the process of:\n",
|
||||||
|
"\n",
|
||||||
|
"1. Registering the blob container as a Datastore to the Workspace\n",
|
||||||
|
"2. Registering a tabular dataset to the Workspace"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"nteract": {
|
||||||
|
"transient": {
|
||||||
|
"deleting": false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"### 2.1 Data Preparation\n",
|
||||||
|
"The OJ data is available in the public blob container. The data is split to be used for training and for inferencing. For the current dataset, the data was split on time column ('WeekStarting') before and after '1992-5-28' .\n",
|
||||||
|
"\n",
|
||||||
|
"The container has\n",
|
||||||
|
"<ol>\n",
|
||||||
|
" <li><b>'oj-data-tabular'</b> and <b>'oj-inference-tabular'</b> folders that contains training and inference data respectively for the 11,973 models. </li>\n",
|
||||||
|
" <li>It also has <b>'oj-data-small-tabular'</b> and <b>'oj-inference-small-tabular'</b> folders that has training and inference data for 10 models.</li>\n",
|
||||||
|
"</ol>\n",
|
||||||
|
"\n",
|
||||||
|
"To create the [TabularDataset](https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.data.tabular_dataset.tabulardataset?view=azure-ml-py) needed for the ParallelRunStep, you first need to register the blob container to the workspace."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"nteract": {
|
||||||
|
"transient": {
|
||||||
|
"deleting": false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"<b> To use your own data, put your own data in a blobstore folder. As shown it can be one file or multiple files. We can then register datastore using that blob as shown below.\n",
|
||||||
|
" \n",
|
||||||
|
"<h3> How sample data in blob store looks like</h3>\n",
|
||||||
|
"\n",
|
||||||
|
"['oj-data-tabular'](https://ms.portal.azure.com/#blade/Microsoft_Azure_Storage/ContainerMenuBlade/overview/storageAccountId/%2Fsubscriptions%2F102a16c3-37d3-48a8-9237-4c9b1e8e80e0%2FresourceGroups%2FAutoMLSampleNotebooksData%2Fproviders%2FMicrosoft.Storage%2FstorageAccounts%2Fautomlsamplenotebookdata/path/automl-sample-notebook-data/etag/%220x8D84EAA65DE50B7%22/defaultEncryptionScope/%24account-encryption-key/denyEncryptionScopeOverride//defaultId//publicAccessVal/Container)</b>\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"['oj-inference-tabular'](https://ms.portal.azure.com/#blade/Microsoft_Azure_Storage/ContainerMenuBlade/overview/storageAccountId/%2Fsubscriptions%2F102a16c3-37d3-48a8-9237-4c9b1e8e80e0%2FresourceGroups%2FAutoMLSampleNotebooksData%2Fproviders%2FMicrosoft.Storage%2FstorageAccounts%2Fautomlsamplenotebookdata/path/automl-sample-notebook-data/etag/%220x8D84EAA65DE50B7%22/defaultEncryptionScope/%24account-encryption-key/denyEncryptionScopeOverride//defaultId//publicAccessVal/Container)\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"['oj-data-small-tabular'](https://ms.portal.azure.com/#blade/Microsoft_Azure_Storage/ContainerMenuBlade/overview/storageAccountId/%2Fsubscriptions%2F102a16c3-37d3-48a8-9237-4c9b1e8e80e0%2FresourceGroups%2FAutoMLSampleNotebooksData%2Fproviders%2FMicrosoft.Storage%2FstorageAccounts%2Fautomlsamplenotebookdata/path/automl-sample-notebook-data/etag/%220x8D84EAA65DE50B7%22/defaultEncryptionScope/%24account-encryption-key/denyEncryptionScopeOverride//defaultId//publicAccessVal/Container)\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"['oj-inference-small-tabular'](https://ms.portal.azure.com/#blade/Microsoft_Azure_Storage/ContainerMenuBlade/overview/storageAccountId/%2Fsubscriptions%2F102a16c3-37d3-48a8-9237-4c9b1e8e80e0%2FresourceGroups%2FAutoMLSampleNotebooksData%2Fproviders%2FMicrosoft.Storage%2FstorageAccounts%2Fautomlsamplenotebookdata/path/automl-sample-notebook-data/etag/%220x8D84EAA65DE50B7%22/defaultEncryptionScope/%24account-encryption-key/denyEncryptionScopeOverride//defaultId//publicAccessVal/Container)\n",
|
||||||
|
""
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### 2.2 Register the blob container as DataStore\n",
|
||||||
|
"\n",
|
||||||
|
"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.\n",
|
||||||
|
"\n",
|
||||||
|
"Please refer to [Datastore](https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.datastore(class)?view=azure-ml-py) documentation on how to access data from Datastore.\n",
|
||||||
|
"\n",
|
||||||
|
"In this next step, we will be registering blob storage as datastore to the Workspace."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core import Datastore\n",
|
||||||
|
"\n",
|
||||||
|
"# Please change the following to point to your own blob container and pass in account_key\n",
|
||||||
|
"blob_datastore_name = \"automl_many_models\"\n",
|
||||||
|
"container_name = \"automl-sample-notebook-data\"\n",
|
||||||
|
"account_name = \"automlsamplenotebookdata\"\n",
|
||||||
|
"\n",
|
||||||
|
"oj_datastore = Datastore.register_azure_blob_container(\n",
|
||||||
|
" workspace=ws,\n",
|
||||||
|
" datastore_name=blob_datastore_name,\n",
|
||||||
|
" container_name=container_name,\n",
|
||||||
|
" account_name=account_name,\n",
|
||||||
|
" create_if_not_exists=True,\n",
|
||||||
|
")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### 2.3 Using tabular datasets \n",
|
||||||
|
"\n",
|
||||||
|
"Now that the datastore is available from the Workspace, [TabularDataset](https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.data.tabular_dataset.tabulardataset?view=azure-ml-py) can be created. Datasets in Azure Machine Learning are references to specific data in a Datastore. We are using TabularDataset, so that users who have their data which can be in one or many files (*.parquet or *.csv) and have not split up data according to group columns needed for training, can do so using out of box support for 'partiion_by' feature of TabularDataset shown in section 5.0 below."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {
|
||||||
|
"gather": {
|
||||||
|
"logged": 1613007017296
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core import Dataset\n",
|
||||||
|
"\n",
|
||||||
|
"ds_name_small = \"oj-data-small-tabular\"\n",
|
||||||
|
"input_ds_small = Dataset.Tabular.from_delimited_files(\n",
|
||||||
|
" path=oj_datastore.path(ds_name_small + \"/\"), validate=False\n",
|
||||||
|
")\n",
|
||||||
|
"\n",
|
||||||
|
"inference_name_small = \"oj-inference-small-tabular\"\n",
|
||||||
|
"inference_ds_small = Dataset.Tabular.from_delimited_files(\n",
|
||||||
|
" path=oj_datastore.path(inference_name_small + \"/\"), validate=False\n",
|
||||||
|
")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## 3.0 Build the training pipeline\n",
|
||||||
|
"Now that the dataset, WorkSpace, and datastore are set up, we can put together a pipeline for training.\n",
|
||||||
|
"\n",
|
||||||
|
"> 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."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Choose a compute target\n",
|
||||||
|
"\n",
|
||||||
|
"You will need to create a [compute target](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-set-up-training-targets#amlcompute) for your AutoML run. In this tutorial, you create AmlCompute as your training compute resource.\n",
|
||||||
|
"\n",
|
||||||
|
"\\*\\*Creation of AmlCompute takes approximately 5 minutes.**\n",
|
||||||
|
"\n",
|
||||||
|
"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](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-manage-quotas) on the default limits and how to request more quota."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {
|
||||||
|
"gather": {
|
||||||
|
"logged": 1613007037308
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core.compute import ComputeTarget, AmlCompute\n",
|
||||||
|
"\n",
|
||||||
|
"# Name your cluster\n",
|
||||||
|
"compute_name = \"mm-compute\"\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"if compute_name in ws.compute_targets:\n",
|
||||||
|
" compute_target = ws.compute_targets[compute_name]\n",
|
||||||
|
" if compute_target and type(compute_target) is AmlCompute:\n",
|
||||||
|
" print(\"Found compute target: \" + compute_name)\n",
|
||||||
|
"else:\n",
|
||||||
|
" print(\"Creating a new compute target...\")\n",
|
||||||
|
" provisioning_config = AmlCompute.provisioning_configuration(\n",
|
||||||
|
" vm_size=\"STANDARD_D16S_V3\", max_nodes=20\n",
|
||||||
|
" )\n",
|
||||||
|
" # Create the compute target\n",
|
||||||
|
" compute_target = ComputeTarget.create(ws, compute_name, provisioning_config)\n",
|
||||||
|
"\n",
|
||||||
|
" # Can poll for a minimum number of nodes and for a specific timeout.\n",
|
||||||
|
" # If no min node count is provided it will use the scale settings for the cluster\n",
|
||||||
|
" compute_target.wait_for_completion(\n",
|
||||||
|
" show_output=True, min_node_count=None, timeout_in_minutes=20\n",
|
||||||
|
" )\n",
|
||||||
|
"\n",
|
||||||
|
" # For a more detailed view of current cluster status, use the 'status' property\n",
|
||||||
|
" print(compute_target.status.serialize())"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Set up training parameters\n",
|
||||||
|
"\n",
|
||||||
|
"This dictionary defines the AutoML and many models settings. For this forecasting task we need to define several settings including the name of the time column, the maximum forecast horizon, and the partition column name definition.\n",
|
||||||
|
"\n",
|
||||||
|
"| Property | Description|\n",
|
||||||
|
"| :--------------- | :------------------- |\n",
|
||||||
|
"| **task** | forecasting |\n",
|
||||||
|
"| **primary_metric** | This is the metric that you want to optimize.<br> Forecasting supports the following primary metrics <br><i>spearman_correlation</i><br><i>normalized_root_mean_squared_error</i><br><i>r2_score</i><br><i>normalized_mean_absolute_error</i> |\n",
|
||||||
|
"| **blocked_models** | Blocked models won't be used by AutoML. |\n",
|
||||||
|
"| **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. |\n",
|
||||||
|
"| **iterations** | Number of models to train. This is optional but provides customers with greater control on exit criteria. |\n",
|
||||||
|
"| **experiment_timeout_hours** | Maximum amount of time in hours that the experiment can take before it terminates. This is optional but provides customers with greater control on exit criteria. |\n",
|
||||||
|
"| **label_column_name** | The name of the label column. |\n",
|
||||||
|
"| **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. |\n",
|
||||||
|
"| **n_cross_validations** | Number of cross validation splits. Rolling Origin Validation is used to split time-series in a temporally consistent way. |\n",
|
||||||
|
"| **enable_early_stopping** | Flag to enable early termination if the score is not improving in the short term. |\n",
|
||||||
|
"| **time_column_name** | The name of your time column. |\n",
|
||||||
|
"| **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. |\n",
|
||||||
|
"| **time_series_id_column_name** | The column names used to uniquely identify timeseries in data that has multiple rows with the same timestamp. |\n",
|
||||||
|
"| **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). |\n",
|
||||||
|
"| **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. |\n",
|
||||||
|
"| **partition_column_names** | The names of columns used to group your models. For timeseries, the groups must not split up individual time-series. That is, each group must contain one or more whole time-series. |"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {
|
||||||
|
"gather": {
|
||||||
|
"logged": 1613007061544
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.train.automl.runtime._many_models.many_models_parameters import (\n",
|
||||||
|
" ManyModelsTrainParameters,\n",
|
||||||
|
")\n",
|
||||||
|
"\n",
|
||||||
|
"partition_column_names = [\"Store\", \"Brand\"]\n",
|
||||||
|
"automl_settings = {\n",
|
||||||
|
" \"task\": \"forecasting\",\n",
|
||||||
|
" \"primary_metric\": \"normalized_root_mean_squared_error\",\n",
|
||||||
|
" \"iteration_timeout_minutes\": 10, # This needs to be changed based on the dataset. We ask customer to explore how long training is taking before settings this value\n",
|
||||||
|
" \"iterations\": 15,\n",
|
||||||
|
" \"experiment_timeout_hours\": 0.25,\n",
|
||||||
|
" \"label_column_name\": \"Quantity\",\n",
|
||||||
|
" \"n_cross_validations\": 3,\n",
|
||||||
|
" \"time_column_name\": \"WeekStarting\",\n",
|
||||||
|
" \"drop_column_names\": \"Revenue\",\n",
|
||||||
|
" \"max_horizon\": 6,\n",
|
||||||
|
" \"grain_column_names\": partition_column_names,\n",
|
||||||
|
" \"track_child_runs\": False,\n",
|
||||||
|
"}\n",
|
||||||
|
"\n",
|
||||||
|
"mm_paramters = ManyModelsTrainParameters(\n",
|
||||||
|
" automl_settings=automl_settings, partition_column_names=partition_column_names\n",
|
||||||
|
")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Set up many models pipeline"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"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.\n",
|
||||||
|
"\n",
|
||||||
|
"| Property | Description|\n",
|
||||||
|
"| :--------------- | :------------------- |\n",
|
||||||
|
"| **experiment** | The experiment used for training. |\n",
|
||||||
|
"| **train_data** | The file dataset to be used as input to the training run. |\n",
|
||||||
|
"| **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. |\n",
|
||||||
|
"| **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 or optimal performance. |\n",
|
||||||
|
"| **train_pipeline_parameters** | The set of configuration parameters defined in the previous section. |\n",
|
||||||
|
"\n",
|
||||||
|
"Calling this method will create a new aggregated dataset which is generated dynamically on pipeline execution."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.contrib.automl.pipeline.steps import AutoMLPipelineBuilder\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"training_pipeline_steps = AutoMLPipelineBuilder.get_many_models_train_steps(\n",
|
||||||
|
" experiment=experiment,\n",
|
||||||
|
" train_data=input_ds_small,\n",
|
||||||
|
" compute_target=compute_target,\n",
|
||||||
|
" node_count=2,\n",
|
||||||
|
" process_count_per_node=8,\n",
|
||||||
|
" run_invocation_timeout=920,\n",
|
||||||
|
" train_pipeline_parameters=mm_paramters,\n",
|
||||||
|
")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.pipeline.core import Pipeline\n",
|
||||||
|
"\n",
|
||||||
|
"training_pipeline = Pipeline(ws, steps=training_pipeline_steps)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Submit the pipeline to run\n",
|
||||||
|
"Next we submit our pipeline to run. The whole training pipeline takes about 40m using a STANDARD_D16S_V3 VM with our current ParallelRunConfig setting."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"training_run = experiment.submit(training_pipeline)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"training_run.wait_for_completion(show_output=False)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"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."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## 5.0 Publish and schedule the train pipeline (Optional)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### 5.1 Publish the pipeline\n",
|
||||||
|
"\n",
|
||||||
|
"Once you have a pipeline you're happy with, you can publish a pipeline so you can call it programmatically later on. See this [tutorial](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-create-your-first-pipeline#publish-a-pipeline) for additional information on publishing and calling pipelines."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# published_pipeline = training_pipeline.publish(name = 'automl_train_many_models',\n",
|
||||||
|
"# description = 'train many models',\n",
|
||||||
|
"# version = '1',\n",
|
||||||
|
"# continue_on_step_failure = False)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### 7.2 Schedule the pipeline\n",
|
||||||
|
"You can also [schedule the pipeline](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-schedule-pipelines) to run on a time-based or change-based schedule. This could be used to automatically retrain models every month or based on another trigger such as data drift."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# from azureml.pipeline.core import Schedule, ScheduleRecurrence\n",
|
||||||
|
"\n",
|
||||||
|
"# training_pipeline_id = published_pipeline.id\n",
|
||||||
|
"\n",
|
||||||
|
"# recurrence = ScheduleRecurrence(frequency=\"Month\", interval=1, start_time=\"2020-01-01T09:00:00\")\n",
|
||||||
|
"# recurring_schedule = Schedule.create(ws, name=\"automl_training_recurring_schedule\",\n",
|
||||||
|
"# description=\"Schedule Training Pipeline to run on the first day of every month\",\n",
|
||||||
|
"# pipeline_id=training_pipeline_id,\n",
|
||||||
|
"# experiment_name=experiment.name,\n",
|
||||||
|
"# recurrence=recurrence)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## 6.0 Forecasting"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Set up output dataset for inference data\n",
|
||||||
|
"Output of inference can be represented as [OutputFileDatasetConfig](https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.data.output_dataset_config.outputdatasetconfig?view=azure-ml-py) object and OutputFileDatasetConfig can be registered as a dataset. "
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.data import OutputFileDatasetConfig\n",
|
||||||
|
"\n",
|
||||||
|
"output_inference_data_ds = OutputFileDatasetConfig(\n",
|
||||||
|
" name=\"many_models_inference_output\", destination=(dstore, \"oj/inference_data/\")\n",
|
||||||
|
").register_on_complete(name=\"oj_inference_data_ds\")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"For many models we need to provide the ManyModelsInferenceParameters object.\n",
|
||||||
|
"\n",
|
||||||
|
"#### ManyModelsInferenceParameters arguments\n",
|
||||||
|
"| Property | Description|\n",
|
||||||
|
"| :--------------- | :------------------- |\n",
|
||||||
|
"| **partition_column_names** | List of column names that identifies groups. |\n",
|
||||||
|
"| **target_column_name** | \\[Optional] Column name only if the inference dataset has the target. |\n",
|
||||||
|
"| **time_column_name** | \\[Optional] Column name only if it is timeseries. |\n",
|
||||||
|
"| **many_models_run_id** | \\[Optional] Many models run id where models were trained. |\n",
|
||||||
|
"\n",
|
||||||
|
"#### get_many_models_batch_inference_steps arguments\n",
|
||||||
|
"| Property | Description|\n",
|
||||||
|
"| :--------------- | :------------------- |\n",
|
||||||
|
"| **experiment** | The experiment used for inference run. |\n",
|
||||||
|
"| **inference_data** | The data to use for inferencing. It should be the same schema as used for training.\n",
|
||||||
|
"| **compute_target** | The compute target that runs the inference pipeline.|\n",
|
||||||
|
"| **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). |\n",
|
||||||
|
"| **process_count_per_node** | The number of processes per node.\n",
|
||||||
|
"| **train_run_id** | \\[Optional\\] The run id of the hierarchy training, by default it is the latest successful training many model run in the experiment. |\n",
|
||||||
|
"| **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. |\n",
|
||||||
|
"| **process_count_per_node** | \\[Optional\\] The number of processes per node, by default it's 4. |"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.contrib.automl.pipeline.steps import AutoMLPipelineBuilder\n",
|
||||||
|
"from azureml.train.automl.runtime._many_models.many_models_parameters import (\n",
|
||||||
|
" ManyModelsInferenceParameters,\n",
|
||||||
|
")\n",
|
||||||
|
"\n",
|
||||||
|
"mm_parameters = ManyModelsInferenceParameters(\n",
|
||||||
|
" partition_column_names=[\"Store\", \"Brand\"],\n",
|
||||||
|
" time_column_name=\"WeekStarting\",\n",
|
||||||
|
" target_column_name=\"Quantity\",\n",
|
||||||
|
")\n",
|
||||||
|
"\n",
|
||||||
|
"inference_steps = AutoMLPipelineBuilder.get_many_models_batch_inference_steps(\n",
|
||||||
|
" experiment=experiment,\n",
|
||||||
|
" inference_data=inference_ds_small,\n",
|
||||||
|
" node_count=2,\n",
|
||||||
|
" process_count_per_node=8,\n",
|
||||||
|
" compute_target=compute_target,\n",
|
||||||
|
" run_invocation_timeout=300,\n",
|
||||||
|
" output_datastore=output_inference_data_ds,\n",
|
||||||
|
" train_run_id=training_run.id,\n",
|
||||||
|
" train_experiment_name=training_run.experiment.name,\n",
|
||||||
|
" inference_pipeline_parameters=mm_parameters,\n",
|
||||||
|
")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.pipeline.core import Pipeline\n",
|
||||||
|
"\n",
|
||||||
|
"inference_pipeline = Pipeline(ws, steps=inference_steps)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"inference_run = experiment.submit(inference_pipeline)\n",
|
||||||
|
"inference_run.wait_for_completion(show_output=False)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Retrieve results\n",
|
||||||
|
"\n",
|
||||||
|
"The forecasting pipeline forecasts the orange juice quantity for a Store by Brand. The pipeline returns one file with the predictions for each store and outputs the result to the forecasting_output Blob container. The details of the blob container is listed in 'forecasting_output.txt' under Outputs+logs. \n",
|
||||||
|
"\n",
|
||||||
|
"The following code snippet:\n",
|
||||||
|
"1. Downloads the contents of the output folder that is passed in the parallel run step \n",
|
||||||
|
"2. Reads the parallel_run_step.txt file that has the predictions as pandas dataframe and \n",
|
||||||
|
"3. Displays the top 10 rows of the predictions"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.contrib.automl.pipeline.steps.utilities import get_output_from_mm_pipeline\n",
|
||||||
|
"\n",
|
||||||
|
"forecasting_results_name = \"forecasting_results\"\n",
|
||||||
|
"forecasting_output_name = \"many_models_inference_output\"\n",
|
||||||
|
"forecast_file = get_output_from_mm_pipeline(\n",
|
||||||
|
" inference_run, forecasting_results_name, forecasting_output_name\n",
|
||||||
|
")\n",
|
||||||
|
"df = pd.read_csv(forecast_file, delimiter=\" \", header=None)\n",
|
||||||
|
"df.columns = [\n",
|
||||||
|
" \"Week Starting\",\n",
|
||||||
|
" \"Store\",\n",
|
||||||
|
" \"Brand\",\n",
|
||||||
|
" \"Quantity\",\n",
|
||||||
|
" \"Advert\",\n",
|
||||||
|
" \"Price\",\n",
|
||||||
|
" \"Revenue\",\n",
|
||||||
|
" \"Predicted\",\n",
|
||||||
|
"]\n",
|
||||||
|
"print(\n",
|
||||||
|
" \"Prediction has \", df.shape[0], \" rows. Here the first 10 rows are being displayed.\"\n",
|
||||||
|
")\n",
|
||||||
|
"df.head(10)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## 7.0 Publish and schedule the inference pipeline (Optional)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### 7.1 Publish the pipeline\n",
|
||||||
|
"\n",
|
||||||
|
"Once you have a pipeline you're happy with, you can publish a pipeline so you can call it programmatically later on. See this [tutorial](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-create-your-first-pipeline#publish-a-pipeline) for additional information on publishing and calling pipelines."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# published_pipeline_inf = inference_pipeline.publish(name = 'automl_forecast_many_models',\n",
|
||||||
|
"# description = 'forecast many models',\n",
|
||||||
|
"# version = '1',\n",
|
||||||
|
"# continue_on_step_failure = False)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### 7.2 Schedule the pipeline\n",
|
||||||
|
"You can also [schedule the pipeline](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-schedule-pipelines) to run on a time-based or change-based schedule. This could be used to automatically retrain or forecast models every month or based on another trigger such as data drift."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# from azureml.pipeline.core import Schedule, ScheduleRecurrence\n",
|
||||||
|
"\n",
|
||||||
|
"# forecasting_pipeline_id = published_pipeline.id\n",
|
||||||
|
"\n",
|
||||||
|
"# recurrence = ScheduleRecurrence(frequency=\"Month\", interval=1, start_time=\"2020-01-01T09:00:00\")\n",
|
||||||
|
"# recurring_schedule = Schedule.create(ws, name=\"automl_forecasting_recurring_schedule\",\n",
|
||||||
|
"# description=\"Schedule Forecasting Pipeline to run on the first day of every week\",\n",
|
||||||
|
"# pipeline_id=forecasting_pipeline_id,\n",
|
||||||
|
"# experiment_name=experiment.name,\n",
|
||||||
|
"# recurrence=recurrence)"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"authors": [
|
||||||
|
{
|
||||||
|
"name": "jialiu"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"categories": [
|
||||||
|
"how-to-use-azureml",
|
||||||
|
"automated-machine-learning"
|
||||||
|
],
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 3.6",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python36"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"codemirror_mode": {
|
||||||
|
"name": "ipython",
|
||||||
|
"version": 3
|
||||||
|
},
|
||||||
|
"file_extension": ".py",
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython3",
|
||||||
|
"version": "3.6.8"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 4
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
name: auto-ml-forecasting-many-models
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
|
After Width: | Height: | Size: 176 KiB |
|
After Width: | Height: | Size: 165 KiB |
|
After Width: | Height: | Size: 162 KiB |
|
After Width: | Height: | Size: 166 KiB |
@@ -24,20 +24,20 @@
|
|||||||
"_**Orange Juice Sales Forecasting**_\n",
|
"_**Orange Juice Sales Forecasting**_\n",
|
||||||
"\n",
|
"\n",
|
||||||
"## Contents\n",
|
"## Contents\n",
|
||||||
"1. [Introduction](#Introduction)\n",
|
"1. [Introduction](#introduction)\n",
|
||||||
"1. [Setup](#Setup)\n",
|
"1. [Setup](#setup)\n",
|
||||||
"1. [Compute](#Compute)\n",
|
"1. [Compute](#compute)\n",
|
||||||
"1. [Data](#Data)\n",
|
"1. [Data](#data)\n",
|
||||||
"1. [Train](#Train)\n",
|
"1. [Train](#train)\n",
|
||||||
"1. [Predict](#Predict)\n",
|
"1. [Forecast](#forecast)\n",
|
||||||
"1. [Operationalize](#Operationalize)"
|
"1. [Operationalize](#operationalize)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Introduction\n",
|
"## Introduction<a id=\"introduction\"></a>\n",
|
||||||
"In this example, we use AutoML to train, select, and operationalize a time-series forecasting model for multiple time-series.\n",
|
"In this example, we use AutoML to train, select, and operationalize a time-series forecasting model for multiple time-series.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Make sure you have executed the [configuration notebook](../../../configuration.ipynb) before running this notebook.\n",
|
"Make sure you have executed the [configuration notebook](../../../configuration.ipynb) before running this notebook.\n",
|
||||||
@@ -49,7 +49,7 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Setup"
|
"## Setup<a id=\"setup\"></a>"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -60,7 +60,6 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"import azureml.core\n",
|
"import azureml.core\n",
|
||||||
"import pandas as pd\n",
|
"import pandas as pd\n",
|
||||||
"import numpy as np\n",
|
|
||||||
"import logging\n",
|
"import logging\n",
|
||||||
"\n",
|
"\n",
|
||||||
"from azureml.core.workspace import Workspace\n",
|
"from azureml.core.workspace import Workspace\n",
|
||||||
@@ -82,7 +81,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"print(\"This notebook was created using version 1.12.0 of the Azure ML SDK\")\n",
|
"print(\"This notebook was created using version 1.37.0 of the Azure ML SDK\")\n",
|
||||||
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -102,19 +101,19 @@
|
|||||||
"ws = Workspace.from_config()\n",
|
"ws = Workspace.from_config()\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# choose a name for the run history container in the workspace\n",
|
"# choose a name for the run history container in the workspace\n",
|
||||||
"experiment_name = 'automl-ojforecasting'\n",
|
"experiment_name = \"automl-ojforecasting\"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"experiment = Experiment(ws, experiment_name)\n",
|
"experiment = Experiment(ws, experiment_name)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"output = {}\n",
|
"output = {}\n",
|
||||||
"output['Subscription ID'] = ws.subscription_id\n",
|
"output[\"Subscription ID\"] = ws.subscription_id\n",
|
||||||
"output['Workspace'] = ws.name\n",
|
"output[\"Workspace\"] = ws.name\n",
|
||||||
"output['SKU'] = ws.sku\n",
|
"output[\"SKU\"] = ws.sku\n",
|
||||||
"output['Resource Group'] = ws.resource_group\n",
|
"output[\"Resource Group\"] = ws.resource_group\n",
|
||||||
"output['Location'] = ws.location\n",
|
"output[\"Location\"] = ws.location\n",
|
||||||
"output['Run History Name'] = experiment_name\n",
|
"output[\"Run History Name\"] = experiment_name\n",
|
||||||
"pd.set_option('display.max_colwidth', -1)\n",
|
"pd.set_option(\"display.max_colwidth\", -1)\n",
|
||||||
"outputDf = pd.DataFrame(data = output, index = [''])\n",
|
"outputDf = pd.DataFrame(data=output, index=[\"\"])\n",
|
||||||
"outputDf.T"
|
"outputDf.T"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -122,11 +121,14 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Compute\n",
|
"## Compute<a id=\"compute\"></a>\n",
|
||||||
"You will need to create a [compute target](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-set-up-training-targets#amlcompute) for your AutoML run. In this tutorial, you create AmlCompute as your training compute resource.\n",
|
"You will need to create a [compute target](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-set-up-training-targets#amlcompute) for your AutoML run. In this tutorial, you create AmlCompute as your training compute resource.\n",
|
||||||
|
"\n",
|
||||||
|
"> 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.\n",
|
||||||
|
"\n",
|
||||||
"#### Creation of AmlCompute takes approximately 5 minutes. \n",
|
"#### Creation of AmlCompute takes approximately 5 minutes. \n",
|
||||||
"If the AmlCompute with that name is already in your workspace this code will skip the creation process.\n",
|
"If the AmlCompute with that name is already in your workspace this code will skip the creation process.\n",
|
||||||
"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."
|
"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](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -144,10 +146,11 @@
|
|||||||
"# Verify that cluster does not exist already\n",
|
"# Verify that cluster does not exist already\n",
|
||||||
"try:\n",
|
"try:\n",
|
||||||
" compute_target = ComputeTarget(workspace=ws, name=amlcompute_cluster_name)\n",
|
" compute_target = ComputeTarget(workspace=ws, name=amlcompute_cluster_name)\n",
|
||||||
" print('Found existing cluster, use it.')\n",
|
" print(\"Found existing cluster, use it.\")\n",
|
||||||
"except ComputeTargetException:\n",
|
"except ComputeTargetException:\n",
|
||||||
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_D2_V2',\n",
|
" compute_config = AmlCompute.provisioning_configuration(\n",
|
||||||
" max_nodes=6)\n",
|
" vm_size=\"STANDARD_D12_V2\", max_nodes=6\n",
|
||||||
|
" )\n",
|
||||||
" compute_target = ComputeTarget.create(ws, amlcompute_cluster_name, compute_config)\n",
|
" compute_target = ComputeTarget.create(ws, amlcompute_cluster_name, compute_config)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"compute_target.wait_for_completion(show_output=True)"
|
"compute_target.wait_for_completion(show_output=True)"
|
||||||
@@ -157,7 +160,7 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Data\n",
|
"## Data<a id=\"data\"></a>\n",
|
||||||
"You are now ready to load the historical orange juice sales data. We will load the CSV file into a plain pandas DataFrame; the time column in the CSV is called _WeekStarting_, so it will be specially parsed into the datetime type."
|
"You are now ready to load the historical orange juice sales data. We will load the CSV file into a plain pandas DataFrame; the time column in the CSV is called _WeekStarting_, so it will be specially parsed into the datetime type."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -167,8 +170,12 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"time_column_name = 'WeekStarting'\n",
|
"time_column_name = \"WeekStarting\"\n",
|
||||||
"data = pd.read_csv(\"dominicks_OJ.csv\", parse_dates=[time_column_name])\n",
|
"data = pd.read_csv(\"dominicks_OJ.csv\", parse_dates=[time_column_name])\n",
|
||||||
|
"\n",
|
||||||
|
"# Drop the columns 'logQuantity' as it is a leaky feature.\n",
|
||||||
|
"data.drop(\"logQuantity\", axis=1, inplace=True)\n",
|
||||||
|
"\n",
|
||||||
"data.head()"
|
"data.head()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -187,9 +194,9 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"time_series_id_column_names = ['Store', 'Brand']\n",
|
"time_series_id_column_names = [\"Store\", \"Brand\"]\n",
|
||||||
"nseries = data.groupby(time_series_id_column_names).ngroups\n",
|
"nseries = data.groupby(time_series_id_column_names).ngroups\n",
|
||||||
"print('Data contains {0} individual time-series.'.format(nseries))"
|
"print(\"Data contains {0} individual time-series.\".format(nseries))"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -208,7 +215,7 @@
|
|||||||
"use_stores = [2, 5, 8]\n",
|
"use_stores = [2, 5, 8]\n",
|
||||||
"data_subset = data[data.Store.isin(use_stores)]\n",
|
"data_subset = data[data.Store.isin(use_stores)]\n",
|
||||||
"nseries = data_subset.groupby(time_series_id_column_names).ngroups\n",
|
"nseries = data_subset.groupby(time_series_id_column_names).ngroups\n",
|
||||||
"print('Data subset contains {0} individual time-series.'.format(nseries))"
|
"print(\"Data subset contains {0} individual time-series.\".format(nseries))"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -227,14 +234,17 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"n_test_periods = 20\n",
|
"n_test_periods = 20\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"def split_last_n_by_series_id(df, n):\n",
|
"def split_last_n_by_series_id(df, n):\n",
|
||||||
" \"\"\"Group df by series identifiers and split on last n rows for each group.\"\"\"\n",
|
" \"\"\"Group df by series identifiers and split on last n rows for each group.\"\"\"\n",
|
||||||
" df_grouped = (df.sort_values(time_column_name) # Sort by ascending time\n",
|
" df_grouped = df.sort_values(time_column_name).groupby( # Sort by ascending time\n",
|
||||||
" .groupby(time_series_id_column_names, group_keys=False))\n",
|
" time_series_id_column_names, group_keys=False\n",
|
||||||
|
" )\n",
|
||||||
" df_head = df_grouped.apply(lambda dfg: dfg.iloc[:-n])\n",
|
" df_head = df_grouped.apply(lambda dfg: dfg.iloc[:-n])\n",
|
||||||
" df_tail = df_grouped.apply(lambda dfg: dfg.iloc[-n:])\n",
|
" df_tail = df_grouped.apply(lambda dfg: dfg.iloc[-n:])\n",
|
||||||
" return df_head, df_tail\n",
|
" return df_head, df_tail\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"train, test = split_last_n_by_series_id(data_subset, n_test_periods)"
|
"train, test = split_last_n_by_series_id(data_subset, n_test_periods)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -252,18 +262,15 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"train.to_csv (r'./dominicks_OJ_train.csv', index = None, header=True)\n",
|
"from azureml.data.dataset_factory import TabularDatasetFactory\n",
|
||||||
"test.to_csv (r'./dominicks_OJ_test.csv', index = None, header=True)"
|
"\n",
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"datastore = ws.get_default_datastore()\n",
|
"datastore = ws.get_default_datastore()\n",
|
||||||
"datastore.upload_files(files = ['./dominicks_OJ_train.csv', './dominicks_OJ_test.csv'], target_path = 'dataset/', overwrite = True,show_progress = True)"
|
"train_dataset = TabularDatasetFactory.register_pandas_dataframe(\n",
|
||||||
|
" train, target=(datastore, \"dataset/\"), name=\"dominicks_OJ_train\"\n",
|
||||||
|
")\n",
|
||||||
|
"test_dataset = TabularDatasetFactory.register_pandas_dataframe(\n",
|
||||||
|
" test, target=(datastore, \"dataset/\"), name=\"dominicks_OJ_test\"\n",
|
||||||
|
")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -273,16 +280,6 @@
|
|||||||
"### Create dataset for training"
|
"### Create dataset for training"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.core.dataset import Dataset\n",
|
|
||||||
"train_dataset = Dataset.Tabular.from_delimited_files(path=datastore.path('dataset/dominicks_OJ_train.csv'))"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
@@ -316,7 +313,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"target_column_name = 'Quantity'"
|
"target_column_name = \"Quantity\""
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -325,12 +322,11 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"## Customization\n",
|
"## Customization\n",
|
||||||
"\n",
|
"\n",
|
||||||
"The featurization customization in forecasting is an advanced feature in AutoML which allows our customers to change the default forecasting featurization behaviors and column types through `FeaturizationConfig`. The supported scenarios include,\n",
|
"The featurization customization in forecasting is an advanced feature in AutoML which allows our customers to change the default forecasting featurization behaviors and column types through `FeaturizationConfig`. The supported scenarios include:\n",
|
||||||
"1. Column purposes update: Override feature type for the specified column. Currently supports DateTime, Categorical and Numeric. This customization can be used in the scenario that the type of the column cannot correctly reflect its purpose. Some numerical columns, for instance, can be treated as Categorical columns which need to be converted to categorical while some can be treated as epoch timestamp which need to be converted to datetime. To tell our SDK to correctly preprocess these columns, a configuration need to be add with the columns and their desired types.\n",
|
|
||||||
"2. Transformer parameters update: Currently supports parameter change for Imputer only. User can customize imputation methods, the supported methods are constant for target data and mean, median, most frequent and constant for training data. This customization can be used for the scenario that our customers know which imputation methods fit best to the input data. For instance, some datasets use NaN to represent 0 which the correct behavior should impute all the missing value with 0. To achieve this behavior, these columns need to be configured as constant imputation with `fill_value` 0.\n",
|
|
||||||
"3. Drop columns: Columns to drop from being featurized. These usually are the columns which are leaky or the columns contain no useful data.\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
"This step requires an Enterprise workspace to gain access to this feature. To learn more about creating an Enterprise workspace or upgrading to an Enterprise workspace from the Azure portal, please visit our [Workspace page.](https://docs.microsoft.com/azure/machine-learning/service/concept-workspace#upgrade)"
|
"1. Column purposes update: Override feature type for the specified column. Currently supports DateTime, Categorical and Numeric. This customization can be used in the scenario that the type of the column cannot correctly reflect its purpose. Some numerical columns, for instance, can be treated as Categorical columns which need to be converted to categorical while some can be treated as epoch timestamp which need to be converted to datetime. To tell our SDK to correctly preprocess these columns, a configuration need to be add with the columns and their desired types.\n",
|
||||||
|
"2. Transformer parameters update: Currently supports parameter change for Imputer only. User can customize imputation methods. The supported imputing methods for target column are constant and ffill (forward fill). The supported imputing methods for feature columns are mean, median, most frequent, constant and ffill (forward fill). This customization can be used for the scenario that our customers know which imputation methods fit best to the input data. For instance, some datasets use NaN to represent 0 which the correct behavior should impute all the missing value with 0. To achieve this behavior, these columns need to be configured as constant imputation with `fill_value` 0.\n",
|
||||||
|
"3. Drop columns: Columns to drop from being featurized. These usually are the columns which are leaky or the columns contain no useful data."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -344,13 +340,18 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"featurization_config = FeaturizationConfig()\n",
|
"featurization_config = FeaturizationConfig()\n",
|
||||||
"featurization_config.drop_columns = ['logQuantity'] # 'logQuantity' is a leaky feature, so we remove it.\n",
|
|
||||||
"# Force the CPWVOL5 feature to be numeric type.\n",
|
"# Force the CPWVOL5 feature to be numeric type.\n",
|
||||||
"featurization_config.add_column_purpose('CPWVOL5', 'Numeric')\n",
|
"featurization_config.add_column_purpose(\"CPWVOL5\", \"Numeric\")\n",
|
||||||
"# Fill missing values in the target column, Quantity, with zeros.\n",
|
"# Fill missing values in the target column, Quantity, with zeros.\n",
|
||||||
"featurization_config.add_transformer_params('Imputer', ['Quantity'], {\"strategy\": \"constant\", \"fill_value\": 0})\n",
|
"featurization_config.add_transformer_params(\n",
|
||||||
|
" \"Imputer\", [\"Quantity\"], {\"strategy\": \"constant\", \"fill_value\": 0}\n",
|
||||||
|
")\n",
|
||||||
"# Fill missing values in the INCOME column with median value.\n",
|
"# Fill missing values in the INCOME column with median value.\n",
|
||||||
"featurization_config.add_transformer_params('Imputer', ['INCOME'], {\"strategy\": \"median\"})"
|
"featurization_config.add_transformer_params(\n",
|
||||||
|
" \"Imputer\", [\"INCOME\"], {\"strategy\": \"median\"}\n",
|
||||||
|
")\n",
|
||||||
|
"# Fill missing values in the Price column with forward fill (last value carried forward).\n",
|
||||||
|
"featurization_config.add_transformer_params(\"Imputer\", [\"Price\"], {\"strategy\": \"ffill\"})"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -365,14 +366,15 @@
|
|||||||
"|-|-|\n",
|
"|-|-|\n",
|
||||||
"|**time_column_name**|The name of your time column.|\n",
|
"|**time_column_name**|The name of your time column.|\n",
|
||||||
"|**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).|\n",
|
"|**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).|\n",
|
||||||
"|**time_series_id_column_names**|The column names used to uniquely identify the time series in data that has multiple rows with the same timestamp. If the time series identifiers are not defined, the data set is assumed to be one time series.|"
|
"|**time_series_id_column_names**|The column names used to uniquely identify the time series in data that has multiple rows with the same timestamp. If the time series identifiers are not defined, the data set is assumed to be one time series.|\n",
|
||||||
|
"|**freq**|Forecast frequency. This optional parameter represents the period with which the forecast is desired, for example, daily, weekly, yearly, etc. Use this parameter for the correction of time series containing irregular data points or for padding of short time series. The frequency needs to be a pandas offset alias. Please refer to [pandas documentation](https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#dateoffset-objects) for more information."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Train\n",
|
"## Train<a id=\"train\"></a>\n",
|
||||||
"\n",
|
"\n",
|
||||||
"The [AutoMLConfig](https://docs.microsoft.com/en-us/python/api/azureml-train-automl-client/azureml.train.automl.automlconfig.automlconfig?view=azure-ml-py) object defines the settings and data for an AutoML training job. Here, we set necessary inputs like the task type, the number of AutoML iterations to try, the training data, and cross-validation parameters.\n",
|
"The [AutoMLConfig](https://docs.microsoft.com/en-us/python/api/azureml-train-automl-client/azureml.train.automl.automlconfig.automlconfig?view=azure-ml-py) object defines the settings and data for an AutoML training job. Here, we set necessary inputs like the task type, the number of AutoML iterations to try, the training data, and cross-validation parameters.\n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -381,7 +383,7 @@
|
|||||||
"The forecast horizon is given in units of the time-series frequency; for instance, the OJ series frequency is weekly, so a horizon of 20 means that a trained model will estimate sales up to 20 weeks beyond the latest date in the training data for each series. In this example, we set the forecast horizon to the number of samples per series in the test set (n_test_periods). Generally, the value of this parameter will be dictated by business needs. For example, a demand planning application that estimates the next month of sales should set the horizon according to suitable planning time-scales. Please see the [energy_demand notebook](https://github.com/Azure/MachineLearningNotebooks/tree/master/how-to-use-azureml/automated-machine-learning/forecasting-energy-demand) for more discussion of forecast horizon.\n",
|
"The forecast horizon is given in units of the time-series frequency; for instance, the OJ series frequency is weekly, so a horizon of 20 means that a trained model will estimate sales up to 20 weeks beyond the latest date in the training data for each series. In this example, we set the forecast horizon to the number of samples per series in the test set (n_test_periods). Generally, the value of this parameter will be dictated by business needs. For example, a demand planning application that estimates the next month of sales should set the horizon according to suitable planning time-scales. Please see the [energy_demand notebook](https://github.com/Azure/MachineLearningNotebooks/tree/master/how-to-use-azureml/automated-machine-learning/forecasting-energy-demand) for more discussion of forecast horizon.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"We note here that AutoML can sweep over two types of time-series models:\n",
|
"We note here that AutoML can sweep over two types of time-series models:\n",
|
||||||
"* Models that are trained for each series such as ARIMA and Facebook's Prophet. Note that these models are only available for [Enterprise Edition Workspaces](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-manage-workspace#upgrade).\n",
|
"* Models that are trained for each series such as ARIMA and Facebook's Prophet.\n",
|
||||||
"* Models trained across multiple time-series using a regression approach.\n",
|
"* Models trained across multiple time-series using a regression approach.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"In the first case, AutoML loops over all time-series in your dataset and trains one model (e.g. AutoArima or Prophet, as the case may be) for each series. This can result in long runtimes to train these models if there are a lot of series in the data. One way to mitigate this problem is to fit models for different series in parallel if you have multiple compute cores available. To enable this behavior, set the `max_cores_per_iteration` parameter in your AutoMLConfig as shown in the example in the next cell. \n",
|
"In the first case, AutoML loops over all time-series in your dataset and trains one model (e.g. AutoArima or Prophet, as the case may be) for each series. This can result in long runtimes to train these models if there are a lot of series in the data. One way to mitigate this problem is to fit models for different series in parallel if you have multiple compute cores available. To enable this behavior, set the `max_cores_per_iteration` parameter in your AutoMLConfig as shown in the example in the next cell. \n",
|
||||||
@@ -415,25 +417,29 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from azureml.automl.core.forecasting_parameters import ForecastingParameters\n",
|
"from azureml.automl.core.forecasting_parameters import ForecastingParameters\n",
|
||||||
|
"\n",
|
||||||
"forecasting_parameters = ForecastingParameters(\n",
|
"forecasting_parameters = ForecastingParameters(\n",
|
||||||
" time_column_name=time_column_name,\n",
|
" time_column_name=time_column_name,\n",
|
||||||
" forecast_horizon=n_test_periods,\n",
|
" forecast_horizon=n_test_periods,\n",
|
||||||
" time_series_id_column_names=time_series_id_column_names\n",
|
" time_series_id_column_names=time_series_id_column_names,\n",
|
||||||
|
" freq=\"W-THU\", # Set the forecast frequency to be weekly (start on each Thursday)\n",
|
||||||
")\n",
|
")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"automl_config = AutoMLConfig(task='forecasting',\n",
|
"automl_config = AutoMLConfig(\n",
|
||||||
" debug_log='automl_oj_sales_errors.log',\n",
|
" task=\"forecasting\",\n",
|
||||||
" primary_metric='normalized_mean_absolute_error',\n",
|
" debug_log=\"automl_oj_sales_errors.log\",\n",
|
||||||
" experiment_timeout_hours=0.25,\n",
|
" primary_metric=\"normalized_mean_absolute_error\",\n",
|
||||||
" training_data=train_dataset,\n",
|
" experiment_timeout_hours=0.25,\n",
|
||||||
" label_column_name=target_column_name,\n",
|
" training_data=train_dataset,\n",
|
||||||
" compute_target=compute_target,\n",
|
" label_column_name=target_column_name,\n",
|
||||||
" enable_early_stopping=True,\n",
|
" compute_target=compute_target,\n",
|
||||||
" featurization=featurization_config,\n",
|
" enable_early_stopping=True,\n",
|
||||||
" n_cross_validations=3,\n",
|
" featurization=featurization_config,\n",
|
||||||
" verbosity=logging.INFO,\n",
|
" n_cross_validations=3,\n",
|
||||||
" max_cores_per_iteration=-1,\n",
|
" verbosity=logging.INFO,\n",
|
||||||
" forecasting_parameters=forecasting_parameters)"
|
" max_cores_per_iteration=-1,\n",
|
||||||
|
" forecasting_parameters=forecasting_parameters,\n",
|
||||||
|
")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -450,8 +456,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"remote_run = experiment.submit(automl_config, show_output=False)\n",
|
"remote_run = experiment.submit(automl_config, show_output=False)"
|
||||||
"remote_run"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -479,7 +484,7 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"best_run, fitted_model = remote_run.get_output()\n",
|
"best_run, fitted_model = remote_run.get_output()\n",
|
||||||
"print(fitted_model.steps)\n",
|
"print(fitted_model.steps)\n",
|
||||||
"model_name = best_run.properties['model_name']"
|
"model_name = best_run.properties[\"model_name\"]"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -497,7 +502,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"custom_featurizer = fitted_model.named_steps['timeseriestransformer']"
|
"custom_featurizer = fitted_model.named_steps[\"timeseriestransformer\"]"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -513,9 +518,11 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"# Forecasting\n",
|
"# Forecast<a id=\"forecast\"></a>\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Now that we have retrieved the best pipeline/model, it can be used to make predictions on test data. First, we remove the target values from the test set:"
|
"Now that we have retrieved the best pipeline/model, it can be used to make predictions on test data. We will do batch scoring on the test dataset which should have the same schema as training dataset.\n",
|
||||||
|
"\n",
|
||||||
|
"The inference will run on a remote compute. In this example, it will re-use the training compute."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -524,17 +531,15 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"X_test = test\n",
|
"test_experiment = Experiment(ws, experiment_name + \"_inference\")"
|
||||||
"y_test = X_test.pop(target_column_name).values"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "markdown",
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
"source": [
|
||||||
"X_test.head()"
|
"### Retreiving forecasts from the model\n",
|
||||||
|
"We have created a function called `run_forecast` that submits the test data to the best model determined during the training run and retrieves forecasts. This function uses a helper script `forecasting_script` which is uploaded and expecuted on the remote compute."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -550,18 +555,19 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"# forecast returns the predictions and the featurized data, aligned to X_test.\n",
|
"from run_forecast import run_remote_inference\n",
|
||||||
"# This contains the assumptions that were made in the forecast\n",
|
|
||||||
"y_predictions, X_trans = fitted_model.forecast(X_test)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"If you are used to scikit pipelines, perhaps you expected `predict(X_test)`. However, forecasting requires a more general interface that also supplies the past target `y` values. Please use `forecast(X,y)` as `predict(X)` is reserved for internal purposes on forecasting models.\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
"The [forecast function notebook](../forecasting-forecast-function/auto-ml-forecasting-function.ipynb)."
|
"remote_run_infer = run_remote_inference(\n",
|
||||||
|
" test_experiment=test_experiment,\n",
|
||||||
|
" compute_target=compute_target,\n",
|
||||||
|
" train_run=best_run,\n",
|
||||||
|
" test_dataset=test_dataset,\n",
|
||||||
|
" target_column_name=target_column_name,\n",
|
||||||
|
")\n",
|
||||||
|
"remote_run_infer.wait_for_completion(show_output=False)\n",
|
||||||
|
"\n",
|
||||||
|
"# download the forecast file to the local machine\n",
|
||||||
|
"remote_run_infer.download_file(\"outputs/predictions.csv\", \"predictions.csv\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -570,7 +576,7 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"# Evaluate\n",
|
"# Evaluate\n",
|
||||||
"\n",
|
"\n",
|
||||||
"To evaluate the accuracy of the forecast, we'll compare against the actual sales quantities for some select metrics, included the mean absolute percentage error (MAPE). \n",
|
"To evaluate the accuracy of the forecast, we'll compare against the actual sales quantities for some select metrics, included the mean absolute percentage error (MAPE). For more metrics that can be used for evaluation after training, please see [supported metrics](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-understand-automated-ml#regressionforecasting-metrics), and [how to calculate residuals](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-understand-automated-ml#residuals).\n",
|
||||||
"\n",
|
"\n",
|
||||||
"We'll add predictions and actuals into a single dataframe for convenience in calculating the metrics."
|
"We'll add predictions and actuals into a single dataframe for convenience in calculating the metrics."
|
||||||
]
|
]
|
||||||
@@ -581,8 +587,9 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"assign_dict = {'predicted': y_predictions, target_column_name: y_test}\n",
|
"# load forecast data frame\n",
|
||||||
"df_all = X_test.assign(**assign_dict)"
|
"fcst_df = pd.read_csv(\"predictions.csv\", parse_dates=[time_column_name])\n",
|
||||||
|
"fcst_df.head()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -597,19 +604,24 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"# use automl scoring module\n",
|
"# use automl scoring module\n",
|
||||||
"scores = scoring.score_regression(\n",
|
"scores = scoring.score_regression(\n",
|
||||||
" y_test=df_all[target_column_name],\n",
|
" y_test=fcst_df[target_column_name],\n",
|
||||||
" y_pred=df_all['predicted'],\n",
|
" y_pred=fcst_df[\"predicted\"],\n",
|
||||||
" metrics=list(constants.Metric.SCALAR_REGRESSION_SET))\n",
|
" metrics=list(constants.Metric.SCALAR_REGRESSION_SET),\n",
|
||||||
|
")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"print(\"[Test data scores]\\n\")\n",
|
"print(\"[Test data scores]\\n\")\n",
|
||||||
"for key, value in scores.items(): \n",
|
"for key, value in scores.items():\n",
|
||||||
" print('{}: {:.3f}'.format(key, value))\n",
|
" print(\"{}: {:.3f}\".format(key, value))\n",
|
||||||
" \n",
|
"\n",
|
||||||
"# Plot outputs\n",
|
"# Plot outputs\n",
|
||||||
"%matplotlib inline\n",
|
"%matplotlib inline\n",
|
||||||
"test_pred = plt.scatter(df_all[target_column_name], df_all['predicted'], color='b')\n",
|
"test_pred = plt.scatter(fcst_df[target_column_name], fcst_df[\"predicted\"], color=\"b\")\n",
|
||||||
"test_test = plt.scatter(df_all[target_column_name], df_all[target_column_name], color='g')\n",
|
"test_test = plt.scatter(\n",
|
||||||
"plt.legend((test_pred, test_test), ('prediction', 'truth'), loc='upper left', fontsize=8)\n",
|
" fcst_df[target_column_name], fcst_df[target_column_name], color=\"g\"\n",
|
||||||
|
")\n",
|
||||||
|
"plt.legend(\n",
|
||||||
|
" (test_pred, test_test), (\"prediction\", \"truth\"), loc=\"upper left\", fontsize=8\n",
|
||||||
|
")\n",
|
||||||
"plt.show()"
|
"plt.show()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -617,7 +629,7 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"# Operationalize"
|
"# Operationalize<a id=\"operationalize\"></a>"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -633,9 +645,11 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"description = 'AutoML OJ forecaster'\n",
|
"description = \"AutoML OJ forecaster\"\n",
|
||||||
"tags = None\n",
|
"tags = None\n",
|
||||||
"model = remote_run.register_model(model_name = model_name, description = description, tags = tags)\n",
|
"model = remote_run.register_model(\n",
|
||||||
|
" model_name=model_name, description=description, tags=tags\n",
|
||||||
|
")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"print(remote_run.model_id)"
|
"print(remote_run.model_id)"
|
||||||
]
|
]
|
||||||
@@ -655,8 +669,8 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"script_file_name = 'score_fcast.py'\n",
|
"script_file_name = \"score_fcast.py\"\n",
|
||||||
"best_run.download_file('outputs/scoring_file_v_1_0_0.py', script_file_name)"
|
"best_run.download_file(\"outputs/scoring_file_v_1_0_0.py\", script_file_name)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -677,15 +691,18 @@
|
|||||||
"from azureml.core.webservice import Webservice\n",
|
"from azureml.core.webservice import Webservice\n",
|
||||||
"from azureml.core.model import Model\n",
|
"from azureml.core.model import Model\n",
|
||||||
"\n",
|
"\n",
|
||||||
"inference_config = InferenceConfig(environment = best_run.get_environment(), \n",
|
"inference_config = InferenceConfig(\n",
|
||||||
" entry_script = script_file_name)\n",
|
" environment=best_run.get_environment(), entry_script=script_file_name\n",
|
||||||
|
")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"aciconfig = AciWebservice.deploy_configuration(cpu_cores = 1, \n",
|
"aciconfig = AciWebservice.deploy_configuration(\n",
|
||||||
" memory_gb = 2, \n",
|
" cpu_cores=2,\n",
|
||||||
" tags = {'type': \"automl-forecasting\"},\n",
|
" memory_gb=4,\n",
|
||||||
" description = \"Automl forecasting sample service\")\n",
|
" tags={\"type\": \"automl-forecasting\"},\n",
|
||||||
|
" description=\"Automl forecasting sample service\",\n",
|
||||||
|
")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"aci_service_name = 'automl-oj-forecast-01'\n",
|
"aci_service_name = \"automl-oj-forecast-01\"\n",
|
||||||
"print(aci_service_name)\n",
|
"print(aci_service_name)\n",
|
||||||
"aci_service = Model.deploy(ws, aci_service_name, [model], inference_config, aciconfig)\n",
|
"aci_service = Model.deploy(ws, aci_service_name, [model], inference_config, aciconfig)\n",
|
||||||
"aci_service.wait_for_deployment(True)\n",
|
"aci_service.wait_for_deployment(True)\n",
|
||||||
@@ -715,19 +732,27 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"import json\n",
|
"import json\n",
|
||||||
"X_query = X_test.copy()\n",
|
"\n",
|
||||||
|
"X_query = test.copy()\n",
|
||||||
|
"X_query.pop(target_column_name)\n",
|
||||||
"# We have to convert datetime to string, because Timestamps cannot be serialized to JSON.\n",
|
"# We have to convert datetime to string, because Timestamps cannot be serialized to JSON.\n",
|
||||||
"X_query[time_column_name] = X_query[time_column_name].astype(str)\n",
|
"X_query[time_column_name] = X_query[time_column_name].astype(str)\n",
|
||||||
"# The Service object accept the complex dictionary, which is internally converted to JSON string.\n",
|
"# The Service object accept the complex dictionary, which is internally converted to JSON string.\n",
|
||||||
"# The section 'data' contains the data frame in the form of dictionary.\n",
|
"# The section 'data' contains the data frame in the form of dictionary.\n",
|
||||||
"test_sample = json.dumps({'data': X_query.to_dict(orient='records')})\n",
|
"sample_quantiles = [0.025, 0.975]\n",
|
||||||
"response = aci_service.run(input_data = test_sample)\n",
|
"test_sample = json.dumps(\n",
|
||||||
|
" {\"data\": X_query.to_dict(orient=\"records\"), \"quantiles\": sample_quantiles}\n",
|
||||||
|
")\n",
|
||||||
|
"response = aci_service.run(input_data=test_sample)\n",
|
||||||
"# translate from networkese to datascientese\n",
|
"# translate from networkese to datascientese\n",
|
||||||
"try: \n",
|
"try:\n",
|
||||||
" res_dict = json.loads(response)\n",
|
" res_dict = json.loads(response)\n",
|
||||||
" y_fcst_all = pd.DataFrame(res_dict['index'])\n",
|
" y_fcst_all = pd.DataFrame(res_dict[\"index\"])\n",
|
||||||
" y_fcst_all[time_column_name] = pd.to_datetime(y_fcst_all[time_column_name], unit = 'ms')\n",
|
" y_fcst_all[time_column_name] = pd.to_datetime(\n",
|
||||||
" y_fcst_all['forecast'] = res_dict['forecast'] \n",
|
" y_fcst_all[time_column_name], unit=\"ms\"\n",
|
||||||
|
" )\n",
|
||||||
|
" y_fcst_all[\"forecast\"] = res_dict[\"forecast\"]\n",
|
||||||
|
" y_fcst_all[\"prediction_interval\"] = res_dict[\"prediction_interval\"]\n",
|
||||||
"except:\n",
|
"except:\n",
|
||||||
" print(res_dict)"
|
" print(res_dict)"
|
||||||
]
|
]
|
||||||
@@ -754,15 +779,15 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"serv = Webservice(ws, 'automl-oj-forecast-01')\n",
|
"serv = Webservice(ws, \"automl-oj-forecast-01\")\n",
|
||||||
"serv.delete() # don't do it accidentally"
|
"serv.delete() # don't do it accidentally"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"authors": [
|
"authors": [
|
||||||
{
|
{
|
||||||
"name": "erwright"
|
"name": "jialiu"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"category": "tutorial",
|
"category": "tutorial",
|
||||||
@@ -797,7 +822,7 @@
|
|||||||
"name": "python",
|
"name": "python",
|
||||||
"nbconvert_exporter": "python",
|
"nbconvert_exporter": "python",
|
||||||
"pygments_lexer": "ipython3",
|
"pygments_lexer": "ipython3",
|
||||||
"version": "3.6.8"
|
"version": "3.6.9"
|
||||||
},
|
},
|
||||||
"tags": [
|
"tags": [
|
||||||
"None"
|
"None"
|
||||||
|
|||||||
@@ -0,0 +1,61 @@
|
|||||||
|
"""
|
||||||
|
This is the script that is executed on the compute instance. It relies
|
||||||
|
on the model.pkl file which is uploaded along with this script to the
|
||||||
|
compute instance.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
from azureml.core import Dataset, Run
|
||||||
|
from sklearn.externals import joblib
|
||||||
|
from pandas.tseries.frequencies import to_offset
|
||||||
|
|
||||||
|
parser = argparse.ArgumentParser()
|
||||||
|
parser.add_argument(
|
||||||
|
"--target_column_name",
|
||||||
|
type=str,
|
||||||
|
dest="target_column_name",
|
||||||
|
help="Target Column Name",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--test_dataset", type=str, dest="test_dataset", help="Test Dataset"
|
||||||
|
)
|
||||||
|
|
||||||
|
args = parser.parse_args()
|
||||||
|
target_column_name = args.target_column_name
|
||||||
|
test_dataset_id = args.test_dataset
|
||||||
|
|
||||||
|
run = Run.get_context()
|
||||||
|
ws = run.experiment.workspace
|
||||||
|
|
||||||
|
# get the input dataset by id
|
||||||
|
test_dataset = Dataset.get_by_id(ws, id=test_dataset_id)
|
||||||
|
|
||||||
|
X_test = test_dataset.to_pandas_dataframe().reset_index(drop=True)
|
||||||
|
y_test = X_test.pop(target_column_name).values
|
||||||
|
|
||||||
|
# generate forecast
|
||||||
|
fitted_model = joblib.load("model.pkl")
|
||||||
|
# We have default quantiles values set as below(95th percentile)
|
||||||
|
quantiles = [0.025, 0.5, 0.975]
|
||||||
|
predicted_column_name = "predicted"
|
||||||
|
PI = "prediction_interval"
|
||||||
|
fitted_model.quantiles = quantiles
|
||||||
|
pred_quantiles = fitted_model.forecast_quantiles(X_test)
|
||||||
|
pred_quantiles[PI] = pred_quantiles[[min(quantiles), max(quantiles)]].apply(
|
||||||
|
lambda x: "[{}, {}]".format(x[0], x[1]), axis=1
|
||||||
|
)
|
||||||
|
X_test[target_column_name] = y_test
|
||||||
|
X_test[PI] = pred_quantiles[PI]
|
||||||
|
X_test[predicted_column_name] = pred_quantiles[0.5]
|
||||||
|
# drop rows where prediction or actuals are nan
|
||||||
|
# happens because of missing actuals
|
||||||
|
# or at edges of time due to lags/rolling windows
|
||||||
|
clean = X_test[
|
||||||
|
X_test[[target_column_name, predicted_column_name]].notnull().all(axis=1)
|
||||||
|
]
|
||||||
|
|
||||||
|
file_name = "outputs/predictions.csv"
|
||||||
|
export_csv = clean.to_csv(file_name, header=True, index=False) # added Index
|
||||||
|
|
||||||
|
# Upload the predictions into artifacts
|
||||||
|
run.upload_file(name=file_name, path_or_stream=file_name)
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
from azureml.core import ScriptRunConfig
|
||||||
|
|
||||||
|
|
||||||
|
def run_remote_inference(
|
||||||
|
test_experiment,
|
||||||
|
compute_target,
|
||||||
|
train_run,
|
||||||
|
test_dataset,
|
||||||
|
target_column_name,
|
||||||
|
inference_folder="./forecast",
|
||||||
|
):
|
||||||
|
# Create local directory to copy the model.pkl and forecsting_script.py files into.
|
||||||
|
# These files will be uploaded to and executed on the compute instance.
|
||||||
|
os.makedirs(inference_folder, exist_ok=True)
|
||||||
|
shutil.copy("forecasting_script.py", inference_folder)
|
||||||
|
|
||||||
|
train_run.download_file(
|
||||||
|
"outputs/model.pkl", os.path.join(inference_folder, "model.pkl")
|
||||||
|
)
|
||||||
|
|
||||||
|
inference_env = train_run.get_environment()
|
||||||
|
|
||||||
|
config = ScriptRunConfig(
|
||||||
|
source_directory=inference_folder,
|
||||||
|
script="forecasting_script.py",
|
||||||
|
arguments=[
|
||||||
|
"--target_column_name",
|
||||||
|
target_column_name,
|
||||||
|
"--test_dataset",
|
||||||
|
test_dataset.as_named_input(test_dataset.name),
|
||||||
|
],
|
||||||
|
compute_target=compute_target,
|
||||||
|
environment=inference_env,
|
||||||
|
)
|
||||||
|
|
||||||
|
run = test_experiment.submit(
|
||||||
|
config,
|
||||||
|
tags={
|
||||||
|
"training_run_id": train_run.id,
|
||||||
|
"run_algorithm": train_run.properties["run_algorithm"],
|
||||||
|
"valid_score": train_run.properties["score"],
|
||||||
|
"primary_metric": train_run.properties["primary_metric"],
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
run.log("run_algorithm", run.tags["run_algorithm"])
|
||||||
|
return run
|
||||||
@@ -0,0 +1,494 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
||||||
|
"\n",
|
||||||
|
"Licensed under the MIT License."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
""
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"In this notebook we will explore the univaraite time-series data to determine the settings for an automated ML experiment. We will follow the thought process depicted in the following diagram:<br/>\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"The objective is to answer the following questions:\n",
|
||||||
|
"\n",
|
||||||
|
"<ol>\n",
|
||||||
|
" <li>Is there a seasonal pattern in the data? </li>\n",
|
||||||
|
" <ul style=\"margin-top:-1px; list-style-type:none\"> \n",
|
||||||
|
" <li> Importance: If we are able to detect regular seasonal patterns, the forecast accuracy may be improved by extracting these patterns and including them as features into the model. </li>\n",
|
||||||
|
" </ul>\n",
|
||||||
|
" <li>Is the data stationary? </li>\n",
|
||||||
|
" <ul style=\"margin-top:-1px; list-style-type:none\"> \n",
|
||||||
|
" <li> Importance: In the absense of features that capture trend behavior, ML models (regression and tree based) are not well equiped to predict stochastic trends. Working with stationary data solves this problem. </li>\n",
|
||||||
|
" </ul>\n",
|
||||||
|
" <li>Is there a detectable auto-regressive pattern in the stationary data? </li>\n",
|
||||||
|
" <ul style=\"margin-top:-1px; list-style-type:none\"> \n",
|
||||||
|
" <li> Importance: The accuracy of ML models can be improved if serial correlation is modeled by including lags of the dependent/target varaible as features. Including target lags in every experiment by default will result in a regression in accuracy scores if such setting is not warranted. </li>\n",
|
||||||
|
" </ul>\n",
|
||||||
|
"</ol>\n",
|
||||||
|
"\n",
|
||||||
|
"The answers to these questions will help determine the appropriate settings for the automated ML experiment.\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"import os\n",
|
||||||
|
"import warnings\n",
|
||||||
|
"import pandas as pd\n",
|
||||||
|
"\n",
|
||||||
|
"from statsmodels.graphics.tsaplots import plot_acf, plot_pacf\n",
|
||||||
|
"import matplotlib.pyplot as plt\n",
|
||||||
|
"from pandas.plotting import register_matplotlib_converters\n",
|
||||||
|
"\n",
|
||||||
|
"register_matplotlib_converters() # fixes the future warning issue\n",
|
||||||
|
"\n",
|
||||||
|
"from helper_functions import unit_root_test_wrapper\n",
|
||||||
|
"from statsmodels.tools.sm_exceptions import InterpolationWarning\n",
|
||||||
|
"\n",
|
||||||
|
"warnings.simplefilter(\"ignore\", InterpolationWarning)\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"# set printing options\n",
|
||||||
|
"pd.set_option(\"display.max_columns\", 500)\n",
|
||||||
|
"pd.set_option(\"display.width\", 1000)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# load data\n",
|
||||||
|
"main_data_loc = \"data\"\n",
|
||||||
|
"train_file_name = \"S4248SM144SCEN.csv\"\n",
|
||||||
|
"\n",
|
||||||
|
"TARGET_COLNAME = \"S4248SM144SCEN\"\n",
|
||||||
|
"TIME_COLNAME = \"observation_date\"\n",
|
||||||
|
"COVID_PERIOD_START = \"2020-03-01\"\n",
|
||||||
|
"\n",
|
||||||
|
"df = pd.read_csv(os.path.join(main_data_loc, train_file_name))\n",
|
||||||
|
"df[TIME_COLNAME] = pd.to_datetime(df[TIME_COLNAME], format=\"%Y-%m-%d\")\n",
|
||||||
|
"df.sort_values(by=TIME_COLNAME, inplace=True)\n",
|
||||||
|
"df.set_index(TIME_COLNAME, inplace=True)\n",
|
||||||
|
"df.head(2)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# plot the entire dataset\n",
|
||||||
|
"fig, ax = plt.subplots(figsize=(6, 2), dpi=180)\n",
|
||||||
|
"ax.plot(df)\n",
|
||||||
|
"ax.title.set_text(\"Original Data Series\")\n",
|
||||||
|
"locs, labels = plt.xticks()\n",
|
||||||
|
"plt.xticks(rotation=45)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"The graph plots the alcohol sales in the United States. Because the data is trending, it can be difficult to see cycles, seasonality or other interestng behaviors due to the scaling issues. For example, if there is a seasonal pattern, which we will discuss later, we cannot see them on the trending data. In such case, it is worth plotting the same data in first differences."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# plot the entire dataset in first differences\n",
|
||||||
|
"fig, ax = plt.subplots(figsize=(6, 2), dpi=180)\n",
|
||||||
|
"ax.plot(df.diff().dropna())\n",
|
||||||
|
"ax.title.set_text(\"Data in first differences\")\n",
|
||||||
|
"locs, labels = plt.xticks()\n",
|
||||||
|
"plt.xticks(rotation=45)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"In the previous plot we observe that the data is more volatile towards the end of the series. This period coincides with the Covid-19 period, so we will exclude it from our experiment. Since in this example there are no user-provided features it is hard to make an argument that a model trained on the less volatile pre-covid data will be able to accurately predict the covid period."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# 1. Seasonality\n",
|
||||||
|
"\n",
|
||||||
|
"#### Questions that need to be answered in this section:\n",
|
||||||
|
"1. Is there a seasonality?\n",
|
||||||
|
"2. If it's seasonal, does the data exhibit a trend (up or down)?\n",
|
||||||
|
"\n",
|
||||||
|
"It is hard to visually detect seasonality when the data is trending. The reason being is scale of seasonal fluctuations is dwarfed by the range of the trend in the data. One way to deal with this is to de-trend the data by taking the first differences. We will discuss this in more detail in the next section."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# plot the entire dataset in first differences\n",
|
||||||
|
"fig, ax = plt.subplots(figsize=(6, 2), dpi=180)\n",
|
||||||
|
"ax.plot(df.diff().dropna())\n",
|
||||||
|
"ax.title.set_text(\"Data in first differences\")\n",
|
||||||
|
"locs, labels = plt.xticks()\n",
|
||||||
|
"plt.xticks(rotation=45)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"For the next plot, we will exclude the Covid period again. We will also shorten the length of data because plotting a very long time series may prevent us from seeing seasonal patterns, if there are any, because the plot may look like a random walk."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# remove COVID period\n",
|
||||||
|
"df = df[:COVID_PERIOD_START]\n",
|
||||||
|
"\n",
|
||||||
|
"# plot the entire dataset in first differences\n",
|
||||||
|
"fig, ax = plt.subplots(figsize=(6, 2), dpi=180)\n",
|
||||||
|
"ax.plot(df[\"2015-01-01\":].diff().dropna())\n",
|
||||||
|
"ax.title.set_text(\"Data in first differences\")\n",
|
||||||
|
"locs, labels = plt.xticks()\n",
|
||||||
|
"plt.xticks(rotation=45)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<p style=\"font-size:150%; color:blue\"> Conclusion </p>\n",
|
||||||
|
"\n",
|
||||||
|
"Visual examination does not suggest clear seasonal patterns. We will set the STL_TYPE = None, and we will move to the next section that examines stationarity. \n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"Say, we are working with a different data set that shows clear patterns of seasonality, we have several options for setting the settings:is hard to say which option will work best in your case, hence you will need to run both options to see which one results in more accurate forecasts. </li>\n",
|
||||||
|
"<ol>\n",
|
||||||
|
" <li> If the data does not appear to be trending, set DIFFERENCE_SERIES=False, TARGET_LAGS=None and STL_TYPE = \"season\" </li>\n",
|
||||||
|
" <li> If the data appears to be trending, consider one of the following two settings:\n",
|
||||||
|
" <ul>\n",
|
||||||
|
" <ol type=\"a\">\n",
|
||||||
|
" <li> DIFFERENCE_SERIES=True, TARGET_LAGS=None and STL_TYPE = \"season\", or </li>\n",
|
||||||
|
" <li> DIFFERENCE_SERIES=False, TARGET_LAGS=None and STL_TYPE = \"trend_season\" </li>\n",
|
||||||
|
" </ol>\n",
|
||||||
|
" <li> In the first case, by taking first differences we are removing stochastic trend, but we do not remove seasonal patterns. In the second case, we do not remove the stochastic trend and it can be captured by the trend component of the STL decomposition. It is hard to say which option will work best in your case, hence you will need to run both options to see which one results in more accurate forecasts. </li>\n",
|
||||||
|
" </ul>\n",
|
||||||
|
"</ol>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# 2. Stationarity\n",
|
||||||
|
"If the data does not exhibit seasonal patterns, we would like to see if the data is non-stationary. Particularly, we want to see if there is a clear trending behavior. If such behavior is observed, we would like to first difference the data and examine the plot of an auto-correlation function (ACF) known as correlogram. If the data is seasonal, differencing it will not get rid off the seasonality and this will be shown on the correlogram as well.\n",
|
||||||
|
"\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li> Question: What is stationarity and how to we detect it? </li>\n",
|
||||||
|
" <ul>\n",
|
||||||
|
" <li> This is a fairly complex topic. Please read the following <a href=\"https://otexts.com/fpp2/stationarity.html\"> link </a> for a high level discussion on this subject. </li>\n",
|
||||||
|
" <li> Simply put, we are looking for scenario when examining the time series plots the mean of the series is roughly the same, regardless which time interval you pick to compute it. Thus, trending and seasonal data are examples of non-stationary series. </li>\n",
|
||||||
|
" </ul>\n",
|
||||||
|
"</ul>\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li> Question: Why do want to work with stationary data?</li>\n",
|
||||||
|
" <ul> \n",
|
||||||
|
" <li> In the absence of features that capture stochastic trends, the ML models that use (deterministic) time based features (hour of the day, day of the week, month of the year, etc) cannot capture such trends, and will over or under predict depending on the behavior of the time series. By working with stationary data, we eliminate the need to predict such trends, which improves the forecast accuracy. Classical time series models such as Arima and Exponential Smoothing handle non-stationary series by design and do not need such transformations. By differencing the data we are still able to run the same family of models. </li>\n",
|
||||||
|
" </ul>\n",
|
||||||
|
"</ul>\n",
|
||||||
|
"\n",
|
||||||
|
"#### Questions that need to be answered in this section:\n",
|
||||||
|
"<ol> \n",
|
||||||
|
" <li> Is the data stationary? </li>\n",
|
||||||
|
" <li> Does the stationarized data (either the original or the differenced series) exhibit a clear auto-regressive pattern?</li>\n",
|
||||||
|
"</ol>\n",
|
||||||
|
"\n",
|
||||||
|
"To answer the first question, we run a series of tests (we call them unit root tests)."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# unit root tests\n",
|
||||||
|
"test = unit_root_test_wrapper(df[TARGET_COLNAME])\n",
|
||||||
|
"print(\"---------------\", \"\\n\")\n",
|
||||||
|
"print(\"Summary table\", \"\\n\", test[\"summary\"], \"\\n\")\n",
|
||||||
|
"print(\"Is the {} series stationary?: {}\".format(TARGET_COLNAME, test[\"stationary\"]))\n",
|
||||||
|
"print(\"---------------\", \"\\n\")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"In the previous cell, we ran a series of unit root tests. The summary table contains the following columns:\n",
|
||||||
|
"<ul> \n",
|
||||||
|
" <li> test_name is the name of the test.\n",
|
||||||
|
" <ul> \n",
|
||||||
|
" <li> ADF: Augmented Dickey-Fuller test </li>\n",
|
||||||
|
" <li> KPSS: Kwiatkowski-Phillips\u00e2\u20ac\u201cSchmidt\u00e2\u20ac\u201cShin test </li>\n",
|
||||||
|
" <li> PP: Phillips-Perron test\n",
|
||||||
|
" <li> ADF GLS: Augmented Dickey-Fuller using generalized least squares method </li>\n",
|
||||||
|
" <li> AZ: Andrews-Zivot test </li>\n",
|
||||||
|
" </ul>\n",
|
||||||
|
" <li> statistic: test statistic </li>\n",
|
||||||
|
" <li> crit_val: critical value of the test statistic </li>\n",
|
||||||
|
" <li> p_val: p-value of the test statistic. If the p-val is less than 0.05, the null hypothesis is rejected. </li>\n",
|
||||||
|
" <li> stationary: is the series stationary based on the test result? </li>\n",
|
||||||
|
" <li> Null hypothesis: what is being tested. Notice, some test such as ADF and PP assume the process has a unit root and looks for evidence to reject this hypothesis. Other tests, ex.g: KPSS, assumes the process is stationary and looks for evidence to reject such claim.\n",
|
||||||
|
"</ul>\n",
|
||||||
|
"\n",
|
||||||
|
"Each of the tests shows that the original time series is non-stationary. The final decision is based on the majority rule. If, there is a split decision, the algorithm will claim it is stationary. We run a series of tests because each test by itself may not be accurate. In many cases when there are conflicting test results, the user needs to make determination if the series is stationary or not.\n",
|
||||||
|
"\n",
|
||||||
|
"Since we found the series to be non-stationary, we will difference it and then test if the differenced series is stationary."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# unit root tests\n",
|
||||||
|
"test = unit_root_test_wrapper(df[TARGET_COLNAME].diff().dropna())\n",
|
||||||
|
"print(\"---------------\", \"\\n\")\n",
|
||||||
|
"print(\"Summary table\", \"\\n\", test[\"summary\"], \"\\n\")\n",
|
||||||
|
"print(\"Is the {} series stationary?: {}\".format(TARGET_COLNAME, test[\"stationary\"]))\n",
|
||||||
|
"print(\"---------------\", \"\\n\")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Four out of five tests show that the series in first differences is stationary. Notice that this decision is not unanimous. Next, let's plot the original series in first-differences to illustrate the difference between non-stationary (unit root) process vs the stationary one."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# plot original and stationary data\n",
|
||||||
|
"fig = plt.figure(figsize=(10, 10))\n",
|
||||||
|
"ax1 = fig.add_subplot(211)\n",
|
||||||
|
"ax1.plot(df[TARGET_COLNAME], \"-b\")\n",
|
||||||
|
"ax2 = fig.add_subplot(212)\n",
|
||||||
|
"ax2.plot(df[TARGET_COLNAME].diff().dropna(), \"-b\")\n",
|
||||||
|
"ax1.title.set_text(\"Original data\")\n",
|
||||||
|
"ax2.title.set_text(\"Data in first differences\")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"If you were asked a question \"What is the mean of the series before and after 2008?\", for the series titled \"Original data\" the mean values will be significantly different. This implies that the first moment of the series (in this case, it is the mean) is time dependent, i.e., mean changes depending on the interval one is looking at. Thus, the series is deemed to be non-stationary. On the other hand, for the series titled \"Data in first differences\" the means for both periods are roughly the same. Hence, the first moment is time invariant; meaning it does not depend on the interval of time one is looking at. In this example it is easy to visually distinguish between stationary and non-stationary data. Often this distinction is not easy to make, therefore we rely on the statistical tests described above to help us make an informed decision. "
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<p style=\"font-size:150%; color:blue\"> Conclusion </p>\n",
|
||||||
|
"Since we found the original process to be non-stationary (contains unit root), we will have to model the data in first differences. As a result, we will set the DIFFERENCE_SERIES parameter to True."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# 3 Check if there is a clear autoregressive pattern\n",
|
||||||
|
"We need to determine if we should include lags of the target variable as features in order to improve forecast accuracy. To do this, we will examine the ACF and partial ACF (PACF) plots of the stationary series. In our case, it is a series in first diffrences.\n",
|
||||||
|
"\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li> Question: What is an Auto-regressive pattern? What are we looking for? </li>\n",
|
||||||
|
" <ul style=\"list-style-type:none;\">\n",
|
||||||
|
" <li> We are looking for a classical profiles for an AR(p) process such as an exponential decay of an ACF and a the first $p$ significant lags of the PACF. For a more detailed explanation of ACF and PACF please refer to the appendix at the end of this notebook. For illustration purposes, let's examine the ACF/PACF profiles of the simulated data that follows a second order auto-regressive process, abbreviated as an AR(2). <li/>\n",
|
||||||
|
" <li><img src=\"figures/ACF_PACF_for_AR2.png\" class=\"img_class\">\n",
|
||||||
|
" <br/>\n",
|
||||||
|
" The lag order is on the x-axis while the auto- and partial-correlation coefficients are on the y-axis. Vertical lines that are outside the shaded area represent statistically significant lags. Notice, the ACF function decays to zero and the PACF shows 2 significant spikes (we ignore the first spike for lag 0 in both plots since the linear relationship of any series with itself is always 1). <li/>\n",
|
||||||
|
" </ul>\n",
|
||||||
|
"<ul/>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<ul>\n",
|
||||||
|
" <li> Question: What do I do if I observe an auto-regressive behavior? </li>\n",
|
||||||
|
" <ul style=\"list-style-type:none;\">\n",
|
||||||
|
" <li> If such behavior is observed, we might improve the forecast accuracy by enabling the target lags feature in AutoML. There are a few options of doing this </li>\n",
|
||||||
|
" <ol>\n",
|
||||||
|
" <li> Set the target lags parameter to 'auto', or </li>\n",
|
||||||
|
" <li> Specify the list of lags you want to include. Ex.g: target_lags = [1,2,5] </li>\n",
|
||||||
|
" </ol>\n",
|
||||||
|
" </ul>\n",
|
||||||
|
" <br/>\n",
|
||||||
|
" <li> Next, let's examine the ACF and PACF plots of the stationary target variable (depicted below). Here, we do not see a decay in the ACF, instead we see a decay in PACF. It is hard to make an argument the the target variable exhibits auto-regressive behavior. </li>\n",
|
||||||
|
" </ul>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Plot the ACF/PACF for the series in differences\n",
|
||||||
|
"fig, ax = plt.subplots(1, 2, figsize=(10, 5))\n",
|
||||||
|
"plot_acf(df[TARGET_COLNAME].diff().dropna().values.squeeze(), ax=ax[0])\n",
|
||||||
|
"plot_pacf(df[TARGET_COLNAME].diff().dropna().values.squeeze(), ax=ax[1])\n",
|
||||||
|
"plt.show()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<p style=\"font-size:150%; color:blue\"> Conclusion </p>\n",
|
||||||
|
"Since we do not see a clear indication of an AR(p) process, we will not be using target lags and will set the TARGET_LAGS parameter to None."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<p style=\"font-size:150%; color:blue; font-weight: bold\"> AutoML Experiment Settings </p>\n",
|
||||||
|
"Based on the analysis performed, we should try the following settings for the AutoML experiment and use them in the \"2_run_experiment\" notebook.\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li> STL_TYPE=None </li>\n",
|
||||||
|
" <li> DIFFERENCE_SERIES=True </li>\n",
|
||||||
|
" <li> TARGET_LAGS=None </li>\n",
|
||||||
|
"</ul>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Appendix: ACF, PACF and Lag Selection\n",
|
||||||
|
"To do this, we will examine the ACF and partial ACF (PACF) plots of the differenced series. \n",
|
||||||
|
"\n",
|
||||||
|
"<ul>\n",
|
||||||
|
" <li> Question: What is the ACF? </li>\n",
|
||||||
|
" <ul style=\"list-style-type:none;\">\n",
|
||||||
|
" <li> To understand the ACF, first let's look at the correlation coefficient $\\rho_{xz}$\n",
|
||||||
|
" \\begin{equation}\n",
|
||||||
|
" \\rho_{xz} = \\frac{\\sigma_{xz}}{\\sigma_{x} \\sigma_{zy}}\n",
|
||||||
|
" \\end{equation}\n",
|
||||||
|
" </li>\n",
|
||||||
|
" where $\\sigma_{xzy}$ is the covariance between two random variables $X$ and $Z$; $\\sigma_x$ and $\\sigma_z$ is the variance for $X$ and $Z$, respectively. The correlation coefficient measures the strength of linear relationship between two random variables. This metric can take any value from -1 to 1. <li/>\n",
|
||||||
|
" <br/>\n",
|
||||||
|
" <li> The auto-correlation coefficient $\\rho_{Y_{t} Y_{t-k}}$ is the time series equivalent of the correlation coefficient, except instead of measuring linear association between two random variables $X$ and $Z$, it measures the strength of a linear relationship between a random variable $Y_t$ and its lag $Y_{t-k}$ for any positive interger value of $k$. </li> \n",
|
||||||
|
" <br />\n",
|
||||||
|
" <li> To visualize the ACF for a particular lag, say lag 2, plot the second lag of a series $y_{t-2}$ on the x-axis, and plot the series itself $y_t$ on the y-axis. The autocorrelation coefficient is the slope of the best fitted regression line and can be interpreted as follows. A one unit increase in the lag of a variable one period ago leads to a $\\rho_{Y_{t} Y_{t-2}}$ units change in the variable in the current period. This interpreation can be applied to any lag. </li> \n",
|
||||||
|
" <br />\n",
|
||||||
|
" <li> In the interpretation posted above we need to be careful not to confuse the word \"leads\" with \"causes\" since these are not the same thing. We do not know the lagged value of the varaible causes it to change. Afterall, there are probably many other features that may explain the movement in $Y_t$. All we are trying to do in this section is to identify situations when the variable contains the strong auto-regressive components that needs to be included in the model to improve forecast accuracy. </li>\n",
|
||||||
|
" </ul>\n",
|
||||||
|
"</ul>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<ul>\n",
|
||||||
|
" <li> Question: What is the PACF? </li>\n",
|
||||||
|
" <ul style=\"list-style-type:none;\">\n",
|
||||||
|
" <li> When describing the ACF we essentially running a regression between a partigular lag of a series, say, lag 4, and the series itself. What this implies is the regression coefficient for lag 4 captures the impact of everything that happens in lags 1, 2 and 3. In other words, if lag 1 is the most important lag and we exclude it from the regression, naturally, the regression model will assign the importance of the 1st lag to the 4th one. Partial auto-correlation function fixes this problem since it measures the contribution of each lag accounting for the information added by the intermediary lags. If we were to illustrate ACF and PACF for the fourth lag using the regression analogy, the difference is a follows: \n",
|
||||||
|
" \\begin{align}\n",
|
||||||
|
" Y_{t} &= a_{0} + a_{4} Y_{t-4} + e_{t} \\\\\n",
|
||||||
|
" Y_{t} &= b_{0} + b_{1} Y_{t-1} + b_{2} Y_{t-2} + b_{3} Y_{t-3} + b_{4} Y_{t-4} + \\varepsilon_{t} \\\\\n",
|
||||||
|
" \\end{align}\n",
|
||||||
|
" </li>\n",
|
||||||
|
" <br/>\n",
|
||||||
|
" <li>\n",
|
||||||
|
" Here, you can think of $a_4$ and $b_{4}$ as the auto- and partial auto-correlation coefficients for lag 4. Notice, in the second equation we explicitely accounting for the intermediate lags by adding them as regrerssors.\n",
|
||||||
|
" </li>\n",
|
||||||
|
" </ul>\n",
|
||||||
|
"</ul>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<ul>\n",
|
||||||
|
" <li> Question: Auto-regressive pattern? What are we looking for? </li>\n",
|
||||||
|
" <ul style=\"list-style-type:none;\">\n",
|
||||||
|
" <li> We are looking for a classical profiles for an AR(p) process such as an exponential decay of an ACF and a the first $p$ significant lags of the PACF. Let's examine the ACF/PACF profiles of the same simulated AR(2) shown in Section 3, and check if the ACF/PACF explanation are refelcted in these plots. <li/>\n",
|
||||||
|
" <li><img src=\"figures/ACF_PACF_for_AR2.png\" class=\"img_class\">\n",
|
||||||
|
" <li> The autocorrelation coefficient for the 3rd lag is 0.6, which can be interpreted that a one unit increase in the value of the target varaible three periods ago leads to 0.6 units increase in the current period. However, the PACF plot shows that the partial autocorrealtion coefficient is zero (from a statistical point of view since it lies within the shaded region). This is happening because the 1st and 2nd lags are good predictors of the target variable. Ommiting these two lags from the regression results in the misleading conclusion that the third lag is a good prediciton. <li/>\n",
|
||||||
|
" <br/>\n",
|
||||||
|
" <li> This is why it is important to examine both the ACF and the PACF plots when tring to determine the auto regressive order for the variable in question. <li/>\n",
|
||||||
|
" </ul>\n",
|
||||||
|
"</ul> "
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"authors": [
|
||||||
|
{
|
||||||
|
"name": "vlbejan"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 3.6",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python36"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"codemirror_mode": {
|
||||||
|
"name": "ipython",
|
||||||
|
"version": 3
|
||||||
|
},
|
||||||
|
"file_extension": ".py",
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython3",
|
||||||
|
"version": "3.6.9"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 4
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
name: auto-ml-forecasting-univariate-recipe-experiment-settings
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
@@ -0,0 +1,593 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
||||||
|
"\n",
|
||||||
|
"Licensed under the MIT License."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
""
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Running AutoML experiments\n",
|
||||||
|
"\n",
|
||||||
|
"See the `auto-ml-forecasting-univariate-recipe-experiment-settings` notebook on how to determine settings for seasonal features, target lags and whether the series needs to be differenced or not. To make experimentation user-friendly, the user has to specify several parameters: DIFFERENCE_SERIES, TARGET_LAGS and STL_TYPE. Once these parameters are set, the notebook will generate correct transformations and settings to run experiments, generate forecasts, compute inference set metrics and plot forecast vs actuals. It will also convert the forecast from first differences to levels (original units of measurement) if the DIFFERENCE_SERIES parameter is set to True before calculating inference set metrics.\n",
|
||||||
|
"\n",
|
||||||
|
"<br/>\n",
|
||||||
|
"\n",
|
||||||
|
"The output generated by this notebook is saved in the `experiment_output`folder."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Setup"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"import os\n",
|
||||||
|
"import logging\n",
|
||||||
|
"import pandas as pd\n",
|
||||||
|
"import numpy as np\n",
|
||||||
|
"\n",
|
||||||
|
"import azureml.automl.runtime\n",
|
||||||
|
"from azureml.core.compute import AmlCompute\n",
|
||||||
|
"from azureml.core.compute import ComputeTarget\n",
|
||||||
|
"import matplotlib.pyplot as plt\n",
|
||||||
|
"from helper_functions import ts_train_test_split, compute_metrics\n",
|
||||||
|
"\n",
|
||||||
|
"import azureml.core\n",
|
||||||
|
"from azureml.core.workspace import Workspace\n",
|
||||||
|
"from azureml.core.experiment import Experiment\n",
|
||||||
|
"from azureml.train.automl import AutoMLConfig\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"# set printing options\n",
|
||||||
|
"np.set_printoptions(precision=4, suppress=True, linewidth=100)\n",
|
||||||
|
"pd.set_option(\"display.max_columns\", 500)\n",
|
||||||
|
"pd.set_option(\"display.width\", 1000)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"As part of the setup you have already created a **Workspace**. You will also need to create a [compute target](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-set-up-training-targets#amlcompute) for your AutoML run. In this tutorial, you create AmlCompute as your training compute resource.\n",
|
||||||
|
"> 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."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"ws = Workspace.from_config()\n",
|
||||||
|
"amlcompute_cluster_name = \"recipe-cluster\"\n",
|
||||||
|
"\n",
|
||||||
|
"found = False\n",
|
||||||
|
"# Check if this compute target already exists in the workspace.\n",
|
||||||
|
"cts = ws.compute_targets\n",
|
||||||
|
"if amlcompute_cluster_name in cts and cts[amlcompute_cluster_name].type == \"AmlCompute\":\n",
|
||||||
|
" found = True\n",
|
||||||
|
" print(\"Found existing compute target.\")\n",
|
||||||
|
" compute_target = cts[amlcompute_cluster_name]\n",
|
||||||
|
"\n",
|
||||||
|
"if not found:\n",
|
||||||
|
" print(\"Creating a new compute target...\")\n",
|
||||||
|
" provisioning_config = AmlCompute.provisioning_configuration(\n",
|
||||||
|
" vm_size=\"STANDARD_D2_V2\", max_nodes=6\n",
|
||||||
|
" )\n",
|
||||||
|
"\n",
|
||||||
|
" # Create the cluster.\\n\",\n",
|
||||||
|
" compute_target = ComputeTarget.create(\n",
|
||||||
|
" ws, amlcompute_cluster_name, provisioning_config\n",
|
||||||
|
" )\n",
|
||||||
|
"\n",
|
||||||
|
"print(\"Checking cluster status...\")\n",
|
||||||
|
"# Can poll for a minimum number of nodes and for a specific timeout.\n",
|
||||||
|
"# If no min_node_count is provided, it will use the scale settings for the cluster.\n",
|
||||||
|
"compute_target.wait_for_completion(\n",
|
||||||
|
" show_output=True, min_node_count=None, timeout_in_minutes=20\n",
|
||||||
|
")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Data\n",
|
||||||
|
"\n",
|
||||||
|
"Here, we will load the data from the csv file and drop the Covid period."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"main_data_loc = \"data\"\n",
|
||||||
|
"train_file_name = \"S4248SM144SCEN.csv\"\n",
|
||||||
|
"\n",
|
||||||
|
"TARGET_COLNAME = \"S4248SM144SCEN\"\n",
|
||||||
|
"TIME_COLNAME = \"observation_date\"\n",
|
||||||
|
"COVID_PERIOD_START = (\n",
|
||||||
|
" \"2020-03-01\" # start of the covid period. To be excluded from evaluation.\n",
|
||||||
|
")\n",
|
||||||
|
"\n",
|
||||||
|
"# load data\n",
|
||||||
|
"df = pd.read_csv(os.path.join(main_data_loc, train_file_name))\n",
|
||||||
|
"df[TIME_COLNAME] = pd.to_datetime(df[TIME_COLNAME], format=\"%Y-%m-%d\")\n",
|
||||||
|
"df.sort_values(by=TIME_COLNAME, inplace=True)\n",
|
||||||
|
"\n",
|
||||||
|
"# remove the Covid period\n",
|
||||||
|
"df = df.query('{} <= \"{}\"'.format(TIME_COLNAME, COVID_PERIOD_START))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Set parameters\n",
|
||||||
|
"\n",
|
||||||
|
"The first set of parameters is based on the analysis performed in the `auto-ml-forecasting-univariate-recipe-experiment-settings` notebook. "
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# set parameters based on the settings notebook analysis\n",
|
||||||
|
"DIFFERENCE_SERIES = True\n",
|
||||||
|
"TARGET_LAGS = None\n",
|
||||||
|
"STL_TYPE = None"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Next, define additional parameters to be used in the <a href=\"https://docs.microsoft.com/en-us/python/api/azureml-train-automl-client/azureml.train.automl.automlconfig?view=azure-ml-py\"> AutoML config </a> class.\n",
|
||||||
|
"\n",
|
||||||
|
"<ul> \n",
|
||||||
|
" <li> FORECAST_HORIZON: The forecast horizon is the number of periods into the future that the model should predict. Here, we set the horizon to 12 periods (i.e. 12 quarters). For more discussion of forecast horizons and guiding principles for setting them, please see the <a href=\"https://github.com/Azure/MachineLearningNotebooks/tree/master/how-to-use-azureml/automated-machine-learning/forecasting-energy-demand\"> energy demand notebook </a>. \n",
|
||||||
|
" </li>\n",
|
||||||
|
" <li> TIME_SERIES_ID_COLNAMES: The names of columns used to group a timeseries. It can be used to create multiple series. If time series identifier is not defined, the data set is assumed to be one time-series. This parameter is used with task type forecasting. Since we are working with a single series, this list is empty.\n",
|
||||||
|
" </li>\n",
|
||||||
|
" <li> BLOCKED_MODELS: Optional list of models to be blocked from consideration during model selection stage. At this point we want to consider all ML and Time Series models.\n",
|
||||||
|
" <ul>\n",
|
||||||
|
" <li> See the following <a href=\"https://docs.microsoft.com/en-us/python/api/azureml-train-automl-client/azureml.train.automl.constants.supportedmodels.forecasting?view=azure-ml-py\"> link </a> for a list of supported Forecasting models</li>\n",
|
||||||
|
" </ul>\n",
|
||||||
|
" </li>\n",
|
||||||
|
"</ul>\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# set other parameters\n",
|
||||||
|
"FORECAST_HORIZON = 12\n",
|
||||||
|
"TIME_SERIES_ID_COLNAMES = []\n",
|
||||||
|
"BLOCKED_MODELS = []"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"To run AutoML, you also need to create an **Experiment**. An Experiment corresponds to a prediction problem you are trying to solve, while a Run corresponds to a specific approach to the problem."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# choose a name for the run history container in the workspace\n",
|
||||||
|
"if isinstance(TARGET_LAGS, list):\n",
|
||||||
|
" TARGET_LAGS_STR = (\n",
|
||||||
|
" \"-\".join(map(str, TARGET_LAGS)) if (len(TARGET_LAGS) > 0) else None\n",
|
||||||
|
" )\n",
|
||||||
|
"else:\n",
|
||||||
|
" TARGET_LAGS_STR = TARGET_LAGS\n",
|
||||||
|
"\n",
|
||||||
|
"experiment_desc = \"diff-{}_lags-{}_STL-{}\".format(\n",
|
||||||
|
" DIFFERENCE_SERIES, TARGET_LAGS_STR, STL_TYPE\n",
|
||||||
|
")\n",
|
||||||
|
"experiment_name = \"alcohol_{}\".format(experiment_desc)\n",
|
||||||
|
"experiment = Experiment(ws, experiment_name)\n",
|
||||||
|
"\n",
|
||||||
|
"output = {}\n",
|
||||||
|
"output[\"SDK version\"] = azureml.core.VERSION\n",
|
||||||
|
"output[\"Subscription ID\"] = ws.subscription_id\n",
|
||||||
|
"output[\"Workspace\"] = ws.name\n",
|
||||||
|
"output[\"SKU\"] = ws.sku\n",
|
||||||
|
"output[\"Resource Group\"] = ws.resource_group\n",
|
||||||
|
"output[\"Location\"] = ws.location\n",
|
||||||
|
"output[\"Run History Name\"] = experiment_name\n",
|
||||||
|
"pd.set_option(\"display.max_colwidth\", -1)\n",
|
||||||
|
"outputDf = pd.DataFrame(data=output, index=[\"\"])\n",
|
||||||
|
"print(outputDf.T)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# create output directory\n",
|
||||||
|
"output_dir = \"experiment_output/{}\".format(experiment_desc)\n",
|
||||||
|
"if not os.path.exists(output_dir):\n",
|
||||||
|
" os.makedirs(output_dir)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# difference data and test for unit root\n",
|
||||||
|
"if DIFFERENCE_SERIES:\n",
|
||||||
|
" df_delta = df.copy()\n",
|
||||||
|
" df_delta[TARGET_COLNAME] = df[TARGET_COLNAME].diff()\n",
|
||||||
|
" df_delta.dropna(axis=0, inplace=True)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# split the data into train and test set\n",
|
||||||
|
"if DIFFERENCE_SERIES:\n",
|
||||||
|
" # generate train/inference sets using data in first differences\n",
|
||||||
|
" df_train, df_test = ts_train_test_split(\n",
|
||||||
|
" df_input=df_delta,\n",
|
||||||
|
" n=FORECAST_HORIZON,\n",
|
||||||
|
" time_colname=TIME_COLNAME,\n",
|
||||||
|
" ts_id_colnames=TIME_SERIES_ID_COLNAMES,\n",
|
||||||
|
" )\n",
|
||||||
|
"else:\n",
|
||||||
|
" df_train, df_test = ts_train_test_split(\n",
|
||||||
|
" df_input=df,\n",
|
||||||
|
" n=FORECAST_HORIZON,\n",
|
||||||
|
" time_colname=TIME_COLNAME,\n",
|
||||||
|
" ts_id_colnames=TIME_SERIES_ID_COLNAMES,\n",
|
||||||
|
" )"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Upload files to the Datastore\n",
|
||||||
|
"The [Machine Learning service workspace](https://docs.microsoft.com/en-us/azure/machine-learning/service/concept-workspace) is paired with the storage account, which contains the default data store. We will use it to upload the bike share data and create [tabular dataset](https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.data.tabulardataset?view=azure-ml-py) for training. A tabular dataset defines a series of lazily-evaluated, immutable operations to load data from the data source into tabular representation."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"df_train.to_csv(\"train.csv\", index=False)\n",
|
||||||
|
"df_test.to_csv(\"test.csv\", index=False)\n",
|
||||||
|
"\n",
|
||||||
|
"datastore = ws.get_default_datastore()\n",
|
||||||
|
"datastore.upload_files(\n",
|
||||||
|
" files=[\"./train.csv\"],\n",
|
||||||
|
" target_path=\"uni-recipe-dataset/tabular/\",\n",
|
||||||
|
" overwrite=True,\n",
|
||||||
|
" show_progress=True,\n",
|
||||||
|
")\n",
|
||||||
|
"datastore.upload_files(\n",
|
||||||
|
" files=[\"./test.csv\"],\n",
|
||||||
|
" target_path=\"uni-recipe-dataset/tabular/\",\n",
|
||||||
|
" overwrite=True,\n",
|
||||||
|
" show_progress=True,\n",
|
||||||
|
")\n",
|
||||||
|
"\n",
|
||||||
|
"from azureml.core import Dataset\n",
|
||||||
|
"\n",
|
||||||
|
"train_dataset = Dataset.Tabular.from_delimited_files(\n",
|
||||||
|
" path=[(datastore, \"uni-recipe-dataset/tabular/train.csv\")]\n",
|
||||||
|
")\n",
|
||||||
|
"test_dataset = Dataset.Tabular.from_delimited_files(\n",
|
||||||
|
" path=[(datastore, \"uni-recipe-dataset/tabular/test.csv\")]\n",
|
||||||
|
")\n",
|
||||||
|
"\n",
|
||||||
|
"# print the first 5 rows of the Dataset\n",
|
||||||
|
"train_dataset.to_pandas_dataframe().reset_index(drop=True).head(5)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Config AutoML"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"time_series_settings = {\n",
|
||||||
|
" \"time_column_name\": TIME_COLNAME,\n",
|
||||||
|
" \"forecast_horizon\": FORECAST_HORIZON,\n",
|
||||||
|
" \"target_lags\": TARGET_LAGS,\n",
|
||||||
|
" \"use_stl\": STL_TYPE,\n",
|
||||||
|
" \"blocked_models\": BLOCKED_MODELS,\n",
|
||||||
|
" \"time_series_id_column_names\": TIME_SERIES_ID_COLNAMES,\n",
|
||||||
|
"}\n",
|
||||||
|
"\n",
|
||||||
|
"automl_config = AutoMLConfig(\n",
|
||||||
|
" task=\"forecasting\",\n",
|
||||||
|
" debug_log=\"sample_experiment.log\",\n",
|
||||||
|
" primary_metric=\"normalized_root_mean_squared_error\",\n",
|
||||||
|
" experiment_timeout_minutes=20,\n",
|
||||||
|
" iteration_timeout_minutes=5,\n",
|
||||||
|
" enable_early_stopping=True,\n",
|
||||||
|
" training_data=train_dataset,\n",
|
||||||
|
" label_column_name=TARGET_COLNAME,\n",
|
||||||
|
" n_cross_validations=5,\n",
|
||||||
|
" verbosity=logging.INFO,\n",
|
||||||
|
" max_cores_per_iteration=-1,\n",
|
||||||
|
" compute_target=compute_target,\n",
|
||||||
|
" **time_series_settings,\n",
|
||||||
|
")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"We will now run the experiment, you can go to Azure ML portal to view the run details."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"remote_run = experiment.submit(automl_config, show_output=False)\n",
|
||||||
|
"remote_run.wait_for_completion()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Retrieve the best model\n",
|
||||||
|
"Below we select the best model from all the training iterations using get_output method."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"best_run, fitted_model = remote_run.get_output()\n",
|
||||||
|
"fitted_model.steps"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Inference\n",
|
||||||
|
"\n",
|
||||||
|
"We now use the best fitted model from the AutoML Run to make forecasts for the test set. We will do batch scoring on the test dataset which should have the same schema as training dataset.\n",
|
||||||
|
"\n",
|
||||||
|
"The inference will run on a remote compute. In this example, it will re-use the training compute."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"test_experiment = Experiment(ws, experiment_name + \"_inference\")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Retreiving forecasts from the model\n",
|
||||||
|
"We have created a function called `run_forecast` that submits the test data to the best model determined during the training run and retrieves forecasts. This function uses a helper script `forecasting_script` which is uploaded and expecuted on the remote compute."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from run_forecast import run_remote_inference\n",
|
||||||
|
"\n",
|
||||||
|
"remote_run = run_remote_inference(\n",
|
||||||
|
" test_experiment=test_experiment,\n",
|
||||||
|
" compute_target=compute_target,\n",
|
||||||
|
" train_run=best_run,\n",
|
||||||
|
" test_dataset=test_dataset,\n",
|
||||||
|
" target_column_name=TARGET_COLNAME,\n",
|
||||||
|
")\n",
|
||||||
|
"remote_run.wait_for_completion(show_output=False)\n",
|
||||||
|
"\n",
|
||||||
|
"remote_run.download_file(\"outputs/predictions.csv\", f\"{output_dir}/predictions.csv\")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Download the prediction result for metrics calcuation\n",
|
||||||
|
"The test data with predictions are saved in artifact `outputs/predictions.csv`. We will use it to calculate accuracy metrics and vizualize predictions versus actuals."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"X_trans = pd.read_csv(f\"{output_dir}/predictions.csv\", parse_dates=[TIME_COLNAME])\n",
|
||||||
|
"X_trans.head()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# convert forecast in differences to levels\n",
|
||||||
|
"def convert_fcst_diff_to_levels(fcst, yt, df_orig):\n",
|
||||||
|
" \"\"\"Convert forecast from first differences to levels.\"\"\"\n",
|
||||||
|
" fcst = fcst.reset_index(drop=False, inplace=False)\n",
|
||||||
|
" fcst[\"predicted_level\"] = fcst[\"predicted\"].cumsum()\n",
|
||||||
|
" fcst[\"predicted_level\"] = fcst[\"predicted_level\"].astype(float) + float(yt)\n",
|
||||||
|
" # merge actuals\n",
|
||||||
|
" out = pd.merge(\n",
|
||||||
|
" fcst, df_orig[[TIME_COLNAME, TARGET_COLNAME]], on=[TIME_COLNAME], how=\"inner\"\n",
|
||||||
|
" )\n",
|
||||||
|
" out.rename(columns={TARGET_COLNAME: \"actual_level\"}, inplace=True)\n",
|
||||||
|
" return out"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"if DIFFERENCE_SERIES:\n",
|
||||||
|
" # convert forecast in differences to the levels\n",
|
||||||
|
" INFORMATION_SET_DATE = max(df_train[TIME_COLNAME])\n",
|
||||||
|
" YT = df.query(\"{} == @INFORMATION_SET_DATE\".format(TIME_COLNAME))[TARGET_COLNAME]\n",
|
||||||
|
"\n",
|
||||||
|
" fcst_df = convert_fcst_diff_to_levels(fcst=X_trans, yt=YT, df_orig=df)\n",
|
||||||
|
"else:\n",
|
||||||
|
" fcst_df = X_trans.copy()\n",
|
||||||
|
" fcst_df[\"actual_level\"] = y_test\n",
|
||||||
|
" fcst_df[\"predicted_level\"] = y_predictions\n",
|
||||||
|
"\n",
|
||||||
|
"del X_trans"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Calculate metrics and save output"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# compute metrics\n",
|
||||||
|
"metrics_df = compute_metrics(fcst_df=fcst_df, metric_name=None, ts_id_colnames=None)\n",
|
||||||
|
"# save output\n",
|
||||||
|
"metrics_file_name = \"{}_metrics.csv\".format(experiment_name)\n",
|
||||||
|
"fcst_file_name = \"{}_forecst.csv\".format(experiment_name)\n",
|
||||||
|
"plot_file_name = \"{}_plot.pdf\".format(experiment_name)\n",
|
||||||
|
"\n",
|
||||||
|
"metrics_df.to_csv(os.path.join(output_dir, metrics_file_name), index=True)\n",
|
||||||
|
"fcst_df.to_csv(os.path.join(output_dir, fcst_file_name), index=True)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Generate and save visuals"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"plot_df = df.query('{} > \"2010-01-01\"'.format(TIME_COLNAME))\n",
|
||||||
|
"plot_df.set_index(TIME_COLNAME, inplace=True)\n",
|
||||||
|
"fcst_df.set_index(TIME_COLNAME, inplace=True)\n",
|
||||||
|
"\n",
|
||||||
|
"# generate and save plots\n",
|
||||||
|
"fig, ax = plt.subplots(dpi=180)\n",
|
||||||
|
"ax.plot(plot_df[TARGET_COLNAME], \"-g\", label=\"Historical\")\n",
|
||||||
|
"ax.plot(fcst_df[\"actual_level\"], \"-b\", label=\"Actual\")\n",
|
||||||
|
"ax.plot(fcst_df[\"predicted_level\"], \"-r\", label=\"Forecast\")\n",
|
||||||
|
"ax.legend()\n",
|
||||||
|
"ax.set_title(\"Forecast vs Actuals\")\n",
|
||||||
|
"ax.set_xlabel(TIME_COLNAME)\n",
|
||||||
|
"ax.set_ylabel(TARGET_COLNAME)\n",
|
||||||
|
"locs, labels = plt.xticks()\n",
|
||||||
|
"\n",
|
||||||
|
"plt.setp(labels, rotation=45)\n",
|
||||||
|
"plt.savefig(os.path.join(output_dir, plot_file_name))"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"authors": [
|
||||||
|
{
|
||||||
|
"name": "vlbejan"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 3.6",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python36"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"codemirror_mode": {
|
||||||
|
"name": "ipython",
|
||||||
|
"version": 3
|
||||||
|
},
|
||||||
|
"file_extension": ".py",
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython3",
|
||||||
|
"version": "3.6.9"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 4
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
name: auto-ml-forecasting-univariate-recipe-run-experiment
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
@@ -0,0 +1,350 @@
|
|||||||
|
observation_date,S4248SM144SCEN
|
||||||
|
1992-01-01,4302
|
||||||
|
1992-02-01,4323
|
||||||
|
1992-03-01,4199
|
||||||
|
1992-04-01,4397
|
||||||
|
1992-05-01,4159
|
||||||
|
1992-06-01,4091
|
||||||
|
1992-07-01,4109
|
||||||
|
1992-08-01,4116
|
||||||
|
1992-09-01,4093
|
||||||
|
1992-10-01,4095
|
||||||
|
1992-11-01,4169
|
||||||
|
1992-12-01,4169
|
||||||
|
1993-01-01,4124
|
||||||
|
1993-02-01,4107
|
||||||
|
1993-03-01,4168
|
||||||
|
1993-04-01,4254
|
||||||
|
1993-05-01,4290
|
||||||
|
1993-06-01,4163
|
||||||
|
1993-07-01,4274
|
||||||
|
1993-08-01,4253
|
||||||
|
1993-09-01,4312
|
||||||
|
1993-10-01,4296
|
||||||
|
1993-11-01,4221
|
||||||
|
1993-12-01,4233
|
||||||
|
1994-01-01,4218
|
||||||
|
1994-02-01,4237
|
||||||
|
1994-03-01,4343
|
||||||
|
1994-04-01,4357
|
||||||
|
1994-05-01,4264
|
||||||
|
1994-06-01,4392
|
||||||
|
1994-07-01,4381
|
||||||
|
1994-08-01,4290
|
||||||
|
1994-09-01,4348
|
||||||
|
1994-10-01,4357
|
||||||
|
1994-11-01,4417
|
||||||
|
1994-12-01,4411
|
||||||
|
1995-01-01,4417
|
||||||
|
1995-02-01,4339
|
||||||
|
1995-03-01,4256
|
||||||
|
1995-04-01,4276
|
||||||
|
1995-05-01,4290
|
||||||
|
1995-06-01,4413
|
||||||
|
1995-07-01,4305
|
||||||
|
1995-08-01,4476
|
||||||
|
1995-09-01,4393
|
||||||
|
1995-10-01,4447
|
||||||
|
1995-11-01,4492
|
||||||
|
1995-12-01,4489
|
||||||
|
1996-01-01,4635
|
||||||
|
1996-02-01,4697
|
||||||
|
1996-03-01,4588
|
||||||
|
1996-04-01,4633
|
||||||
|
1996-05-01,4685
|
||||||
|
1996-06-01,4672
|
||||||
|
1996-07-01,4666
|
||||||
|
1996-08-01,4726
|
||||||
|
1996-09-01,4571
|
||||||
|
1996-10-01,4624
|
||||||
|
1996-11-01,4691
|
||||||
|
1996-12-01,4604
|
||||||
|
1997-01-01,4657
|
||||||
|
1997-02-01,4711
|
||||||
|
1997-03-01,4810
|
||||||
|
1997-04-01,4626
|
||||||
|
1997-05-01,4860
|
||||||
|
1997-06-01,4757
|
||||||
|
1997-07-01,4916
|
||||||
|
1997-08-01,4921
|
||||||
|
1997-09-01,4985
|
||||||
|
1997-10-01,4905
|
||||||
|
1997-11-01,4880
|
||||||
|
1997-12-01,5165
|
||||||
|
1998-01-01,4885
|
||||||
|
1998-02-01,4925
|
||||||
|
1998-03-01,5049
|
||||||
|
1998-04-01,5090
|
||||||
|
1998-05-01,5094
|
||||||
|
1998-06-01,4929
|
||||||
|
1998-07-01,5132
|
||||||
|
1998-08-01,5061
|
||||||
|
1998-09-01,5471
|
||||||
|
1998-10-01,5327
|
||||||
|
1998-11-01,5257
|
||||||
|
1998-12-01,5354
|
||||||
|
1999-01-01,5427
|
||||||
|
1999-02-01,5415
|
||||||
|
1999-03-01,5387
|
||||||
|
1999-04-01,5483
|
||||||
|
1999-05-01,5510
|
||||||
|
1999-06-01,5539
|
||||||
|
1999-07-01,5532
|
||||||
|
1999-08-01,5625
|
||||||
|
1999-09-01,5799
|
||||||
|
1999-10-01,5843
|
||||||
|
1999-11-01,5836
|
||||||
|
1999-12-01,5724
|
||||||
|
2000-01-01,5757
|
||||||
|
2000-02-01,5731
|
||||||
|
2000-03-01,5839
|
||||||
|
2000-04-01,5825
|
||||||
|
2000-05-01,5877
|
||||||
|
2000-06-01,5979
|
||||||
|
2000-07-01,5828
|
||||||
|
2000-08-01,6016
|
||||||
|
2000-09-01,6113
|
||||||
|
2000-10-01,6150
|
||||||
|
2000-11-01,6111
|
||||||
|
2000-12-01,6088
|
||||||
|
2001-01-01,6360
|
||||||
|
2001-02-01,6300
|
||||||
|
2001-03-01,5935
|
||||||
|
2001-04-01,6204
|
||||||
|
2001-05-01,6164
|
||||||
|
2001-06-01,6231
|
||||||
|
2001-07-01,6336
|
||||||
|
2001-08-01,6179
|
||||||
|
2001-09-01,6120
|
||||||
|
2001-10-01,6134
|
||||||
|
2001-11-01,6381
|
||||||
|
2001-12-01,6521
|
||||||
|
2002-01-01,6333
|
||||||
|
2002-02-01,6541
|
||||||
|
2002-03-01,6692
|
||||||
|
2002-04-01,6591
|
||||||
|
2002-05-01,6554
|
||||||
|
2002-06-01,6596
|
||||||
|
2002-07-01,6620
|
||||||
|
2002-08-01,6577
|
||||||
|
2002-09-01,6625
|
||||||
|
2002-10-01,6441
|
||||||
|
2002-11-01,6584
|
||||||
|
2002-12-01,6923
|
||||||
|
2003-01-01,6600
|
||||||
|
2003-02-01,6742
|
||||||
|
2003-03-01,6831
|
||||||
|
2003-04-01,6782
|
||||||
|
2003-05-01,6714
|
||||||
|
2003-06-01,6736
|
||||||
|
2003-07-01,7146
|
||||||
|
2003-08-01,7027
|
||||||
|
2003-09-01,6896
|
||||||
|
2003-10-01,7107
|
||||||
|
2003-11-01,6997
|
||||||
|
2003-12-01,7075
|
||||||
|
2004-01-01,7235
|
||||||
|
2004-02-01,7072
|
||||||
|
2004-03-01,6968
|
||||||
|
2004-04-01,7144
|
||||||
|
2004-05-01,7232
|
||||||
|
2004-06-01,7095
|
||||||
|
2004-07-01,7181
|
||||||
|
2004-08-01,7146
|
||||||
|
2004-09-01,7230
|
||||||
|
2004-10-01,7327
|
||||||
|
2004-11-01,7328
|
||||||
|
2004-12-01,7425
|
||||||
|
2005-01-01,7520
|
||||||
|
2005-02-01,7551
|
||||||
|
2005-03-01,7572
|
||||||
|
2005-04-01,7701
|
||||||
|
2005-05-01,7819
|
||||||
|
2005-06-01,7770
|
||||||
|
2005-07-01,7627
|
||||||
|
2005-08-01,7816
|
||||||
|
2005-09-01,7718
|
||||||
|
2005-10-01,7772
|
||||||
|
2005-11-01,7788
|
||||||
|
2005-12-01,7576
|
||||||
|
2006-01-01,7940
|
||||||
|
2006-02-01,8027
|
||||||
|
2006-03-01,7884
|
||||||
|
2006-04-01,8043
|
||||||
|
2006-05-01,7995
|
||||||
|
2006-06-01,8218
|
||||||
|
2006-07-01,8159
|
||||||
|
2006-08-01,8331
|
||||||
|
2006-09-01,8320
|
||||||
|
2006-10-01,8397
|
||||||
|
2006-11-01,8603
|
||||||
|
2006-12-01,8515
|
||||||
|
2007-01-01,8336
|
||||||
|
2007-02-01,8233
|
||||||
|
2007-03-01,8475
|
||||||
|
2007-04-01,8310
|
||||||
|
2007-05-01,8583
|
||||||
|
2007-06-01,8645
|
||||||
|
2007-07-01,8713
|
||||||
|
2007-08-01,8636
|
||||||
|
2007-09-01,8791
|
||||||
|
2007-10-01,8984
|
||||||
|
2007-11-01,8867
|
||||||
|
2007-12-01,9059
|
||||||
|
2008-01-01,8911
|
||||||
|
2008-02-01,8701
|
||||||
|
2008-03-01,8956
|
||||||
|
2008-04-01,9095
|
||||||
|
2008-05-01,9102
|
||||||
|
2008-06-01,9170
|
||||||
|
2008-07-01,9194
|
||||||
|
2008-08-01,9164
|
||||||
|
2008-09-01,9337
|
||||||
|
2008-10-01,9186
|
||||||
|
2008-11-01,9029
|
||||||
|
2008-12-01,9025
|
||||||
|
2009-01-01,9486
|
||||||
|
2009-02-01,9219
|
||||||
|
2009-03-01,9059
|
||||||
|
2009-04-01,9171
|
||||||
|
2009-05-01,9114
|
||||||
|
2009-06-01,8926
|
||||||
|
2009-07-01,9150
|
||||||
|
2009-08-01,9105
|
||||||
|
2009-09-01,9011
|
||||||
|
2009-10-01,8743
|
||||||
|
2009-11-01,8958
|
||||||
|
2009-12-01,8969
|
||||||
|
2010-01-01,8984
|
||||||
|
2010-02-01,9068
|
||||||
|
2010-03-01,9335
|
||||||
|
2010-04-01,9481
|
||||||
|
2010-05-01,9132
|
||||||
|
2010-06-01,9192
|
||||||
|
2010-07-01,9123
|
||||||
|
2010-08-01,9091
|
||||||
|
2010-09-01,9155
|
||||||
|
2010-10-01,9556
|
||||||
|
2010-11-01,9477
|
||||||
|
2010-12-01,9436
|
||||||
|
2011-01-01,9519
|
||||||
|
2011-02-01,9667
|
||||||
|
2011-03-01,9668
|
||||||
|
2011-04-01,9628
|
||||||
|
2011-05-01,9376
|
||||||
|
2011-06-01,9830
|
||||||
|
2011-07-01,9626
|
||||||
|
2011-08-01,9802
|
||||||
|
2011-09-01,9858
|
||||||
|
2011-10-01,9838
|
||||||
|
2011-11-01,9846
|
||||||
|
2011-12-01,9789
|
||||||
|
2012-01-01,9955
|
||||||
|
2012-02-01,9909
|
||||||
|
2012-03-01,9897
|
||||||
|
2012-04-01,9909
|
||||||
|
2012-05-01,10127
|
||||||
|
2012-06-01,10175
|
||||||
|
2012-07-01,10129
|
||||||
|
2012-08-01,10251
|
||||||
|
2012-09-01,10227
|
||||||
|
2012-10-01,10174
|
||||||
|
2012-11-01,10402
|
||||||
|
2012-12-01,10664
|
||||||
|
2013-01-01,10585
|
||||||
|
2013-02-01,10661
|
||||||
|
2013-03-01,10649
|
||||||
|
2013-04-01,10676
|
||||||
|
2013-05-01,10863
|
||||||
|
2013-06-01,10690
|
||||||
|
2013-07-01,11007
|
||||||
|
2013-08-01,10835
|
||||||
|
2013-09-01,10900
|
||||||
|
2013-10-01,10749
|
||||||
|
2013-11-01,10946
|
||||||
|
2013-12-01,10864
|
||||||
|
2014-01-01,10726
|
||||||
|
2014-02-01,10821
|
||||||
|
2014-03-01,10789
|
||||||
|
2014-04-01,10892
|
||||||
|
2014-05-01,10892
|
||||||
|
2014-06-01,10789
|
||||||
|
2014-07-01,10662
|
||||||
|
2014-08-01,10767
|
||||||
|
2014-09-01,10779
|
||||||
|
2014-10-01,10922
|
||||||
|
2014-11-01,10662
|
||||||
|
2014-12-01,10808
|
||||||
|
2015-01-01,10865
|
||||||
|
2015-02-01,10740
|
||||||
|
2015-03-01,10917
|
||||||
|
2015-04-01,10933
|
||||||
|
2015-05-01,11074
|
||||||
|
2015-06-01,11108
|
||||||
|
2015-07-01,11493
|
||||||
|
2015-08-01,11386
|
||||||
|
2015-09-01,11502
|
||||||
|
2015-10-01,11487
|
||||||
|
2015-11-01,11375
|
||||||
|
2015-12-01,11445
|
||||||
|
2016-01-01,11787
|
||||||
|
2016-02-01,11792
|
||||||
|
2016-03-01,11649
|
||||||
|
2016-04-01,11810
|
||||||
|
2016-05-01,11496
|
||||||
|
2016-06-01,11600
|
||||||
|
2016-07-01,11503
|
||||||
|
2016-08-01,11715
|
||||||
|
2016-09-01,11732
|
||||||
|
2016-10-01,11885
|
||||||
|
2016-11-01,12092
|
||||||
|
2016-12-01,11857
|
||||||
|
2017-01-01,11881
|
||||||
|
2017-02-01,12355
|
||||||
|
2017-03-01,12027
|
||||||
|
2017-04-01,12183
|
||||||
|
2017-05-01,12170
|
||||||
|
2017-06-01,12387
|
||||||
|
2017-07-01,12041
|
||||||
|
2017-08-01,12139
|
||||||
|
2017-09-01,11861
|
||||||
|
2017-10-01,12202
|
||||||
|
2017-11-01,12178
|
||||||
|
2017-12-01,12126
|
||||||
|
2018-01-01,11942
|
||||||
|
2018-02-01,12206
|
||||||
|
2018-03-01,12362
|
||||||
|
2018-04-01,12287
|
||||||
|
2018-05-01,12497
|
||||||
|
2018-06-01,12621
|
||||||
|
2018-07-01,12729
|
||||||
|
2018-08-01,12689
|
||||||
|
2018-09-01,12874
|
||||||
|
2018-10-01,12776
|
||||||
|
2018-11-01,12995
|
||||||
|
2018-12-01,13291
|
||||||
|
2019-01-01,13364
|
||||||
|
2019-02-01,13135
|
||||||
|
2019-03-01,13123
|
||||||
|
2019-04-01,13110
|
||||||
|
2019-05-01,13152
|
||||||
|
2019-06-01,13201
|
||||||
|
2019-07-01,13354
|
||||||
|
2019-08-01,13427
|
||||||
|
2019-09-01,13472
|
||||||
|
2019-10-01,13436
|
||||||
|
2019-11-01,13430
|
||||||
|
2019-12-01,13588
|
||||||
|
2020-01-01,13533
|
||||||
|
2020-02-01,13575
|
||||||
|
2020-03-01,13867
|
||||||
|
2020-04-01,12319
|
||||||
|
2020-05-01,13909
|
||||||
|
2020-06-01,13982
|
||||||
|
2020-07-01,15384
|
||||||
|
2020-08-01,15701
|
||||||
|
2020-09-01,15006
|
||||||
|
2020-10-01,15741
|
||||||
|
2020-11-01,14934
|
||||||
|
2020-12-01,13061
|
||||||
|
2021-01-01,15743
|
||||||
|
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 212 KiB |
@@ -0,0 +1,70 @@
|
|||||||
|
"""
|
||||||
|
This is the script that is executed on the compute instance. It relies
|
||||||
|
on the model.pkl file which is uploaded along with this script to the
|
||||||
|
compute instance.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
from azureml.core import Dataset, Run
|
||||||
|
from azureml.automl.core.shared.constants import TimeSeriesInternal
|
||||||
|
from sklearn.externals import joblib
|
||||||
|
|
||||||
|
parser = argparse.ArgumentParser()
|
||||||
|
parser.add_argument(
|
||||||
|
"--target_column_name",
|
||||||
|
type=str,
|
||||||
|
dest="target_column_name",
|
||||||
|
help="Target Column Name",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--test_dataset", type=str, dest="test_dataset", help="Test Dataset"
|
||||||
|
)
|
||||||
|
|
||||||
|
args = parser.parse_args()
|
||||||
|
target_column_name = args.target_column_name
|
||||||
|
test_dataset_id = args.test_dataset
|
||||||
|
|
||||||
|
run = Run.get_context()
|
||||||
|
ws = run.experiment.workspace
|
||||||
|
|
||||||
|
# get the input dataset by id
|
||||||
|
test_dataset = Dataset.get_by_id(ws, id=test_dataset_id)
|
||||||
|
|
||||||
|
X_test = (
|
||||||
|
test_dataset.drop_columns(columns=[target_column_name])
|
||||||
|
.to_pandas_dataframe()
|
||||||
|
.reset_index(drop=True)
|
||||||
|
)
|
||||||
|
y_test_df = (
|
||||||
|
test_dataset.with_timestamp_columns(None)
|
||||||
|
.keep_columns(columns=[target_column_name])
|
||||||
|
.to_pandas_dataframe()
|
||||||
|
)
|
||||||
|
|
||||||
|
# generate forecast
|
||||||
|
fitted_model = joblib.load("model.pkl")
|
||||||
|
# We have default quantiles values set as below(95th percentile)
|
||||||
|
quantiles = [0.025, 0.5, 0.975]
|
||||||
|
predicted_column_name = "predicted"
|
||||||
|
PI = "prediction_interval"
|
||||||
|
fitted_model.quantiles = quantiles
|
||||||
|
pred_quantiles = fitted_model.forecast_quantiles(X_test)
|
||||||
|
pred_quantiles[PI] = pred_quantiles[[min(quantiles), max(quantiles)]].apply(
|
||||||
|
lambda x: "[{}, {}]".format(x[0], x[1]), axis=1
|
||||||
|
)
|
||||||
|
X_test[target_column_name] = y_test_df[target_column_name]
|
||||||
|
X_test[PI] = pred_quantiles[PI]
|
||||||
|
X_test[predicted_column_name] = pred_quantiles[0.5]
|
||||||
|
# drop rows where prediction or actuals are nan
|
||||||
|
# happens because of missing actuals
|
||||||
|
# or at edges of time due to lags/rolling windows
|
||||||
|
clean = X_test[
|
||||||
|
X_test[[target_column_name, predicted_column_name]].notnull().all(axis=1)
|
||||||
|
]
|
||||||
|
clean.rename(columns={target_column_name: "actual"}, inplace=True)
|
||||||
|
|
||||||
|
file_name = "outputs/predictions.csv"
|
||||||
|
export_csv = clean.to_csv(file_name, header=True, index=False) # added Index
|
||||||
|
|
||||||
|
# Upload the predictions into artifacts
|
||||||
|
run.upload_file(name=file_name, path_or_stream=file_name)
|
||||||
@@ -0,0 +1,263 @@
|
|||||||
|
"""
|
||||||
|
Helper functions to determine AutoML experiment settings for forecasting.
|
||||||
|
"""
|
||||||
|
import pandas as pd
|
||||||
|
import statsmodels.tsa.stattools as stattools
|
||||||
|
from arch import unitroot
|
||||||
|
from azureml.automl.core.shared import constants
|
||||||
|
from azureml.automl.runtime.shared.score import scoring
|
||||||
|
|
||||||
|
|
||||||
|
def adf_test(series, **kw):
|
||||||
|
"""
|
||||||
|
Wrapper for the augmented Dickey-Fuller test. Allows users to set the lag order.
|
||||||
|
|
||||||
|
:param series: series to test
|
||||||
|
:return: dictionary of results
|
||||||
|
"""
|
||||||
|
if "lags" in kw.keys():
|
||||||
|
msg = "Lag order of {} detected. Running the ADF test...".format(
|
||||||
|
str(kw["lags"])
|
||||||
|
)
|
||||||
|
print(msg)
|
||||||
|
statistic, pval, critval, resstore = stattools.adfuller(
|
||||||
|
series, maxlag=kw["lags"], autolag=kw["autolag"], store=kw["store"]
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
statistic, pval, critval, resstore = stattools.adfuller(
|
||||||
|
series, autolag=kw["IC"], store=kw["store"]
|
||||||
|
)
|
||||||
|
|
||||||
|
output = {
|
||||||
|
"statistic": statistic,
|
||||||
|
"pval": pval,
|
||||||
|
"critical": critval,
|
||||||
|
"resstore": resstore,
|
||||||
|
}
|
||||||
|
return output
|
||||||
|
|
||||||
|
|
||||||
|
def kpss_test(series, **kw):
|
||||||
|
"""
|
||||||
|
Wrapper for the KPSS test. Allows users to set the lag order.
|
||||||
|
|
||||||
|
:param series: series to test
|
||||||
|
:return: dictionary of results
|
||||||
|
"""
|
||||||
|
if kw["store"]:
|
||||||
|
statistic, p_value, critical_values, rstore = stattools.kpss(
|
||||||
|
series, regression=kw["reg_type"], lags=kw["lags"], store=kw["store"]
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
statistic, p_value, lags, critical_values = stattools.kpss(
|
||||||
|
series, regression=kw["reg_type"], lags=kw["lags"]
|
||||||
|
)
|
||||||
|
output = {
|
||||||
|
"statistic": statistic,
|
||||||
|
"pval": p_value,
|
||||||
|
"critical": critical_values,
|
||||||
|
"lags": rstore.lags if kw["store"] else lags,
|
||||||
|
}
|
||||||
|
|
||||||
|
if kw["store"]:
|
||||||
|
output.update({"resstore": rstore})
|
||||||
|
return output
|
||||||
|
|
||||||
|
|
||||||
|
def format_test_output(test_name, test_res, H0_unit_root=True):
|
||||||
|
"""
|
||||||
|
Helper function to format output. Return a dictionary with specific keys. Will be used to
|
||||||
|
construct the summary data frame for all unit root tests.
|
||||||
|
|
||||||
|
TODO: Add functionality of choosing based on the max lag order specified by user.
|
||||||
|
|
||||||
|
:param test_name: name of the test
|
||||||
|
:param test_res: object that contains corresponding test information. Can be None if test failed.
|
||||||
|
:param H0_unit_root: does the null hypothesis of the test assume a unit root process? Some tests do (ADF),
|
||||||
|
some don't (KPSS).
|
||||||
|
:return: dictionary of summary table for all tests and final decision on stationary vs non-stationary.
|
||||||
|
If test failed (test_res is None), return empty dictionary.
|
||||||
|
"""
|
||||||
|
# Check if the test failed by trying to extract the test statistic
|
||||||
|
if test_name in ("ADF", "KPSS"):
|
||||||
|
try:
|
||||||
|
test_res["statistic"]
|
||||||
|
except BaseException:
|
||||||
|
test_res = None
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
test_res.stat
|
||||||
|
except BaseException:
|
||||||
|
test_res = None
|
||||||
|
|
||||||
|
if test_res is None:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
# extract necessary information
|
||||||
|
if test_name in ("ADF", "KPSS"):
|
||||||
|
statistic = test_res["statistic"]
|
||||||
|
crit_val = test_res["critical"]["5%"]
|
||||||
|
p_val = test_res["pval"]
|
||||||
|
lags = test_res["resstore"].usedlag if test_name == "ADF" else test_res["lags"]
|
||||||
|
else:
|
||||||
|
statistic = test_res.stat
|
||||||
|
crit_val = test_res.critical_values["5%"]
|
||||||
|
p_val = test_res.pvalue
|
||||||
|
lags = test_res.lags
|
||||||
|
|
||||||
|
if H0_unit_root:
|
||||||
|
H0 = "The process is non-stationary"
|
||||||
|
stationary = "yes" if p_val < 0.05 else "not"
|
||||||
|
else:
|
||||||
|
H0 = "The process is stationary"
|
||||||
|
stationary = "yes" if p_val > 0.05 else "not"
|
||||||
|
|
||||||
|
out = {
|
||||||
|
"test_name": test_name,
|
||||||
|
"statistic": statistic,
|
||||||
|
"crit_val": crit_val,
|
||||||
|
"p_val": p_val,
|
||||||
|
"lags": int(lags),
|
||||||
|
"stationary": stationary,
|
||||||
|
"Null Hypothesis": H0,
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def unit_root_test_wrapper(series, lags=None):
|
||||||
|
"""
|
||||||
|
Main function to run multiple stationarity tests. Runs five tests and returns a summary table + decision
|
||||||
|
based on the majority rule. If the number of tests that determine a series is stationary equals to the
|
||||||
|
number of tests that deem it non-stationary, we assume the series is non-stationary.
|
||||||
|
* Augmented Dickey-Fuller (ADF),
|
||||||
|
* KPSS,
|
||||||
|
* ADF using GLS,
|
||||||
|
* Phillips-Perron (PP),
|
||||||
|
* Zivot-Andrews (ZA)
|
||||||
|
|
||||||
|
:param lags: (optional) parameter that allows user to run a series of tests for a specific lag value.
|
||||||
|
:param series: series to test
|
||||||
|
:return: dictionary of summary table for all tests and final decision on stationary vs nonstaionary
|
||||||
|
"""
|
||||||
|
# setting for ADF and KPSS tests
|
||||||
|
adf_settings = {"IC": "AIC", "store": True}
|
||||||
|
|
||||||
|
kpss_settings = {"reg_type": "c", "lags": "auto", "store": True}
|
||||||
|
|
||||||
|
arch_test_settings = {} # settings for PP, ADF GLS and ZA tests
|
||||||
|
if lags is not None:
|
||||||
|
adf_settings.update({"lags": lags, "autolag": None})
|
||||||
|
kpss_settings.update({"lags:": lags})
|
||||||
|
arch_test_settings = {"lags": lags}
|
||||||
|
# Run individual tests
|
||||||
|
adf = adf_test(series, **adf_settings) # ADF test
|
||||||
|
kpss = kpss_test(series, **kpss_settings) # KPSS test
|
||||||
|
pp = unitroot.PhillipsPerron(series, **arch_test_settings) # Phillips-Perron test
|
||||||
|
adfgls = unitroot.DFGLS(series, **arch_test_settings) # ADF using GLS test
|
||||||
|
za = unitroot.ZivotAndrews(series, **arch_test_settings) # Zivot-Andrews test
|
||||||
|
|
||||||
|
# generate output table
|
||||||
|
adf_dict = format_test_output(test_name="ADF", test_res=adf, H0_unit_root=True)
|
||||||
|
kpss_dict = format_test_output(test_name="KPSS", test_res=kpss, H0_unit_root=False)
|
||||||
|
pp_dict = format_test_output(
|
||||||
|
test_name="Philips Perron", test_res=pp, H0_unit_root=True
|
||||||
|
)
|
||||||
|
adfgls_dict = format_test_output(
|
||||||
|
test_name="ADF GLS", test_res=adfgls, H0_unit_root=True
|
||||||
|
)
|
||||||
|
za_dict = format_test_output(
|
||||||
|
test_name="Zivot-Andrews", test_res=za, H0_unit_root=True
|
||||||
|
)
|
||||||
|
|
||||||
|
test_dict = {
|
||||||
|
"ADF": adf_dict,
|
||||||
|
"KPSS": kpss_dict,
|
||||||
|
"PP": pp_dict,
|
||||||
|
"ADF GLS": adfgls_dict,
|
||||||
|
"ZA": za_dict,
|
||||||
|
}
|
||||||
|
test_sum = pd.DataFrame.from_dict(test_dict, orient="index").reset_index(drop=True)
|
||||||
|
|
||||||
|
# decision based on the majority rule
|
||||||
|
if test_sum.shape[0] > 0:
|
||||||
|
ratio = test_sum[test_sum["stationary"] == "yes"].shape[0] / test_sum.shape[0]
|
||||||
|
else:
|
||||||
|
ratio = 1 # all tests fail, assume the series is stationary
|
||||||
|
|
||||||
|
# Majority rule. If the ratio is exactly 0.5, assume the series in non-stationary.
|
||||||
|
stationary = "YES" if (ratio > 0.5) else "NO"
|
||||||
|
|
||||||
|
out = {"summary": test_sum, "stationary": stationary}
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def ts_train_test_split(df_input, n, time_colname, ts_id_colnames=None):
|
||||||
|
"""
|
||||||
|
Group data frame by time series ID and split on last n rows for each group.
|
||||||
|
|
||||||
|
:param df_input: input data frame
|
||||||
|
:param n: number of observations in the test set
|
||||||
|
:param time_colname: time column
|
||||||
|
:param ts_id_colnames: (optional) list of grain column names
|
||||||
|
:return train and test data frames
|
||||||
|
"""
|
||||||
|
if ts_id_colnames is None:
|
||||||
|
ts_id_colnames = []
|
||||||
|
ts_id_colnames_original = ts_id_colnames.copy()
|
||||||
|
if len(ts_id_colnames) == 0:
|
||||||
|
ts_id_colnames = ["Grain"]
|
||||||
|
df_input[ts_id_colnames[0]] = "dummy"
|
||||||
|
# Sort by ascending time
|
||||||
|
df_grouped = df_input.sort_values(time_colname).groupby(
|
||||||
|
ts_id_colnames, group_keys=False
|
||||||
|
)
|
||||||
|
df_head = df_grouped.apply(lambda dfg: dfg.iloc[:-n])
|
||||||
|
df_tail = df_grouped.apply(lambda dfg: dfg.iloc[-n:])
|
||||||
|
# drop group column name if it was not originally provided
|
||||||
|
if len(ts_id_colnames_original) == 0:
|
||||||
|
df_head.drop(ts_id_colnames, axis=1, inplace=True)
|
||||||
|
df_tail.drop(ts_id_colnames, axis=1, inplace=True)
|
||||||
|
return df_head, df_tail
|
||||||
|
|
||||||
|
|
||||||
|
def compute_metrics(fcst_df, metric_name=None, ts_id_colnames=None):
|
||||||
|
"""
|
||||||
|
Calculate metrics per grain.
|
||||||
|
|
||||||
|
:param fcst_df: forecast data frame. Must contain 2 columns: 'actual_level' and 'predicted_level'
|
||||||
|
:param metric_name: (optional) name of the metric to return
|
||||||
|
:param ts_id_colnames: (optional) list of grain column names
|
||||||
|
:return: dictionary of summary table for all tests and final decision on stationary vs nonstaionary
|
||||||
|
"""
|
||||||
|
if ts_id_colnames is None:
|
||||||
|
ts_id_colnames = []
|
||||||
|
if len(ts_id_colnames) == 0:
|
||||||
|
ts_id_colnames = ["TS_ID"]
|
||||||
|
fcst_df[ts_id_colnames[0]] = "dummy"
|
||||||
|
metrics_list = []
|
||||||
|
for grain, df in fcst_df.groupby(ts_id_colnames):
|
||||||
|
try:
|
||||||
|
scores = scoring.score_regression(
|
||||||
|
y_test=df["actual_level"],
|
||||||
|
y_pred=df["predicted_level"],
|
||||||
|
metrics=list(constants.Metric.SCALAR_REGRESSION_SET),
|
||||||
|
)
|
||||||
|
except BaseException:
|
||||||
|
msg = "{}: metrics calculation failed.".format(grain)
|
||||||
|
print(msg)
|
||||||
|
scores = {}
|
||||||
|
one_grain_metrics_df = pd.DataFrame(
|
||||||
|
list(scores.items()), columns=["metric_name", "metric"]
|
||||||
|
).sort_values(["metric_name"])
|
||||||
|
one_grain_metrics_df.reset_index(inplace=True, drop=True)
|
||||||
|
if len(ts_id_colnames) < 2:
|
||||||
|
one_grain_metrics_df["grain"] = ts_id_colnames[0]
|
||||||
|
else:
|
||||||
|
one_grain_metrics_df["grain"] = "|".join(list(grain))
|
||||||
|
|
||||||
|
metrics_list.append(one_grain_metrics_df)
|
||||||
|
# collect into a data frame
|
||||||
|
grain_metrics = pd.concat(metrics_list)
|
||||||
|
if metric_name is not None:
|
||||||
|
grain_metrics = grain_metrics.query("metric_name == @metric_name")
|
||||||
|
return grain_metrics
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
from azureml.core import ScriptRunConfig
|
||||||
|
|
||||||
|
|
||||||
|
def run_remote_inference(
|
||||||
|
test_experiment,
|
||||||
|
compute_target,
|
||||||
|
train_run,
|
||||||
|
test_dataset,
|
||||||
|
target_column_name,
|
||||||
|
inference_folder="./forecast",
|
||||||
|
):
|
||||||
|
# Create local directory to copy the model.pkl and forecsting_script.py files into.
|
||||||
|
# These files will be uploaded to and executed on the compute instance.
|
||||||
|
os.makedirs(inference_folder, exist_ok=True)
|
||||||
|
shutil.copy("forecasting_script.py", inference_folder)
|
||||||
|
|
||||||
|
train_run.download_file(
|
||||||
|
"outputs/model.pkl", os.path.join(inference_folder, "model.pkl")
|
||||||
|
)
|
||||||
|
|
||||||
|
inference_env = train_run.get_environment()
|
||||||
|
|
||||||
|
config = ScriptRunConfig(
|
||||||
|
source_directory=inference_folder,
|
||||||
|
script="forecasting_script.py",
|
||||||
|
arguments=[
|
||||||
|
"--target_column_name",
|
||||||
|
target_column_name,
|
||||||
|
"--test_dataset",
|
||||||
|
test_dataset.as_named_input(test_dataset.name),
|
||||||
|
],
|
||||||
|
compute_target=compute_target,
|
||||||
|
environment=inference_env,
|
||||||
|
)
|
||||||
|
|
||||||
|
run = test_experiment.submit(
|
||||||
|
config,
|
||||||
|
tags={
|
||||||
|
"training_run_id": train_run.id,
|
||||||
|
"run_algorithm": train_run.properties["run_algorithm"],
|
||||||
|
"valid_score": train_run.properties["score"],
|
||||||
|
"primary_metric": train_run.properties["primary_metric"],
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
run.log("run_algorithm", run.tags["run_algorithm"])
|
||||||
|
return run
|
||||||
@@ -80,7 +80,7 @@
|
|||||||
"from azureml.core.workspace import Workspace\n",
|
"from azureml.core.workspace import Workspace\n",
|
||||||
"from azureml.core.dataset import Dataset\n",
|
"from azureml.core.dataset import Dataset\n",
|
||||||
"from azureml.train.automl import AutoMLConfig\n",
|
"from azureml.train.automl import AutoMLConfig\n",
|
||||||
"from azureml.interpret._internal.explanation_client import ExplanationClient"
|
"from azureml.interpret import ExplanationClient"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -96,7 +96,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"print(\"This notebook was created using version 1.12.0 of the Azure ML SDK\")\n",
|
"print(\"This notebook was created using version 1.37.0 of the Azure ML SDK\")\n",
|
||||||
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -173,7 +173,7 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"automl_settings = {\n",
|
"automl_settings = {\n",
|
||||||
" \"n_cross_validations\": 3,\n",
|
" \"n_cross_validations\": 3,\n",
|
||||||
" \"primary_metric\": 'average_precision_score_weighted',\n",
|
" \"primary_metric\": 'AUC_weighted',\n",
|
||||||
" \"experiment_timeout_hours\": 0.25, # This is a time limit for testing purposes, remove it for real use cases, this will drastically limit ability to find the best model possible\n",
|
" \"experiment_timeout_hours\": 0.25, # This is a time limit for testing purposes, remove it for real use cases, this will drastically limit ability to find the best model possible\n",
|
||||||
" \"verbosity\": logging.INFO,\n",
|
" \"verbosity\": logging.INFO,\n",
|
||||||
" \"enable_stack_ensemble\": False\n",
|
" \"enable_stack_ensemble\": False\n",
|
||||||
@@ -215,15 +215,6 @@
|
|||||||
"#local_run = AutoMLRun(experiment = experiment, run_id = '<replace with your run id>')"
|
"#local_run = AutoMLRun(experiment = experiment, run_id = '<replace with your run id>')"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"local_run"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
@@ -359,7 +350,7 @@
|
|||||||
"Besides retrieving an existing model explanation for an AutoML model, you can also explain your AutoML model with different test data. The following steps will allow you to compute and visualize engineered feature importance based on your test data.\n",
|
"Besides retrieving an existing model explanation for an AutoML model, you can also explain your AutoML model with different test data. The following steps will allow you to compute and visualize engineered feature importance based on your test data.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"### Run the explanation\n",
|
"### Run the explanation\n",
|
||||||
"#### Download engineered feature importance from artifact store\n",
|
"#### Download the engineered feature importance from artifact store\n",
|
||||||
"You can use ExplanationClient to download the engineered feature explanations from the artifact store of the best_run. You can also use azure portal url to view the dash board visualization of the feature importance values of the engineered features."
|
"You can use ExplanationClient to download the engineered feature explanations from the artifact store of the best_run. You can also use azure portal url to view the dash board visualization of the feature importance values of the engineered features."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -375,6 +366,25 @@
|
|||||||
"print(\"You can visualize the engineered explanations under the 'Explanations (preview)' tab in the AutoML run at:-\\n\" + best_run.get_portal_url())"
|
"print(\"You can visualize the engineered explanations under the 'Explanations (preview)' tab in the AutoML run at:-\\n\" + best_run.get_portal_url())"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Download the raw feature importance from artifact store\n",
|
||||||
|
"You can use ExplanationClient to download the raw feature explanations from the artifact store of the best_run. You can also use azure portal url to view the dash board visualization of the feature importance values of the raw features."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"raw_explanations = client.download_model_explanation(raw=True)\n",
|
||||||
|
"print(raw_explanations.get_feature_importance_dict())\n",
|
||||||
|
"print(\"You can visualize the raw explanations under the 'Explanations (preview)' tab in the AutoML run at:-\\n\" + best_run.get_portal_url())"
|
||||||
|
]
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
@@ -426,7 +436,8 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"automl_explainer_setup_obj = automl_setup_model_explanations(fitted_model, X=X_train, \n",
|
"automl_explainer_setup_obj = automl_setup_model_explanations(fitted_model, X=X_train, \n",
|
||||||
" X_test=X_test, y=y_train, \n",
|
" X_test=X_test, y=y_train, \n",
|
||||||
" task='classification')"
|
" task='classification',\n",
|
||||||
|
" automl_run=automl_run)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -443,11 +454,10 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from interpret.ext.glassbox import LGBMExplainableModel\n",
|
|
||||||
"from azureml.interpret.mimic_wrapper import MimicWrapper\n",
|
"from azureml.interpret.mimic_wrapper import MimicWrapper\n",
|
||||||
"explainer = MimicWrapper(ws, automl_explainer_setup_obj.automl_estimator,\n",
|
"explainer = MimicWrapper(ws, automl_explainer_setup_obj.automl_estimator,\n",
|
||||||
" explainable_model=automl_explainer_setup_obj.surrogate_model, \n",
|
" explainable_model=automl_explainer_setup_obj.surrogate_model, \n",
|
||||||
" init_dataset=automl_explainer_setup_obj.X_transform, run=automl_run,\n",
|
" init_dataset=automl_explainer_setup_obj.X_transform, run=automl_explainer_setup_obj.automl_run,\n",
|
||||||
" features=automl_explainer_setup_obj.engineered_feature_names, \n",
|
" features=automl_explainer_setup_obj.engineered_feature_names, \n",
|
||||||
" feature_maps=[automl_explainer_setup_obj.feature_map],\n",
|
" feature_maps=[automl_explainer_setup_obj.feature_map],\n",
|
||||||
" classes=automl_explainer_setup_obj.classes,\n",
|
" classes=automl_explainer_setup_obj.classes,\n",
|
||||||
@@ -474,6 +484,29 @@
|
|||||||
"print(\"You can visualize the engineered explanations under the 'Explanations (preview)' tab in the AutoML run at:-\\n\" + automl_run.get_portal_url())"
|
"print(\"You can visualize the engineered explanations under the 'Explanations (preview)' tab in the AutoML run at:-\\n\" + automl_run.get_portal_url())"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Use Mimic Explainer for computing and visualizing raw feature importance\n",
|
||||||
|
"The explain() method in MimicWrapper can be called with the transformed test samples to get the feature importance for the original features in your data. You can also use azure portal url to view the dash board visualization of the feature importance values of the original/raw features."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Compute the raw explanations\n",
|
||||||
|
"raw_explanations = explainer.explain(['local', 'global'], get_raw=True,\n",
|
||||||
|
" raw_feature_names=automl_explainer_setup_obj.raw_feature_names,\n",
|
||||||
|
" eval_dataset=automl_explainer_setup_obj.X_test_transform,\n",
|
||||||
|
" raw_eval_dataset=automl_explainer_setup_obj.X_test_raw)\n",
|
||||||
|
"print(raw_explanations.get_feature_importance_dict())\n",
|
||||||
|
"print(\"You can visualize the raw explanations under the 'Explanations (preview)' tab in the AutoML run at:-\\n\" + automl_run.get_portal_url())"
|
||||||
|
]
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
@@ -562,16 +595,10 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"%%writefile score.py\n",
|
"%%writefile score.py\n",
|
||||||
"import numpy as np\n",
|
|
||||||
"import pandas as pd\n",
|
|
||||||
"import os\n",
|
|
||||||
"import pickle\n",
|
|
||||||
"import azureml.train.automl\n",
|
|
||||||
"import azureml.interpret\n",
|
|
||||||
"from azureml.train.automl.runtime.automl_explain_utilities import AutoMLExplainerSetupClass, \\\n",
|
|
||||||
" automl_setup_model_explanations\n",
|
|
||||||
"import joblib\n",
|
"import joblib\n",
|
||||||
|
"import pandas as pd\n",
|
||||||
"from azureml.core.model import Model\n",
|
"from azureml.core.model import Model\n",
|
||||||
|
"from azureml.train.automl.runtime.automl_explain_utilities import automl_setup_model_explanations\n",
|
||||||
"\n",
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"def init():\n",
|
"def init():\n",
|
||||||
@@ -595,10 +622,13 @@
|
|||||||
" automl_explainer_setup_obj = automl_setup_model_explanations(automl_model,\n",
|
" automl_explainer_setup_obj = automl_setup_model_explanations(automl_model,\n",
|
||||||
" X_test=data, task='classification')\n",
|
" X_test=data, task='classification')\n",
|
||||||
" # Retrieve model explanations for engineered explanations\n",
|
" # Retrieve model explanations for engineered explanations\n",
|
||||||
" engineered_local_importance_values = scoring_explainer.explain(automl_explainer_setup_obj.X_test_transform) \n",
|
" engineered_local_importance_values = scoring_explainer.explain(automl_explainer_setup_obj.X_test_transform)\n",
|
||||||
|
" # Retrieve model explanations for raw explanations\n",
|
||||||
|
" raw_local_importance_values = scoring_explainer.explain(automl_explainer_setup_obj.X_test_transform, get_raw=True)\n",
|
||||||
" # You can return any data type as long as it is JSON-serializable\n",
|
" # You can return any data type as long as it is JSON-serializable\n",
|
||||||
" return {'predictions': predictions.tolist(),\n",
|
" return {'predictions': predictions.tolist(),\n",
|
||||||
" 'engineered_local_importance_values': engineered_local_importance_values}\n"
|
" 'engineered_local_importance_values': engineered_local_importance_values,\n",
|
||||||
|
" 'raw_local_importance_values': raw_local_importance_values}\n"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -731,7 +761,9 @@
|
|||||||
"# Print the predicted value\n",
|
"# Print the predicted value\n",
|
||||||
"print('predictions:\\n{}\\n'.format(output['predictions']))\n",
|
"print('predictions:\\n{}\\n'.format(output['predictions']))\n",
|
||||||
"# Print the engineered feature importances for the predicted value\n",
|
"# Print the engineered feature importances for the predicted value\n",
|
||||||
"print('engineered_local_importance_values:\\n{}\\n'.format(output['engineered_local_importance_values']))"
|
"print('engineered_local_importance_values:\\n{}\\n'.format(output['engineered_local_importance_values']))\n",
|
||||||
|
"# Print the raw feature importances for the predicted value\n",
|
||||||
|
"print('raw_local_importance_values:\\n{}\\n'.format(output['raw_local_importance_values']))\n"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -779,7 +811,7 @@
|
|||||||
"metadata": {
|
"metadata": {
|
||||||
"authors": [
|
"authors": [
|
||||||
{
|
{
|
||||||
"name": "anumamah"
|
"name": "ratanase"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"category": "tutorial",
|
"category": "tutorial",
|
||||||
|
|||||||
@@ -42,8 +42,6 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"If you are using an Azure Machine Learning Compute Instance, you are all set. Otherwise, go through the [configuration](../../../configuration.ipynb) notebook first if you haven't already to establish your connection to the AzureML Workspace. \n",
|
"If you are using an Azure Machine Learning Compute Instance, you are all set. Otherwise, go through the [configuration](../../../configuration.ipynb) notebook first if you haven't already to establish your connection to the AzureML Workspace. \n",
|
||||||
"\n",
|
"\n",
|
||||||
"An Enterprise workspace is required for this notebook. To learn more about creating an Enterprise workspace or upgrading to an Enterprise workspace from the Azure portal, please visit our [Workspace page.](https://docs.microsoft.com/azure/machine-learning/service/concept-workspace#upgrade) \n",
|
|
||||||
"\n",
|
|
||||||
"In this notebook you will learn how to:\n",
|
"In this notebook you will learn how to:\n",
|
||||||
"1. Create an `Experiment` in an existing `Workspace`.\n",
|
"1. Create an `Experiment` in an existing `Workspace`.\n",
|
||||||
"2. Instantiating AutoMLConfig with FeaturizationConfig for customization\n",
|
"2. Instantiating AutoMLConfig with FeaturizationConfig for customization\n",
|
||||||
@@ -70,6 +68,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
|
"import json\n",
|
||||||
"import logging\n",
|
"import logging\n",
|
||||||
"\n",
|
"\n",
|
||||||
"from matplotlib import pyplot as plt\n",
|
"from matplotlib import pyplot as plt\n",
|
||||||
@@ -79,7 +78,6 @@
|
|||||||
"import azureml.core\n",
|
"import azureml.core\n",
|
||||||
"from azureml.core.experiment import Experiment\n",
|
"from azureml.core.experiment import Experiment\n",
|
||||||
"from azureml.core.workspace import Workspace\n",
|
"from azureml.core.workspace import Workspace\n",
|
||||||
"import azureml.dataprep as dprep\n",
|
|
||||||
"from azureml.automl.core.featurization import FeaturizationConfig\n",
|
"from azureml.automl.core.featurization import FeaturizationConfig\n",
|
||||||
"from azureml.train.automl import AutoMLConfig\n",
|
"from azureml.train.automl import AutoMLConfig\n",
|
||||||
"from azureml.core.dataset import Dataset"
|
"from azureml.core.dataset import Dataset"
|
||||||
@@ -98,7 +96,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"print(\"This notebook was created using version 1.12.0 of the Azure ML SDK\")\n",
|
"print(\"This notebook was created using version 1.37.0 of the Azure ML SDK\")\n",
|
||||||
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -132,6 +130,8 @@
|
|||||||
"### Create or Attach existing AmlCompute\n",
|
"### Create or Attach existing AmlCompute\n",
|
||||||
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for your AutoML run. In this tutorial, you create `AmlCompute` as your training compute resource.\n",
|
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for your AutoML run. In this tutorial, you create `AmlCompute` as your training compute resource.\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"> 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.\n",
|
||||||
|
"\n",
|
||||||
"**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.\n",
|
"**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.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"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](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
"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](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
||||||
@@ -154,7 +154,7 @@
|
|||||||
" compute_target = ComputeTarget(workspace=ws, name=amlcompute_cluster_name)\n",
|
" compute_target = ComputeTarget(workspace=ws, name=amlcompute_cluster_name)\n",
|
||||||
" print('Found existing cluster, use it.')\n",
|
" print('Found existing cluster, use it.')\n",
|
||||||
"except ComputeTargetException:\n",
|
"except ComputeTargetException:\n",
|
||||||
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_D2_V2',\n",
|
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_DS12_V2',\n",
|
||||||
" max_nodes=4)\n",
|
" max_nodes=4)\n",
|
||||||
" compute_target = ComputeTarget.create(ws, amlcompute_cluster_name, compute_config)\n",
|
" compute_target = ComputeTarget.create(ws, amlcompute_cluster_name, compute_config)\n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -223,9 +223,8 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"## Customization\n",
|
"## Customization\n",
|
||||||
"\n",
|
"\n",
|
||||||
"This step requires an Enterprise workspace to gain access to this feature. To learn more about creating an Enterprise workspace or upgrading to an Enterprise workspace from the Azure portal, please visit our [Workspace page.](https://docs.microsoft.com/azure/machine-learning/service/concept-workspace#upgrade). \n",
|
|
||||||
"\n",
|
|
||||||
"Supported customization includes:\n",
|
"Supported customization includes:\n",
|
||||||
|
"\n",
|
||||||
"1. Column purpose update: Override feature type for the specified column.\n",
|
"1. Column purpose update: Override feature type for the specified column.\n",
|
||||||
"2. Transformer parameter update: Update parameters for the specified transformer. Currently supports Imputer and HashOneHotEncoder.\n",
|
"2. Transformer parameter update: Update parameters for the specified transformer. Currently supports Imputer and HashOneHotEncoder.\n",
|
||||||
"3. Drop columns: Columns to drop from being featurized.\n",
|
"3. Drop columns: Columns to drop from being featurized.\n",
|
||||||
@@ -308,15 +307,6 @@
|
|||||||
"remote_run = experiment.submit(automl_config, show_output = False)"
|
"remote_run = experiment.submit(automl_config, show_output = False)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"remote_run"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
@@ -350,16 +340,8 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"best_run, fitted_model = remote_run.get_output()"
|
"# Retrieve the best Run object\n",
|
||||||
]
|
"best_run = remote_run.get_best_child()"
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"best_run_customized, fitted_model_customized = remote_run.get_output()"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -368,7 +350,7 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"## Transparency\n",
|
"## Transparency\n",
|
||||||
"\n",
|
"\n",
|
||||||
"View updated featurization summary"
|
"View featurization summary for the best model - to study how different features were transformed. This is stored as a JSON file in the outputs directory for the run."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -377,41 +359,14 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"custom_featurizer = fitted_model_customized.named_steps['datatransformer']"
|
"# Download the featuurization summary JSON file locally\n",
|
||||||
]
|
"best_run.download_file(\"outputs/featurization_summary.json\", \"featurization_summary.json\")\n",
|
||||||
},
|
"\n",
|
||||||
{
|
"# Render the JSON as a pandas DataFrame\n",
|
||||||
"cell_type": "code",
|
"with open(\"featurization_summary.json\", \"r\") as f:\n",
|
||||||
"execution_count": null,
|
" records = json.load(f)\n",
|
||||||
"metadata": {},
|
"\n",
|
||||||
"outputs": [],
|
"pd.DataFrame.from_records(records)"
|
||||||
"source": [
|
|
||||||
"custom_featurizer.get_featurization_summary()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"is_user_friendly=False allows for more detailed summary for transforms being applied"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"custom_featurizer.get_featurization_summary(is_user_friendly=False)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"custom_featurizer.get_stats_feature_type_summary()"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -447,12 +402,11 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Explanations\n",
|
"## Explanations\n",
|
||||||
"This step requires an Enterprise workspace to gain access to this feature. To learn more about creating an Enterprise workspace or upgrading to an Enterprise workspace from the Azure portal, please visit our [Workspace page.](https://docs.microsoft.com/azure/machine-learning/service/concept-workspace#upgrade). \n",
|
|
||||||
"This section will walk you through the workflow to compute model explanations for an AutoML model on your remote compute.\n",
|
"This section will walk you through the workflow to compute model explanations for an AutoML model on your remote compute.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"### Retrieve any AutoML Model for explanations\n",
|
"### Retrieve any AutoML Model for explanations\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Below we select the some AutoML pipeline from our iterations. The `get_output` method returns the a AutoML run and the fitted model for the last invocation. Overloads on `get_output` allow you to retrieve the best run and fitted model for *any* logged metric or for a particular *iteration*."
|
"Below we select an AutoML pipeline from our iterations. The `get_output` method returns the a AutoML run and the fitted model for the last invocation. Overloads on `get_output` allow you to retrieve the best run and fitted model for any logged `metric` or for a particular `iteration`."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -461,7 +415,8 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"automl_run, fitted_model = remote_run.get_output(metric='r2_score')"
|
"#automl_run, fitted_model = remote_run.get_output(metric='r2_score')\n",
|
||||||
|
"automl_run, fitted_model = remote_run.get_output(iteration=2)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -551,8 +506,6 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from azureml.core.runconfig import RunConfiguration\n",
|
"from azureml.core.runconfig import RunConfiguration\n",
|
||||||
"from azureml.core.conda_dependencies import CondaDependencies\n",
|
|
||||||
"import pkg_resources\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
"# create a new RunConfig object\n",
|
"# create a new RunConfig object\n",
|
||||||
"conda_run_config = RunConfiguration(framework=\"python\")\n",
|
"conda_run_config = RunConfiguration(framework=\"python\")\n",
|
||||||
@@ -625,7 +578,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from azureml.interpret._internal.explanation_client import ExplanationClient\n",
|
"from azureml.interpret import ExplanationClient\n",
|
||||||
"client = ExplanationClient.from_run(automl_run)\n",
|
"client = ExplanationClient.from_run(automl_run)\n",
|
||||||
"engineered_explanations = client.download_model_explanation(raw=False, comment='engineered explanations')\n",
|
"engineered_explanations = client.download_model_explanation(raw=False, comment='engineered explanations')\n",
|
||||||
"print(engineered_explanations.get_feature_importance_dict())\n",
|
"print(engineered_explanations.get_feature_importance_dict())\n",
|
||||||
@@ -655,7 +608,7 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Operationailze\n",
|
"## Operationalize\n",
|
||||||
"In this section we will show how you can operationalize an AutoML model and the explainer which was used to compute the explanations in the previous section.\n",
|
"In this section we will show how you can operationalize an AutoML model and the explainer which was used to compute the explanations in the previous section.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"### Register the AutoML model and the scoring explainer\n",
|
"### Register the AutoML model and the scoring explainer\n",
|
||||||
@@ -730,14 +683,13 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from azureml.core.webservice import Webservice\n",
|
|
||||||
"from azureml.core.model import InferenceConfig\n",
|
"from azureml.core.model import InferenceConfig\n",
|
||||||
"from azureml.core.webservice import AciWebservice\n",
|
"from azureml.core.webservice import AciWebservice\n",
|
||||||
"from azureml.core.model import Model\n",
|
"from azureml.core.model import Model\n",
|
||||||
"from azureml.core.environment import Environment\n",
|
"from azureml.core.environment import Environment\n",
|
||||||
"\n",
|
"\n",
|
||||||
"aciconfig = AciWebservice.deploy_configuration(cpu_cores=1, \n",
|
"aciconfig = AciWebservice.deploy_configuration(cpu_cores=2, \n",
|
||||||
" memory_gb=1, \n",
|
" memory_gb=2, \n",
|
||||||
" tags={\"data\": \"Machine Data\", \n",
|
" tags={\"data\": \"Machine Data\", \n",
|
||||||
" \"method\" : \"local_explanation\"}, \n",
|
" \"method\" : \"local_explanation\"}, \n",
|
||||||
" description='Get local explanations for Machine test data')\n",
|
" description='Get local explanations for Machine test data')\n",
|
||||||
@@ -905,7 +857,7 @@
|
|||||||
"metadata": {
|
"metadata": {
|
||||||
"authors": [
|
"authors": [
|
||||||
{
|
{
|
||||||
"name": "anumamah"
|
"name": "anshirga"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"categories": [
|
"categories": [
|
||||||
|
|||||||
@@ -1,14 +1,7 @@
|
|||||||
import json
|
|
||||||
import numpy as np
|
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
import os
|
|
||||||
import pickle
|
|
||||||
import azureml.train.automl
|
|
||||||
import azureml.interpret
|
|
||||||
from azureml.train.automl.runtime.automl_explain_utilities import AutoMLExplainerSetupClass, \
|
|
||||||
automl_setup_model_explanations
|
|
||||||
import joblib
|
import joblib
|
||||||
from azureml.core.model import Model
|
from azureml.core.model import Model
|
||||||
|
from azureml.train.automl.runtime.automl_explain_utilities import automl_setup_model_explanations
|
||||||
|
|
||||||
|
|
||||||
def init():
|
def init():
|
||||||
|
|||||||
@@ -1,17 +1,17 @@
|
|||||||
# Copyright (c) Microsoft. All rights reserved.
|
# Copyright (c) Microsoft. All rights reserved.
|
||||||
# Licensed under the MIT license.
|
# Licensed under the MIT license.
|
||||||
import os
|
import os
|
||||||
|
import joblib
|
||||||
|
|
||||||
from azureml.core.run import Run
|
from interpret.ext.glassbox import LGBMExplainableModel
|
||||||
|
from azureml.automl.core.shared.constants import MODEL_PATH
|
||||||
from azureml.core.experiment import Experiment
|
from azureml.core.experiment import Experiment
|
||||||
from azureml.core.dataset import Dataset
|
from azureml.core.dataset import Dataset
|
||||||
from azureml.train.automl.runtime.automl_explain_utilities import AutoMLExplainerSetupClass, \
|
from azureml.core.run import Run
|
||||||
automl_setup_model_explanations, automl_check_model_if_explainable
|
|
||||||
from interpret.ext.glassbox import LGBMExplainableModel
|
|
||||||
from azureml.interpret.mimic_wrapper import MimicWrapper
|
from azureml.interpret.mimic_wrapper import MimicWrapper
|
||||||
from automl.client.core.common.constants import MODEL_PATH
|
|
||||||
from azureml.interpret.scoring.scoring_explainer import TreeScoringExplainer
|
from azureml.interpret.scoring.scoring_explainer import TreeScoringExplainer
|
||||||
import joblib
|
from azureml.train.automl.runtime.automl_explain_utilities import automl_setup_model_explanations, \
|
||||||
|
automl_check_model_if_explainable
|
||||||
|
|
||||||
|
|
||||||
OUTPUT_DIR = './outputs/'
|
OUTPUT_DIR = './outputs/'
|
||||||
@@ -27,7 +27,7 @@ automl_run = Run(experiment=experiment, run_id='<<run_id>>')
|
|||||||
|
|
||||||
# Check if this AutoML model is explainable
|
# Check if this AutoML model is explainable
|
||||||
if not automl_check_model_if_explainable(automl_run):
|
if not automl_check_model_if_explainable(automl_run):
|
||||||
raise Exception("Model explanations is currently not supported for " + automl_run.get_properties().get(
|
raise Exception("Model explanations are currently not supported for " + automl_run.get_properties().get(
|
||||||
'run_algorithm'))
|
'run_algorithm'))
|
||||||
|
|
||||||
# Download the best model from the artifact store
|
# Download the best model from the artifact store
|
||||||
@@ -38,23 +38,25 @@ fitted_model = joblib.load('model.pkl')
|
|||||||
|
|
||||||
# Get the train dataset from the workspace
|
# Get the train dataset from the workspace
|
||||||
train_dataset = Dataset.get_by_name(workspace=ws, name='<<train_dataset_name>>')
|
train_dataset = Dataset.get_by_name(workspace=ws, name='<<train_dataset_name>>')
|
||||||
# Drop the lablled column to get the training set.
|
# Drop the labeled column to get the training set.
|
||||||
X_train = train_dataset.drop_columns(columns=['<<target_column_name>>'])
|
X_train = train_dataset.drop_columns(columns=['<<target_column_name>>'])
|
||||||
y_train = train_dataset.keep_columns(columns=['<<target_column_name>>'], validate=True)
|
y_train = train_dataset.keep_columns(columns=['<<target_column_name>>'], validate=True)
|
||||||
|
|
||||||
# Get the train dataset from the workspace
|
# Get the test dataset from the workspace
|
||||||
test_dataset = Dataset.get_by_name(workspace=ws, name='<<test_dataset_name>>')
|
test_dataset = Dataset.get_by_name(workspace=ws, name='<<test_dataset_name>>')
|
||||||
# Drop the lablled column to get the testing set.
|
# Drop the labeled column to get the testing set.
|
||||||
X_test = test_dataset.drop_columns(columns=['<<target_column_name>>'])
|
X_test = test_dataset.drop_columns(columns=['<<target_column_name>>'])
|
||||||
|
|
||||||
# Setup the class for explaining the AtuoML models
|
# Setup the class for explaining the AutoML models
|
||||||
automl_explainer_setup_obj = automl_setup_model_explanations(fitted_model, '<<task>>',
|
automl_explainer_setup_obj = automl_setup_model_explanations(fitted_model, '<<task>>',
|
||||||
X=X_train, X_test=X_test,
|
X=X_train, X_test=X_test,
|
||||||
y=y_train)
|
y=y_train,
|
||||||
|
automl_run=automl_run)
|
||||||
|
|
||||||
# Initialize the Mimic Explainer
|
# Initialize the Mimic Explainer
|
||||||
explainer = MimicWrapper(ws, automl_explainer_setup_obj.automl_estimator, LGBMExplainableModel,
|
explainer = MimicWrapper(ws, automl_explainer_setup_obj.automl_estimator, LGBMExplainableModel,
|
||||||
init_dataset=automl_explainer_setup_obj.X_transform, run=automl_run,
|
init_dataset=automl_explainer_setup_obj.X_transform,
|
||||||
|
run=automl_explainer_setup_obj.automl_run,
|
||||||
features=automl_explainer_setup_obj.engineered_feature_names,
|
features=automl_explainer_setup_obj.engineered_feature_names,
|
||||||
feature_maps=[automl_explainer_setup_obj.feature_map],
|
feature_maps=[automl_explainer_setup_obj.feature_map],
|
||||||
classes=automl_explainer_setup_obj.classes)
|
classes=automl_explainer_setup_obj.classes)
|
||||||
@@ -66,7 +68,8 @@ engineered_explanations = explainer.explain(['local', 'global'], tag='engineered
|
|||||||
# Compute the raw explanations
|
# Compute the raw explanations
|
||||||
raw_explanations = explainer.explain(['local', 'global'], get_raw=True, tag='raw explanations',
|
raw_explanations = explainer.explain(['local', 'global'], get_raw=True, tag='raw explanations',
|
||||||
raw_feature_names=automl_explainer_setup_obj.raw_feature_names,
|
raw_feature_names=automl_explainer_setup_obj.raw_feature_names,
|
||||||
eval_dataset=automl_explainer_setup_obj.X_test_transform)
|
eval_dataset=automl_explainer_setup_obj.X_test_transform,
|
||||||
|
raw_eval_dataset=automl_explainer_setup_obj.X_test_raw)
|
||||||
|
|
||||||
print("Engineered and raw explanations computed successfully")
|
print("Engineered and raw explanations computed successfully")
|
||||||
|
|
||||||
|
|||||||
@@ -92,7 +92,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"print(\"This notebook was created using version 1.12.0 of the Azure ML SDK\")\n",
|
"print(\"This notebook was created using version 1.37.0 of the Azure ML SDK\")\n",
|
||||||
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -145,7 +145,7 @@
|
|||||||
" compute_target = ComputeTarget(workspace=ws, name=cpu_cluster_name)\n",
|
" compute_target = ComputeTarget(workspace=ws, name=cpu_cluster_name)\n",
|
||||||
" print('Found existing cluster, use it.')\n",
|
" print('Found existing cluster, use it.')\n",
|
||||||
"except ComputeTargetException:\n",
|
"except ComputeTargetException:\n",
|
||||||
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_D2_V2',\n",
|
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_DS12_V2',\n",
|
||||||
" max_nodes=4)\n",
|
" max_nodes=4)\n",
|
||||||
" compute_target = ComputeTarget.create(ws, cpu_cluster_name, compute_config)\n",
|
" compute_target = ComputeTarget.create(ws, cpu_cluster_name, compute_config)\n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -213,7 +213,7 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"automl_settings = {\n",
|
"automl_settings = {\n",
|
||||||
" \"n_cross_validations\": 3,\n",
|
" \"n_cross_validations\": 3,\n",
|
||||||
" \"primary_metric\": 'r2_score',\n",
|
" \"primary_metric\": 'normalized_root_mean_squared_error',\n",
|
||||||
" \"enable_early_stopping\": True, \n",
|
" \"enable_early_stopping\": True, \n",
|
||||||
" \"experiment_timeout_hours\": 0.3, #for real scenarios we reccommend a timeout of at least one hour \n",
|
" \"experiment_timeout_hours\": 0.3, #for real scenarios we reccommend a timeout of at least one hour \n",
|
||||||
" \"max_concurrent_iterations\": 4,\n",
|
" \"max_concurrent_iterations\": 4,\n",
|
||||||
@@ -256,15 +256,6 @@
|
|||||||
"#remote_run = AutoMLRun(experiment = experiment, run_id = '<replace with your run id>')"
|
"#remote_run = AutoMLRun(experiment = experiment, run_id = '<replace with your run id>')"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"remote_run"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
@@ -375,18 +366,12 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"# preview the first 3 rows of the dataset\n",
|
"y_test = test_data.keep_columns('ERP').to_pandas_dataframe()\n",
|
||||||
"\n",
|
"test_data = test_data.drop_columns('ERP').to_pandas_dataframe()\n",
|
||||||
"test_data = test_data.to_pandas_dataframe()\n",
|
|
||||||
"y_test = test_data['ERP'].fillna(0)\n",
|
|
||||||
"test_data = test_data.drop('ERP', 1)\n",
|
|
||||||
"test_data = test_data.fillna(0)\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"train_data = train_data.to_pandas_dataframe()\n",
|
"y_train = train_data.keep_columns('ERP').to_pandas_dataframe()\n",
|
||||||
"y_train = train_data['ERP'].fillna(0)\n",
|
"train_data = train_data.drop_columns('ERP').to_pandas_dataframe()\n"
|
||||||
"train_data = train_data.drop('ERP', 1)\n",
|
|
||||||
"train_data = train_data.fillna(0)\n"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -396,10 +381,10 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"y_pred_train = fitted_model.predict(train_data)\n",
|
"y_pred_train = fitted_model.predict(train_data)\n",
|
||||||
"y_residual_train = y_train - y_pred_train\n",
|
"y_residual_train = y_train.values - y_pred_train\n",
|
||||||
"\n",
|
"\n",
|
||||||
"y_pred_test = fitted_model.predict(test_data)\n",
|
"y_pred_test = fitted_model.predict(test_data)\n",
|
||||||
"y_residual_test = y_test - y_pred_test"
|
"y_residual_test = y_test.values - y_pred_test"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -462,7 +447,7 @@
|
|||||||
"metadata": {
|
"metadata": {
|
||||||
"authors": [
|
"authors": [
|
||||||
{
|
{
|
||||||
"name": "rakellam"
|
"name": "ratanase"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"categories": [
|
"categories": [
|
||||||
|
|||||||
@@ -1,33 +0,0 @@
|
|||||||
Azure Databricks is a managed Spark offering on Azure and customers already use it for advanced analytics. It provides a collaborative Notebook based environment with CPU or GPU based compute cluster.
|
|
||||||
|
|
||||||
In this section, you will find sample notebooks on how to use Azure Machine Learning SDK with Azure Databricks. You can train a model using Spark MLlib and then deploy the model to ACI/AKS from within Azure Databricks. You can also use Automated ML capability (**public preview**) of Azure ML SDK with Azure Databricks.
|
|
||||||
|
|
||||||
- Customers who use Azure Databricks for advanced analytics can now use the same cluster to run experiments with or without automated machine learning.
|
|
||||||
- You can keep the data within the same cluster.
|
|
||||||
- You can leverage the local worker nodes with autoscale and auto termination capabilities.
|
|
||||||
- You can use multiple cores of your Azure Databricks cluster to perform simultenous training.
|
|
||||||
- You can further tune the model generated by automated machine learning if you chose to.
|
|
||||||
- Every run (including the best run) is available as a pipeline, which you can tune further if needed.
|
|
||||||
- The model trained using Azure Databricks can be registered in Azure ML SDK workspace and then deployed to Azure managed compute (ACI or AKS) using the Azure Machine learning SDK.
|
|
||||||
|
|
||||||
Please follow our [Azure doc](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-configure-environment#azure-databricks) to install the sdk in your Azure Databricks cluster before trying any of the sample notebooks.
|
|
||||||
|
|
||||||
**Single file** -
|
|
||||||
The following archive contains all the sample notebooks. You can the run notebooks after importing [DBC](Databricks_AMLSDK_1-4_6.dbc) in your Databricks workspace instead of downloading individually.
|
|
||||||
|
|
||||||
Notebooks 1-4 have to be run sequentially & are related to Income prediction experiment based on this [dataset](https://archive.ics.uci.edu/ml/datasets/adult) and demonstrate how to data prep, train and operationalize a Spark ML model with Azure ML Python SDK from within Azure Databricks.
|
|
||||||
|
|
||||||
Notebook 6 is an Automated ML sample notebook for Classification.
|
|
||||||
|
|
||||||
Learn more about [how to use Azure Databricks as a development environment](https://docs.microsoft.com/azure/machine-learning/service/how-to-configure-environment#azure-databricks) for Azure Machine Learning service.
|
|
||||||
|
|
||||||
**Databricks as a Compute Target from AML Pipelines**
|
|
||||||
You can use Azure Databricks as a compute target from [Azure Machine Learning Pipelines](https://docs.microsoft.com/en-us/azure/machine-learning/service/concept-ml-pipelines). Take a look at this notebook for details: [aml-pipelines-use-databricks-as-compute-target.ipynb](https://github.com/Azure/MachineLearningNotebooks/tree/master/how-to-use-azureml/azure-databricks/databricks-as-remote-compute-target/aml-pipelines-use-databricks-as-compute-target.ipynb).
|
|
||||||
|
|
||||||
For more on SDK concepts, please refer to [notebooks](https://github.com/Azure/MachineLearningNotebooks).
|
|
||||||
|
|
||||||
**Please let us know your feedback.**
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||

|
|
||||||
@@ -1,373 +0,0 @@
|
|||||||
{
|
|
||||||
"cells": [
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Azure ML & Azure Databricks notebooks by Parashar Shah.\n",
|
|
||||||
"\n",
|
|
||||||
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
|
||||||
"\n",
|
|
||||||
"Licensed under the MIT License."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#Model Building"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"import os\n",
|
|
||||||
"import pprint\n",
|
|
||||||
"import numpy as np\n",
|
|
||||||
"\n",
|
|
||||||
"from pyspark.ml import Pipeline, PipelineModel\n",
|
|
||||||
"from pyspark.ml.feature import OneHotEncoder, StringIndexer, VectorAssembler\n",
|
|
||||||
"from pyspark.ml.classification import LogisticRegression\n",
|
|
||||||
"from pyspark.ml.evaluation import BinaryClassificationEvaluator\n",
|
|
||||||
"from pyspark.ml.tuning import CrossValidator, ParamGridBuilder"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"import azureml.core\n",
|
|
||||||
"\n",
|
|
||||||
"# Check core SDK version number\n",
|
|
||||||
"print(\"SDK version:\", azureml.core.VERSION)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# Set auth to be used by workspace related APIs.\n",
|
|
||||||
"# For automation or CI/CD ServicePrincipalAuthentication can be used.\n",
|
|
||||||
"# https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.authentication.serviceprincipalauthentication?view=azure-ml-py\n",
|
|
||||||
"auth = None"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# import the Workspace class and check the azureml SDK version\n",
|
|
||||||
"from azureml.core import Workspace\n",
|
|
||||||
"\n",
|
|
||||||
"ws = Workspace.from_config(auth = auth)\n",
|
|
||||||
"print('Workspace name: ' + ws.name, \n",
|
|
||||||
" 'Azure region: ' + ws.location, \n",
|
|
||||||
" 'Subscription id: ' + ws.subscription_id, \n",
|
|
||||||
" 'Resource group: ' + ws.resource_group, sep = '\\n')"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"#get the train and test datasets\n",
|
|
||||||
"train_data_path = \"AdultCensusIncomeTrain\"\n",
|
|
||||||
"test_data_path = \"AdultCensusIncomeTest\"\n",
|
|
||||||
"\n",
|
|
||||||
"train = spark.read.parquet(train_data_path)\n",
|
|
||||||
"test = spark.read.parquet(test_data_path)\n",
|
|
||||||
"\n",
|
|
||||||
"print(\"train: ({}, {})\".format(train.count(), len(train.columns)))\n",
|
|
||||||
"print(\"test: ({}, {})\".format(test.count(), len(test.columns)))\n",
|
|
||||||
"\n",
|
|
||||||
"train.printSchema()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#Define Model"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"label = \"income\"\n",
|
|
||||||
"dtypes = dict(train.dtypes)\n",
|
|
||||||
"dtypes.pop(label)\n",
|
|
||||||
"\n",
|
|
||||||
"si_xvars = []\n",
|
|
||||||
"ohe_xvars = []\n",
|
|
||||||
"featureCols = []\n",
|
|
||||||
"for idx,key in enumerate(dtypes):\n",
|
|
||||||
" if dtypes[key] == \"string\":\n",
|
|
||||||
" featureCol = \"-\".join([key, \"encoded\"])\n",
|
|
||||||
" featureCols.append(featureCol)\n",
|
|
||||||
" \n",
|
|
||||||
" tmpCol = \"-\".join([key, \"tmp\"])\n",
|
|
||||||
" # string-index and one-hot encode the string column\n",
|
|
||||||
" #https://spark.apache.org/docs/2.3.0/api/java/org/apache/spark/ml/feature/StringIndexer.html\n",
|
|
||||||
" #handleInvalid: Param for how to handle invalid data (unseen labels or NULL values). \n",
|
|
||||||
" #Options are 'skip' (filter out rows with invalid data), 'error' (throw an error), \n",
|
|
||||||
" #or 'keep' (put invalid data in a special additional bucket, at index numLabels). Default: \"error\"\n",
|
|
||||||
" si_xvars.append(StringIndexer(inputCol=key, outputCol=tmpCol, handleInvalid=\"skip\"))\n",
|
|
||||||
" ohe_xvars.append(OneHotEncoder(inputCol=tmpCol, outputCol=featureCol))\n",
|
|
||||||
" else:\n",
|
|
||||||
" featureCols.append(key)\n",
|
|
||||||
"\n",
|
|
||||||
"# string-index the label column into a column named \"label\"\n",
|
|
||||||
"si_label = StringIndexer(inputCol=label, outputCol='label')\n",
|
|
||||||
"\n",
|
|
||||||
"# assemble the encoded feature columns in to a column named \"features\"\n",
|
|
||||||
"assembler = VectorAssembler(inputCols=featureCols, outputCol=\"features\")"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.core.run import Run\n",
|
|
||||||
"from azureml.core.experiment import Experiment\n",
|
|
||||||
"import numpy as np\n",
|
|
||||||
"import os\n",
|
|
||||||
"import shutil\n",
|
|
||||||
"\n",
|
|
||||||
"model_name = \"AdultCensus_runHistory.mml\"\n",
|
|
||||||
"model_dbfs = os.path.join(\"/dbfs\", model_name)\n",
|
|
||||||
"run_history_name = 'spark-ml-notebook'\n",
|
|
||||||
"\n",
|
|
||||||
"# start a training run by defining an experiment\n",
|
|
||||||
"myexperiment = Experiment(ws, \"Ignite_AI_Talk\")\n",
|
|
||||||
"root_run = myexperiment.start_logging()\n",
|
|
||||||
"\n",
|
|
||||||
"# Regularization Rates - \n",
|
|
||||||
"regs = [0.0001, 0.001, 0.01, 0.1]\n",
|
|
||||||
" \n",
|
|
||||||
"# try a bunch of regularization rate in a Logistic Regression model\n",
|
|
||||||
"for reg in regs:\n",
|
|
||||||
" print(\"Regularization rate: {}\".format(reg))\n",
|
|
||||||
" # create a bunch of child runs\n",
|
|
||||||
" with root_run.child_run(\"reg-\" + str(reg)) as run:\n",
|
|
||||||
" # create a new Logistic Regression model.\n",
|
|
||||||
" lr = LogisticRegression(regParam=reg)\n",
|
|
||||||
" \n",
|
|
||||||
" # put together the pipeline\n",
|
|
||||||
" pipe = Pipeline(stages=[*si_xvars, *ohe_xvars, si_label, assembler, lr])\n",
|
|
||||||
"\n",
|
|
||||||
" # train the model\n",
|
|
||||||
" model_p = pipe.fit(train)\n",
|
|
||||||
" \n",
|
|
||||||
" # make prediction\n",
|
|
||||||
" pred = model_p.transform(test)\n",
|
|
||||||
" \n",
|
|
||||||
" # evaluate. note only 2 metrics are supported out of the box by Spark ML.\n",
|
|
||||||
" bce = BinaryClassificationEvaluator(rawPredictionCol='rawPrediction')\n",
|
|
||||||
" au_roc = bce.setMetricName('areaUnderROC').evaluate(pred)\n",
|
|
||||||
" au_prc = bce.setMetricName('areaUnderPR').evaluate(pred)\n",
|
|
||||||
"\n",
|
|
||||||
" print(\"Area under ROC: {}\".format(au_roc))\n",
|
|
||||||
" print(\"Area Under PR: {}\".format(au_prc))\n",
|
|
||||||
" \n",
|
|
||||||
" # log reg, au_roc, au_prc and feature names in run history\n",
|
|
||||||
" run.log(\"reg\", reg)\n",
|
|
||||||
" run.log(\"au_roc\", au_roc)\n",
|
|
||||||
" run.log(\"au_prc\", au_prc)\n",
|
|
||||||
" run.log_list(\"columns\", train.columns)\n",
|
|
||||||
"\n",
|
|
||||||
" # save model\n",
|
|
||||||
" model_p.write().overwrite().save(model_name)\n",
|
|
||||||
" \n",
|
|
||||||
" # upload the serialized model into run history record\n",
|
|
||||||
" mdl, ext = model_name.split(\".\")\n",
|
|
||||||
" model_zip = mdl + \".zip\"\n",
|
|
||||||
" shutil.make_archive(mdl, 'zip', model_dbfs)\n",
|
|
||||||
" run.upload_file(\"outputs/\" + model_name, model_zip) \n",
|
|
||||||
" #run.upload_file(\"outputs/\" + model_name, path_or_stream = model_dbfs) #cannot deal with folders\n",
|
|
||||||
"\n",
|
|
||||||
" # now delete the serialized model from local folder since it is already uploaded to run history \n",
|
|
||||||
" shutil.rmtree(model_dbfs)\n",
|
|
||||||
" os.remove(model_zip)\n",
|
|
||||||
" \n",
|
|
||||||
"# Declare run completed\n",
|
|
||||||
"root_run.complete()\n",
|
|
||||||
"root_run_id = root_run.id\n",
|
|
||||||
"print (\"run id:\", root_run.id)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"metrics = root_run.get_metrics(recursive=True)\n",
|
|
||||||
"best_run_id = max(metrics, key = lambda k: metrics[k]['au_roc'])\n",
|
|
||||||
"print(best_run_id, metrics[best_run_id]['au_roc'], metrics[best_run_id]['reg'])"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"#Get the best run\n",
|
|
||||||
"child_runs = {}\n",
|
|
||||||
"\n",
|
|
||||||
"for r in root_run.get_children():\n",
|
|
||||||
" child_runs[r.id] = r\n",
|
|
||||||
" \n",
|
|
||||||
"best_run = child_runs[best_run_id]"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"#Download the model from the best run to a local folder\n",
|
|
||||||
"best_model_file_name = \"best_model.zip\"\n",
|
|
||||||
"best_run.download_file(name = 'outputs/' + model_name, output_file_path = best_model_file_name)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#Model Evaluation"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"##unzip the model to dbfs (as load() seems to require that) and load it.\n",
|
|
||||||
"if os.path.isfile(model_dbfs) or os.path.isdir(model_dbfs):\n",
|
|
||||||
" shutil.rmtree(model_dbfs)\n",
|
|
||||||
"shutil.unpack_archive(best_model_file_name, model_dbfs)\n",
|
|
||||||
"\n",
|
|
||||||
"model_p_best = PipelineModel.load(model_name)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# make prediction\n",
|
|
||||||
"pred = model_p_best.transform(test)\n",
|
|
||||||
"output = pred[['hours_per_week','age','workclass','marital_status','income','prediction']]\n",
|
|
||||||
"display(output.limit(5))"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# evaluate. note only 2 metrics are supported out of the box by Spark ML.\n",
|
|
||||||
"bce = BinaryClassificationEvaluator(rawPredictionCol='rawPrediction')\n",
|
|
||||||
"au_roc = bce.setMetricName('areaUnderROC').evaluate(pred)\n",
|
|
||||||
"au_prc = bce.setMetricName('areaUnderPR').evaluate(pred)\n",
|
|
||||||
"\n",
|
|
||||||
"print(\"Area under ROC: {}\".format(au_roc))\n",
|
|
||||||
"print(\"Area Under PR: {}\".format(au_prc))"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#Model Persistence"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"##NOTE: by default the model is saved to and loaded from /dbfs/ instead of cwd!\n",
|
|
||||||
"model_p_best.write().overwrite().save(model_name)\n",
|
|
||||||
"print(\"saved model to {}\".format(model_dbfs))"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"%sh\n",
|
|
||||||
"\n",
|
|
||||||
"ls -la /dbfs/AdultCensus_runHistory.mml/*"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"dbutils.notebook.exit(\"success\")"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
""
|
|
||||||
]
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"metadata": {
|
|
||||||
"authors": [
|
|
||||||
{
|
|
||||||
"name": "pasha"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"kernelspec": {
|
|
||||||
"display_name": "Python 3.6",
|
|
||||||
"language": "python",
|
|
||||||
"name": "python36"
|
|
||||||
},
|
|
||||||
"language_info": {
|
|
||||||
"codemirror_mode": {
|
|
||||||
"name": "ipython",
|
|
||||||
"version": 3
|
|
||||||
},
|
|
||||||
"file_extension": ".py",
|
|
||||||
"mimetype": "text/x-python",
|
|
||||||
"name": "python",
|
|
||||||
"nbconvert_exporter": "python",
|
|
||||||
"pygments_lexer": "ipython3",
|
|
||||||
"version": "3.6.6"
|
|
||||||
},
|
|
||||||
"name": "build-model-run-history-03",
|
|
||||||
"notebookId": 3836944406456339
|
|
||||||
},
|
|
||||||
"nbformat": 4,
|
|
||||||
"nbformat_minor": 1
|
|
||||||
}
|
|
||||||
@@ -1,320 +0,0 @@
|
|||||||
{
|
|
||||||
"cells": [
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Azure ML & Azure Databricks notebooks by Parashar Shah.\n",
|
|
||||||
"\n",
|
|
||||||
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
|
||||||
"\n",
|
|
||||||
"Licensed under the MIT License."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"# Register Azure Databricks trained model and deploy it to ACI\n"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Please ensure you have run all previous notebooks in sequence before running this.\n",
|
|
||||||
"\n",
|
|
||||||
"Please Register Azure Container Instance(ACI) using Azure Portal: https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-supported-services#portal in your subscription before using the SDK to deploy your ML model to ACI."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"import azureml.core\n",
|
|
||||||
"\n",
|
|
||||||
"# Check core SDK version number\n",
|
|
||||||
"print(\"SDK version:\", azureml.core.VERSION)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# Set auth to be used by workspace related APIs.\n",
|
|
||||||
"# For automation or CI/CD ServicePrincipalAuthentication can be used.\n",
|
|
||||||
"# https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.authentication.serviceprincipalauthentication?view=azure-ml-py\n",
|
|
||||||
"auth = None"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.core import Workspace\n",
|
|
||||||
"\n",
|
|
||||||
"ws = Workspace.from_config(auth = auth)\n",
|
|
||||||
"print('Workspace name: ' + ws.name, \n",
|
|
||||||
" 'Azure region: ' + ws.location, \n",
|
|
||||||
" 'Subscription id: ' + ws.subscription_id, \n",
|
|
||||||
" 'Resource group: ' + ws.resource_group, sep = '\\n')"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"##NOTE: service deployment always gets the model from the current working dir.\n",
|
|
||||||
"import os\n",
|
|
||||||
"\n",
|
|
||||||
"model_name = \"AdultCensus_runHistory.mml\" # \n",
|
|
||||||
"model_name_dbfs = os.path.join(\"/dbfs\", model_name)\n",
|
|
||||||
"\n",
|
|
||||||
"print(\"copy model from dbfs to local\")\n",
|
|
||||||
"model_local = \"file:\" + os.getcwd() + \"/\" + model_name\n",
|
|
||||||
"dbutils.fs.cp(model_name, model_local, True)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"#Register the model\n",
|
|
||||||
"from azureml.core.model import Model\n",
|
|
||||||
"mymodel = Model.register(model_path = model_name, # this points to a local file\n",
|
|
||||||
" model_name = model_name, # this is the name the model is registered as, am using same name for both path and name. \n",
|
|
||||||
" description = \"ADB trained model by Parashar\",\n",
|
|
||||||
" workspace = ws)\n",
|
|
||||||
"\n",
|
|
||||||
"print(mymodel.name, mymodel.description, mymodel.version)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"#%%writefile score_sparkml.py\n",
|
|
||||||
"score_sparkml = \"\"\"\n",
|
|
||||||
" \n",
|
|
||||||
"import json\n",
|
|
||||||
" \n",
|
|
||||||
"def init():\n",
|
|
||||||
" # One-time initialization of PySpark and predictive model\n",
|
|
||||||
" import pyspark\n",
|
|
||||||
" import os\n",
|
|
||||||
" from azureml.core.model import Model\n",
|
|
||||||
" from pyspark.ml import PipelineModel\n",
|
|
||||||
" \n",
|
|
||||||
" global trainedModel\n",
|
|
||||||
" global spark\n",
|
|
||||||
" \n",
|
|
||||||
" spark = pyspark.sql.SparkSession.builder.appName(\"ADB and AML notebook by Parashar\").getOrCreate()\n",
|
|
||||||
" model_name = \"{model_name}\" #interpolated\n",
|
|
||||||
" # AZUREML_MODEL_DIR is an environment variable created during deployment.\n",
|
|
||||||
" # It is the path to the model folder (./azureml-models/$MODEL_NAME/$VERSION)\n",
|
|
||||||
" # For multiple models, it points to the folder containing all deployed models (./azureml-models)\n",
|
|
||||||
" model_path = os.path.join(os.getenv('AZUREML_MODEL_DIR'), model_name)\n",
|
|
||||||
" trainedModel = PipelineModel.load(model_path)\n",
|
|
||||||
" \n",
|
|
||||||
"def run(input_json):\n",
|
|
||||||
" if isinstance(trainedModel, Exception):\n",
|
|
||||||
" return json.dumps({{\"trainedModel\":str(trainedModel)}})\n",
|
|
||||||
" \n",
|
|
||||||
" try:\n",
|
|
||||||
" sc = spark.sparkContext\n",
|
|
||||||
" input_list = json.loads(input_json)\n",
|
|
||||||
" input_rdd = sc.parallelize(input_list)\n",
|
|
||||||
" input_df = spark.read.json(input_rdd)\n",
|
|
||||||
" \n",
|
|
||||||
" # Compute prediction\n",
|
|
||||||
" prediction = trainedModel.transform(input_df)\n",
|
|
||||||
" #result = prediction.first().prediction\n",
|
|
||||||
" predictions = prediction.collect()\n",
|
|
||||||
" \n",
|
|
||||||
" #Get each scored result\n",
|
|
||||||
" preds = [str(x['prediction']) for x in predictions]\n",
|
|
||||||
" result = \",\".join(preds)\n",
|
|
||||||
" # you can return any data type as long as it is JSON-serializable\n",
|
|
||||||
" return result.tolist()\n",
|
|
||||||
" except Exception as e:\n",
|
|
||||||
" result = str(e)\n",
|
|
||||||
" return result\n",
|
|
||||||
" \n",
|
|
||||||
"\"\"\".format(model_name=model_name)\n",
|
|
||||||
" \n",
|
|
||||||
"exec(score_sparkml)\n",
|
|
||||||
" \n",
|
|
||||||
"with open(\"score_sparkml.py\", \"w\") as file:\n",
|
|
||||||
" file.write(score_sparkml)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.core.conda_dependencies import CondaDependencies \n",
|
|
||||||
"\n",
|
|
||||||
"myacienv = CondaDependencies.create(conda_packages=['scikit-learn','numpy','pandas']) # showing how to add libs as an eg. - not needed for this model.\n",
|
|
||||||
"\n",
|
|
||||||
"with open(\"myenv.yml\",\"w\") as f:\n",
|
|
||||||
" f.write(myacienv.serialize_to_string())"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"#deploy to ACI\n",
|
|
||||||
"from azureml.core.webservice import AciWebservice, Webservice\n",
|
|
||||||
"from azureml.exceptions import WebserviceException\n",
|
|
||||||
"from azureml.core.model import InferenceConfig\n",
|
|
||||||
"from azureml.core.environment import Environment\n",
|
|
||||||
"from azureml.core.conda_dependencies import CondaDependencies\n",
|
|
||||||
"\n",
|
|
||||||
"\n",
|
|
||||||
"myaci_config = AciWebservice.deploy_configuration(cpu_cores = 2, \n",
|
|
||||||
" memory_gb = 2, \n",
|
|
||||||
" tags = {'name':'Databricks Azure ML ACI'}, \n",
|
|
||||||
" description = 'This is for ADB and AML example.')\n",
|
|
||||||
"\n",
|
|
||||||
"service_name = 'aciws'\n",
|
|
||||||
"\n",
|
|
||||||
"# Remove any existing service under the same name.\n",
|
|
||||||
"try:\n",
|
|
||||||
" Webservice(ws, service_name).delete()\n",
|
|
||||||
"except WebserviceException:\n",
|
|
||||||
" pass\n",
|
|
||||||
"\n",
|
|
||||||
"myenv = Environment.get(ws, name='AzureML-PySpark-MmlSpark-0.15')\n",
|
|
||||||
"# we need to add extra packages to procured environment\n",
|
|
||||||
"# in order to deploy amended environment we need to rename it\n",
|
|
||||||
"myenv.name = 'myenv'\n",
|
|
||||||
"model_dependencies = CondaDependencies('myenv.yml')\n",
|
|
||||||
"for pip_dep in model_dependencies.pip_packages:\n",
|
|
||||||
" myenv.python.conda_dependencies.add_pip_package(pip_dep)\n",
|
|
||||||
"for conda_dep in model_dependencies.conda_packages:\n",
|
|
||||||
" myenv.python.conda_dependencies.add_conda_package(conda_dep)\n",
|
|
||||||
"inference_config = InferenceConfig(entry_script='score_sparkml.py', environment=myenv)\n",
|
|
||||||
"\n",
|
|
||||||
"myservice = Model.deploy(ws, service_name, [mymodel], inference_config, myaci_config)\n",
|
|
||||||
"myservice.wait_for_deployment(show_output=True)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"help(Webservice)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"#for using the Web HTTP API \n",
|
|
||||||
"print(myservice.scoring_uri)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"import json\n",
|
|
||||||
"\n",
|
|
||||||
"#get the some sample data\n",
|
|
||||||
"test_data_path = \"AdultCensusIncomeTest\"\n",
|
|
||||||
"test = spark.read.parquet(test_data_path).limit(5)\n",
|
|
||||||
"\n",
|
|
||||||
"test_json = json.dumps(test.toJSON().collect())\n",
|
|
||||||
"\n",
|
|
||||||
"print(test_json)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"#using data defined above predict if income is >50K (1) or <=50K (0)\n",
|
|
||||||
"myservice.run(input_data=test_json)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"#comment to not delete the web service\n",
|
|
||||||
"myservice.delete()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Deploying to other types of computes\n",
|
|
||||||
"\n",
|
|
||||||
"In order to learn how to deploy to other types of compute targets, such as AKS, please take a look at the set of notebooks in the [deployment](https://github.com/Azure/MachineLearningNotebooks/tree/master/how-to-use-azureml/deployment) folder."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
""
|
|
||||||
]
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"metadata": {
|
|
||||||
"authors": [
|
|
||||||
{
|
|
||||||
"name": "pasha"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"kernelspec": {
|
|
||||||
"display_name": "Python 3.6",
|
|
||||||
"language": "python",
|
|
||||||
"name": "python36"
|
|
||||||
},
|
|
||||||
"language_info": {
|
|
||||||
"codemirror_mode": {
|
|
||||||
"name": "ipython",
|
|
||||||
"version": 3
|
|
||||||
},
|
|
||||||
"file_extension": ".py",
|
|
||||||
"mimetype": "text/x-python",
|
|
||||||
"name": "python",
|
|
||||||
"nbconvert_exporter": "python",
|
|
||||||
"pygments_lexer": "ipython3",
|
|
||||||
"version": "3.6.8"
|
|
||||||
},
|
|
||||||
"name": "deploy-to-aci-04",
|
|
||||||
"notebookId": 3836944406456376
|
|
||||||
},
|
|
||||||
"nbformat": 4,
|
|
||||||
"nbformat_minor": 1
|
|
||||||
}
|
|
||||||
@@ -1,179 +0,0 @@
|
|||||||
{
|
|
||||||
"cells": [
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Azure ML & Azure Databricks notebooks by Parashar Shah.\n",
|
|
||||||
"\n",
|
|
||||||
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
|
||||||
"\n",
|
|
||||||
"Licensed under the MIT License."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#Data Ingestion"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"import os\n",
|
|
||||||
"import urllib"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# Download AdultCensusIncome.csv from Azure CDN. This file has 32,561 rows.\n",
|
|
||||||
"dataurl = \"https://amldockerdatasets.azureedge.net/AdultCensusIncome.csv\"\n",
|
|
||||||
"datafile = \"AdultCensusIncome.csv\"\n",
|
|
||||||
"datafile_dbfs = os.path.join(\"/dbfs\", datafile)\n",
|
|
||||||
"\n",
|
|
||||||
"if os.path.isfile(datafile_dbfs):\n",
|
|
||||||
" print(\"found {} at {}\".format(datafile, datafile_dbfs))\n",
|
|
||||||
"else:\n",
|
|
||||||
" print(\"downloading {} to {}\".format(datafile, datafile_dbfs))\n",
|
|
||||||
" urllib.request.urlretrieve(dataurl, datafile_dbfs)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# Create a Spark dataframe out of the csv file.\n",
|
|
||||||
"data_all = sqlContext.read.format('csv').options(header='true', inferSchema='true', ignoreLeadingWhiteSpace='true', ignoreTrailingWhiteSpace='true').load(datafile)\n",
|
|
||||||
"print(\"({}, {})\".format(data_all.count(), len(data_all.columns)))\n",
|
|
||||||
"data_all.printSchema()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"#renaming columns\n",
|
|
||||||
"columns_new = [col.replace(\"-\", \"_\") for col in data_all.columns]\n",
|
|
||||||
"data_all = data_all.toDF(*columns_new)\n",
|
|
||||||
"data_all.printSchema()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"display(data_all.limit(5))"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#Data Preparation"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# Choose feature columns and the label column.\n",
|
|
||||||
"label = \"income\"\n",
|
|
||||||
"xvars = set(data_all.columns) - {label}\n",
|
|
||||||
"\n",
|
|
||||||
"print(\"label = {}\".format(label))\n",
|
|
||||||
"print(\"features = {}\".format(xvars))\n",
|
|
||||||
"\n",
|
|
||||||
"data = data_all.select([*xvars, label])\n",
|
|
||||||
"\n",
|
|
||||||
"# Split data into train and test.\n",
|
|
||||||
"train, test = data.randomSplit([0.75, 0.25], seed=123)\n",
|
|
||||||
"\n",
|
|
||||||
"print(\"train ({}, {})\".format(train.count(), len(train.columns)))\n",
|
|
||||||
"print(\"test ({}, {})\".format(test.count(), len(test.columns)))"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#Data Persistence"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# Write the train and test data sets to intermediate storage\n",
|
|
||||||
"train_data_path = \"AdultCensusIncomeTrain\"\n",
|
|
||||||
"test_data_path = \"AdultCensusIncomeTest\"\n",
|
|
||||||
"\n",
|
|
||||||
"train_data_path_dbfs = os.path.join(\"/dbfs\", \"AdultCensusIncomeTrain\")\n",
|
|
||||||
"test_data_path_dbfs = os.path.join(\"/dbfs\", \"AdultCensusIncomeTest\")\n",
|
|
||||||
"\n",
|
|
||||||
"train.write.mode('overwrite').parquet(train_data_path)\n",
|
|
||||||
"test.write.mode('overwrite').parquet(test_data_path)\n",
|
|
||||||
"print(\"train and test datasets saved to {} and {}\".format(train_data_path_dbfs, test_data_path_dbfs))"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": []
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
""
|
|
||||||
]
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"metadata": {
|
|
||||||
"authors": [
|
|
||||||
{
|
|
||||||
"name": "pasha"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"kernelspec": {
|
|
||||||
"display_name": "Python 3.6",
|
|
||||||
"language": "python",
|
|
||||||
"name": "python36"
|
|
||||||
},
|
|
||||||
"language_info": {
|
|
||||||
"codemirror_mode": {
|
|
||||||
"name": "ipython",
|
|
||||||
"version": 3
|
|
||||||
},
|
|
||||||
"file_extension": ".py",
|
|
||||||
"mimetype": "text/x-python",
|
|
||||||
"name": "python",
|
|
||||||
"nbconvert_exporter": "python",
|
|
||||||
"pygments_lexer": "ipython3",
|
|
||||||
"version": "3.6.6"
|
|
||||||
},
|
|
||||||
"name": "ingest-data-02",
|
|
||||||
"notebookId": 3836944406456362
|
|
||||||
},
|
|
||||||
"nbformat": 4,
|
|
||||||
"nbformat_minor": 1
|
|
||||||
}
|
|
||||||
@@ -1,183 +0,0 @@
|
|||||||
{
|
|
||||||
"cells": [
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Azure ML & Azure Databricks notebooks by Parashar Shah.\n",
|
|
||||||
"\n",
|
|
||||||
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
|
||||||
"\n",
|
|
||||||
"Licensed under the MIT License."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"We support installing AML SDK as library from GUI. When attaching a library follow this https://docs.databricks.com/user-guide/libraries.html and add the below string as your PyPi package. You can select the option to attach the library to all clusters or just one cluster.\n",
|
|
||||||
"\n",
|
|
||||||
"**install azureml-sdk**\n",
|
|
||||||
"* Source: Upload Python Egg or PyPi\n",
|
|
||||||
"* PyPi Name: `azureml-sdk[databricks]`\n",
|
|
||||||
"* Select Install Library"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"import azureml.core\n",
|
|
||||||
"\n",
|
|
||||||
"# Check core SDK version number - based on build number of preview/master.\n",
|
|
||||||
"print(\"SDK version:\", azureml.core.VERSION)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Please specify the Azure subscription Id, resource group name, workspace name, and the region in which you want to create the Azure Machine Learning Workspace.\n",
|
|
||||||
"\n",
|
|
||||||
"You can get the value of your Azure subscription ID from the Azure Portal, and then selecting Subscriptions from the menu on the left.\n",
|
|
||||||
"\n",
|
|
||||||
"For the resource_group, use the name of the resource group that contains your Azure Databricks Workspace.\n",
|
|
||||||
"\n",
|
|
||||||
"NOTE: If you provide a resource group name that does not exist, the resource group will be automatically created. This may or may not succeed in your environment, depending on the permissions you have on your Azure Subscription."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# subscription_id = \"<your-subscription-id>\"\n",
|
|
||||||
"# resource_group = \"<your-existing-resource-group>\"\n",
|
|
||||||
"# workspace_name = \"<a-new-or-existing-workspace; it is unrelated to Databricks workspace>\"\n",
|
|
||||||
"# workspace_region = \"<your-resource group-region>\""
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# Set auth to be used by workspace related APIs.\n",
|
|
||||||
"# For automation or CI/CD ServicePrincipalAuthentication can be used.\n",
|
|
||||||
"# https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.authentication.serviceprincipalauthentication?view=azure-ml-py\n",
|
|
||||||
"auth = None"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# import the Workspace class and check the azureml SDK version\n",
|
|
||||||
"# exist_ok checks if workspace exists or not.\n",
|
|
||||||
"\n",
|
|
||||||
"from azureml.core import Workspace\n",
|
|
||||||
"\n",
|
|
||||||
"ws = Workspace.create(name = workspace_name,\n",
|
|
||||||
" subscription_id = subscription_id,\n",
|
|
||||||
" resource_group = resource_group, \n",
|
|
||||||
" location = workspace_region,\n",
|
|
||||||
" auth = auth,\n",
|
|
||||||
" exist_ok=True)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"#get workspace details\n",
|
|
||||||
"ws.get_details()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"ws = Workspace(workspace_name = workspace_name,\n",
|
|
||||||
" subscription_id = subscription_id,\n",
|
|
||||||
" resource_group = resource_group,\n",
|
|
||||||
" auth = auth)\n",
|
|
||||||
"\n",
|
|
||||||
"# persist the subscription id, resource group name, and workspace name in aml_config/config.json.\n",
|
|
||||||
"ws.write_config()\n",
|
|
||||||
"#if you need to give a different path/filename please use this\n",
|
|
||||||
"#write_config(path=\"/databricks/driver/aml_config/\",file_name=<alias_conf.cfg>)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"help(Workspace)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# import the Workspace class and check the azureml SDK version\n",
|
|
||||||
"from azureml.core import Workspace\n",
|
|
||||||
"\n",
|
|
||||||
"ws = Workspace.from_config(auth = auth)\n",
|
|
||||||
"#ws = Workspace.from_config(<full path>)\n",
|
|
||||||
"print('Workspace name: ' + ws.name, \n",
|
|
||||||
" 'Azure region: ' + ws.location, \n",
|
|
||||||
" 'Subscription id: ' + ws.subscription_id, \n",
|
|
||||||
" 'Resource group: ' + ws.resource_group, sep = '\\n')"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
""
|
|
||||||
]
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"metadata": {
|
|
||||||
"authors": [
|
|
||||||
{
|
|
||||||
"name": "pasha"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"kernelspec": {
|
|
||||||
"display_name": "Python 3.6",
|
|
||||||
"language": "python",
|
|
||||||
"name": "python36"
|
|
||||||
},
|
|
||||||
"language_info": {
|
|
||||||
"codemirror_mode": {
|
|
||||||
"name": "ipython",
|
|
||||||
"version": 3
|
|
||||||
},
|
|
||||||
"file_extension": ".py",
|
|
||||||
"mimetype": "text/x-python",
|
|
||||||
"name": "python",
|
|
||||||
"nbconvert_exporter": "python",
|
|
||||||
"pygments_lexer": "ipython3",
|
|
||||||
"version": "3.6.6"
|
|
||||||
},
|
|
||||||
"name": "installation-and-configuration-01",
|
|
||||||
"notebookId": 3688394266452835
|
|
||||||
},
|
|
||||||
"nbformat": 4,
|
|
||||||
"nbformat_minor": 1
|
|
||||||
}
|
|
||||||
70
how-to-use-azureml/azure-databricks/automl/README.md
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
# Automated ML introduction
|
||||||
|
Automated machine learning (automated ML) builds high quality machine learning models for you by automating model and hyperparameter selection. Bring a labelled dataset that you want to build a model for, automated ML will give you a high quality machine learning model that you can use for predictions.
|
||||||
|
|
||||||
|
|
||||||
|
If you are new to Data Science, automated ML will help you get jumpstarted by simplifying machine learning model building. It abstracts you from needing to perform model selection, hyperparameter selection and in one step creates a high quality trained model for you to use.
|
||||||
|
|
||||||
|
If you are an experienced data scientist, automated ML will help increase your productivity by intelligently performing the model and hyperparameter selection for your training and generates high quality models much quicker than manually specifying several combinations of the parameters and running training jobs. Automated ML provides visibility and access to all the training jobs and the performance characteristics of the models to help you further tune the pipeline if you desire.
|
||||||
|
|
||||||
|
# Install Instructions using Azure Databricks :
|
||||||
|
|
||||||
|
#### For Databricks non ML runtime 7.1(scala 2.21, spark 3.0.0) and up, Install Automated Machine Learning sdk by adding and running the following command as the first cell of your notebook. This will install AutoML dependencies specific for your notebook.
|
||||||
|
|
||||||
|
%pip install --upgrade --force-reinstall -r https://aka.ms/automl_linux_requirements.txt
|
||||||
|
|
||||||
|
|
||||||
|
#### For Databricks non ML runtime 7.0 and lower, Install Automated Machine Learning sdk using init script as shown below before running the notebook.**
|
||||||
|
|
||||||
|
**Create the Azure Databricks cluster-scoped init script 'azureml-cluster-init.sh' as below
|
||||||
|
|
||||||
|
1. Create the base directory you want to store the init script in if it does not exist.
|
||||||
|
```
|
||||||
|
dbutils.fs.mkdirs("dbfs:/databricks/init/")
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Create the script azureml-cluster-init.sh
|
||||||
|
```
|
||||||
|
dbutils.fs.put("/databricks/init/azureml-cluster-init.sh","""
|
||||||
|
#!/bin/bash
|
||||||
|
set -ex
|
||||||
|
/databricks/python/bin/pip install --upgrade --force-reinstall -r https://aka.ms/automl_linux_requirements.txt
|
||||||
|
""", True)
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Check that the script exists.
|
||||||
|
```
|
||||||
|
display(dbutils.fs.ls("dbfs:/databricks/init/azureml-cluster-init.sh"))
|
||||||
|
```
|
||||||
|
|
||||||
|
**Install libraries to cluster using init script 'azureml-cluster-init.sh' created in previous step
|
||||||
|
|
||||||
|
1. Configure the cluster to run the script.
|
||||||
|
* Using the cluster configuration page
|
||||||
|
1. On the cluster configuration page, click the Advanced Options toggle.
|
||||||
|
1. At the bottom of the page, click the Init Scripts tab.
|
||||||
|
1. In the Destination drop-down, select a destination type. Example: 'DBFS'
|
||||||
|
1. Specify a path to the init script.
|
||||||
|
```
|
||||||
|
dbfs:/databricks/init/azureml-cluster-init.sh
|
||||||
|
```
|
||||||
|
1. Click Add
|
||||||
|
|
||||||
|
* Using the API.
|
||||||
|
```
|
||||||
|
curl -n -X POST -H 'Content-Type: application/json' -d '{
|
||||||
|
"cluster_id": "<cluster_id>",
|
||||||
|
"num_workers": <num_workers>,
|
||||||
|
"spark_version": "<spark_version>",
|
||||||
|
"node_type_id": "<node_type_id>",
|
||||||
|
"cluster_log_conf": {
|
||||||
|
"dbfs" : {
|
||||||
|
"destination": "dbfs:/cluster-logs"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"init_scripts": [ {
|
||||||
|
"dbfs": {
|
||||||
|
"destination": "dbfs:/databricks/init/azureml-cluster-init.sh"
|
||||||
|
}
|
||||||
|
} ]
|
||||||
|
}' https://<databricks-instance>/api/2.0/clusters/edit
|
||||||
|
```
|
||||||
@@ -13,12 +13,13 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"We support installing AML SDK as library from GUI. When attaching a library follow this https://docs.databricks.com/user-guide/libraries.html and add the below string as your PyPi package. You can select the option to attach the library to all clusters or just one cluster.\n",
|
"## AutoML Installation\n",
|
||||||
"\n",
|
"\n",
|
||||||
"**install azureml-sdk with Automated ML**\n",
|
"**For Databricks non ML runtime 7.1(scala 2.21, spark 3.0.0) and up, Install AML sdk by running the following command in the first cell of the notebook.**\n",
|
||||||
"* Source: Upload Python Egg or PyPi\n",
|
"\n",
|
||||||
"* PyPi Name: `azureml-sdk[automl]`\n",
|
"%pip install --upgrade --force-reinstall -r https://aka.ms/automl_linux_requirements.txt\n",
|
||||||
"* Select Install Library"
|
"\n",
|
||||||
|
"**For Databricks non ML runtime 7.0 and lower, Install AML sdk using init script as shown in [readme](https://github.com/Azure/MachineLearningNotebooks/blob/master/how-to-use-azureml/azure-databricks/automl/README.md) before running this notebook.**\n"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -349,32 +350,6 @@
|
|||||||
"displayHTML(\"<a href={} target='_blank'>Azure Portal: {}</a>\".format(local_run.get_portal_url(), local_run.id))"
|
"displayHTML(\"<a href={} target='_blank'>Azure Portal: {}</a>\".format(local_run.get_portal_url(), local_run.id))"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Retrieve All Child Runs after the experiment is completed (in portal)\n",
|
|
||||||
"You can also use SDK methods to fetch all the child runs and see individual metrics that we log."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"children = list(local_run.get_children())\n",
|
|
||||||
"metricslist = {}\n",
|
|
||||||
"for run in children:\n",
|
|
||||||
" properties = run.get_properties()\n",
|
|
||||||
" #print(properties)\n",
|
|
||||||
" metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)} \n",
|
|
||||||
" metricslist[int(properties['iteration'])] = metrics\n",
|
|
||||||
"\n",
|
|
||||||
"rundata = pd.DataFrame(metricslist).sort_index(1)\n",
|
|
||||||
"rundata"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
|
|||||||
@@ -13,12 +13,13 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"We support installing AML SDK as library from GUI. When attaching a library follow this https://docs.databricks.com/user-guide/libraries.html and add the below string as your PyPi package. You can select the option to attach the library to all clusters or just one cluster.\n",
|
"## AutoML Installation\n",
|
||||||
"\n",
|
"\n",
|
||||||
"**install azureml-sdk with Automated ML**\n",
|
"**For Databricks non ML runtime 7.1(scala 2.21, spark 3.0.0) and up, Install AML sdk by running the following command in the first cell of the notebook.**\n",
|
||||||
"* Source: Upload Python Egg or PyPi\n",
|
"\n",
|
||||||
"* PyPi Name: `azureml-sdk[automl]`\n",
|
"%pip install --upgrade --force-reinstall -r https://aka.ms/automl_linux_requirements.txt\n",
|
||||||
"* Select Install Library"
|
"\n",
|
||||||
|
"**For Databricks non ML runtime 7.0 and lower, Install AML sdk using init script as shown in [readme](https://github.com/Azure/MachineLearningNotebooks/blob/master/how-to-use-azureml/azure-databricks/automl/README.md) before running this notebook.**"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -351,32 +352,6 @@
|
|||||||
"displayHTML(\"<a href={} target='_blank'>Azure Portal: {}</a>\".format(local_run.get_portal_url(), local_run.id))"
|
"displayHTML(\"<a href={} target='_blank'>Azure Portal: {}</a>\".format(local_run.get_portal_url(), local_run.id))"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Retrieve All Child Runs after the experiment is completed (in portal)\n",
|
|
||||||
"You can also use SDK methods to fetch all the child runs and see individual metrics that we log."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"children = list(local_run.get_children())\n",
|
|
||||||
"metricslist = {}\n",
|
|
||||||
"for run in children:\n",
|
|
||||||
" properties = run.get_properties()\n",
|
|
||||||
" #print(properties)\n",
|
|
||||||
" metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)} \n",
|
|
||||||
" metricslist[int(properties['iteration'])] = metrics\n",
|
|
||||||
"\n",
|
|
||||||
"rundata = pd.DataFrame(metricslist).sort_index(1)\n",
|
|
||||||
"rundata"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
|
|||||||
@@ -1,719 +0,0 @@
|
|||||||
{
|
|
||||||
"cells": [
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Copyright (c) Microsoft Corporation. All rights reserved. \n",
|
|
||||||
"Licensed under the MIT License."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"# Using Databricks as a Compute Target from Azure Machine Learning Pipeline\n",
|
|
||||||
"To use Databricks as a compute target from [Azure Machine Learning Pipeline](https://aka.ms/pl-concept), a [DatabricksStep](https://docs.microsoft.com/en-us/python/api/azureml-pipeline-steps/azureml.pipeline.steps.databricks_step.databricksstep?view=azure-ml-py) is used. This notebook demonstrates the use of DatabricksStep in Azure Machine Learning Pipeline.\n",
|
|
||||||
"\n",
|
|
||||||
"The notebook will show:\n",
|
|
||||||
"1. Running an arbitrary Databricks notebook that the customer has in Databricks workspace\n",
|
|
||||||
"2. Running an arbitrary Python script that the customer has in DBFS\n",
|
|
||||||
"3. Running an arbitrary Python script that is available on local computer (will upload to DBFS, and then run in Databricks) \n",
|
|
||||||
"4. Running a JAR job that the customer has in DBFS.\n",
|
|
||||||
"\n",
|
|
||||||
"## Before you begin:\n",
|
|
||||||
"\n",
|
|
||||||
"1. **Create an Azure Databricks workspace** in the same subscription where you have your Azure Machine Learning workspace. You will need details of this workspace later on to define DatabricksStep. [Click here](https://ms.portal.azure.com/#blade/HubsExtension/Resources/resourceType/Microsoft.Databricks%2Fworkspaces) for more information.\n",
|
|
||||||
"2. **Create PAT (access token)**: Manually create a Databricks access token at the Azure Databricks portal. See [this](https://docs.databricks.com/api/latest/authentication.html#generate-a-token) for more information.\n",
|
|
||||||
"3. **Add demo notebook to ADB**: This notebook has a sample you can use as is. Launch Azure Databricks attached to your Azure Machine Learning workspace and add a new notebook. \n",
|
|
||||||
"4. **Create/attach a Blob storage** for use from ADB"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Add demo notebook to ADB Workspace\n",
|
|
||||||
"Copy and paste the below code to create a new notebook in your ADB workspace."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"```python\n",
|
|
||||||
"# direct access\n",
|
|
||||||
"dbutils.widgets.get(\"myparam\")\n",
|
|
||||||
"p = getArgument(\"myparam\")\n",
|
|
||||||
"print (\"Param -\\'myparam':\")\n",
|
|
||||||
"print (p)\n",
|
|
||||||
"\n",
|
|
||||||
"dbutils.widgets.get(\"input\")\n",
|
|
||||||
"i = getArgument(\"input\")\n",
|
|
||||||
"print (\"Param -\\'input':\")\n",
|
|
||||||
"print (i)\n",
|
|
||||||
"\n",
|
|
||||||
"dbutils.widgets.get(\"output\")\n",
|
|
||||||
"o = getArgument(\"output\")\n",
|
|
||||||
"print (\"Param -\\'output':\")\n",
|
|
||||||
"print (o)\n",
|
|
||||||
"\n",
|
|
||||||
"n = i + \"/testdata.txt\"\n",
|
|
||||||
"df = spark.read.csv(n)\n",
|
|
||||||
"\n",
|
|
||||||
"display (df)\n",
|
|
||||||
"\n",
|
|
||||||
"data = [('value1', 'value2')]\n",
|
|
||||||
"df2 = spark.createDataFrame(data)\n",
|
|
||||||
"\n",
|
|
||||||
"z = o + \"/output.txt\"\n",
|
|
||||||
"df2.write.csv(z)\n",
|
|
||||||
"```"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Azure Machine Learning and Pipeline SDK-specific imports"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"import os\n",
|
|
||||||
"import azureml.core\n",
|
|
||||||
"from azureml.core.runconfig import JarLibrary\n",
|
|
||||||
"from azureml.core.compute import ComputeTarget, DatabricksCompute\n",
|
|
||||||
"from azureml.exceptions import ComputeTargetException\n",
|
|
||||||
"from azureml.core import Workspace, Experiment\n",
|
|
||||||
"from azureml.pipeline.core import Pipeline, PipelineData\n",
|
|
||||||
"from azureml.pipeline.steps import DatabricksStep\n",
|
|
||||||
"from azureml.core.datastore import Datastore\n",
|
|
||||||
"from azureml.data.data_reference import DataReference\n",
|
|
||||||
"\n",
|
|
||||||
"# Check core SDK version number\n",
|
|
||||||
"print(\"SDK version:\", azureml.core.VERSION)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Initialize Workspace\n",
|
|
||||||
"\n",
|
|
||||||
"Initialize a workspace object from persisted configuration. Make sure the config file is present at .\\config.json"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"ws = Workspace.from_config()\n",
|
|
||||||
"print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep = '\\n')"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Attach Databricks compute target\n",
|
|
||||||
"Next, you need to add your Databricks workspace to Azure Machine Learning as a compute target and give it a name. You will use this name to refer to your Databricks workspace compute target inside Azure Machine Learning.\n",
|
|
||||||
"\n",
|
|
||||||
"- **Resource Group** - The resource group name of your Azure Machine Learning workspace\n",
|
|
||||||
"- **Databricks Workspace Name** - The workspace name of your Azure Databricks workspace\n",
|
|
||||||
"- **Databricks Access Token** - The access token you created in ADB\n",
|
|
||||||
"\n",
|
|
||||||
"**The Databricks workspace need to be present in the same subscription as your AML workspace**"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# Replace with your account info before running.\n",
|
|
||||||
" \n",
|
|
||||||
"db_compute_name=os.getenv(\"DATABRICKS_COMPUTE_NAME\", \"<my-databricks-compute-name>\") # Databricks compute name\n",
|
|
||||||
"db_resource_group=os.getenv(\"DATABRICKS_RESOURCE_GROUP\", \"<my-db-resource-group>\") # Databricks resource group\n",
|
|
||||||
"db_workspace_name=os.getenv(\"DATABRICKS_WORKSPACE_NAME\", \"<my-db-workspace-name>\") # Databricks workspace name\n",
|
|
||||||
"db_access_token=os.getenv(\"DATABRICKS_ACCESS_TOKEN\", \"<my-access-token>\") # Databricks access token\n",
|
|
||||||
" \n",
|
|
||||||
"try:\n",
|
|
||||||
" databricks_compute = DatabricksCompute(workspace=ws, name=db_compute_name)\n",
|
|
||||||
" print('Compute target {} already exists'.format(db_compute_name))\n",
|
|
||||||
"except ComputeTargetException:\n",
|
|
||||||
" print('Compute not found, will use below parameters to attach new one')\n",
|
|
||||||
" print('db_compute_name {}'.format(db_compute_name))\n",
|
|
||||||
" print('db_resource_group {}'.format(db_resource_group))\n",
|
|
||||||
" print('db_workspace_name {}'.format(db_workspace_name))\n",
|
|
||||||
" print('db_access_token {}'.format(db_access_token))\n",
|
|
||||||
" \n",
|
|
||||||
" config = DatabricksCompute.attach_configuration(\n",
|
|
||||||
" resource_group = db_resource_group,\n",
|
|
||||||
" workspace_name = db_workspace_name,\n",
|
|
||||||
" access_token= db_access_token)\n",
|
|
||||||
" databricks_compute=ComputeTarget.attach(ws, db_compute_name, config)\n",
|
|
||||||
" databricks_compute.wait_for_completion(True)\n"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Data Connections with Inputs and Outputs\n",
|
|
||||||
"The DatabricksStep supports Azure Bloband ADLS for inputs and outputs. You also will need to define a [Secrets](https://docs.azuredatabricks.net/user-guide/secrets/index.html) scope to enable authentication to external data sources such as Blob and ADLS from Databricks.\n",
|
|
||||||
"\n",
|
|
||||||
"- Databricks documentation on [Azure Blob](https://docs.azuredatabricks.net/spark/latest/data-sources/azure/azure-storage.html)\n",
|
|
||||||
"- Databricks documentation on [ADLS](https://docs.databricks.com/spark/latest/data-sources/azure/azure-datalake.html)\n",
|
|
||||||
"\n",
|
|
||||||
"### Type of Data Access\n",
|
|
||||||
"Databricks allows to interact with Azure Blob and ADLS in two ways.\n",
|
|
||||||
"- **Direct Access**: Databricks allows you to interact with Azure Blob or ADLS URIs directly. The input or output URIs will be mapped to a Databricks widget param in the Databricks notebook.\n",
|
|
||||||
"- **Mounting**: You will be supplied with additional parameters and secrets that will enable you to mount your ADLS or Azure Blob input or output location in your Databricks notebook."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Direct Access: Python sample code\n",
|
|
||||||
"If you have a data reference named \"input\" it will represent the URI of the input and you can access it directly in the Databricks python notebook like so:"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"```python\n",
|
|
||||||
"dbutils.widgets.get(\"input\")\n",
|
|
||||||
"y = getArgument(\"input\")\n",
|
|
||||||
"df = spark.read.csv(y)\n",
|
|
||||||
"```"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Mounting: Python sample code for Azure Blob\n",
|
|
||||||
"Given an Azure Blob data reference named \"input\" the following widget params will be made available in the Databricks notebook:"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"```python\n",
|
|
||||||
"# This contains the input URI\n",
|
|
||||||
"dbutils.widgets.get(\"input\")\n",
|
|
||||||
"myinput_uri = getArgument(\"input\")\n",
|
|
||||||
"\n",
|
|
||||||
"# How to get the input datastore name inside ADB notebook\n",
|
|
||||||
"# This contains the name of a Databricks secret (in the predefined \"amlscope\" secret scope) \n",
|
|
||||||
"# that contians an access key or sas for the Azure Blob input (this name is obtained by appending \n",
|
|
||||||
"# the name of the input with \"_blob_secretname\". \n",
|
|
||||||
"dbutils.widgets.get(\"input_blob_secretname\") \n",
|
|
||||||
"myinput_blob_secretname = getArgument(\"input_blob_secretname\")\n",
|
|
||||||
"\n",
|
|
||||||
"# This contains the required configuration for mounting\n",
|
|
||||||
"dbutils.widgets.get(\"input_blob_config\")\n",
|
|
||||||
"myinput_blob_config = getArgument(\"input_blob_config\")\n",
|
|
||||||
"\n",
|
|
||||||
"# Usage\n",
|
|
||||||
"dbutils.fs.mount(\n",
|
|
||||||
" source = myinput_uri,\n",
|
|
||||||
" mount_point = \"/mnt/input\",\n",
|
|
||||||
" extra_configs = {myinput_blob_config:dbutils.secrets.get(scope = \"amlscope\", key = myinput_blob_secretname)})\n",
|
|
||||||
"```"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Mounting: Python sample code for ADLS\n",
|
|
||||||
"Given an ADLS data reference named \"input\" the following widget params will be made available in the Databricks notebook:"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"```python\n",
|
|
||||||
"# This contains the input URI\n",
|
|
||||||
"dbutils.widgets.get(\"input\") \n",
|
|
||||||
"myinput_uri = getArgument(\"input\")\n",
|
|
||||||
"\n",
|
|
||||||
"# This contains the client id for the service principal \n",
|
|
||||||
"# that has access to the adls input\n",
|
|
||||||
"dbutils.widgets.get(\"input_adls_clientid\") \n",
|
|
||||||
"myinput_adls_clientid = getArgument(\"input_adls_clientid\")\n",
|
|
||||||
"\n",
|
|
||||||
"# This contains the name of a Databricks secret (in the predefined \"amlscope\" secret scope) \n",
|
|
||||||
"# that contains the secret for the above mentioned service principal\n",
|
|
||||||
"dbutils.widgets.get(\"input_adls_secretname\") \n",
|
|
||||||
"myinput_adls_secretname = getArgument(\"input_adls_secretname\")\n",
|
|
||||||
"\n",
|
|
||||||
"# This contains the refresh url for the mounting configs\n",
|
|
||||||
"dbutils.widgets.get(\"input_adls_refresh_url\") \n",
|
|
||||||
"myinput_adls_refresh_url = getArgument(\"input_adls_refresh_url\")\n",
|
|
||||||
"\n",
|
|
||||||
"# Usage \n",
|
|
||||||
"configs = {\"dfs.adls.oauth2.access.token.provider.type\": \"ClientCredential\",\n",
|
|
||||||
" \"dfs.adls.oauth2.client.id\": myinput_adls_clientid,\n",
|
|
||||||
" \"dfs.adls.oauth2.credential\": dbutils.secrets.get(scope = \"amlscope\", key =myinput_adls_secretname),\n",
|
|
||||||
" \"dfs.adls.oauth2.refresh.url\": myinput_adls_refresh_url}\n",
|
|
||||||
"\n",
|
|
||||||
"dbutils.fs.mount(\n",
|
|
||||||
" source = myinput_uri,\n",
|
|
||||||
" mount_point = \"/mnt/output\",\n",
|
|
||||||
" extra_configs = configs)\n",
|
|
||||||
"```"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Use Databricks from Azure Machine Learning Pipeline\n",
|
|
||||||
"To use Databricks as a compute target from Azure Machine Learning Pipeline, a DatabricksStep is used. Let's define a datasource (via DataReference) and intermediate data (via PipelineData) to be used in DatabricksStep."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# Use the default blob storage\n",
|
|
||||||
"def_blob_store = Datastore(ws, \"workspaceblobstore\")\n",
|
|
||||||
"print('Datastore {} will be used'.format(def_blob_store.name))\n",
|
|
||||||
"\n",
|
|
||||||
"# We are uploading a sample file in the local directory to be used as a datasource\n",
|
|
||||||
"def_blob_store.upload_files(files=[\"./testdata.txt\"], target_path=\"dbtest\", overwrite=False)\n",
|
|
||||||
"\n",
|
|
||||||
"step_1_input = DataReference(datastore=def_blob_store, path_on_datastore=\"dbtest\",\n",
|
|
||||||
" data_reference_name=\"input\")\n",
|
|
||||||
"\n",
|
|
||||||
"step_1_output = PipelineData(\"output\", datastore=def_blob_store)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Add a DatabricksStep\n",
|
|
||||||
"Adds a Databricks notebook as a step in a Pipeline.\n",
|
|
||||||
"- ***name:** Name of the Module\n",
|
|
||||||
"- **inputs:** List of input connections for data consumed by this step. Fetch this inside the notebook using dbutils.widgets.get(\"input\")\n",
|
|
||||||
"- **outputs:** List of output port definitions for outputs produced by this step. Fetch this inside the notebook using dbutils.widgets.get(\"output\")\n",
|
|
||||||
"- **existing_cluster_id:** Cluster ID of an existing Interactive cluster on the Databricks workspace. If you are providing this, do not provide any of the parameters below that are used to create a new cluster such as spark_version, node_type, etc.\n",
|
|
||||||
"- **spark_version:** Version of spark for the databricks run cluster. default value: 4.0.x-scala2.11\n",
|
|
||||||
"- **node_type:** Azure vm node types for the databricks run cluster. default value: Standard_D3_v2\n",
|
|
||||||
"- **num_workers:** Specifies a static number of workers for the databricks run cluster\n",
|
|
||||||
"- **min_workers:** Specifies a min number of workers to use for auto-scaling the databricks run cluster\n",
|
|
||||||
"- **max_workers:** Specifies a max number of workers to use for auto-scaling the databricks run cluster\n",
|
|
||||||
"- **spark_env_variables:** Spark environment variables for the databricks run cluster (dictionary of {str:str}). default value: {'PYSPARK_PYTHON': '/databricks/python3/bin/python3'}\n",
|
|
||||||
"- **notebook_path:** Path to the notebook in the databricks instance. If you are providing this, do not provide python script related paramaters or JAR related parameters.\n",
|
|
||||||
"- **notebook_params:** Parameters for the databricks notebook (dictionary of {str:str}). Fetch this inside the notebook using dbutils.widgets.get(\"myparam\")\n",
|
|
||||||
"- **python_script_path:** The path to the python script in the DBFS or S3. If you are providing this, do not provide python_script_name which is used for uploading script from local machine.\n",
|
|
||||||
"- **python_script_params:** Parameters for the python script (list of str)\n",
|
|
||||||
"- **main_class_name:** The name of the entry point in a JAR module. If you are providing this, do not provide any python script or notebook related parameters.\n",
|
|
||||||
"- **jar_params:** Parameters for the JAR module (list of str)\n",
|
|
||||||
"- **python_script_name:** name of a python script on your local machine (relative to source_directory). If you are providing this do not provide python_script_path which is used to execute a remote python script; or any of the JAR or notebook related parameters.\n",
|
|
||||||
"- **source_directory:** folder that contains the script and other files\n",
|
|
||||||
"- **hash_paths:** list of paths to hash to detect a change in source_directory (script file is always hashed)\n",
|
|
||||||
"- **run_name:** Name in databricks for this run\n",
|
|
||||||
"- **timeout_seconds:** Timeout for the databricks run\n",
|
|
||||||
"- **runconfig:** Runconfig to use. Either pass runconfig or each library type as a separate parameter but do not mix the two\n",
|
|
||||||
"- **maven_libraries:** maven libraries for the databricks run\n",
|
|
||||||
"- **pypi_libraries:** pypi libraries for the databricks run\n",
|
|
||||||
"- **egg_libraries:** egg libraries for the databricks run\n",
|
|
||||||
"- **jar_libraries:** jar libraries for the databricks run\n",
|
|
||||||
"- **rcran_libraries:** rcran libraries for the databricks run\n",
|
|
||||||
"- **compute_target:** Azure Databricks compute\n",
|
|
||||||
"- **allow_reuse:** Whether the step should reuse previous results when run with the same settings/inputs\n",
|
|
||||||
"- **version:** Optional version tag to denote a change in functionality for the step\n",
|
|
||||||
"\n",
|
|
||||||
"\\* *denotes required fields* \n",
|
|
||||||
"*You must provide exactly one of num_workers or min_workers and max_workers paramaters* \n",
|
|
||||||
"*You must provide exactly one of databricks_compute or databricks_compute_name parameters*\n",
|
|
||||||
"\n",
|
|
||||||
"## Use runconfig to specify library dependencies\n",
|
|
||||||
"You can use a runconfig to specify the library dependencies for your cluster in Databricks. The runconfig will contain a databricks section as follows:\n",
|
|
||||||
"\n",
|
|
||||||
"```yaml\n",
|
|
||||||
"environment:\n",
|
|
||||||
"# Databricks details\n",
|
|
||||||
" databricks:\n",
|
|
||||||
"# List of maven libraries.\n",
|
|
||||||
" mavenLibraries:\n",
|
|
||||||
" - coordinates: org.jsoup:jsoup:1.7.1\n",
|
|
||||||
" repo: ''\n",
|
|
||||||
" exclusions:\n",
|
|
||||||
" - slf4j:slf4j\n",
|
|
||||||
" - '*:hadoop-client'\n",
|
|
||||||
"# List of PyPi libraries\n",
|
|
||||||
" pypiLibraries:\n",
|
|
||||||
" - package: beautifulsoup4\n",
|
|
||||||
" repo: ''\n",
|
|
||||||
"# List of RCran libraries\n",
|
|
||||||
" rcranLibraries:\n",
|
|
||||||
" -\n",
|
|
||||||
"# Coordinates.\n",
|
|
||||||
" package: ada\n",
|
|
||||||
"# Repo\n",
|
|
||||||
" repo: http://cran.us.r-project.org\n",
|
|
||||||
"# List of JAR libraries\n",
|
|
||||||
" jarLibraries:\n",
|
|
||||||
" -\n",
|
|
||||||
"# Coordinates.\n",
|
|
||||||
" library: dbfs:/mnt/libraries/library.jar\n",
|
|
||||||
"# List of Egg libraries\n",
|
|
||||||
" eggLibraries:\n",
|
|
||||||
" -\n",
|
|
||||||
"# Coordinates.\n",
|
|
||||||
" library: dbfs:/mnt/libraries/library.egg\n",
|
|
||||||
"```\n",
|
|
||||||
"\n",
|
|
||||||
"You can then create a RunConfiguration object using this file and pass it as the runconfig parameter to DatabricksStep.\n",
|
|
||||||
"```python\n",
|
|
||||||
"from azureml.core.runconfig import RunConfiguration\n",
|
|
||||||
"\n",
|
|
||||||
"runconfig = RunConfiguration()\n",
|
|
||||||
"runconfig.load(path='<directory_where_runconfig_is_stored>', name='<runconfig_file_name>')\n",
|
|
||||||
"```"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### 1. Running the demo notebook already added to the Databricks workspace\n",
|
|
||||||
"Create a notebook in the Azure Databricks workspace, and provide the path to that notebook as the value associated with the environment variable \"DATABRICKS_NOTEBOOK_PATH\". This will then set the variable\u00c2\u00a0notebook_path\u00c2\u00a0when you run the code cell below:"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {
|
|
||||||
"tags": [
|
|
||||||
"databricksstep-remarks-sample"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"notebook_path=os.getenv(\"DATABRICKS_NOTEBOOK_PATH\", \"<my-databricks-notebook-path>\") # Databricks notebook path\n",
|
|
||||||
"\n",
|
|
||||||
"dbNbStep = DatabricksStep(\n",
|
|
||||||
" name=\"DBNotebookInWS\",\n",
|
|
||||||
" inputs=[step_1_input],\n",
|
|
||||||
" outputs=[step_1_output],\n",
|
|
||||||
" num_workers=1,\n",
|
|
||||||
" notebook_path=notebook_path,\n",
|
|
||||||
" notebook_params={'myparam': 'testparam'},\n",
|
|
||||||
" run_name='DB_Notebook_demo',\n",
|
|
||||||
" compute_target=databricks_compute,\n",
|
|
||||||
" allow_reuse=True\n",
|
|
||||||
")"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Build and submit the Experiment"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"steps = [dbNbStep]\n",
|
|
||||||
"pipeline = Pipeline(workspace=ws, steps=steps)\n",
|
|
||||||
"pipeline_run = Experiment(ws, 'DB_Notebook_demo').submit(pipeline)\n",
|
|
||||||
"pipeline_run.wait_for_completion()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### View Run Details"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.widgets import RunDetails\n",
|
|
||||||
"RunDetails(pipeline_run).show()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### 2. Running a Python script from DBFS\n",
|
|
||||||
"This shows how to run a Python script in DBFS. \n",
|
|
||||||
"\n",
|
|
||||||
"To complete this, you will need to first upload the Python script in your local machine to DBFS using the [CLI](https://docs.azuredatabricks.net/user-guide/dbfs-databricks-file-system.html). The CLI command is given below:\n",
|
|
||||||
"\n",
|
|
||||||
"```\n",
|
|
||||||
"dbfs cp ./train-db-dbfs.py dbfs:/train-db-dbfs.py\n",
|
|
||||||
"```\n",
|
|
||||||
"\n",
|
|
||||||
"The code in the below cell assumes that you have completed the previous step of uploading the script `train-db-dbfs.py` to the root folder in DBFS."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"python_script_path = os.getenv(\"DATABRICKS_PYTHON_SCRIPT_PATH\", \"<my-databricks-python-script-path>\") # Databricks python script path\n",
|
|
||||||
"\n",
|
|
||||||
"dbPythonInDbfsStep = DatabricksStep(\n",
|
|
||||||
" name=\"DBPythonInDBFS\",\n",
|
|
||||||
" inputs=[step_1_input],\n",
|
|
||||||
" num_workers=1,\n",
|
|
||||||
" python_script_path=python_script_path,\n",
|
|
||||||
" python_script_params={'--input_data'},\n",
|
|
||||||
" run_name='DB_Python_demo',\n",
|
|
||||||
" compute_target=databricks_compute,\n",
|
|
||||||
" allow_reuse=True\n",
|
|
||||||
")"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Build and submit the Experiment"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"steps = [dbPythonInDbfsStep]\n",
|
|
||||||
"pipeline = Pipeline(workspace=ws, steps=steps)\n",
|
|
||||||
"pipeline_run = Experiment(ws, 'DB_Python_demo').submit(pipeline)\n",
|
|
||||||
"pipeline_run.wait_for_completion()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### View Run Details"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.widgets import RunDetails\n",
|
|
||||||
"RunDetails(pipeline_run).show()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### 3. Running a Python script in Databricks that currenlty is in local computer\n",
|
|
||||||
"To run a Python script that is currently in your local computer, follow the instructions below. \n",
|
|
||||||
"\n",
|
|
||||||
"The commented out code below code assumes that you have `train-db-local.py` in the `scripts` subdirectory under the current working directory.\n",
|
|
||||||
"\n",
|
|
||||||
"In this case, the Python script will be uploaded first to DBFS, and then the script will be run in Databricks."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"python_script_name = \"train-db-local.py\"\n",
|
|
||||||
"source_directory = \".\"\n",
|
|
||||||
"\n",
|
|
||||||
"dbPythonInLocalMachineStep = DatabricksStep(\n",
|
|
||||||
" name=\"DBPythonInLocalMachine\",\n",
|
|
||||||
" inputs=[step_1_input],\n",
|
|
||||||
" num_workers=1,\n",
|
|
||||||
" python_script_name=python_script_name,\n",
|
|
||||||
" source_directory=source_directory,\n",
|
|
||||||
" run_name='DB_Python_Local_demo',\n",
|
|
||||||
" compute_target=databricks_compute,\n",
|
|
||||||
" allow_reuse=True\n",
|
|
||||||
")"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Build and submit the Experiment"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"steps = [dbPythonInLocalMachineStep]\n",
|
|
||||||
"pipeline = Pipeline(workspace=ws, steps=steps)\n",
|
|
||||||
"pipeline_run = Experiment(ws, 'DB_Python_Local_demo').submit(pipeline)\n",
|
|
||||||
"pipeline_run.wait_for_completion()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### View Run Details"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.widgets import RunDetails\n",
|
|
||||||
"RunDetails(pipeline_run).show()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### 4. Running a JAR job that is alreay added in DBFS\n",
|
|
||||||
"To run a JAR job that is already uploaded to DBFS, follow the instructions below. You will first upload the JAR file to DBFS using the [CLI](https://docs.azuredatabricks.net/user-guide/dbfs-databricks-file-system.html).\n",
|
|
||||||
"\n",
|
|
||||||
"The commented out code in the below cell assumes that you have uploaded `train-db-dbfs.jar` to the root folder in DBFS. You can upload `train-db-dbfs.jar` to the root folder in DBFS using this commandline so you can use `jar_library_dbfs_path = \"dbfs:/train-db-dbfs.jar\"`:\n",
|
|
||||||
"\n",
|
|
||||||
"```\n",
|
|
||||||
"dbfs cp ./train-db-dbfs.jar dbfs:/train-db-dbfs.jar\n",
|
|
||||||
"```"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"main_jar_class_name = \"com.microsoft.aeva.Main\"\n",
|
|
||||||
"jar_library_dbfs_path = os.getenv(\"DATABRICKS_JAR_LIB_PATH\", \"<my-databricks-jar-lib-path>\") # Databricks jar library path\n",
|
|
||||||
"\n",
|
|
||||||
"dbJarInDbfsStep = DatabricksStep(\n",
|
|
||||||
" name=\"DBJarInDBFS\",\n",
|
|
||||||
" inputs=[step_1_input],\n",
|
|
||||||
" num_workers=1,\n",
|
|
||||||
" main_class_name=main_jar_class_name,\n",
|
|
||||||
" jar_params={'arg1', 'arg2'},\n",
|
|
||||||
" run_name='DB_JAR_demo',\n",
|
|
||||||
" jar_libraries=[JarLibrary(jar_library_dbfs_path)],\n",
|
|
||||||
" compute_target=databricks_compute,\n",
|
|
||||||
" allow_reuse=True\n",
|
|
||||||
")"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Build and submit the Experiment"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"steps = [dbJarInDbfsStep]\n",
|
|
||||||
"pipeline = Pipeline(workspace=ws, steps=steps)\n",
|
|
||||||
"pipeline_run = Experiment(ws, 'DB_JAR_demo').submit(pipeline)\n",
|
|
||||||
"pipeline_run.wait_for_completion()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### View Run Details"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.widgets import RunDetails\n",
|
|
||||||
"RunDetails(pipeline_run).show()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"# Next: ADLA as a Compute Target\n",
|
|
||||||
"To use ADLA as a compute target from Azure Machine Learning Pipeline, a AdlaStep is used. This [notebook](https://aka.ms/pl-adla) demonstrates the use of AdlaStep in Azure Machine Learning Pipeline."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
""
|
|
||||||
]
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"metadata": {
|
|
||||||
"authors": [
|
|
||||||
{
|
|
||||||
"name": "diray"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"kernelspec": {
|
|
||||||
"display_name": "Python 3.6",
|
|
||||||
"language": "python",
|
|
||||||
"name": "python36"
|
|
||||||
},
|
|
||||||
"language_info": {
|
|
||||||
"codemirror_mode": {
|
|
||||||
"name": "ipython",
|
|
||||||
"version": 3
|
|
||||||
},
|
|
||||||
"file_extension": ".py",
|
|
||||||
"mimetype": "text/x-python",
|
|
||||||
"name": "python",
|
|
||||||
"nbconvert_exporter": "python",
|
|
||||||
"pygments_lexer": "ipython3",
|
|
||||||
"version": "3.6.2"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"nbformat": 4,
|
|
||||||
"nbformat_minor": 2
|
|
||||||
}
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
Test1
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
# Copyright (c) Microsoft. All rights reserved.
|
|
||||||
# Licensed under the MIT license.
|
|
||||||
|
|
||||||
print("In train.py")
|
|
||||||
print("As a data scientist, this is where I use my training code.")
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
# Copyright (c) Microsoft. All rights reserved.
|
|
||||||
# Licensed under the MIT license.
|
|
||||||
|
|
||||||
print("In train.py")
|
|
||||||
print("As a data scientist, this is where I use my training code.")
|
|
||||||
84
how-to-use-azureml/azure-synapse/README.md
Normal file
@@ -0,0 +1,84 @@
|
|||||||
|
Azure Synapse Analytics is a limitless analytics service that brings together data integration, enterprise data warehousing, and big data analytics. It gives you the freedom to query data on your terms, using either serverless or dedicated resources—at scale. Azure Synapse brings these worlds together with a unified experience to ingest, explore, prepare, manage, and serve data for immediate BI and machine learning needs. A core offering within Azure Synapse Analytics are serverless Apache Spark pools enhanced for big data workloads.
|
||||||
|
|
||||||
|
Synapse in Aml integration is for customers who want to use Apache Spark in Azure Synapse Analytics to prepare data at scale in Azure ML before training their ML model. This will allow customers to work on their end-to-end ML lifecycle including large-scale data preparation, model training and deployment within Azure ML workspace without having to use suboptimal tools for machine learning or switch between multiple tools for data preparation and model training. The ability to perform all ML tasks within Azure ML will reduce time required for customers to iterate on a machine learning project which typically includes multiple rounds of data preparation and training.
|
||||||
|
|
||||||
|
In the public preview, the capabilities are provided:
|
||||||
|
|
||||||
|
- Link Azure Synapse Analytics workspace to Azure Machine Learning workspace (via ARM, UI or SDK)
|
||||||
|
- Attach Apache Spark pools powered by Azure Synapse Analytics as Azure Machine Learning compute targets (via ARM, UI or SDK)
|
||||||
|
- Launch Apache Spark sessions in notebooks and perform interactive data exploration and preparation. This interactive experience leverages Apache Spark magic and customers will have session-level Conda support to install packages.
|
||||||
|
- Productionize ML pipelines by leveraging Apache Spark pools to pre-process big data
|
||||||
|
|
||||||
|
# Using Synapse in Azure machine learning
|
||||||
|
|
||||||
|
## Create synapse resources
|
||||||
|
|
||||||
|
Follow up the documents to create Synapse workspace and resource-setup.sh is available for you to create the resources.
|
||||||
|
|
||||||
|
- Create from [Portal](https://docs.microsoft.com/en-us/azure/synapse-analytics/quickstart-create-workspace)
|
||||||
|
- Create from [Cli](https://docs.microsoft.com/en-us/azure/synapse-analytics/quickstart-create-workspace-cli)
|
||||||
|
|
||||||
|
Follow up the documents to create Synapse spark pool
|
||||||
|
|
||||||
|
- Create from [Portal](https://docs.microsoft.com/en-us/azure/synapse-analytics/quickstart-create-apache-spark-pool-portal)
|
||||||
|
- Create from [Cli](https://docs.microsoft.com/en-us/cli/azure/ext/synapse/synapse/spark/pool?view=azure-cli-latest)
|
||||||
|
|
||||||
|
## Link Synapse Workspace
|
||||||
|
|
||||||
|
Make sure you are the owner of synapse workspace so that you can link synapse workspace into AML.
|
||||||
|
You can run resource-setup.py to link the synapse workspace and attach compute
|
||||||
|
|
||||||
|
```python
|
||||||
|
from azureml.core import Workspace
|
||||||
|
ws = Workspace.from_config()
|
||||||
|
|
||||||
|
from azureml.core import LinkedService, SynapseWorkspaceLinkedServiceConfiguration
|
||||||
|
synapse_link_config = SynapseWorkspaceLinkedServiceConfiguration(
|
||||||
|
subscription_id="<subscription id>",
|
||||||
|
resource_group="<resource group",
|
||||||
|
name="<synapse workspace name>"
|
||||||
|
)
|
||||||
|
|
||||||
|
linked_service = LinkedService.register(
|
||||||
|
workspace=ws,
|
||||||
|
name='<link name>',
|
||||||
|
linked_service_config=synapse_link_config)
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
## Attach synapse spark pool as AzureML compute
|
||||||
|
|
||||||
|
```python
|
||||||
|
|
||||||
|
from azureml.core.compute import SynapseCompute, ComputeTarget
|
||||||
|
spark_pool_name = "<spark pool name>"
|
||||||
|
attached_synapse_name = "<attached compute name>"
|
||||||
|
|
||||||
|
attach_config = SynapseCompute.attach_configuration(
|
||||||
|
linked_service,
|
||||||
|
type="SynapseSpark",
|
||||||
|
pool_name=spark_pool_name)
|
||||||
|
|
||||||
|
synapse_compute=ComputeTarget.attach(
|
||||||
|
workspace=ws,
|
||||||
|
name=attached_synapse_name,
|
||||||
|
attach_configuration=attach_config)
|
||||||
|
|
||||||
|
synapse_compute.wait_for_completion()
|
||||||
|
```
|
||||||
|
|
||||||
|
## Set up permission
|
||||||
|
|
||||||
|
Grant Spark admin role to system assigned identity of the linked service so that the user can submit experiment run or pipeline run from AML workspace to synapse spark pool.
|
||||||
|
|
||||||
|
Grant Spark admin role to the specific user so that the user can start spark session to synapse spark pool.
|
||||||
|
|
||||||
|
You can get the system assigned identity information by running
|
||||||
|
|
||||||
|
```python
|
||||||
|
print(linked_service.system_assigned_identity_principal_id)
|
||||||
|
```
|
||||||
|
|
||||||
|
- Launch synapse studio of the synapse workspace and grant linked service MSI "Synapse Apache Spark administrator" role.
|
||||||
|
|
||||||
|
- In azure portal grant linked service MSI "Storage Blob Data Contributor" role of the primary adlsgen2 account of synapse workspace to use the library management feature.
|
||||||