Compare commits

...

22 Commits

Author SHA1 Message Date
amlrelsa-ms
d2a423dde9 update samples from Release-110 as a part of SDK release 2021-08-20 00:28:42 +00:00
Harneet Virk
3ecbfd6532 Merge pull request #1578 from Azure/release_update/Release-109
update samples from Release-109 as a part of  SDK release
2021-08-18 18:16:31 -07:00
amlrelsa-ms
02ecb2d755 update samples from Release-109 as a part of SDK release 2021-08-18 22:07:12 +00:00
Harneet Virk
122df6e846 Merge pull request #1576 from Azure/release_update/Release-108
update samples from Release-108 as a part of  SDK release
2021-08-18 09:47:34 -07:00
amlrelsa-ms
7d6a0a2051 update samples from Release-108 as a part of SDK release 2021-08-18 00:33:54 +00:00
Harneet Virk
6cc8af80a2 Merge pull request #1565 from Azure/release_update/Release-107
update samples from Release-107 as a part of  SDK release 1.33
2021-08-02 13:14:30 -07:00
amlrelsa-ms
f61898f718 update samples from Release-107 as a part of SDK release 2021-08-02 18:01:38 +00:00
Harneet Virk
5cb465171e Merge pull request #1556 from Azure/update-spark-notebook
updating spark notebook
2021-07-26 17:09:42 -07:00
Shivani Santosh Sambare
0ce37dd18f updating spark notebook 2021-07-26 15:51:54 -07:00
Cody
d835b183a5 update README.md (#1552) 2021-07-15 10:43:22 -07:00
Cody
d3cafebff9 add code of conduct (#1551) 2021-07-15 08:08:44 -07:00
Harneet Virk
354b194a25 Merge pull request #1543 from Azure/release_update/Release-106
update samples from Release-106 as a part of  SDK release
2021-07-06 11:05:55 -07:00
amlrelsa-ms
a52d67bb84 update samples from Release-106 as a part of SDK release 2021-07-06 17:17:27 +00:00
Harneet Virk
421ea3d920 Merge pull request #1530 from Azure/release_update/Release-105
update samples from Release-105 as a part of  SDK release
2021-06-25 09:58:05 -07:00
amlrelsa-ms
24f53f1aa1 update samples from Release-105 as a part of SDK release 2021-06-24 23:00:13 +00:00
Harneet Virk
6fc5d11de2 Merge pull request #1518 from Azure/release_update/Release-104
update samples from Release-104 as a part of  SDK release
2021-06-21 10:29:53 -07:00
amlrelsa-ms
d17547d890 update samples from Release-104 as a part of SDK release 2021-06-21 17:16:09 +00:00
Harneet Virk
928e0d4327 Merge pull request #1510 from Azure/release_update/Release-103
update samples from Release-103 as a part of  SDK release
2021-06-14 10:33:34 -07:00
amlrelsa-ms
05327cfbb9 update samples from Release-103 as a part of SDK release 2021-06-14 17:30:30 +00:00
Harneet Virk
8f7717014b Merge pull request #1506 from Azure/release_update/Release-102
update samples from Release-102 as a part of  SDK release 1.30.0
2021-06-07 11:14:02 -07:00
amlrelsa-ms
a47e50b79a update samples from Release-102 as a part of SDK release 2021-06-07 17:34:51 +00:00
Harneet Virk
8f89d88def Merge pull request #1505 from Azure/release_update/Release-101
update samples from Release-101 as a part of  SDK release
2021-06-04 19:54:53 -07:00
80 changed files with 3816 additions and 1249 deletions

9
CODE_OF_CONDUCT.md Normal file
View 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

View File

@@ -1,77 +1,43 @@
# Azure Machine Learning service example notebooks # Azure Machine Learning Python SDK notebooks
> a community-driven repository of examples using mlflow for tracking can be found at https://github.com/Azure/azureml-examples > a community-driven repository of examples using mlflow for tracking can be found at https://github.com/Azure/azureml-examples
This repository contains example notebooks demonstrating the [Azure Machine Learning](https://azure.microsoft.com/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. Welcome to the Azure Machine Learning Python SDK notebooks repository!
![Azure ML Workflow](https://raw.githubusercontent.com/MicrosoftDocs/azure-docs/master/articles/machine-learning/media/concept-azure-machine-learning-architecture/workflow.png) ## Getting started
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.
## Quick installation However, the notebooks can be run in any development environment with the correct `azureml` packages installed.
```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? Install the `azureml.core` Python package:
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...
* ...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: [track and monitor experiments](./how-to-use-azureml/track-and-monitor-experiments).
* ...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/ml-frameworks/pytorch/train-hyperparameter-tune-deploy-with-pytorch/train-hyperparameter-tune-deploy-with-pytorch.ipynb) and [distributed training](./how-to-use-azureml/ml-frameworks/pytorch/distributed-pytorch-with-horovod/distributed-pytorch-with-horovod.ipynb).
* ...deploy models as a realtime scoring service, first learn the basics by [deploying to Azure Container Instance](./how-to-use-azureml/deployment/deploy-to-cloud/model-register-and-deploy.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: [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 ML and DL frameworks](./how-to-use-azureml/ml-frameworks) - Examples demonstrating how to build and train machine learning models at scale on Azure ML and perform hyperparameter tuning.
- [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
- [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:
- [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 Microsoft 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
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/README.png)" pip install azureml-core
``` ```
This URL will be slightly different depending on the file.
![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/README.png) 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)

View File

@@ -103,7 +103,7 @@
"source": [ "source": [
"import azureml.core\n", "import azureml.core\n",
"\n", "\n",
"print(\"This notebook was created using version 1.29.0 of the Azure ML SDK\")\n", "print(\"This notebook was created using version 1.33.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\")"
] ]
}, },

View File

@@ -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` (v0.5.0 will work with minor modifications)\n", "* `fairlearn>=0.6.2` (pre-v0.5.0 will work with minor modifications)\n",
"* `joblib`\n", "* `joblib`\n",
"* `liac-arff`\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:"
] ]
@@ -85,7 +86,7 @@
"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",
"\n", "\n",
"from sklearn.compose import ColumnTransformer\n", "from sklearn.compose import ColumnTransformer\n",
"from sklearn.impute import SimpleImputer\n", "from sklearn.impute import SimpleImputer\n",
@@ -256,7 +257,7 @@
"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)})"
] ]
@@ -311,8 +312,8 @@
"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",
"# For Fairlearn v0.5.0, need sweep.predictors_\n", "# For Fairlearn pre-v0.5.0, need sweep._predictors\n",
"predictors = sweep._predictors" "predictors = sweep.predictors_"
] ]
}, },
{ {
@@ -329,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",
@@ -387,8 +386,7 @@
"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)"
] ]
@@ -409,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",

View File

@@ -3,6 +3,7 @@ dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- azureml-contrib-fairness - azureml-contrib-fairness
- fairlearn==0.4.6 - fairlearn>=0.6.2
- joblib - joblib
- liac-arff - liac-arff
- raiwidgets~=0.7.0

View File

