mirror of
https://github.com/Azure/MachineLearningNotebooks.git
synced 2025-12-20 09:37:04 -05:00
Compare commits
1 Commits
update-spa
...
release_up
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
82133343bd |
@@ -1,9 +0,0 @@
|
|||||||
# 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
|
|
||||||
98
README.md
98
README.md
@@ -1,43 +1,77 @@
|
|||||||
# Azure Machine Learning Python SDK notebooks
|
# Azure Machine Learning service example 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
|
||||||
|
|
||||||
Welcome to the Azure Machine Learning Python SDK notebooks repository!
|
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.
|
||||||
|
|
||||||
## 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.
|
|
||||||
|
|
||||||
However, the notebooks can be run in any development environment with the correct `azureml` packages installed.
|
## Quick installation
|
||||||
|
```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.
|
||||||
|
|
||||||
Install the `azureml.core` Python package:
|
## How to navigate and use the example notebooks?
|
||||||
|
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
|
||||||
pip install azureml-core
|
""
|
||||||
```
|
```
|
||||||
|
This URL will be slightly different depending on the file.
|
||||||
|
|
||||||
Install additional packages as needed:
|

|
||||||
|
|
||||||
```sh
|
|
||||||
pip install azureml-mlflow
|
|
||||||
pip install azureml-dataset-runtime
|
|
||||||
pip install azureml-automl-runtime
|
|
||||||
pip install azureml-pipeline
|
|
||||||
pip install azureml-pipeline-steps
|
|
||||||
...
|
|
||||||
```
|
|
||||||
|
|
||||||
We recommend starting with one of the [quickstarts](tutorials/compute-instance-quickstarts).
|
|
||||||
|
|
||||||
## Contributing
|
|
||||||
|
|
||||||
This repository is a push-only mirror. Pull requests are ignored.
|
|
||||||
|
|
||||||
## Code of Conduct
|
|
||||||
|
|
||||||
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). Please see the [code of conduct](CODE_OF_CONDUCT.md) for details.
|
|
||||||
|
|
||||||
## Reference
|
|
||||||
|
|
||||||
- [Documentation](https://docs.microsoft.com/azure/machine-learning)
|
|
||||||
|
|
||||||
|
|||||||
@@ -103,7 +103,7 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"import azureml.core\n",
|
"import azureml.core\n",
|
||||||
"\n",
|
"\n",
|
||||||
"print(\"This notebook was created using version 1.32.0 of the Azure ML SDK\")\n",
|
"print(\"This notebook was created using version 1.26.0 of the Azure ML SDK\")\n",
|
||||||
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -254,8 +254,6 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"Many of the sample notebooks use Azure ML managed compute (AmlCompute) to train models using a dynamically scalable pool of compute. In this section you will create default compute clusters for use by the other notebooks and any other operations you choose.\n",
|
"Many of the sample notebooks use Azure ML managed compute (AmlCompute) to train models using a dynamically scalable pool of compute. In this section you will create default compute clusters for use by the other notebooks and any other operations you choose.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"> Note that if you have an AzureML Data Scientist role, you will not have permission to create compute resources. Talk to your workspace or IT admin to create the compute targets described in this section, if they do not already exist.\n",
|
|
||||||
"\n",
|
|
||||||
"To create a cluster, you need to specify a compute configuration that specifies the type of machine to be used and the scalability behaviors. Then you choose a name for the cluster that is unique within the workspace that can be used to address the cluster later.\n",
|
"To create a cluster, you need to specify a compute configuration that specifies the type of machine to be used and the scalability behaviors. Then you choose a name for the cluster that is unique within the workspace that can be used to address the cluster later.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"The cluster parameters are:\n",
|
"The cluster parameters are:\n",
|
||||||
|
|||||||
@@ -36,9 +36,9 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"<a id=\"Introduction\"></a>\n",
|
"<a id=\"Introduction\"></a>\n",
|
||||||
"## Introduction\n",
|
"## Introduction\n",
|
||||||
"This notebook shows how to use [Fairlearn (an open source fairness assessment and unfairness mitigation package)](http://fairlearn.org) and Azure Machine Learning Studio for a binary classification problem. This example uses the well-known adult census dataset. For the purposes of this notebook, we shall treat this as a loan decision problem. We will pretend that the label indicates whether or not each individual repaid a loan in the past. We will use the data to train a predictor to predict whether previously unseen individuals will repay a loan or not. The assumption is that the model predictions are used to decide whether an individual should be offered a loan. Its purpose is purely illustrative of a workflow including a fairness dashboard - in particular, we do **not** include a full discussion of the detailed issues which arise when considering fairness in machine learning. For such discussions, please [refer to the Fairlearn website](http://fairlearn.org/).\n",
|
"This notebook shows how to use [Fairlearn (an open source fairness assessment and unfairness mitigation package)](http://fairlearn.github.io) and Azure Machine Learning Studio for a binary classification problem. This example uses the well-known adult census dataset. For the purposes of this notebook, we shall treat this as a loan decision problem. We will pretend that the label indicates whether or not each individual repaid a loan in the past. We will use the data to train a predictor to predict whether previously unseen individuals will repay a loan or not. The assumption is that the model predictions are used to decide whether an individual should be offered a loan. Its purpose is purely illustrative of a workflow including a fairness dashboard - in particular, we do **not** include a full discussion of the detailed issues which arise when considering fairness in machine learning. For such discussions, please [refer to the Fairlearn website](http://fairlearn.github.io/).\n",
|
||||||
"\n",
|
"\n",
|
||||||
"We will apply the [grid search algorithm](https://fairlearn.org/v0.4.6/api_reference/fairlearn.reductions.html#fairlearn.reductions.GridSearch) from the Fairlearn package using a specific notion of fairness called Demographic Parity. This produces a set of models, and we will view these in a dashboard both locally and in the Azure Machine Learning Studio.\n",
|
"We will apply the [grid search algorithm](https://fairlearn.github.io/master/api_reference/fairlearn.reductions.html#fairlearn.reductions.GridSearch) from the Fairlearn package using a specific notion of fairness called Demographic Parity. This produces a set of models, and we will view these in a dashboard both locally and in the Azure Machine Learning Studio.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"### Setup\n",
|
"### Setup\n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -46,10 +46,9 @@
|
|||||||
"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.6.2` (pre-v0.5.0 will work with minor modifications)\n",
|
"* `fairlearn==0.4.6` (v0.5.0 will work with minor modifications)\n",
|
||||||
"* `joblib`\n",
|
"* `joblib`\n",
|
||||||
"* `liac-arff`\n",
|
"* `shap`\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:"
|
||||||
]
|
]
|
||||||
@@ -86,9 +85,10 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from fairlearn.reductions import GridSearch, DemographicParity, ErrorRate\n",
|
"from fairlearn.reductions import GridSearch, DemographicParity, ErrorRate\n",
|
||||||
"from raiwidgets import FairnessDashboard\n",
|
"from fairlearn.widget import FairlearnDashboard\n",
|
||||||
"\n",
|
"\n",
|
||||||
"from sklearn.compose import ColumnTransformer\n",
|
"from sklearn.compose import ColumnTransformer\n",
|
||||||
|
"from sklearn.datasets import fetch_openml\n",
|
||||||
"from sklearn.impute import SimpleImputer\n",
|
"from sklearn.impute import SimpleImputer\n",
|
||||||
"from sklearn.linear_model import LogisticRegression\n",
|
"from sklearn.linear_model import LogisticRegression\n",
|
||||||
"from sklearn.model_selection import train_test_split\n",
|
"from sklearn.model_selection import train_test_split\n",
|
||||||
@@ -112,9 +112,9 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from fairness_nb_utils import fetch_census_dataset\n",
|
"from fairness_nb_utils import fetch_openml_with_retries\n",
|
||||||
"\n",
|
"\n",
|
||||||
"data = fetch_census_dataset()\n",
|
"data = fetch_openml_with_retries(data_id=1590)\n",
|
||||||
" \n",
|
" \n",
|
||||||
"# Extract the items we want\n",
|
"# Extract the items we want\n",
|
||||||
"X_raw = data.data\n",
|
"X_raw = data.data\n",
|
||||||
@@ -257,7 +257,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"FairnessDashboard(sensitive_features=A_test,\n",
|
"FairlearnDashboard(sensitive_features=A_test, sensitive_feature_names=['Sex', 'Race'],\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)})"
|
||||||
]
|
]
|
||||||
@@ -312,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 pre-v0.5.0, need sweep._predictors\n",
|
"# For Fairlearn v0.5.0, need sweep.predictors_\n",
|
||||||
"predictors = sweep.predictors_"
|
"predictors = sweep._predictors"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -330,14 +330,16 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"errors, disparities = [], []\n",
|
"errors, disparities = [], []\n",
|
||||||
"for predictor in predictors:\n",
|
"for m 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(predictor.predict)[0])\n",
|
" errors.append(error.gamma(classifier)[0])\n",
|
||||||
" disparities.append(disparity.gamma(predictor.predict).max())\n",
|
" disparities.append(disparity.gamma(classifier).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",
|
||||||
@@ -386,7 +388,8 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"FairnessDashboard(sensitive_features=A_test, \n",
|
"FairlearnDashboard(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)"
|
||||||
]
|
]
|
||||||
@@ -407,7 +410,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 `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",
|
"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",
|
||||||
"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",
|
||||||
@@ -581,7 +584,7 @@
|
|||||||
"<a id=\"Conclusion\"></a>\n",
|
"<a id=\"Conclusion\"></a>\n",
|
||||||
"## Conclusion\n",
|
"## Conclusion\n",
|
||||||
"\n",
|
"\n",
|
||||||
"In this notebook we have demonstrated how to use the `GridSearch` algorithm from Fairlearn to generate a collection of models, and then present them in the fairness dashboard in Azure Machine Learning Studio. Please remember that this notebook has not attempted to discuss the many considerations which should be part of any approach to unfairness mitigation. The [Fairlearn website](http://fairlearn.org/) provides that discussion"
|
"In this notebook we have demonstrated how to use the `GridSearch` algorithm from Fairlearn to generate a collection of models, and then present them in the fairness dashboard in Azure Machine Learning Studio. Please remember that this notebook has not attempted to discuss the many considerations which should be part of any approach to unfairness mitigation. The [Fairlearn website](http://fairlearn.github.io/) provides that discussion"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -3,7 +3,5 @@ dependencies:
|
|||||||
- pip:
|
- pip:
|
||||||
- azureml-sdk
|
- azureml-sdk
|
||||||
- azureml-contrib-fairness
|
- azureml-contrib-fairness
|
||||||
- fairlearn>=0.6.2
|
- fairlearn==0.4.6
|
||||||
- joblib
|
- joblib
|
||||||
- liac-arff
|
|
||||||
- raiwidgets~=0.7.0
|
|
||||||
|
|||||||
@@ -4,13 +4,7 @@
|
|||||||
|
|
||||||
"""Utilities for azureml-contrib-fairness notebooks."""
|
"""Utilities for azureml-contrib-fairness notebooks."""
|
||||||
|
|
||||||
import arff
|
|
||||||
from collections import OrderedDict
|
|
||||||
from contextlib import closing
|
|
||||||
import gzip
|
|
||||||
import pandas as pd
|
|
||||||
from sklearn.datasets import fetch_openml
|
from sklearn.datasets import fetch_openml
|
||||||
from sklearn.utils import Bunch
|
|
||||||
import time
|
import time
|
||||||
|
|
||||||
|
|
||||||
@@ -21,7 +15,7 @@ def fetch_openml_with_retries(data_id, max_retries=4, retry_delay=60):
|
|||||||
print("Download attempt {0} of {1}".format(i + 1, max_retries))
|
print("Download attempt {0} of {1}".format(i + 1, max_retries))
|
||||||
data = fetch_openml(data_id=data_id, as_frame=True)
|
data = fetch_openml(data_id=data_id, as_frame=True)
|
||||||
break
|
break
|
||||||
except Exception as e: # noqa: B902
|
except Exception as e:
|
||||||
print("Download attempt failed with exception:")
|
print("Download attempt failed with exception:")
|
||||||
print(e)
|
print(e)
|
||||||
if i + 1 != max_retries:
|
if i + 1 != max_retries:
|
||||||
@@ -32,80 +26,3 @@ def fetch_openml_with_retries(data_id, max_retries=4, retry_delay=60):
|
|||||||
raise RuntimeError("Unable to download dataset from OpenML")
|
raise RuntimeError("Unable to download dataset from OpenML")
|
||||||
|
|
||||||
return data
|
return data
|
||||||
|
|
||||||
|
|
||||||
_categorical_columns = [
|
|
||||||
'workclass',
|
|
||||||
'education',
|
|
||||||
'marital-status',
|
|
||||||
'occupation',
|
|
||||||
'relationship',
|
|
||||||
'race',
|
|
||||||
'sex',
|
|
||||||
'native-country'
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
def fetch_census_dataset():
|
|
||||||
"""Fetch the Adult Census Dataset.
|
|
||||||
|
|
||||||
This uses a particular URL for the Adult Census dataset. The code
|
|
||||||
is a simplified version of fetch_openml() in sklearn.
|
|
||||||
|
|
||||||
The data are copied from:
|
|
||||||
https://openml.org/data/v1/download/1595261.gz
|
|
||||||
(as of 2021-03-31)
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
from urllib import urlretrieve
|
|
||||||
except ImportError:
|
|
||||||
from urllib.request import urlretrieve
|
|
||||||
|
|
||||||
filename = "1595261.gz"
|
|
||||||
data_url = "https://rainotebookscdn.blob.core.windows.net/datasets/"
|
|
||||||
|
|
||||||
remaining_attempts = 5
|
|
||||||
sleep_duration = 10
|
|
||||||
while remaining_attempts > 0:
|
|
||||||
try:
|
|
||||||
urlretrieve(data_url + filename, filename)
|
|
||||||
|
|
||||||
http_stream = gzip.GzipFile(filename=filename, mode='rb')
|
|
||||||
|
|
||||||
with closing(http_stream):
|
|
||||||
def _stream_generator(response):
|
|
||||||
for line in response:
|
|
||||||
yield line.decode('utf-8')
|
|
||||||
|
|
||||||
stream = _stream_generator(http_stream)
|
|
||||||
data = arff.load(stream)
|
|
||||||
except Exception as exc: # noqa: B902
|
|
||||||
remaining_attempts -= 1
|
|
||||||
print("Error downloading dataset from {} ({} attempt(s) remaining)"
|
|
||||||
.format(data_url, remaining_attempts))
|
|
||||||
print(exc)
|
|
||||||
time.sleep(sleep_duration)
|
|
||||||
sleep_duration *= 2
|
|
||||||
continue
|
|
||||||
else:
|
|
||||||
# dataset successfully downloaded
|
|
||||||
break
|
|
||||||
else:
|
|
||||||
raise Exception("Could not retrieve dataset from {}.".format(data_url))
|
|
||||||
|
|
||||||
attributes = OrderedDict(data['attributes'])
|
|
||||||
arff_columns = list(attributes)
|
|
||||||
|
|
||||||
raw_df = pd.DataFrame(data=data['data'], columns=arff_columns)
|
|
||||||
|
|
||||||
target_column_name = 'class'
|
|
||||||
target = raw_df.pop(target_column_name)
|
|
||||||
for col_name in _categorical_columns:
|
|
||||||
dtype = pd.api.types.CategoricalDtype(attributes[col_name])
|
|
||||||
raw_df[col_name] = raw_df[col_name].astype(dtype, copy=False)
|
|
||||||
|
|
||||||
result = Bunch()
|
|
||||||
result.data = raw_df
|
|
||||||
result.target = target
|
|
||||||
|
|
||||||
return result
|
|
||||||
|
|||||||
@@ -30,7 +30,7 @@
|
|||||||
"1. [Training Models](#TrainingModels)\n",
|
"1. [Training Models](#TrainingModels)\n",
|
||||||
"1. [Logging in to AzureML](#LoginAzureML)\n",
|
"1. [Logging in to AzureML](#LoginAzureML)\n",
|
||||||
"1. [Registering the Models](#RegisterModels)\n",
|
"1. [Registering the Models](#RegisterModels)\n",
|
||||||
"1. [Using the Fairness Dashboard](#LocalDashboard)\n",
|
"1. [Using the Fairlearn 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,10 +48,9 @@
|
|||||||
"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.6.2` (also works for pre-v0.5.0 with slight modifications)\n",
|
"* `fairlearn==0.4.6` (should also work with v0.5.0)\n",
|
||||||
"* `joblib`\n",
|
"* `joblib`\n",
|
||||||
"* `liac-arff`\n",
|
"* `shap`\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:"
|
||||||
]
|
]
|
||||||
@@ -89,6 +88,7 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"from sklearn import svm\n",
|
"from sklearn import svm\n",
|
||||||
"from sklearn.compose import ColumnTransformer\n",
|
"from sklearn.compose import ColumnTransformer\n",
|
||||||
|
"from sklearn.datasets import fetch_openml\n",
|
||||||
"from sklearn.impute import SimpleImputer\n",
|
"from sklearn.impute import SimpleImputer\n",
|
||||||
"from sklearn.linear_model import LogisticRegression\n",
|
"from sklearn.linear_model import LogisticRegression\n",
|
||||||
"from sklearn.model_selection import train_test_split\n",
|
"from sklearn.model_selection import train_test_split\n",
|
||||||
@@ -110,9 +110,9 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from fairness_nb_utils import fetch_census_dataset\n",
|
"from fairness_nb_utils import fetch_openml_with_retries\n",
|
||||||
"\n",
|
"\n",
|
||||||
"data = fetch_census_dataset()\n",
|
"data = fetch_openml_with_retries(data_id=1590)\n",
|
||||||
" \n",
|
" \n",
|
||||||
"# Extract the items we want\n",
|
"# Extract the items we want\n",
|
||||||
"X_raw = data.data\n",
|
"X_raw = data.data\n",
|
||||||
@@ -389,9 +389,10 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from raiwidgets import FairnessDashboard\n",
|
"from fairlearn.widget import FairlearnDashboard\n",
|
||||||
"\n",
|
"\n",
|
||||||
"FairnessDashboard(sensitive_features=A_test, \n",
|
"FairlearnDashboard(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 +404,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 `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",
|
"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",
|
||||||
"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",
|
||||||
|
|||||||
@@ -3,7 +3,5 @@ dependencies:
|
|||||||
- pip:
|
- pip:
|
||||||
- azureml-sdk
|
- azureml-sdk
|
||||||
- azureml-contrib-fairness
|
- azureml-contrib-fairness
|
||||||
- fairlearn>=0.6.2
|
- fairlearn==0.4.6
|
||||||
- joblib
|
- joblib
|
||||||
- liac-arff
|
|
||||||
- raiwidgets~=0.7.0
|
|
||||||
|
|||||||
@@ -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==21.1.2
|
- pip==20.2.4
|
||||||
- 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,8 @@ dependencies:
|
|||||||
|
|
||||||
- pip:
|
- pip:
|
||||||
# Required packages for AzureML execution, history, and data preparation.
|
# Required packages for AzureML execution, history, and data preparation.
|
||||||
- azureml-widgets~=1.32.0
|
- azureml-widgets~=1.26.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.32.0/validated_win32_requirements.txt [--no-deps]
|
- -r https://automlcesdkdataresources.blob.core.windows.net/validated-requirements/1.26.0/validated_win32_requirements.txt [--no-deps]
|
||||||
|
|||||||
@@ -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==21.1.2
|
- pip==20.2.4
|
||||||
- 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,8 @@ dependencies:
|
|||||||
|
|
||||||
- pip:
|
- pip:
|
||||||
# Required packages for AzureML execution, history, and data preparation.
|
# Required packages for AzureML execution, history, and data preparation.
|
||||||
- azureml-widgets~=1.32.0
|
- azureml-widgets~=1.26.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.32.0/validated_linux_requirements.txt [--no-deps]
|
- -r https://automlcesdkdataresources.blob.core.windows.net/validated-requirements/1.26.0/validated_linux_requirements.txt [--no-deps]
|
||||||
|
|||||||
@@ -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==21.1.2
|
- pip==20.2.4
|
||||||
- nomkl
|
- nomkl
|
||||||
- python>=3.5.2,<3.8
|
- python>=3.5.2,<3.8
|
||||||
- nb_conda
|
- nb_conda
|
||||||
@@ -22,8 +22,8 @@ dependencies:
|
|||||||
|
|
||||||
- pip:
|
- pip:
|
||||||
# Required packages for AzureML execution, history, and data preparation.
|
# Required packages for AzureML execution, history, and data preparation.
|
||||||
- azureml-widgets~=1.32.0
|
- azureml-widgets~=1.26.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.32.0/validated_darwin_requirements.txt [--no-deps]
|
- -r https://automlcesdkdataresources.blob.core.windows.net/validated-requirements/1.26.0/validated_darwin_requirements.txt [--no-deps]
|
||||||
|
|||||||
@@ -105,7 +105,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"print(\"This notebook was created using version 1.32.0 of the Azure ML SDK\")\n",
|
"print(\"This notebook was created using version 1.26.0 of the Azure ML SDK\")\n",
|
||||||
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -165,9 +165,6 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"## Create or Attach existing AmlCompute\n",
|
"## Create or Attach existing AmlCompute\n",
|
||||||
"You will need to create a compute target for your AutoML run. In this tutorial, you create AmlCompute as your training compute resource.\n",
|
"You will need to create a compute target for your AutoML run. In this tutorial, you create AmlCompute as your training compute resource.\n",
|
||||||
"\n",
|
|
||||||
"> Note that if you have an AzureML Data Scientist role, you will not have permission to create compute resources. Talk to your workspace or IT admin to create the compute targets described in this section, if they do not already exist.\n",
|
|
||||||
"\n",
|
|
||||||
"#### Creation of AmlCompute takes approximately 5 minutes. \n",
|
"#### Creation of AmlCompute takes approximately 5 minutes. \n",
|
||||||
"If the AmlCompute with that name is already in your workspace this code will skip the creation process.\n",
|
"If the AmlCompute with that name is already in your workspace this code will skip the creation process.\n",
|
||||||
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
||||||
@@ -190,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_DS12_V2',\n",
|
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_D2_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",
|
||||||
|
|||||||
@@ -93,7 +93,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"print(\"This notebook was created using version 1.32.0 of the Azure ML SDK\")\n",
|
"print(\"This notebook was created using version 1.26.0 of the Azure ML SDK\")\n",
|
||||||
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -127,9 +127,6 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"## Create or Attach existing AmlCompute\n",
|
"## Create or Attach existing AmlCompute\n",
|
||||||
"A compute target is required to execute the Automated ML run. In this tutorial, you create AmlCompute as your training compute resource.\n",
|
"A compute target is required to execute the Automated ML run. In this tutorial, you create AmlCompute as your training compute resource.\n",
|
||||||
"\n",
|
|
||||||
"> Note that if you have an AzureML Data Scientist role, you will not have permission to create compute resources. Talk to your workspace or IT admin to create the compute targets described in this section, if they do not already exist.\n",
|
|
||||||
"\n",
|
|
||||||
"#### Creation of AmlCompute takes approximately 5 minutes. \n",
|
"#### Creation of AmlCompute takes approximately 5 minutes. \n",
|
||||||
"If the AmlCompute with that name is already in your workspace this code will skip the creation process.\n",
|
"If the AmlCompute with that name is already in your workspace this code will skip the creation process.\n",
|
||||||
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
||||||
|
|||||||
@@ -96,7 +96,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"print(\"This notebook was created using version 1.32.0 of the Azure ML SDK\")\n",
|
"print(\"This notebook was created using version 1.26.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\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -138,8 +138,6 @@
|
|||||||
"## Set up a compute cluster\n",
|
"## Set up a compute cluster\n",
|
||||||
"This section uses a user-provided compute cluster (named \"dnntext-cluster\" in this example). If a cluster with this name does not exist in the user's workspace, the below code will create a new cluster. You can choose the parameters of the cluster as mentioned in the comments.\n",
|
"This section uses a user-provided compute cluster (named \"dnntext-cluster\" in this example). If a cluster with this name does not exist in the user's workspace, the below code will create a new cluster. You can choose the parameters of the cluster as mentioned in the comments.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"> Note that if you have an AzureML Data Scientist role, you will not have permission to create compute resources. Talk to your workspace or IT admin to create the compute targets described in this section, if they do not already exist.\n",
|
|
||||||
"\n",
|
|
||||||
"Whether you provide/select a CPU or GPU cluster, AutoML will choose the appropriate DNN for that setup - BiLSTM or BERT text featurizer will be included in the candidate featurizers on CPU and GPU respectively. If your goal is to obtain the most accurate model, we recommend you use GPU clusters since BERT featurizers usually outperform BiLSTM featurizers."
|
"Whether you provide/select a CPU or GPU cluster, AutoML will choose the appropriate DNN for that setup - BiLSTM or BERT text featurizer will be included in the candidate featurizers on CPU and GPU respectively. If your goal is to obtain the most accurate model, we recommend you use GPU clusters since BERT featurizers usually outperform BiLSTM featurizers."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -162,7 +160,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_DS12_V2\" \n",
|
" compute_config = AmlCompute.provisioning_configuration(vm_size = \"STANDARD_NC6\", # CPU for BiLSTM, such as \"STANDARD_D2_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",
|
||||||
@@ -283,7 +281,7 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"automl_settings = {\n",
|
"automl_settings = {\n",
|
||||||
" \"experiment_timeout_minutes\": 30,\n",
|
" \"experiment_timeout_minutes\": 20,\n",
|
||||||
" \"primary_metric\": 'accuracy',\n",
|
" \"primary_metric\": 'accuracy',\n",
|
||||||
" \"max_concurrent_iterations\": num_nodes, \n",
|
" \"max_concurrent_iterations\": num_nodes, \n",
|
||||||
" \"max_cores_per_iteration\": -1,\n",
|
" \"max_cores_per_iteration\": -1,\n",
|
||||||
@@ -487,7 +485,7 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"test_run = run_inference(test_experiment, compute_target, script_folder, best_dnn_run,\n",
|
"test_run = run_inference(test_experiment, compute_target, script_folder, best_dnn_run,\n",
|
||||||
" test_dataset, target_column_name, model_name)"
|
" train_dataset, test_dataset, target_column_name, model_name)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ from azureml.core.run import Run
|
|||||||
|
|
||||||
|
|
||||||
def run_inference(test_experiment, compute_target, script_folder, train_run,
|
def run_inference(test_experiment, compute_target, script_folder, train_run,
|
||||||
test_dataset, target_column_name, model_name):
|
train_dataset, test_dataset, target_column_name, model_name):
|
||||||
|
|
||||||
inference_env = train_run.get_environment()
|
inference_env = train_run.get_environment()
|
||||||
|
|
||||||
@@ -16,6 +16,7 @@ def run_inference(test_experiment, compute_target, script_folder, train_run,
|
|||||||
'--model_name': model_name
|
'--model_name': model_name
|
||||||
},
|
},
|
||||||
inputs=[
|
inputs=[
|
||||||
|
train_dataset.as_named_input('train_data'),
|
||||||
test_dataset.as_named_input('test_data')
|
test_dataset.as_named_input('test_data')
|
||||||
],
|
],
|
||||||
compute_target=compute_target,
|
compute_target=compute_target,
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import argparse
|
import argparse
|
||||||
|
|
||||||
import pandas as pd
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
||||||
from sklearn.externals import joblib
|
from sklearn.externals import joblib
|
||||||
@@ -33,21 +32,22 @@ model = joblib.load(model_path)
|
|||||||
run = Run.get_context()
|
run = Run.get_context()
|
||||||
# get input dataset by name
|
# get input dataset by name
|
||||||
test_dataset = run.input_datasets['test_data']
|
test_dataset = run.input_datasets['test_data']
|
||||||
|
train_dataset = run.input_datasets['train_data']
|
||||||
|
|
||||||
X_test_df = test_dataset.drop_columns(columns=[target_column_name]) \
|
X_test_df = test_dataset.drop_columns(columns=[target_column_name]) \
|
||||||
.to_pandas_dataframe()
|
.to_pandas_dataframe()
|
||||||
y_test_df = test_dataset.with_timestamp_columns(None) \
|
y_test_df = test_dataset.with_timestamp_columns(None) \
|
||||||
.keep_columns(columns=[target_column_name]) \
|
.keep_columns(columns=[target_column_name]) \
|
||||||
.to_pandas_dataframe()
|
.to_pandas_dataframe()
|
||||||
|
y_train_df = test_dataset.with_timestamp_columns(None) \
|
||||||
|
.keep_columns(columns=[target_column_name]) \
|
||||||
|
.to_pandas_dataframe()
|
||||||
|
|
||||||
predicted = model.predict_proba(X_test_df)
|
predicted = model.predict_proba(X_test_df)
|
||||||
|
|
||||||
if isinstance(predicted, pd.DataFrame):
|
|
||||||
predicted = predicted.values
|
|
||||||
|
|
||||||
# Use the AutoML scoring module
|
# Use the AutoML scoring module
|
||||||
|
class_labels = np.unique(np.concatenate((y_train_df.values, y_test_df.values)))
|
||||||
train_labels = model.classes_
|
train_labels = model.classes_
|
||||||
class_labels = np.unique(np.concatenate((y_test_df.values, np.reshape(train_labels, (-1, 1)))))
|
|
||||||
classification_metrics = list(constants.CLASSIFICATION_SCALAR_SET)
|
classification_metrics = list(constants.CLASSIFICATION_SCALAR_SET)
|
||||||
scores = scoring.score_classification(y_test_df.values, predicted,
|
scores = scoring.score_classification(y_test_df.values, predicted,
|
||||||
classification_metrics,
|
classification_metrics,
|
||||||
|
|||||||
@@ -81,7 +81,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"print(\"This notebook was created using version 1.32.0 of the Azure ML SDK\")\n",
|
"print(\"This notebook was created using version 1.26.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\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -141,9 +141,6 @@
|
|||||||
"#### Create or Attach existing AmlCompute\n",
|
"#### Create or Attach existing AmlCompute\n",
|
||||||
"\n",
|
"\n",
|
||||||
"You will need to create a compute target for your AutoML run. In this tutorial, you create AmlCompute as your training compute resource.\n",
|
"You will need to create a compute target for your AutoML run. In this tutorial, you create AmlCompute as your training compute resource.\n",
|
||||||
"\n",
|
|
||||||
"> Note that if you have an AzureML Data Scientist role, you will not have permission to create compute resources. Talk to your workspace or IT admin to create the compute targets described in this section, if they do not already exist.\n",
|
|
||||||
"\n",
|
|
||||||
"#### Creation of AmlCompute takes approximately 5 minutes. \n",
|
"#### Creation of AmlCompute takes approximately 5 minutes. \n",
|
||||||
"If the AmlCompute with that name is already in your workspace this code will skip the creation process.\n",
|
"If the AmlCompute with that name is already in your workspace this code will skip the creation process.\n",
|
||||||
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
||||||
@@ -166,7 +163,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_DS12_V2',\n",
|
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_D2_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",
|
||||||
|
|||||||
@@ -49,24 +49,22 @@ print("Argument 1(ds_name): %s" % args.ds_name)
|
|||||||
|
|
||||||
dstor = ws.get_default_datastore()
|
dstor = ws.get_default_datastore()
|
||||||
register_dataset = False
|
register_dataset = False
|
||||||
end_time = datetime.utcnow()
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
ds = Dataset.get_by_name(ws, args.ds_name)
|
ds = Dataset.get_by_name(ws, args.ds_name)
|
||||||
end_time_last_slice = ds.data_changed_time.replace(tzinfo=None)
|
end_time_last_slice = ds.data_changed_time.replace(tzinfo=None)
|
||||||
print("Dataset {0} last updated on {1}".format(args.ds_name,
|
print("Dataset {0} last updated on {1}".format(args.ds_name,
|
||||||
end_time_last_slice))
|
end_time_last_slice))
|
||||||
except Exception:
|
except Exception as e:
|
||||||
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 = datetime(2021, 5, 1, 0, 0)
|
end_time_last_slice = datetime.today() - relativedelta(weeks=2)
|
||||||
end_time_last_slice = end_time - relativedelta(weeks=2)
|
|
||||||
|
|
||||||
|
end_time = datetime.utcnow()
|
||||||
train_df = get_noaa_data(end_time_last_slice, end_time)
|
train_df = get_noaa_data(end_time_last_slice, end_time)
|
||||||
|
|
||||||
if train_df.size > 0:
|
if train_df.size > 0:
|
||||||
print("Received {0} rows of new data after {1}.".format(
|
print("Received {0} rows of new data after {0}.".format(
|
||||||
train_df.shape[0], end_time_last_slice))
|
train_df.shape[0], end_time_last_slice))
|
||||||
folder_name = "{}/{:04d}/{:02d}/{:02d}/{:02d}/{:02d}/{:02d}".format(args.ds_name, end_time.year,
|
folder_name = "{}/{:04d}/{:02d}/{:02d}/{:02d}/{:02d}/{:02d}".format(args.ds_name, end_time.year,
|
||||||
end_time.month, end_time.day,
|
end_time.month, end_time.day,
|
||||||
|
|||||||
@@ -1,420 +0,0 @@
|
|||||||
{
|
|
||||||
"cells": [
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
|
||||||
"\n",
|
|
||||||
"Licensed under the MIT License."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
""
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"# Automated Machine Learning\n",
|
|
||||||
"_**Classification of credit card fraudulent transactions on local managed compute **_\n",
|
|
||||||
"\n",
|
|
||||||
"## Contents\n",
|
|
||||||
"1. [Introduction](#Introduction)\n",
|
|
||||||
"1. [Setup](#Setup)\n",
|
|
||||||
"1. [Train](#Train)\n",
|
|
||||||
"1. [Results](#Results)\n",
|
|
||||||
"1. [Test](#Test)\n",
|
|
||||||
"1. [Acknowledgements](#Acknowledgements)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Introduction\n",
|
|
||||||
"\n",
|
|
||||||
"In this example we use the associated credit card dataset to showcase how you can use AutoML for a simple classification problem. The goal is to predict if a credit card transaction is considered a fraudulent charge.\n",
|
|
||||||
"\n",
|
|
||||||
"This notebook is using local managed compute to train the model.\n",
|
|
||||||
"\n",
|
|
||||||
"If you are using an Azure Machine Learning Compute Instance, you are all set. Otherwise, go through the [configuration](../../../configuration.ipynb) notebook first if you haven't already to establish your connection to the AzureML Workspace. \n",
|
|
||||||
"\n",
|
|
||||||
"In this notebook you will learn how to:\n",
|
|
||||||
"1. Create an experiment using an existing workspace.\n",
|
|
||||||
"2. Configure AutoML using `AutoMLConfig`.\n",
|
|
||||||
"3. Train the model using local managed compute.\n",
|
|
||||||
"4. Explore the results.\n",
|
|
||||||
"5. Test the fitted model."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Setup\n",
|
|
||||||
"\n",
|
|
||||||
"As part of the setup you have already created an Azure ML `Workspace` object. For Automated ML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"import logging\n",
|
|
||||||
"\n",
|
|
||||||
"import pandas as pd\n",
|
|
||||||
"\n",
|
|
||||||
"import azureml.core\n",
|
|
||||||
"from azureml.core.compute_target import LocalTarget\n",
|
|
||||||
"from azureml.core.experiment import Experiment\n",
|
|
||||||
"from azureml.core.workspace import Workspace\n",
|
|
||||||
"from azureml.core.dataset import Dataset\n",
|
|
||||||
"from azureml.train.automl import AutoMLConfig"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"This sample notebook may use features that are not available in previous versions of the Azure ML SDK."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"print(\"This notebook was created using version 1.32.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
|
|
||||||
}
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
name: auto-ml-classification-credit-card-fraud-local-managed
|
|
||||||
dependencies:
|
|
||||||
- pip:
|
|
||||||
- azureml-sdk
|
|
||||||
@@ -91,7 +91,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"print(\"This notebook was created using version 1.32.0 of the Azure ML SDK\")\n",
|
"print(\"This notebook was created using version 1.26.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_DS12_V2',\n",
|
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_D2_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",
|
||||||
|
|||||||
@@ -113,7 +113,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"print(\"This notebook was created using version 1.32.0 of the Azure ML SDK\")\n",
|
"print(\"This notebook was created using version 1.26.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,9 +162,7 @@
|
|||||||
},
|
},
|
||||||
"source": [
|
"source": [
|
||||||
"### Using AmlCompute\n",
|
"### Using AmlCompute\n",
|
||||||
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for your AutoML run. In this tutorial, you use `AmlCompute` as your training compute resource.\n",
|
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for your AutoML run. In this tutorial, you use `AmlCompute` as your training compute resource."
|
||||||
"\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."
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -187,7 +185,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_DS12_V2',\n",
|
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_D2_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",
|
||||||
@@ -662,7 +660,7 @@
|
|||||||
"name": "python",
|
"name": "python",
|
||||||
"nbconvert_exporter": "python",
|
"nbconvert_exporter": "python",
|
||||||
"pygments_lexer": "ipython3",
|
"pygments_lexer": "ipython3",
|
||||||
"version": "3.6.9"
|
"version": "3.6.7"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"nbformat": 4,
|
"nbformat": 4,
|
||||||
|
|||||||
@@ -87,7 +87,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"print(\"This notebook was created using version 1.32.0 of the Azure ML SDK\")\n",
|
"print(\"This notebook was created using version 1.26.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\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -129,9 +129,6 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"## Compute\n",
|
"## Compute\n",
|
||||||
"You will need to create a [compute target](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-set-up-training-targets#amlcompute) for your AutoML run. In this tutorial, you create AmlCompute as your training compute resource.\n",
|
"You will need to create a [compute target](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-set-up-training-targets#amlcompute) for your AutoML run. In this tutorial, you create AmlCompute as your training compute resource.\n",
|
||||||
"\n",
|
|
||||||
"> Note that if you have an AzureML Data Scientist role, you will not have permission to create compute resources. Talk to your workspace or IT admin to create the compute targets described in this section, if they do not already exist.\n",
|
|
||||||
"\n",
|
|
||||||
"#### Creation of AmlCompute takes approximately 5 minutes. \n",
|
"#### Creation of AmlCompute takes approximately 5 minutes. \n",
|
||||||
"If the AmlCompute with that name is already in your workspace this code will skip the creation process.\n",
|
"If the AmlCompute with that name is already in your workspace this code will skip the creation process.\n",
|
||||||
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
||||||
@@ -154,7 +151,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_DS12_V2',\n",
|
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_D2_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",
|
||||||
|
|||||||
@@ -24,11 +24,10 @@
|
|||||||
"_**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",
|
||||||
@@ -39,7 +38,7 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"# Introduction<a id=\"introduction\"></a>\n",
|
"## Introduction\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",
|
||||||
@@ -50,16 +49,15 @@
|
|||||||
"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 with lagging features"
|
"1. Run and explore the forecast"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"# Setup<a id=\"setup\"></a>"
|
"## Setup"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -99,7 +97,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"print(\"This notebook was created using version 1.32.0 of the Azure ML SDK\")\n",
|
"print(\"This notebook was created using version 1.26.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\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -179,7 +177,7 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"# Data<a id=\"data\"></a>\n",
|
"# Data\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",
|
||||||
@@ -311,7 +309,7 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"# Train<a id=\"train\"></a>\n",
|
"## Train\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",
|
||||||
@@ -453,11 +451,9 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"# Forecasting<a id=\"forecast\"></a>\n",
|
"## Forecasting\n",
|
||||||
"\n",
|
"\n",
|
||||||
"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",
|
"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:"
|
||||||
"\n",
|
|
||||||
"The inference will run on a remote compute. In this example, it will re-use the training compute."
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -466,15 +462,16 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"test_experiment = Experiment(ws, experiment_name + \"_inference\")"
|
"X_test = test.to_pandas_dataframe().reset_index(drop=True)\n",
|
||||||
|
"y_test = X_test.pop(target_column_name).values"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"### Retreiving forecasts from the model\n",
|
"### Forecast Function\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."
|
"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)."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -483,16 +480,10 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from run_forecast import run_remote_inference\n",
|
"# The featurized data, aligned to y, will also be returned.\n",
|
||||||
"remote_run_infer = run_remote_inference(test_experiment=test_experiment,\n",
|
"# This contains the assumptions that were made in the forecast\n",
|
||||||
" compute_target=compute_target,\n",
|
"# and helps align the forecast to the original data\n",
|
||||||
" train_run=best_run,\n",
|
"y_predictions, X_trans = fitted_model.forecast(X_test)"
|
||||||
" 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')"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -500,7 +491,9 @@
|
|||||||
"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)."
|
"To evaluate the accuracy of the forecast, we'll compare against the actual sales quantities for some select metrics, included the mean absolute percentage error (MAPE). For more metrics that can be used for evaluation after training, please see [supported metrics](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-understand-automated-ml#regressionforecasting-metrics), and [how to calculate residuals](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-understand-automated-ml#residuals).\n",
|
||||||
|
"\n",
|
||||||
|
"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."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -509,9 +502,9 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"# load forecast data frame\n",
|
"from forecasting_helper import align_outputs\n",
|
||||||
"fcst_df = pd.read_csv('predictions.csv', parse_dates=[time_column_name])\n",
|
"\n",
|
||||||
"fcst_df.head()"
|
"df_all = align_outputs(y_predictions, X_trans, X_test, y_test, target_column_name)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -526,8 +519,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=fcst_df[target_column_name],\n",
|
" y_test=df_all[target_column_name],\n",
|
||||||
" y_pred=fcst_df['predicted'],\n",
|
" y_pred=df_all['predicted'],\n",
|
||||||
" metrics=list(constants.Metric.SCALAR_REGRESSION_SET))\n",
|
" metrics=list(constants.Metric.SCALAR_REGRESSION_SET))\n",
|
||||||
"\n",
|
"\n",
|
||||||
"print(\"[Test data scores]\\n\")\n",
|
"print(\"[Test data scores]\\n\")\n",
|
||||||
@@ -536,8 +529,8 @@
|
|||||||
" \n",
|
" \n",
|
||||||
"# Plot outputs\n",
|
"# Plot outputs\n",
|
||||||
"%matplotlib inline\n",
|
"%matplotlib inline\n",
|
||||||
"test_pred = plt.scatter(fcst_df[target_column_name], fcst_df['predicted'], color='b')\n",
|
"test_pred = plt.scatter(df_all[target_column_name], df_all['predicted'], color='b')\n",
|
||||||
"test_test = plt.scatter(fcst_df[target_column_name], fcst_df[target_column_name], color='g')\n",
|
"test_test = plt.scatter(df_all[target_column_name], df_all[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()"
|
||||||
]
|
]
|
||||||
@@ -546,7 +539,23 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"# Advanced Training <a id=\"advanced_training\"></a>\n",
|
"Looking at `X_trans` is also useful to see what featurization happened to the data."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"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."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -629,7 +638,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."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -639,17 +648,10 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"test_experiment_advanced = Experiment(ws, experiment_name + \"_inference_advanced\")\n",
|
"# The featurized data, aligned to y, will also be returned.\n",
|
||||||
"advanced_remote_run_infer = run_remote_inference(test_experiment=test_experiment_advanced,\n",
|
"# This contains the assumptions that were made in the forecast\n",
|
||||||
" compute_target=compute_target,\n",
|
"# and helps align the forecast to the original data\n",
|
||||||
" train_run=best_run_lags,\n",
|
"y_predictions, X_trans = fitted_model_lags.forecast(X_test)"
|
||||||
" 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')"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -658,8 +660,9 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"fcst_adv_df = pd.read_csv('predictions_advanced.csv', parse_dates=[time_column_name])\n",
|
"from forecasting_helper import align_outputs\n",
|
||||||
"fcst_adv_df.head()"
|
"\n",
|
||||||
|
"df_all = align_outputs(y_predictions, X_trans, X_test, y_test, target_column_name)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -674,8 +677,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=fcst_adv_df[target_column_name],\n",
|
" y_test=df_all[target_column_name],\n",
|
||||||
" y_pred=fcst_adv_df['predicted'],\n",
|
" y_pred=df_all['predicted'],\n",
|
||||||
" metrics=list(constants.Metric.SCALAR_REGRESSION_SET))\n",
|
" metrics=list(constants.Metric.SCALAR_REGRESSION_SET))\n",
|
||||||
"\n",
|
"\n",
|
||||||
"print(\"[Test data scores]\\n\")\n",
|
"print(\"[Test data scores]\\n\")\n",
|
||||||
@@ -684,8 +687,8 @@
|
|||||||
" \n",
|
" \n",
|
||||||
"# Plot outputs\n",
|
"# Plot outputs\n",
|
||||||
"%matplotlib inline\n",
|
"%matplotlib inline\n",
|
||||||
"test_pred = plt.scatter(fcst_adv_df[target_column_name], fcst_adv_df['predicted'], color='b')\n",
|
"test_pred = plt.scatter(df_all[target_column_name], df_all['predicted'], color='b')\n",
|
||||||
"test_test = plt.scatter(fcst_adv_df[target_column_name], fcst_adv_df[target_column_name], color='g')\n",
|
"test_test = plt.scatter(df_all[target_column_name], df_all[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()"
|
||||||
]
|
]
|
||||||
@@ -716,7 +719,7 @@
|
|||||||
"name": "python",
|
"name": "python",
|
||||||
"nbconvert_exporter": "python",
|
"nbconvert_exporter": "python",
|
||||||
"pygments_lexer": "ipython3",
|
"pygments_lexer": "ipython3",
|
||||||
"version": "3.6.9"
|
"version": "3.6.8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"nbformat": 4,
|
"nbformat": 4,
|
||||||
|
|||||||
@@ -1,15 +1,5 @@
|
|||||||
"""
|
|
||||||
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
|
||||||
|
|
||||||
|
|
||||||
@@ -52,38 +42,3 @@ 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)
|
|
||||||
@@ -1,89 +0,0 @@
|
|||||||
"""
|
|
||||||
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)
|
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
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))
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
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
|
|
||||||
@@ -94,7 +94,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"print(\"This notebook was created using version 1.32.0 of the Azure ML SDK\")\n",
|
"print(\"This notebook was created using version 1.26.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\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -263,9 +263,7 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"You will need to create a [compute target](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-set-up-training-targets#amlcompute) for your AutoML run. In this tutorial, you create AmlCompute as your training compute resource.\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",
|
|
||||||
"> 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."
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -285,7 +283,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_DS12_V2',\n",
|
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_D2_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",
|
||||||
|
|||||||
@@ -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. [Forecast](#forecast)\n",
|
"1. [Predict](#Predict)\n",
|
||||||
"1. [Operationalize](#operationalize)"
|
"1. [Operationalize](#Operationalize)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Introduction<a id=\"introduction\"></a>\n",
|
"## Introduction\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<a id=\"setup\"></a>"
|
"## Setup"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -82,7 +82,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"print(\"This notebook was created using version 1.32.0 of the Azure ML SDK\")\n",
|
"print(\"This notebook was created using version 1.26.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,11 +122,8 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Compute<a id=\"compute\"></a>\n",
|
"## Compute\n",
|
||||||
"You will need to create a [compute target](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-set-up-training-targets#amlcompute) for your AutoML run. In this tutorial, you create AmlCompute as your training compute resource.\n",
|
"You will need to create a [compute target](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-set-up-training-targets#amlcompute) for your AutoML run. In this tutorial, you create AmlCompute as your training compute resource.\n",
|
||||||
"\n",
|
|
||||||
"> Note that if you have an AzureML Data Scientist role, you will not have permission to create compute resources. Talk to your workspace or IT admin to create the compute targets described in this section, if they do not already exist.\n",
|
|
||||||
"\n",
|
|
||||||
"#### Creation of AmlCompute takes approximately 5 minutes. \n",
|
"#### Creation of AmlCompute takes approximately 5 minutes. \n",
|
||||||
"If the AmlCompute with that name is already in your workspace this code will skip the creation process.\n",
|
"If the AmlCompute with that name is already in your workspace this code will skip the creation process.\n",
|
||||||
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
||||||
@@ -149,7 +146,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_D12_V2',\n",
|
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_D2_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 +157,7 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Data<a id=\"data\"></a>\n",
|
"## Data\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,8 +284,7 @@
|
|||||||
"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'))\n",
|
"train_dataset = Dataset.Tabular.from_delimited_files(path=datastore.path('dataset/dominicks_OJ_train.csv'))"
|
||||||
"test_dataset = Dataset.Tabular.from_delimited_files(path=datastore.path('dataset/dominicks_OJ_test.csv'))"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -381,7 +377,7 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Train<a id=\"train\"></a>\n",
|
"## Train\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",
|
||||||
@@ -522,11 +518,9 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"# Forecast<a id=\"forecast\"></a>\n",
|
"# Forecasting\n",
|
||||||
"\n",
|
"\n",
|
||||||
"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",
|
"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:"
|
||||||
"\n",
|
|
||||||
"The inference will run on a remote compute. In this example, it will re-use the training compute."
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -535,15 +529,17 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"test_experiment = Experiment(ws, experiment_name + \"_inference\")"
|
"X_test = test\n",
|
||||||
|
"y_test = X_test.pop(target_column_name).values"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"### Retreiving forecasts from the model\n",
|
"X_test.head()"
|
||||||
"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."
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -559,16 +555,18 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from run_forecast import run_remote_inference\n",
|
"# forecast returns the predictions and the featurized data, aligned to X_test.\n",
|
||||||
"remote_run_infer = run_remote_inference(test_experiment=test_experiment, \n",
|
"# This contains the assumptions that were made in the forecast\n",
|
||||||
" compute_target=compute_target,\n",
|
"y_predictions, X_trans = fitted_model.forecast(X_test)"
|
||||||
" train_run=best_run,\n",
|
]
|
||||||
" test_dataset=test_dataset,\n",
|
},
|
||||||
" target_column_name=target_column_name)\n",
|
{
|
||||||
"remote_run_infer.wait_for_completion(show_output=False)\n",
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"If you are used to scikit pipelines, perhaps you expected `predict(X_test)`. However, forecasting requires a more general interface that also supplies the past target `y` values. Please use `forecast(X,y)` as `predict(X)` is reserved for internal purposes on forecasting models.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# download the forecast file to the local machine\n",
|
"The [forecast function notebook](../forecasting-forecast-function/auto-ml-forecasting-function.ipynb)."
|
||||||
"remote_run_infer.download_file('outputs/predictions.csv', 'predictions.csv')"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -588,9 +586,8 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"# load forecast data frame\n",
|
"assign_dict = {'predicted': y_predictions, target_column_name: y_test}\n",
|
||||||
"fcst_df = pd.read_csv('predictions.csv', parse_dates=[time_column_name])\n",
|
"df_all = X_test.assign(**assign_dict)"
|
||||||
"fcst_df.head()"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -605,8 +602,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=fcst_df[target_column_name],\n",
|
" y_test=df_all[target_column_name],\n",
|
||||||
" y_pred=fcst_df['predicted'],\n",
|
" y_pred=df_all['predicted'],\n",
|
||||||
" metrics=list(constants.Metric.SCALAR_REGRESSION_SET))\n",
|
" metrics=list(constants.Metric.SCALAR_REGRESSION_SET))\n",
|
||||||
"\n",
|
"\n",
|
||||||
"print(\"[Test data scores]\\n\")\n",
|
"print(\"[Test data scores]\\n\")\n",
|
||||||
@@ -615,8 +612,8 @@
|
|||||||
" \n",
|
" \n",
|
||||||
"# Plot outputs\n",
|
"# Plot outputs\n",
|
||||||
"%matplotlib inline\n",
|
"%matplotlib inline\n",
|
||||||
"test_pred = plt.scatter(fcst_df[target_column_name], fcst_df['predicted'], color='b')\n",
|
"test_pred = plt.scatter(df_all[target_column_name], df_all['predicted'], color='b')\n",
|
||||||
"test_test = plt.scatter(fcst_df[target_column_name], fcst_df[target_column_name], color='g')\n",
|
"test_test = plt.scatter(df_all[target_column_name], df_all[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 +622,7 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"# Operationalize<a id=\"operationalize\"></a>"
|
"# Operationalize"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -723,13 +720,12 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"import json\n",
|
"import json\n",
|
||||||
"X_query = test.copy()\n",
|
"X_query = X_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\": json.loads(X_query.to_json(orient=\"records\"))})\n",
|
"test_sample = json.dumps({'data': X_query.to_dict(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",
|
||||||
@@ -806,7 +802,7 @@
|
|||||||
"name": "python",
|
"name": "python",
|
||||||
"nbconvert_exporter": "python",
|
"nbconvert_exporter": "python",
|
||||||
"pygments_lexer": "ipython3",
|
"pygments_lexer": "ipython3",
|
||||||
"version": "3.6.9"
|
"version": "3.6.8"
|
||||||
},
|
},
|
||||||
"tags": [
|
"tags": [
|
||||||
"None"
|
"None"
|
||||||
|
|||||||
@@ -1,38 +0,0 @@
|
|||||||
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
|
|
||||||
@@ -96,7 +96,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"print(\"This notebook was created using version 1.32.0 of the Azure ML SDK\")\n",
|
"print(\"This notebook was created using version 1.26.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,8 +436,7 @@
|
|||||||
"\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',\n",
|
" task='classification')"
|
||||||
" automl_run=automl_run)"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -454,10 +453,11 @@
|
|||||||
"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_explainer_setup_obj.automl_run,\n",
|
" init_dataset=automl_explainer_setup_obj.X_transform, run=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",
|
||||||
|
|||||||
@@ -96,7 +96,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"print(\"This notebook was created using version 1.32.0 of the Azure ML SDK\")\n",
|
"print(\"This notebook was created using version 1.26.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\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -130,8 +130,6 @@
|
|||||||
"### Create or Attach existing AmlCompute\n",
|
"### Create or Attach existing AmlCompute\n",
|
||||||
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for your AutoML run. In this tutorial, you create `AmlCompute` as your training compute resource.\n",
|
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for your AutoML run. In this tutorial, you create `AmlCompute` as your training compute resource.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"> Note that if you have an AzureML Data Scientist role, you will not have permission to create compute resources. Talk to your workspace or IT admin to create the compute targets described in this section, if they do not already exist.\n",
|
|
||||||
"\n",
|
|
||||||
"**Creation of AmlCompute takes approximately 5 minutes.** If the AmlCompute with that name is already in your workspace this code will skip the creation process.\n",
|
"**Creation of AmlCompute takes approximately 5 minutes.** If the AmlCompute with that name is already in your workspace this code will skip the creation process.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
||||||
@@ -154,7 +152,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_DS12_V2',\n",
|
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_D2_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",
|
||||||
@@ -441,7 +439,7 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"### Retrieve any AutoML Model for explanations\n",
|
"### Retrieve any AutoML Model for explanations\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Below we select an AutoML pipeline from our iterations. The `get_output` method returns the a AutoML run and the fitted model for the last invocation. Overloads on `get_output` allow you to retrieve the best run and fitted model for any logged `metric` or for a particular `iteration`."
|
"Below we select the some AutoML pipeline from our iterations. The `get_output` method returns the a AutoML run and the fitted model for the last invocation. Overloads on `get_output` allow you to retrieve the best run and fitted model for *any* logged metric or for a particular *iteration*."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -450,8 +448,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"#automl_run, fitted_model = remote_run.get_output(metric='r2_score')\n",
|
"automl_run, fitted_model = remote_run.get_output(metric='r2_score')"
|
||||||
"automl_run, fitted_model = remote_run.get_output(iteration=2)"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -50,13 +50,11 @@ 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,
|
init_dataset=automl_explainer_setup_obj.X_transform, run=automl_run,
|
||||||
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)
|
||||||
|
|||||||
@@ -92,7 +92,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"print(\"This notebook was created using version 1.32.0 of the Azure ML SDK\")\n",
|
"print(\"This notebook was created using version 1.26.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_DS12_V2',\n",
|
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_D2_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",
|
||||||
|
|||||||
@@ -350,6 +350,32 @@
|
|||||||
"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": {},
|
||||||
|
|||||||
@@ -352,6 +352,32 @@
|
|||||||
"displayHTML(\"<a href={} target='_blank'>Azure Portal: {}</a>\".format(local_run.get_portal_url(), local_run.id))"
|
"displayHTML(\"<a href={} target='_blank'>Azure Portal: {}</a>\".format(local_run.get_portal_url(), local_run.id))"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Retrieve All Child Runs after the experiment is completed (in portal)\n",
|
||||||
|
"You can also use SDK methods to fetch all the child runs and see individual metrics that we log."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"children = list(local_run.get_children())\n",
|
||||||
|
"metricslist = {}\n",
|
||||||
|
"for run in children:\n",
|
||||||
|
" properties = run.get_properties()\n",
|
||||||
|
" #print(properties)\n",
|
||||||
|
" metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)} \n",
|
||||||
|
" metricslist[int(properties['iteration'])] = metrics\n",
|
||||||
|
"\n",
|
||||||
|
"rundata = pd.DataFrame(metricslist).sort_index(1)\n",
|
||||||
|
"rundata"
|
||||||
|
]
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
|
|||||||
@@ -1,186 +0,0 @@
|
|||||||
{
|
|
||||||
"cells": [
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Copyright (c) Microsoft Corporation. All rights reserved. \n",
|
|
||||||
"\n",
|
|
||||||
"Licensed under the MIT License."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
""
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## 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
|
|
||||||
}
|
|
||||||
@@ -1,240 +0,0 @@
|
|||||||
{
|
|
||||||
"cells": [
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Copyright (c) Microsoft Corporation. All rights reserved. \n",
|
|
||||||
"\n",
|
|
||||||
"Licensed under the MIT License."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
""
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"# 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
|
|
||||||
}
|
|
||||||
@@ -1,270 +0,0 @@
|
|||||||
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
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -46,7 +46,7 @@
|
|||||||
"import azureml.core\n",
|
"import azureml.core\n",
|
||||||
"from azureml.core import Workspace, Experiment\n",
|
"from azureml.core import Workspace, Experiment\n",
|
||||||
"from azureml.core import LinkedService, SynapseWorkspaceLinkedServiceConfiguration\n",
|
"from azureml.core import LinkedService, SynapseWorkspaceLinkedServiceConfiguration\n",
|
||||||
"from azureml.core.compute import ComputeTarget, AmlCompute, SynapseCompute\n",
|
"from azureml.core.compute import ComputeTarget, SynapseCompute\n",
|
||||||
"from azureml.exceptions import ComputeTargetException\n",
|
"from azureml.exceptions import ComputeTargetException\n",
|
||||||
"from azureml.data import HDFSOutputDatasetConfig\n",
|
"from azureml.data import HDFSOutputDatasetConfig\n",
|
||||||
"from azureml.core.datastore import Datastore\n",
|
"from azureml.core.datastore import Datastore\n",
|
||||||
|
|||||||
@@ -1,18 +0,0 @@
|
|||||||
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)
|
|
||||||
@@ -157,9 +157,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Provision the AKS Cluster\n",
|
"## Provision the AKS Cluster\n",
|
||||||
"If you already have an AKS cluster attached to this workspace, skip the step below and provide the name of the cluster.\n",
|
"If you already have an AKS cluster attached to this workspace, skip the step below and provide the name of the cluster."
|
||||||
"\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."
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -267,9 +267,7 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"### Create AKS compute if you haven't done so.\n",
|
"### Create AKS compute if you haven't done so."
|
||||||
"\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."
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -211,8 +211,6 @@
|
|||||||
"# Provision the AKS Cluster with SSL\n",
|
"# Provision the AKS Cluster with SSL\n",
|
||||||
"This is a one time setup. You can reuse this cluster for multiple deployments after it has been created. If you delete the cluster or the resource group that contains it, then you would have to recreate it.\n",
|
"This is a one time setup. You can reuse this cluster for multiple deployments after it has been created. If you delete the cluster or the resource group that contains it, then you would have to recreate it.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"> Note that if you have an AzureML Data Scientist role, you will not have permission to create compute resources. Talk to your workspace or IT admin to create the compute targets described in this section, if they do not already exist.\n",
|
|
||||||
"\n",
|
|
||||||
"See code snippet below. Check the documentation [here](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-secure-web-service) for more details"
|
"See code snippet below. Check the documentation [here](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-secure-web-service) for more details"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -325,9 +325,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"# Provision the AKS Cluster\n",
|
"# Provision the AKS Cluster\n",
|
||||||
"This is a one time setup. You can reuse this cluster for multiple deployments after it has been created. If you delete the cluster or the resource group that contains it, then you would have to recreate it.\n",
|
"This is a one time setup. You can reuse this cluster for multiple deployments after it has been created. If you delete the cluster or the resource group that contains it, then you would have to recreate it."
|
||||||
"\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."
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -2,22 +2,23 @@
|
|||||||
"cells": [
|
"cells": [
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Licensed under the MIT License."
|
"Licensed under the MIT License."
|
||||||
],
|
]
|
||||||
"metadata": {}
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
""
|
""
|
||||||
],
|
]
|
||||||
"metadata": {}
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"# Register Spark Model and deploy as Webservice\n",
|
"# Register Spark Model and deploy as Webservice\n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -25,128 +26,120 @@
|
|||||||
"\n",
|
"\n",
|
||||||
" 1. Register Spark Model\n",
|
" 1. Register Spark Model\n",
|
||||||
" 2. Deploy Spark Model as Webservice"
|
" 2. Deploy Spark Model as Webservice"
|
||||||
],
|
]
|
||||||
"metadata": {}
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Prerequisites\n",
|
"## Prerequisites\n",
|
||||||
"If you are using an Azure Machine Learning Notebook VM, you are all set. Otherwise, make sure you go through the [configuration](../../../configuration.ipynb) Notebook first if you haven't."
|
"If you are using an Azure Machine Learning Notebook VM, you are all set. Otherwise, make sure you go through the [configuration](../../../configuration.ipynb) Notebook first if you haven't."
|
||||||
],
|
]
|
||||||
"metadata": {}
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
"source": [
|
"metadata": {},
|
||||||
"# Check core SDK version number\r\n",
|
|
||||||
"import azureml.core\r\n",
|
|
||||||
"\r\n",
|
|
||||||
"print(\"SDK version:\", azureml.core.VERSION)"
|
|
||||||
],
|
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"metadata": {}
|
"source": [
|
||||||
|
"# Check core SDK version number\n",
|
||||||
|
"import azureml.core\n",
|
||||||
|
"\n",
|
||||||
|
"print(\"SDK version:\", azureml.core.VERSION)"
|
||||||
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Initialize Workspace\n",
|
"## Initialize Workspace\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Initialize a workspace object from persisted configuration."
|
"Initialize a workspace object from persisted configuration."
|
||||||
],
|
]
|
||||||
"metadata": {}
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
"source": [
|
|
||||||
"from azureml.core import Workspace\r\n",
|
|
||||||
"\r\n",
|
|
||||||
"ws = Workspace.from_config()\r\n",
|
|
||||||
"print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep='\\n')"
|
|
||||||
],
|
|
||||||
"outputs": [],
|
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"tags": [
|
"tags": [
|
||||||
"create workspace"
|
"create workspace"
|
||||||
]
|
]
|
||||||
}
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core import Workspace\n",
|
||||||
|
"\n",
|
||||||
|
"ws = Workspace.from_config()\n",
|
||||||
|
"print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep='\\n')"
|
||||||
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"### Register Model"
|
"### Register Model"
|
||||||
],
|
]
|
||||||
"metadata": {}
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"You can add tags and descriptions to your Models. Note you need to have a `iris.model` file in the current directory. This model file is generated using [train in spark](../training/train-in-spark/train-in-spark.ipynb) notebook. The below call registers that file as a Model with the same name `iris.model` in the workspace.\n",
|
"You can add tags and descriptions to your Models. Note you need to have a `iris.model` file in the current directory. This model file is generated using [train in spark](../training/train-in-spark/train-in-spark.ipynb) notebook. The below call registers that file as a Model with the same name `iris.model` in the workspace.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Using tags, you can track useful information such as the name and version of the machine learning library used to train the model. Note that tags must be alphanumeric."
|
"Using tags, you can track useful information such as the name and version of the machine learning library used to train the model. Note that tags must be alphanumeric."
|
||||||
],
|
]
|
||||||
"metadata": {}
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
"source": [
|
|
||||||
"from azureml.core.model import Model\r\n",
|
|
||||||
"\r\n",
|
|
||||||
"model = Model.register(model_path=\"iris.model\",\r\n",
|
|
||||||
" model_name=\"iris.model\",\r\n",
|
|
||||||
" tags={'type': \"regression\"},\r\n",
|
|
||||||
" description=\"Logistic regression model to predict iris species\",\r\n",
|
|
||||||
" workspace=ws)"
|
|
||||||
],
|
|
||||||
"outputs": [],
|
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"tags": [
|
"tags": [
|
||||||
"register model from file"
|
"register model from file"
|
||||||
]
|
]
|
||||||
}
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core.model import Model\n",
|
||||||
|
"\n",
|
||||||
|
"model = Model.register(model_path=\"iris.model\",\n",
|
||||||
|
" model_name=\"iris.model\",\n",
|
||||||
|
" tags={'type': \"regression\"},\n",
|
||||||
|
" description=\"Logistic regression model to predict iris species\",\n",
|
||||||
|
" workspace=ws)"
|
||||||
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"### Fetch Environment"
|
"### Fetch Environment"
|
||||||
],
|
]
|
||||||
"metadata": {}
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
"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",
|
"In this notebook, we will be using 'AzureML-PySpark-MmlSpark-0.15', a curated environment.\n",
|
||||||
"\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)."
|
||||||
],
|
]
|
||||||
"metadata": {}
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
"source": [
|
"metadata": {},
|
||||||
"from azureml.core import Environment\r\n",
|
|
||||||
"from azureml.core.environment import SparkPackage\r\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"
|
|
||||||
],
|
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"metadata": {}
|
"source": [
|
||||||
|
"from azureml.core import Environment\n",
|
||||||
|
"\n",
|
||||||
|
"env = Environment.get(ws, name='AzureML-PySpark-MmlSpark-0.15')\n"
|
||||||
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Create Inference Configuration\n",
|
"## Create Inference Configuration\n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -164,109 +157,109 @@
|
|||||||
" - source_directory = holds source path as string, this entire folder gets added in image so its really easy to access any files within this folder or subfolder\n",
|
" - source_directory = holds source path as string, this entire folder gets added in image so its really easy to access any files within this folder or subfolder\n",
|
||||||
" - entry_script = contains logic specific to initializing your model and running predictions\n",
|
" - entry_script = contains logic specific to initializing your model and running predictions\n",
|
||||||
" - environment = An environment object to use for the deployment. Doesn't have to be registered"
|
" - environment = An environment object to use for the deployment. Doesn't have to be registered"
|
||||||
],
|
]
|
||||||
"metadata": {}
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
"source": [
|
|
||||||
"from azureml.core.model import InferenceConfig\r\n",
|
|
||||||
"\r\n",
|
|
||||||
"inference_config = InferenceConfig(entry_script=\"score.py\", environment=myenv)"
|
|
||||||
],
|
|
||||||
"outputs": [],
|
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"tags": [
|
"tags": [
|
||||||
"create image"
|
"create image"
|
||||||
]
|
]
|
||||||
}
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core.model import InferenceConfig\n",
|
||||||
|
"\n",
|
||||||
|
"inference_config = InferenceConfig(entry_script=\"score.py\", environment=env)"
|
||||||
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"### Deploy Model as Webservice on Azure Container Instance\n",
|
"### Deploy Model as Webservice on Azure Container Instance\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Note that the service creation can take few minutes."
|
"Note that the service creation can take few minutes."
|
||||||
],
|
]
|
||||||
"metadata": {}
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
"source": [
|
|
||||||
"from azureml.core.webservice import AciWebservice, Webservice\r\n",
|
|
||||||
"from azureml.exceptions import WebserviceException\r\n",
|
|
||||||
"\r\n",
|
|
||||||
"deployment_config = AciWebservice.deploy_configuration(cpu_cores=1, memory_gb=1)\r\n",
|
|
||||||
"aci_service_name = 'aciservice1'\r\n",
|
|
||||||
"\r\n",
|
|
||||||
"try:\r\n",
|
|
||||||
" # if you want to get existing service below is the command\r\n",
|
|
||||||
" # since aci name needs to be unique in subscription deleting existing aci if any\r\n",
|
|
||||||
" # we use aci_service_name to create azure aci\r\n",
|
|
||||||
" service = Webservice(ws, name=aci_service_name)\r\n",
|
|
||||||
" if service:\r\n",
|
|
||||||
" service.delete()\r\n",
|
|
||||||
"except WebserviceException as e:\r\n",
|
|
||||||
" print()\r\n",
|
|
||||||
"\r\n",
|
|
||||||
"service = Model.deploy(ws, aci_service_name, [model], inference_config, deployment_config)\r\n",
|
|
||||||
"\r\n",
|
|
||||||
"service.wait_for_deployment(True)\r\n",
|
|
||||||
"print(service.state)"
|
|
||||||
],
|
|
||||||
"outputs": [],
|
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"tags": [
|
"tags": [
|
||||||
"azuremlexception-remarks-sample"
|
"azuremlexception-remarks-sample"
|
||||||
]
|
]
|
||||||
}
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core.webservice import AciWebservice, Webservice\n",
|
||||||
|
"from azureml.exceptions import WebserviceException\n",
|
||||||
|
"\n",
|
||||||
|
"deployment_config = AciWebservice.deploy_configuration(cpu_cores=1, memory_gb=1)\n",
|
||||||
|
"aci_service_name = 'aciservice1'\n",
|
||||||
|
"\n",
|
||||||
|
"try:\n",
|
||||||
|
" # if you want to get existing service below is the command\n",
|
||||||
|
" # since aci name needs to be unique in subscription deleting existing aci if any\n",
|
||||||
|
" # we use aci_service_name to create azure aci\n",
|
||||||
|
" service = Webservice(ws, name=aci_service_name)\n",
|
||||||
|
" if service:\n",
|
||||||
|
" service.delete()\n",
|
||||||
|
"except WebserviceException as e:\n",
|
||||||
|
" print()\n",
|
||||||
|
"\n",
|
||||||
|
"service = Model.deploy(ws, aci_service_name, [model], inference_config, deployment_config)\n",
|
||||||
|
"\n",
|
||||||
|
"service.wait_for_deployment(True)\n",
|
||||||
|
"print(service.state)"
|
||||||
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"#### Test web service"
|
"#### Test web service"
|
||||||
],
|
]
|
||||||
"metadata": {}
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
"source": [
|
"metadata": {},
|
||||||
"import json\r\n",
|
|
||||||
"test_sample = json.dumps({'features':{'type':1,'values':[4.3,3.0,1.1,0.1]},'label':2.0})\r\n",
|
|
||||||
"\r\n",
|
|
||||||
"test_sample_encoded = bytes(test_sample, encoding='utf8')\r\n",
|
|
||||||
"prediction = service.run(input_data=test_sample_encoded)\r\n",
|
|
||||||
"print(prediction)"
|
|
||||||
],
|
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"metadata": {}
|
"source": [
|
||||||
|
"import json\n",
|
||||||
|
"test_sample = json.dumps({'features':{'type':1,'values':[4.3,3.0,1.1,0.1]},'label':2.0})\n",
|
||||||
|
"\n",
|
||||||
|
"test_sample_encoded = bytes(test_sample, encoding='utf8')\n",
|
||||||
|
"prediction = service.run(input_data=test_sample_encoded)\n",
|
||||||
|
"print(prediction)"
|
||||||
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"#### Delete ACI to clean up"
|
"#### Delete ACI to clean up"
|
||||||
],
|
]
|
||||||
"metadata": {}
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
"source": [
|
|
||||||
"service.delete()"
|
|
||||||
],
|
|
||||||
"outputs": [],
|
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"tags": [
|
"tags": [
|
||||||
"deploy service",
|
"deploy service",
|
||||||
"aci"
|
"aci"
|
||||||
]
|
]
|
||||||
}
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"service.delete()"
|
||||||
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"### Model Profiling\n",
|
"### Model Profiling\n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -278,11 +271,11 @@
|
|||||||
"profiling_results = profile.get_results()\n",
|
"profiling_results = profile.get_results()\n",
|
||||||
"print(profiling_results)\n",
|
"print(profiling_results)\n",
|
||||||
"```"
|
"```"
|
||||||
],
|
]
|
||||||
"metadata": {}
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"### Model Packaging\n",
|
"### Model Packaging\n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -303,8 +296,7 @@
|
|||||||
"package.wait_for_creation(show_output=True)\n",
|
"package.wait_for_creation(show_output=True)\n",
|
||||||
"package.save(\"./local_context_dir\")\n",
|
"package.save(\"./local_context_dir\")\n",
|
||||||
"```"
|
"```"
|
||||||
],
|
]
|
||||||
"metadata": {}
|
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"metadata": {
|
"metadata": {
|
||||||
|
|||||||
@@ -203,8 +203,6 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"### Provision a compute target\n",
|
"### Provision a compute target\n",
|
||||||
"\n",
|
"\n",
|
||||||
"> Note that if you have an AzureML Data Scientist role, you will not have permission to create compute resources. Talk to your workspace or IT admin to create the compute targets described in this section, if they do not already exist.\n",
|
|
||||||
"\n",
|
|
||||||
"You can provision an AmlCompute resource by simply defining two parameters thanks to smart defaults. By default it autoscales from 0 nodes and provisions dedicated VMs to run your job in a container. This is useful when you want to continously re-use the same target, debug it between jobs or simply share the resource with other users of your workspace.\n",
|
"You can provision an AmlCompute resource by simply defining two parameters thanks to smart defaults. By default it autoscales from 0 nodes and provisions dedicated VMs to run your job in a container. This is useful when you want to continously re-use the same target, debug it between jobs or simply share the resource with other users of your workspace.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"* `vm_size`: VM family of the nodes provisioned by AmlCompute. Simply choose from the supported_vmsizes() above\n",
|
"* `vm_size`: VM family of the nodes provisioned by AmlCompute. Simply choose from the supported_vmsizes() above\n",
|
||||||
@@ -217,6 +215,7 @@
|
|||||||
"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",
|
||||||
@@ -266,7 +265,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 list(available_packages):\n",
|
"for dist in 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",
|
||||||
@@ -285,6 +284,7 @@
|
|||||||
"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",
|
||||||
@@ -414,6 +414,7 @@
|
|||||||
"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)"
|
||||||
]
|
]
|
||||||
@@ -441,7 +442,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from raiwidgets import ExplanationDashboard"
|
"from interpret_community.widget import ExplanationDashboard"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -450,7 +451,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"ExplanationDashboard(global_explanation, original_model, dataset=x_test)"
|
"ExplanationDashboard(global_explanation, original_model, datasetX=x_test)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -11,4 +11,3 @@ dependencies:
|
|||||||
- matplotlib
|
- matplotlib
|
||||||
- azureml-dataset-runtime
|
- azureml-dataset-runtime
|
||||||
- ipywidgets
|
- ipywidgets
|
||||||
- raiwidgets~=0.7.0
|
|
||||||
|
|||||||
@@ -87,6 +87,7 @@
|
|||||||
"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",
|
||||||
@@ -532,7 +533,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from raiwidgets import ExplanationDashboard"
|
"from interpret_community.widget import ExplanationDashboard"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -541,7 +542,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"ExplanationDashboard(downloaded_global_explanation, model, dataset=x_test)"
|
"ExplanationDashboard(downloaded_global_explanation, model, datasetX=x_test)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -10,4 +10,3 @@ dependencies:
|
|||||||
- ipython
|
- ipython
|
||||||
- matplotlib
|
- matplotlib
|
||||||
- ipywidgets
|
- ipywidgets
|
||||||
- raiwidgets~=0.7.0
|
|
||||||
|
|||||||
@@ -170,6 +170,7 @@
|
|||||||
"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",
|
||||||
@@ -220,6 +221,7 @@
|
|||||||
" ('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",
|
||||||
@@ -294,7 +296,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from raiwidgets import ExplanationDashboard"
|
"from interpret_community.widget import ExplanationDashboard"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -303,7 +305,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"ExplanationDashboard(global_explanation, clf, dataset=x_test)"
|
"ExplanationDashboard(global_explanation, clf, datasetX=x_test)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -354,7 +356,8 @@
|
|||||||
"# 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",
|
||||||
@@ -380,10 +383,11 @@
|
|||||||
"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",
|
|
||||||
"\n",
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"aciconfig = AciWebservice.deploy_configuration(cpu_cores=1, \n",
|
"aciconfig = AciWebservice.deploy_configuration(cpu_cores=1, \n",
|
||||||
|
|||||||
@@ -10,4 +10,3 @@ dependencies:
|
|||||||
- ipython
|
- ipython
|
||||||
- matplotlib
|
- matplotlib
|
||||||
- ipywidgets
|
- ipywidgets
|
||||||
- raiwidgets~=0.7.0
|
|
||||||
|
|||||||
@@ -204,8 +204,6 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"### Provision a compute target\n",
|
"### Provision a compute target\n",
|
||||||
"\n",
|
"\n",
|
||||||
"> Note that if you have an AzureML Data Scientist role, you will not have permission to create compute resources. Talk to your workspace or IT admin to create the compute targets described in this section, if they do not already exist.\n",
|
|
||||||
"\n",
|
|
||||||
"You can provision an AmlCompute resource by simply defining two parameters thanks to smart defaults. By default it autoscales from 0 nodes and provisions dedicated VMs to run your job in a container. This is useful when you want to continously re-use the same target, debug it between jobs or simply share the resource with other users of your workspace.\n",
|
"You can provision an AmlCompute resource by simply defining two parameters thanks to smart defaults. By default it autoscales from 0 nodes and provisions dedicated VMs to run your job in a container. This is useful when you want to continously re-use the same target, debug it between jobs or simply share the resource with other users of your workspace.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"* `vm_size`: VM family of the nodes provisioned by AmlCompute. Simply choose from the supported_vmsizes() above\n",
|
"* `vm_size`: VM family of the nodes provisioned by AmlCompute. Simply choose from the supported_vmsizes() above\n",
|
||||||
@@ -218,6 +216,7 @@
|
|||||||
"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",
|
||||||
@@ -379,6 +378,7 @@
|
|||||||
"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)"
|
||||||
@@ -398,7 +398,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from raiwidgets import ExplanationDashboard"
|
"from interpret_community.widget import ExplanationDashboard"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -407,7 +407,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"ExplanationDashboard(global_explanation, original_svm_model, dataset=x_test)"
|
"ExplanationDashboard(global_explanation, original_svm_model, datasetX=x_test)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -424,6 +424,8 @@
|
|||||||
"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",
|
||||||
@@ -433,6 +435,7 @@
|
|||||||
"\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",
|
||||||
@@ -478,10 +481,11 @@
|
|||||||
"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",
|
|
||||||
"\n",
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"aciconfig = AciWebservice.deploy_configuration(cpu_cores=1, \n",
|
"aciconfig = AciWebservice.deploy_configuration(cpu_cores=1, \n",
|
||||||
|
|||||||
@@ -12,4 +12,3 @@ dependencies:
|
|||||||
- azureml-dataset-runtime
|
- azureml-dataset-runtime
|
||||||
- azureml-core
|
- azureml-core
|
||||||
- ipywidgets
|
- ipywidgets
|
||||||
- raiwidgets~=0.7.0
|
|
||||||
|
|||||||
@@ -209,8 +209,6 @@
|
|||||||
"#### Retrieve or create a Azure Machine Learning compute\n",
|
"#### Retrieve or create a Azure Machine Learning compute\n",
|
||||||
"Azure Machine Learning Compute is a service for provisioning and managing clusters of Azure virtual machines for running machine learning workloads. Let's create a new Azure Machine Learning Compute in the current workspace, if it doesn't already exist. We will then run the training script on this compute target.\n",
|
"Azure Machine Learning Compute is a service for provisioning and managing clusters of Azure virtual machines for running machine learning workloads. Let's create a new Azure Machine Learning Compute in the current workspace, if it doesn't already exist. We will then run the training script on this compute target.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"> Note that if you have an AzureML Data Scientist role, you will not have permission to create compute resources. Talk to your workspace or IT admin to create the compute targets described in this section, if they do not already exist.\n",
|
|
||||||
"\n",
|
|
||||||
"If we could not find the compute with the given name in the previous cell, then we will create a new compute here. We will create an Azure Machine Learning Compute containing **STANDARD_D2_V2 CPU VMs**. This process is broken down into the following steps:\n",
|
"If we could not find the compute with the given name in the previous cell, then we will create a new compute here. We will create an Azure Machine Learning Compute containing **STANDARD_D2_V2 CPU VMs**. This process is broken down into the following steps:\n",
|
||||||
"\n",
|
"\n",
|
||||||
"1. Create the configuration\n",
|
"1. Create the configuration\n",
|
||||||
|
|||||||
@@ -55,9 +55,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"### Compute Target\n",
|
"### Compute Target\n",
|
||||||
"Retrieve an already attached Azure Machine Learning Compute to use in the Pipeline.\n",
|
"Retrieve an already attached Azure Machine Learning Compute to use in the Pipeline."
|
||||||
"\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."
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -210,8 +210,6 @@
|
|||||||
"## Retrieve or create a Azure Machine Learning compute\n",
|
"## Retrieve or create a Azure Machine Learning compute\n",
|
||||||
"Azure Machine Learning Compute is a service for provisioning and managing clusters of Azure virtual machines for running machine learning workloads. Let's create a new Azure Machine Learning Compute in the current workspace, if it doesn't already exist. We will then run the training script on this compute target.\n",
|
"Azure Machine Learning Compute is a service for provisioning and managing clusters of Azure virtual machines for running machine learning workloads. Let's create a new Azure Machine Learning Compute in the current workspace, if it doesn't already exist. We will then run the training script on this compute target.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"> Note that if you have an AzureML Data Scientist role, you will not have permission to create compute resources. Talk to your workspace or IT admin to create the compute targets described in this section, if they do not already exist.\n",
|
|
||||||
"\n",
|
|
||||||
"If we could not find the compute with the given name in the previous cell, then we will create a new compute here. This process is broken down into the following steps:\n",
|
"If we could not find the compute with the given name in the previous cell, then we will create a new compute here. This process is broken down into the following steps:\n",
|
||||||
"\n",
|
"\n",
|
||||||
"1. Create the configuration\n",
|
"1. Create the configuration\n",
|
||||||
|
|||||||
@@ -68,9 +68,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"### Compute Targets\n",
|
"### Compute Targets\n",
|
||||||
"#### Retrieve an already attached Azure Machine Learning Compute\n",
|
"#### Retrieve an already attached Azure Machine Learning Compute"
|
||||||
"\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."
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -54,9 +54,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"### Compute Targets\n",
|
"### Compute Targets\n",
|
||||||
"#### Retrieve an already attached Azure Machine Learning Compute\n",
|
"#### Retrieve an already attached Azure Machine Learning Compute"
|
||||||
"\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."
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -78,9 +78,7 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"#### Initialization, Steps to create a Pipeline\n",
|
"#### Initialization, Steps to create a Pipeline\n",
|
||||||
"\n",
|
"\n",
|
||||||
"The best practice is to use separate folders for scripts and its dependent files for each step and specify that folder as the `source_directory` for the step. This helps reduce the size of the snapshot created for the step (only the specific folder is snapshotted). Since changes in any files in the `source_directory` would trigger a re-upload of the snapshot, this helps keep the reuse of the step when there are no changes in the `source_directory` of the step.\n",
|
"The best practice is to use separate folders for scripts and its dependent files for each step and specify that folder as the `source_directory` for the step. This helps reduce the size of the snapshot created for the step (only the specific folder is snapshotted). Since changes in any files in the `source_directory` would trigger a re-upload of the snapshot, this helps keep the reuse of the step when there are no changes in the `source_directory` of the step."
|
||||||
"\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."
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -109,9 +109,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Create or Attach an AmlCompute cluster\n",
|
"## Create or Attach an AmlCompute cluster\n",
|
||||||
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for your AutoML run. In this tutorial, you get the default `AmlCompute` as your training compute resource.\n",
|
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for your AutoML run. In this tutorial, you get the default `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."
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -111,9 +111,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Create or Attach an AmlCompute cluster\n",
|
"## Create or Attach an AmlCompute cluster\n",
|
||||||
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for your AutoML run. In this tutorial, you get the default `AmlCompute` as your training compute resource.\n",
|
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for your AutoML run. In this tutorial, you get the default `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."
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -699,162 +699,12 @@
|
|||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"source": [
|
|
||||||
"### 5. Running demo notebook already added to the Databricks workspace using existing cluster\n",
|
|
||||||
"First you need register DBFS datastore and make sure path_on_datastore does exist in databricks file system, you can browser the files by refering [this](https://docs.azuredatabricks.net/user-guide/dbfs-databricks-file-system.html).\n",
|
|
||||||
"\n",
|
|
||||||
"Find existing_cluster_id by opeing Azure Databricks UI with Clusters page and in url you will find a string connected with '-' right after \"clusters/\"."
|
|
||||||
],
|
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"try:\n",
|
|
||||||
" dbfs_ds = Datastore.get(workspace=ws, datastore_name='dbfs_datastore')\n",
|
|
||||||
" print('DBFS Datastore already exists')\n",
|
|
||||||
"except Exception as ex:\n",
|
|
||||||
" dbfs_ds = Datastore.register_dbfs(ws, datastore_name='dbfs_datastore')\n",
|
|
||||||
"\n",
|
|
||||||
"step_1_input = DataReference(datastore=dbfs_ds, path_on_datastore=\"FileStore\", data_reference_name=\"input\")\n",
|
|
||||||
"step_1_output = PipelineData(\"output\", datastore=dbfs_ds)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"dbNbWithExistingClusterStep = DatabricksStep(\n",
|
|
||||||
" name=\"DBFSReferenceWithExisting\",\n",
|
|
||||||
" inputs=[step_1_input],\n",
|
|
||||||
" outputs=[step_1_output],\n",
|
|
||||||
" notebook_path=notebook_path,\n",
|
|
||||||
" notebook_params={'myparam': 'testparam', \n",
|
|
||||||
" 'myparam2': pipeline_param},\n",
|
|
||||||
" run_name='DBFS_Reference_With_Existing',\n",
|
|
||||||
" compute_target=databricks_compute,\n",
|
|
||||||
" existing_cluster_id=\"your existing cluster id\",\n",
|
|
||||||
" allow_reuse=True\n",
|
|
||||||
")"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"source": [
|
|
||||||
"#### Build and submit the Experiment"
|
|
||||||
],
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"steps = [dbNbWithExistingClusterStep]\n",
|
|
||||||
"pipeline = Pipeline(workspace=ws, steps=steps)\n",
|
|
||||||
"pipeline_run = Experiment(ws, 'DBFS_Reference_With_Existing').submit(pipeline)\n",
|
|
||||||
"pipeline_run.wait_for_completion()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"source": [
|
|
||||||
"#### View Run Details"
|
|
||||||
],
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.widgets import RunDetails\n",
|
|
||||||
"RunDetails(pipeline_run).show()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"source": [
|
|
||||||
"### 6. Running a Python script in Databricks that currenlty is in local computer with existing cluster\n",
|
|
||||||
"When you access azure blob or data lake storage from an existing (interactive) cluster, you need to ensure the Spark configuration is set up correctly to access this storage and this set up may require the cluster to be restarted.\n",
|
|
||||||
"\n",
|
|
||||||
"If you set permit_cluster_restart to True, AML will check if the spark configuration needs to be updated and restart the cluster for you if required. This will ensure that the storage can be correctly accessed from the Databricks cluster."
|
|
||||||
],
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"step_1_input = DataReference(datastore=def_blob_store, path_on_datastore=\"dbtest\",\n",
|
|
||||||
" data_reference_name=\"input\")\n",
|
|
||||||
"\n",
|
|
||||||
"dbPythonInLocalWithExistingStep = DatabricksStep(\n",
|
|
||||||
" name=\"DBPythonInLocalMachineWithExisting\",\n",
|
|
||||||
" inputs=[step_1_input],\n",
|
|
||||||
" python_script_name=python_script_name,\n",
|
|
||||||
" source_directory=source_directory,\n",
|
|
||||||
" run_name='DB_Python_Local_existing_demo',\n",
|
|
||||||
" compute_target=databricks_compute,\n",
|
|
||||||
" existing_cluster_id=\"your existing cluster id\",\n",
|
|
||||||
" allow_reuse=False,\n",
|
|
||||||
" permit_cluster_restart=True\n",
|
|
||||||
")"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"source": [
|
|
||||||
"#### Build and submit the Experiment"
|
|
||||||
],
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"steps = [dbPythonInLocalWithExistingStep]\n",
|
|
||||||
"pipeline = Pipeline(workspace=ws, steps=steps)\n",
|
|
||||||
"pipeline_run = Experiment(ws, 'DB_Python_Local_existing_demo').submit(pipeline)\n",
|
|
||||||
"pipeline_run.wait_for_completion()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"source": [
|
|
||||||
"#### View Run Details"
|
|
||||||
],
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.widgets import RunDetails\n",
|
|
||||||
"RunDetails(pipeline_run).show()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"source": [
|
"source": [
|
||||||
"# Next: ADLA as a Compute Target\n",
|
"# Next: ADLA as a Compute Target\n",
|
||||||
"To use ADLA as a compute target from Azure Machine Learning Pipeline, a AdlaStep is used. This [notebook](https://aka.ms/pl-adla) demonstrates the use of AdlaStep in Azure Machine Learning Pipeline."
|
"To use ADLA as a compute target from Azure Machine Learning Pipeline, a AdlaStep is used. This [notebook](https://aka.ms/pl-adla) demonstrates the use of AdlaStep in Azure Machine Learning Pipeline."
|
||||||
],
|
]
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {}
|
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"metadata": {
|
"metadata": {
|
||||||
|
|||||||
@@ -125,9 +125,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"### Create or Attach an AmlCompute cluster\n",
|
"### Create or Attach an AmlCompute cluster\n",
|
||||||
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for your AutoML run. In this tutorial, you get the default `AmlCompute` as your training compute resource.\n",
|
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for your AutoML run. In this tutorial, you get the default `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."
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -148,7 +146,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_DS12_V2',# for GPU, use \"STANDARD_NC6\"\n",
|
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_D2_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",
|
||||||
|
|||||||
@@ -79,9 +79,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Create or Attach existing AmlCompute\n",
|
"## Create or Attach existing AmlCompute\n",
|
||||||
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for training your model. In this tutorial, you create `AmlCompute` as your training compute resource.\n",
|
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for training your model. 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."
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -77,9 +77,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Create or Attach existing AmlCompute\n",
|
"## Create or Attach existing AmlCompute\n",
|
||||||
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for training your model. In this tutorial, you create `AmlCompute` as your training compute resource.\n",
|
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for training your model. 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."
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -134,9 +134,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"#### Retrieve or create an Aml compute\n",
|
"#### Retrieve or create an Aml compute\n",
|
||||||
"Azure Machine Learning Compute is a service for provisioning and managing clusters of Azure virtual machines for running machine learning workloads. Let's get the default Aml Compute in the current workspace. We will then run the training script on this compute target.\n",
|
"Azure Machine Learning Compute is a service for provisioning and managing clusters of Azure virtual machines for running machine learning workloads. Let's get the default Aml Compute in the current workspace. We will then run the training script on this compute target."
|
||||||
"\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."
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -147,9 +147,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"### Create or Attach an AmlCompute cluster\n",
|
"### Create or Attach an AmlCompute cluster\n",
|
||||||
"You will need to create a [compute target](https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.computetarget?view=azure-ml-py) for your remote run. In this tutorial, you get the default `AmlCompute` as your training compute resource.\n",
|
"You will need to create a [compute target](https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.computetarget?view=azure-ml-py) for your remote run. In this tutorial, you get the default `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."
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -225,9 +225,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"### Setup Compute\n",
|
"### Setup Compute\n",
|
||||||
"#### Create new or use an existing compute\n",
|
"#### Create new or use an existing compute"
|
||||||
"\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."
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -247,7 +245,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_DS12_V2',\n",
|
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_D2_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,6 +679,7 @@
|
|||||||
"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",
|
||||||
@@ -783,8 +782,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(current_step, output_name):\n",
|
"def fetch_df(step, output_name):\n",
|
||||||
" output_data = current_step.get_output_data(output_name) \n",
|
" output_data = 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",
|
||||||
@@ -940,6 +939,32 @@
|
|||||||
"#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": {},
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ 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
|
||||||
|
|||||||
@@ -122,8 +122,4 @@ 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.
|
|
||||||
|
|
||||||

|

|
||||||
|
|||||||
@@ -24,9 +24,9 @@
|
|||||||
"In this notebook, we will demonstrate how to make predictions on large quantities of data asynchronously using the ML pipelines with Azure Machine Learning. Batch inference (or batch scoring) provides cost-effective inference, with unparalleled throughput for asynchronous applications. Batch prediction pipelines can scale to perform inference on terabytes of production data. Batch prediction is optimized for high throughput, fire-and-forget predictions for a large collection of data.\n",
|
"In this notebook, we will demonstrate how to make predictions on large quantities of data asynchronously using the ML pipelines with Azure Machine Learning. Batch inference (or batch scoring) provides cost-effective inference, with unparalleled throughput for asynchronous applications. Batch prediction pipelines can scale to perform inference on terabytes of production data. Batch prediction is optimized for high throughput, fire-and-forget predictions for a large collection of data.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"> **Tip**\n",
|
"> **Tip**\n",
|
||||||
"If your system requires low-latency processing (to process a single document or small set of documents quickly), use [real-time scoring](https://docs.microsoft.com/azure/machine-learning/service/how-to-consume-web-service) instead of batch prediction.\n",
|
"If your system requires low-latency processing (to process a single document or small set of documents quickly), use [real-time scoring](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-consume-web-service) instead of batch prediction.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"In this example will be take a digit identification model already-trained on MNIST dataset using the [AzureML training with deep learning example notebook](https://github.com/Azure/MachineLearningNotebooks/blob/master/how-to-use-azureml/ml-frameworks/keras/train-hyperparameter-tune-deploy-with-keras/train-hyperparameter-tune-deploy-with-keras.ipynb), and run that trained model on some of the MNIST test images in batch. \n",
|
"In this example will be take a digit identification model already-trained on MNIST dataset using the [AzureML training with deep learning example notebook](https://github.com/Azure/MachineLearningNotebooks/blob/master/how-to-use-azureml/training-with-deep-learning/train-hyperparameter-tune-deploy-with-keras/train-hyperparameter-tune-deploy-with-keras.ipynb), and run that trained model on some of the MNIST test images in batch. \n",
|
||||||
"\n",
|
"\n",
|
||||||
"The input dataset used for this notebook differs from a standard MNIST dataset in that it has been converted to PNG images to demonstrate use of files as inputs to Batch Inference. A sample of PNG-converted images of the MNIST dataset were take from [this repository](https://github.com/myleott/mnist_png). \n",
|
"The input dataset used for this notebook differs from a standard MNIST dataset in that it has been converted to PNG images to demonstrate use of files as inputs to Batch Inference. A sample of PNG-converted images of the MNIST dataset were take from [this repository](https://github.com/myleott/mnist_png). \n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -86,8 +86,6 @@
|
|||||||
"### Create or Attach existing compute resource\n",
|
"### Create or Attach existing compute resource\n",
|
||||||
"By using Azure Machine Learning Compute, a managed service, data scientists can train machine learning models on clusters of Azure virtual machines. Examples include VMs with GPU support. In this tutorial, you create Azure Machine Learning Compute as your training environment. The code below creates the compute clusters for you if they don't already exist in your workspace.\n",
|
"By using Azure Machine Learning Compute, a managed service, data scientists can train machine learning models on clusters of Azure virtual machines. Examples include VMs with GPU support. In this tutorial, you create Azure Machine Learning Compute as your training environment. The code below creates the compute clusters for you if they don't already exist in your workspace.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"> Note that if you have an AzureML Data Scientist role, you will not have permission to create compute resources. Talk to your workspace or IT admin to create the compute targets described in this section, if they do not already exist.\n",
|
|
||||||
"\n",
|
|
||||||
"**Creation of compute takes approximately 5 minutes. If the AmlCompute with that name is already in your workspace the code will skip the creation process.**"
|
"**Creation of compute takes approximately 5 minutes. If the AmlCompute with that name is already in your workspace the code will skip the creation process.**"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -182,7 +180,8 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"### Create a FileDataset\n",
|
"### Create a FileDataset\n",
|
||||||
"A [FileDataset](https://docs.microsoft.com/python/api/azureml-core/azureml.data.filedataset?view=azure-ml-py) references single or multiple files in your datastores or public urls. The files can be of any format. FileDataset provides you with the ability to download or mount the files to your compute. By creating a dataset, you create a reference to the data source location. If you applied any subsetting transformations to the dataset, they will be stored in the dataset as well. The data remains in its existing location, so no extra storage cost is incurred.\n",
|
"A [FileDataset](https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.data.filedataset?view=azure-ml-py) references single or multiple files in your datastores or public urls. The files can be of any format. FileDataset provides you with the ability to download or mount the files to your compute. By creating a dataset, you create a reference to the data source location. If you applied any subsetting transformations to the dataset, they will be stored in the dataset as well. The data remains in its existing location, so no extra storage cost is incurred.",
|
||||||
|
"\n",
|
||||||
"You can use dataset objects as inputs. Register the datasets to the workspace if you want to reuse them later."
|
"You can use dataset objects as inputs. Register the datasets to the workspace if you want to reuse them later."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -225,7 +224,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"### Intermediate/Output Data\n",
|
"### Intermediate/Output Data\n",
|
||||||
"Intermediate data (or output of a Step) is represented by [PipelineData](https://docs.microsoft.com/python/api/azureml-pipeline-core/azureml.pipeline.core.pipelinedata?view=azure-ml-py) object. PipelineData can be produced by one step and consumed in another step by providing the PipelineData object as an output of one step and the input of one or more steps."
|
"Intermediate data (or output of a Step) is represented by [PipelineData](https://docs.microsoft.com/en-us/python/api/azureml-pipeline-core/azureml.pipeline.core.pipelinedata?view=azure-ml-py) object. PipelineData can be produced by one step and consumed in another step by providing the PipelineData object as an output of one step and the input of one or more steps."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -277,7 +276,7 @@
|
|||||||
"### Register the model with Workspace\n",
|
"### Register the model with Workspace\n",
|
||||||
"A registered model is a logical container for one or more files that make up your model. For example, if you have a model that's stored in multiple files, you can register them as a single model in the workspace. After you register the files, you can then download or deploy the registered model and receive all the files that you registered.\n",
|
"A registered model is a logical container for one or more files that make up your model. For example, if you have a model that's stored in multiple files, you can register them as a single model in the workspace. After you register the files, you can then download or deploy the registered model and receive all the files that you registered.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Using tags, you can track useful information such as the name and version of the machine learning library used to train the model. Note that tags must be alphanumeric. Learn more about registering models [here](https://docs.microsoft.com/azure/machine-learning/service/how-to-deploy-and-where#registermodel) "
|
"Using tags, you can track useful information such as the name and version of the machine learning library used to train the model. Note that tags must be alphanumeric. Learn more about registering models [here](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-deploy-and-where#registermodel) "
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -363,6 +362,7 @@
|
|||||||
" \"azureml-core\", \"azureml-dataset-runtime[fuse]\"])\n",
|
" \"azureml-core\", \"azureml-dataset-runtime[fuse]\"])\n",
|
||||||
"batch_env = Environment(name=\"batch_environment\")\n",
|
"batch_env = Environment(name=\"batch_environment\")\n",
|
||||||
"batch_env.python.conda_dependencies = batch_conda_deps\n",
|
"batch_env.python.conda_dependencies = batch_conda_deps\n",
|
||||||
|
"batch_env.docker.enabled = True\n",
|
||||||
"batch_env.docker.base_image = DEFAULT_CPU_IMAGE"
|
"batch_env.docker.base_image = DEFAULT_CPU_IMAGE"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -379,6 +379,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
|
"from azureml.pipeline.core import PipelineParameter\n",
|
||||||
"from azureml.pipeline.steps import ParallelRunStep, ParallelRunConfig\n",
|
"from azureml.pipeline.steps import ParallelRunStep, ParallelRunConfig\n",
|
||||||
"\n",
|
"\n",
|
||||||
"parallel_run_config = ParallelRunConfig(\n",
|
"parallel_run_config = ParallelRunConfig(\n",
|
||||||
|
|||||||
@@ -24,7 +24,7 @@
|
|||||||
"In this notebook, we will demonstrate how to make predictions on large quantities of data asynchronously using the ML pipelines with Azure Machine Learning. Batch inference (or batch scoring) provides cost-effective inference, with unparalleled throughput for asynchronous applications. Batch prediction pipelines can scale to perform inference on terabytes of production data. Batch prediction is optimized for high throughput, fire-and-forget predictions for a large collection of data.\n",
|
"In this notebook, we will demonstrate how to make predictions on large quantities of data asynchronously using the ML pipelines with Azure Machine Learning. Batch inference (or batch scoring) provides cost-effective inference, with unparalleled throughput for asynchronous applications. Batch prediction pipelines can scale to perform inference on terabytes of production data. Batch prediction is optimized for high throughput, fire-and-forget predictions for a large collection of data.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"> **Tip**\n",
|
"> **Tip**\n",
|
||||||
"If your system requires low-latency processing (to process a single document or small set of documents quickly), use [real-time scoring](https://docs.microsoft.com/azure/machine-learning/service/how-to-consume-web-service) instead of batch prediction.\n",
|
"If your system requires low-latency processing (to process a single document or small set of documents quickly), use [real-time scoring](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-consume-web-service) instead of batch prediction.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"In this example we will take use a machine learning model already trained to predict different types of iris flowers and run that trained model on some of the data in a CSV file which has characteristics of different iris flowers. However, the same example can be extended to manipulating data to any embarrassingly-parallel processing through a python script.\n",
|
"In this example we will take use a machine learning model already trained to predict different types of iris flowers and run that trained model on some of the data in a CSV file which has characteristics of different iris flowers. However, the same example can be extended to manipulating data to any embarrassingly-parallel processing through a python script.\n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -84,8 +84,6 @@
|
|||||||
"### Create or Attach existing compute resource\n",
|
"### Create or Attach existing compute resource\n",
|
||||||
"By using Azure Machine Learning Compute, a managed service, data scientists can train machine learning models on clusters of Azure virtual machines. Examples include VMs with GPU support. In this tutorial, you create Azure Machine Learning Compute as your training environment. The code below creates the compute clusters for you if they don't already exist in your workspace.\n",
|
"By using Azure Machine Learning Compute, a managed service, data scientists can train machine learning models on clusters of Azure virtual machines. Examples include VMs with GPU support. In this tutorial, you create Azure Machine Learning Compute as your training environment. The code below creates the compute clusters for you if they don't already exist in your workspace.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"> Note that if you have an AzureML Data Scientist role, you will not have permission to create compute resources. Talk to your workspace or IT admin to create the compute targets described in this section, if they do not already exist.\n",
|
|
||||||
"\n",
|
|
||||||
"**Creation of compute takes approximately 5 minutes. If the AmlCompute with that name is already in your workspace the code will skip the creation process.**"
|
"**Creation of compute takes approximately 5 minutes. If the AmlCompute with that name is already in your workspace the code will skip the creation process.**"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -162,7 +160,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"### Create a TabularDataset\n",
|
"### Create a TabularDataset\n",
|
||||||
"A [TabularDataSet](https://docs.microsoft.com/python/api/azureml-core/azureml.data.tabulardataset?view=azure-ml-py) references single or multiple files which contain data in a tabular structure (ie like CSV files) in your datastores or public urls. TabularDatasets provides you with the ability to download or mount the files to your compute. By creating a dataset, you create a reference to the data source location. If you applied any subsetting transformations to the dataset, they will be stored in the dataset as well. The data remains in its existing location, so no extra storage cost is incurred.\n",
|
"A [TabularDataSet](https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.data.tabulardataset?view=azure-ml-py) references single or multiple files which contain data in a tabular structure (ie like CSV files) in your datastores or public urls. TabularDatasets provides you with the ability to download or mount the files to your compute. By creating a dataset, you create a reference to the data source location. If you applied any subsetting transformations to the dataset, they will be stored in the dataset as well. The data remains in its existing location, so no extra storage cost is incurred.\n",
|
||||||
"You can use dataset objects as inputs. Register the datasets to the workspace if you want to reuse them later."
|
"You can use dataset objects as inputs. Register the datasets to the workspace if you want to reuse them later."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -186,7 +184,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"### Intermediate/Output Data\n",
|
"### Intermediate/Output Data\n",
|
||||||
"Intermediate data (or output of a Step) is represented by [PipelineData](https://docs.microsoft.com/python/api/azureml-pipeline-core/azureml.pipeline.core.pipelinedata?view=azure-ml-py) object. PipelineData can be produced by one step and consumed in another step by providing the PipelineData object as an output of one step and the input of one or more steps."
|
"Intermediate data (or output of a Step) is represented by [PipelineData](https://docs.microsoft.com/en-us/python/api/azureml-pipeline-core/azureml.pipeline.core.pipelinedata?view=azure-ml-py) object. PipelineData can be produced by one step and consumed in another step by providing the PipelineData object as an output of one step and the input of one or more steps."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -313,6 +311,7 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"predict_env = Environment(name=\"predict_environment\")\n",
|
"predict_env = Environment(name=\"predict_environment\")\n",
|
||||||
"predict_env.python.conda_dependencies = predict_conda_deps\n",
|
"predict_env.python.conda_dependencies = predict_conda_deps\n",
|
||||||
|
"predict_env.docker.enabled = True\n",
|
||||||
"predict_env.spark.precache_packages = False"
|
"predict_env.spark.precache_packages = False"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -178,9 +178,7 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"# Create or use existing compute\n",
|
"# Create or use existing compute"
|
||||||
"\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."
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -98,8 +98,6 @@
|
|||||||
"## Create or attach existing AmlCompute\n",
|
"## Create or attach existing AmlCompute\n",
|
||||||
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for training your model. In this tutorial, we use Azure ML managed compute ([AmlCompute](https://docs.microsoft.com/azure/machine-learning/service/how-to-set-up-training-targets#amlcompute)) for our remote training compute resource. Specifically, the below code creates an `STANDARD_NC6` GPU cluster that autoscales from `0` to `4` nodes.\n",
|
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for training your model. In this tutorial, we use Azure ML managed compute ([AmlCompute](https://docs.microsoft.com/azure/machine-learning/service/how-to-set-up-training-targets#amlcompute)) for our remote training compute resource. Specifically, the below code creates an `STANDARD_NC6` GPU cluster that autoscales from `0` to `4` nodes.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"> Note that if you have an AzureML Data Scientist role, you will not have permission to create compute resources. Talk to your workspace or IT admin to create the compute targets described in this section, if they do not already exist.\n",
|
|
||||||
"\n",
|
|
||||||
"**Creation of AmlCompute takes approximately 5 minutes.** If the AmlCompute with that name is already in your workspace, this code will skip the creation process.\n",
|
"**Creation of AmlCompute takes approximately 5 minutes.** If the AmlCompute with that name is already in your workspace, this code will skip the creation process.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
||||||
|
|||||||
@@ -98,8 +98,6 @@
|
|||||||
"## Create or Attach existing AmlCompute\n",
|
"## Create or Attach existing AmlCompute\n",
|
||||||
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for training your model. In this tutorial, we use Azure ML managed compute ([AmlCompute](https://docs.microsoft.com/azure/machine-learning/service/how-to-set-up-training-targets#amlcompute)) for our remote training compute resource.\n",
|
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for training your model. In this tutorial, we use Azure ML managed compute ([AmlCompute](https://docs.microsoft.com/azure/machine-learning/service/how-to-set-up-training-targets#amlcompute)) for our remote training compute resource.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"> Note that if you have an AzureML Data Scientist role, you will not have permission to create compute resources. Talk to your workspace or IT admin to create the compute targets described in this section, if they do not already exist.\n",
|
|
||||||
"\n",
|
|
||||||
"**Creation of AmlCompute takes approximately 5 minutes.** If the AmlCompute with that name is already in your workspace, this code will skip the creation process.\n",
|
"**Creation of AmlCompute takes approximately 5 minutes.** If the AmlCompute with that name is already in your workspace, this code will skip the creation process.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
||||||
|
|||||||
@@ -222,8 +222,6 @@
|
|||||||
"### Create or attach existing AmlCompute\n",
|
"### Create or attach existing AmlCompute\n",
|
||||||
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for training your model. In this tutorial, you create `AmlCompute` as your training compute resource.\n",
|
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for training your model. In this tutorial, you create `AmlCompute` as your training compute resource.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"> Note that if you have an AzureML Data Scientist role, you will not have permission to create compute resources. Talk to your workspace or IT admin to create the compute targets described in this section, if they do not already exist.\n",
|
|
||||||
"\n",
|
|
||||||
"**Creation of AmlCompute takes approximately 5 minutes.** If the AmlCompute with that name is already in your workspace this code will skip the creation process.\n",
|
"**Creation of AmlCompute takes approximately 5 minutes.** If the AmlCompute with that name is already in your workspace this code will skip the creation process.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
||||||
|
|||||||
@@ -272,9 +272,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Create or Attach existing AmlCompute\n",
|
"## Create or Attach existing AmlCompute\n",
|
||||||
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for training your model. In this tutorial, you create `AmlCompute` as your training compute resource.\n",
|
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for training your model. 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."
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -99,8 +99,6 @@
|
|||||||
"## Create or attach existing AmlCompute\n",
|
"## Create or attach existing AmlCompute\n",
|
||||||
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for training your model. In this tutorial, we use Azure ML managed compute ([AmlCompute](https://docs.microsoft.com/azure/machine-learning/service/how-to-set-up-training-targets#amlcompute)) for our remote training compute resource. Specifically, the below code creates an `STANDARD_NC6` GPU cluster that autoscales from `0` to `4` nodes.\n",
|
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for training your model. In this tutorial, we use Azure ML managed compute ([AmlCompute](https://docs.microsoft.com/azure/machine-learning/service/how-to-set-up-training-targets#amlcompute)) for our remote training compute resource. Specifically, the below code creates an `STANDARD_NC6` GPU cluster that autoscales from `0` to `4` nodes.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"> Note that if you have an AzureML Data Scientist role, you will not have permission to create compute resources. Talk to your workspace or IT admin to create the compute targets described in this section, if they do not already exist.\n",
|
|
||||||
"\n",
|
|
||||||
"**Creation of AmlCompute takes approximately 5 minutes.** If the AmlCompute with that name is already in your workspace, this code will skip the creation process.\n",
|
"**Creation of AmlCompute takes approximately 5 minutes.** If the AmlCompute with that name is already in your workspace, this code will skip the creation process.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
||||||
|
|||||||
@@ -99,8 +99,6 @@
|
|||||||
"## Create or attach existing AmlCompute\n",
|
"## Create or attach existing AmlCompute\n",
|
||||||
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for training your model. In this tutorial, we use Azure ML managed compute ([AmlCompute](https://docs.microsoft.com/azure/machine-learning/service/how-to-set-up-training-targets#amlcompute)) for our remote training compute resource. Specifically, the below code creates an `STANDARD_NC6` GPU cluster that autoscales from `0` to `4` nodes.\n",
|
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for training your model. In this tutorial, we use Azure ML managed compute ([AmlCompute](https://docs.microsoft.com/azure/machine-learning/service/how-to-set-up-training-targets#amlcompute)) for our remote training compute resource. Specifically, the below code creates an `STANDARD_NC6` GPU cluster that autoscales from `0` to `4` nodes.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"> Note that if you have an AzureML Data Scientist role, you will not have permission to create compute resources. Talk to your workspace or IT admin to create the compute targets described in this section, if they do not already exist.\n",
|
|
||||||
"\n",
|
|
||||||
"**Creation of AmlCompute takes approximately 5 minutes.** If the AmlCompute with that name is already in your workspace, this code will skip the creation process.\n",
|
"**Creation of AmlCompute takes approximately 5 minutes.** If the AmlCompute with that name is already in your workspace, this code will skip the creation process.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
||||||
|
|||||||
@@ -100,8 +100,6 @@
|
|||||||
"## Create or Attach existing AmlCompute\n",
|
"## Create or Attach existing AmlCompute\n",
|
||||||
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for training your model. In this tutorial, we use Azure ML managed compute ([AmlCompute](https://docs.microsoft.com/azure/machine-learning/service/how-to-set-up-training-targets#amlcompute)) for our remote training compute resource.\n",
|
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for training your model. In this tutorial, we use Azure ML managed compute ([AmlCompute](https://docs.microsoft.com/azure/machine-learning/service/how-to-set-up-training-targets#amlcompute)) for our remote training compute resource.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"> Note that if you have an AzureML Data Scientist role, you will not have permission to create compute resources. Talk to your workspace or IT admin to create the compute targets described in this section, if they do not already exist.\n",
|
|
||||||
"\n",
|
|
||||||
"**Creation of AmlCompute takes approximately 5 minutes.** If the AmlCompute with that name is already in your workspace, this code will skip the creation process.\n",
|
"**Creation of AmlCompute takes approximately 5 minutes.** If the AmlCompute with that name is already in your workspace, this code will skip the creation process.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
||||||
|
|||||||
@@ -117,8 +117,6 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for training your model. In this tutorial, we use Azure ML managed compute ([AmlCompute](https://docs.microsoft.com/azure/machine-learning/service/how-to-set-up-training-targets#amlcompute)) for our remote training compute resource.\n",
|
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for training your model. In this tutorial, we use Azure ML managed compute ([AmlCompute](https://docs.microsoft.com/azure/machine-learning/service/how-to-set-up-training-targets#amlcompute)) for our remote training compute resource.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"> Note that if you have an AzureML Data Scientist role, you will not have permission to create compute resources. Talk to your workspace or IT admin to create the compute targets described in this section, if they do not already exist.\n",
|
|
||||||
"\n",
|
|
||||||
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -101,8 +101,6 @@
|
|||||||
"## Create or Attach existing AmlCompute\n",
|
"## Create or Attach existing AmlCompute\n",
|
||||||
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for training your model. In this tutorial, you create `AmlCompute` as your training compute resource.\n",
|
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for training your model. In this tutorial, you create `AmlCompute` as your training compute resource.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"> Note that if you have an AzureML Data Scientist role, you will not have permission to create compute resources. Talk to your workspace or IT admin to create the compute targets described in this section, if they do not already exist.\n",
|
|
||||||
"\n",
|
|
||||||
"**Creation of AmlCompute takes approximately 5 minutes.** If the AmlCompute with that name is already in your workspace this code will skip the creation process.\n",
|
"**Creation of AmlCompute takes approximately 5 minutes.** If the AmlCompute with that name is already in your workspace this code will skip the creation process.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
||||||
|
|||||||
@@ -101,8 +101,6 @@
|
|||||||
"## Create or Attach existing AmlCompute\n",
|
"## Create or Attach existing AmlCompute\n",
|
||||||
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for training your model. In this tutorial, you create `AmlCompute` as your training compute resource.\n",
|
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for training your model. In this tutorial, you create `AmlCompute` as your training compute resource.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"> Note that if you have an AzureML Data Scientist role, you will not have permission to create compute resources. Talk to your workspace or IT admin to create the compute targets described in this section, if they do not already exist.\n",
|
|
||||||
"\n",
|
|
||||||
"**Creation of AmlCompute takes approximately 5 minutes.** If the AmlCompute with that name is already in your workspace this code will skip the creation process.\n",
|
"**Creation of AmlCompute takes approximately 5 minutes.** If the AmlCompute with that name is already in your workspace this code will skip the creation process.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
||||||
|
|||||||
@@ -270,9 +270,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Create or Attach existing AmlCompute\n",
|
"## Create or Attach existing AmlCompute\n",
|
||||||
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for training your model. In this tutorial, you create `AmlCompute` as your training compute resource.\n",
|
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for training your model. 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."
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -286,9 +286,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Create or Attach existing AmlCompute\n",
|
"## Create or Attach existing AmlCompute\n",
|
||||||
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for training your model. In this tutorial, you create `AmlCompute` as your training compute resource.\n",
|
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for training your model. 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."
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -101,8 +101,6 @@
|
|||||||
"## Create or Attach existing AmlCompute\n",
|
"## Create or Attach existing AmlCompute\n",
|
||||||
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for training your model. In this tutorial, you create `AmlCompute` as your training compute resource.\n",
|
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for training your model. In this tutorial, you create `AmlCompute` as your training compute resource.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"> Note that if you have an AzureML Data Scientist role, you will not have permission to create compute resources. Talk to your workspace or IT admin to create the compute targets described in this section, if they do not already exist.\n",
|
|
||||||
"\n",
|
|
||||||
"**Creation of AmlCompute takes approximately 5 minutes.** If the AmlCompute with that name is already in your workspace this code will skip the creation process.\n",
|
"**Creation of AmlCompute takes approximately 5 minutes.** If the AmlCompute with that name is already in your workspace this code will skip the creation process.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
||||||
|
|||||||
@@ -250,7 +250,7 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"### Deploy model as web service\n",
|
"### Deploy model as web service\n",
|
||||||
"\n",
|
"\n",
|
||||||
"The ```client.create_deployment``` function registers the logged Keras+Tensorflow model and deploys the model in a framework-aware manner. It automatically creates the Tensorflow-specific inferencing wrapper code and specifies package dependencies for you. See [this doc](https://mlflow.org/docs/latest/models.html#id34) for more information on deploying models on Azure ML using MLflow.\n",
|
"The ```mlflow.azureml.deploy``` function registers the logged Keras+Tensorflow model and deploys the model in a framework-aware manner. It automatically creates the Tensorflow-specific inferencing wrapper code and specifies package dependencies for you. See [this doc](https://mlflow.org/docs/latest/models.html#id34) for more information on deploying models on Azure ML using MLflow.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"In this example, we deploy the Docker image to Azure Container Instance: a serverless compute capable of running a single container. You can tag and add descriptions to help keep track of your web service. \n",
|
"In this example, we deploy the Docker image to Azure Container Instance: a serverless compute capable of running a single container. You can tag and add descriptions to help keep track of your web service. \n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -259,63 +259,131 @@
|
|||||||
"Note that the service deployment can take several minutes."
|
"Note that the service deployment can take several minutes."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"source": [
|
|
||||||
"First define your deployment target and customize parameters in the deployment config. Refer to [this documentation](https://docs.microsoft.com/azure/machine-learning/reference-azure-machine-learning-cli#azure-container-instance-deployment-configuration-schema) for more information. "
|
|
||||||
],
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {}
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"import json\n",
|
"from azureml.core.webservice import AciWebservice, Webservice\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# Data to be written\n",
|
|
||||||
"deploy_config ={\n",
|
|
||||||
" \"computeType\": \"aci\"\n",
|
|
||||||
"}\n",
|
|
||||||
"# Serializing json \n",
|
|
||||||
"json_object = json.dumps(deploy_config)\n",
|
|
||||||
" \n",
|
|
||||||
"# Writing to sample.json\n",
|
|
||||||
"with open(\"deployment_config.json\", \"w\") as outfile:\n",
|
|
||||||
" outfile.write(json_object)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from mlflow.deployments import get_deploy_client\n",
|
|
||||||
"\n",
|
|
||||||
"# set the tracking uri as the deployment client\n",
|
|
||||||
"client = get_deploy_client(mlflow.get_tracking_uri())\n",
|
|
||||||
"\n",
|
|
||||||
"# set the model path \n",
|
|
||||||
"model_path = \"model\"\n",
|
"model_path = \"model\"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# set the deployment config\n",
|
"aci_config = AciWebservice.deploy_configuration(cpu_cores=2, \n",
|
||||||
"deployment_config_path = \"deployment_config.json\"\n",
|
" memory_gb=5, \n",
|
||||||
"test_config = {'deploy-config-file': deployment_config_path}\n",
|
" tags={\"data\": \"MNIST\", \"method\" : \"keras\"}, \n",
|
||||||
|
" description=\"Predict using webservice\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# define the model path and the name is the service name\n",
|
"webservice, azure_model = mlflow.azureml.deploy(model_uri='runs:/{}/{}'.format(run.id, model_path),\n",
|
||||||
"# the model gets registered automatically and a name is autogenerated using the \"name\" parameter below \n",
|
" workspace=ws,\n",
|
||||||
"client.create_deployment(model_uri='runs:/{}/{}'.format(run.id, model_path),\n",
|
" deployment_config=aci_config,\n",
|
||||||
" config=test_config,\n",
|
" service_name=\"keras-mnist-1\",\n",
|
||||||
" name=\"keras-aci-deployment\")"
|
" model_name=\"keras_mnist\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"Once the deployment has completed you can check the scoring URI of the web service in AzureML studio UI in the endpoints tab. Refer [mlflow predict](https://mlflow.org/docs/latest/python_api/mlflow.deployments.html#mlflow.deployments.BaseDeploymentClient.predict) on how to test your deployment. "
|
"Once the deployment has completed you can check the scoring URI of the web service."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"print(\"Scoring URI is: {}\".format(webservice.scoring_uri))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"In case of a service creation issue, you can use ```webservice.get_logs()``` to get logs to debug."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Make predictions using a web service\n",
|
||||||
|
"\n",
|
||||||
|
"To make the web service, create a test data set as normalized NumPy array. \n",
|
||||||
|
"\n",
|
||||||
|
"Then, let's define a utility function that takes a random image and converts it into a format and shape suitable for input to the Keras inferencing end-point. The conversion is done by: \n",
|
||||||
|
"\n",
|
||||||
|
" 1. Select a random (image, label) tuple\n",
|
||||||
|
" 2. Take the image and converting to to NumPy array \n",
|
||||||
|
" 3. Reshape array into 1 x 1 x N array\n",
|
||||||
|
" * 1 image in batch, 1 color channel, N = 784 pixels for MNIST images\n",
|
||||||
|
" * Note also ```x = x.view(-1, 1, 28, 28)``` in net definition in ```train.py``` program to shape incoming scoring requests.\n",
|
||||||
|
" 4. Convert the NumPy array to list to make it into a built-in type.\n",
|
||||||
|
" 5. Create a dictionary {\"data\", <list>} that can be converted to JSON string for web service requests."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"import keras\n",
|
||||||
|
"import random\n",
|
||||||
|
"import numpy as np\n",
|
||||||
|
"\n",
|
||||||
|
"# the data, split between train and test sets\n",
|
||||||
|
"(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()\n",
|
||||||
|
"\n",
|
||||||
|
"# Scale images to the [0, 1] range\n",
|
||||||
|
"x_test = x_test.astype(\"float32\") / 255\n",
|
||||||
|
"x_test = x_test.reshape(len(x_test), -1)\n",
|
||||||
|
"\n",
|
||||||
|
"# convert class vectors to binary class matrices\n",
|
||||||
|
"y_test = keras.utils.to_categorical(y_test, 10)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"%matplotlib inline\n",
|
||||||
|
"\n",
|
||||||
|
"import json\n",
|
||||||
|
"import matplotlib.pyplot as plt\n",
|
||||||
|
"\n",
|
||||||
|
"# send a random row from the test set to score\n",
|
||||||
|
"random_index = np.random.randint(0, len(x_test)-1)\n",
|
||||||
|
"input_data = \"{\\\"data\\\": [\" + str(list(x_test[random_index])) + \"]}\"\n",
|
||||||
|
"\n",
|
||||||
|
"response = webservice.run(input_data)\n",
|
||||||
|
"\n",
|
||||||
|
"response = sorted(response[0].items(), key = lambda x: x[1], reverse = True)\n",
|
||||||
|
"\n",
|
||||||
|
"print(\"Predicted label:\", response[0][0])\n",
|
||||||
|
"plt.imshow(x_test[random_index].reshape(28,28), cmap = \"gray\")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"You can also call the web service using a raw POST method against the web service"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"import requests\n",
|
||||||
|
"\n",
|
||||||
|
"response = requests.post(url=webservice.scoring_uri, data=input_data,headers={\"Content-type\": \"application/json\"})\n",
|
||||||
|
"print(response.text)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -332,7 +400,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"client.delete(\"keras-aci-deployment\")"
|
"webservice.delete()"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -249,7 +249,7 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"## Deploy model as web service\n",
|
"## Deploy model as web service\n",
|
||||||
"\n",
|
"\n",
|
||||||
"The ```client.create_deployment``` function registers the logged PyTorch model and deploys the model in a framework-aware manner. It automatically creates the PyTorch-specific inferencing wrapper code and specifies package dependencies for you. See [this doc](https://mlflow.org/docs/latest/models.html#id34) for more information on deploying models on Azure ML using MLflow.\n",
|
"The ```mlflow.azureml.deploy``` function registers the logged PyTorch model and deploys the model in a framework-aware manner. It automatically creates the PyTorch-specific inferencing wrapper code and specifies package dependencies for you. See [this doc](https://mlflow.org/docs/latest/models.html#id34) for more information on deploying models on Azure ML using MLflow.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"In this example, we deploy the Docker image to Azure Container Instance: a serverless compute capable of running a single container. You can tag and add descriptions to help keep track of your web service. \n",
|
"In this example, we deploy the Docker image to Azure Container Instance: a serverless compute capable of running a single container. You can tag and add descriptions to help keep track of your web service. \n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -258,63 +258,33 @@
|
|||||||
"Note that the service deployment can take several minutes."
|
"Note that the service deployment can take several minutes."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"source": [
|
|
||||||
"First define your deployment target and customize parameters in the deployment config. Refer to [this documentation](https://docs.microsoft.com/azure/machine-learning/reference-azure-machine-learning-cli#azure-container-instance-deployment-configuration-schema) for more information. "
|
|
||||||
],
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {}
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"import json\n",
|
"from azureml.core.webservice import AciWebservice, Webservice\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# Data to be written\n",
|
|
||||||
"deploy_config ={\n",
|
|
||||||
" \"computeType\": \"aci\"\n",
|
|
||||||
"}\n",
|
|
||||||
"# Serializing json \n",
|
|
||||||
"json_object = json.dumps(deploy_config)\n",
|
|
||||||
" \n",
|
|
||||||
"# Writing to sample.json\n",
|
|
||||||
"with open(\"deployment_config.json\", \"w\") as outfile:\n",
|
|
||||||
" outfile.write(json_object)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from mlflow.deployments import get_deploy_client\n",
|
|
||||||
"\n",
|
|
||||||
"# set the tracking uri as the deployment client\n",
|
|
||||||
"client = get_deploy_client(mlflow.get_tracking_uri())\n",
|
|
||||||
"\n",
|
|
||||||
"# set the model path \n",
|
|
||||||
"model_path = \"model\"\n",
|
"model_path = \"model\"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# set the deployment config\n",
|
"aci_config = AciWebservice.deploy_configuration(cpu_cores=2, \n",
|
||||||
"deployment_config_path = \"deployment_config.json\"\n",
|
" memory_gb=5, \n",
|
||||||
"test_config = {'deploy-config-file': deployment_config_path}\n",
|
" tags={\"data\": \"MNIST\", \"method\" : \"pytorch\"}, \n",
|
||||||
|
" description=\"Predict using webservice\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# define the model path and the name is the service name\n",
|
"webservice, azure_model = mlflow.azureml.deploy(model_uri='runs:/{}/{}'.format(run.id, model_path),\n",
|
||||||
"# the model gets registered automatically and a name is autogenerated using the \"name\" parameter below \n",
|
" workspace=ws,\n",
|
||||||
"client.create_deployment(model_uri='runs:/{}/{}'.format(run.id, model_path),\n",
|
" deployment_config=aci_config,\n",
|
||||||
" config=test_config,\n",
|
" service_name=\"pytorch-mnist-1\",\n",
|
||||||
" name=\"keras-aci-deployment\")"
|
" model_name=\"pytorch_mnist\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"Once the deployment has completed you can check the scoring URI of the web service in AzureML studio UI in the endpoints tab. Refer [mlflow predict](https://mlflow.org/docs/latest/python_api/mlflow.deployments.html#mlflow.deployments.BaseDeploymentClient.predict) on how to test your deployment. "
|
"Once the deployment has completed you can check the scoring URI of the web service."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -323,7 +293,133 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"client.delete(\"keras-aci-deployment\")"
|
"print(\"Scoring URI is: {}\".format(webservice.scoring_uri))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"In case of a service creation issue, you can use ```webservice.get_logs()``` to get logs to debug."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Make predictions using a web service\n",
|
||||||
|
"\n",
|
||||||
|
"To make the web service, create a test data set as normalized PyTorch tensors. \n",
|
||||||
|
"\n",
|
||||||
|
"Then, let's define a utility function that takes a random image and converts it into a format and shape suitable for input to the PyTorch inferencing end-point. The conversion is done by: \n",
|
||||||
|
"\n",
|
||||||
|
" 1. Select a random (image, label) tuple\n",
|
||||||
|
" 2. Take the image and converting the tensor to NumPy array \n",
|
||||||
|
" 3. Reshape array into 1 x 1 x N array\n",
|
||||||
|
" * 1 image in batch, 1 color channel, N = 784 pixels for MNIST images\n",
|
||||||
|
" * Note also ```x = x.view(-1, 1, 28, 28)``` in net definition in ```train.py``` program to shape incoming scoring requests.\n",
|
||||||
|
" 4. Convert the NumPy array to list to make it into a built-in type.\n",
|
||||||
|
" 5. Create a dictionary {\"data\", <list>} that can be converted to JSON string for web service requests."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from torchvision import datasets, transforms\n",
|
||||||
|
"import random\n",
|
||||||
|
"import numpy as np\n",
|
||||||
|
"\n",
|
||||||
|
"# Use Azure Open Datasets for MNIST dataset\n",
|
||||||
|
"datasets.MNIST.resources = [\n",
|
||||||
|
" (\"https://azureopendatastorage.azurefd.net/mnist/train-images-idx3-ubyte.gz\",\n",
|
||||||
|
" \"f68b3c2dcbeaaa9fbdd348bbdeb94873\"),\n",
|
||||||
|
" (\"https://azureopendatastorage.azurefd.net/mnist/train-labels-idx1-ubyte.gz\",\n",
|
||||||
|
" \"d53e105ee54ea40749a09fcbcd1e9432\"),\n",
|
||||||
|
" (\"https://azureopendatastorage.azurefd.net/mnist/t10k-images-idx3-ubyte.gz\",\n",
|
||||||
|
" \"9fb629c4189551a2d022fa330f9573f3\"),\n",
|
||||||
|
" (\"https://azureopendatastorage.azurefd.net/mnist/t10k-labels-idx1-ubyte.gz\",\n",
|
||||||
|
" \"ec29112dd5afa0611ce80d1b7f02629c\")\n",
|
||||||
|
"]\n",
|
||||||
|
"\n",
|
||||||
|
"test_data = datasets.MNIST('../data', train=False, transform=transforms.Compose([\n",
|
||||||
|
" transforms.ToTensor(),\n",
|
||||||
|
" transforms.Normalize((0.1307,), (0.3081,))]))\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"def get_random_image():\n",
|
||||||
|
" image_idx = random.randint(0,len(test_data))\n",
|
||||||
|
" image_as_tensor = test_data[image_idx][0]\n",
|
||||||
|
" return {\"data\": elem for elem in image_as_tensor.numpy().reshape(1,1,-1).tolist()}"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Then, invoke the web service using a random test image. Convert the dictionary containing the image to JSON string before passing it to web service.\n",
|
||||||
|
"\n",
|
||||||
|
"The response contains the raw scores for each label, with greater value indicating higher probability. Sort the labels and select the one with greatest score to get the prediction. Let's also plot the image sent to web service for comparison purposes."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"%matplotlib inline\n",
|
||||||
|
"\n",
|
||||||
|
"import json\n",
|
||||||
|
"import matplotlib.pyplot as plt\n",
|
||||||
|
"\n",
|
||||||
|
"test_image = get_random_image()\n",
|
||||||
|
"\n",
|
||||||
|
"response = webservice.run(json.dumps(test_image))\n",
|
||||||
|
"\n",
|
||||||
|
"response = sorted(response[0].items(), key = lambda x: x[1], reverse = True)\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"print(\"Predicted label:\", response[0][0])\n",
|
||||||
|
"plt.imshow(np.array(test_image[\"data\"]).reshape(28,28), cmap = \"gray\")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"You can also call the web service using a raw POST method against the web service"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"import requests\n",
|
||||||
|
"\n",
|
||||||
|
"response = requests.post(url=webservice.scoring_uri, data=json.dumps(test_image),headers={\"Content-type\": \"application/json\"})\n",
|
||||||
|
"print(response.text)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Clean up\n",
|
||||||
|
"You can delete the ACI deployment with a delete API call."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"webservice.delete()"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -141,20 +141,13 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"### Create Virtual Network and Network Security Group\n",
|
"### Create Virtual Network\n",
|
||||||
"\n",
|
"\n",
|
||||||
"**If you are using separate compute targets for the Ray head and worker, as we do in this notebook**, a virtual network must be created in the resource group. If you have already created a virtual network in the resource group, you can skip this step.\n",
|
"If you are using separate compute targets for the Ray head and worker, a virtual network must be created in the resource group. If you have alraeady created a virtual network in the resource group, you can skip this step.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"> Note that your user role must have permissions to create and manage virtual networks to run the cells below. Talk to your IT admin if you do not have these permissions.\n",
|
"To do this, you first must install the Azure Networking API.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"#### Create Virtual Network\n",
|
"`pip install --upgrade azure-mgmt-network==12.0.0`"
|
||||||
"To create the virtual network you first must install the [Azure Networking Python API](https://docs.microsoft.com/python/api/overview/azure/network?view=azure-python).\n",
|
|
||||||
"\n",
|
|
||||||
"`pip install --upgrade azure-mgmt-network`\n",
|
|
||||||
"\n",
|
|
||||||
"Note: In this section we are using [DefaultAzureCredential](https://docs.microsoft.com/python/api/azure-identity/azure.identity.defaultazurecredential?view=azure-python)\n",
|
|
||||||
"class for authentication which, by default, examines several options in turn, and stops on the first option that provides\n",
|
|
||||||
"a token. You will need to log in using Azure CLI, if none of the other options are available (please find more details [here](https://docs.microsoft.com/python/api/azure-identity/azure.identity.defaultazurecredential?view=azure-python))."
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -164,7 +157,7 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"# If you need to install the Azure Networking SDK, uncomment the following line.\n",
|
"# If you need to install the Azure Networking SDK, uncomment the following line.\n",
|
||||||
"#!pip install --upgrade azure-mgmt-network"
|
"#!pip install --upgrade azure-mgmt-network==12.0.0"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -174,7 +167,6 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from azure.mgmt.network import NetworkManagementClient\n",
|
"from azure.mgmt.network import NetworkManagementClient\n",
|
||||||
"from azure.identity import DefaultAzureCredential\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
"# Virtual network name\n",
|
"# Virtual network name\n",
|
||||||
"vnet_name =\"rl_pong_vnet\"\n",
|
"vnet_name =\"rl_pong_vnet\"\n",
|
||||||
@@ -191,9 +183,9 @@
|
|||||||
"# Azure region of the resource group\n",
|
"# Azure region of the resource group\n",
|
||||||
"location=ws.location\n",
|
"location=ws.location\n",
|
||||||
"\n",
|
"\n",
|
||||||
"network_client = NetworkManagementClient(credential=DefaultAzureCredential(), subscription_id=subscription_id)\n",
|
"network_client = NetworkManagementClient(ws._auth_object, subscription_id)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"async_vnet_creation = network_client.virtual_networks.begin_create_or_update(\n",
|
"async_vnet_creation = network_client.virtual_networks.create_or_update(\n",
|
||||||
" resource_group,\n",
|
" resource_group,\n",
|
||||||
" vnet_name,\n",
|
" vnet_name,\n",
|
||||||
" {\n",
|
" {\n",
|
||||||
@@ -212,9 +204,9 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"#### Set up Network Security Group on Virtual Network\n",
|
"### Set up Network Security Group on Virtual Network\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Depending on your Azure setup, you may need to open certain ports to make it possible for Azure to manage the compute targets that you create. The ports that need to be opened are described [here](https://docs.microsoft.com/azure/machine-learning/how-to-enable-virtual-network).\n",
|
"Depending on your Azure setup, you may need to open certain ports to make it possible for Azure to manage the compute targets that you create. The ports that need to be opened are described [here](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-enable-virtual-network).\n",
|
||||||
"\n",
|
"\n",
|
||||||
"A common situation is that ports `29876-29877` are closed. The following code will add a security rule to open these ports. Or you can do this manually in the [Azure portal](https://portal.azure.com).\n",
|
"A common situation is that ports `29876-29877` are closed. The following code will add a security rule to open these ports. Or you can do this manually in the [Azure portal](https://portal.azure.com).\n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -251,7 +243,7 @@
|
|||||||
" ],\n",
|
" ],\n",
|
||||||
")\n",
|
")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"async_nsg_creation = network_client.network_security_groups.begin_create_or_update(\n",
|
"async_nsg_creation = network_client.network_security_groups.create_or_update(\n",
|
||||||
" resource_group,\n",
|
" resource_group,\n",
|
||||||
" security_group_name,\n",
|
" security_group_name,\n",
|
||||||
" nsg_params,\n",
|
" nsg_params,\n",
|
||||||
@@ -273,7 +265,7 @@
|
|||||||
" )\n",
|
" )\n",
|
||||||
" \n",
|
" \n",
|
||||||
"# Create subnet on virtual network\n",
|
"# Create subnet on virtual network\n",
|
||||||
"async_subnet_creation = network_client.subnets.begin_create_or_update(\n",
|
"async_subnet_creation = network_client.subnets.create_or_update(\n",
|
||||||
" resource_group_name=resource_group,\n",
|
" resource_group_name=resource_group,\n",
|
||||||
" virtual_network_name=vnet_name,\n",
|
" virtual_network_name=vnet_name,\n",
|
||||||
" subnet_name=subnet_name,\n",
|
" subnet_name=subnet_name,\n",
|
||||||
@@ -288,7 +280,7 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"#### Review the virtual network security rules\n",
|
"### Review the virtual network security rules\n",
|
||||||
"Ensure that the virtual network is configured correctly with required ports open. It is possible that you have configured rules with broader range of ports that allows ports 29876-29877 to be opened. Kindly review your network security group rules. "
|
"Ensure that the virtual network is configured correctly with required ports open. It is possible that you have configured rules with broader range of ports that allows ports 29876-29877 to be opened. Kindly review your network security group rules. "
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -299,24 +291,17 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from files.networkutils import *\n",
|
"from files.networkutils import *\n",
|
||||||
"from azure.identity import DefaultAzureCredential\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
"check_vnet_security_rules(DefaultAzureCredential(), ws.subscription_id, ws.resource_group, vnet_name, True)"
|
"check_vnet_security_rules(ws._auth_object, ws.subscription_id, ws.resource_group, vnet_name, True)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"### Create compute targets\n",
|
"### Create head compute target\n",
|
||||||
"\n",
|
"\n",
|
||||||
"In this example, we show how to set up separate compute targets for the Ray head and Ray worker nodes.\n",
|
"In this example, we show how to set up separate compute targets for the Ray head and Ray worker nodes. First we define the head cluster with GPU for the Ray head node. One CPU of the head node will be used for the Ray head process and the rest of the CPUs will be used by the Ray worker processes."
|
||||||
"\n",
|
|
||||||
"> Note that if you have an AzureML Data Scientist role, you will not have permission to create compute resources. Talk to your workspace or IT admin to create the compute targets described in this section, if they do not already exist.\n",
|
|
||||||
"\n",
|
|
||||||
"#### Create head compute target\n",
|
|
||||||
"\n",
|
|
||||||
"First we define the head cluster with GPU for the Ray head node. One CPU of the head node will be used for the Ray head process and the rest of the CPUs will be used by the Ray worker processes."
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -368,7 +353,7 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"#### Create worker compute target\n",
|
"### Create worker compute target\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Now we create a compute target with CPUs for the additional Ray worker nodes. CPUs in these worker nodes are used by Ray worker processes. Each Ray worker node, depending on the CPUs on the node, may have multiple Ray worker processes. There can be multiple worker tasks on each worker process (core)."
|
"Now we create a compute target with CPUs for the additional Ray worker nodes. CPUs in these worker nodes are used by Ray worker processes. Each Ray worker node, depending on the CPUs on the node, may have multiple Ray worker processes. There can be multiple worker tasks on each worker process (core)."
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -5,5 +5,4 @@ dependencies:
|
|||||||
- azureml-contrib-reinforcementlearning
|
- azureml-contrib-reinforcementlearning
|
||||||
- azureml-widgets
|
- azureml-widgets
|
||||||
- matplotlib
|
- matplotlib
|
||||||
- azure-mgmt-network
|
- azure-mgmt-network==12.0.0
|
||||||
- azure-cli
|
|
||||||
|
|||||||
@@ -451,8 +451,9 @@
|
|||||||
"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.\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/<run_id>** directory.\n",
|
||||||
"We can use the Run API to download policy training artifacts (saved model and checkpoints) to local compute."
|
"\n",
|
||||||
|
"Here we create a file dataset from the stored artifacts, and then use this dataset to feed these data to rollout estimator."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -461,90 +462,22 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from os import path\n",
|
|
||||||
"from distutils import dir_util\n",
|
|
||||||
"\n",
|
|
||||||
"training_artifacts_path = path.join(\"logs\", training_algorithm)\n",
|
|
||||||
"print(\"Training artifacts path:\", training_artifacts_path)\n",
|
|
||||||
"\n",
|
|
||||||
"if path.exists(training_artifacts_path):\n",
|
|
||||||
" dir_util.remove_tree(training_artifacts_path)\n",
|
|
||||||
"\n",
|
|
||||||
"# Download run artifacts to local compute\n",
|
|
||||||
"child_run_0.download_files(training_artifacts_path)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Now let's find the checkpoints and the last checkpoint number."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# 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",
|
"from azureml.core import Dataset\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",
|
||||||
|
"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",
|
"datastore = ws.get_default_datastore()\n",
|
||||||
"checkpoint_dataref = datastore.upload_files(checkpoint_files, target_path='cartpole_checkpoints_' + run_id, overwrite=True)\n",
|
"training_artifacts_ds = Dataset.File.from_files(datastore.path(os.path.join(run_artifacts_path, '**')))"
|
||||||
"checkpoint_ds = Dataset.File.from_files(checkpoint_dataref)"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"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."
|
"To verify, we can print out the number (and paths) of all the files in the dataset, as follows."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -553,7 +486,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"artifacts_paths = checkpoint_ds.to_path()\n",
|
"artifacts_paths = training_artifacts_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",
|
||||||
@@ -572,6 +505,36 @@
|
|||||||
"\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."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -613,8 +576,8 @@
|
|||||||
" \n",
|
" \n",
|
||||||
" # Data inputs\n",
|
" # Data inputs\n",
|
||||||
" inputs=[\n",
|
" inputs=[\n",
|
||||||
" checkpoint_ds.as_named_input('artifacts_dataset'),\n",
|
" training_artifacts_ds.as_named_input('artifacts_dataset'),\n",
|
||||||
" checkpoint_ds.as_named_input('artifacts_path').as_mount()],\n",
|
" training_artifacts_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",
|
||||||
|
|||||||
@@ -118,8 +118,6 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"A compute target is a designated compute resource where you run your training and simulation scripts. This location may be your local machine or a cloud-based compute resource. The code below shows how to create a cloud-based compute target. For more information see [What are compute targets in Azure Machine Learning?](https://docs.microsoft.com/en-us/azure/machine-learning/concept-compute-target)\n",
|
"A compute target is a designated compute resource where you run your training and simulation scripts. This location may be your local machine or a cloud-based compute resource. The code below shows how to create a cloud-based compute target. For more information see [What are compute targets in Azure Machine Learning?](https://docs.microsoft.com/en-us/azure/machine-learning/concept-compute-target)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"> Note that if you have an AzureML Data Scientist role, you will not have permission to create compute resources. Talk to your workspace or IT admin to create the compute targets described in this section, if they do not already exist.\n",
|
|
||||||
"\n",
|
|
||||||
"**Note: Creation of a compute resource can take several minutes**. Please make sure to change `STANDARD_D2_V2` to a [size available in your region](https://azure.microsoft.com/en-us/global-infrastructure/services/?products=virtual-machines)."
|
"**Note: Creation of a compute resource can take several minutes**. Please make sure to change `STANDARD_D2_V2` to a [size available in your region](https://azure.microsoft.com/en-us/global-infrastructure/services/?products=virtual-machines)."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -474,14 +472,61 @@
|
|||||||
"from os import path\n",
|
"from os import path\n",
|
||||||
"from distutils import dir_util\n",
|
"from distutils import dir_util\n",
|
||||||
"\n",
|
"\n",
|
||||||
"training_artifacts_path = path.join(\"logs\", training_algorithm)\n",
|
"path_prefix = path.join(\"logs\", training_algorithm)\n",
|
||||||
"print(\"Training artifacts path:\", training_artifacts_path)\n",
|
"print(\"Path prefix:\", path_prefix)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"if path.exists(training_artifacts_path):\n",
|
"if path.exists(path_prefix):\n",
|
||||||
" dir_util.remove_tree(training_artifacts_path)\n",
|
" dir_util.remove_tree(path_prefix)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# Download run artifacts to local compute\n",
|
"# Uncomment line below to download run artifacts to local compute\n",
|
||||||
"child_run_0.download_files(training_artifacts_path)"
|
"#child_run_0.download_files(path_prefix)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"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/<run_id>** 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)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -503,6 +548,21 @@
|
|||||||
"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",
|
||||||
@@ -528,6 +588,34 @@
|
|||||||
" )"
|
" )"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"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": {},
|
||||||
@@ -541,7 +629,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"mp4_files = find_movies(training_artifacts_path)\n",
|
"mp4_files = find_movies(training_movies_path)\n",
|
||||||
"mp4_files.sort()"
|
"mp4_files.sort()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -608,25 +696,6 @@
|
|||||||
"Let's find the checkpoints and the last checkpoint number first."
|
"Let's find the checkpoints and the last checkpoint number first."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# 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\n",
|
|
||||||
"\n",
|
|
||||||
"checkpoint_files = find_checkpoints(training_artifacts_path)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
@@ -634,11 +703,15 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"# Find checkpoints and last checkpoint number\n",
|
"# 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",
|
"checkpoint_numbers = []\n",
|
||||||
"for file in checkpoint_files:\n",
|
"for file in checkpoint_files:\n",
|
||||||
" file = os.path.basename(file)\n",
|
" checkpoint_numbers.append(int(file.split('-')[1]))\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",
|
||||||
@@ -646,20 +719,6 @@
|
|||||||
"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": {},
|
||||||
@@ -735,8 +794,8 @@
|
|||||||
" \n",
|
" \n",
|
||||||
" # Data inputs\n",
|
" # Data inputs\n",
|
||||||
" inputs=[\n",
|
" inputs=[\n",
|
||||||
" checkpoint_ds.as_named_input('artifacts_dataset'),\n",
|
" training_artifacts_ds.as_named_input('artifacts_dataset'),\n",
|
||||||
" checkpoint_ds.as_named_input('artifacts_path').as_mount()],\n",
|
" training_artifacts_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",
|
||||||
@@ -818,15 +877,16 @@
|
|||||||
"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",
|
||||||
"# Download rollout artifacts\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",
|
||||||
"rollout_artifacts_path = path.join(\"logs\", \"rollout\")\n",
|
"run_artifacts_path = os.path.join('azureml', run_id)\n",
|
||||||
"print(\"Rollout artifacts path:\", rollout_artifacts_path)\n",
|
"print(\"Run artifacts path:\", run_artifacts_path)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"if path.exists(rollout_artifacts_path):\n",
|
"# Create a file dataset object from the files stored on default datastore\n",
|
||||||
" dir_util.remove_tree(rollout_artifacts_path)\n",
|
"datastore = ws.get_default_datastore()\n",
|
||||||
|
"rollout_artifacts_ds = Dataset.File.from_files(datastore.path(os.path.join(run_artifacts_path, '**')))\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# Download videos to local compute\n",
|
"artifacts_paths = rollout_artifacts_ds.to_path()\n",
|
||||||
"child_run_0.download_files(\"logs/video\", output_directory = rollout_artifacts_path)"
|
"print(\"Number of files in dataset:\", len(artifacts_paths))"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -842,11 +902,20 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"# Look for the downloaded movie in local directory\n",
|
"# Find last movie\n",
|
||||||
"mp4_files = find_movies(rollout_artifacts_path)\n",
|
"mp4_files = [file for file in rollout_artifacts_ds.to_path() if file.endswith('.mp4')]\n",
|
||||||
"mp4_files.sort()\n",
|
"mp4_files.sort()\n",
|
||||||
|
"\n",
|
||||||
"last_movie = mp4_files[-1] if len(mp4_files) > 1 else None\n",
|
"last_movie = mp4_files[-1] if len(mp4_files) > 1 else None\n",
|
||||||
"print(\"Last movie:\", last_movie)"
|
"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",
|
||||||
|
"mp4_files = find_movies(rollout_movies_path)\n",
|
||||||
|
"mp4_files.sort()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -889,12 +958,16 @@
|
|||||||
"#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(training_artifacts_path):\n",
|
"#if os.path.exists(path_prefix):\n",
|
||||||
"# dir_util.remove_tree(training_artifacts_path)\n",
|
"# dir_util.remove_tree(path_prefix)\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_artifacts_path):\n",
|
"#if path.exists(rollout_movies_path):\n",
|
||||||
"# dir_util.remove_tree(rollout_artifacts_path)"
|
"# dir_util.remove_tree(rollout_movies_path)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -911,9 +984,6 @@
|
|||||||
"authors": [
|
"authors": [
|
||||||
{
|
{
|
||||||
"name": "hoazari"
|
"name": "hoazari"
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "dasommer"
|
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"kernelspec": {
|
"kernelspec": {
|
||||||
|
|||||||
@@ -138,8 +138,6 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"A compute target is a designated compute resource where you run your training script. For more information, see [What are compute targets in Azure Machine Learning service?](https://docs.microsoft.com/en-us/azure/machine-learning/concept-compute-target).\n",
|
"A compute target is a designated compute resource where you run your training script. For more information, see [What are compute targets in Azure Machine Learning service?](https://docs.microsoft.com/en-us/azure/machine-learning/concept-compute-target).\n",
|
||||||
"\n",
|
"\n",
|
||||||
"> Note that if you have an AzureML Data Scientist role, you will not have permission to create compute resources. Talk to your workspace or IT admin to create the compute targets described in this section, if they do not already exist.\n",
|
|
||||||
"\n",
|
|
||||||
"#### CPU target for Ray head\n",
|
"#### CPU target for Ray head\n",
|
||||||
"\n",
|
"\n",
|
||||||
"In the experiment setup for this tutorial, the Ray head node will\n",
|
"In the experiment setup for this tutorial, the Ray head node will\n",
|
||||||
|
|||||||
@@ -35,7 +35,7 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"## Install required packages\n",
|
"## Install required packages\n",
|
||||||
"\n",
|
"\n",
|
||||||
"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:"
|
"This notebook works with Fairlearn v0.4.6, and not later versions. If needed, please uncomment and run the following cell:"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -44,7 +44,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"# %pip install --upgrade fairlearn>=0.6.2"
|
"# %pip install --upgrade fairlearn==0.4.6"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -70,18 +70,24 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from fairlearn.reductions import GridSearch\n",
|
"from fairlearn.reductions import GridSearch\n",
|
||||||
"from fairlearn.reductions import DemographicParity\n",
|
"from fairlearn.reductions import DemographicParity, ErrorRate\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"from sklearn import svm, neighbors, tree\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, OneHotEncoder\n",
|
"from sklearn.preprocessing import LabelEncoder,StandardScaler\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",
|
||||||
|
"from sklearn.datasets import fetch_openml\n",
|
||||||
"\n",
|
"\n",
|
||||||
"import pandas as pd\n",
|
"import pandas as pd\n",
|
||||||
|
"import numpy as np\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"
|
||||||
]
|
]
|
||||||
@@ -99,9 +105,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from utilities import fetch_census_dataset\n",
|
"dataset = fetch_openml(data_id=1590, as_frame=True)\n",
|
||||||
"\n",
|
|
||||||
"dataset = fetch_census_dataset()\n",
|
|
||||||
"X_raw, y = dataset['data'], dataset['target']\n",
|
"X_raw, y = dataset['data'], dataset['target']\n",
|
||||||
"X_raw[\"race\"].value_counts().to_dict()"
|
"X_raw[\"race\"].value_counts().to_dict()"
|
||||||
]
|
]
|
||||||
@@ -337,11 +341,11 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from raiwidgets import FairnessDashboard\n",
|
"from fairlearn.widget import FairlearnDashboard\n",
|
||||||
"\n",
|
"\n",
|
||||||
"y_pred = model.predict(X_test)\n",
|
"y_pred = model.predict(X_test)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"FairnessDashboard(sensitive_features=sensitive_features_test,\n",
|
"FairlearnDashboard(sensitive_features=sensitive_features_test,\n",
|
||||||
" y_true=y_test,\n",
|
" y_true=y_test,\n",
|
||||||
" y_pred=y_pred)"
|
" y_pred=y_pred)"
|
||||||
]
|
]
|
||||||
@@ -399,7 +403,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"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -465,7 +469,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",
|
||||||
"FairnessDashboard(sensitive_features=sensitive_features_test, \n",
|
"FairlearnDashboard(sensitive_features=sensitive_features_test, \n",
|
||||||
" y_true=y_test,\n",
|
" y_true=y_test,\n",
|
||||||
" y_pred=dominant_all)"
|
" y_pred=dominant_all)"
|
||||||
]
|
]
|
||||||
@@ -560,7 +564,7 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"import joblib\n",
|
"import joblib\n",
|
||||||
"import os\n",
|
"import os\n",
|
||||||
"from azureml.core import Model, Experiment\n",
|
"from azureml.core import Model, Experiment, Run\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",
|
||||||
|
|||||||
@@ -4,9 +4,8 @@ dependencies:
|
|||||||
- azureml-sdk
|
- azureml-sdk
|
||||||
- azureml-interpret
|
- azureml-interpret
|
||||||
- azureml-contrib-fairness
|
- azureml-contrib-fairness
|
||||||
- fairlearn>=0.6.2
|
- fairlearn==0.4.6
|
||||||
- matplotlib
|
- matplotlib
|
||||||
- azureml-dataset-runtime
|
- azureml-dataset-runtime
|
||||||
- ipywidgets
|
- ipywidgets
|
||||||
- raiwidgets~=0.7.0
|
- raiwidgets
|
||||||
- liac-arff
|
|
||||||
|
|||||||
@@ -1,93 +0,0 @@
|
|||||||
# ---------------------------------------------------------
|
|
||||||
# Copyright (c) Microsoft Corporation. All rights reserved.
|
|
||||||
# ---------------------------------------------------------
|
|
||||||
|
|
||||||
"""Utilities for azureml-contrib-fairness notebooks."""
|
|
||||||
|
|
||||||
import arff
|
|
||||||
from collections import OrderedDict
|
|
||||||
from contextlib import closing
|
|
||||||
import gzip
|
|
||||||
import pandas as pd
|
|
||||||
from sklearn.utils import Bunch
|
|
||||||
from time import sleep
|
|
||||||
|
|
||||||
|
|
||||||
def _is_gzip_encoded(_fsrc):
|
|
||||||
return _fsrc.info().get('Content-Encoding', '') == 'gzip'
|
|
||||||
|
|
||||||
|
|
||||||
_categorical_columns = [
|
|
||||||
'workclass',
|
|
||||||
'education',
|
|
||||||
'marital-status',
|
|
||||||
'occupation',
|
|
||||||
'relationship',
|
|
||||||
'race',
|
|
||||||
'sex',
|
|
||||||
'native-country'
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
def fetch_census_dataset():
|
|
||||||
"""Fetch the Adult Census Dataset.
|
|
||||||
|
|
||||||
This uses a particular URL for the Adult Census dataset. The code
|
|
||||||
is a simplified version of fetch_openml() in sklearn.
|
|
||||||
|
|
||||||
The data are copied from:
|
|
||||||
https://openml.org/data/v1/download/1595261.gz
|
|
||||||
(as of 2021-03-31)
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
from urllib import urlretrieve
|
|
||||||
except ImportError:
|
|
||||||
from urllib.request import urlretrieve
|
|
||||||
|
|
||||||
filename = "1595261.gz"
|
|
||||||
data_url = "https://rainotebookscdn.blob.core.windows.net/datasets/"
|
|
||||||
|
|
||||||
remaining_attempts = 5
|
|
||||||
sleep_duration = 10
|
|
||||||
while remaining_attempts > 0:
|
|
||||||
try:
|
|
||||||
urlretrieve(data_url + filename, filename)
|
|
||||||
|
|
||||||
http_stream = gzip.GzipFile(filename=filename, mode='rb')
|
|
||||||
|
|
||||||
with closing(http_stream):
|
|
||||||
def _stream_generator(response):
|
|
||||||
for line in response:
|
|
||||||
yield line.decode('utf-8')
|
|
||||||
|
|
||||||
stream = _stream_generator(http_stream)
|
|
||||||
data = arff.load(stream)
|
|
||||||
except Exception as exc: # noqa: B902
|
|
||||||
remaining_attempts -= 1
|
|
||||||
print("Error downloading dataset from {} ({} attempt(s) remaining)"
|
|
||||||
.format(data_url, remaining_attempts))
|
|
||||||
print(exc)
|
|
||||||
sleep(sleep_duration)
|
|
||||||
sleep_duration *= 2
|
|
||||||
continue
|
|
||||||
else:
|
|
||||||
# dataset successfully downloaded
|
|
||||||
break
|
|
||||||
else:
|
|
||||||
raise Exception("Could not retrieve dataset from {}.".format(data_url))
|
|
||||||
|
|
||||||
attributes = OrderedDict(data['attributes'])
|
|
||||||
arff_columns = list(attributes)
|
|
||||||
raw_df = pd.DataFrame(data=data['data'], columns=arff_columns)
|
|
||||||
|
|
||||||
target_column_name = 'class'
|
|
||||||
target = raw_df.pop(target_column_name)
|
|
||||||
for col_name in _categorical_columns:
|
|
||||||
dtype = pd.api.types.CategoricalDtype(attributes[col_name])
|
|
||||||
raw_df[col_name] = raw_df[col_name].astype(dtype, copy=False)
|
|
||||||
|
|
||||||
result = Bunch()
|
|
||||||
result.data = raw_df
|
|
||||||
result.target = target
|
|
||||||
|
|
||||||
return result
|
|
||||||
@@ -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.32.0, you are currently running version\", azureml.core.VERSION)"
|
"print(\"This notebook was created using SDK version 1.26.0, you are currently running version\", azureml.core.VERSION)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -390,9 +390,7 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"## Once more, with an AmlCompute cluster\n",
|
"## Once more, with an AmlCompute cluster\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Just to prove we can, let's create an AmlCompute CPU cluster, and run our demo there, as well.\n",
|
"Just to prove we can, let's create an AmlCompute CPU cluster, and run our demo there, as well."
|
||||||
"\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."
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user