@@ -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` (should also work with v0.5.0)\n", "* `fairlearn>=0.6.2` (also works for pre-v0.5.0 with slight modifications)\n",
"* `joblib`\n", "* `joblib`\n",
"* `liac-arff`\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:"
] ]
@@ -388,10 +389,9 @@
"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)"
] ]
@@ -403,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",

View File

@@ -3,6 +3,7 @@ dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- azureml-contrib-fairness - azureml-contrib-fairness
- fairlearn==0.4.6 - fairlearn>=0.6.2
- joblib - joblib
- liac-arff - liac-arff
- raiwidgets~=0.7.0

View File

@@ -2,7 +2,7 @@ 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==20.2.4 - pip==21.1.2
- python>=3.5.2,<3.8 - python>=3.5.2,<3.8
- nb_conda - nb_conda
- boto3==1.15.18 - boto3==1.15.18
@@ -21,8 +21,9 @@ dependencies:
- pip: - pip:
# Required packages for AzureML execution, history, and data preparation. # Required packages for AzureML execution, history, and data preparation.
- azureml-widgets~=1.29.0 - azureml-widgets~=1.33.0
- 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://automlresources-prod.azureedge.net/validated-requirements/1.29.0/validated_win32_requirements.txt [--no-deps] - -r https://automlresources-prod.azureedge.net/validated-requirements/1.33.0/validated_win32_requirements.txt [--no-deps]
- arch==4.14

View File

@@ -2,7 +2,7 @@ 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==20.2.4 - pip==21.1.2
- python>=3.5.2,<3.8 - python>=3.5.2,<3.8
- nb_conda - nb_conda
- boto3==1.15.18 - boto3==1.15.18
@@ -21,8 +21,9 @@ dependencies:
- pip: - pip:
# Required packages for AzureML execution, history, and data preparation. # Required packages for AzureML execution, history, and data preparation.
- azureml-widgets~=1.29.0 - azureml-widgets~=1.33.0
- 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://automlresources-prod.azureedge.net/validated-requirements/1.29.0/validated_linux_requirements.txt [--no-deps] - -r https://automlresources-prod.azureedge.net/validated-requirements/1.33.0/validated_linux_requirements.txt [--no-deps]
- arch==4.14

View File

@@ -2,7 +2,7 @@ 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==20.2.4 - pip==21.1.2
- nomkl - nomkl
- python>=3.5.2,<3.8 - python>=3.5.2,<3.8
- nb_conda - nb_conda
@@ -22,8 +22,9 @@ dependencies:
- pip: - pip:
# Required packages for AzureML execution, history, and data preparation. # Required packages for AzureML execution, history, and data preparation.
- azureml-widgets~=1.29.0 - azureml-widgets~=1.33.0
- 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://automlresources-prod.azureedge.net/validated-requirements/1.29.0/validated_darwin_requirements.txt [--no-deps] - -r https://automlresources-prod.azureedge.net/validated-requirements/1.33.0/validated_darwin_requirements.txt [--no-deps]
- arch==4.14

View File

@@ -86,7 +86,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",
"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 import ExplanationClient" "from azureml.interpret import ExplanationClient"
@@ -105,7 +104,7 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"print(\"This notebook was created using version 1.29.0 of the Azure ML SDK\")\n", "print(\"This notebook was created using version 1.33.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\")"
] ]
}, },
@@ -190,7 +189,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",
@@ -599,27 +598,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",
@@ -708,14 +701,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(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",
@@ -792,7 +783,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",
@@ -832,7 +822,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",

View File

@@ -93,7 +93,7 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"print(\"This notebook was created using version 1.29.0 of the Azure ML SDK\")\n", "print(\"This notebook was created using version 1.33.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\")"
] ]
}, },

View File

@@ -96,7 +96,7 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"print(\"This notebook was created using version 1.29.0 of the Azure ML SDK\")\n", "print(\"This notebook was created using version 1.33.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\")"
] ]
}, },
@@ -162,7 +162,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_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",

View File

@@ -81,7 +81,7 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"print(\"This notebook was created using version 1.29.0 of the Azure ML SDK\")\n", "print(\"This notebook was created using version 1.33.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\")"
] ]
}, },
@@ -166,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",

View File

@@ -49,6 +49,8 @@ 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)
@@ -58,9 +60,9 @@ 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=4) 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:

View File

@@ -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": [
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/experimental/classification-credit-card-fraud/auto-ml-classification-credit-card-fraud.png)"
]
},
{
"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.33.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
}

View File

@@ -0,0 +1,4 @@
name: auto-ml-classification-credit-card-fraud-local-managed
dependencies:
- pip:
- azureml-sdk

View File

@@ -91,7 +91,7 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"print(\"This notebook was created using version 1.29.0 of the Azure ML SDK\")\n", "print(\"This notebook was created using version 1.33.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\")"
] ]
}, },
@@ -143,7 +143,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",

View File

@@ -113,7 +113,7 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"print(\"This notebook was created using version 1.29.0 of the Azure ML SDK\")\n", "print(\"This notebook was created using version 1.33.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\")"
] ]
}, },
@@ -187,7 +187,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",
@@ -372,7 +372,8 @@
" freq='MS' # Set the forecast frequency to be monthly (start of the month)\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",
"automl_config = AutoMLConfig(task='forecasting',\n",
" primary_metric='normalized_root_mean_squared_error',\n", " primary_metric='normalized_root_mean_squared_error',\n",
" experiment_timeout_hours = 1,\n", " experiment_timeout_hours = 1,\n",
" training_data=train_dataset,\n", " training_data=train_dataset,\n",
@@ -383,6 +384,7 @@
" max_concurrent_iterations=4,\n", " max_concurrent_iterations=4,\n",
" max_cores_per_iteration=-1,\n", " max_cores_per_iteration=-1,\n",
" enable_dnn=True,\n", " enable_dnn=True,\n",
" enable_early_stopping=False,\n",
" forecasting_parameters=forecasting_parameters)" " forecasting_parameters=forecasting_parameters)"
] ]
}, },
@@ -662,7 +664,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,

View File

@@ -87,7 +87,7 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"print(\"This notebook was created using version 1.29.0 of the Azure ML SDK\")\n", "print(\"This notebook was created using version 1.33.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\")"
] ]
}, },
@@ -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",

View File

@@ -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.29.0 of the Azure ML SDK\")\n", "print(\"This notebook was created using version 1.33.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\")"
] ]
}, },
@@ -177,7 +179,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",
@@ -309,7 +311,7 @@
"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",
@@ -451,9 +453,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."
] ]
}, },
{ {
@@ -462,16 +466,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."
] ]
}, },
{ {
@@ -480,10 +483,16 @@
"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", "remote_run_infer = run_remote_inference(test_experiment=test_experiment,\n",
"# and helps align the forecast to the original data\n", " compute_target=compute_target,\n",
"y_predictions, X_trans = fitted_model.forecast(X_test)" " train_run=best_run,\n",
" test_dataset=test,\n",
" target_column_name=target_column_name)\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')"
] ]
}, },
{ {
@@ -491,9 +500,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). 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", "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."
] ]
}, },
{ {
@@ -502,9 +509,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()"
] ]
}, },
{ {
@@ -519,8 +526,8 @@
"\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",
"print(\"[Test data scores]\\n\")\n", "print(\"[Test data scores]\\n\")\n",
@@ -529,8 +536,8 @@
" \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(fcst_df[target_column_name], fcst_df[target_column_name], color='g')\n",
"plt.legend((test_pred, test_test), ('prediction', 'truth'), loc='upper left', fontsize=8)\n", "plt.legend((test_pred, test_test), ('prediction', 'truth'), loc='upper left', fontsize=8)\n",
"plt.show()" "plt.show()"
] ]
@@ -539,23 +546,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."
] ]
}, },
@@ -638,7 +629,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."
] ]
}, },
@@ -648,10 +639,17 @@
"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(test_experiment=test_experiment_advanced,\n",
"# and helps align the forecast to the original data\n", " compute_target=compute_target,\n",
"y_predictions, X_trans = fitted_model_lags.forecast(X_test)" " train_run=best_run_lags,\n",
" test_dataset=test,\n",
" target_column_name=target_column_name,\n",
" inference_folder='./forecast_advanced')\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('outputs/predictions.csv', 'predictions_advanced.csv')"
] ]
}, },
{ {
@@ -660,9 +658,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)"
] ]
}, },
{ {
@@ -677,8 +674,8 @@
"\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",
"print(\"[Test data scores]\\n\")\n", "print(\"[Test data scores]\\n\")\n",
@@ -687,8 +684,8 @@
" \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_adv_df[target_column_name], fcst_adv_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(fcst_adv_df[target_column_name], fcst_adv_df[target_column_name], color='g')\n",
"plt.legend((test_pred, test_test), ('prediction', 'truth'), loc='upper left', fontsize=8)\n", "plt.legend((test_pred, test_test), ('prediction', 'truth'), loc='upper left', fontsize=8)\n",
"plt.show()" "plt.show()"
] ]
@@ -719,7 +716,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,

View File

@@ -1,5 +1,15 @@
"""
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
import pandas as pd import pandas as pd
import numpy as np import numpy as np
from azureml.core import Dataset, Run
from azureml.automl.core.shared.constants import TimeSeriesInternal
from sklearn.externals import joblib
from pandas.tseries.frequencies import to_offset from pandas.tseries.frequencies import to_offset
@@ -42,3 +52,38 @@ def align_outputs(y_predicted, X_trans, X_test, y_test, target_column_name,
clean = together[together[[target_column_name, clean = together[together[[target_column_name,
predicted_column_name]].notnull().all(axis=1)] predicted_column_name]].notnull().all(axis=1)]
return(clean) return(clean)
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')
y_predictions, X_trans = fitted_model.forecast(X_test)
# align output
df_all = align_outputs(y_predictions, X_trans, X_test, y_test, target_column_name)
file_name = 'outputs/predictions.csv'
export_csv = df_all.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)

View File

@@ -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))

View File

@@ -0,0 +1,38 @@
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

View File

@@ -94,7 +94,7 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"print(\"This notebook was created using version 1.29.0 of the Azure ML SDK\")\n", "print(\"This notebook was created using version 1.33.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\")"
] ]
}, },
@@ -285,7 +285,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=6)\n", " max_nodes=6)\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",

View File

@@ -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.29.0 of the Azure ML SDK\")\n", "print(\"This notebook was created using version 1.33.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\")"
] ]
}, },
@@ -122,7 +121,7 @@
"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", "\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", "> 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",
@@ -149,7 +148,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_D12_V2',\n",
" max_nodes=6)\n", " max_nodes=6)\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",
@@ -160,7 +159,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."
] ]
}, },
@@ -287,7 +286,8 @@
"outputs": [], "outputs": [],
"source": [ "source": [
"from azureml.core.dataset import Dataset\n", "from azureml.core.dataset import Dataset\n",
"train_dataset = Dataset.Tabular.from_delimited_files(path=datastore.path('dataset/dominicks_OJ_train.csv'))" "train_dataset = Dataset.Tabular.from_delimited_files(path=datastore.path('dataset/dominicks_OJ_train.csv'))\n",
"test_dataset = Dataset.Tabular.from_delimited_files(path=datastore.path('dataset/dominicks_OJ_test.csv'))"
] ]
}, },
{ {
@@ -380,7 +380,7 @@
"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",
@@ -521,9 +521,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."
] ]
}, },
{ {
@@ -532,17 +534,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."
] ]
}, },
{ {
@@ -558,18 +558,16 @@
"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", "remote_run_infer = run_remote_inference(test_experiment=test_experiment, \n",
"y_predictions, X_trans = fitted_model.forecast(X_test)" " compute_target=compute_target,\n",
] " train_run=best_run,\n",
}, " test_dataset=test_dataset,\n",
{ " target_column_name=target_column_name)\n",
"cell_type": "markdown", "remote_run_infer.wait_for_completion(show_output=False)\n",
"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)." "# download the forecast file to the local machine\n",
"remote_run_infer.download_file('outputs/predictions.csv', 'predictions.csv')"
] ]
}, },
{ {
@@ -589,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()"
] ]
}, },
{ {
@@ -605,8 +604,8 @@
"\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",
"print(\"[Test data scores]\\n\")\n", "print(\"[Test data scores]\\n\")\n",
@@ -615,8 +614,8 @@
" \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(fcst_df[target_column_name], fcst_df[target_column_name], color='g')\n",
"plt.legend((test_pred, test_test), ('prediction', 'truth'), loc='upper left', fontsize=8)\n", "plt.legend((test_pred, test_test), ('prediction', 'truth'), loc='upper left', fontsize=8)\n",
"plt.show()" "plt.show()"
] ]
@@ -625,7 +624,7 @@
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {}, "metadata": {},
"source": [ "source": [
"# Operationalize" "# Operationalize<a id=\"operationalize\"></a>"
] ]
}, },
{ {
@@ -688,8 +687,8 @@
"inference_config = InferenceConfig(environment = best_run.get_environment(), \n", "inference_config = InferenceConfig(environment = best_run.get_environment(), \n",
" entry_script = script_file_name)\n", " 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 = 2, \n", " memory_gb = 4, \n",
" tags = {'type': \"automl-forecasting\"},\n", " tags = {'type': \"automl-forecasting\"},\n",
" description = \"Automl forecasting sample service\")\n", " description = \"Automl forecasting sample service\")\n",
"\n", "\n",
@@ -723,12 +722,13 @@
"outputs": [], "outputs": [],
"source": [ "source": [
"import json\n", "import json\n",
"X_query = X_test.copy()\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", "test_sample = json.dumps({\"data\": json.loads(X_query.to_json(orient=\"records\"))})\n",
"response = aci_service.run(input_data = test_sample)\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",
@@ -805,7 +805,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"

View File

@@ -0,0 +1,89 @@
"""
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
import pandas as pd
import numpy as np
from azureml.core import Dataset, Run
from azureml.automl.core.shared.constants import TimeSeriesInternal
from sklearn.externals import joblib
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)
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')
y_predictions, X_trans = fitted_model.forecast(X_test)
# align output
df_all = align_outputs(y_predictions, X_trans, X_test, y_test, target_column_name)
file_name = 'outputs/predictions.csv'
export_csv = df_all.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)

View File

@@ -0,0 +1,38 @@
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

View File

@@ -0,0 +1,492 @@
{
"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": [
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/forecasting-recipes-univariate/1_determine_experiment_settings.png)"
]
},
{
"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",
"![Forecasting after training](figures/univariate_settings_map_20210408.jpg)\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",
"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",
"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
}

View File

@@ -0,0 +1,4 @@
name: auto-ml-forecasting-univariate-recipe-experiment-settings
dependencies:
- pip:
- azureml-sdk

View File

@@ -0,0 +1,560 @@
{
"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": [
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/forecasting-recipes-univariate/2_run_experiment.png)"
]
},
{
"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(vm_size = \"STANDARD_D2_V2\",\n",
" max_nodes = 6)\n",
"\n",
" # Create the cluster.\\n\",\n",
" compute_target = ComputeTarget.create(ws, amlcompute_cluster_name, provisioning_config)\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(show_output = True, min_node_count = None, timeout_in_minutes = 20)"
]
},
{
"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 = '2020-03-01' # start of the covid period. To be excluded from evaluation.\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 = '-'.join(map(str, TARGET_LAGS)) if (len(TARGET_LAGS) > 0) else None\n",
"else:\n",
" TARGET_LAGS_STR = TARGET_LAGS\n",
"\n",
"experiment_desc = 'diff-{}_lags-{}_STL-{}'.format(DIFFERENCE_SERIES, TARGET_LAGS_STR, STL_TYPE)\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(df_input=df_delta,\n",
" n=FORECAST_HORIZON,\n",
" time_colname=TIME_COLNAME,\n",
" ts_id_colnames=TIME_SERIES_ID_COLNAMES)\n",
"else:\n",
" df_train, df_test = ts_train_test_split(df_input=df,\n",
" n=FORECAST_HORIZON,\n",
" time_colname=TIME_COLNAME,\n",
" ts_id_colnames=TIME_SERIES_ID_COLNAMES)"
]
},
{
"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(files = ['./train.csv'], target_path = 'uni-recipe-dataset/tabular/', overwrite = True,show_progress = True)\n",
"datastore.upload_files(files = ['./test.csv'], target_path = 'uni-recipe-dataset/tabular/', overwrite = True,show_progress = True)\n",
"\n",
"from azureml.core import Dataset\n",
"train_dataset = Dataset.Tabular.from_delimited_files(path = [(datastore, 'uni-recipe-dataset/tabular/train.csv')])\n",
"test_dataset = Dataset.Tabular.from_delimited_files(path = [(datastore, 'uni-recipe-dataset/tabular/test.csv')])\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(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)"
]
},
{
"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",
"remote_run = run_remote_inference(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",
"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(fcst,\n",
" df_orig[[TIME_COLNAME, TARGET_COLNAME]], \n",
" on=[TIME_COLNAME], how='inner')\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,\n",
" metric_name=None,\n",
" 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
}

View File

@@ -0,0 +1,4 @@
name: auto-ml-forecasting-univariate-recipe-run-experiment
dependencies:
- pip:
- azureml-sdk

View File

@@ -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
1 observation_date S4248SM144SCEN
2 1992-01-01 4302
3 1992-02-01 4323
4 1992-03-01 4199
5 1992-04-01 4397
6 1992-05-01 4159
7 1992-06-01 4091
8 1992-07-01 4109
9 1992-08-01 4116
10 1992-09-01 4093
11 1992-10-01 4095
12 1992-11-01 4169
13 1992-12-01 4169
14 1993-01-01 4124
15 1993-02-01 4107
16 1993-03-01 4168
17 1993-04-01 4254
18 1993-05-01 4290
19 1993-06-01 4163
20 1993-07-01 4274
21 1993-08-01 4253
22 1993-09-01 4312
23 1993-10-01 4296
24 1993-11-01 4221
25 1993-12-01 4233
26 1994-01-01 4218
27 1994-02-01 4237
28 1994-03-01 4343
29 1994-04-01 4357
30 1994-05-01 4264
31 1994-06-01 4392
32 1994-07-01 4381
33 1994-08-01 4290
34 1994-09-01 4348
35 1994-10-01 4357
36 1994-11-01 4417
37 1994-12-01 4411
38 1995-01-01 4417
39 1995-02-01 4339
40 1995-03-01 4256
41 1995-04-01 4276
42 1995-05-01 4290
43 1995-06-01 4413
44 1995-07-01 4305
45 1995-08-01 4476
46 1995-09-01 4393
47 1995-10-01 4447
48 1995-11-01 4492
49 1995-12-01 4489
50 1996-01-01 4635
51 1996-02-01 4697
52 1996-03-01 4588
53 1996-04-01 4633
54 1996-05-01 4685
55 1996-06-01 4672
56 1996-07-01 4666
57 1996-08-01 4726
58 1996-09-01 4571
59 1996-10-01 4624
60 1996-11-01 4691
61 1996-12-01 4604
62 1997-01-01 4657
63 1997-02-01 4711
64 1997-03-01 4810
65 1997-04-01 4626
66 1997-05-01 4860
67 1997-06-01 4757
68 1997-07-01 4916
69 1997-08-01 4921
70 1997-09-01 4985
71 1997-10-01 4905
72 1997-11-01 4880
73 1997-12-01 5165
74 1998-01-01 4885
75 1998-02-01 4925
76 1998-03-01 5049
77 1998-04-01 5090
78 1998-05-01 5094
79 1998-06-01 4929
80 1998-07-01 5132
81 1998-08-01 5061
82 1998-09-01 5471
83 1998-10-01 5327
84 1998-11-01 5257
85 1998-12-01 5354
86 1999-01-01 5427
87 1999-02-01 5415
88 1999-03-01 5387
89 1999-04-01 5483
90 1999-05-01 5510
91 1999-06-01 5539
92 1999-07-01 5532
93 1999-08-01 5625
94 1999-09-01 5799
95 1999-10-01 5843
96 1999-11-01 5836
97 1999-12-01 5724
98 2000-01-01 5757
99 2000-02-01 5731
100 2000-03-01 5839
101 2000-04-01 5825
102 2000-05-01 5877
103 2000-06-01 5979
104 2000-07-01 5828
105 2000-08-01 6016
106 2000-09-01 6113
107 2000-10-01 6150
108 2000-11-01 6111
109 2000-12-01 6088
110 2001-01-01 6360
111 2001-02-01 6300
112 2001-03-01 5935
113 2001-04-01 6204
114 2001-05-01 6164
115 2001-06-01 6231
116 2001-07-01 6336
117 2001-08-01 6179
118 2001-09-01 6120
119 2001-10-01 6134
120 2001-11-01 6381
121 2001-12-01 6521
122 2002-01-01 6333
123 2002-02-01 6541
124 2002-03-01 6692
125 2002-04-01 6591
126 2002-05-01 6554
127 2002-06-01 6596
128 2002-07-01 6620
129 2002-08-01 6577
130 2002-09-01 6625
131 2002-10-01 6441
132 2002-11-01 6584
133 2002-12-01 6923
134 2003-01-01 6600
135 2003-02-01 6742
136 2003-03-01 6831
137 2003-04-01 6782
138 2003-05-01 6714
139 2003-06-01 6736
140 2003-07-01 7146
141 2003-08-01 7027
142 2003-09-01 6896
143 2003-10-01 7107
144 2003-11-01 6997
145 2003-12-01 7075
146 2004-01-01 7235
147 2004-02-01 7072
148 2004-03-01 6968
149 2004-04-01 7144
150 2004-05-01 7232
151 2004-06-01 7095
152 2004-07-01 7181
153 2004-08-01 7146
154 2004-09-01 7230
155 2004-10-01 7327
156 2004-11-01 7328
157 2004-12-01 7425
158 2005-01-01 7520
159 2005-02-01 7551
160 2005-03-01 7572
161 2005-04-01 7701
162 2005-05-01 7819
163 2005-06-01 7770
164 2005-07-01 7627
165 2005-08-01 7816
166 2005-09-01 7718
167 2005-10-01 7772
168 2005-11-01 7788
169 2005-12-01 7576
170 2006-01-01 7940
171 2006-02-01 8027
172 2006-03-01 7884
173 2006-04-01 8043
174 2006-05-01 7995
175 2006-06-01 8218
176 2006-07-01 8159
177 2006-08-01 8331
178 2006-09-01 8320
179 2006-10-01 8397
180 2006-11-01 8603
181 2006-12-01 8515
182 2007-01-01 8336
183 2007-02-01 8233
184 2007-03-01 8475
185 2007-04-01 8310
186 2007-05-01 8583
187 2007-06-01 8645
188 2007-07-01 8713
189 2007-08-01 8636
190 2007-09-01 8791
191 2007-10-01 8984
192 2007-11-01 8867
193 2007-12-01 9059
194 2008-01-01 8911
195 2008-02-01 8701
196 2008-03-01 8956
197 2008-04-01 9095
198 2008-05-01 9102
199 2008-06-01 9170
200 2008-07-01 9194
201 2008-08-01 9164
202 2008-09-01 9337
203 2008-10-01 9186
204 2008-11-01 9029
205 2008-12-01 9025
206 2009-01-01 9486
207 2009-02-01 9219
208 2009-03-01 9059
209 2009-04-01 9171
210 2009-05-01 9114
211 2009-06-01 8926
212 2009-07-01 9150
213 2009-08-01 9105
214 2009-09-01 9011
215 2009-10-01 8743
216 2009-11-01 8958
217 2009-12-01 8969
218 2010-01-01 8984
219 2010-02-01 9068
220 2010-03-01 9335
221 2010-04-01 9481
222 2010-05-01 9132
223 2010-06-01 9192
224 2010-07-01 9123
225 2010-08-01 9091
226 2010-09-01 9155
227 2010-10-01 9556
228 2010-11-01 9477
229 2010-12-01 9436
230 2011-01-01 9519
231 2011-02-01 9667
232 2011-03-01 9668
233 2011-04-01 9628
234 2011-05-01 9376
235 2011-06-01 9830
236 2011-07-01 9626
237 2011-08-01 9802
238 2011-09-01 9858
239 2011-10-01 9838
240 2011-11-01 9846
241 2011-12-01 9789
242 2012-01-01 9955
243 2012-02-01 9909
244 2012-03-01 9897
245 2012-04-01 9909
246 2012-05-01 10127
247 2012-06-01 10175
248 2012-07-01 10129
249 2012-08-01 10251
250 2012-09-01 10227
251 2012-10-01 10174
252 2012-11-01 10402
253 2012-12-01 10664
254 2013-01-01 10585
255 2013-02-01 10661
256 2013-03-01 10649
257 2013-04-01 10676
258 2013-05-01 10863
259 2013-06-01 10690
260 2013-07-01 11007
261 2013-08-01 10835
262 2013-09-01 10900
263 2013-10-01 10749
264 2013-11-01 10946
265 2013-12-01 10864
266 2014-01-01 10726
267 2014-02-01 10821
268 2014-03-01 10789
269 2014-04-01 10892
270 2014-05-01 10892
271 2014-06-01 10789
272 2014-07-01 10662
273 2014-08-01 10767
274 2014-09-01 10779
275 2014-10-01 10922
276 2014-11-01 10662
277 2014-12-01 10808
278 2015-01-01 10865
279 2015-02-01 10740
280 2015-03-01 10917
281 2015-04-01 10933
282 2015-05-01 11074
283 2015-06-01 11108
284 2015-07-01 11493
285 2015-08-01 11386
286 2015-09-01 11502
287 2015-10-01 11487
288 2015-11-01 11375
289 2015-12-01 11445
290 2016-01-01 11787
291 2016-02-01 11792
292 2016-03-01 11649
293 2016-04-01 11810
294 2016-05-01 11496
295 2016-06-01 11600
296 2016-07-01 11503
297 2016-08-01 11715
298 2016-09-01 11732
299 2016-10-01 11885
300 2016-11-01 12092
301 2016-12-01 11857
302 2017-01-01 11881
303 2017-02-01 12355
304 2017-03-01 12027
305 2017-04-01 12183
306 2017-05-01 12170
307 2017-06-01 12387
308 2017-07-01 12041
309 2017-08-01 12139
310 2017-09-01 11861
311 2017-10-01 12202
312 2017-11-01 12178
313 2017-12-01 12126
314 2018-01-01 11942
315 2018-02-01 12206
316 2018-03-01 12362
317 2018-04-01 12287
318 2018-05-01 12497
319 2018-06-01 12621
320 2018-07-01 12729
321 2018-08-01 12689
322 2018-09-01 12874
323 2018-10-01 12776
324 2018-11-01 12995
325 2018-12-01 13291
326 2019-01-01 13364
327 2019-02-01 13135
328 2019-03-01 13123
329 2019-04-01 13110
330 2019-05-01 13152
331 2019-06-01 13201
332 2019-07-01 13354
333 2019-08-01 13427
334 2019-09-01 13472
335 2019-10-01 13436
336 2019-11-01 13430
337 2019-12-01 13588
338 2020-01-01 13533
339 2020-02-01 13575
340 2020-03-01 13867
341 2020-04-01 12319
342 2020-05-01 13909
343 2020-06-01 13982
344 2020-07-01 15384
345 2020-08-01 15701
346 2020-09-01 15006
347 2020-10-01 15741
348 2020-11-01 14934
349 2020-12-01 13061
350 2021-01-01 15743

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

View File

@@ -0,0 +1,46 @@
"""
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_df = 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')
y_pred, X_trans = fitted_model.forecast(X_test_df)
# rename target column
X_trans.reset_index(drop=False, inplace=True)
X_trans.rename(columns={TimeSeriesInternal.DUMMY_TARGET_COLUMN: 'predicted'}, inplace=True)
X_trans['actual'] = y_test_df[target_column_name].values
file_name = 'outputs/predictions.csv'
export_csv = X_trans.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)

View File

@@ -0,0 +1,250 @@
"""
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

View File

@@ -0,0 +1,38 @@
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

View File

@@ -96,7 +96,7 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"print(\"This notebook was created using version 1.29.0 of the Azure ML SDK\")\n", "print(\"This notebook was created using version 1.33.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\")"
] ]
}, },
@@ -436,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)"
] ]
}, },
{ {
@@ -453,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",

View File

@@ -77,7 +77,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"
@@ -96,7 +95,7 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"print(\"This notebook was created using version 1.29.0 of the Azure ML SDK\")\n", "print(\"This notebook was created using version 1.33.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\")"
] ]
}, },
@@ -154,7 +153,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",
@@ -541,8 +540,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",
@@ -720,14 +717,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",

View File

@@ -50,11 +50,13 @@ X_test = test_dataset.drop_columns(columns=['<<target_column_name>>'])
# Setup the class for explaining the AutoML 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)

View File

@@ -92,7 +92,7 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"print(\"This notebook was created using version 1.29.0 of the Azure ML SDK\")\n", "print(\"This notebook was created using version 1.33.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",

View File

@@ -350,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": {},

View File

@@ -352,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": {},

View File

@@ -0,0 +1,186 @@
{
"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": [
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/azure-arcadia/Synapse_Job_Scala_Support.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Get AML workspace which has synapse spark pool attached"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.core import Workspace, Experiment, Dataset, Environment\n",
"\n",
"ws = Workspace.from_config()\n",
"print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep = '\\n')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Leverage ScriptRunConfig to submit scala job to an attached synapse spark cluster"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Prepare data"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.core.datastore import Datastore\n",
"# Use the default blob storage\n",
"def_blob_store = Datastore(ws, \"workspaceblobstore\")\n",
"\n",
"# We are uploading a sample file in the local directory to be used as a datasource\n",
"file_name = \"shakespeare.txt\"\n",
"def_blob_store.upload_files(files=[\"./{}\".format(file_name)], overwrite=False)\n",
"\n",
"# Create file dataset\n",
"file_dataset = Dataset.File.from_files(path=[(def_blob_store, file_name)])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.core.runconfig import RunConfiguration\n",
"from azureml.data import HDFSOutputDatasetConfig\n",
"import uuid\n",
"\n",
"run_config = RunConfiguration(framework=\"pyspark\")\n",
"run_config.target = \"link-pool\"\n",
"run_config.spark.configuration[\"spark.driver.memory\"] = \"2g\"\n",
"run_config.spark.configuration[\"spark.driver.cores\"] = 2\n",
"run_config.spark.configuration[\"spark.executor.memory\"] = \"2g\"\n",
"run_config.spark.configuration[\"spark.executor.cores\"] = 1\n",
"run_config.spark.configuration[\"spark.executor.instances\"] = 1\n",
"# This can be removed if you are using local jars in source folder\n",
"run_config.spark.configuration[\"spark.yarn.dist.jars\"]=\"wasbs://synapse@azuremlexamples.blob.core.windows.net/shared/wordcount.jar\"\n",
"\n",
"dir_name = \"wordcount-{}\".format(str(uuid.uuid4()))\n",
"input = file_dataset.as_named_input(\"input\").as_hdfs()\n",
"output = HDFSOutputDatasetConfig(destination=(ws.get_default_datastore(), \"{}/result\".format(dir_name)))\n",
"\n",
"from azureml.core import ScriptRunConfig\n",
"args = ['--input', input, '--output', output]\n",
"script_run_config = ScriptRunConfig(source_directory = '.',\n",
" script= 'start_script.py',\n",
" arguments= args,\n",
" run_config = run_config)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.core import Experiment\n",
"exp = Experiment(workspace=ws, name='synapse-spark')\n",
"run = exp.submit(config=script_run_config)\n",
"run"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Leverage SynapseSparkStep in an AML pipeline to add dataprep step on synapse spark cluster"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.pipeline.core import Pipeline\n",
"from azureml.pipeline.steps import SynapseSparkStep\n",
"\n",
"configs = {}\n",
"#configs[\"spark.yarn.dist.jars\"] = \"wasbs://synapse@azuremlexamples.blob.core.windows.net/shared/wordcount.jar\"\n",
"step_1 = SynapseSparkStep(name = 'synapse-spark',\n",
" file = 'start_script.py',\n",
" jars = \"wasbs://synapse@azuremlexamples.blob.core.windows.net/shared/wordcount.jar\",\n",
" source_directory=\".\",\n",
" arguments = args,\n",
" compute_target = 'link-pool',\n",
" driver_memory = \"2g\",\n",
" driver_cores = 2,\n",
" executor_memory = \"2g\",\n",
" executor_cores = 1,\n",
" num_executors = 1,\n",
" conf = configs)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"pipeline = Pipeline(workspace=ws, steps=[step_1])\n",
"pipeline_run = pipeline.submit('synapse-pipeline', regenerate_outputs=True)"
]
}
],
"metadata": {
"authors": [
{
"name": "feli1"
}
],
"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.5"
},
"nteract": {
"version": "0.28.0"
}
},
"nbformat": 4,
"nbformat_minor": 2
}

View File

@@ -0,0 +1,240 @@
{
"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": [
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/azure-arcadia/Synapse_Session_Scala_Support.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Interactive Spark Session on Synapse Spark Pool"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!pip install -U \"azureml-synapse\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"For JupyterLab, please additionally run:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!jupyter lab build --minimize=False"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## PLEASE restart kernel and then refresh web page before starting spark session."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 0. Magic Usage"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {
"iopub.execute_input": "2020-06-05T03:22:14.965395Z",
"iopub.status.busy": "2020-06-05T03:22:14.965395Z",
"iopub.status.idle": "2020-06-05T03:22:14.970398Z",
"shell.execute_reply": "2020-06-05T03:22:14.969397Z",
"shell.execute_reply.started": "2020-06-05T03:22:14.965395Z"
},
"gather": {
"logged": 1615594584642
}
},
"outputs": [],
"source": [
"# show help\n",
"%synapse ?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 1. Start Synapse Session"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"gather": {
"logged": 1615577715289
}
},
"outputs": [],
"source": [
"%synapse start -c linktestpool --start-timeout 1000"
]
},
{
"cell_type": "markdown",
"metadata": {
"nteract": {
"transient": {
"deleting": false
}
}
},
"source": [
"# 2. Use Scala"
]
},
{
"cell_type": "markdown",
"metadata": {
"nteract": {
"transient": {
"deleting": false
}
}
},
"source": [
"## (1) Read Data"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"jupyter": {
"outputs_hidden": false,
"source_hidden": false
},
"nteract": {
"transient": {
"deleting": false
}
}
},
"outputs": [],
"source": [
"%%synapse scala\n",
"\n",
"var df = spark.read.option(\"header\", \"true\").csv(\"wasbs://demo@dprepdata.blob.core.windows.net/Titanic.csv\")\n",
"df.show(5)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## (2) Use Scala Sql"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"jupyter": {
"outputs_hidden": false,
"source_hidden": false
},
"nteract": {
"transient": {
"deleting": false
}
}
},
"outputs": [],
"source": [
"%%synapse scala\n",
"\n",
"df.createOrReplaceTempView(\"titanic\")\n",
"var sqlDF = spark.sql(\"SELECT Name, Fare from titanic\")\n",
"sqlDF.show(5)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Stop Session"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"jupyter": {
"outputs_hidden": false,
"source_hidden": false
},
"nteract": {
"transient": {
"deleting": false
}
}
},
"outputs": [],
"source": [
"%synapse stop"
]
}
],
"metadata": {
"authors": [
{
"name": "feli1"
}
],
"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.5"
},
"nteract": {
"version": "0.28.0"
}
},
"nbformat": 4,
"nbformat_minor": 4
}

View File

@@ -0,0 +1,270 @@
This is the 100th Etext file presented by Project Gutenberg, and
is presented in cooperation with World Library, Inc., from their
Library of the Future and Shakespeare CDROMS. Project Gutenberg
often releases Etexts that are NOT placed in the Public Domain!!
Shakespeare
*This Etext has certain copyright implications you should read!*
<<THIS ELECTRONIC VERSION OF THE COMPLETE WORKS OF WILLIAM
SHAKESPEARE IS COPYRIGHT 1990-1993 BY WORLD LIBRARY, INC., AND IS
PROVIDED BY PROJECT GUTENBERG ETEXT OF ILLINOIS BENEDICTINE COLLEGE
WITH PERMISSION. ELECTRONIC AND MACHINE READABLE COPIES MAY BE
DISTRIBUTED SO LONG AS SUCH COPIES (1) ARE FOR YOUR OR OTHERS
PERSONAL USE ONLY, AND (2) ARE NOT DISTRIBUTED OR USED
COMMERCIALLY. PROHIBITED COMMERCIAL DISTRIBUTION INCLUDES BY ANY
SERVICE THAT CHARGES FOR DOWNLOAD TIME OR FOR MEMBERSHIP.>>
*Project Gutenberg is proud to cooperate with The World Library*
in the presentation of The Complete Works of William Shakespeare
for your reading for education and entertainment. HOWEVER, THIS
IS NEITHER SHAREWARE NOR PUBLIC DOMAIN. . .AND UNDER THE LIBRARY
OF THE FUTURE CONDITIONS OF THIS PRESENTATION. . .NO CHARGES MAY
BE MADE FOR *ANY* ACCESS TO THIS MATERIAL. YOU ARE ENCOURAGED!!
TO GIVE IT AWAY TO ANYONE YOU LIKE, BUT NO CHARGES ARE ALLOWED!!
**Welcome To The World of Free Plain Vanilla Electronic Texts**
**Etexts Readable By Both Humans and By Computers, Since 1971**
*These Etexts Prepared By Hundreds of Volunteers and Donations*
Information on contacting Project Gutenberg to get Etexts, and
further information is included below. We need your donations.
The Complete Works of William Shakespeare
January, 1994 [Etext #100]
The Library of the Future Complete Works of William Shakespeare
Library of the Future is a TradeMark (TM) of World Library Inc.
******This file should be named shaks12.txt or shaks12.zip*****
Corrected EDITIONS of our etexts get a new NUMBER, shaks13.txt
VERSIONS based on separate sources get new LETTER, shaks10a.txt
If you would like further information about World Library, Inc.
Please call them at 1-800-443-0238 or email julianc@netcom.com
Please give them our thanks for their Shakespeare cooperation!
The official release date of all Project Gutenberg Etexts is at
Midnight, Central Time, of the last day of the stated month. A
preliminary version may often be posted for suggestion, comment
and editing by those who wish to do so. To be sure you have an
up to date first edition [xxxxx10x.xxx] please check file sizes
in the first week of the next month. Since our ftp program has
a bug in it that scrambles the date [tried to fix and failed] a
look at the file size will have to do, but we will try to see a
new copy has at least one byte more or less.
Information about Project Gutenberg (one page)
We produce about two million dollars for each hour we work. The
fifty hours is one conservative estimate for how long it we take
to get any etext selected, entered, proofread, edited, copyright
searched and analyzed, the copyright letters written, etc. This
projected audience is one hundred million readers. If our value
per text is nominally estimated at one dollar, then we produce 2
million dollars per hour this year we, will have to do four text
files per month: thus upping our productivity from one million.
The Goal of Project Gutenberg is to Give Away One Trillion Etext
Files by the December 31, 2001. [10,000 x 100,000,000=Trillion]
This is ten thousand titles each to one hundred million readers,
which is 10% of the expected number of computer users by the end
of the year 2001.
We need your donations more than ever!
All donations should be made to "Project Gutenberg/IBC", and are
tax deductible to the extent allowable by law ("IBC" is Illinois
Benedictine College). (Subscriptions to our paper newsletter go
to IBC, too)
For these and other matters, please mail to:
Project Gutenberg
P. O. Box 2782
Champaign, IL 61825
When all other email fails try our Michael S. Hart, Executive Director:
hart@vmd.cso.uiuc.edu (internet) hart@uiucvmd (bitnet)
We would prefer to send you this information by email
(Internet, Bitnet, Compuserve, ATTMAIL or MCImail).
******
If you have an FTP program (or emulator), please
FTP directly to the Project Gutenberg archives:
[Mac users, do NOT point and click. . .type]
ftp mrcnext.cso.uiuc.edu
login: anonymous
password: your@login
cd etext/etext91
or cd etext92
or cd etext93 [for new books] [now also in cd etext/etext93]
or cd etext/articles [get suggest gut for more information]
dir [to see files]
get or mget [to get files. . .set bin for zip files]
GET 0INDEX.GUT
for a list of books
and
GET NEW GUT for general information
and
MGET GUT* for newsletters.
**Information prepared by the Project Gutenberg legal advisor**
***** SMALL PRINT! for COMPLETE SHAKESPEARE *****
THIS ELECTRONIC VERSION OF THE COMPLETE WORKS OF WILLIAM
SHAKESPEARE IS COPYRIGHT 1990-1993 BY WORLD LIBRARY, INC.,
AND IS PROVIDED BY PROJECT GUTENBERG ETEXT OF
ILLINOIS BENEDICTINE COLLEGE WITH PERMISSION.
Since unlike many other Project Gutenberg-tm etexts, this etext
is copyright protected, and since the materials and methods you
use will effect the Project's reputation, your right to copy and
distribute it is limited by the copyright and other laws, and by
the conditions of this "Small Print!" statement.
1. LICENSE
A) YOU MAY (AND ARE ENCOURAGED) TO DISTRIBUTE ELECTRONIC AND
MACHINE READABLE COPIES OF THIS ETEXT, SO LONG AS SUCH COPIES
(1) ARE FOR YOUR OR OTHERS PERSONAL USE ONLY, AND (2) ARE NOT
DISTRIBUTED OR USED COMMERCIALLY. PROHIBITED COMMERCIAL
DISTRIBUTION INCLUDES BY ANY SERVICE THAT CHARGES FOR DOWNLOAD
TIME OR FOR MEMBERSHIP.
B) This license is subject to the conditions that you honor
the refund and replacement provisions of this "small print!"
statement; and that you distribute exact copies of this etext,
including this Small Print statement. Such copies can be
compressed or any proprietary form (including any form resulting
from word processing or hypertext software), so long as
*EITHER*:
(1) The etext, when displayed, is clearly readable, and does
*not* contain characters other than those intended by the
author of the work, although tilde (~), asterisk (*) and
underline (_) characters may be used to convey punctuation
intended by the author, and additional characters may be used
to indicate hypertext links; OR
(2) The etext is readily convertible by the reader at no
expense into plain ASCII, EBCDIC or equivalent form by the
program that displays the etext (as is the case, for instance,
with most word processors); OR
(3) You provide or agree to provide on request at no
additional cost, fee or expense, a copy of the etext in plain
ASCII.
2. LIMITED WARRANTY; DISCLAIMER OF DAMAGES
This etext may contain a "Defect" in the form of incomplete,
inaccurate or corrupt data, transcription errors, a copyright or
other infringement, a defective or damaged disk, computer virus,
or codes that damage or cannot be read by your equipment. But
for the "Right of Replacement or Refund" described below, the
Project (and any other party you may receive this etext from as
a PROJECT GUTENBERG-tm etext) disclaims all liability to you for
damages, costs and expenses, including legal fees, and YOU HAVE
NO REMEDIES FOR NEGLIGENCE OR UNDER STRICT LIABILITY, OR FOR
BREACH OF WARRANTY OR CONTRACT, INCLUDING BUT NOT LIMITED TO
INDIRECT, CONSEQUENTIAL, PUNITIVE OR INCIDENTAL DAMAGES, EVEN IF
YOU GIVE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES.
If you discover a Defect in this etext within 90 days of receiv-
ing it, you can receive a refund of the money (if any) you paid
for it by sending an explanatory note within that time to the
person you received it from. If you received it on a physical
medium, you must return it with your note, and such person may
choose to alternatively give you a replacement copy. If you
received it electronically, such person may choose to
alternatively give you a second opportunity to receive it
electronically.
THIS ETEXT IS OTHERWISE PROVIDED TO YOU "AS-IS". NO OTHER
WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED, ARE MADE TO YOU AS
TO THE ETEXT OR ANY MEDIUM IT MAY BE ON, INCLUDING BUT NOT
LIMITED TO WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A
PARTICULAR PURPOSE. Some states do not allow disclaimers of
implied warranties or the exclusion or limitation of consequen-
tial damages, so the above disclaimers and exclusions may not
apply to you, and you may have other legal rights.
3. INDEMNITY: You will indemnify and hold the Project, its
directors, officers, members and agents harmless from all lia-
bility, cost and expense, including legal fees, that arise
directly or indirectly from any of the following that you do or
cause: [A] distribution of this etext, [B] alteration,
modification, or addition to the etext, or [C] any Defect.
4. WHAT IF YOU *WANT* TO SEND MONEY EVEN IF YOU DON'T HAVE TO?
Project Gutenberg is dedicated to increasing the number of
public domain and licensed works that can be freely distributed
in machine readable form. The Project gratefully accepts
contributions in money, time, scanning machines, OCR software,
public domain etexts, royalty free copyright licenses, and
whatever else you can think of. Money should be paid to "Pro-
ject Gutenberg Association / Illinois Benedictine College".
WRITE TO US! We can be reached at:
Internet: hart@vmd.cso.uiuc.edu
Bitnet: hart@uiucvmd
CompuServe: >internet:hart@.vmd.cso.uiuc.edu
Attmail: internet!vmd.cso.uiuc.edu!Hart
Mail: Prof. Michael Hart
P.O. Box 2782
Champaign, IL 61825
This "Small Print!" by Charles B. Kramer, Attorney
Internet (72600.2026@compuserve.com); TEL: (212-254-5093)
**** SMALL PRINT! FOR __ COMPLETE SHAKESPEARE ****
["Small Print" V.12.08.93]
<<THIS ELECTRONIC VERSION OF THE COMPLETE WORKS OF WILLIAM
SHAKESPEARE IS COPYRIGHT 1990-1993 BY WORLD LIBRARY, INC., AND IS
PROVIDED BY PROJECT GUTENBERG ETEXT OF ILLINOIS BENEDICTINE COLLEGE
WITH PERMISSION. ELECTRONIC AND MACHINE READABLE COPIES MAY BE
DISTRIBUTED SO LONG AS SUCH COPIES (1) ARE FOR YOUR OR OTHERS
PERSONAL USE ONLY, AND (2) ARE NOT DISTRIBUTED OR USED
COMMERCIALLY. PROHIBITED COMMERCIAL DISTRIBUTION INCLUDES BY ANY
SERVICE THAT CHARGES FOR DOWNLOAD TIME OR FOR MEMBERSHIP.>>
1609
THE SONNETS
by William Shakespeare
THE END
<<THIS ELECTRONIC VERSION OF THE COMPLETE WORKS OF WILLIAM
SHAKESPEARE IS COPYRIGHT 1990-1993 BY WORLD LIBRARY, INC., AND IS
PROVIDED BY PROJECT GUTENBERG ETEXT OF ILLINOIS BENEDICTINE COLLEGE
WITH PERMISSION. ELECTRONIC AND MACHINE READABLE COPIES MAY BE
DISTRIBUTED SO LONG AS SUCH COPIES (1) ARE FOR YOUR OR OTHERS
PERSONAL USE ONLY, AND (2) ARE NOT DISTRIBUTED OR USED
COMMERCIALLY. PROHIBITED COMMERCIAL DISTRIBUTION INCLUDES BY ANY
SERVICE THAT CHARGES FOR DOWNLOAD TIME OR FOR MEMBERSHIP.>>
End of this Etext of The Complete Works of William Shakespeare

View File

@@ -0,0 +1,18 @@
from pyspark.sql import SparkSession
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--input", default="")
parser.add_argument("--output", default="")
args, unparsed = parser.parse_known_args()
spark = SparkSession.builder.getOrCreate()
sc = spark.sparkContext
arr = sc._gateway.new_array(sc._jvm.java.lang.String, 2)
arr[0] = args.input
arr[1] = args.output
obj = sc._jvm.WordCount
obj.main(arr)

View File

@@ -121,8 +121,6 @@
"source": [ "source": [
"You can now create and/or use an Environment object when deploying a Webservice. The Environment can have been previously registered with your Workspace, or it will be registered with it as a part of the Webservice deployment.\n", "You can now create and/or use an Environment object when deploying a Webservice. The Environment can have been previously registered with your Workspace, or it will be registered with it as a part of the Webservice deployment.\n",
"\n", "\n",
"In this notebook, we will be using 'AzureML-PySpark-MmlSpark-0.15', a curated environment.\n",
"\n",
"More information can be found in our [using environments notebook](../training/using-environments/using-environments.ipynb)." "More information can be found in our [using environments notebook](../training/using-environments/using-environments.ipynb)."
] ]
}, },
@@ -132,9 +130,17 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"from azureml.core import Environment\n", "from azureml.core import Environment\r\n",
"\n", "from azureml.core.environment import SparkPackage\r\n",
"env = Environment.get(ws, name='AzureML-PySpark-MmlSpark-0.15')\n" "from azureml.core.conda_dependencies import CondaDependencies\r\n",
"\r\n",
"myenv = Environment('my-pyspark-environment')\r\n",
"myenv.docker.base_image = \"mcr.microsoft.com/mmlspark/release:0.15\"\r\n",
"myenv.inferencing_stack_version = \"latest\"\r\n",
"myenv.python.conda_dependencies = CondaDependencies.create(pip_packages=[\"azureml-core\",\"azureml-defaults\",\"azureml-telemetry\",\"azureml-train-restclients-hyperdrive\",\"azureml-train-core\"], python_version=\"3.6.2\")\r\n",
"myenv.python.conda_dependencies.add_channel(\"conda-forge\")\r\n",
"myenv.spark.packages = [SparkPackage(\"com.microsoft.ml.spark\", \"mmlspark_2.11\", \"0.15\"), SparkPackage(\"com.microsoft.azure\", \"azure-storage\", \"2.0.0\"), SparkPackage(\"org.apache.hadoop\", \"hadoop-azure\", \"2.7.0\")]\r\n",
"myenv.spark.repositories = [\"https://mmlspark.azureedge.net/maven\"]\r\n"
] ]
}, },
{ {
@@ -171,7 +177,7 @@
"source": [ "source": [
"from azureml.core.model import InferenceConfig\n", "from azureml.core.model import InferenceConfig\n",
"\n", "\n",
"inference_config = InferenceConfig(entry_script=\"score.py\", environment=env)" "inference_config = InferenceConfig(entry_script=\"score.py\", environment=myenv)"
] ]
}, },
{ {

View File

@@ -217,7 +217,6 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"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",
"# Choose a name for your CPU cluster\n", "# Choose a name for your CPU cluster\n",
@@ -267,7 +266,7 @@
"available_packages = pkg_resources.working_set\n", "available_packages = pkg_resources.working_set\n",
"sklearn_ver = None\n", "sklearn_ver = None\n",
"pandas_ver = None\n", "pandas_ver = None\n",
"for dist in available_packages:\n", "for dist in list(available_packages):\n",
" if dist.key == 'scikit-learn':\n", " if dist.key == 'scikit-learn':\n",
" sklearn_ver = dist.version\n", " sklearn_ver = dist.version\n",
" elif dist.key == 'pandas':\n", " elif dist.key == 'pandas':\n",
@@ -286,7 +285,6 @@
"azureml_pip_packages.extend([sklearn_dep, pandas_dep])\n", "azureml_pip_packages.extend([sklearn_dep, pandas_dep])\n",
"run_config.environment.python.conda_dependencies = CondaDependencies.create(pip_packages=azureml_pip_packages)\n", "run_config.environment.python.conda_dependencies = CondaDependencies.create(pip_packages=azureml_pip_packages)\n",
"\n", "\n",
"from azureml.core import Run\n",
"from azureml.core import ScriptRunConfig\n", "from azureml.core import ScriptRunConfig\n",
"\n", "\n",
"src = ScriptRunConfig(source_directory=project_folder, \n", "src = ScriptRunConfig(source_directory=project_folder, \n",
@@ -416,7 +414,6 @@
"outputs": [], "outputs": [],
"source": [ "source": [
"# Retrieve x_test for visualization\n", "# Retrieve x_test for visualization\n",
"import joblib\n",
"x_test_path = './x_test_boston_housing.pkl'\n", "x_test_path = './x_test_boston_housing.pkl'\n",
"run.download_file('x_test_boston_housing.pkl', output_file_path=x_test_path)" "run.download_file('x_test_boston_housing.pkl', output_file_path=x_test_path)"
] ]
@@ -444,7 +441,7 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"from interpret_community.widget import ExplanationDashboard" "from raiwidgets import ExplanationDashboard"
] ]
}, },
{ {
@@ -453,7 +450,7 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"ExplanationDashboard(global_explanation, original_model, datasetX=x_test)" "ExplanationDashboard(global_explanation, original_model, dataset=x_test)"
] ]
}, },
{ {

View File

@@ -11,3 +11,4 @@ dependencies:
- matplotlib - matplotlib
- azureml-dataset-runtime - azureml-dataset-runtime
- ipywidgets - ipywidgets
- raiwidgets~=0.7.0

View File

@@ -87,7 +87,6 @@
"from sklearn.preprocessing import StandardScaler, OneHotEncoder\n", "from sklearn.preprocessing import StandardScaler, OneHotEncoder\n",
"from sklearn.svm import SVC\n", "from sklearn.svm import SVC\n",
"import pandas as pd\n", "import pandas as pd\n",
"import numpy as np\n",
"\n", "\n",
"# Explainers:\n", "# Explainers:\n",
"# 1. SHAP Tabular Explainer\n", "# 1. SHAP Tabular Explainer\n",
@@ -533,7 +532,7 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"from interpret_community.widget import ExplanationDashboard" "from raiwidgets import ExplanationDashboard"
] ]
}, },
{ {
@@ -542,7 +541,7 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"ExplanationDashboard(downloaded_global_explanation, model, datasetX=x_test)" "ExplanationDashboard(downloaded_global_explanation, model, dataset=x_test)"
] ]
}, },
{ {

View File

@@ -10,3 +10,4 @@ dependencies:
- ipython - ipython
- matplotlib - matplotlib
- ipywidgets - ipywidgets
- raiwidgets~=0.7.0

View File

@@ -170,7 +170,6 @@
"from sklearn.preprocessing import StandardScaler, OneHotEncoder\n", "from sklearn.preprocessing import StandardScaler, OneHotEncoder\n",
"from sklearn.impute import SimpleImputer\n", "from sklearn.impute import SimpleImputer\n",
"from sklearn.pipeline import Pipeline\n", "from sklearn.pipeline import Pipeline\n",
"from sklearn.linear_model import LogisticRegression\n",
"from sklearn.ensemble import RandomForestClassifier\n", "from sklearn.ensemble import RandomForestClassifier\n",
"\n", "\n",
"from interpret.ext.blackbox import TabularExplainer\n", "from interpret.ext.blackbox import TabularExplainer\n",
@@ -221,7 +220,6 @@
" ('classifier', RandomForestClassifier())])\n", " ('classifier', RandomForestClassifier())])\n",
"\n", "\n",
"# Split data into train and test\n", "# Split data into train and test\n",
"from sklearn.model_selection import train_test_split\n",
"x_train, x_test, y_train, y_test = train_test_split(attritionXData,\n", "x_train, x_test, y_train, y_test = train_test_split(attritionXData,\n",
" target,\n", " target,\n",
" test_size=0.2,\n", " test_size=0.2,\n",
@@ -296,7 +294,7 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"from interpret_community.widget import ExplanationDashboard" "from raiwidgets import ExplanationDashboard"
] ]
}, },
{ {
@@ -305,7 +303,7 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"ExplanationDashboard(global_explanation, clf, datasetX=x_test)" "ExplanationDashboard(global_explanation, clf, dataset=x_test)"
] ]
}, },
{ {
@@ -356,8 +354,7 @@
"# the submitted job is run in. Note the remote environment(s) needs to be similar to the local\n", "# the submitted job is run in. Note the remote environment(s) needs to be similar to the local\n",
"# environment, otherwise if a model is trained or deployed in a different environment this can\n", "# environment, otherwise if a model is trained or deployed in a different environment this can\n",
"# cause errors. Please take extra care when specifying your dependencies in a production environment.\n", "# cause errors. Please take extra care when specifying your dependencies in a production environment.\n",
"myenv = CondaDependencies.create(pip_packages=['pyyaml', sklearn_dep, pandas_dep] + azureml_pip_packages,\n", "myenv = CondaDependencies.create(pip_packages=['pyyaml', sklearn_dep, pandas_dep] + azureml_pip_packages)\n",
" pin_sdk_version=False)\n",
"\n", "\n",
"with open(\"myenv.yml\",\"w\") as f:\n", "with open(\"myenv.yml\",\"w\") as f:\n",
" f.write(myenv.serialize_to_string())\n", " f.write(myenv.serialize_to_string())\n",
@@ -383,10 +380,8 @@
"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.environment import Environment\n", "from azureml.core.environment import Environment\n",
"from azureml.exceptions import WebserviceException\n", "from azureml.exceptions import WebserviceException\n",
"\n", "\n",

View File

@@ -10,3 +10,4 @@ dependencies:
- ipython - ipython
- matplotlib - matplotlib
- ipywidgets - ipywidgets
- raiwidgets~=0.7.0

View File

@@ -218,7 +218,6 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"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",
"# Choose a name for your CPU cluster\n", "# Choose a name for your CPU cluster\n",
@@ -380,7 +379,6 @@
"outputs": [], "outputs": [],
"source": [ "source": [
"# Retrieve x_test for visualization\n", "# Retrieve x_test for visualization\n",
"import joblib\n",
"x_test_path = './x_test.pkl'\n", "x_test_path = './x_test.pkl'\n",
"run.download_file('x_test_ibm.pkl', output_file_path=x_test_path)\n", "run.download_file('x_test_ibm.pkl', output_file_path=x_test_path)\n",
"x_test = joblib.load(x_test_path)" "x_test = joblib.load(x_test_path)"
@@ -400,7 +398,7 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"from interpret_community.widget import ExplanationDashboard" "from raiwidgets import ExplanationDashboard"
] ]
}, },
{ {
@@ -409,7 +407,7 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"ExplanationDashboard(global_explanation, original_svm_model, datasetX=x_test)" "ExplanationDashboard(global_explanation, original_svm_model, dataset=x_test)"
] ]
}, },
{ {
@@ -426,8 +424,6 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"from azureml.core.conda_dependencies import CondaDependencies \n",
"\n",
"# WARNING: to install this, g++ needs to be available on the Docker image and is not by default (look at the next cell)\n", "# WARNING: to install this, g++ needs to be available on the Docker image and is not by default (look at the next cell)\n",
"azureml_pip_packages = [\n", "azureml_pip_packages = [\n",
" 'azureml-defaults', 'azureml-core', 'azureml-telemetry',\n", " 'azureml-defaults', 'azureml-core', 'azureml-telemetry',\n",
@@ -437,7 +433,6 @@
"\n", "\n",
"# Note: this is to pin the scikit-learn and pandas versions to be same as notebook.\n", "# Note: this is to pin the scikit-learn and pandas versions to be same as notebook.\n",
"# In production scenario user would choose their dependencies\n", "# In production scenario user would choose their dependencies\n",
"import pkg_resources\n",
"available_packages = pkg_resources.working_set\n", "available_packages = pkg_resources.working_set\n",
"sklearn_ver = None\n", "sklearn_ver = None\n",
"pandas_ver = None\n", "pandas_ver = None\n",
@@ -483,10 +478,8 @@
"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.environment import Environment\n", "from azureml.core.environment import Environment\n",
"from azureml.exceptions import WebserviceException\n", "from azureml.exceptions import WebserviceException\n",
"\n", "\n",

View File

@@ -12,3 +12,4 @@ dependencies:
- azureml-dataset-runtime - azureml-dataset-runtime
- azureml-core - azureml-core
- ipywidgets - ipywidgets
- raiwidgets~=0.7.0

View File

@@ -126,7 +126,7 @@
}, },
"outputs": [], "outputs": [],
"source": [ "source": [
"from msrest.exceptions import HttpOperationError\n", "from azureml.exceptions import UserErrorException\n",
"\n", "\n",
"blob_datastore_name='MyBlobDatastore'\n", "blob_datastore_name='MyBlobDatastore'\n",
"account_name=os.getenv(\"BLOB_ACCOUNTNAME_62\", \"<my-account-name>\") # Storage account name\n", "account_name=os.getenv(\"BLOB_ACCOUNTNAME_62\", \"<my-account-name>\") # Storage account name\n",
@@ -136,7 +136,7 @@
"try:\n", "try:\n",
" blob_datastore = Datastore.get(ws, blob_datastore_name)\n", " blob_datastore = Datastore.get(ws, blob_datastore_name)\n",
" print(\"Found Blob Datastore with name: %s\" % blob_datastore_name)\n", " print(\"Found Blob Datastore with name: %s\" % blob_datastore_name)\n",
"except HttpOperationError:\n", "except UserErrorException:\n",
" blob_datastore = Datastore.register_azure_blob_container(\n", " blob_datastore = Datastore.register_azure_blob_container(\n",
" workspace=ws,\n", " workspace=ws,\n",
" datastore_name=blob_datastore_name,\n", " datastore_name=blob_datastore_name,\n",
@@ -180,7 +180,7 @@
"try:\n", "try:\n",
" adls_datastore = Datastore.get(ws, datastore_name)\n", " adls_datastore = Datastore.get(ws, datastore_name)\n",
" print(\"Found datastore with name: %s\" % datastore_name)\n", " print(\"Found datastore with name: %s\" % datastore_name)\n",
"except HttpOperationError:\n", "except UserErrorException:\n",
" adls_datastore = Datastore.register_azure_data_lake(\n", " adls_datastore = Datastore.register_azure_data_lake(\n",
" workspace=ws,\n", " workspace=ws,\n",
" datastore_name=datastore_name,\n", " datastore_name=datastore_name,\n",
@@ -270,7 +270,7 @@
"try:\n", "try:\n",
" sql_datastore = Datastore.get(ws, sql_datastore_name)\n", " sql_datastore = Datastore.get(ws, sql_datastore_name)\n",
" print(\"Found sql database datastore with name: %s\" % sql_datastore_name)\n", " print(\"Found sql database datastore with name: %s\" % sql_datastore_name)\n",
"except HttpOperationError:\n", "except UserErrorException:\n",
" sql_datastore = Datastore.register_azure_sql_database(\n", " sql_datastore = Datastore.register_azure_sql_database(\n",
" workspace=ws,\n", " workspace=ws,\n",
" datastore_name=sql_datastore_name,\n", " datastore_name=sql_datastore_name,\n",
@@ -312,7 +312,7 @@
"try:\n", "try:\n",
" psql_datastore = Datastore.get(ws, psql_datastore_name)\n", " psql_datastore = Datastore.get(ws, psql_datastore_name)\n",
" print(\"Found PostgreSQL database datastore with name: %s\" % psql_datastore_name)\n", " print(\"Found PostgreSQL database datastore with name: %s\" % psql_datastore_name)\n",
"except HttpOperationError:\n", "except UserErrorException:\n",
" psql_datastore = Datastore.register_azure_postgre_sql(\n", " psql_datastore = Datastore.register_azure_postgre_sql(\n",
" workspace=ws,\n", " workspace=ws,\n",
" datastore_name=psql_datastore_name,\n", " datastore_name=psql_datastore_name,\n",
@@ -353,7 +353,7 @@
"try:\n", "try:\n",
" mysql_datastore = Datastore.get(ws, mysql_datastore_name)\n", " mysql_datastore = Datastore.get(ws, mysql_datastore_name)\n",
" print(\"Found MySQL database datastore with name: %s\" % mysql_datastore_name)\n", " print(\"Found MySQL database datastore with name: %s\" % mysql_datastore_name)\n",
"except HttpOperationError:\n", "except UserErrorException:\n",
" mysql_datastore = Datastore.register_azure_my_sql(\n", " mysql_datastore = Datastore.register_azure_my_sql(\n",
" workspace=ws,\n", " workspace=ws,\n",
" datastore_name=mysql_datastore_name,\n", " datastore_name=mysql_datastore_name,\n",

View File

@@ -47,8 +47,9 @@
"outputs": [], "outputs": [],
"source": [ "source": [
"import azureml.core\n", "import azureml.core\n",
"from azureml.core import Workspace, Experiment, Dataset\n", "from azureml.core import Workspace, Experiment, Dataset, RunConfiguration\n",
"from azureml.core.compute import ComputeTarget, AmlCompute\n", "from azureml.core.compute import ComputeTarget, AmlCompute\n",
"from azureml.core.environment import CondaDependencies\n",
"from azureml.data.dataset_consumption_config import DatasetConsumptionConfig\n", "from azureml.data.dataset_consumption_config import DatasetConsumptionConfig\n",
"from azureml.widgets import RunDetails\n", "from azureml.widgets import RunDetails\n",
"\n", "\n",
@@ -223,6 +224,18 @@
"Note that the ```file_ds_consumption``` and ```tabular_ds_consumption``` are specified as both arguments and inputs to create a step." "Note that the ```file_ds_consumption``` and ```tabular_ds_consumption``` are specified as both arguments and inputs to create a step."
] ]
}, },
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"conda_dep = CondaDependencies()\n",
"conda_dep.add_pip_package(\"pandas\")\n",
"\n",
"run_config = RunConfiguration(conda_dependencies=conda_dep)"
]
},
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
@@ -235,7 +248,8 @@
" arguments=[\"--param1\", file_ds_consumption, \"--param2\", tabular_ds_consumption],\n", " arguments=[\"--param1\", file_ds_consumption, \"--param2\", tabular_ds_consumption],\n",
" inputs=[file_ds_consumption, tabular_ds_consumption],\n", " inputs=[file_ds_consumption, tabular_ds_consumption],\n",
" compute_target=compute_target,\n", " compute_target=compute_target,\n",
" source_directory=source_directory)\n", " source_directory=source_directory,\n",
" runconfig=run_config)\n",
"\n", "\n",
"print(\"train_step created\")\n", "print(\"train_step created\")\n",
"\n", "\n",
@@ -498,7 +512,7 @@
"pygments_lexer": "ipython3", "pygments_lexer": "ipython3",
"version": "3.6.7" "version": "3.6.7"
}, },
"order_index": 13, "order_index": 13.0,
"star_tag": [ "star_tag": [
"featured" "featured"
], ],

View File

@@ -148,7 +148,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',# for GPU, use \"STANDARD_NC6\"\n", " compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_DS12_V2',# for GPU, use \"STANDARD_NC6\"\n",
" #vm_priority = 'lowpriority', # optional\n", " #vm_priority = 'lowpriority', # optional\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",

View File

@@ -247,7 +247,7 @@
" aml_compute = ComputeTarget(workspace=ws, name=amlcompute_cluster_name)\n", " aml_compute = 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",
" aml_compute = ComputeTarget.create(ws, amlcompute_cluster_name, compute_config)\n", " aml_compute = ComputeTarget.create(ws, amlcompute_cluster_name, compute_config)\n",
"\n", "\n",
@@ -681,7 +681,6 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"import logging\n",
"from azureml.train.automl import AutoMLConfig\n", "from azureml.train.automl import AutoMLConfig\n",
"\n", "\n",
"# Change iterations to a reasonable number (50) to get better accuracy\n", "# Change iterations to a reasonable number (50) to get better accuracy\n",
@@ -784,8 +783,8 @@
" path = download_path + '/azureml/' + output_folder + '/' + output_name\n", " path = download_path + '/azureml/' + output_folder + '/' + output_name\n",
" return path\n", " return path\n",
"\n", "\n",
"def fetch_df(step, output_name):\n", "def fetch_df(current_step, output_name):\n",
" output_data = step.get_output_data(output_name) \n", " output_data = current_step.get_output_data(output_name) \n",
" download_path = './outputs/' + output_name\n", " download_path = './outputs/' + output_name\n",
" output_data.download(download_path, overwrite=True)\n", " output_data.download(download_path, overwrite=True)\n",
" df_path = get_download_path(download_path, output_name) + '/processed.parquet'\n", " df_path = get_download_path(download_path, output_name) + '/processed.parquet'\n",
@@ -941,32 +940,6 @@
"#RunDetails(automl_run).show()" "#RunDetails(automl_run).show()"
] ]
}, },
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Retrieve all Child runs\n",
"\n",
"We 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(automl_run.get_children())\n",
"metricslist = {}\n",
"for run in children:\n",
" properties = run.get_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": {},

View File

@@ -2,6 +2,7 @@ name: nyc-taxi-data-regression-model-building
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- certifi
- azureml-widgets - azureml-widgets
- azureml-opendatasets - azureml-opendatasets
- azureml-train-automl - azureml-train-automl

View File

@@ -122,4 +122,8 @@ pipeline_run.wait_for_completion(show_output=True)
- [tabular-dataset-inference-iris.ipynb](./tabular-dataset-inference-iris.ipynb) demonstrates how to run batch inference on an IRIS dataset using TabularDataset. - [tabular-dataset-inference-iris.ipynb](./tabular-dataset-inference-iris.ipynb) demonstrates how to run batch inference on an IRIS dataset using TabularDataset.
- [pipeline-style-transfer.ipynb](../pipeline-style-transfer/pipeline-style-transfer-parallel-run.ipynb) demonstrates using ParallelRunStep in multi-step pipeline and using output from one step as input to ParallelRunStep. - [pipeline-style-transfer.ipynb](../pipeline-style-transfer/pipeline-style-transfer-parallel-run.ipynb) demonstrates using ParallelRunStep in multi-step pipeline and using output from one step as input to ParallelRunStep.
# Troubleshooting guide
- [Troubleshooting the ParallelRunStep](https://aka.ms/prstsg) includes answers to frequently asked questions. You can find more references there.
![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/machine-learning-pipelines/parallel-run/README.png) ![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/machine-learning-pipelines/parallel-run/README.png)

View File

@@ -183,7 +183,7 @@
"outputs": [], "outputs": [],
"source": [ "source": [
"# make sure utils.py is in the same directory as this code\n", "# make sure utils.py is in the same directory as this code\n",
"from utils import load_data, one_hot_encode\n", "from utils import load_data\n",
"\n", "\n",
"# note we also shrink the intensity values (X) from 0-255 to 0-1. This helps the model converge faster.\n", "# note we also shrink the intensity values (X) from 0-255 to 0-1. This helps the model converge faster.\n",
"X_train = load_data(os.path.join(data_folder, 'train-images-idx3-ubyte.gz'), False) / 255.0\n", "X_train = load_data(os.path.join(data_folder, 'train-images-idx3-ubyte.gz'), False) / 255.0\n",
@@ -253,11 +253,12 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"from azureml.exceptions import UserErrorException\n",
"dataset_registered = False\n", "dataset_registered = False\n",
"try:\n", "try:\n",
" temp = Dataset.get_by_name(workspace = ws, name = 'mnist-dataset')\n", " temp = Dataset.get_by_name(workspace = ws, name = 'mnist-dataset')\n",
" dataset_registered = True\n", " dataset_registered = True\n",
"except:\n", "except UserErrorException:\n",
" print(\"The dataset mnist-dataset is not registered in workspace yet.\")\n", " print(\"The dataset mnist-dataset is not registered in workspace yet.\")\n",
"\n", "\n",
"if not dataset_registered:\n", "if not dataset_registered:\n",
@@ -1009,15 +1010,14 @@
"from azureml.core.webservice import AciWebservice\n", "from azureml.core.webservice import AciWebservice\n",
"from azureml.core.model import InferenceConfig\n", "from azureml.core.model import InferenceConfig\n",
"from azureml.core.model import Model\n", "from azureml.core.model import Model\n",
"from azureml.core.environment import Environment\n",
"\n", "\n",
"\n", "\n",
"myenv = Environment.from_conda_specification(name=\"myenv\", file_path=\"myenv.yml\")\n", "myenv = Environment.from_conda_specification(name=\"myenv\", file_path=\"myenv.yml\")\n",
"inference_config = InferenceConfig(entry_script=\"score.py\", environment=myenv)\n", "inference_config = InferenceConfig(entry_script=\"score.py\", environment=myenv)\n",
"\n", "\n",
"aciconfig = AciWebservice.deploy_configuration(cpu_cores=1,\n", "aciconfig = AciWebservice.deploy_configuration(cpu_cores=2,\n",
" auth_enabled=True, # this flag generates API keys to secure access\n", " auth_enabled=True, # this flag generates API keys to secure access\n",
" memory_gb=1,\n", " memory_gb=2,\n",
" tags={'name': 'mnist', 'framework': 'Keras'},\n", " tags={'name': 'mnist', 'framework': 'Keras'},\n",
" description='Keras MLP on MNIST')\n", " description='Keras MLP on MNIST')\n",
"\n", "\n",

View File

@@ -579,13 +579,12 @@
"source": [ "source": [
"from azureml.core.webservice import AciWebservice\n", "from azureml.core.webservice import AciWebservice\n",
"from azureml.core.model import InferenceConfig\n", "from azureml.core.model import InferenceConfig\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(entry_script=\"pytorch_score.py\", environment=pytorch_env)\n", "inference_config = InferenceConfig(entry_script=\"pytorch_score.py\", environment=pytorch_env)\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': 'birds', 'method':'transfer learning', 'framework':'pytorch'},\n", " tags={'data': 'birds', 'method':'transfer learning', 'framework':'pytorch'},\n",
" description='Classify turkey/chickens using transfer learning with PyTorch')\n", " description='Classify turkey/chickens using transfer learning with PyTorch')\n",
"\n", "\n",

View File

@@ -265,11 +265,12 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"from azureml.exceptions import UserErrorException\n",
"dataset_registered = False\n", "dataset_registered = False\n",
"try:\n", "try:\n",
" temp = Dataset.get_by_name(workspace = ws, name = 'mnist-dataset')\n", " temp = Dataset.get_by_name(workspace = ws, name = 'mnist-dataset')\n",
" dataset_registered = True\n", " dataset_registered = True\n",
"except:\n", "except UserErrorException:\n",
" print(\"The dataset mnist-dataset is not registered in workspace yet.\")\n", " print(\"The dataset mnist-dataset is not registered in workspace yet.\")\n",
"\n", "\n",
"if not dataset_registered:\n", "if not dataset_registered:\n",
@@ -964,14 +965,13 @@
"from azureml.core.webservice import AciWebservice\n", "from azureml.core.webservice import AciWebservice\n",
"from azureml.core.model import InferenceConfig\n", "from azureml.core.model import InferenceConfig\n",
"from azureml.core.model import Model\n", "from azureml.core.model import Model\n",
"from azureml.core.environment import Environment\n",
"\n", "\n",
"\n", "\n",
"myenv = Environment.from_conda_specification(name=\"myenv\", file_path=\"myenv.yml\")\n", "myenv = Environment.from_conda_specification(name=\"myenv\", file_path=\"myenv.yml\")\n",
"inference_config = InferenceConfig(entry_script=\"score.py\", environment=myenv)\n", "inference_config = InferenceConfig(entry_script=\"score.py\", environment=myenv)\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={'name':'mnist', 'framework': 'TensorFlow DNN'},\n", " tags={'name':'mnist', 'framework': 'TensorFlow DNN'},\n",
" description='Tensorflow DNN on MNIST')\n", " description='Tensorflow DNN on MNIST')\n",
"\n", "\n",

View File

@@ -451,9 +451,8 @@
"metadata": {}, "metadata": {},
"source": [ "source": [
"### Create a dataset of training artifacts\n", "### Create a dataset of training artifacts\n",
"To evaluate a trained policy (a checkpoint) we need to make the checkpoint accessible to the rollout script. All the training artifacts are stored in workspace default datastore under **azureml/&lt;run_id&gt;** directory.\n", "To evaluate a trained policy (a checkpoint) we need to make the checkpoint accessible to the rollout script.\n",
"\n", "We can use the Run API to download policy training artifacts (saved model and checkpoints) to local compute."
"Here we create a file dataset from the stored artifacts, and then use this dataset to feed these data to rollout estimator."
] ]
}, },
{ {
@@ -462,22 +461,24 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"from azureml.core import Dataset\n", "from os import path\n",
"from distutils import dir_util\n",
"\n", "\n",
"run_id = child_run_0.id # Or set to run id of a completed run (e.g. 'rl-cartpole-v0_1587572312_06e04ace_head')\n", "training_artifacts_path = path.join(\"logs\", training_algorithm)\n",
"run_artifacts_path = os.path.join('azureml', run_id)\n", "print(\"Training artifacts path:\", training_artifacts_path)\n",
"print(\"Run artifacts path:\", run_artifacts_path)\n",
"\n", "\n",
"# Create a file dataset object from the files stored on default datastore\n", "if path.exists(training_artifacts_path):\n",
"datastore = ws.get_default_datastore()\n", " dir_util.remove_tree(training_artifacts_path)\n",
"training_artifacts_ds = Dataset.File.from_files(datastore.path(os.path.join(run_artifacts_path, '**')))" "\n",
"# Download run artifacts to local compute\n",
"child_run_0.download_files(training_artifacts_path)"
] ]
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {}, "metadata": {},
"source": [ "source": [
"To verify, we can print out the number (and paths) of all the files in the dataset, as follows." "Now let's find the checkpoints and the last checkpoint number."
] ]
}, },
{ {
@@ -486,7 +487,73 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"artifacts_paths = training_artifacts_ds.to_path()\n", "# A helper function to find checkpoint files in a directory\n",
"def find_checkpoints(file_path):\n",
" print(\"Looking in path:\", file_path)\n",
" checkpoints = []\n",
" for root, _, files in os.walk(file_path):\n",
" for name in files:\n",
" if os.path.basename(root).startswith('checkpoint_'):\n",
" checkpoints.append(path.join(root, name))\n",
" return checkpoints"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Find checkpoints and last checkpoint number\n",
"checkpoint_files = find_checkpoints(training_artifacts_path)\n",
"\n",
"checkpoint_numbers = []\n",
"for file in checkpoint_files:\n",
" file = os.path.basename(file)\n",
" if file.startswith('checkpoint-') and not file.endswith('.tune_metadata'):\n",
" checkpoint_numbers.append(int(file.split('-')[1]))\n",
"\n",
"print(\"Checkpoints:\", checkpoint_numbers)\n",
"\n",
"last_checkpoint_number = max(checkpoint_numbers)\n",
"print(\"Last checkpoint number:\", last_checkpoint_number)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we upload checkpoints to default datastore and create a file dataset. This dataset will be used to pass in the checkpoints to the rollout script."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Upload the checkpoint files and create a DataSet\n",
"from azureml.core import Dataset\n",
"\n",
"datastore = ws.get_default_datastore()\n",
"checkpoint_dataref = datastore.upload_files(checkpoint_files, target_path='cartpole_checkpoints_' + run_id, overwrite=True)\n",
"checkpoint_ds = Dataset.File.from_files(checkpoint_dataref)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To verify, we can print out the number (and paths) of all the files in the dataset."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"artifacts_paths = checkpoint_ds.to_path()\n",
"print(\"Number of files in dataset:\", len(artifacts_paths))\n", "print(\"Number of files in dataset:\", len(artifacts_paths))\n",
"\n", "\n",
"# Uncomment line below to print all file paths\n", "# Uncomment line below to print all file paths\n",
@@ -505,36 +572,6 @@
"\n", "\n",
"The checkpoints dataset will be accessible to the rollout script as a mounted folder. The mounted folder and the checkpoint number, passed in via `checkpoint-number`, will be used to create a path to the checkpoint we are going to evaluate. The created checkpoint path then will be passed into RLlib rollout script for evaluation.\n", "The checkpoints dataset will be accessible to the rollout script as a mounted folder. The mounted folder and the checkpoint number, passed in via `checkpoint-number`, will be used to create a path to the checkpoint we are going to evaluate. The created checkpoint path then will be passed into RLlib rollout script for evaluation.\n",
"\n", "\n",
"Let's find the checkpoints and the last checkpoint number first."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Find checkpoints and last checkpoint number\n",
"checkpoint_files = [\n",
" os.path.basename(file) for file in training_artifacts_ds.to_path() \\\n",
" if os.path.basename(file).startswith('checkpoint-') and \\\n",
" not os.path.basename(file).endswith('tune_metadata')\n",
"]\n",
"\n",
"checkpoint_numbers = []\n",
"for file in checkpoint_files:\n",
" checkpoint_numbers.append(int(file.split('-')[1]))\n",
"\n",
"print(\"Checkpoints:\", checkpoint_numbers)\n",
"\n",
"last_checkpoint_number = max(checkpoint_numbers)\n",
"print(\"Last checkpoint number:\", last_checkpoint_number)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now let's configure rollout estimator. Note that we use the last checkpoint for evaluation. The assumption is that the last checkpoint points to our best trained agent. You may change this to any of the checkpoint numbers printed above and observe the effect." "Now let's configure rollout estimator. Note that we use the last checkpoint for evaluation. The assumption is that the last checkpoint points to our best trained agent. You may change this to any of the checkpoint numbers printed above and observe the effect."
] ]
}, },
@@ -576,8 +613,8 @@
" \n", " \n",
" # Data inputs\n", " # Data inputs\n",
" inputs=[\n", " inputs=[\n",
" training_artifacts_ds.as_named_input('artifacts_dataset'),\n", " checkpoint_ds.as_named_input('artifacts_dataset'),\n",
" training_artifacts_ds.as_named_input('artifacts_path').as_mount()],\n", " checkpoint_ds.as_named_input('artifacts_path').as_mount()],\n",
" \n", " \n",
" # The Azure Machine Learning compute target\n", " # The Azure Machine Learning compute target\n",
" compute_target=compute_target,\n", " compute_target=compute_target,\n",

View File

@@ -474,61 +474,14 @@
"from os import path\n", "from os import path\n",
"from distutils import dir_util\n", "from distutils import dir_util\n",
"\n", "\n",
"path_prefix = path.join(\"logs\", training_algorithm)\n", "training_artifacts_path = path.join(\"logs\", training_algorithm)\n",
"print(\"Path prefix:\", path_prefix)\n", "print(\"Training artifacts path:\", training_artifacts_path)\n",
"\n", "\n",
"if path.exists(path_prefix):\n", "if path.exists(training_artifacts_path):\n",
" dir_util.remove_tree(path_prefix)\n", " dir_util.remove_tree(training_artifacts_path)\n",
"\n", "\n",
"# Uncomment line below to download run artifacts to local compute\n", "# Download run artifacts to local compute\n",
"#child_run_0.download_files(path_prefix)" "child_run_0.download_files(training_artifacts_path)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Create a dataset of training artifacts\n",
"To evaluate a trained policy (a checkpoint) we need to make the checkpoint accessible to the rollout script. All the training artifacts are stored in workspace default datastore under **azureml/&lt;run_id&gt;** directory.\n",
"\n",
"Here we create a file dataset from the stored artifacts, and then use this dataset to feed these data to rollout estimator."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.core import Dataset\n",
"\n",
"run_id = child_run_0.id # Or set to run id of a completed run (e.g. 'rl-cartpole-v0_1587572312_06e04ace_head')\n",
"run_artifacts_path = os.path.join('azureml', run_id)\n",
"print(\"Run artifacts path:\", run_artifacts_path)\n",
"\n",
"# Create a file dataset object from the files stored on default datastore\n",
"datastore = ws.get_default_datastore()\n",
"training_artifacts_ds = Dataset.File.from_files(datastore.path(os.path.join(run_artifacts_path, '**')))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To verify, we can print out the number (and paths) of all the files in the dataset, as follows."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"artifacts_paths = training_artifacts_ds.to_path()\n",
"print(\"Number of files in dataset:\", len(artifacts_paths))\n",
"\n",
"# Uncomment line below to print all file paths\n",
"#print(\"Artifacts dataset file paths: \", artifacts_paths)"
] ]
}, },
{ {
@@ -550,21 +503,6 @@
"source": [ "source": [
"import shutil\n", "import shutil\n",
"\n", "\n",
"# A helper function to download movies from a dataset to local directory\n",
"def download_movies(artifacts_ds, movies, destination):\n",
" # Create the local destination directory \n",
" if path.exists(destination):\n",
" dir_util.remove_tree(destination)\n",
" dir_util.mkpath(destination)\n",
"\n",
" for i, artifact in enumerate(artifacts_ds.to_path()):\n",
" if artifact in movies:\n",
" print('Downloading {} ...'.format(artifact))\n",
" artifacts_ds.skip(i).take(1).download(target_path=destination, overwrite=True)\n",
"\n",
" print('Downloading movies completed!')\n",
"\n",
"\n",
"# A helper function to find movies in a directory\n", "# A helper function to find movies in a directory\n",
"def find_movies(movie_path):\n", "def find_movies(movie_path):\n",
" print(\"Looking in path:\", movie_path)\n", " print(\"Looking in path:\", movie_path)\n",
@@ -590,34 +528,6 @@
" )" " )"
] ]
}, },
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now let's find the first and the last recorded videos in training artifacts dataset and download them to a local directory."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Find first and last movie\n",
"mp4_files = [file for file in training_artifacts_ds.to_path() if file.endswith('.mp4')]\n",
"mp4_files.sort()\n",
"\n",
"first_movie = mp4_files[0] if len(mp4_files) > 0 else None\n",
"last_movie = mp4_files[-1] if len(mp4_files) > 1 else None\n",
"\n",
"print(\"First movie:\", first_movie)\n",
"print(\"Last movie:\", last_movie)\n",
"\n",
"# Download movies\n",
"training_movies_path = path.join(\"training\", \"videos\")\n",
"download_movies(training_artifacts_ds, [first_movie, last_movie], training_movies_path)"
]
},
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {}, "metadata": {},
@@ -631,7 +541,7 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"mp4_files = find_movies(training_movies_path)\n", "mp4_files = find_movies(training_artifacts_path)\n",
"mp4_files.sort()" "mp4_files.sort()"
] ]
}, },
@@ -704,16 +614,31 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"# Find checkpoints and last checkpoint number\n", "# A helper function to find checkpoint files in a directory\n",
"checkpoint_files = [\n", "def find_checkpoints(file_path):\n",
" os.path.basename(file) for file in training_artifacts_ds.to_path() \\\n", " print(\"Looking in path:\", file_path)\n",
" if os.path.basename(file).startswith('checkpoint-') and \\\n", " checkpoints = []\n",
" not os.path.basename(file).endswith('tune_metadata')\n", " for root, _, files in os.walk(file_path):\n",
"]\n", " for name in files:\n",
" if os.path.basename(root).startswith('checkpoint_'):\n",
" checkpoints.append(path.join(root, name))\n",
" return checkpoints\n",
"\n", "\n",
"checkpoint_files = find_checkpoints(training_artifacts_path)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Find checkpoints and last checkpoint number\n",
"checkpoint_numbers = []\n", "checkpoint_numbers = []\n",
"for file in checkpoint_files:\n", "for file in checkpoint_files:\n",
" checkpoint_numbers.append(int(file.split('-')[1]))\n", " file = os.path.basename(file)\n",
" if file.startswith('checkpoint-') and not file.endswith('.tune_metadata'):\n",
" checkpoint_numbers.append(int(file.split('-')[-1]))\n",
"\n", "\n",
"print(\"Checkpoints:\", checkpoint_numbers)\n", "print(\"Checkpoints:\", checkpoint_numbers)\n",
"\n", "\n",
@@ -721,6 +646,20 @@
"print(\"Last checkpoint number:\", last_checkpoint_number)" "print(\"Last checkpoint number:\", last_checkpoint_number)"
] ]
}, },
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Upload the checkpoint files and create a DataSet\n",
"from azureml.core import Dataset\n",
"\n",
"datastore = ws.get_default_datastore()\n",
"checkpoint_dataref = datastore.upload_files(checkpoint_files, target_path='cartpole_checkpoints_' + run_id, overwrite=True)\n",
"checkpoint_ds = Dataset.File.from_files(checkpoint_dataref)"
]
},
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {}, "metadata": {},
@@ -796,8 +735,8 @@
" \n", " \n",
" # Data inputs\n", " # Data inputs\n",
" inputs=[\n", " inputs=[\n",
" training_artifacts_ds.as_named_input('artifacts_dataset'),\n", " checkpoint_ds.as_named_input('artifacts_dataset'),\n",
" training_artifacts_ds.as_named_input('artifacts_path').as_mount()],\n", " checkpoint_ds.as_named_input('artifacts_path').as_mount()],\n",
" \n", " \n",
" # The Azure Machine Learning compute target set up for Ray head nodes\n", " # The Azure Machine Learning compute target set up for Ray head nodes\n",
" compute_target=compute_target,\n", " compute_target=compute_target,\n",
@@ -879,16 +818,15 @@
"print('Number of child runs:', len(child_runs))\n", "print('Number of child runs:', len(child_runs))\n",
"child_run_0 = child_runs[0]\n", "child_run_0 = child_runs[0]\n",
"\n", "\n",
"run_id = child_run_0.id # Or set to run id of a completed run (e.g. 'rl-cartpole-v0_1587572312_06e04ace_head')\n", "# Download rollout artifacts\n",
"run_artifacts_path = os.path.join('azureml', run_id)\n", "rollout_artifacts_path = path.join(\"logs\", \"rollout\")\n",
"print(\"Run artifacts path:\", run_artifacts_path)\n", "print(\"Rollout artifacts path:\", rollout_artifacts_path)\n",
"\n", "\n",
"# Create a file dataset object from the files stored on default datastore\n", "if path.exists(rollout_artifacts_path):\n",
"datastore = ws.get_default_datastore()\n", " dir_util.remove_tree(rollout_artifacts_path)\n",
"rollout_artifacts_ds = Dataset.File.from_files(datastore.path(os.path.join(run_artifacts_path, '**')))\n",
"\n", "\n",
"artifacts_paths = rollout_artifacts_ds.to_path()\n", "# Download videos to local compute\n",
"print(\"Number of files in dataset:\", len(artifacts_paths))" "child_run_0.download_files(\"logs/video\", output_directory = rollout_artifacts_path)"
] ]
}, },
{ {
@@ -904,20 +842,11 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"# Find last movie\n",
"mp4_files = [file for file in rollout_artifacts_ds.to_path() if file.endswith('.mp4')]\n",
"mp4_files.sort()\n",
"\n",
"last_movie = mp4_files[-1] if len(mp4_files) > 1 else None\n",
"print(\"Last movie:\", last_movie)\n",
"\n",
"# Download last movie\n",
"rollout_movies_path = path.join(\"rollout\", \"videos\")\n",
"download_movies(rollout_artifacts_ds, [last_movie], rollout_movies_path)\n",
"\n",
"# Look for the downloaded movie in local directory\n", "# Look for the downloaded movie in local directory\n",
"mp4_files = find_movies(rollout_movies_path)\n", "mp4_files = find_movies(rollout_artifacts_path)\n",
"mp4_files.sort()" "mp4_files.sort()\n",
"last_movie = mp4_files[-1] if len(mp4_files) > 1 else None\n",
"print(\"Last movie:\", last_movie)"
] ]
}, },
{ {
@@ -960,16 +889,12 @@
"#compute_target.delete()\n", "#compute_target.delete()\n",
"\n", "\n",
"# To delete downloaded training artifacts\n", "# To delete downloaded training artifacts\n",
"#if os.path.exists(path_prefix):\n", "#if os.path.exists(training_artifacts_path):\n",
"# dir_util.remove_tree(path_prefix)\n", "# dir_util.remove_tree(training_artifacts_path)\n",
"\n",
"# To delete downloaded training videos\n",
"#if path.exists(training_movies_path):\n",
"# dir_util.remove_tree(training_movies_path)\n",
"\n", "\n",
"# To delete downloaded rollout videos\n", "# To delete downloaded rollout videos\n",
"#if path.exists(rollout_movies_path):\n", "#if path.exists(rollout_artifacts_path):\n",
"# dir_util.remove_tree(rollout_movies_path)" "# dir_util.remove_tree(rollout_artifacts_path)"
] ]
}, },
{ {
@@ -986,6 +911,9 @@
"authors": [ "authors": [
{ {
"name": "hoazari" "name": "hoazari"
},
{
"name": "dasommer"
} }
], ],
"kernelspec": { "kernelspec": {

View File

@@ -35,7 +35,7 @@
"source": [ "source": [
"## Install required packages\n", "## Install required packages\n",
"\n", "\n",
"This notebook works with Fairlearn v0.4.6, and not later versions. If needed, please uncomment and run the following cell:" "This notebook works with Fairlearn v0.7.0, but not with versions pre-v0.5.0. If needed, please uncomment and run the following cell:"
] ]
}, },
{ {
@@ -44,7 +44,7 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"# %pip install --upgrade fairlearn==0.4.6" "# %pip install --upgrade fairlearn>=0.6.2"
] ]
}, },
{ {
@@ -70,21 +70,18 @@
"outputs": [], "outputs": [],
"source": [ "source": [
"from fairlearn.reductions import GridSearch\n", "from fairlearn.reductions import GridSearch\n",
"from fairlearn.reductions import DemographicParity, ErrorRate\n", "from fairlearn.reductions import DemographicParity\n",
"\n", "\n",
"from sklearn.compose import ColumnTransformer, make_column_selector\n", "from sklearn.compose import ColumnTransformer, make_column_selector\n",
"from sklearn.preprocessing import LabelEncoder,StandardScaler\n", "from sklearn.preprocessing import LabelEncoder, StandardScaler, OneHotEncoder\n",
"from sklearn.linear_model import LogisticRegression\n", "from sklearn.linear_model import LogisticRegression\n",
"from sklearn.pipeline import Pipeline\n", "from sklearn.pipeline import Pipeline\n",
"from sklearn.impute import SimpleImputer\n", "from sklearn.impute import SimpleImputer\n",
"from sklearn.preprocessing import StandardScaler, OneHotEncoder\n",
"from sklearn.svm import SVC\n",
"from sklearn.metrics import accuracy_score\n", "from sklearn.metrics import accuracy_score\n",
"\n", "\n",
"import pandas as pd\n", "import pandas as pd\n",
"\n", "\n",
"# SHAP Tabular Explainer\n", "# SHAP Tabular Explainer\n",
"from interpret.ext.blackbox import KernelExplainer\n",
"from interpret.ext.blackbox import MimicExplainer\n", "from interpret.ext.blackbox import MimicExplainer\n",
"from interpret.ext.glassbox import LGBMExplainableModel" "from interpret.ext.glassbox import LGBMExplainableModel"
] ]
@@ -340,11 +337,11 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"from fairlearn.widget import FairlearnDashboard\n", "from raiwidgets import FairnessDashboard\n",
"\n", "\n",
"y_pred = model.predict(X_test)\n", "y_pred = model.predict(X_test)\n",
"\n", "\n",
"FairlearnDashboard(sensitive_features=sensitive_features_test,\n", "FairnessDashboard(sensitive_features=sensitive_features_test,\n",
" y_true=y_test,\n", " y_true=y_test,\n",
" y_pred=y_pred)" " y_pred=y_pred)"
] ]
@@ -402,7 +399,7 @@
"sweep.fit(X_train_prep, y_train,\n", "sweep.fit(X_train_prep, y_train,\n",
" sensitive_features=sensitive_features_train.sex)\n", " sensitive_features=sensitive_features_train.sex)\n",
"\n", "\n",
"predictors = sweep._predictors" "predictors = sweep.predictors_"
] ]
}, },
{ {
@@ -468,7 +465,7 @@
"for name, predictor in dominant_models_dict.items():\n", "for name, predictor in dominant_models_dict.items():\n",
" dominant_all[name] = predictor.predict(X_test_prep)\n", " dominant_all[name] = predictor.predict(X_test_prep)\n",
"\n", "\n",
"FairlearnDashboard(sensitive_features=sensitive_features_test, \n", "FairnessDashboard(sensitive_features=sensitive_features_test, \n",
" y_true=y_test,\n", " y_true=y_test,\n",
" y_pred=dominant_all)" " y_pred=dominant_all)"
] ]
@@ -563,7 +560,7 @@
"source": [ "source": [
"import joblib\n", "import joblib\n",
"import os\n", "import os\n",
"from azureml.core import Model, Experiment, Run\n", "from azureml.core import Model, Experiment\n",
"\n", "\n",
"os.makedirs('models', exist_ok=True)\n", "os.makedirs('models', exist_ok=True)\n",
"def register_model(name, model):\n", "def register_model(name, model):\n",

View File

@@ -4,9 +4,9 @@ dependencies:
- azureml-sdk - azureml-sdk
- azureml-interpret - azureml-interpret
- azureml-contrib-fairness - azureml-contrib-fairness
- fairlearn==0.4.6 - fairlearn>=0.6.2
- matplotlib - matplotlib
- azureml-dataset-runtime - azureml-dataset-runtime
- ipywidgets - ipywidgets
- raiwidgets - raiwidgets~=0.7.0
- liac-arff - liac-arff

View File

@@ -100,7 +100,7 @@
"\n", "\n",
"# Check core SDK version number\n", "# Check core SDK version number\n",
"\n", "\n",
"print(\"This notebook was created using SDK version 1.29.0, you are currently running version\", azureml.core.VERSION)" "print(\"This notebook was created using SDK version 1.33.0, you are currently running version\", azureml.core.VERSION)"
] ]
}, },
{ {

View File

@@ -129,6 +129,7 @@
"for env in envs:\n", "for env in envs:\n",
" if env.startswith(\"AzureML\"):\n", " if env.startswith(\"AzureML\"):\n",
" print(\"Name\",env)\n", " print(\"Name\",env)\n",
" if envs[env].python.conda_dependencies is not None:\n",
" print(\"packages\", envs[env].python.conda_dependencies.serialize_to_string())" " print(\"packages\", envs[env].python.conda_dependencies.serialize_to_string())"
] ]
}, },

View File

@@ -273,8 +273,8 @@
"- python=3.6.2\n", "- python=3.6.2\n",
"- pip:\n", "- pip:\n",
" - azureml-defaults\n", " - azureml-defaults\n",
" - keras\n", " - keras==2.4.3\n",
" - tensorflow<=2.4.*\n", " - tensorflow==2.4.3\n",
" - numpy\n", " - numpy\n",
" - scikit-learn\n", " - scikit-learn\n",
" - pandas\n", " - pandas\n",

View File

@@ -0,0 +1,151 @@
sepal_length,sepal_width,petal_length,petal_width,species
5.1,3.5,1.4,0.2,Iris-setosa
4.9,3,1.4,0.2,Iris-setosa
4.7,3.2,1.3,0.2,Iris-setosa
4.6,3.1,1.5,0.2,Iris-setosa
5,3.6,1.4,0.2,Iris-setosa
5.4,3.9,1.7,0.4,Iris-setosa
4.6,3.4,1.4,0.3,Iris-setosa
5,3.4,1.5,0.2,Iris-setosa
4.4,2.9,1.4,0.2,Iris-setosa
4.9,3.1,1.5,0.1,Iris-setosa
5.4,3.7,1.5,0.2,Iris-setosa
4.8,3.4,1.6,0.2,Iris-setosa
4.8,3,1.4,0.1,Iris-setosa
4.3,3,1.1,0.1,Iris-setosa
5.8,4,1.2,0.2,Iris-setosa
5.7,4.4,1.5,0.4,Iris-setosa
5.4,3.9,1.3,0.4,Iris-setosa
5.1,3.5,1.4,0.3,Iris-setosa
5.7,3.8,1.7,0.3,Iris-setosa
5.1,3.8,1.5,0.3,Iris-setosa
5.4,3.4,1.7,0.2,Iris-setosa
5.1,3.7,1.5,0.4,Iris-setosa
4.6,3.6,1,0.2,Iris-setosa
5.1,3.3,1.7,0.5,Iris-setosa
4.8,3.4,1.9,0.2,Iris-setosa
5,3,1.6,0.2,Iris-setosa
5,3.4,1.6,0.4,Iris-setosa
5.2,3.5,1.5,0.2,Iris-setosa
5.2,3.4,1.4,0.2,Iris-setosa
4.7,3.2,1.6,0.2,Iris-setosa
4.8,3.1,1.6,0.2,Iris-setosa
5.4,3.4,1.5,0.4,Iris-setosa
5.2,4.1,1.5,0.1,Iris-setosa
5.5,4.2,1.4,0.2,Iris-setosa
4.9,3.1,1.5,0.1,Iris-setosa
5,3.2,1.2,0.2,Iris-setosa
5.5,3.5,1.3,0.2,Iris-setosa
4.9,3.1,1.5,0.1,Iris-setosa
4.4,3,1.3,0.2,Iris-setosa
5.1,3.4,1.5,0.2,Iris-setosa
5,3.5,1.3,0.3,Iris-setosa
4.5,2.3,1.3,0.3,Iris-setosa
4.4,3.2,1.3,0.2,Iris-setosa
5,3.5,1.6,0.6,Iris-setosa
5.1,3.8,1.9,0.4,Iris-setosa
4.8,3,1.4,0.3,Iris-setosa
5.1,3.8,1.6,0.2,Iris-setosa
4.6,3.2,1.4,0.2,Iris-setosa
5.3,3.7,1.5,0.2,Iris-setosa
5,3.3,1.4,0.2,Iris-setosa
7,3.2,4.7,1.4,Iris-versicolor
6.4,3.2,4.5,1.5,Iris-versicolor
6.9,3.1,4.9,1.5,Iris-versicolor
5.5,2.3,4,1.3,Iris-versicolor
6.5,2.8,4.6,1.5,Iris-versicolor
5.7,2.8,4.5,1.3,Iris-versicolor
6.3,3.3,4.7,1.6,Iris-versicolor
4.9,2.4,3.3,1,Iris-versicolor
6.6,2.9,4.6,1.3,Iris-versicolor
5.2,2.7,3.9,1.4,Iris-versicolor
5,2,3.5,1,Iris-versicolor
5.9,3,4.2,1.5,Iris-versicolor
6,2.2,4,1,Iris-versicolor
6.1,2.9,4.7,1.4,Iris-versicolor
5.6,2.9,3.6,1.3,Iris-versicolor
6.7,3.1,4.4,1.4,Iris-versicolor
5.6,3,4.5,1.5,Iris-versicolor
5.8,2.7,4.1,1,Iris-versicolor
6.2,2.2,4.5,1.5,Iris-versicolor
5.6,2.5,3.9,1.1,Iris-versicolor
5.9,3.2,4.8,1.8,Iris-versicolor
6.1,2.8,4,1.3,Iris-versicolor
6.3,2.5,4.9,1.5,Iris-versicolor
6.1,2.8,4.7,1.2,Iris-versicolor
6.4,2.9,4.3,1.3,Iris-versicolor
6.6,3,4.4,1.4,Iris-versicolor
6.8,2.8,4.8,1.4,Iris-versicolor
6.7,3,5,1.7,Iris-versicolor
6,2.9,4.5,1.5,Iris-versicolor
5.7,2.6,3.5,1,Iris-versicolor
5.5,2.4,3.8,1.1,Iris-versicolor
5.5,2.4,3.7,1,Iris-versicolor
5.8,2.7,3.9,1.2,Iris-versicolor
6,2.7,5.1,1.6,Iris-versicolor
5.4,3,4.5,1.5,Iris-versicolor
6,3.4,4.5,1.6,Iris-versicolor
6.7,3.1,4.7,1.5,Iris-versicolor
6.3,2.3,4.4,1.3,Iris-versicolor
5.6,3,4.1,1.3,Iris-versicolor
5.5,2.5,4,1.3,Iris-versicolor
5.5,2.6,4.4,1.2,Iris-versicolor
6.1,3,4.6,1.4,Iris-versicolor
5.8,2.6,4,1.2,Iris-versicolor
5,2.3,3.3,1,Iris-versicolor
5.6,2.7,4.2,1.3,Iris-versicolor
5.7,3,4.2,1.2,Iris-versicolor
5.7,2.9,4.2,1.3,Iris-versicolor
6.2,2.9,4.3,1.3,Iris-versicolor
5.1,2.5,3,1.1,Iris-versicolor
5.7,2.8,4.1,1.3,Iris-versicolor
6.3,3.3,6,2.5,Iris-virginica
5.8,2.7,5.1,1.9,Iris-virginica
7.1,3,5.9,2.1,Iris-virginica
6.3,2.9,5.6,1.8,Iris-virginica
6.5,3,5.8,2.2,Iris-virginica
7.6,3,6.6,2.1,Iris-virginica
4.9,2.5,4.5,1.7,Iris-virginica
7.3,2.9,6.3,1.8,Iris-virginica
6.7,2.5,5.8,1.8,Iris-virginica
7.2,3.6,6.1,2.5,Iris-virginica
6.5,3.2,5.1,2,Iris-virginica
6.4,2.7,5.3,1.9,Iris-virginica
6.8,3,5.5,2.1,Iris-virginica
5.7,2.5,5,2,Iris-virginica
5.8,2.8,5.1,2.4,Iris-virginica
6.4,3.2,5.3,2.3,Iris-virginica
6.5,3,5.5,1.8,Iris-virginica
7.7,3.8,6.7,2.2,Iris-virginica
7.7,2.6,6.9,2.3,Iris-virginica
6,2.2,5,1.5,Iris-virginica
6.9,3.2,5.7,2.3,Iris-virginica
5.6,2.8,4.9,2,Iris-virginica
7.7,2.8,6.7,2,Iris-virginica
6.3,2.7,4.9,1.8,Iris-virginica
6.7,3.3,5.7,2.1,Iris-virginica
7.2,3.2,6,1.8,Iris-virginica
6.2,2.8,4.8,1.8,Iris-virginica
6.1,3,4.9,1.8,Iris-virginica
6.4,2.8,5.6,2.1,Iris-virginica
7.2,3,5.8,1.6,Iris-virginica
7.4,2.8,6.1,1.9,Iris-virginica
7.9,3.8,6.4,2,Iris-virginica
6.4,2.8,5.6,2.2,Iris-virginica
6.3,2.8,5.1,1.5,Iris-virginica
6.1,2.6,5.6,1.4,Iris-virginica
7.7,3,6.1,2.3,Iris-virginica
6.3,3.4,5.6,2.4,Iris-virginica
6.4,3.1,5.5,1.8,Iris-virginica
6,3,4.8,1.8,Iris-virginica
6.9,3.1,5.4,2.1,Iris-virginica
6.7,3.1,5.6,2.4,Iris-virginica
6.9,3.1,5.1,2.3,Iris-virginica
5.8,2.7,5.1,1.9,Iris-virginica
6.8,3.2,5.9,2.3,Iris-virginica
6.7,3.3,5.7,2.5,Iris-virginica
6.7,3,5.2,2.3,Iris-virginica
6.3,2.5,5,1.9,Iris-virginica
6.5,3,5.2,2,Iris-virginica
6.2,3.4,5.4,2.3,Iris-virginica
5.9,3,5.1,1.8,Iris-virginica
1 sepal_length sepal_width petal_length petal_width species
2 5.1 3.5 1.4 0.2 Iris-setosa
3 4.9 3 1.4 0.2 Iris-setosa
4 4.7 3.2 1.3 0.2 Iris-setosa
5 4.6 3.1 1.5 0.2 Iris-setosa
6 5 3.6 1.4 0.2 Iris-setosa
7 5.4 3.9 1.7 0.4 Iris-setosa
8 4.6 3.4 1.4 0.3 Iris-setosa
9 5 3.4 1.5 0.2 Iris-setosa
10 4.4 2.9 1.4 0.2 Iris-setosa
11 4.9 3.1 1.5 0.1 Iris-setosa
12 5.4 3.7 1.5 0.2 Iris-setosa
13 4.8 3.4 1.6 0.2 Iris-setosa
14 4.8 3 1.4 0.1 Iris-setosa
15 4.3 3 1.1 0.1 Iris-setosa
16 5.8 4 1.2 0.2 Iris-setosa
17 5.7 4.4 1.5 0.4 Iris-setosa
18 5.4 3.9 1.3 0.4 Iris-setosa
19 5.1 3.5 1.4 0.3 Iris-setosa
20 5.7 3.8 1.7 0.3 Iris-setosa
21 5.1 3.8 1.5 0.3 Iris-setosa
22 5.4 3.4 1.7 0.2 Iris-setosa
23 5.1 3.7 1.5 0.4 Iris-setosa
24 4.6 3.6 1 0.2 Iris-setosa
25 5.1 3.3 1.7 0.5 Iris-setosa
26 4.8 3.4 1.9 0.2 Iris-setosa
27 5 3 1.6 0.2 Iris-setosa
28 5 3.4 1.6 0.4 Iris-setosa
29 5.2 3.5 1.5 0.2 Iris-setosa
30 5.2 3.4 1.4 0.2 Iris-setosa
31 4.7 3.2 1.6 0.2 Iris-setosa
32 4.8 3.1 1.6 0.2 Iris-setosa
33 5.4 3.4 1.5 0.4 Iris-setosa
34 5.2 4.1 1.5 0.1 Iris-setosa
35 5.5 4.2 1.4 0.2 Iris-setosa
36 4.9 3.1 1.5 0.1 Iris-setosa
37 5 3.2 1.2 0.2 Iris-setosa
38 5.5 3.5 1.3 0.2 Iris-setosa
39 4.9 3.1 1.5 0.1 Iris-setosa
40 4.4 3 1.3 0.2 Iris-setosa
41 5.1 3.4 1.5 0.2 Iris-setosa
42 5 3.5 1.3 0.3 Iris-setosa
43 4.5 2.3 1.3 0.3 Iris-setosa
44 4.4 3.2 1.3 0.2 Iris-setosa
45 5 3.5 1.6 0.6 Iris-setosa
46 5.1 3.8 1.9 0.4 Iris-setosa
47 4.8 3 1.4 0.3 Iris-setosa
48 5.1 3.8 1.6 0.2 Iris-setosa
49 4.6 3.2 1.4 0.2 Iris-setosa
50 5.3 3.7 1.5 0.2 Iris-setosa
51 5 3.3 1.4 0.2 Iris-setosa
52 7 3.2 4.7 1.4 Iris-versicolor
53 6.4 3.2 4.5 1.5 Iris-versicolor
54 6.9 3.1 4.9 1.5 Iris-versicolor
55 5.5 2.3 4 1.3 Iris-versicolor
56 6.5 2.8 4.6 1.5 Iris-versicolor
57 5.7 2.8 4.5 1.3 Iris-versicolor
58 6.3 3.3 4.7 1.6 Iris-versicolor
59 4.9 2.4 3.3 1 Iris-versicolor
60 6.6 2.9 4.6 1.3 Iris-versicolor
61 5.2 2.7 3.9 1.4 Iris-versicolor
62 5 2 3.5 1 Iris-versicolor
63 5.9 3 4.2 1.5 Iris-versicolor
64 6 2.2 4 1 Iris-versicolor
65 6.1 2.9 4.7 1.4 Iris-versicolor
66 5.6 2.9 3.6 1.3 Iris-versicolor
67 6.7 3.1 4.4 1.4 Iris-versicolor
68 5.6 3 4.5 1.5 Iris-versicolor
69 5.8 2.7 4.1 1 Iris-versicolor
70 6.2 2.2 4.5 1.5 Iris-versicolor
71 5.6 2.5 3.9 1.1 Iris-versicolor
72 5.9 3.2 4.8 1.8 Iris-versicolor
73 6.1 2.8 4 1.3 Iris-versicolor
74 6.3 2.5 4.9 1.5 Iris-versicolor
75 6.1 2.8 4.7 1.2 Iris-versicolor
76 6.4 2.9 4.3 1.3 Iris-versicolor
77 6.6 3 4.4 1.4 Iris-versicolor
78 6.8 2.8 4.8 1.4 Iris-versicolor
79 6.7 3 5 1.7 Iris-versicolor
80 6 2.9 4.5 1.5 Iris-versicolor
81 5.7 2.6 3.5 1 Iris-versicolor
82 5.5 2.4 3.8 1.1 Iris-versicolor
83 5.5 2.4 3.7 1 Iris-versicolor
84 5.8 2.7 3.9 1.2 Iris-versicolor
85 6 2.7 5.1 1.6 Iris-versicolor
86 5.4 3 4.5 1.5 Iris-versicolor
87 6 3.4 4.5 1.6 Iris-versicolor
88 6.7 3.1 4.7 1.5 Iris-versicolor
89 6.3 2.3 4.4 1.3 Iris-versicolor
90 5.6 3 4.1 1.3 Iris-versicolor
91 5.5 2.5 4 1.3 Iris-versicolor
92 5.5 2.6 4.4 1.2 Iris-versicolor
93 6.1 3 4.6 1.4 Iris-versicolor
94 5.8 2.6 4 1.2 Iris-versicolor
95 5 2.3 3.3 1 Iris-versicolor
96 5.6 2.7 4.2 1.3 Iris-versicolor
97 5.7 3 4.2 1.2 Iris-versicolor
98 5.7 2.9 4.2 1.3 Iris-versicolor
99 6.2 2.9 4.3 1.3 Iris-versicolor
100 5.1 2.5 3 1.1 Iris-versicolor
101 5.7 2.8 4.1 1.3 Iris-versicolor
102 6.3 3.3 6 2.5 Iris-virginica
103 5.8 2.7 5.1 1.9 Iris-virginica
104 7.1 3 5.9 2.1 Iris-virginica
105 6.3 2.9 5.6 1.8 Iris-virginica
106 6.5 3 5.8 2.2 Iris-virginica
107 7.6 3 6.6 2.1 Iris-virginica
108 4.9 2.5 4.5 1.7 Iris-virginica
109 7.3 2.9 6.3 1.8 Iris-virginica
110 6.7 2.5 5.8 1.8 Iris-virginica
111 7.2 3.6 6.1 2.5 Iris-virginica
112 6.5 3.2 5.1 2 Iris-virginica
113 6.4 2.7 5.3 1.9 Iris-virginica
114 6.8 3 5.5 2.1 Iris-virginica
115 5.7 2.5 5 2 Iris-virginica
116 5.8 2.8 5.1 2.4 Iris-virginica
117 6.4 3.2 5.3 2.3 Iris-virginica
118 6.5 3 5.5 1.8 Iris-virginica
119 7.7 3.8 6.7 2.2 Iris-virginica
120 7.7 2.6 6.9 2.3 Iris-virginica
121 6 2.2 5 1.5 Iris-virginica
122 6.9 3.2 5.7 2.3 Iris-virginica
123 5.6 2.8 4.9 2 Iris-virginica
124 7.7 2.8 6.7 2 Iris-virginica
125 6.3 2.7 4.9 1.8 Iris-virginica
126 6.7 3.3 5.7 2.1 Iris-virginica
127 7.2 3.2 6 1.8 Iris-virginica
128 6.2 2.8 4.8 1.8 Iris-virginica
129 6.1 3 4.9 1.8 Iris-virginica
130 6.4 2.8 5.6 2.1 Iris-virginica
131 7.2 3 5.8 1.6 Iris-virginica
132 7.4 2.8 6.1 1.9 Iris-virginica
133 7.9 3.8 6.4 2 Iris-virginica
134 6.4 2.8 5.6 2.2 Iris-virginica
135 6.3 2.8 5.1 1.5 Iris-virginica
136 6.1 2.6 5.6 1.4 Iris-virginica
137 7.7 3 6.1 2.3 Iris-virginica
138 6.3 3.4 5.6 2.4 Iris-virginica
139 6.4 3.1 5.5 1.8 Iris-virginica
140 6 3 4.8 1.8 Iris-virginica
141 6.9 3.1 5.4 2.1 Iris-virginica
142 6.7 3.1 5.6 2.4 Iris-virginica
143 6.9 3.1 5.1 2.3 Iris-virginica
144 5.8 2.7 5.1 1.9 Iris-virginica
145 6.8 3.2 5.9 2.3 Iris-virginica
146 6.7 3.3 5.7 2.5 Iris-virginica
147 6.7 3 5.2 2.3 Iris-virginica
148 6.3 2.5 5 1.9 Iris-virginica
149 6.5 3 5.2 2 Iris-virginica
150 6.2 3.4 5.4 2.3 Iris-virginica
151 5.9 3 5.1 1.8 Iris-virginica

View File

@@ -25,6 +25,7 @@ Machine Learning notebook samples and encourage efficient retrieval of topics an
| [Forecasting away from training data](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/automated-machine-learning/forecasting-forecast-function/auto-ml-forecasting-function.ipynb) | Forecasting | None | Remote | None | Azure ML AutoML | Forecasting, Confidence Intervals | | [Forecasting away from training data](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/automated-machine-learning/forecasting-forecast-function/auto-ml-forecasting-function.ipynb) | Forecasting | None | Remote | None | Azure ML AutoML | Forecasting, Confidence Intervals |
| [Automated ML run with basic edition features.](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/automated-machine-learning/classification-bank-marketing-all-features/auto-ml-classification-bank-marketing-all-features.ipynb) | Classification | Bankmarketing | AML | ACI | None | featurization, explainability, remote_run, AutomatedML | | [Automated ML run with basic edition features.](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/automated-machine-learning/classification-bank-marketing-all-features/auto-ml-classification-bank-marketing-all-features.ipynb) | Classification | Bankmarketing | AML | ACI | None | featurization, explainability, remote_run, AutomatedML |
| [Classification of credit card fraudulent transactions using Automated ML](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/automated-machine-learning/classification-credit-card-fraud/auto-ml-classification-credit-card-fraud.ipynb) | Classification | Creditcard | AML Compute | None | None | remote_run, AutomatedML | | [Classification of credit card fraudulent transactions using Automated ML](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/automated-machine-learning/classification-credit-card-fraud/auto-ml-classification-credit-card-fraud.ipynb) | Classification | Creditcard | AML Compute | None | None | remote_run, AutomatedML |
| [Classification of credit card fraudulent transactions using Automated ML](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/automated-machine-learning/experimental/classification-credit-card-fraud-local-managed/auto-ml-classification-credit-card-fraud-local-managed.ipynb) | Classification | Creditcard | AML Compute | None | None | AutomatedML |
| [Automated ML run with featurization and model explainability.](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/automated-machine-learning/regression-explanation-featurization/auto-ml-regression-explanation-featurization.ipynb) | Regression | MachineData | AML | ACI | None | featurization, explainability, remote_run, AutomatedML | | [Automated ML run with featurization and model explainability.](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/automated-machine-learning/regression-explanation-featurization/auto-ml-regression-explanation-featurization.ipynb) | Regression | MachineData | AML | ACI | None | featurization, explainability, remote_run, AutomatedML |
| :star:[Azure Machine Learning Pipeline with DataTranferStep](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-data-transfer.ipynb) | Demonstrates the use of DataTranferStep | Custom | ADF | None | Azure ML | None | | :star:[Azure Machine Learning Pipeline with DataTranferStep](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-data-transfer.ipynb) | Demonstrates the use of DataTranferStep | Custom | ADF | None | Azure ML | None |
| [Getting Started with Azure Machine Learning Pipelines](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-getting-started.ipynb) | Getting Started notebook for ANML Pipelines | Custom | AML Compute | None | Azure ML | None | | [Getting Started with Azure Machine Learning Pipelines](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-getting-started.ipynb) | Getting Started notebook for ANML Pipelines | Custom | AML Compute | None | Azure ML | None |
@@ -106,11 +107,15 @@ Machine Learning notebook samples and encourage efficient retrieval of topics an
| [auto-ml-regression-model-proxy](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/automated-machine-learning/experimental/regression-model-proxy/auto-ml-regression-model-proxy.ipynb) | | | | | | | | [auto-ml-regression-model-proxy](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/automated-machine-learning/experimental/regression-model-proxy/auto-ml-regression-model-proxy.ipynb) | | | | | | |
| [auto-ml-forecasting-beer-remote](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/automated-machine-learning/forecasting-beer-remote/auto-ml-forecasting-beer-remote.ipynb) | | | | | | | | [auto-ml-forecasting-beer-remote](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/automated-machine-learning/forecasting-beer-remote/auto-ml-forecasting-beer-remote.ipynb) | | | | | | |
| [auto-ml-forecasting-energy-demand](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/automated-machine-learning/forecasting-energy-demand/auto-ml-forecasting-energy-demand.ipynb) | | | | | | | | [auto-ml-forecasting-energy-demand](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/automated-machine-learning/forecasting-energy-demand/auto-ml-forecasting-energy-demand.ipynb) | | | | | | |
| [auto-ml-forecasting-univariate-recipe-experiment-settings](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/automated-machine-learning/forecasting-recipes-univariate/auto-ml-forecasting-univariate-recipe-experiment-settings.ipynb) | | | | | | |
| [auto-ml-forecasting-univariate-recipe-run-experiment](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/automated-machine-learning/forecasting-recipes-univariate/auto-ml-forecasting-univariate-recipe-run-experiment.ipynb) | | | | | | |
| [auto-ml-regression](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/automated-machine-learning/regression/auto-ml-regression.ipynb) | | | | | | | | [auto-ml-regression](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/automated-machine-learning/regression/auto-ml-regression.ipynb) | | | | | | |
| [automl-databricks-local-01](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/azure-databricks/automl/automl-databricks-local-01.ipynb) | | | | | | | | [automl-databricks-local-01](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/azure-databricks/automl/automl-databricks-local-01.ipynb) | | | | | | |
| [automl-databricks-local-with-deployment](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/azure-databricks/automl/automl-databricks-local-with-deployment.ipynb) | | | | | | | | [automl-databricks-local-with-deployment](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/azure-databricks/automl/automl-databricks-local-with-deployment.ipynb) | | | | | | |
| [spark_job_on_synapse_spark_pool](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/azure-synapse/spark_job_on_synapse_spark_pool.ipynb) | | | | | | | | [spark_job_on_synapse_spark_pool](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/azure-synapse/spark_job_on_synapse_spark_pool.ipynb) | | | | | | |
| [spark_session_on_synapse_spark_pool](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/azure-synapse/spark_session_on_synapse_spark_pool.ipynb) | | | | | | | | [spark_session_on_synapse_spark_pool](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/azure-synapse/spark_session_on_synapse_spark_pool.ipynb) | | | | | | |
| [Synapse_Job_Scala_Support](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/azure-synapse/Synapse_Job_Scala_Support.ipynb) | | | | | | |
| [Synapse_Session_Scala_Support](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/azure-synapse/Synapse_Session_Scala_Support.ipynb) | | | | | | |
| [multi-model-register-and-deploy](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/deployment/deploy-multi-model/multi-model-register-and-deploy.ipynb) | | | | | | | | [multi-model-register-and-deploy](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/deployment/deploy-multi-model/multi-model-register-and-deploy.ipynb) | | | | | | |
| [register-model-deploy-local-advanced](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/deployment/deploy-to-local/register-model-deploy-local-advanced.ipynb) | | | | | | | | [register-model-deploy-local-advanced](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/deployment/deploy-to-local/register-model-deploy-local-advanced.ipynb) | | | | | | |
| [enable-app-insights-in-production-service](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/deployment/enable-app-insights-in-production-service/enable-app-insights-in-production-service.ipynb) | | | | | | | | [enable-app-insights-in-production-service](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/deployment/enable-app-insights-in-production-service/enable-app-insights-in-production-service.ipynb) | | | | | | |

View File

@@ -102,7 +102,7 @@
"source": [ "source": [
"import azureml.core\n", "import azureml.core\n",
"\n", "\n",
"print(\"This notebook was created using version 1.29.0 of the Azure ML SDK\")\n", "print(\"This notebook was created using version 1.33.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\")"
] ]
}, },

View File

@@ -23,59 +23,9 @@
"\n", "\n",
"You'll learn how to:\n", "You'll learn how to:\n",
"\n", "\n",
"> * Download a dataset and look at the data\n", "* Download a dataset and look at the data\n",
"> * Train an image classification model and log metrics\n", "* Train an image classification model and log metrics using MLflow\n",
"> * Deploy the model" "* Deploy the model to do real-time inference"
]
},
{
"cell_type": "markdown",
"metadata": {
"nteract": {
"transient": {
"deleting": false
}
}
},
"source": [
"## Connect to your workspace and create an experiment\n",
"\n",
"Import some libraries and create an experiment to track the runs in your workspace. A workspace can have multiple experiments, and all users that have access to the workspace can collaborate on them."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"gather": {
"logged": 1612965916889
},
"jupyter": {
"outputs_hidden": false,
"source_hidden": false
},
"nteract": {
"transient": {
"deleting": false
}
}
},
"outputs": [],
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"\n",
"import azureml.core\n",
"from azureml.core import Workspace\n",
"from azureml.core import Experiment\n",
"\n",
"# connect to your workspace\n",
"ws = Workspace.from_config()\n",
"\n",
"# create experiment and start logging to a new run in the experiment\n",
"experiment_name = \"azure-ml-in10-mins-tutorial\"\n",
"exp = Experiment(workspace=ws, name=experiment_name)\n",
"run = exp.start_logging(snapshot_directory=None)"
] ]
}, },
{ {
@@ -95,46 +45,23 @@
"* Download the MNIST dataset\n", "* Download the MNIST dataset\n",
"* Display some sample images\n", "* Display some sample images\n",
"\n", "\n",
"### Download the MNIST dataset\n",
"\n",
"You'll use Azure Open Datasets to get the raw MNIST data files. [Azure Open Datasets](https://docs.microsoft.com/azure/open-datasets/overview-what-are-open-datasets) are curated public datasets that you can use to add scenario-specific features to machine learning solutions for better models. Each dataset has a corresponding class, `MNIST` in this case, to retrieve the data in different ways." "You'll use Azure Open Datasets to get the raw MNIST data files. [Azure Open Datasets](https://docs.microsoft.com/azure/open-datasets/overview-what-are-open-datasets) are curated public datasets that you can use to add scenario-specific features to machine learning solutions for better models. Each dataset has a corresponding class, `MNIST` in this case, to retrieve the data in different ways."
] ]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {},
"gather": {
"logged": 1612965922274
},
"jupyter": {
"outputs_hidden": false,
"source_hidden": false
},
"nteract": {
"transient": {
"deleting": false
}
}
},
"outputs": [], "outputs": [],
"source": [ "source": [
"import os\n", "import os\n",
"from azureml.core import Dataset\n",
"from azureml.opendatasets import MNIST\n", "from azureml.opendatasets import MNIST\n",
"\n", "\n",
"data_folder = os.path.join(os.getcwd(), \"data\")\n", "data_folder = os.path.join(os.getcwd(), \"/tmp/qs_data\")\n",
"os.makedirs(data_folder, exist_ok=True)\n", "os.makedirs(data_folder, exist_ok=True)\n",
"\n", "\n",
"mnist_file_dataset = MNIST.get_file_dataset()\n", "mnist_file_dataset = MNIST.get_file_dataset()\n",
"mnist_file_dataset.download(data_folder, overwrite=True)\n", "mnist_file_dataset.download(data_folder, overwrite=True)"
"\n",
"mnist_file_dataset = mnist_file_dataset.register(\n",
" workspace=ws,\n",
" name=\"mnist_opendataset\",\n",
" description=\"training and test dataset\",\n",
" create_new_version=True,\n",
")"
] ]
}, },
{ {
@@ -157,20 +84,7 @@
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {},
"gather": {
"logged": 1612965929041
},
"jupyter": {
"outputs_hidden": false,
"source_hidden": false
},
"nteract": {
"transient": {
"deleting": false
}
}
},
"outputs": [], "outputs": [],
"source": [ "source": [
"from utils import load_data\n", "from utils import load_data\n",
@@ -236,13 +150,13 @@
} }
}, },
"source": [ "source": [
"## Train model and log metrics\n", "## Train model and log metrics with MLflow\n",
"\n", "\n",
"You'll train the model using the code below. Your training runs and metrics will be registered in the experiment you created, so that this information is available after you've finished.\n", "You'll train the model using the code below. Note that you are using MLflow autologging to track metrics and log model artefacts.\n",
"\n", "\n",
"You'll be using the [LogisticRegression](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html) classifier from the [SciKit Learn framework](https://scikit-learn.org/) to classify the data.\n", "You'll be using the [LogisticRegression](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html) classifier from the [SciKit Learn framework](https://scikit-learn.org/) to classify the data.\n",
"\n", "\n",
"> **Note: The model training takes around 1 minute to complete.**" "**Note: The model training takes approximately 2 minutes to complete.**"
] ]
}, },
{ {
@@ -265,41 +179,43 @@
"outputs": [], "outputs": [],
"source": [ "source": [
"# create the model\n", "# create the model\n",
"import mlflow\n",
"import numpy as np\n", "import numpy as np\n",
"from sklearn.linear_model import LogisticRegression\n", "from sklearn.linear_model import LogisticRegression\n",
"from azureml.core import Workspace\n",
"\n", "\n",
"# connect to your workspace\n",
"ws = Workspace.from_config()\n",
"\n",
"# create experiment and start logging to a new run in the experiment\n",
"experiment_name = \"azure-ml-in10-mins-tutorial\"\n",
"\n",
"# set up MLflow to track the metrics\n",
"mlflow.set_tracking_uri(ws.get_mlflow_tracking_uri())\n",
"mlflow.set_experiment(experiment_name)\n",
"mlflow.autolog()\n",
"\n",
"# set up the Logistic regression model\n",
"reg = 0.5\n", "reg = 0.5\n",
"clf = LogisticRegression(\n", "clf = LogisticRegression(\n",
" C=1.0 / reg, solver=\"liblinear\", multi_class=\"auto\", random_state=42\n", " C=1.0 / reg, solver=\"liblinear\", multi_class=\"auto\", random_state=42\n",
")\n", ")\n",
"clf.fit(X_train, y_train)\n",
"\n", "\n",
"# make predictions using the test set and calculate the accuracy\n", "# train the model\n",
"y_hat = clf.predict(X_test)\n", "with mlflow.start_run() as run:\n",
"\n", " clf.fit(X_train, y_train)"
"# calculate accuracy on the prediction\n",
"acc = np.average(y_hat == y_test)\n",
"print(\"Accuracy is\", acc)\n",
"\n",
"run.log(\"regularization rate\", np.float(reg))\n",
"run.log(\"accuracy\", np.float(acc))"
] ]
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {}, "metadata": {},
"source": [ "source": [
"## View Experiment\n",
"In the left-hand menu in Azure Machine Learning Studio, select __Experiments__ and then select your experiment (azure-ml-in10-mins-tutorial). An experiment is a grouping of many runs from a specified script or piece of code. Information for the run is stored under that experiment. If the name doesn't exist when you submit an experiment, if you select your run you will see various tabs containing metrics, logs, explanations, etc.\n",
"\n", "\n",
"## Version control your models with the model registry\n", "## Version control your models with the model registry\n",
"\n", "\n",
"You can use model registration to store and version your models in your workspace. Registered models are identified by name and version. Each time you register a model with the same name as an existing one, the registry increments the version. Azure Machine Learning supports any model that can be loaded through Python 3.\n", "You can use model registration to store and version your models in your workspace. Registered models are identified by name and version. Each time you register a model with the same name as an existing one, the registry increments the version. The code below registers and versions the model you trained above. Once you have executed the code cell below you will be able to see the model in the registry by selecting __Models__ in the left-hand menu in Azure Machine Learning Studio."
"\n",
"The code below:\n",
"\n",
"1. Saves the model to disk\n",
"1. Uploads the model file to the run \n",
"1. Registers the uploaded model file\n",
"1. Transitions the run to a completed state"
] ]
}, },
{ {
@@ -321,30 +237,20 @@
}, },
"outputs": [], "outputs": [],
"source": [ "source": [
"import joblib\n", "# register the model\n",
"from azureml.core.model import Model\n", "model_uri = \"runs:/{}/model\".format(run.info.run_id)\n",
"\n", "model = mlflow.register_model(model_uri, \"sklearn_mnist_model\")"
"path = \"sklearn_mnist_model.pkl\"\n",
"joblib.dump(value=clf, filename=path)\n",
"\n",
"run.upload_file(name=path, path_or_stream=path)\n",
"\n",
"model = run.register_model(\n",
" model_name=\"sklearn_mnist_model\",\n",
" model_path=path,\n",
" description=\"Mnist handwriting recognition\",\n",
")\n",
"\n",
"run.complete()"
] ]
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {}, "metadata": {},
"source": [ "source": [
"## Deploy the model\n", "## Deploy the model for real-time inference\n",
"In this section you learn how to deploy a model so that an application can consume (inference) the model over REST.\n",
"\n", "\n",
"The next cell deploys the model to an Azure Container Instance so that you can score data in real-time (Azure Machine Learning also provides mechanisms to do batch scoring). A real-time endpoint allows application developers to integrate machine learning into their apps." "### Create deployment configuration\n",
"The code cell gets a _curated environment_, which specifies all the dependencies required to host the model (for example, the packages like scikit-learn). Also, you create a _deployment configuration_, which specifies the amount of compute required to host the model. In this case, the compute will have 1CPU and 1GB memory."
] ]
}, },
{ {
@@ -369,22 +275,17 @@
"# create environment for the deploy\n", "# create environment for the deploy\n",
"from azureml.core.environment import Environment\n", "from azureml.core.environment import Environment\n",
"from azureml.core.conda_dependencies import CondaDependencies\n", "from azureml.core.conda_dependencies import CondaDependencies\n",
"\n",
"# to install required packages\n",
"env = Environment(\"quickstart-env\")\n",
"cd = CondaDependencies.create(\n",
" pip_packages=[\"azureml-dataset-runtime[pandas,fuse]\", \"azureml-defaults\"],\n",
" conda_packages=[\"scikit-learn==0.22.1\"],\n",
")\n",
"\n",
"env.python.conda_dependencies = cd\n",
"\n",
"# Register environment to re-use later\n",
"env.register(workspace=ws)\n",
"\n",
"# create config file\n",
"from azureml.core.webservice import AciWebservice\n", "from azureml.core.webservice import AciWebservice\n",
"\n", "\n",
"# get a curated environment\n",
"env = Environment.get(\n",
" workspace=ws, \n",
" name=\"AzureML-sklearn-0.24.1-ubuntu18.04-py37-cpu-inference\",\n",
" version=1\n",
")\n",
"env.inferencing_stack_version='latest'\n",
"\n",
"# create deployment config i.e. compute resources\n",
"aciconfig = AciWebservice.deploy_configuration(\n", "aciconfig = AciWebservice.deploy_configuration(\n",
" cpu_cores=1,\n", " cpu_cores=1,\n",
" memory_gb=1,\n", " memory_gb=1,\n",
@@ -403,7 +304,11 @@
} }
}, },
"source": [ "source": [
"> **Note: The deployment takes around 3 minutes to complete.**" "### Deploy model\n",
"\n",
"This next code cell deploys the model to Azure Container Instance (ACI).\n",
"\n",
"**Note: The deployment takes approximately 3 minutes to complete.**"
] ]
}, },
{ {
@@ -424,19 +329,17 @@
"source": [ "source": [
"%%time\n", "%%time\n",
"import uuid\n", "import uuid\n",
"from azureml.core.webservice import Webservice\n",
"from azureml.core.model import InferenceConfig\n", "from azureml.core.model import InferenceConfig\n",
"from azureml.core.environment import Environment\n", "from azureml.core.environment import Environment\n",
"from azureml.core import Workspace\n",
"from azureml.core.model import Model\n", "from azureml.core.model import Model\n",
"\n", "\n",
"ws = Workspace.from_config()\n", "# get the registered model\n",
"model = Model(ws, \"sklearn_mnist_model\")\n", "model = Model(ws, \"sklearn_mnist_model\")\n",
"\n", "\n",
"# create an inference config i.e. the scoring script and environment\n",
"inference_config = InferenceConfig(entry_script=\"score.py\", environment=env)\n",
"\n", "\n",
"myenv = Environment.get(workspace=ws, name=\"quickstart-env\", version=\"1\")\n", "# deploy the service\n",
"inference_config = InferenceConfig(entry_script=\"score.py\", environment=myenv)\n",
"\n",
"service_name = \"sklearn-mnist-svc-\" + str(uuid.uuid4())[:4]\n", "service_name = \"sklearn-mnist-svc-\" + str(uuid.uuid4())[:4]\n",
"service = Model.deploy(\n", "service = Model.deploy(\n",
" workspace=ws,\n", " workspace=ws,\n",
@@ -456,7 +359,10 @@
"The [*scoring script*](score.py) file referenced in the code above can be found in the same folder as this notebook, and has two functions:\n", "The [*scoring script*](score.py) file referenced in the code above can be found in the same folder as this notebook, and has two functions:\n",
"\n", "\n",
"1. an `init` function that executes once when the service starts - in this function you normally get the model from the registry and set global variables\n", "1. an `init` function that executes once when the service starts - in this function you normally get the model from the registry and set global variables\n",
"1. a `run(data)` function that executes each time a call is made to the service. In this function, you normally format the input data, run a prediction, and output the predicted result." "1. a `run(data)` function that executes each time a call is made to the service. In this function, you normally format the input data, run a prediction, and output the predicted result.\n",
"\n",
"### View Endpoint\n",
"Once the model has been successfully deployed, you can view the endpoint by navigating to __Endpoints__ in the left-hand menu in Azure Machine Learning Studio. You will be able to see the state of the endpoint (healthy/unhealthy), logs, and consume (how applications can consume the model)."
] ]
}, },
{ {
@@ -474,29 +380,6 @@
"You can test the model by sending a raw HTTP request to test the web service. " "You can test the model by sending a raw HTTP request to test the web service. "
] ]
}, },
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"gather": {
"logged": 1612881527399
},
"jupyter": {
"outputs_hidden": false,
"source_hidden": false
},
"nteract": {
"transient": {
"deleting": false
}
}
},
"outputs": [],
"source": [
"# scoring web service HTTP endpoint\n",
"print(service.scoring_uri)"
]
},
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
@@ -525,56 +408,13 @@
"\n", "\n",
"headers = {\"Content-Type\": \"application/json\"}\n", "headers = {\"Content-Type\": \"application/json\"}\n",
"\n", "\n",
"# for AKS deployment you'd need to the service key in the header as well\n",
"# api_key = service.get_key()\n",
"# headers = {'Content-Type':'application/json', 'Authorization':('Bearer '+ api_key)}\n",
"\n",
"resp = requests.post(service.scoring_uri, input_data, headers=headers)\n", "resp = requests.post(service.scoring_uri, input_data, headers=headers)\n",
"\n", "\n",
"print(\"POST to url\", service.scoring_uri)\n", "print(\"POST to url\", service.scoring_uri)\n",
"# print(\"input data:\", input_data)\n",
"print(\"label:\", y_test[random_index])\n", "print(\"label:\", y_test[random_index])\n",
"print(\"prediction:\", resp.text)" "print(\"prediction:\", resp.text)"
] ]
}, },
{
"cell_type": "markdown",
"metadata": {
"nteract": {
"transient": {
"deleting": false
}
}
},
"source": [
"\n",
"### View the results of your training\n",
"\n",
"When you're finished with an experiment run, you can always return to view the results of your model training here in the Azure Machine Learning studio:\n",
"\n",
"1. Select **Experiments** (left-hand menu)\n",
"1. Select **azure-ml-in10-mins-tutorial**\n",
"1. Select **Run 1**\n",
"1. Select the **Metrics** Tab\n",
"\n",
"The metrics tab will display the parameter values that were logged to the run."
]
},
{
"cell_type": "markdown",
"metadata": {
"nteract": {
"transient": {
"deleting": false
}
}
},
"source": [
"### View the model in the model registry\n",
"\n",
"You can see the stored model by navigating to **Models** in the left-hand menu bar. Select the **sklearn_mnist_model** to see the details of the model, including the experiment run ID that created the model."
]
},
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {}, "metadata": {},

View File

@@ -9,7 +9,7 @@ def init():
# AZUREML_MODEL_DIR is an environment variable created during deployment. # AZUREML_MODEL_DIR is an environment variable created during deployment.
# It is the path to the model folder (./azureml-models/$MODEL_NAME/$VERSION) # It is the path to the model folder (./azureml-models/$MODEL_NAME/$VERSION)
# For multiple models, it points to the folder containing all deployed models (./azureml-models) # For multiple models, it points to the folder containing all deployed models (./azureml-models)
model_path = os.path.join(os.getenv("AZUREML_MODEL_DIR"), "sklearn_mnist_model.pkl") model_path = os.path.join(os.getenv("AZUREML_MODEL_DIR"), "model/model.pkl")
model = joblib.load(model_path) model = joblib.load(model_path)

View File

@@ -17,12 +17,9 @@
} }
}, },
"source": [ "source": [
"# Quickstart: Learn how to get started with Azure ML Job Submission\n", "# Quickstart: Learn how to submit batch jobs with the Azure Machine Learning Python SDK\n",
"\n", "\n",
"In this quickstart, you train a machine learning model by submitting a Job to a compute target. \n", "In this quickstart, you learn how to submit a batch training job using the Python SDK. In this example, we submit the job to the 'local' machine (the compute instance you are running this notebook on). However, you can use exactly the same method to submit the job to different compute targets (for example, AKS, Azure Machine Learning Compute Cluster, Synapse, etc) by changing a single line of code. A full list of support compute targets can be viewed [here](https://docs.microsoft.com/en-us/azure/machine-learning/concept-compute-target). \n",
"When training, it is common to start on your local computer, and then later scale out to a cloud-based cluster. \n",
"\n",
"All you need to do is define the environment for each compute target within a script run configuration. Then, when you want to run your training experiment on a different compute target, specify the run configuration for that compute.\n",
"\n", "\n",
"This quickstart trains a simple logistic regression using the [MNIST](https://azure.microsoft.com/services/open-datasets/catalog/mnist/) dataset and [scikit-learn](http://scikit-learn.org) with Azure Machine Learning. MNIST is a popular dataset consisting of 70,000 grayscale images. Each image is a handwritten digit of 28x28 pixels, representing a number from 0 to 9. The goal is to create a multi-class classifier to identify the digit a given image represents. \n", "This quickstart trains a simple logistic regression using the [MNIST](https://azure.microsoft.com/services/open-datasets/catalog/mnist/) dataset and [scikit-learn](http://scikit-learn.org) with Azure Machine Learning. MNIST is a popular dataset consisting of 70,000 grayscale images. Each image is a handwritten digit of 28x28 pixels, representing a number from 0 to 9. The goal is to create a multi-class classifier to identify the digit a given image represents. \n",
"\n", "\n",
@@ -30,6 +27,7 @@
"\n", "\n",
"> * Download a dataset and look at the data\n", "> * Download a dataset and look at the data\n",
"> * Train an image classification model by submitting a batch job to a compute resource\n", "> * Train an image classification model by submitting a batch job to a compute resource\n",
"> * Use MLflow autologging to track model metrics and log the model artefact\n",
"> * Review training results, find and register the best model" "> * Review training results, find and register the best model"
] ]
}, },
@@ -67,16 +65,14 @@
}, },
"outputs": [], "outputs": [],
"source": [ "source": [
"import numpy as np\r\n", "\n",
"import matplotlib.pyplot as plt\r\n", "from azureml.core import Workspace\n",
"\r\n", "from azureml.core import Experiment\n",
"from azureml.core import Workspace\r\n", "\n",
"from azureml.core import Experiment\r\n", "# connect to your workspace\n",
"\r\n", "ws = Workspace.from_config()\n",
"# connect to your workspace\r\n", "\n",
"ws = Workspace.from_config()\r\n", "experiment_name = \"get-started-with-jobsubmission-tutorial\"\n",
"\r\n",
"experiment_name = \"get-started-with-jobsubmission-tutorial\"\r\n",
"exp = Experiment(workspace=ws, name=experiment_name)" "exp = Experiment(workspace=ws, name=experiment_name)"
] ]
}, },
@@ -90,14 +86,7 @@
} }
}, },
"source": [ "source": [
"## Import Data\n", "### The MNIST dataset\n",
"\n",
"Before you train a model, you need to understand the data that you are using to train it. In this section you will:\n",
"\n",
"* Download the MNIST dataset\n",
"* Display some sample images\n",
"\n",
"### Download the MNIST dataset\n",
"\n", "\n",
"Use Azure Open Datasets to get the raw MNIST data files. [Azure Open Datasets](https://docs.microsoft.com/azure/open-datasets/overview-what-are-open-datasets) are curated public datasets that you can use to add scenario-specific features to machine learning solutions for more accurate models. Each dataset has a corresponding class, `MNIST` in this case, to retrieve the data in different ways.\n", "Use Azure Open Datasets to get the raw MNIST data files. [Azure Open Datasets](https://docs.microsoft.com/azure/open-datasets/overview-what-are-open-datasets) are curated public datasets that you can use to add scenario-specific features to machine learning solutions for more accurate models. Each dataset has a corresponding class, `MNIST` in this case, to retrieve the data in different ways.\n",
"\n", "\n",
@@ -123,215 +112,16 @@
}, },
"outputs": [], "outputs": [],
"source": [ "source": [
"import os\n",
"from azureml.core import Dataset\n",
"from azureml.opendatasets import MNIST\n", "from azureml.opendatasets import MNIST\n",
"\n", "\n",
"data_folder = os.path.join(os.getcwd(), \"data\")\n", "mnist_file_dataset = MNIST.get_file_dataset()"
"os.makedirs(data_folder, exist_ok=True)\n",
"\n",
"mnist_file_dataset = MNIST.get_file_dataset()\n",
"mnist_file_dataset.download(data_folder, overwrite=True)\n",
"\n",
"mnist_file_dataset = mnist_file_dataset.register(\n",
" workspace=ws,\n",
" name=\"mnist_opendataset\",\n",
" description=\"training and test dataset\",\n",
" create_new_version=True,\n",
")"
] ]
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {},
"nteract": {
"transient": {
"deleting": false
}
}
},
"source": [
"### Take a look at the data\n",
"You will load the compressed files into `numpy` arrays. Then use `matplotlib` to plot 30 random images from the dataset with their labels above them. Note this step requires a `load_data` function that's included in an `utils.py` file. This file is placed in the same folder as this notebook. The `load_data` function simply parses the compressed files into numpy arrays. \n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"gather": {
"logged": 1612965857960
},
"jupyter": {
"outputs_hidden": false,
"source_hidden": false
},
"nteract": {
"transient": {
"deleting": false
}
}
},
"outputs": [],
"source": [
"# make sure utils.py is in the same directory as this code\r\n",
"from src.utils import load_data\r\n",
"import glob\r\n",
"\r\n",
"\r\n",
"# note we also shrink the intensity values (X) from 0-255 to 0-1. This helps the model converge faster.\r\n",
"X_train = (\r\n",
" load_data(\r\n",
" glob.glob(\r\n",
" os.path.join(data_folder, \"**/train-images-idx3-ubyte.gz\"), recursive=True\r\n",
" )[0],\r\n",
" False,\r\n",
" )\r\n",
" / 255.0\r\n",
")\r\n",
"X_test = (\r\n",
" load_data(\r\n",
" glob.glob(\r\n",
" os.path.join(data_folder, \"**/t10k-images-idx3-ubyte.gz\"), recursive=True\r\n",
" )[0],\r\n",
" False,\r\n",
" )\r\n",
" / 255.0\r\n",
")\r\n",
"y_train = load_data(\r\n",
" glob.glob(\r\n",
" os.path.join(data_folder, \"**/train-labels-idx1-ubyte.gz\"), recursive=True\r\n",
" )[0],\r\n",
" True,\r\n",
").reshape(-1)\r\n",
"y_test = load_data(\r\n",
" glob.glob(\r\n",
" os.path.join(data_folder, \"**/t10k-labels-idx1-ubyte.gz\"), recursive=True\r\n",
" )[0],\r\n",
" True,\r\n",
").reshape(-1)\r\n",
"\r\n",
"\r\n",
"# now let's show some randomly chosen images from the training set.\r\n",
"count = 0\r\n",
"sample_size = 30\r\n",
"plt.figure(figsize=(16, 6))\r\n",
"for i in np.random.permutation(X_train.shape[0])[:sample_size]:\r\n",
" count = count + 1\r\n",
" plt.subplot(1, sample_size, count)\r\n",
" plt.axhline(\"\")\r\n",
" plt.axvline(\"\")\r\n",
" plt.text(x=10, y=-10, s=y_train[i], fontsize=18)\r\n",
" plt.imshow(X_train[i].reshape(28, 28), cmap=plt.cm.Greys)\r\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {
"nteract": {
"transient": {
"deleting": false
}
}
},
"source": [
"## Submit your training job\n",
"\n",
"In this quickstart you submit a job to run on the local compute, but you can use the same code to submit this training job to other compute targets. With Azure Machine Learning, you can run your script on various compute targets without having to change your training script. \n",
"\n",
"To submit a job you need:\n",
"* A directory\n",
"* A training script\n",
"* Create a script run configuration\n",
"* Submit the job \n",
"\n",
"\n",
"### Directory and training script \n",
"\n",
"You need a directory to deliver the necessary code from your computer to the remote resource. A directory with a training script has been created for you and can be found in the same folder as this notebook.\n",
"\n",
"Take a few minutes to examine the training script."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"gather": {
"logged": 1612965865707
},
"jupyter": {
"outputs_hidden": false,
"source_hidden": false
},
"nteract": {
"transient": {
"deleting": false
}
}
},
"outputs": [],
"source": [
"with open(\"./src/train.py\", \"r\") as f:\n",
" print(f.read())"
]
},
{
"cell_type": "markdown",
"metadata": {
"nteract": {
"transient": {
"deleting": false
}
}
},
"source": [
"Notice how the script gets data and saves models:\n",
"\n",
"+ The training script reads an argument to find the directory containing the data. When you submit the job later, you point to the dataset for this argument:\n",
"`parser.add_argument('--data-folder', type=str, dest='data_folder', help='data directory mounting point')`\n",
"\n",
"\n",
"+ The training script saves your model into a directory named outputs. <br/>\n",
"`joblib.dump(value=clf, filename='outputs/sklearn_mnist_model.pkl')`<br/>\n",
"Anything written in this directory is automatically uploaded into your workspace. You'll access your model from this directory later in the tutorial.\n",
"\n",
"The file `utils.py` is referenced from the training script to load the dataset correctly. This script is also copied into the script folder so that it can be accessed along with the training script."
]
},
{
"cell_type": "markdown",
"metadata": {
"nteract": {
"transient": {
"deleting": false
}
}
},
"source": [
"### Configure the training job\n",
"\n",
"Create a [ScriptRunConfig]() object to specify the configuration details of your training job, including your training script, environment to use, and the compute target to run on. Configure the ScriptRunConfig by specifying:\n",
"\n",
"* The directory that contains your scripts. All the files in this directory are uploaded into the cluster nodes for execution. \n",
"* The compute target. In this case you will point to local compute\n",
"* The training script name, train.py\n",
"* An environment that contains the libraries needed to run the script\n",
"* Arguments required from the training script. \n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"nteract": {
"transient": {
"deleting": false
}
}
},
"source": [ "source": [
"### Define the Environment\n",
"An Environment defines Python packages, environment variables, and Docker settings that are used in machine learning experiments. Here you will be using a curated environment that has already been made available through the workspace. \n", "An Environment defines Python packages, environment variables, and Docker settings that are used in machine learning experiments. Here you will be using a curated environment that has already been made available through the workspace. \n",
"\n", "\n",
"Read [this article](https://docs.microsoft.com/azure/machine-learning/how-to-use-environments) if you want to learn more about Environments and how to use them." "Read [this article](https://docs.microsoft.com/azure/machine-learning/how-to-use-environments) if you want to learn more about Environments and how to use them."
@@ -357,11 +147,12 @@
"outputs": [], "outputs": [],
"source": [ "source": [
"from azureml.core.environment import Environment\n", "from azureml.core.environment import Environment\n",
"from azureml.core.conda_dependencies import CondaDependencies\n",
"\n", "\n",
"# use a curated environment that has already been built for you\n", "# use a curated environment that has already been built for you\n",
"\n", "\n",
"env = Environment.get(workspace=ws, name=\"AzureML-Scikit-learn-0.20.3\")" "env = Environment.get(workspace=ws, \n",
" name=\"AzureML-Scikit-learn0.24-Cuda11-OpenMpi4.1.0-py36\", \n",
" version=1)"
] ]
}, },
{ {
@@ -374,9 +165,17 @@
} }
}, },
"source": [ "source": [
"Create a [ScriptRunConfig](https://docs.microsoft.com/python/api/azureml-core/azureml.core.scriptrunconfig?preserve-view=true&view=azure-ml-py) object to specify the configuration details of your training job, including your training script, environment to use, and the compute target to run on. A script run configuration is used to configure the information necessary for submitting a training run as part of an experiment. In this case we will run this on a 'local' compute target, which is the compute instance you are running this notebook on.\r\n", "### Configure the training job\n",
"\r\n", "\n",
"Read more about configuring and submitting training runs [here](https://docs.microsoft.com/azure/machine-learning/how-to-set-up-training-targets). " "Create a [ScriptRunConfig](https://docs.microsoft.com/python/api/azureml-core/azureml.core.script_run_config.scriptrunconfig?view=azure-ml-py) object to specify the configuration details of your training job, including your training script, environment to use, and the compute target to run on. Configure the ScriptRunConfig by specifying:\n",
"\n",
"* The directory that contains your scripts. All the files in this directory are uploaded into the cluster nodes for execution. \n",
"* The compute target. In this case you will point to local compute\n",
"* The training script name, train.py\n",
"* An environment that contains the libraries needed to run the script\n",
"* Arguments required from the training script. \n",
"\n",
"In this run we will be submitting to \"local\", which is the compute instance you are running this notebook. If you have another compute target (for example: AKS, Azure ML Compute Cluster, Azure Databricks, etc) then you just need to change the `compute_target` argument below. You can learn more about other compute targets [here](https://docs.microsoft.com/azure/machine-learning/how-to-set-up-training-targets). "
] ]
}, },
{ {
@@ -423,7 +222,7 @@
"source": [ "source": [
"### Submit the job\n", "### Submit the job\n",
"\n", "\n",
"Run the experiment by submitting the ScriptRunConfig object. After this there are many options for monitoring your run. You can either navigate to the experiment \"get-started-with-jobsubmission-tutorial\" in the left menu item Experiments to monitor the run (quick link to the run details page in the cell output below), or you can monitor the run inline in this notebook by using the Jupyter widget activated below." "Run the experiment by submitting the ScriptRunConfig object. After this there are many options for monitoring your run. Once submitted, you can either navigate to the experiment \"get-started-with-jobsubmission-tutorial\" in the left menu item __Experiments__ to monitor the run, or you can monitor the run inline as the `run.wait_for_completion(show_output=True)` will stream the logs of the run. You will see that the environment is built for you to ensure reproducibility - this adds a couple of minutes to the run time. On subsequent runs, the environment is re-used making the runtime shorter."
] ]
}, },
{ {
@@ -446,137 +245,9 @@
"outputs": [], "outputs": [],
"source": [ "source": [
"run = exp.submit(config=src)\n", "run = exp.submit(config=src)\n",
"run"
]
},
{
"cell_type": "markdown",
"metadata": {
"nteract": {
"transient": {
"deleting": false
}
}
},
"source": [
"### Jupyter widget\n",
"\n",
"Watch the progress of the run with a Jupyter widget. Like the run submission, the widget is asynchronous and provides live updates every 10-15 seconds until the job completes.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"gather": {
"logged": 1612966026710
},
"jupyter": {
"outputs_hidden": false,
"source_hidden": false
},
"nteract": {
"transient": {
"deleting": false
}
}
},
"outputs": [],
"source": [
"from azureml.widgets import RunDetails\n",
"\n",
"RunDetails(run).show()"
]
},
{
"cell_type": "markdown",
"metadata": {
"nteract": {
"transient": {
"deleting": false
}
}
},
"source": [
"if you want to cancel a run, you can follow [these instructions](https://aka.ms/aml-docs-cancel-run)."
]
},
{
"cell_type": "markdown",
"metadata": {
"nteract": {
"transient": {
"deleting": false
}
}
},
"source": [
"### Get log results upon completion\n",
"\n",
"Model training happens in the background. You can use `wait_for_completion` to block and wait until the model has completed training before running more code. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"gather": {
"logged": 1612966045110
},
"jupyter": {
"outputs_hidden": false,
"source_hidden": false
},
"nteract": {
"transient": {
"deleting": false
}
}
},
"outputs": [],
"source": [
"# specify show_output to True for a verbose log\n",
"run.wait_for_completion(show_output=True)" "run.wait_for_completion(show_output=True)"
] ]
}, },
{
"cell_type": "markdown",
"metadata": {
"nteract": {
"transient": {
"deleting": false
}
}
},
"source": [
"### Display run results\n",
"\n",
"You now have a trained model. Retrieve all the metrics logged during the run, including the accuracy of the model:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"gather": {
"logged": 1612966059052
},
"jupyter": {
"outputs_hidden": false,
"source_hidden": false
},
"nteract": {
"transient": {
"deleting": false
}
}
},
"outputs": [],
"source": [
"print(run.get_metrics())"
]
},
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {
@@ -589,42 +260,11 @@
"source": [ "source": [
"## Register model\n", "## Register model\n",
"\n", "\n",
"The last step in the training script wrote the file `outputs/sklearn_mnist_model.pkl` in a directory named `outputs` on the compute where the job is executed. `outputs` is a special directory in that all content in this directory is automatically uploaded to your workspace. This content appears in the run record in the experiment under your workspace. Hence, the model file is now also available in your workspace." "The training script used the MLflow autologging feature and therefore the model was captured and stored on your behalf. Below we register the model into the Azure Machine Learning Model registry, which lets you keep track of all the models in your Azure Machine Learning workspace.\n",
] "\n",
}, "Models are identified by name and version. Each time you register a model with the same name as an existing one, the registry assumes that it's a new version. The version is incremented, and the new model is registered under the same name.\n",
{ "\n",
"cell_type": "code", "When you register the model, you can provide additional metadata tags and then use the tags when you search for models."
"execution_count": null,
"metadata": {
"gather": {
"logged": 1612966064041
},
"jupyter": {
"outputs_hidden": false,
"source_hidden": false
},
"nteract": {
"transient": {
"deleting": false
}
}
},
"outputs": [],
"source": [
"print(run.get_file_names())"
]
},
{
"cell_type": "markdown",
"metadata": {
"nteract": {
"transient": {
"deleting": false
}
}
},
"source": [
"Register the model in the workspace so that you (or your team members with access to the workspace) can later query, examine, and deploy this model."
] ]
}, },
{ {
@@ -648,11 +288,18 @@
"source": [ "source": [
"# register model\n", "# register model\n",
"model = run.register_model(\n", "model = run.register_model(\n",
" model_name=\"sklearn_mnist\", model_path=\"outputs/sklearn_mnist_model.pkl\"\n", " model_name=\"sklearn_mnist\", model_path=\"model/model.pkl\"\n",
")\n", ")\n",
"print(model.name, model.id, model.version, sep=\"\\t\")" "print(model.name, model.id, model.version, sep=\"\\t\")"
] ]
}, },
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You will now be able to see the model in the regsitry by selecting __Models__ in the left-hand menu of the Azure Machine Learning Studio."
]
},
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {

View File

@@ -2,11 +2,10 @@ import argparse
import os import os
import numpy as np import numpy as np
import glob import glob
import joblib
import mlflow
from sklearn.linear_model import LogisticRegression from sklearn.linear_model import LogisticRegression
import joblib
from azureml.core import Run
from utils import load_data from utils import load_data
# let user feed in 2 parameters, the dataset to mount or download, # let user feed in 2 parameters, the dataset to mount or download,
@@ -58,8 +57,8 @@ y_test = load_data(
print(X_train.shape, y_train.shape, X_test.shape, y_test.shape, sep="\n") print(X_train.shape, y_train.shape, X_test.shape, y_test.shape, sep="\n")
# get hold of the current run # use mlflow autologging
run = Run.get_context() mlflow.autolog()
print("Train a logistic regression model with regularization rate of", args.reg) print("Train a logistic regression model with regularization rate of", args.reg)
clf = LogisticRegression( clf = LogisticRegression(
@@ -73,10 +72,3 @@ y_hat = clf.predict(X_test)
# calculate accuracy on the prediction # calculate accuracy on the prediction
acc = np.average(y_hat == y_test) acc = np.average(y_hat == y_test)
print("Accuracy is", acc) print("Accuracy is", acc)
run.log("regularization rate", np.float(args.reg))
run.log("accuracy", np.float(acc))
os.makedirs("outputs", exist_ok=True)
# note file saved in the outputs folder is automatically uploaded into experiment record
joblib.dump(value=clf, filename="outputs/sklearn_mnist_model.pkl")