Compare commits

..

1 Commits

Author SHA1 Message Date
Vitaliy Zhurba
e792ba8278 MLN repo autocleanup 2019-07-12 10:27:43 -04:00
438 changed files with 162190 additions and 146431 deletions

View File

@@ -1,95 +1,95 @@
# Set up your notebook environment for Azure Machine Learning # Set up your notebook environment for Azure Machine Learning
To run the notebooks in this repository use one of following options. To run the notebooks in this repository use one of following options.
## **Option 1: Use Azure Notebooks** ## **Option 1: Use Azure Notebooks**
Azure Notebooks is a hosted Jupyter-based notebook service in the Azure cloud. Azure Machine Learning Python SDK is already pre-installed in the Azure Notebooks `Python 3.6` kernel. Azure Notebooks is a hosted Jupyter-based notebook service in the Azure cloud. Azure Machine Learning Python SDK is already pre-installed in the Azure Notebooks `Python 3.6` kernel.
1. [![Azure Notebooks](https://notebooks.azure.com/launch.png)](https://aka.ms/aml-clone-azure-notebooks) 1. [![Azure Notebooks](https://notebooks.azure.com/launch.png)](https://aka.ms/aml-clone-azure-notebooks)
[Import sample notebooks ](https://aka.ms/aml-clone-azure-notebooks) into Azure Notebooks [Import sample notebooks ](https://aka.ms/aml-clone-azure-notebooks) into Azure Notebooks
1. Follow the instructions in the [Configuration](configuration.ipynb) notebook to create and connect to a workspace 1. Follow the instructions in the [Configuration](configuration.ipynb) notebook to create and connect to a workspace
1. Open one of the sample notebooks 1. Open one of the sample notebooks
**Make sure the Azure Notebook kernel is set to `Python 3.6`** when you open a notebook by choosing Kernel > Change Kernel > Python 3.6 from the menus. **Make sure the Azure Notebook kernel is set to `Python 3.6`** when you open a notebook by choosing Kernel > Change Kernel > Python 3.6 from the menus.
## **Option 2: Use your own notebook server** ## **Option 2: Use your own notebook server**
### Quick installation ### Quick installation
We recommend you create a Python virtual environment ([Miniconda](https://conda.io/miniconda.html) preferred but [virtualenv](https://virtualenv.pypa.io/en/latest/) works too) and install the SDK in it. We recommend you create a Python virtual environment ([Miniconda](https://conda.io/miniconda.html) preferred but [virtualenv](https://virtualenv.pypa.io/en/latest/) works too) and install the SDK in it.
```sh ```sh
# install just the base SDK # install just the base SDK
pip install azureml-sdk pip install azureml-sdk
# clone the sample repoistory # clone the sample repoistory
git clone https://github.com/Azure/MachineLearningNotebooks.git git clone https://github.com/Azure/MachineLearningNotebooks.git
# below steps are optional # below steps are optional
# install the base SDK, Jupyter notebook server and tensorboard # install the base SDK, Jupyter notebook server and tensorboard
pip install azureml-sdk[notebooks,tensorboard] pip install azureml-sdk[notebooks,tensorboard]
# install model explainability component # install model explainability component
pip install azureml-sdk[explain] pip install azureml-sdk[explain]
# install automated ml components # install automated ml components
pip install azureml-sdk[automl] pip install azureml-sdk[automl]
# install experimental features (not ready for production use) # install experimental features (not ready for production use)
pip install azureml-sdk[contrib] pip install azureml-sdk[contrib]
``` ```
Note the _extras_ (the keywords inside the square brackets) can be combined. For example: Note the _extras_ (the keywords inside the square brackets) can be combined. For example:
```sh ```sh
# install base SDK, Jupyter notebook and automated ml components # install base SDK, Jupyter notebook and automated ml components
pip install azureml-sdk[notebooks,automl] pip install azureml-sdk[notebooks,automl]
``` ```
### Full instructions ### Full instructions
[Install the Azure Machine Learning SDK](https://docs.microsoft.com/en-us/azure/machine-learning/service/quickstart-create-workspace-with-python) [Install the Azure Machine Learning SDK](https://docs.microsoft.com/en-us/azure/machine-learning/service/quickstart-create-workspace-with-python)
Please make sure you start with the [Configuration](configuration.ipynb) notebook to create and connect to a workspace. Please make sure you start with the [Configuration](configuration.ipynb) notebook to create and connect to a workspace.
### Video walkthrough: ### Video walkthrough:
[!VIDEO https://youtu.be/VIsXeTuW3FU] [!VIDEO https://youtu.be/VIsXeTuW3FU]
## **Option 3: Use Docker** ## **Option 3: Use Docker**
You need to have Docker engine installed locally and running. Open a command line window and type the following command. You need to have Docker engine installed locally and running. Open a command line window and type the following command.
__Note:__ We use version `1.0.10` below as an exmaple, but you can replace that with any available version number you like. __Note:__ We use version `1.0.10` below as an exmaple, but you can replace that with any available version number you like.
```sh ```sh
# clone the sample repoistory # clone the sample repoistory
git clone https://github.com/Azure/MachineLearningNotebooks.git git clone https://github.com/Azure/MachineLearningNotebooks.git
# change current directory to the folder # change current directory to the folder
# where Dockerfile of the specific SDK version is located. # where Dockerfile of the specific SDK version is located.
cd MachineLearningNotebooks/Dockerfiles/1.0.10 cd MachineLearningNotebooks/Dockerfiles/1.0.10
# build a Docker image with the a name (azuremlsdk for example) # build a Docker image with the a name (azuremlsdk for example)
# and a version number tag (1.0.10 for example). # and a version number tag (1.0.10 for example).
# this can take several minutes depending on your computer speed and network bandwidth. # this can take several minutes depending on your computer speed and network bandwidth.
docker build . -t azuremlsdk:1.0.10 docker build . -t azuremlsdk:1.0.10
# launch the built Docker container which also automatically starts # launch the built Docker container which also automatically starts
# a Jupyter server instance listening on port 8887 of the host machine # a Jupyter server instance listening on port 8887 of the host machine
docker run -it -p 8887:8887 azuremlsdk:1.0.10 docker run -it -p 8887:8887 azuremlsdk:1.0.10
``` ```
Now you can point your browser to http://localhost:8887. We recommend that you start from the `configuration.ipynb` notebook at the root directory. Now you can point your browser to http://localhost:8887. We recommend that you start from the `configuration.ipynb` notebook at the root directory.
If you need additional Azure ML SDK components, you can either modify the Docker files before you build the Docker images to add additional steps, or install them through command line in the live container after you build the Docker image. For example: If you need additional Azure ML SDK components, you can either modify the Docker files before you build the Docker images to add additional steps, or install them through command line in the live container after you build the Docker image. For example:
```sh ```sh
# install the core SDK and automated ml components # install the core SDK and automated ml components
pip install azureml-sdk[automl] pip install azureml-sdk[automl]
# install the core SDK and model explainability component # install the core SDK and model explainability component
pip install azureml-sdk[explain] pip install azureml-sdk[explain]
# install the core SDK and experimental components # install the core SDK and experimental components
pip install azureml-sdk[contrib] pip install azureml-sdk[contrib]
``` ```
Drag and Drop Drag and Drop
The image will be downloaded by Fatkun The image will be downloaded by Fatkun

144
README.md
View File

@@ -1,76 +1,68 @@
# Azure Machine Learning service example notebooks # Azure Machine Learning service example notebooks
This repository contains example notebooks demonstrating the [Azure Machine Learning](https://azure.microsoft.com/en-us/services/machine-learning-service/) Python SDK which allows you to build, train, deploy and manage machine learning solutions using Azure. The AML SDK allows you the choice of using local or cloud compute resources, while managing and maintaining the complete data science workflow from the cloud. This repository contains example notebooks demonstrating the [Azure Machine Learning](https://azure.microsoft.com/en-us/services/machine-learning-service/) Python SDK which allows you to build, train, deploy and manage machine learning solutions using Azure. The AML SDK allows you the choice of using local or cloud compute resources, while managing and maintaining the complete data science workflow from the cloud.
![Azure ML Workflow](https://raw.githubusercontent.com/MicrosoftDocs/azure-docs/master/articles/machine-learning/service/media/concept-azure-machine-learning-architecture/workflow.png) ![Azure ML workflow](https://raw.githubusercontent.com/MicrosoftDocs/azure-docs/master/articles/machine-learning/service/media/overview-what-is-azure-ml/aml.png)
## Quick installation
## Quick installation ```sh
```sh pip install azureml-sdk
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.
Read more detailed instructions on [how to set up your environment](./NBSETUP.md) using Azure Notebook service, your own Jupyter notebook server, or Docker.
## How to navigate and use the example notebooks?
## 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.
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.
If you want to...
If you want to...
* ...try out and explore Azure ML, start with image classification tutorials: [Part 1 (Training)](./tutorials/img-classification-part1-training.ipynb) and [Part 2 (Deployment)](./tutorials/img-classification-part2-deploy.ipynb).
* ...try out and explore Azure ML, start with image classification tutorials: [Part 1 (Training)](./tutorials/img-classification-part1-training.ipynb) and [Part 2 (Deployment)](./tutorials/img-classification-part2-deploy.ipynb). * ...prepare your data and do automated machine learning, start with regression tutorials: [Part 1 (Data Prep)](./tutorials/regression-part1-data-prep.ipynb) and [Part 2 (Automated ML)](./tutorials/regression-part2-automated-ml.ipynb).
* ...prepare your data and do automated machine learning, start with regression tutorials: [Part 1 (Data Prep)](./tutorials/regression-part1-data-prep.ipynb) and [Part 2 (Automated ML)](./tutorials/regression-part2-automated-ml.ipynb). * ...learn about experimentation and tracking run history, first [train within Notebook](./how-to-use-azureml/training/train-within-notebook/train-within-notebook.ipynb), then try [training on remote VM](./how-to-use-azureml/training/train-on-remote-vm/train-on-remote-vm.ipynb) and [using logging APIs](./how-to-use-azureml/training/logging-api/logging-api.ipynb).
* ...learn about experimentation and tracking run history, first [train within Notebook](./how-to-use-azureml/training/train-within-notebook/train-within-notebook.ipynb), then try [training on remote VM](./how-to-use-azureml/training/train-on-remote-vm/train-on-remote-vm.ipynb) and [using logging APIs](./how-to-use-azureml/training/logging-api/logging-api.ipynb). * ...train deep learning models at scale, first learn about [Machine Learning Compute](./how-to-use-azureml/training/train-on-amlcompute/train-on-amlcompute.ipynb), and then try [distributed hyperparameter tuning](./how-to-use-azureml/training-with-deep-learning/train-hyperparameter-tune-deploy-with-pytorch/train-hyperparameter-tune-deploy-with-pytorch.ipynb) and [distributed training](./how-to-use-azureml/training-with-deep-learning/distributed-pytorch-with-horovod/distributed-pytorch-with-horovod.ipynb).
* ...train deep learning models at scale, first learn about [Machine Learning Compute](./how-to-use-azureml/training/train-on-amlcompute/train-on-amlcompute.ipynb), and then try [distributed hyperparameter tuning](./how-to-use-azureml/training-with-deep-learning/train-hyperparameter-tune-deploy-with-pytorch/train-hyperparameter-tune-deploy-with-pytorch.ipynb) and [distributed training](./how-to-use-azureml/training-with-deep-learning/distributed-pytorch-with-horovod/distributed-pytorch-with-horovod.ipynb). * ...deploy models as a realtime scoring service, first learn the basics by [training within Notebook and deploying to Azure Container Instance](./how-to-use-azureml/training/train-within-notebook/train-within-notebook.ipynb), then learn how to [register and manage models, and create Docker images](./how-to-use-azureml/deployment/register-model-create-image-deploy-service/register-model-create-image-deploy-service.ipynb), and [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 realtime scoring service, first learn the basics by [training within Notebook and deploying to Azure Container Instance](./how-to-use-azureml/training/train-within-notebook/train-within-notebook.ipynb), then learn how to [register and manage models, and create Docker images](./how-to-use-azureml/deployment/register-model-create-image-deploy-service/register-model-create-image-deploy-service.ipynb), and [production deploy models on Azure Kubernetes Cluster](./how-to-use-azureml/deployment/production-deploy-to-aks/production-deploy-to-aks.ipynb). * ...deploy models as a batch scoring service, first [train a model within Notebook](./how-to-use-azureml/training/train-within-notebook/train-within-notebook.ipynb), learn how to [register and manage models](./how-to-use-azureml/deployment/register-model-create-image-deploy-service/register-model-create-image-deploy-service.ipynb), then [create Machine Learning Compute for scoring compute](./how-to-use-azureml/training/train-on-amlcompute/train-on-amlcompute.ipynb), and [use Machine Learning Pipelines to deploy your model](https://aka.ms/pl-batch-scoring).
* ...deploy models as a batch scoring service, first [train a model within Notebook](./how-to-use-azureml/training/train-within-notebook/train-within-notebook.ipynb), learn how to [register and manage models](./how-to-use-azureml/deployment/register-model-create-image-deploy-service/register-model-create-image-deploy-service.ipynb), then [create Machine Learning Compute for scoring compute](./how-to-use-azureml/training/train-on-amlcompute/train-on-amlcompute.ipynb), and [use Machine Learning Pipelines to deploy your model](https://aka.ms/pl-batch-scoring). * ...monitor your deployed models, learn about using [App Insights](./how-to-use-azureml/deployment/enable-app-insights-in-production-service/enable-app-insights-in-production-service.ipynb) and [model data collection](./how-to-use-azureml/deployment/enable-data-collection-for-models-in-aks/enable-data-collection-for-models-in-aks.ipynb).
* ...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) and [model data collection](./how-to-use-azureml/deployment/enable-data-collection-for-models-in-aks/enable-data-collection-for-models-in-aks.ipynb).
## Tutorials
## Tutorials
The [Tutorials](./tutorials) folder contains notebooks for the tutorials described in the [Azure Machine Learning documentation](https://aka.ms/aml-docs).
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
## 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
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](./how-to-use-azureml/training) - Examples of how to build models using Azure ML's logging and execution capabilities on local and remote compute targets - [Training with Deep Learning](./how-to-use-azureml/training-with-deep-learning) - Examples demonstrating how to build deep learning models using estimators and parameter sweeps
- [Training with Deep Learning](./how-to-use-azureml/training-with-deep-learning) - Examples demonstrating how to build deep learning models using estimators and parameter sweeps - [Manage Azure ML Service](./how-to-use-azureml/manage-azureml-service) - Examples how to perform tasks, such as authenticate against Azure ML service in different ways.
- [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
- [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
- [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
- [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
- [Azure Databricks](./how-to-use-azureml/azure-databricks) - Examples showing how to use Azure ML with Azure Databricks
- [Monitor Models](./how-to-use-azureml/monitor-models) - Examples showing how to enable model monitoring services such as DataDrift ---
## Documentation
---
## 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)
* 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/). * 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).
* [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). ---
--- ## Projects using Azure Machine Learning
Visit following repos to see projects contributed by Azure ML users:
## 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. - [Fine tune natural language processing 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)
## Projects using Azure Machine Learning
## Data/Telemetry
Visit following repos to see projects contributed by Azure ML users: This repository collects usage data and sends it to Mircosoft to help improve our products and services. Read Microsoft's [privacy statement to learn more](https://privacy.microsoft.com/en-US/privacystatement)
- [AMLSamples](https://github.com/Azure/AMLSamples) Number of end-to-end examples, including face recognition, predictive maintenance, customer churn and sentiment analysis.
- [Learn about Natural Language Processing best practices using Azure Machine Learning service](https://github.com/microsoft/nlp) To opt out of tracking, please go to the raw markdown or .ipynb files and remove the following line of code:
- [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) ```sh
- [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. "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/README.png)"
```
## Data/Telemetry This URL will be slightly different depending on the file.
This repository collects usage data and sends it to Mircosoft to help improve our products and services. Read Microsoft's [privacy statement to learn more](https://privacy.microsoft.com/en-US/privacystatement)
![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/README.png)
To opt out of tracking, please go to the raw markdown or .ipynb files and remove the following line of code:
```sh
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/README.png)"
```
This URL will be slightly different depending on the file.
![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/README.png)

View File

@@ -1,383 +1,383 @@
{ {
"cells": [ "metadata": {
{ "kernelspec": {
"cell_type": "markdown", "display_name": "Python 3.6",
"metadata": {}, "name": "python36",
"source": [ "language": "python"
"Copyright (c) Microsoft Corporation. All rights reserved.\n", },
"\n", "authors": [
"Licensed under the MIT License." {
] "name": "roastala"
}, }
{ ],
"cell_type": "markdown", "language_info": {
"metadata": {}, "mimetype": "text/x-python",
"source": [ "codemirror_mode": {
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/configuration.png)" "name": "ipython",
] "version": 3
}, },
{ "pygments_lexer": "ipython3",
"cell_type": "markdown", "name": "python",
"metadata": {}, "file_extension": ".py",
"source": [ "nbconvert_exporter": "python",
"# Configuration\n", "version": "3.6.5"
"\n", }
"_**Setting up your Azure Machine Learning services workspace and configuring your notebook library**_\n", },
"\n", "nbformat": 4,
"---\n", "cells": [
"---\n", {
"\n", "metadata": {},
"## Table of Contents\n", "source": [
"\n", "Copyright (c) Microsoft Corporation. All rights reserved.\n",
"1. [Introduction](#Introduction)\n", "\n",
" 1. What is an Azure Machine Learning workspace\n", "Licensed under the MIT License."
"1. [Setup](#Setup)\n", ],
" 1. Azure subscription\n", "cell_type": "markdown"
" 1. Azure ML SDK and other library installation\n", },
" 1. Azure Container Instance registration\n", {
"1. [Configure your Azure ML Workspace](#Configure%20your%20Azure%20ML%20workspace)\n", "metadata": {},
" 1. Workspace parameters\n", "source": [
" 1. Access your workspace\n", "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/configuration.png)"
" 1. Create a new workspace\n", ],
" 1. Create compute resources\n", "cell_type": "markdown"
"1. [Next steps](#Next%20steps)\n", },
"\n", {
"---\n", "metadata": {},
"\n", "source": [
"## Introduction\n", "# Configuration\n",
"\n", "\n",
"This notebook configures your library of notebooks to connect to an Azure Machine Learning (ML) workspace. In this case, a library contains all of the notebooks in the current folder and any nested folders. You can configure this notebook library to use an existing workspace or create a new workspace.\n", "_**Setting up your Azure Machine Learning services workspace and configuring your notebook library**_\n",
"\n", "\n",
"Typically you will need to run this notebook only once per notebook library as all other notebooks will use connection information that is written here. If you want to redirect your notebook library to work with a different workspace, then you should re-run this notebook.\n", "---\n",
"\n", "---\n",
"In this notebook you will\n", "\n",
"* Learn about getting an Azure subscription\n", "## Table of Contents\n",
"* Specify your workspace parameters\n", "\n",
"* Access or create your workspace\n", "1. [Introduction](#Introduction)\n",
"* Add a default compute cluster for your workspace\n", " 1. What is an Azure Machine Learning workspace\n",
"\n", "1. [Setup](#Setup)\n",
"### What is an Azure Machine Learning workspace\n", " 1. Azure subscription\n",
"\n", " 1. Azure ML SDK and other library installation\n",
"An Azure ML Workspace is an Azure resource that organizes and coordinates the actions of many other Azure resources to assist in executing and sharing machine learning workflows. In particular, an Azure ML Workspace coordinates storage, databases, and compute resources providing added functionality for machine learning experimentation, deployment, inference, and the monitoring of deployed models." " 1. Azure Container Instance registration\n",
] "1. [Configure your Azure ML Workspace](#Configure%20your%20Azure%20ML%20workspace)\n",
}, " 1. Workspace parameters\n",
{ " 1. Access your workspace\n",
"cell_type": "markdown", " 1. Create a new workspace\n",
"metadata": {}, " 1. Create compute resources\n",
"source": [ "1. [Next steps](#Next%20steps)\n",
"## Setup\n", "\n",
"\n", "---\n",
"This section describes activities required before you can access any Azure ML services functionality." "\n",
] "## Introduction\n",
}, "\n",
{ "This notebook configures your library of notebooks to connect to an Azure Machine Learning (ML) workspace. In this case, a library contains all of the notebooks in the current folder and any nested folders. You can configure this notebook library to use an existing workspace or create a new workspace.\n",
"cell_type": "markdown", "\n",
"metadata": {}, "Typically you will need to run this notebook only once per notebook library as all other notebooks will use connection information that is written here. If you want to redirect your notebook library to work with a different workspace, then you should re-run this notebook.\n",
"source": [ "\n",
"### 1. Azure Subscription\n", "In this notebook you will\n",
"\n", "* Learn about getting an Azure subscription\n",
"In order to create an Azure ML Workspace, first you need access to an Azure subscription. An Azure subscription allows you to manage storage, compute, and other assets in the Azure cloud. You can [create a new subscription](https://azure.microsoft.com/en-us/free/) or access existing subscription information from the [Azure portal](https://portal.azure.com). Later in this notebook you will need information such as your subscription ID in order to create and access AML workspaces.\n", "* Specify your workspace parameters\n",
"\n", "* Access or create your workspace\n",
"### 2. Azure ML SDK and other library installation\n", "* Add a default compute cluster for your workspace\n",
"\n", "\n",
"If you are running in your own environment, follow [SDK installation instructions](https://docs.microsoft.com/azure/machine-learning/service/how-to-configure-environment). If you are running in Azure Notebooks or another Microsoft managed environment, the SDK is already installed.\n", "### What is an Azure Machine Learning workspace\n",
"\n", "\n",
"Also install following libraries to your environment. Many of the example notebooks depend on them\n", "An Azure ML Workspace is an Azure resource that organizes and coordinates the actions of many other Azure resources to assist in executing and sharing machine learning workflows. In particular, an Azure ML Workspace coordinates storage, databases, and compute resources providing added functionality for machine learning experimentation, deployment, inference, and the monitoring of deployed models."
"\n", ],
"```\n", "cell_type": "markdown"
"(myenv) $ conda install -y matplotlib tqdm scikit-learn\n", },
"```\n", {
"\n", "metadata": {},
"Once installation is complete, the following cell checks the Azure ML SDK version:" "source": [
] "## Setup\n",
}, "\n",
{ "This section describes activities required before you can access any Azure ML services functionality."
"cell_type": "code", ],
"execution_count": null, "cell_type": "markdown"
"metadata": { },
"tags": [ {
"install" "metadata": {},
] "source": [
}, "### 1. Azure Subscription\n",
"outputs": [], "\n",
"source": [ "In order to create an Azure ML Workspace, first you need access to an Azure subscription. An Azure subscription allows you to manage storage, compute, and other assets in the Azure cloud. You can [create a new subscription](https://azure.microsoft.com/en-us/free/) or access existing subscription information from the [Azure portal](https://portal.azure.com). Later in this notebook you will need information such as your subscription ID in order to create and access AML workspaces.\n",
"import azureml.core\n", "\n",
"\n", "### 2. Azure ML SDK and other library installation\n",
"print(\"This notebook was created using version 1.0.69 of the Azure ML SDK\")\n", "\n",
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")" "If you are running in your own environment, follow [SDK installation instructions](https://docs.microsoft.com/azure/machine-learning/service/how-to-configure-environment). If you are running in Azure Notebooks or another Microsoft managed environment, the SDK is already installed.\n",
] "\n",
}, "Also install following libraries to your environment. Many of the example notebooks depend on them\n",
{ "\n",
"cell_type": "markdown", "```\n",
"metadata": {}, "(myenv) $ conda install -y matplotlib tqdm scikit-learn\n",
"source": [ "```\n",
"If you are using an older version of the SDK then this notebook was created using, you should upgrade your SDK.\n", "\n",
"\n", "Once installation is complete, the following cell checks the Azure ML SDK version:"
"### 3. Azure Container Instance registration\n", ],
"Azure Machine Learning uses of [Azure Container Instance (ACI)](https://azure.microsoft.com/services/container-instances) to deploy dev/test web services. An Azure subscription needs to be registered to use ACI. If you or the subscription owner have not yet registered ACI on your subscription, you will need to use the [Azure CLI](https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest) and execute the following commands. Note that if you ran through the AML [quickstart](https://docs.microsoft.com/en-us/azure/machine-learning/service/quickstart-get-started) you have already registered ACI. \n", "cell_type": "markdown"
"\n", },
"```shell\n", {
"# check to see if ACI is already registered\n", "metadata": {
"(myenv) $ az provider show -n Microsoft.ContainerInstance -o table\n", "tags": [
"\n", "install"
"# if ACI is not registered, run this command.\n", ]
"# note you need to be the subscription owner in order to execute this command successfully.\n", },
"(myenv) $ az provider register -n Microsoft.ContainerInstance\n", "outputs": [],
"```\n", "execution_count": null,
"\n", "source": [
"---" "import azureml.core\n",
] "\n",
}, "print(\"This notebook was created using version 1.0.48.post1 of the Azure ML SDK\")\n",
{ "print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
"cell_type": "markdown", ],
"metadata": {}, "cell_type": "code"
"source": [ },
"## Configure your Azure ML workspace\n", {
"\n", "metadata": {},
"### Workspace parameters\n", "source": [
"\n", "If you are using an older version of the SDK then this notebook was created using, you should upgrade your SDK.\n",
"To use an AML Workspace, you will need to import the Azure ML SDK and supply the following information:\n", "\n",
"* Your subscription id\n", "### 3. Azure Container Instance registration\n",
"* A resource group name\n", "Azure Machine Learning uses of [Azure Container Instance (ACI)](https://azure.microsoft.com/services/container-instances) to deploy dev/test web services. An Azure subscription needs to be registered to use ACI. If you or the subscription owner have not yet registered ACI on your subscription, you will need to use the [Azure CLI](https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest) and execute the following commands. Note that if you ran through the AML [quickstart](https://docs.microsoft.com/en-us/azure/machine-learning/service/quickstart-get-started) you have already registered ACI. \n",
"* (optional) The region that will host your workspace\n", "\n",
"* A name for your workspace\n", "```shell\n",
"\n", "# check to see if ACI is already registered\n",
"You can get your subscription ID from the [Azure portal](https://portal.azure.com).\n", "(myenv) $ az provider show -n Microsoft.ContainerInstance -o table\n",
"\n", "\n",
"You will also need access to a [_resource group_](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-overview#resource-groups), which organizes Azure resources and provides a default region for the resources in a group. You can see what resource groups to which you have access, or create a new one in the [Azure portal](https://portal.azure.com). If you don't have a resource group, the create workspace command will create one for you using the name you provide.\n", "# if ACI is not registered, run this command.\n",
"\n", "# note you need to be the subscription owner in order to execute this command successfully.\n",
"The region to host your workspace will be used if you are creating a new workspace. You do not need to specify this if you are using an existing workspace. You can find the list of supported regions [here](https://azure.microsoft.com/en-us/global-infrastructure/services/?products=machine-learning-service). You should pick a region that is close to your location or that contains your data.\n", "(myenv) $ az provider register -n Microsoft.ContainerInstance\n",
"\n", "```\n",
"The name for your workspace is unique within the subscription and should be descriptive enough to discern among other AML Workspaces. The subscription may be used only by you, or it may be used by your department or your entire enterprise, so choose a name that makes sense for your situation.\n", "\n",
"\n", "---"
"The following cell allows you to specify your workspace parameters. This cell uses the python method `os.getenv` to read values from environment variables which is useful for automation. If no environment variable exists, the parameters will be set to the specified default values. \n", ],
"\n", "cell_type": "markdown"
"If you ran the Azure Machine Learning [quickstart](https://docs.microsoft.com/en-us/azure/machine-learning/service/quickstart-get-started) in Azure Notebooks, you already have a configured workspace! You can go to your Azure Machine Learning Getting Started library, view *config.json* file, and copy-paste the values for subscription ID, resource group and workspace name below.\n", },
"\n", {
"Replace the default values in the cell below with your workspace parameters" "metadata": {},
] "source": [
}, "## Configure your Azure ML workspace\n",
{ "\n",
"cell_type": "code", "### Workspace parameters\n",
"execution_count": null, "\n",
"metadata": {}, "To use an AML Workspace, you will need to import the Azure ML SDK and supply the following information:\n",
"outputs": [], "* Your subscription id\n",
"source": [ "* A resource group name\n",
"import os\n", "* (optional) The region that will host your workspace\n",
"\n", "* A name for your workspace\n",
"subscription_id = os.getenv(\"SUBSCRIPTION_ID\", default=\"<my-subscription-id>\")\n", "\n",
"resource_group = os.getenv(\"RESOURCE_GROUP\", default=\"<my-resource-group>\")\n", "You can get your subscription ID from the [Azure portal](https://portal.azure.com).\n",
"workspace_name = os.getenv(\"WORKSPACE_NAME\", default=\"<my-workspace-name>\")\n", "\n",
"workspace_region = os.getenv(\"WORKSPACE_REGION\", default=\"eastus2\")" "You will also need access to a [_resource group_](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-overview#resource-groups), which organizes Azure resources and provides a default region for the resources in a group. You can see what resource groups to which you have access, or create a new one in the [Azure portal](https://portal.azure.com). If you don't have a resource group, the create workspace command will create one for you using the name you provide.\n",
] "\n",
}, "The region to host your workspace will be used if you are creating a new workspace. You do not need to specify this if you are using an existing workspace. You can find the list of supported regions [here](https://azure.microsoft.com/en-us/global-infrastructure/services/?products=machine-learning-service). You should pick a region that is close to your location or that contains your data.\n",
{ "\n",
"cell_type": "markdown", "The name for your workspace is unique within the subscription and should be descriptive enough to discern among other AML Workspaces. The subscription may be used only by you, or it may be used by your department or your entire enterprise, so choose a name that makes sense for your situation.\n",
"metadata": {}, "\n",
"source": [ "The following cell allows you to specify your workspace parameters. This cell uses the python method `os.getenv` to read values from environment variables which is useful for automation. If no environment variable exists, the parameters will be set to the specified default values. \n",
"### Access your workspace\n", "\n",
"\n", "If you ran the Azure Machine Learning [quickstart](https://docs.microsoft.com/en-us/azure/machine-learning/service/quickstart-get-started) in Azure Notebooks, you already have a configured workspace! You can go to your Azure Machine Learning Getting Started library, view *config.json* file, and copy-paste the values for subscription ID, resource group and workspace name below.\n",
"The following cell uses the Azure ML SDK to attempt to load the workspace specified by your parameters. If this cell succeeds, your notebook library will be configured to access the workspace from all notebooks using the `Workspace.from_config()` method. The cell can fail if the specified workspace doesn't exist or you don't have permissions to access it. " "\n",
] "Replace the default values in the cell below with your workspace parameters"
}, ],
{ "cell_type": "markdown"
"cell_type": "code", },
"execution_count": null, {
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "execution_count": null,
"from azureml.core import Workspace\n", "source": [
"\n", "import os\n",
"try:\n", "\n",
" ws = Workspace(subscription_id = subscription_id, resource_group = resource_group, workspace_name = workspace_name)\n", "subscription_id = os.getenv(\"SUBSCRIPTION_ID\", default=\"<my-subscription-id>\")\n",
" # write the details of the workspace to a configuration file to the notebook library\n", "resource_group = os.getenv(\"RESOURCE_GROUP\", default=\"<my-resource-group>\")\n",
" ws.write_config()\n", "workspace_name = os.getenv(\"WORKSPACE_NAME\", default=\"<my-workspace-name>\")\n",
" print(\"Workspace configuration succeeded. Skip the workspace creation steps below\")\n", "workspace_region = os.getenv(\"WORKSPACE_REGION\", default=\"eastus2\")"
"except:\n", ],
" print(\"Workspace not accessible. Change your parameters or create a new workspace below\")" "cell_type": "code"
] },
}, {
{ "metadata": {},
"cell_type": "markdown", "source": [
"metadata": {}, "### Access your workspace\n",
"source": [ "\n",
"### Create a new workspace\n", "The following cell uses the Azure ML SDK to attempt to load the workspace specified by your parameters. If this cell succeeds, your notebook library will be configured to access the workspace from all notebooks using the `Workspace.from_config()` method. The cell can fail if the specified workspace doesn't exist or you don't have permissions to access it. "
"\n", ],
"If you don't have an existing workspace and are the owner of the subscription or resource group, you can create a new workspace. If you don't have a resource group, the create workspace command will create one for you using the name you provide.\n", "cell_type": "markdown"
"\n", },
"**Note**: As with other Azure services, there are limits on certain resources (for example AmlCompute quota) associated with the Azure ML 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.\n", {
"\n", "metadata": {},
"This cell will create an Azure ML workspace for you in a subscription provided you have the correct permissions.\n", "outputs": [],
"\n", "execution_count": null,
"This will fail if:\n", "source": [
"* You do not have permission to create a workspace in the resource group\n", "from azureml.core import Workspace\n",
"* You do not have permission to create a resource group if it's non-existing.\n", "\n",
"* You are not a subscription owner or contributor and no Azure ML workspaces have ever been created in this subscription\n", "try:\n",
"\n", " ws = Workspace(subscription_id = subscription_id, resource_group = resource_group, workspace_name = workspace_name)\n",
"If workspace creation fails, please work with your IT admin to provide you with the appropriate permissions or to provision the required resources." " # write the details of the workspace to a configuration file to the notebook library\n",
] " ws.write_config()\n",
}, " print(\"Workspace configuration succeeded. Skip the workspace creation steps below\")\n",
{ "except:\n",
"cell_type": "code", " print(\"Workspace not accessible. Change your parameters or create a new workspace below\")"
"execution_count": null, ],
"metadata": { "cell_type": "code"
"tags": [ },
"create workspace" {
] "metadata": {},
}, "source": [
"outputs": [], "### Create a new workspace\n",
"source": [ "\n",
"from azureml.core import Workspace\n", "If you don't have an existing workspace and are the owner of the subscription or resource group, you can create a new workspace. If you don't have a resource group, the create workspace command will create one for you using the name you provide.\n",
"\n", "\n",
"# Create the workspace using the specified parameters\n", "**Note**: As with other Azure services, there are limits on certain resources (for example AmlCompute quota) associated with the Azure ML 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.\n",
"ws = Workspace.create(name = workspace_name,\n", "\n",
" subscription_id = subscription_id,\n", "This cell will create an Azure ML workspace for you in a subscription provided you have the correct permissions.\n",
" resource_group = resource_group, \n", "\n",
" location = workspace_region,\n", "This will fail if:\n",
" create_resource_group = True,\n", "* You do not have permission to create a workspace in the resource group\n",
" exist_ok = True)\n", "* You do not have permission to create a resource group if it's non-existing.\n",
"ws.get_details()\n", "* You are not a subscription owner or contributor and no Azure ML workspaces have ever been created in this subscription\n",
"\n", "\n",
"# write the details of the workspace to a configuration file to the notebook library\n", "If workspace creation fails, please work with your IT admin to provide you with the appropriate permissions or to provision the required resources."
"ws.write_config()" ],
] "cell_type": "markdown"
}, },
{ {
"cell_type": "markdown", "metadata": {
"metadata": {}, "tags": [
"source": [ "create workspace"
"### Create compute resources for your training experiments\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", "outputs": [],
"\n", "execution_count": null,
"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", "source": [
"\n", "from azureml.core import Workspace\n",
"The cluster parameters are:\n", "\n",
"* vm_size - this describes the virtual machine type and size used in the cluster. All machines in the cluster are the same type. You can get the list of vm sizes available in your region by using the CLI command\n", "# Create the workspace using the specified parameters\n",
"\n", "ws = Workspace.create(name = workspace_name,\n",
"```shell\n", " subscription_id = subscription_id,\n",
"az vm list-skus -o tsv\n", " resource_group = resource_group, \n",
"```\n", " location = workspace_region,\n",
"* min_nodes - this sets the minimum size of the cluster. If you set the minimum to 0 the cluster will shut down all nodes while not in use. Setting this number to a value higher than 0 will allow for faster start-up times, but you will also be billed when the cluster is not in use.\n", " create_resource_group = True,\n",
"* max_nodes - this sets the maximum size of the cluster. Setting this to a larger number allows for more concurrency and a greater distributed processing of scale-out jobs.\n", " exist_ok = True)\n",
"\n", "ws.get_details()\n",
"\n", "\n",
"To create a **CPU** cluster now, run the cell below. The autoscale settings mean that the cluster will scale down to 0 nodes when inactive and up to 4 nodes when busy." "# write the details of the workspace to a configuration file to the notebook library\n",
] "ws.write_config()"
}, ],
{ "cell_type": "code"
"cell_type": "code", },
"execution_count": null, {
"metadata": {}, "metadata": {},
"outputs": [], "source": [
"source": [ "### Create compute resources for your training experiments\n",
"from azureml.core.compute import ComputeTarget, AmlCompute\n", "\n",
"from azureml.core.compute_target import ComputeTargetException\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",
"# Choose a name for your CPU cluster\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",
"cpu_cluster_name = \"cpu-cluster\"\n", "\n",
"\n", "The cluster parameters are:\n",
"# Verify that cluster does not exist already\n", "* vm_size - this describes the virtual machine type and size used in the cluster. All machines in the cluster are the same type. You can get the list of vm sizes available in your region by using the CLI command\n",
"try:\n", "\n",
" cpu_cluster = ComputeTarget(workspace=ws, name=cpu_cluster_name)\n", "```shell\n",
" print(\"Found existing cpu-cluster\")\n", "az vm list-skus -o tsv\n",
"except ComputeTargetException:\n", "```\n",
" print(\"Creating new cpu-cluster\")\n", "* min_nodes - this sets the minimum size of the cluster. If you set the minimum to 0 the cluster will shut down all nodes while not in use. Setting this number to a value higher than 0 will allow for faster start-up times, but you will also be billed when the cluster is not in use.\n",
" \n", "* max_nodes - this sets the maximum size of the cluster. Setting this to a larger number allows for more concurrency and a greater distributed processing of scale-out jobs.\n",
" # Specify the configuration for the new cluster\n", "\n",
" compute_config = AmlCompute.provisioning_configuration(vm_size=\"STANDARD_D2_V2\",\n", "\n",
" min_nodes=0,\n", "To create a **CPU** cluster now, run the cell below. The autoscale settings mean that the cluster will scale down to 0 nodes when inactive and up to 4 nodes when busy."
" max_nodes=4)\n", ],
"\n", "cell_type": "markdown"
" # Create the cluster with the specified name and configuration\n", },
" cpu_cluster = ComputeTarget.create(ws, cpu_cluster_name, compute_config)\n", {
" \n", "metadata": {},
" # Wait for the cluster to complete, show the output log\n", "outputs": [],
" cpu_cluster.wait_for_completion(show_output=True)" "execution_count": null,
] "source": [
}, "from azureml.core.compute import ComputeTarget, AmlCompute\n",
{ "from azureml.core.compute_target import ComputeTargetException\n",
"cell_type": "markdown", "\n",
"metadata": {}, "# Choose a name for your CPU cluster\n",
"source": [ "cpu_cluster_name = \"cpu-cluster\"\n",
"To create a **GPU** cluster, run the cell below. Note that your subscription must have sufficient quota for GPU VMs or the command will fail. To increase quota, see [these instructions](https://docs.microsoft.com/en-us/azure/azure-supportability/resource-manager-core-quotas-request). " "\n",
] "# Verify that cluster does not exist already\n",
}, "try:\n",
{ " cpu_cluster = ComputeTarget(workspace=ws, name=cpu_cluster_name)\n",
"cell_type": "code", " print(\"Found existing cpu-cluster\")\n",
"execution_count": null, "except ComputeTargetException:\n",
"metadata": {}, " print(\"Creating new cpu-cluster\")\n",
"outputs": [], " \n",
"source": [ " # Specify the configuration for the new cluster\n",
"from azureml.core.compute import ComputeTarget, AmlCompute\n", " compute_config = AmlCompute.provisioning_configuration(vm_size=\"STANDARD_D2_V2\",\n",
"from azureml.core.compute_target import ComputeTargetException\n", " min_nodes=0,\n",
"\n", " max_nodes=4)\n",
"# Choose a name for your GPU cluster\n", "\n",
"gpu_cluster_name = \"gpu-cluster\"\n", " # Create the cluster with the specified name and configuration\n",
"\n", " cpu_cluster = ComputeTarget.create(ws, cpu_cluster_name, compute_config)\n",
"# Verify that cluster does not exist already\n", " \n",
"try:\n", " # Wait for the cluster to complete, show the output log\n",
" gpu_cluster = ComputeTarget(workspace=ws, name=gpu_cluster_name)\n", " cpu_cluster.wait_for_completion(show_output=True)"
" print(\"Found existing gpu cluster\")\n", ],
"except ComputeTargetException:\n", "cell_type": "code"
" print(\"Creating new gpu-cluster\")\n", },
" \n", {
" # Specify the configuration for the new cluster\n", "metadata": {},
" compute_config = AmlCompute.provisioning_configuration(vm_size=\"STANDARD_NC6\",\n", "source": [
" min_nodes=0,\n", "To create a **GPU** cluster, run the cell below. Note that your subscription must have sufficient quota for GPU VMs or the command will fail. To increase quota, see [these instructions](https://docs.microsoft.com/en-us/azure/azure-supportability/resource-manager-core-quotas-request). "
" max_nodes=4)\n", ],
" # Create the cluster with the specified name and configuration\n", "cell_type": "markdown"
" gpu_cluster = ComputeTarget.create(ws, gpu_cluster_name, compute_config)\n", },
"\n", {
" # Wait for the cluster to complete, show the output log\n", "metadata": {},
" gpu_cluster.wait_for_completion(show_output=True)" "outputs": [],
] "execution_count": null,
}, "source": [
{ "from azureml.core.compute import ComputeTarget, AmlCompute\n",
"cell_type": "markdown", "from azureml.core.compute_target import ComputeTargetException\n",
"metadata": {}, "\n",
"source": [ "# Choose a name for your GPU cluster\n",
"---\n", "gpu_cluster_name = \"gpu-cluster\"\n",
"\n", "\n",
"## Next steps\n", "# Verify that cluster does not exist already\n",
"\n", "try:\n",
"In this notebook you configured this notebook library to connect easily to an Azure ML workspace. You can copy this notebook to your own libraries to connect them to you workspace, or use it to bootstrap new workspaces completely.\n", " gpu_cluster = ComputeTarget(workspace=ws, name=gpu_cluster_name)\n",
"\n", " print(\"Found existing gpu cluster\")\n",
"If you came here from another notebook, you can return there and complete that exercise, or you can try out the [Tutorials](./tutorials) or jump into \"how-to\" notebooks and start creating and deploying models. A good place to start is the [train within notebook](./how-to-use-azureml/training/train-within-notebook) example that walks through a simplified but complete end to end machine learning process." "except ComputeTargetException:\n",
] " print(\"Creating new gpu-cluster\")\n",
}, " \n",
{ " # Specify the configuration for the new cluster\n",
"cell_type": "code", " compute_config = AmlCompute.provisioning_configuration(vm_size=\"STANDARD_NC6\",\n",
"execution_count": null, " min_nodes=0,\n",
"metadata": {}, " max_nodes=4)\n",
"outputs": [], " # Create the cluster with the specified name and configuration\n",
"source": [] " gpu_cluster = ComputeTarget.create(ws, gpu_cluster_name, compute_config)\n",
} "\n",
], " # Wait for the cluster to complete, show the output log\n",
"metadata": { " gpu_cluster.wait_for_completion(show_output=True)"
"authors": [ ],
{ "cell_type": "code"
"name": "roastala" },
} {
], "metadata": {},
"kernelspec": { "source": [
"display_name": "Python 3.6", "---\n",
"language": "python", "\n",
"name": "python36" "## Next steps\n",
}, "\n",
"language_info": { "In this notebook you configured this notebook library to connect easily to an Azure ML workspace. You can copy this notebook to your own libraries to connect them to you workspace, or use it to bootstrap new workspaces completely.\n",
"codemirror_mode": { "\n",
"name": "ipython", "If you came here from another notebook, you can return there and complete that exercise, or you can try out the [Tutorials](./tutorials) or jump into \"how-to\" notebooks and start creating and deploying models. A good place to start is the [train within notebook](./how-to-use-azureml/training/train-within-notebook) example that walks through a simplified but complete end to end machine learning process."
"version": 3 ],
}, "cell_type": "markdown"
"file_extension": ".py", },
"mimetype": "text/x-python", {
"name": "python", "metadata": {},
"nbconvert_exporter": "python", "outputs": [],
"pygments_lexer": "ipython3", "execution_count": null,
"version": "3.6.5" "source": [],
} "cell_type": "code"
}, }
"nbformat": 4, ],
"nbformat_minor": 2 "nbformat_minor": 2
} }

View File

@@ -1,4 +1,4 @@
name: configuration name: configuration
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk

File diff suppressed because it is too large Load Diff

View File

@@ -15,6 +15,21 @@ from glob import glob
import os import os
import argparse import argparse
def initialize_rmm_pool():
from librmm_cffi import librmm_config as rmm_cfg
rmm_cfg.use_pool_allocator = True
#rmm_cfg.initial_pool_size = 2<<30 # set to 2GiB. Default is 1/2 total GPU memory
import cudf
return cudf._gdf.rmm_initialize()
def initialize_rmm_no_pool():
from librmm_cffi import librmm_config as rmm_cfg
rmm_cfg.use_pool_allocator = False
import cudf
return cudf._gdf.rmm_initialize()
def run_dask_task(func, **kwargs): def run_dask_task(func, **kwargs):
task = func(**kwargs) task = func(**kwargs)
return task return task
@@ -192,26 +207,26 @@ def gpu_load_names(col_path):
def create_ever_features(gdf, **kwargs): def create_ever_features(gdf, **kwargs):
everdf = gdf[['loan_id', 'current_loan_delinquency_status']] everdf = gdf[['loan_id', 'current_loan_delinquency_status']]
everdf = everdf.groupby('loan_id', method='hash').max().reset_index() everdf = everdf.groupby('loan_id', method='hash').max()
del(gdf) del(gdf)
everdf['ever_30'] = (everdf['current_loan_delinquency_status'] >= 1).astype('int8') everdf['ever_30'] = (everdf['max_current_loan_delinquency_status'] >= 1).astype('int8')
everdf['ever_90'] = (everdf['current_loan_delinquency_status'] >= 3).astype('int8') everdf['ever_90'] = (everdf['max_current_loan_delinquency_status'] >= 3).astype('int8')
everdf['ever_180'] = (everdf['current_loan_delinquency_status'] >= 6).astype('int8') everdf['ever_180'] = (everdf['max_current_loan_delinquency_status'] >= 6).astype('int8')
everdf.drop_column('current_loan_delinquency_status') everdf.drop_column('max_current_loan_delinquency_status')
return everdf return everdf
def create_delinq_features(gdf, **kwargs): def create_delinq_features(gdf, **kwargs):
delinq_gdf = gdf[['loan_id', 'monthly_reporting_period', 'current_loan_delinquency_status']] delinq_gdf = gdf[['loan_id', 'monthly_reporting_period', 'current_loan_delinquency_status']]
del(gdf) del(gdf)
delinq_30 = delinq_gdf.query('current_loan_delinquency_status >= 1')[['loan_id', 'monthly_reporting_period']].groupby('loan_id', method='hash').min().reset_index() delinq_30 = delinq_gdf.query('current_loan_delinquency_status >= 1')[['loan_id', 'monthly_reporting_period']].groupby('loan_id', method='hash').min()
delinq_30['delinquency_30'] = delinq_30['monthly_reporting_period'] delinq_30['delinquency_30'] = delinq_30['min_monthly_reporting_period']
delinq_30.drop_column('monthly_reporting_period') delinq_30.drop_column('min_monthly_reporting_period')
delinq_90 = delinq_gdf.query('current_loan_delinquency_status >= 3')[['loan_id', 'monthly_reporting_period']].groupby('loan_id', method='hash').min().reset_index() delinq_90 = delinq_gdf.query('current_loan_delinquency_status >= 3')[['loan_id', 'monthly_reporting_period']].groupby('loan_id', method='hash').min()
delinq_90['delinquency_90'] = delinq_90['monthly_reporting_period'] delinq_90['delinquency_90'] = delinq_90['min_monthly_reporting_period']
delinq_90.drop_column('monthly_reporting_period') delinq_90.drop_column('min_monthly_reporting_period')
delinq_180 = delinq_gdf.query('current_loan_delinquency_status >= 6')[['loan_id', 'monthly_reporting_period']].groupby('loan_id', method='hash').min().reset_index() delinq_180 = delinq_gdf.query('current_loan_delinquency_status >= 6')[['loan_id', 'monthly_reporting_period']].groupby('loan_id', method='hash').min()
delinq_180['delinquency_180'] = delinq_180['monthly_reporting_period'] delinq_180['delinquency_180'] = delinq_180['min_monthly_reporting_period']
delinq_180.drop_column('monthly_reporting_period') delinq_180.drop_column('min_monthly_reporting_period')
del(delinq_gdf) del(delinq_gdf)
delinq_merge = delinq_30.merge(delinq_90, how='left', on=['loan_id'], type='hash') delinq_merge = delinq_30.merge(delinq_90, how='left', on=['loan_id'], type='hash')
delinq_merge['delinquency_90'] = delinq_merge['delinquency_90'].fillna(np.dtype('datetime64[ms]').type('1970-01-01').astype('datetime64[ms]')) delinq_merge['delinquency_90'] = delinq_merge['delinquency_90'].fillna(np.dtype('datetime64[ms]').type('1970-01-01').astype('datetime64[ms]'))
@@ -264,15 +279,16 @@ def create_joined_df(gdf, everdf, **kwargs):
def create_12_mon_features(joined_df, **kwargs): def create_12_mon_features(joined_df, **kwargs):
testdfs = [] testdfs = []
n_months = 12 n_months = 12
for y in range(1, n_months + 1): for y in range(1, n_months + 1):
tmpdf = joined_df[['loan_id', 'timestamp_year', 'timestamp_month', 'delinquency_12', 'upb_12']] tmpdf = joined_df[['loan_id', 'timestamp_year', 'timestamp_month', 'delinquency_12', 'upb_12']]
tmpdf['josh_months'] = tmpdf['timestamp_year'] * 12 + tmpdf['timestamp_month'] tmpdf['josh_months'] = tmpdf['timestamp_year'] * 12 + tmpdf['timestamp_month']
tmpdf['josh_mody_n'] = ((tmpdf['josh_months'].astype('float64') - 24000 - y) / 12).floor() tmpdf['josh_mody_n'] = ((tmpdf['josh_months'].astype('float64') - 24000 - y) / 12).floor()
tmpdf = tmpdf.groupby(['loan_id', 'josh_mody_n'], method='hash').agg({'delinquency_12': 'max','upb_12': 'min'}).reset_index() tmpdf = tmpdf.groupby(['loan_id', 'josh_mody_n'], method='hash').agg({'delinquency_12': 'max','upb_12': 'min'})
tmpdf['delinquency_12'] = (tmpdf['delinquency_12']>3).astype('int32') tmpdf['delinquency_12'] = (tmpdf['max_delinquency_12']>3).astype('int32')
tmpdf['delinquency_12'] +=(tmpdf['upb_12']==0).astype('int32') tmpdf['delinquency_12'] +=(tmpdf['min_upb_12']==0).astype('int32')
tmpdf['upb_12'] = tmpdf['upb_12'] tmpdf.drop_column('max_delinquency_12')
tmpdf['upb_12'] = tmpdf['min_upb_12']
tmpdf.drop_column('min_upb_12')
tmpdf['timestamp_year'] = (((tmpdf['josh_mody_n'] * n_months) + 24000 + (y - 1)) / 12).floor().astype('int16') tmpdf['timestamp_year'] = (((tmpdf['josh_mody_n'] * n_months) + 24000 + (y - 1)) / 12).floor().astype('int16')
tmpdf['timestamp_month'] = np.int8(y) tmpdf['timestamp_month'] = np.int8(y)
tmpdf.drop_column('josh_mody_n') tmpdf.drop_column('josh_mody_n')
@@ -313,7 +329,6 @@ def last_mile_cleaning(df, **kwargs):
'delinquency_30', 'delinquency_90', 'delinquency_180', 'upb_12', 'delinquency_30', 'delinquency_90', 'delinquency_180', 'upb_12',
'zero_balance_effective_date','foreclosed_after', 'disposition_date','timestamp' 'zero_balance_effective_date','foreclosed_after', 'disposition_date','timestamp'
] ]
for column in drop_list: for column in drop_list:
df.drop_column(column) df.drop_column(column)
for col, dtype in df.dtypes.iteritems(): for col, dtype in df.dtypes.iteritems():
@@ -327,6 +342,7 @@ def last_mile_cleaning(df, **kwargs):
return df.to_arrow(preserve_index=False) return df.to_arrow(preserve_index=False)
def main(): def main():
#print('XGBOOST_BUILD_DOC is ' + os.environ['XGBOOST_BUILD_DOC'])
parser = argparse.ArgumentParser("rapidssample") parser = argparse.ArgumentParser("rapidssample")
parser.add_argument("--data_dir", type=str, help="location of data") parser.add_argument("--data_dir", type=str, help="location of data")
parser.add_argument("--num_gpu", type=int, help="Number of GPUs to use", default=1) parser.add_argument("--num_gpu", type=int, help="Number of GPUs to use", default=1)
@@ -348,6 +364,7 @@ def main():
print('data_dir = {0}'.format(data_dir)) print('data_dir = {0}'.format(data_dir))
print('num_gpu = {0}'.format(num_gpu)) print('num_gpu = {0}'.format(num_gpu))
print('part_count = {0}'.format(part_count)) print('part_count = {0}'.format(part_count))
#part_count = part_count + 1 # adding one because the usage below is not inclusive
print('end_year = {0}'.format(end_year)) print('end_year = {0}'.format(end_year))
print('cpu_predictor = {0}'.format(cpu_predictor)) print('cpu_predictor = {0}'.format(cpu_predictor))
@@ -363,17 +380,19 @@ def main():
client client
print(client.ncores()) print(client.ncores())
# to download data for this notebook, visit https://rapidsai.github.io/demos/datasets/mortgage-data and update the following paths accordingly # to download data for this notebook, visit https://rapidsai.github.io/demos/datasets/mortgage-data and update the following paths accordingly
acq_data_path = "{0}/acq".format(data_dir) #"/rapids/data/mortgage/acq" acq_data_path = "{0}/acq".format(data_dir) #"/rapids/data/mortgage/acq"
perf_data_path = "{0}/perf".format(data_dir) #"/rapids/data/mortgage/perf" perf_data_path = "{0}/perf".format(data_dir) #"/rapids/data/mortgage/perf"
col_names_path = "{0}/names.csv".format(data_dir) # "/rapids/data/mortgage/names.csv" col_names_path = "{0}/names.csv".format(data_dir) # "/rapids/data/mortgage/names.csv"
start_year = 2000 start_year = 2000
#end_year = 2000 # end_year is inclusive -- converted to parameter
#part_count = 2 # the number of data files to train against -- converted to parameter
client.run(initialize_rmm_pool)
client client
print('--->>> Workers used: {0}'.format(client.ncores())) print(client.ncores())
# NOTE: The ETL calculates additional features which are then dropped before creating the XGBoost DMatrix.
# NOTE: The ETL calculates additional features which are then dropped before creating the XGBoost DMatrix. # This can be optimized to avoid calculating the dropped features.
# This can be optimized to avoid calculating the dropped features.
print("Reading ...") print("Reading ...")
t1 = datetime.datetime.now() t1 = datetime.datetime.now()
gpu_dfs = [] gpu_dfs = []
@@ -395,9 +414,14 @@ def main():
wait(gpu_dfs) wait(gpu_dfs)
t2 = datetime.datetime.now() t2 = datetime.datetime.now()
print("Reading time: {0}".format(str(t2-t1))) print("Reading time ...")
print('--->>> Number of data parts: {0}'.format(len(gpu_dfs))) print(t2-t1)
print('len(gpu_dfs) is {0}'.format(len(gpu_dfs)))
client.run(cudf._gdf.rmm_finalize)
client.run(initialize_rmm_no_pool)
client
print(client.ncores())
dxgb_gpu_params = { dxgb_gpu_params = {
'nround': 100, 'nround': 100,
'max_depth': 8, 'max_depth': 8,
@@ -414,7 +438,7 @@ def main():
'n_gpus': 1, 'n_gpus': 1,
'distributed_dask': True, 'distributed_dask': True,
'loss': 'ls', 'loss': 'ls',
'objective': 'reg:squarederror', 'objective': 'gpu:reg:linear',
'max_features': 'auto', 'max_features': 'auto',
'criterion': 'friedman_mse', 'criterion': 'friedman_mse',
'grow_policy': 'lossguide', 'grow_policy': 'lossguide',
@@ -422,13 +446,13 @@ def main():
} }
if cpu_predictor: if cpu_predictor:
print('\n---->>>> Training using CPUs <<<<----\n') print('Training using CPUs')
dxgb_gpu_params['predictor'] = 'cpu_predictor' dxgb_gpu_params['predictor'] = 'cpu_predictor'
dxgb_gpu_params['tree_method'] = 'hist' dxgb_gpu_params['tree_method'] = 'hist'
dxgb_gpu_params['objective'] = 'reg:linear' dxgb_gpu_params['objective'] = 'reg:linear'
else: else:
print('\n---->>>> Training using GPUs <<<<----\n') print('Training using GPUs')
print('Training parameters are {0}'.format(dxgb_gpu_params)) print('Training parameters are {0}'.format(dxgb_gpu_params))
@@ -457,13 +481,14 @@ def main():
gpu_dfs = [gpu_df.persist() for gpu_df in gpu_dfs] gpu_dfs = [gpu_df.persist() for gpu_df in gpu_dfs]
gc.collect() gc.collect()
wait(gpu_dfs) wait(gpu_dfs)
# TRAIN THE MODEL
labels = None labels = None
t1 = datetime.datetime.now() t1 = datetime.datetime.now()
bst = dxgb_gpu.train(client, dxgb_gpu_params, gpu_dfs, labels, num_boost_round=dxgb_gpu_params['nround']) bst = dxgb_gpu.train(client, dxgb_gpu_params, gpu_dfs, labels, num_boost_round=dxgb_gpu_params['nround'])
t2 = datetime.datetime.now() t2 = datetime.datetime.now()
print('\n---->>>> Training time: {0} <<<<----\n'.format(str(t2-t1))) print("Training time ...")
print(t2-t1)
print('str(bst) is {0}'.format(str(bst)))
print('Exiting script') print('Exiting script')
if __name__ == '__main__': if __name__ == '__main__':

View File

@@ -1,8 +1,8 @@
name: azure-ml-datadrift name: azure-ml-datadrift
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- azureml-datadrift - azureml-contrib-datadrift
- azureml-opendatasets - azureml-opendatasets
- lightgbm - lightgbm
- azureml-widgets - azureml-widgets

View File

@@ -1,58 +1,58 @@
import pickle import pickle
import json import json
import numpy import numpy
import azureml.train.automl import azureml.train.automl
from sklearn.externals import joblib from sklearn.externals import joblib
from sklearn.linear_model import Ridge from sklearn.linear_model import Ridge
from azureml.core.model import Model from azureml.core.model import Model
from azureml.core.run import Run from azureml.core.run import Run
from azureml.monitoring import ModelDataCollector from azureml.monitoring import ModelDataCollector
import time import time
import pandas as pd import pandas as pd
def init(): def init():
global model, inputs_dc, prediction_dc, feature_names, categorical_features global model, inputs_dc, prediction_dc, feature_names, categorical_features
print("Model is initialized" + time.strftime("%H:%M:%S")) print("Model is initialized" + time.strftime("%H:%M:%S"))
model_path = Model.get_model_path(model_name="driftmodel") model_path = Model.get_model_path(model_name="driftmodel")
model = joblib.load(model_path) model = joblib.load(model_path)
feature_names = ["usaf", "wban", "latitude", "longitude", "station_name", "p_k", feature_names = ["usaf", "wban", "latitude", "longitude", "station_name", "p_k",
"sine_weekofyear", "cosine_weekofyear", "sine_hourofday", "cosine_hourofday", "sine_weekofyear", "cosine_weekofyear", "sine_hourofday", "cosine_hourofday",
"temperature-7"] "temperature-7"]
categorical_features = ["usaf", "wban", "p_k", "station_name"] categorical_features = ["usaf", "wban", "p_k", "station_name"]
inputs_dc = ModelDataCollector(model_name="driftmodel", inputs_dc = ModelDataCollector(model_name="driftmodel",
identifier="inputs", identifier="inputs",
feature_names=feature_names) feature_names=feature_names)
prediction_dc = ModelDataCollector("driftmodel", prediction_dc = ModelDataCollector("driftmodel",
identifier="predictions", identifier="predictions",
feature_names=["temperature"]) feature_names=["temperature"])
def run(raw_data): def run(raw_data):
global inputs_dc, prediction_dc global inputs_dc, prediction_dc
try: try:
data = json.loads(raw_data)["data"] data = json.loads(raw_data)["data"]
data = pd.DataFrame(data) data = pd.DataFrame(data)
# Remove the categorical features as the model expects OHE values # Remove the categorical features as the model expects OHE values
input_data = data.drop(categorical_features, axis=1) input_data = data.drop(categorical_features, axis=1)
result = model.predict(input_data) result = model.predict(input_data)
# Collect the non-OHE dataframe # Collect the non-OHE dataframe
collected_df = data[feature_names] collected_df = data[feature_names]
inputs_dc.collect(collected_df.values) inputs_dc.collect(collected_df.values)
prediction_dc.collect(result) prediction_dc.collect(result)
return result.tolist() return result.tolist()
except Exception as e: except Exception as e:
error = str(e) error = str(e)
print(error + time.strftime("%H:%M:%S")) print(error + time.strftime("%H:%M:%S"))
return error return error

View File

@@ -8,7 +8,7 @@ As a pre-requisite, run the [configuration Notebook](../configuration.ipynb) not
* [train-on-local](./training/train-on-local): Learn how to submit a run to local computer and use Azure ML managed run configuration. * [train-on-local](./training/train-on-local): Learn how to submit a run to local computer and use Azure ML managed run configuration.
* [train-on-amlcompute](./training/train-on-amlcompute): Use a 1-n node Azure ML managed compute cluster for remote runs on Azure CPU or GPU infrastructure. * [train-on-amlcompute](./training/train-on-amlcompute): Use a 1-n node Azure ML managed compute cluster for remote runs on Azure CPU or GPU infrastructure.
* [train-on-remote-vm](./training/train-on-remote-vm): Use Data Science Virtual Machine as a target for remote runs. * [train-on-remote-vm](./training/train-on-remote-vm): Use Data Science Virtual Machine as a target for remote runs.
* [logging-api](./track-and-monitor-experiments/logging-api): Learn about the details of logging metrics to run history. * [logging-api](./training/logging-api): Learn about the details of logging metrics to run history.
* [register-model-create-image-deploy-service](./deployment/register-model-create-image-deploy-service): Learn about the details of model management. * [register-model-create-image-deploy-service](./deployment/register-model-create-image-deploy-service): Learn about the details of model management.
* [production-deploy-to-aks](./deployment/production-deploy-to-aks) Deploy a model to production at scale on Azure Kubernetes Service. * [production-deploy-to-aks](./deployment/production-deploy-to-aks) Deploy a model to production at scale on Azure Kubernetes Service.
* [enable-data-collection-for-models-in-aks](./deployment/enable-data-collection-for-models-in-aks) Learn about data collection APIs for deployed model. * [enable-data-collection-for-models-in-aks](./deployment/enable-data-collection-for-models-in-aks) Learn about data collection APIs for deployed model.

View File

@@ -1,299 +1,290 @@
# Table of Contents # Table of Contents
1. [Automated ML Introduction](#introduction) 1. [Automated ML Introduction](#introduction)
1. [Setup using Azure Notebooks](#jupyter) 1. [Setup using Azure Notebooks](#jupyter)
1. [Setup using Azure Databricks](#databricks) 1. [Setup using Azure Databricks](#databricks)
1. [Setup using a Local Conda environment](#localconda) 1. [Setup using a Local Conda environment](#localconda)
1. [Automated ML SDK Sample Notebooks](#samples) 1. [Automated ML SDK Sample Notebooks](#samples)
1. [Documentation](#documentation) 1. [Documentation](#documentation)
1. [Running using python command](#pythoncommand) 1. [Running using python command](#pythoncommand)
1. [Troubleshooting](#troubleshooting) 1. [Troubleshooting](#troubleshooting)
<a name="introduction"></a> <a name="introduction"></a>
# Automated ML introduction # Automated ML introduction
Automated machine learning (automated ML) builds high quality machine learning models for you by automating model and hyperparameter selection. Bring a labelled dataset that you want to build a model for, automated ML will give you a high quality machine learning model that you can use for predictions. Automated machine learning (automated ML) builds high quality machine learning models for you by automating model and hyperparameter selection. Bring a labelled dataset that you want to build a model for, automated ML will give you a high quality machine learning model that you can use for predictions.
If you are new to Data Science, automated ML will help you get jumpstarted by simplifying machine learning model building. It abstracts you from needing to perform model selection, hyperparameter selection and in one step creates a high quality trained model for you to use. If you are new to Data Science, automated ML will help you get jumpstarted by simplifying machine learning model building. It abstracts you from needing to perform model selection, hyperparameter selection and in one step creates a high quality trained model for you to use.
If you are an experienced data scientist, automated ML will help increase your productivity by intelligently performing the model and hyperparameter selection for your training and generates high quality models much quicker than manually specifying several combinations of the parameters and running training jobs. Automated ML provides visibility and access to all the training jobs and the performance characteristics of the models to help you further tune the pipeline if you desire. If you are an experienced data scientist, automated ML will help increase your productivity by intelligently performing the model and hyperparameter selection for your training and generates high quality models much quicker than manually specifying several combinations of the parameters and running training jobs. Automated ML provides visibility and access to all the training jobs and the performance characteristics of the models to help you further tune the pipeline if you desire.
Below are the three execution environments supported by automated ML. Below are the three execution environments supported by automated ML.
<a name="jupyter"></a> <a name="jupyter"></a>
## Setup using Azure Notebooks - Jupyter based notebooks in the Azure cloud ## Setup using Azure Notebooks - Jupyter based notebooks in the Azure cloud
1. [![Azure Notebooks](https://notebooks.azure.com/launch.png)](https://aka.ms/aml-clone-azure-notebooks) 1. [![Azure Notebooks](https://notebooks.azure.com/launch.png)](https://aka.ms/aml-clone-azure-notebooks)
[Import sample notebooks ](https://aka.ms/aml-clone-azure-notebooks) into Azure Notebooks. [Import sample notebooks ](https://aka.ms/aml-clone-azure-notebooks) into Azure Notebooks.
1. Follow the instructions in the [configuration](../../configuration.ipynb) notebook to create and connect to a workspace. 1. Follow the instructions in the [configuration](../../configuration.ipynb) notebook to create and connect to a workspace.
1. Open one of the sample notebooks. 1. Open one of the sample notebooks.
<a name="databricks"></a> <a name="databricks"></a>
## Setup using Azure Databricks ## Setup using Azure Databricks
**NOTE**: Please create your Azure Databricks cluster as v4.x (high concurrency preferred) with **Python 3** (dropdown). **NOTE**: Please create your Azure Databricks cluster as v4.x (high concurrency preferred) with **Python 3** (dropdown).
**NOTE**: You should at least have contributor access to your Azure subcription to run the notebook. **NOTE**: You should at least have contributor access to your Azure subcription to run the notebook.
- Please remove the previous SDK version if there is any and install the latest SDK by installing **azureml-sdk[automl_databricks]** as a PyPi library in Azure Databricks workspace. - Please remove the previous SDK version if there is any and install the latest SDK by installing **azureml-sdk[automl_databricks]** as a PyPi library in Azure Databricks workspace.
- You can find the detail Readme instructions at [GitHub](https://github.com/Azure/MachineLearningNotebooks/tree/master/how-to-use-azureml/azure-databricks). - You can find the detail Readme instructions at [GitHub](https://github.com/Azure/MachineLearningNotebooks/tree/master/how-to-use-azureml/azure-databricks).
- Download the sample notebook automl-databricks-local-01.ipynb from [GitHub](https://github.com/Azure/MachineLearningNotebooks/tree/master/how-to-use-azureml/azure-databricks) and import into the Azure databricks workspace. - Download the sample notebook automl-databricks-local-01.ipynb from [GitHub](https://github.com/Azure/MachineLearningNotebooks/tree/master/how-to-use-azureml/azure-databricks) and import into the Azure databricks workspace.
- Attach the notebook to the cluster. - Attach the notebook to the cluster.
<a name="localconda"></a> <a name="localconda"></a>
## Setup using a Local Conda environment ## Setup using a Local Conda environment
To run these notebook on your own notebook server, use these installation instructions. To run these notebook on your own notebook server, use these installation instructions.
The instructions below will install everything you need and then start a Jupyter notebook. The instructions below will install everything you need and then start a Jupyter notebook.
### 1. Install mini-conda from [here](https://conda.io/miniconda.html), choose 64-bit Python 3.7 or higher. ### 1. Install mini-conda from [here](https://conda.io/miniconda.html), choose 64-bit Python 3.7 or higher.
- **Note**: if you already have conda installed, you can keep using it but it should be version 4.4.10 or later (as shown by: conda -V). If you have a previous version installed, you can update it using the command: conda update conda. - **Note**: if you already have conda installed, you can keep using it but it should be version 4.4.10 or later (as shown by: conda -V). If you have a previous version installed, you can update it using the command: conda update conda.
There's no need to install mini-conda specifically. There's no need to install mini-conda specifically.
### 2. Downloading the sample notebooks ### 2. Downloading the sample notebooks
- Download the sample notebooks from [GitHub](https://github.com/Azure/MachineLearningNotebooks) as zip and extract the contents to a local directory. The automated ML sample notebooks are in the "automated-machine-learning" folder. - Download the sample notebooks from [GitHub](https://github.com/Azure/MachineLearningNotebooks) as zip and extract the contents to a local directory. The automated ML sample notebooks are in the "automated-machine-learning" folder.
### 3. Setup a new conda environment ### 3. Setup a new conda environment
The **automl_setup** script creates a new conda environment, installs the necessary packages, configures the widget and starts a jupyter notebook. It takes the conda environment name as an optional parameter. The default conda environment name is azure_automl. The exact command depends on the operating system. See the specific sections below for Windows, Mac and Linux. It can take about 10 minutes to execute. The **automl_setup** script creates a new conda environment, installs the necessary packages, configures the widget and starts a jupyter notebook. It takes the conda environment name as an optional parameter. The default conda environment name is azure_automl. The exact command depends on the operating system. See the specific sections below for Windows, Mac and Linux. It can take about 10 minutes to execute.
Packages installed by the **automl_setup** script: Packages installed by the **automl_setup** script:
<ul><li>python</li><li>nb_conda</li><li>matplotlib</li><li>numpy</li><li>cython</li><li>urllib3</li><li>scipy</li><li>scikit-learn</li><li>pandas</li><li>tensorflow</li><li>py-xgboost</li><li>azureml-sdk</li><li>azureml-widgets</li><li>pandas-ml</li></ul> <ul><li>python</li><li>nb_conda</li><li>matplotlib</li><li>numpy</li><li>cython</li><li>urllib3</li><li>scipy</li><li>scikit-learn</li><li>pandas</li><li>tensorflow</li><li>py-xgboost</li><li>azureml-sdk</li><li>azureml-widgets</li><li>pandas-ml</li></ul>
For more details refer to the [automl_env.yml](./automl_env.yml) For more details refer to the [automl_env.yml](./automl_env.yml)
## Windows ## Windows
Start an **Anaconda Prompt** window, cd to the **how-to-use-azureml/automated-machine-learning** folder where the sample notebooks were extracted and then run: Start an **Anaconda Prompt** window, cd to the **how-to-use-azureml/automated-machine-learning** folder where the sample notebooks were extracted and then run:
``` ```
automl_setup automl_setup
``` ```
## Mac ## Mac
Install "Command line developer tools" if it is not already installed (you can use the command: `xcode-select --install`). Install "Command line developer tools" if it is not already installed (you can use the command: `xcode-select --install`).
Start a Terminal windows, cd to the **how-to-use-azureml/automated-machine-learning** folder where the sample notebooks were extracted and then run: Start a Terminal windows, cd to the **how-to-use-azureml/automated-machine-learning** folder where the sample notebooks were extracted and then run:
``` ```
bash automl_setup_mac.sh bash automl_setup_mac.sh
``` ```
## Linux ## Linux
cd to the **how-to-use-azureml/automated-machine-learning** folder where the sample notebooks were extracted and then run: cd to the **how-to-use-azureml/automated-machine-learning** folder where the sample notebooks were extracted and then run:
``` ```
bash automl_setup_linux.sh bash automl_setup_linux.sh
``` ```
### 4. Running configuration.ipynb ### 4. Running configuration.ipynb
- Before running any samples you next need to run the configuration notebook. Click on [configuration](../../configuration.ipynb) notebook - Before running any samples you next need to run the configuration notebook. Click on [configuration](../../configuration.ipynb) notebook
- Execute the cells in the notebook to Register Machine Learning Services Resource Provider and create a workspace. (*instructions in notebook*) - Execute the cells in the notebook to Register Machine Learning Services Resource Provider and create a workspace. (*instructions in notebook*)
### 5. Running Samples ### 5. Running Samples
- Please make sure you use the Python [conda env:azure_automl] kernel when trying the sample Notebooks. - Please make sure you use the Python [conda env:azure_automl] kernel when trying the sample Notebooks.
- Follow the instructions in the individual notebooks to explore various features in automated ML. - Follow the instructions in the individual notebooks to explore various features in automated ML.
### 6. Starting jupyter notebook manually ### 6. Starting jupyter notebook manually
To start your Jupyter notebook manually, use: To start your Jupyter notebook manually, use:
``` ```
conda activate azure_automl conda activate azure_automl
jupyter notebook jupyter notebook
``` ```
or on Mac or Linux: or on Mac or Linux:
``` ```
source activate azure_automl source activate azure_automl
jupyter notebook jupyter notebook
``` ```
<a name="samples"></a> <a name="samples"></a>
# Automated ML SDK Sample Notebooks # Automated ML SDK Sample Notebooks
- [auto-ml-classification.ipynb](classification/auto-ml-classification.ipynb) - [auto-ml-classification.ipynb](classification/auto-ml-classification.ipynb)
- Dataset: scikit learn's [digit dataset](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html#sklearn.datasets.load_digits) - Dataset: scikit learn's [digit dataset](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html#sklearn.datasets.load_digits)
- Simple example of using automated ML for classification - Simple example of using automated ML for classification
- Uses local compute for training - Uses local compute for training
- [auto-ml-regression.ipynb](regression/auto-ml-regression.ipynb) - [auto-ml-regression.ipynb](regression/auto-ml-regression.ipynb)
- Dataset: scikit learn's [diabetes dataset](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_diabetes.html) - Dataset: scikit learn's [diabetes dataset](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_diabetes.html)
- Simple example of using automated ML for regression - Simple example of using automated ML for regression
- Uses local compute for training - Uses local compute for training
- [auto-ml-remote-amlcompute.ipynb](remote-amlcompute/auto-ml-remote-amlcompute.ipynb) - [auto-ml-remote-amlcompute.ipynb](remote-amlcompute/auto-ml-remote-amlcompute.ipynb)
- Dataset: scikit learn's [digit dataset](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html#sklearn.datasets.load_digits) - Dataset: scikit learn's [digit dataset](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html#sklearn.datasets.load_digits)
- Example of using automated ML for classification using remote AmlCompute for training - Example of using automated ML for classification using remote AmlCompute for training
- Parallel execution of iterations - Parallel execution of iterations
- Async tracking of progress - Async tracking of progress
- Cancelling individual iterations or entire run - Cancelling individual iterations or entire run
- Retrieving models for any iteration or logged metric - Retrieving models for any iteration or logged metric
- Specify automated ML settings as kwargs - Specify automated ML settings as kwargs
- [auto-ml-missing-data-blacklist-early-termination.ipynb](missing-data-blacklist-early-termination/auto-ml-missing-data-blacklist-early-termination.ipynb) - [auto-ml-missing-data-blacklist-early-termination.ipynb](missing-data-blacklist-early-termination/auto-ml-missing-data-blacklist-early-termination.ipynb)
- Dataset: scikit learn's [digit dataset](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html#sklearn.datasets.load_digits) - Dataset: scikit learn's [digit dataset](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html#sklearn.datasets.load_digits)
- Blacklist certain pipelines - Blacklist certain pipelines
- Specify a target metrics to indicate stopping criteria - Specify a target metrics to indicate stopping criteria
- Handling Missing Data in the input - Handling Missing Data in the input
- [auto-ml-sparse-data-train-test-split.ipynb](sparse-data-train-test-split/auto-ml-sparse-data-train-test-split.ipynb) - [auto-ml-sparse-data-train-test-split.ipynb](sparse-data-train-test-split/auto-ml-sparse-data-train-test-split.ipynb)
- Dataset: Scikit learn's [20newsgroup](http://scikit-learn.org/stable/datasets/twenty_newsgroups.html) - Dataset: Scikit learn's [20newsgroup](http://scikit-learn.org/stable/datasets/twenty_newsgroups.html)
- Handle sparse datasets - Handle sparse datasets
- Specify custom train and validation set - Specify custom train and validation set
- [auto-ml-exploring-previous-runs.ipynb](exploring-previous-runs/auto-ml-exploring-previous-runs.ipynb) - [auto-ml-exploring-previous-runs.ipynb](exploring-previous-runs/auto-ml-exploring-previous-runs.ipynb)
- List all projects for the workspace - List all projects for the workspace
- List all automated ML Runs for a given project - List all automated ML Runs for a given project
- Get details for a automated ML Run. (automated ML settings, run widget & all metrics) - Get details for a automated ML Run. (automated ML settings, run widget & all metrics)
- Download fitted pipeline for any iteration - Download fitted pipeline for any iteration
- [auto-ml-classification-with-deployment.ipynb](classification-with-deployment/auto-ml-classification-with-deployment.ipynb) - [auto-ml-classification-with-deployment.ipynb](classification-with-deployment/auto-ml-classification-with-deployment.ipynb)
- Dataset: scikit learn's [digit dataset](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html#sklearn.datasets.load_digits) - Dataset: scikit learn's [digit dataset](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html#sklearn.datasets.load_digits)
- Simple example of using automated ML for classification - Simple example of using automated ML for classification
- Registering the model - Registering the model
- Creating Image and creating aci service - Creating Image and creating aci service
- Testing the aci service - Testing the aci service
- [auto-ml-sample-weight.ipynb](sample-weight/auto-ml-sample-weight.ipynb) - [auto-ml-sample-weight.ipynb](sample-weight/auto-ml-sample-weight.ipynb)
- How to specifying sample_weight - How to specifying sample_weight
- The difference that it makes to test results - The difference that it makes to test results
- [auto-ml-subsampling-local.ipynb](subsampling/auto-ml-subsampling-local.ipynb) - [auto-ml-subsampling-local.ipynb](subsampling/auto-ml-subsampling-local.ipynb)
- How to enable subsampling - How to enable subsampling
- [auto-ml-dataset.ipynb](dataprep/auto-ml-dataset.ipynb) - [auto-ml-dataprep.ipynb](dataprep/auto-ml-dataprep.ipynb)
- Using Dataset for reading data - Using DataPrep for reading data
- [auto-ml-dataset-remote-execution.ipynb](dataprep-remote-execution/auto-ml-dataset-remote-execution.ipynb) - [auto-ml-dataprep-remote-execution.ipynb](dataprep-remote-execution/auto-ml-dataprep-remote-execution.ipynb)
- Using Dataset for reading data with remote execution - Using DataPrep for reading data with remote execution
- [auto-ml-classification-with-whitelisting.ipynb](classification-with-whitelisting/auto-ml-classification-with-whitelisting.ipynb) - [auto-ml-classification-with-whitelisting.ipynb](classification-with-whitelisting/auto-ml-classification-with-whitelisting.ipynb)
- Dataset: scikit learn's [digit dataset](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html#sklearn.datasets.load_digits) - Dataset: scikit learn's [digit dataset](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html#sklearn.datasets.load_digits)
- Simple example of using automated ML for classification with whitelisting tensorflow models. - Simple example of using automated ML for classification with whitelisting tensorflow models.
- Uses local compute for training - Uses local compute for training
- [auto-ml-forecasting-energy-demand.ipynb](forecasting-energy-demand/auto-ml-forecasting-energy-demand.ipynb) - [auto-ml-forecasting-energy-demand.ipynb](forecasting-energy-demand/auto-ml-forecasting-energy-demand.ipynb)
- Dataset: [NYC energy demand data](forecasting-a/nyc_energy.csv) - Dataset: [NYC energy demand data](forecasting-a/nyc_energy.csv)
- Example of using automated ML for training a forecasting model - Example of using automated ML for training a forecasting model
- [auto-ml-forecasting-orange-juice-sales.ipynb](forecasting-orange-juice-sales/auto-ml-forecasting-orange-juice-sales.ipynb) - [auto-ml-forecasting-orange-juice-sales.ipynb](forecasting-orange-juice-sales/auto-ml-forecasting-orange-juice-sales.ipynb)
- Dataset: [Dominick's grocery sales of orange juice](forecasting-b/dominicks_OJ.csv) - Dataset: [Dominick's grocery sales of orange juice](forecasting-b/dominicks_OJ.csv)
- Example of training an automated ML forecasting model on multiple time-series - Example of training an automated ML forecasting model on multiple time-series
- [auto-ml-classification-with-onnx.ipynb](classification-with-onnx/auto-ml-classification-with-onnx.ipynb) - [auto-ml-classification-with-onnx.ipynb](classification-with-onnx/auto-ml-classification-with-onnx.ipynb)
- Dataset: scikit learn's [iris dataset](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_iris.html) - Dataset: scikit learn's [digit dataset](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html#sklearn.datasets.load_digits)
- Simple example of using automated ML for classification with ONNX models - Simple example of using automated ML for classification with ONNX models
- Uses local compute for training - Uses local compute for training
- [auto-ml-remote-amlcompute-with-onnx.ipynb](remote-amlcompute-with-onnx/auto-ml-remote-amlcompute-with-onnx.ipynb) - [auto-ml-bank-marketing-subscribers-with-deployment.ipynb](bank-marketing-subscribers-with-deployment/auto-ml-bank-marketing-with-deployment.ipynb)
- Dataset: scikit learn's [iris dataset](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_iris.html) - Dataset: UCI's [bank marketing dataset](https://www.kaggle.com/janiobachmann/bank-marketing-dataset)
- Example of using automated ML for classification using remote AmlCompute for training - Simple example of using automated ML for classification to predict term deposit subscriptions for a bank
- Train the models with ONNX compatible config on - Uses azure compute for training
- Parallel execution of iterations
- Async tracking of progress - [auto-ml-creditcard-with-deployment.ipynb](credit-card-fraud-detection-with-deployment/auto-ml-creditcard-with-deployment.ipynb)
- Cancelling individual iterations or entire run - Dataset: Kaggle's [credit card fraud detection dataset](https://www.kaggle.com/mlg-ulb/creditcardfraud)
- Retrieving the ONNX models and do the inference with them - Simple example of using automated ML for classification to fraudulent credit card transactions
- Uses azure compute for training
- [auto-ml-bank-marketing-subscribers-with-deployment.ipynb](bank-marketing-subscribers-with-deployment/auto-ml-bank-marketing-with-deployment.ipynb)
- Dataset: UCI's [bank marketing dataset](https://www.kaggle.com/janiobachmann/bank-marketing-dataset) - [auto-ml-hardware-performance-with-deployment.ipynb](hardware-performance-prediction-with-deployment/auto-ml-hardware-performance-with-deployment.ipynb)
- Simple example of using automated ML for classification to predict term deposit subscriptions for a bank - Dataset: UCI's [computer hardware dataset](https://archive.ics.uci.edu/ml/datasets/Computer+Hardware)
- Uses azure compute for training - Simple example of using automated ML for regression to predict the performance of certain combinations of hardware components
- Uses azure compute for training
- [auto-ml-creditcard-with-deployment.ipynb](credit-card-fraud-detection-with-deployment/auto-ml-creditcard-with-deployment.ipynb)
- Dataset: Kaggle's [credit card fraud detection dataset](https://www.kaggle.com/mlg-ulb/creditcardfraud) - [auto-ml-concrete-strength-with-deployment.ipynb](predicting-concrete-strength-with-deployment/auto-ml-concrete-strength-with-deployment.ipynb)
- Simple example of using automated ML for classification to fraudulent credit card transactions - Dataset: UCI's [concrete compressive strength dataset](https://www.kaggle.com/pavanraj159/concrete-compressive-strength-data-set)
- Uses azure compute for training - Simple example of using automated ML for regression to predict the strength predict the compressive strength of concrete based off of different ingredient combinations and quantities of those ingredients
- Uses azure compute for training
- [auto-ml-hardware-performance-with-deployment.ipynb](hardware-performance-prediction-with-deployment/auto-ml-hardware-performance-with-deployment.ipynb)
- Dataset: UCI's [computer hardware dataset](https://archive.ics.uci.edu/ml/datasets/Computer+Hardware) <a name="documentation"></a>
- Simple example of using automated ML for regression to predict the performance of certain combinations of hardware components See [Configure automated machine learning experiments](https://docs.microsoft.com/azure/machine-learning/service/how-to-configure-auto-train) to learn how more about the the settings and features available for automated machine learning experiments.
- Uses azure compute for training
<a name="pythoncommand"></a>
- [auto-ml-concrete-strength-with-deployment.ipynb](predicting-concrete-strength-with-deployment/auto-ml-concrete-strength-with-deployment.ipynb) # Running using python command
- Dataset: UCI's [concrete compressive strength dataset](https://www.kaggle.com/pavanraj159/concrete-compressive-strength-data-set) Jupyter notebook provides a File / Download as / Python (.py) option for saving the notebook as a Python file.
- Simple example of using automated ML for regression to predict the strength predict the compressive strength of concrete based off of different ingredient combinations and quantities of those ingredients You can then run this file using the python command.
- Uses azure compute for training However, on Windows the file needs to be modified before it can be run.
The following condition must be added to the main code in the file:
<a name="documentation"></a>
See [Configure automated machine learning experiments](https://docs.microsoft.com/azure/machine-learning/service/how-to-configure-auto-train) to learn how more about the the settings and features available for automated machine learning experiments. if __name__ == "__main__":
<a name="pythoncommand"></a> The main code of the file must be indented so that it is under this condition.
# Running using python command
Jupyter notebook provides a File / Download as / Python (.py) option for saving the notebook as a Python file. <a name="troubleshooting"></a>
You can then run this file using the python command. # Troubleshooting
However, on Windows the file needs to be modified before it can be run. ## automl_setup fails
The following condition must be added to the main code in the file: 1. On Windows, make sure that you are running automl_setup from an Anconda Prompt window rather than a regular cmd window. You can launch the "Anaconda Prompt" window by hitting the Start button and typing "Anaconda Prompt". If you don't see the application "Anaconda Prompt", you might not have conda or mini conda installed. In that case, you can install it [here](https://conda.io/miniconda.html)
2. Check that you have conda 64-bit installed rather than 32-bit. You can check this with the command `conda info`. The `platform` should be `win-64` for Windows or `osx-64` for Mac.
if __name__ == "__main__": 3. Check that you have conda 4.4.10 or later. You can check the version with the command `conda -V`. If you have a previous version installed, you can update it using the command: `conda update conda`.
4. On Linux, if the error is `gcc: error trying to exec 'cc1plus': execvp: No such file or directory`, install build essentials using the command `sudo apt-get install build-essential`.
The main code of the file must be indented so that it is under this condition. 5. Pass a new name as the first parameter to automl_setup so that it creates a new conda environment. You can view existing conda environments using `conda env list` and remove them with `conda env remove -n <environmentname>`.
<a name="troubleshooting"></a> ## automl_setup_linux.sh fails
# Troubleshooting If automl_setup_linux.sh fails on Ubuntu Linux with the error: `unable to execute 'gcc': No such file or directory`
## automl_setup fails 1. Make sure that outbound ports 53 and 80 are enabled. On an Azure VM, you can do this from the Azure Portal by selecting the VM and clicking on Networking.
1. On Windows, make sure that you are running automl_setup from an Anconda Prompt window rather than a regular cmd window. You can launch the "Anaconda Prompt" window by hitting the Start button and typing "Anaconda Prompt". If you don't see the application "Anaconda Prompt", you might not have conda or mini conda installed. In that case, you can install it [here](https://conda.io/miniconda.html) 2. Run the command: `sudo apt-get update`
2. Check that you have conda 64-bit installed rather than 32-bit. You can check this with the command `conda info`. The `platform` should be `win-64` for Windows or `osx-64` for Mac. 3. Run the command: `sudo apt-get install build-essential --fix-missing`
3. Check that you have conda 4.4.10 or later. You can check the version with the command `conda -V`. If you have a previous version installed, you can update it using the command: `conda update conda`. 4. Run `automl_setup_linux.sh` again.
4. On Linux, if the error is `gcc: error trying to exec 'cc1plus': execvp: No such file or directory`, install build essentials using the command `sudo apt-get install build-essential`.
5. Pass a new name as the first parameter to automl_setup so that it creates a new conda environment. You can view existing conda environments using `conda env list` and remove them with `conda env remove -n <environmentname>`. ## configuration.ipynb fails
1) For local conda, make sure that you have susccessfully run automl_setup first.
## automl_setup_linux.sh fails 2) Check that the subscription_id is correct. You can find the subscription_id in the Azure Portal by selecting All Service and then Subscriptions. The characters "<" and ">" should not be included in the subscription_id value. For example, `subscription_id = "12345678-90ab-1234-5678-1234567890abcd"` has the valid format.
If automl_setup_linux.sh fails on Ubuntu Linux with the error: `unable to execute 'gcc': No such file or directory` 3) Check that you have Contributor or Owner access to the Subscription.
1. Make sure that outbound ports 53 and 80 are enabled. On an Azure VM, you can do this from the Azure Portal by selecting the VM and clicking on Networking. 4) Check that the region is one of the supported regions: `eastus2`, `eastus`, `westcentralus`, `southeastasia`, `westeurope`, `australiaeast`, `westus2`, `southcentralus`
2. Run the command: `sudo apt-get update` 5) Check that you have access to the region using the Azure Portal.
3. Run the command: `sudo apt-get install build-essential --fix-missing`
4. Run `automl_setup_linux.sh` again. ## workspace.from_config fails
If the call `ws = Workspace.from_config()` fails:
## configuration.ipynb fails 1) Make sure that you have run the `configuration.ipynb` notebook successfully.
1) For local conda, make sure that you have susccessfully run automl_setup first. 2) If you are running a notebook from a folder that is not under the folder where you ran `configuration.ipynb`, copy the folder aml_config and the file config.json that it contains to the new folder. Workspace.from_config reads the config.json for the notebook folder or it parent folder.
2) Check that the subscription_id is correct. You can find the subscription_id in the Azure Portal by selecting All Service and then Subscriptions. The characters "<" and ">" should not be included in the subscription_id value. For example, `subscription_id = "12345678-90ab-1234-5678-1234567890abcd"` has the valid format. 3) If you are switching to a new subscription, resource group, workspace or region, make sure that you run the `configuration.ipynb` notebook again. Changing config.json directly will only work if the workspace already exists in the specified resource group under the specified subscription.
3) Check that you have Contributor or Owner access to the Subscription. 4) If you want to change the region, please change the workspace, resource group or subscription. `Workspace.create` will not create or update a workspace if it already exists, even if the region specified is different.
4) Check that the region is one of the supported regions: `eastus2`, `eastus`, `westcentralus`, `southeastasia`, `westeurope`, `australiaeast`, `westus2`, `southcentralus`
5) Check that you have access to the region using the Azure Portal. ## Sample notebook fails
If a sample notebook fails with an error that property, method or library does not exist:
## workspace.from_config fails 1) Check that you have selected correct kernel in jupyter notebook. The kernel is displayed in the top right of the notebook page. It can be changed using the `Kernel | Change Kernel` menu option. For Azure Notebooks, it should be `Python 3.6`. For local conda environments, it should be the conda envioronment name that you specified in automl_setup. The default is azure_automl. Note that the kernel is saved as part of the notebook. So, if you switch to a new conda environment, you will have to select the new kernel in the notebook.
If the call `ws = Workspace.from_config()` fails: 2) Check that the notebook is for the SDK version that you are using. You can check the SDK version by executing `azureml.core.VERSION` in a jupyter notebook cell. You can download previous version of the sample notebooks from GitHub by clicking the `Branch` button, selecting the `Tags` tab and then selecting the version.
1) Make sure that you have run the `configuration.ipynb` notebook successfully.
2) If you are running a notebook from a folder that is not under the folder where you ran `configuration.ipynb`, copy the folder aml_config and the file config.json that it contains to the new folder. Workspace.from_config reads the config.json for the notebook folder or it parent folder. ## Numpy import fails on Windows
3) If you are switching to a new subscription, resource group, workspace or region, make sure that you run the `configuration.ipynb` notebook again. Changing config.json directly will only work if the workspace already exists in the specified resource group under the specified subscription. Some Windows environments see an error loading numpy with the latest Python version 3.6.8. If you see this issue, try with Python version 3.6.7.
4) If you want to change the region, please change the workspace, resource group or subscription. `Workspace.create` will not create or update a workspace if it already exists, even if the region specified is different.
## Numpy import fails
## Sample notebook fails Check the tensorflow version in the automated ml conda environment. Supported versions are < 1.13. Uninstall tensorflow from the environment if version is >= 1.13
If a sample notebook fails with an error that property, method or library does not exist: You may check the version of tensorflow and uninstall as follows
1) Check that you have selected correct kernel in jupyter notebook. The kernel is displayed in the top right of the notebook page. It can be changed using the `Kernel | Change Kernel` menu option. For Azure Notebooks, it should be `Python 3.6`. For local conda environments, it should be the conda envioronment name that you specified in automl_setup. The default is azure_automl. Note that the kernel is saved as part of the notebook. So, if you switch to a new conda environment, you will have to select the new kernel in the notebook. 1) start a command shell, activate conda environment where automated ml packages are installed
2) Check that the notebook is for the SDK version that you are using. You can check the SDK version by executing `azureml.core.VERSION` in a jupyter notebook cell. You can download previous version of the sample notebooks from GitHub by clicking the `Branch` button, selecting the `Tags` tab and then selecting the version. 2) enter `pip freeze` and look for `tensorflow` , if found, the version listed should be < 1.13
3) If the listed version is a not a supported version, `pip uninstall tensorflow` in the command shell and enter y for confirmation.
## Numpy import fails on Windows
Some Windows environments see an error loading numpy with the latest Python version 3.6.8. If you see this issue, try with Python version 3.6.7. ## Remote run: DsvmCompute.create fails
There are several reasons why the DsvmCompute.create can fail. The reason is usually in the error message but you have to look at the end of the error message for the detailed reason. Some common reasons are:
## Numpy import fails 1) `Compute name is invalid, it should start with a letter, be between 2 and 16 character, and only include letters (a-zA-Z), numbers (0-9) and \'-\'.` Note that underscore is not allowed in the name.
Check the tensorflow version in the automated ml conda environment. Supported versions are < 1.13. Uninstall tensorflow from the environment if version is >= 1.13 2) `The requested VM size xxxxx is not available in the current region.` You can select a different region or vm_size.
You may check the version of tensorflow and uninstall as follows
1) start a command shell, activate conda environment where automated ml packages are installed ## Remote run: Unable to establish SSH connection
2) enter `pip freeze` and look for `tensorflow` , if found, the version listed should be < 1.13 Automated ML uses the SSH protocol to communicate with remote DSVMs. This defaults to port 22. Possible causes for this error are:
3) If the listed version is a not a supported version, `pip uninstall tensorflow` in the command shell and enter y for confirmation. 1) The DSVM is not ready for SSH connections. When DSVM creation completes, the DSVM might still not be ready to acceept SSH connections. The sample notebooks have a one minute delay to allow for this.
2) Your Azure Subscription may restrict the IP address ranges that can access the DSVM on port 22. You can check this in the Azure Portal by selecting the Virtual Machine and then clicking Networking. The Virtual Machine name is the name that you provided in the notebook plus 10 alpha numeric characters to make the name unique. The Inbound Port Rules define what can access the VM on specific ports. Note that there is a priority priority order. So, a Deny entry with a low priority number will override a Allow entry with a higher priority number.
## Remote run: DsvmCompute.create fails
There are several reasons why the DsvmCompute.create can fail. The reason is usually in the error message but you have to look at the end of the error message for the detailed reason. Some common reasons are: ## Remote run: setup iteration fails
1) `Compute name is invalid, it should start with a letter, be between 2 and 16 character, and only include letters (a-zA-Z), numbers (0-9) and \'-\'.` Note that underscore is not allowed in the name. This is often an issue with the `get_data` method.
2) `The requested VM size xxxxx is not available in the current region.` You can select a different region or vm_size. 1) Check that the `get_data` method is valid by running it locally.
2) Make sure that `get_data` isn't referring to any local files. `get_data` is executed on the remote DSVM. So, it doesn't have direct access to local data files. Instead you can store the data files with DataStore. See [auto-ml-remote-execution-with-datastore.ipynb](remote-execution-with-datastore/auto-ml-remote-execution-with-datastore.ipynb)
## Remote run: Unable to establish SSH connection 3) You can get to the error log for the setup iteration by clicking the `Click here to see the run in Azure portal` link, click `Back to Experiment`, click on the highest run number and then click on Logs.
Automated ML uses the SSH protocol to communicate with remote DSVMs. This defaults to port 22. Possible causes for this error are:
1) The DSVM is not ready for SSH connections. When DSVM creation completes, the DSVM might still not be ready to acceept SSH connections. The sample notebooks have a one minute delay to allow for this. ## Remote run: disk full
2) Your Azure Subscription may restrict the IP address ranges that can access the DSVM on port 22. You can check this in the Azure Portal by selecting the Virtual Machine and then clicking Networking. The Virtual Machine name is the name that you provided in the notebook plus 10 alpha numeric characters to make the name unique. The Inbound Port Rules define what can access the VM on specific ports. Note that there is a priority priority order. So, a Deny entry with a low priority number will override a Allow entry with a higher priority number. Automated ML creates files under /tmp/azureml_runs for each iteration that it runs. It creates a folder with the iteration id. For example: AutoML_9a038a18-77cc-48f1-80fb-65abdbc33abe_93. Under this, there is a azureml-logs folder, which contains logs. If you run too many iterations on the same DSVM, these files can fill the disk.
You can delete the files under /tmp/azureml_runs or just delete the VM and create a new one.
## Remote run: setup iteration fails If your get_data downloads files, make sure the delete them or they can use disk space as well.
This is often an issue with the `get_data` method. When using DataStore, it is good to specify an absolute path for the files so that they are downloaded just once. If you specify a relative path, it will download a file for each iteration.
1) Check that the `get_data` method is valid by running it locally.
2) Make sure that `get_data` isn't referring to any local files. `get_data` is executed on the remote DSVM. So, it doesn't have direct access to local data files. Instead you can store the data files with DataStore. See [auto-ml-remote-execution-with-datastore.ipynb](remote-execution-with-datastore/auto-ml-remote-execution-with-datastore.ipynb) ## Remote run: Iterations fail and the log contains "MemoryError"
3) You can get to the error log for the setup iteration by clicking the `Click here to see the run in Azure portal` link, click `Back to Experiment`, click on the highest run number and then click on Logs. This can be caused by insufficient memory on the DSVM. Automated ML loads all training data into memory. So, the available memory should be more than the training data size.
If you are using a remote DSVM, memory is needed for each concurrent iteration. The max_concurrent_iterations setting specifies the maximum concurrent iterations. For example, if the training data size is 8Gb and max_concurrent_iterations is set to 10, the minimum memory required is at least 80Gb.
## Remote run: disk full To resolve this issue, allocate a DSVM with more memory or reduce the value specified for max_concurrent_iterations.
Automated ML creates files under /tmp/azureml_runs for each iteration that it runs. It creates a folder with the iteration id. For example: AutoML_9a038a18-77cc-48f1-80fb-65abdbc33abe_93. Under this, there is a azureml-logs folder, which contains logs. If you run too many iterations on the same DSVM, these files can fill the disk.
You can delete the files under /tmp/azureml_runs or just delete the VM and create a new one. ## Remote run: Iterations show as "Not Responding" in the RunDetails widget.
If your get_data downloads files, make sure the delete them or they can use disk space as well. This can be caused by too many concurrent iterations for a remote DSVM. Each concurrent iteration usually takes 100% of a core when it is running. Some iterations can use multiple cores. So, the max_concurrent_iterations setting should always be less than the number of cores of the DSVM.
When using DataStore, it is good to specify an absolute path for the files so that they are downloaded just once. If you specify a relative path, it will download a file for each iteration. To resolve this issue, try reducing the value specified for the max_concurrent_iterations setting.
## Remote run: Iterations fail and the log contains "MemoryError"
This can be caused by insufficient memory on the DSVM. Automated ML loads all training data into memory. So, the available memory should be more than the training data size.
If you are using a remote DSVM, memory is needed for each concurrent iteration. The max_concurrent_iterations setting specifies the maximum concurrent iterations. For example, if the training data size is 8Gb and max_concurrent_iterations is set to 10, the minimum memory required is at least 80Gb.
To resolve this issue, allocate a DSVM with more memory or reduce the value specified for max_concurrent_iterations.
## Remote run: Iterations show as "Not Responding" in the RunDetails widget.
This can be caused by too many concurrent iterations for a remote DSVM. Each concurrent iteration usually takes 100% of a core when it is running. Some iterations can use multiple cores. So, the max_concurrent_iterations setting should always be less than the number of cores of the DSVM.
To resolve this issue, try reducing the value specified for the max_concurrent_iterations setting.

View File

@@ -1,27 +1,22 @@
name: azure_automl 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 - pip
- python>=3.5.2,<3.6.8 - python>=3.5.2,<3.6.8
- nb_conda - nb_conda
- matplotlib==2.1.0 - matplotlib==2.1.0
- numpy>=1.16.0,<=1.16.2 - numpy>=1.11.0,<=1.16.2
- cython - cython
- urllib3<1.24 - urllib3<1.24
- scipy>=1.0.0,<=1.1.0 - scipy>=1.0.0,<=1.1.0
- scikit-learn>=0.19.0,<=0.20.3 - scikit-learn>=0.19.0,<=0.20.3
- pandas>=0.22.0,<=0.23.4 - pandas>=0.22.0,<=0.23.4
- py-xgboost<=0.80 - py-xgboost<=0.80
- pyarrow>=0.11.0
- conda-forge::fbprophet==0.5 - pip:
# Required packages for AzureML execution, history, and data preparation.
- pip: - azureml-sdk[automl,explain]
# Required packages for AzureML execution, history, and data preparation. - azureml-widgets
- azureml-defaults - pandas_ml
- azureml-train-automl
- azureml-widgets
- azureml-explain-model
- azureml-contrib-interpret
- pandas_ml

View File

@@ -1,28 +0,0 @@
name: azure_automl
dependencies:
# The python interpreter version.
# Currently Azure ML only supports 3.5.2 and later.
- pip
- nomkl
- python>=3.5.2,<3.6.8
- nb_conda
- matplotlib==2.1.0
- numpy>=1.16.0,<=1.16.2
- cython
- urllib3<1.24
- scipy>=1.0.0,<=1.1.0
- scikit-learn>=0.19.0,<=0.20.3
- pandas>=0.22.0,<0.23.0
- py-xgboost<=0.80
- pyarrow>=0.11.0
- conda-forge::fbprophet==0.5
- pip:
# Required packages for AzureML execution, history, and data preparation.
- azureml-defaults
- azureml-train-automl
- azureml-widgets
- azureml-explain-model
- azureml-contrib-interpret
- pandas_ml

View File

@@ -1,62 +1,62 @@
@echo off @echo off
set conda_env_name=%1 set conda_env_name=%1
set automl_env_file=%2 set automl_env_file=%2
set options=%3 set options=%3
set PIP_NO_WARN_SCRIPT_LOCATION=0 set PIP_NO_WARN_SCRIPT_LOCATION=0
IF "%conda_env_name%"=="" SET conda_env_name="azure_automl" IF "%conda_env_name%"=="" SET conda_env_name="azure_automl"
IF "%automl_env_file%"=="" SET automl_env_file="automl_env.yml" IF "%automl_env_file%"=="" SET automl_env_file="automl_env.yml"
IF NOT EXIST %automl_env_file% GOTO YmlMissing IF NOT EXIST %automl_env_file% GOTO YmlMissing
IF "%CONDA_EXE%"=="" GOTO CondaMissing IF "%CONDA_EXE%"=="" GOTO CondaMissing
call conda activate %conda_env_name% 2>nul: call conda activate %conda_env_name% 2>nul:
if not errorlevel 1 ( if not errorlevel 1 (
echo Upgrading azureml-sdk[automl,notebooks,explain] in existing conda environment %conda_env_name% echo Upgrading azureml-sdk[automl,notebooks,explain] in existing conda environment %conda_env_name%
call pip install --upgrade azureml-sdk[automl,notebooks,explain] call pip install --upgrade azureml-sdk[automl,notebooks,explain]
if errorlevel 1 goto ErrorExit if errorlevel 1 goto ErrorExit
) else ( ) else (
call conda env create -f %automl_env_file% -n %conda_env_name% call conda env create -f %automl_env_file% -n %conda_env_name%
) )
call conda activate %conda_env_name% 2>nul: call conda activate %conda_env_name% 2>nul:
if errorlevel 1 goto ErrorExit if errorlevel 1 goto ErrorExit
call python -m ipykernel install --user --name %conda_env_name% --display-name "Python (%conda_env_name%)" call python -m ipykernel install --user --name %conda_env_name% --display-name "Python (%conda_env_name%)"
REM azureml.widgets is now installed as part of the pip install under the conda env. REM azureml.widgets is now installed as part of the pip install under the conda env.
REM Removing the old user install so that the notebooks will use the latest widget. REM Removing the old user install so that the notebooks will use the latest widget.
call jupyter nbextension uninstall --user --py azureml.widgets call jupyter nbextension uninstall --user --py azureml.widgets
echo. echo.
echo. echo.
echo *************************************** echo ***************************************
echo * AutoML setup completed successfully * echo * AutoML setup completed successfully *
echo *************************************** echo ***************************************
IF NOT "%options%"=="nolaunch" ( IF NOT "%options%"=="nolaunch" (
echo. echo.
echo Starting jupyter notebook - please run the configuration notebook echo Starting jupyter notebook - please run the configuration notebook
echo. echo.
jupyter notebook --log-level=50 --notebook-dir='..\..' jupyter notebook --log-level=50 --notebook-dir='..\..'
) )
goto End goto End
:CondaMissing :CondaMissing
echo Please run this script from an Anaconda Prompt window. echo Please run this script from an Anaconda Prompt window.
echo You can start an Anaconda Prompt window by echo You can start an Anaconda Prompt window by
echo typing Anaconda Prompt on the Start menu. echo typing Anaconda Prompt on the Start menu.
echo If you don't see the Anaconda Prompt app, install Miniconda. echo If you don't see the Anaconda Prompt app, install Miniconda.
echo If you are running an older version of Miniconda or Anaconda, echo If you are running an older version of Miniconda or Anaconda,
echo you can upgrade using the command: conda update conda echo you can upgrade using the command: conda update conda
goto End goto End
:YmlMissing :YmlMissing
echo File %automl_env_file% not found. echo File %automl_env_file% not found.
:ErrorExit :ErrorExit
echo Install failed echo Install failed
:End :End

View File

@@ -1,52 +1,52 @@
#!/bin/bash #!/bin/bash
CONDA_ENV_NAME=$1 CONDA_ENV_NAME=$1
AUTOML_ENV_FILE=$2 AUTOML_ENV_FILE=$2
OPTIONS=$3 OPTIONS=$3
PIP_NO_WARN_SCRIPT_LOCATION=0 PIP_NO_WARN_SCRIPT_LOCATION=0
if [ "$CONDA_ENV_NAME" == "" ] if [ "$CONDA_ENV_NAME" == "" ]
then then
CONDA_ENV_NAME="azure_automl" CONDA_ENV_NAME="azure_automl"
fi fi
if [ "$AUTOML_ENV_FILE" == "" ] if [ "$AUTOML_ENV_FILE" == "" ]
then then
AUTOML_ENV_FILE="automl_env.yml" AUTOML_ENV_FILE="automl_env.yml"
fi fi
if [ ! -f $AUTOML_ENV_FILE ]; then if [ ! -f $AUTOML_ENV_FILE ]; then
echo "File $AUTOML_ENV_FILE not found" echo "File $AUTOML_ENV_FILE not found"
exit 1 exit 1
fi fi
if source activate $CONDA_ENV_NAME 2> /dev/null if source activate $CONDA_ENV_NAME 2> /dev/null
then then
echo "Upgrading azureml-sdk[automl,notebooks,explain] in existing conda environment" $CONDA_ENV_NAME echo "Upgrading azureml-sdk[automl,notebooks,explain] in existing conda environment" $CONDA_ENV_NAME
pip install --upgrade azureml-sdk[automl,notebooks,explain] && pip install --upgrade azureml-sdk[automl,notebooks,explain] &&
jupyter nbextension uninstall --user --py azureml.widgets jupyter nbextension uninstall --user --py azureml.widgets
else else
conda env create -f $AUTOML_ENV_FILE -n $CONDA_ENV_NAME && conda env create -f $AUTOML_ENV_FILE -n $CONDA_ENV_NAME &&
source activate $CONDA_ENV_NAME && source activate $CONDA_ENV_NAME &&
python -m ipykernel install --user --name $CONDA_ENV_NAME --display-name "Python ($CONDA_ENV_NAME)" && python -m ipykernel install --user --name $CONDA_ENV_NAME --display-name "Python ($CONDA_ENV_NAME)" &&
jupyter nbextension uninstall --user --py azureml.widgets && jupyter nbextension uninstall --user --py azureml.widgets &&
echo "" && echo "" &&
echo "" && echo "" &&
echo "***************************************" && echo "***************************************" &&
echo "* AutoML setup completed successfully *" && echo "* AutoML setup completed successfully *" &&
echo "***************************************" && echo "***************************************" &&
if [ "$OPTIONS" != "nolaunch" ] if [ "$OPTIONS" != "nolaunch" ]
then then
echo "" && echo "" &&
echo "Starting jupyter notebook - please run the configuration notebook" && echo "Starting jupyter notebook - please run the configuration notebook" &&
echo "" && echo "" &&
jupyter notebook --log-level=50 --notebook-dir '../..' jupyter notebook --log-level=50 --notebook-dir '../..'
fi fi
fi fi
if [ $? -gt 0 ] if [ $? -gt 0 ]
then then
echo "Installation failed" echo "Installation failed"
fi fi

View File

@@ -1,54 +1,54 @@
#!/bin/bash #!/bin/bash
CONDA_ENV_NAME=$1 CONDA_ENV_NAME=$1
AUTOML_ENV_FILE=$2 AUTOML_ENV_FILE=$2
OPTIONS=$3 OPTIONS=$3
PIP_NO_WARN_SCRIPT_LOCATION=0 PIP_NO_WARN_SCRIPT_LOCATION=0
if [ "$CONDA_ENV_NAME" == "" ] if [ "$CONDA_ENV_NAME" == "" ]
then then
CONDA_ENV_NAME="azure_automl" CONDA_ENV_NAME="azure_automl"
fi fi
if [ "$AUTOML_ENV_FILE" == "" ] if [ "$AUTOML_ENV_FILE" == "" ]
then then
AUTOML_ENV_FILE="automl_env_mac.yml" AUTOML_ENV_FILE="automl_env_mac.yml"
fi fi
if [ ! -f $AUTOML_ENV_FILE ]; then if [ ! -f $AUTOML_ENV_FILE ]; then
echo "File $AUTOML_ENV_FILE not found" echo "File $AUTOML_ENV_FILE not found"
exit 1 exit 1
fi fi
if source activate $CONDA_ENV_NAME 2> /dev/null if source activate $CONDA_ENV_NAME 2> /dev/null
then then
echo "Upgrading azureml-sdk[automl,notebooks,explain] in existing conda environment" $CONDA_ENV_NAME echo "Upgrading azureml-sdk[automl,notebooks,explain] in existing conda environment" $CONDA_ENV_NAME
pip install --upgrade azureml-sdk[automl,notebooks,explain] && pip install --upgrade azureml-sdk[automl,notebooks,explain] &&
jupyter nbextension uninstall --user --py azureml.widgets jupyter nbextension uninstall --user --py azureml.widgets
else else
conda env create -f $AUTOML_ENV_FILE -n $CONDA_ENV_NAME && conda env create -f $AUTOML_ENV_FILE -n $CONDA_ENV_NAME &&
source activate $CONDA_ENV_NAME && source activate $CONDA_ENV_NAME &&
conda install lightgbm -c conda-forge -y && conda install lightgbm -c conda-forge -y &&
python -m ipykernel install --user --name $CONDA_ENV_NAME --display-name "Python ($CONDA_ENV_NAME)" && python -m ipykernel install --user --name $CONDA_ENV_NAME --display-name "Python ($CONDA_ENV_NAME)" &&
jupyter nbextension uninstall --user --py azureml.widgets && jupyter nbextension uninstall --user --py azureml.widgets &&
echo "" && echo "" &&
echo "" && echo "" &&
echo "***************************************" && echo "***************************************" &&
echo "* AutoML setup completed successfully *" && echo "* AutoML setup completed successfully *" &&
echo "***************************************" && echo "***************************************" &&
if [ "$OPTIONS" != "nolaunch" ] if [ "$OPTIONS" != "nolaunch" ]
then then
echo "" && echo "" &&
echo "Starting jupyter notebook - please run the configuration notebook" && echo "Starting jupyter notebook - please run the configuration notebook" &&
echo "" && echo "" &&
jupyter notebook --log-level=50 --notebook-dir '../..' jupyter notebook --log-level=50 --notebook-dir '../..'
fi fi
fi fi
if [ $? -gt 0 ] if [ $? -gt 0 ]
then then
echo "Installation failed" echo "Installation failed"
fi fi

View File

@@ -1,11 +1,8 @@
name: auto-ml-classification-bank-marketing name: auto-ml-classification-bank-marketing
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- interpret - azureml-train-automl
- azureml-defaults - azureml-widgets
- azureml-explain-model - matplotlib
- azureml-train-automl - pandas_ml
- azureml-widgets
- matplotlib
- pandas_ml

View File

@@ -1,11 +1,8 @@
name: auto-ml-classification-credit-card-fraud name: auto-ml-classification-credit-card-fraud
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- interpret - azureml-train-automl
- azureml-defaults - azureml-widgets
- azureml-explain-model - matplotlib
- azureml-train-automl - pandas_ml
- azureml-widgets
- matplotlib
- pandas_ml

View File

@@ -1,479 +1,510 @@
{ {
"cells": [ "metadata": {
{ "kernelspec": {
"cell_type": "markdown", "display_name": "Python 3.6",
"metadata": {}, "name": "python36",
"source": [ "language": "python"
"Copyright (c) Microsoft Corporation. All rights reserved.\n", },
"\n", "authors": [
"Licensed under the MIT License." {
] "name": "savitam"
}, }
{ ],
"cell_type": "markdown", "language_info": {
"metadata": {}, "mimetype": "text/x-python",
"source": [ "codemirror_mode": {
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/classification-with-deployment/auto-ml-classification-with-deployment.png)" "name": "ipython",
] "version": 3
}, },
{ "pygments_lexer": "ipython3",
"cell_type": "markdown", "name": "python",
"metadata": {}, "file_extension": ".py",
"source": [ "nbconvert_exporter": "python",
"# Automated Machine Learning\n", "version": "3.6.6"
"_**Classification with Deployment**_\n", }
"\n", },
"## Contents\n", "nbformat": 4,
"1. [Introduction](#Introduction)\n", "cells": [
"1. [Setup](#Setup)\n", {
"1. [Train](#Train)\n", "metadata": {},
"1. [Deploy](#Deploy)\n", "source": [
"1. [Test](#Test)" "Copyright (c) Microsoft Corporation. All rights reserved.\n",
] "\n",
}, "Licensed under the MIT License."
{ ],
"cell_type": "markdown", "cell_type": "markdown"
"metadata": {}, },
"source": [ {
"## Introduction\n", "metadata": {},
"\n", "source": [
"In this example we use the scikit learn's [digit dataset](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html) to showcase how you can use AutoML for a simple classification problem and deploy it to an Azure Container Instance (ACI).\n", "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/classification-with-deployment/auto-ml-classification-with-deployment.png)"
"\n", ],
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n", "cell_type": "markdown"
"\n", },
"In this notebook you will learn how to:\n", {
"1. Create an experiment using an existing workspace.\n", "metadata": {},
"2. Configure AutoML using `AutoMLConfig`.\n", "source": [
"3. Train the model using local compute.\n", "# Automated Machine Learning\n",
"4. Explore the results.\n", "_**Classification with Deployment**_\n",
"5. Register the model.\n", "\n",
"6. Create a container image.\n", "## Contents\n",
"7. Create an Azure Container Instance (ACI) service.\n", "1. [Introduction](#Introduction)\n",
"8. Test the ACI service." "1. [Setup](#Setup)\n",
] "1. [Train](#Train)\n",
}, "1. [Deploy](#Deploy)\n",
{ "1. [Test](#Test)"
"cell_type": "markdown", ],
"metadata": {}, "cell_type": "markdown"
"source": [ },
"## Setup\n", {
"\n", "metadata": {},
"As part of the setup you have already created an Azure ML `Workspace` object. For AutoML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments." "source": [
] "## Introduction\n",
}, "\n",
{ "In this example we use the scikit learn's [digit dataset](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html) to showcase how you can use AutoML for a simple classification problem and deploy it to an Azure Container Instance (ACI).\n",
"cell_type": "code", "\n",
"execution_count": null, "Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
"metadata": {}, "\n",
"outputs": [], "In this notebook you will learn how to:\n",
"source": [ "1. Create an experiment using an existing workspace.\n",
"import json\n", "2. Configure AutoML using `AutoMLConfig`.\n",
"import logging\n", "3. Train the model using local compute.\n",
"\n", "4. Explore the results.\n",
"from matplotlib import pyplot as plt\n", "5. Register the model.\n",
"import numpy as np\n", "6. Create a container image.\n",
"import pandas as pd\n", "7. Create an Azure Container Instance (ACI) service.\n",
"from sklearn import datasets\n", "8. Test the ACI service."
"\n", ],
"import azureml.core\n", "cell_type": "markdown"
"from azureml.core.experiment import Experiment\n", },
"from azureml.core.workspace import Workspace\n", {
"from azureml.train.automl import AutoMLConfig\n", "metadata": {},
"from azureml.train.automl.run import AutoMLRun" "source": [
] "## Setup\n",
}, "\n",
{ "As part of the setup you have already created an Azure ML `Workspace` object. For AutoML 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, "cell_type": "markdown"
"metadata": {}, },
"outputs": [], {
"source": [ "metadata": {},
"ws = Workspace.from_config()\n", "outputs": [],
"\n", "execution_count": null,
"# choose a name for experiment\n", "source": [
"experiment_name = 'automl-classification-deployment'\n", "import json\n",
"\n", "import logging\n",
"experiment=Experiment(ws, experiment_name)\n", "\n",
"\n", "from matplotlib import pyplot as plt\n",
"output = {}\n", "import numpy as np\n",
"output['SDK version'] = azureml.core.VERSION\n", "import pandas as pd\n",
"output['Subscription ID'] = ws.subscription_id\n", "from sklearn import datasets\n",
"output['Workspace'] = ws.name\n", "\n",
"output['Resource Group'] = ws.resource_group\n", "import azureml.core\n",
"output['Location'] = ws.location\n", "from azureml.core.experiment import Experiment\n",
"output['Experiment Name'] = experiment.name\n", "from azureml.core.workspace import Workspace\n",
"pd.set_option('display.max_colwidth', -1)\n", "from azureml.train.automl import AutoMLConfig\n",
"outputDf = pd.DataFrame(data = output, index = [''])\n", "from azureml.train.automl.run import AutoMLRun"
"outputDf.T" ],
] "cell_type": "code"
}, },
{ {
"cell_type": "markdown", "metadata": {},
"metadata": {}, "outputs": [],
"source": [ "execution_count": null,
"## Train\n", "source": [
"\n", "ws = Workspace.from_config()\n",
"Instantiate a AutoMLConfig object. This defines the settings and data used to run the experiment.\n", "\n",
"\n", "# choose a name for experiment\n",
"|Property|Description|\n", "experiment_name = 'automl-classification-deployment'\n",
"|-|-|\n", "# project folder\n",
"|**task**|classification or regression|\n", "project_folder = './sample_projects/automl-classification-deployment'\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", "\n",
"|**iteration_timeout_minutes**|Time limit in minutes for each iteration.|\n", "experiment=Experiment(ws, experiment_name)\n",
"|**iterations**|Number of iterations. In each iteration AutoML trains a specific pipeline with the data.|\n", "\n",
"|**n_cross_validations**|Number of cross validation splits.|\n", "output = {}\n",
"|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n", "output['SDK version'] = azureml.core.VERSION\n",
"|**y**|(sparse) array-like, shape = [n_samples, ], Multi-class targets.|" "output['Subscription ID'] = ws.subscription_id\n",
] "output['Workspace'] = ws.name\n",
}, "output['Resource Group'] = ws.resource_group\n",
{ "output['Location'] = ws.location\n",
"cell_type": "code", "output['Project Directory'] = project_folder\n",
"execution_count": null, "output['Experiment Name'] = experiment.name\n",
"metadata": {}, "pd.set_option('display.max_colwidth', -1)\n",
"outputs": [], "outputDf = pd.DataFrame(data = output, index = [''])\n",
"source": [ "outputDf.T"
"digits = datasets.load_digits()\n", ],
"X_train = digits.data[10:,:]\n", "cell_type": "code"
"y_train = digits.target[10:]\n", },
"\n", {
"automl_config = AutoMLConfig(task = 'classification',\n", "metadata": {},
" name = experiment_name,\n", "source": [
" debug_log = 'automl_errors.log',\n", "## Train\n",
" primary_metric = 'AUC_weighted',\n", "\n",
" iteration_timeout_minutes = 20,\n", "Instantiate a AutoMLConfig object. This defines the settings and data used to run the experiment.\n",
" iterations = 10,\n", "\n",
" verbosity = logging.INFO,\n", "|Property|Description|\n",
" X = X_train, \n", "|-|-|\n",
" y = y_train)" "|**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",
}, "|**iteration_timeout_minutes**|Time limit in minutes for each iteration.|\n",
{ "|**iterations**|Number of iterations. In each iteration AutoML trains a specific pipeline with the data.|\n",
"cell_type": "markdown", "|**n_cross_validations**|Number of cross validation splits.|\n",
"metadata": {}, "|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n",
"source": [ "|**y**|(sparse) array-like, shape = [n_samples, ], Multi-class targets.|\n",
"Call the `submit` method on the experiment object and pass the run configuration. Execution of local runs is synchronous. Depending on the data and the number of iterations this can run for a while.\n", "|**path**|Relative path to the project folder. AutoML stores configuration files for the experiment under this folder. You can specify a new empty folder.|"
"In this example, we specify `show_output = True` to print currently running iterations to the console." ],
] "cell_type": "markdown"
}, },
{ {
"cell_type": "code", "metadata": {},
"execution_count": null, "outputs": [],
"metadata": {}, "execution_count": null,
"outputs": [], "source": [
"source": [ "digits = datasets.load_digits()\n",
"local_run = experiment.submit(automl_config, show_output = True)" "X_train = digits.data[10:,:]\n",
] "y_train = digits.target[10:]\n",
}, "\n",
{ "automl_config = AutoMLConfig(task = 'classification',\n",
"cell_type": "code", " name = experiment_name,\n",
"execution_count": null, " debug_log = 'automl_errors.log',\n",
"metadata": {}, " primary_metric = 'AUC_weighted',\n",
"outputs": [], " iteration_timeout_minutes = 20,\n",
"source": [ " iterations = 10,\n",
"local_run" " verbosity = logging.INFO,\n",
] " X = X_train, \n",
}, " y = y_train,\n",
{ " path = project_folder)"
"cell_type": "markdown", ],
"metadata": {}, "cell_type": "code"
"source": [ },
"## Deploy\n", {
"\n", "metadata": {},
"### Retrieve the Best Model\n", "source": [
"\n", "Call the `submit` method on the experiment object and pass the run configuration. Execution of local runs is synchronous. Depending on the data and the number of iterations this can run for a while.\n",
"Below we select the best pipeline from our iterations. The `get_output` method on `automl_classifier` returns the best 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*." "In this example, we specify `show_output = True` to print currently running iterations to the console."
] ],
}, "cell_type": "markdown"
{ },
"cell_type": "code", {
"execution_count": null, "metadata": {},
"metadata": {}, "outputs": [],
"outputs": [], "execution_count": null,
"source": [ "source": [
"best_run, fitted_model = local_run.get_output()" "local_run = experiment.submit(automl_config, show_output = True)"
] ],
}, "cell_type": "code"
{ },
"cell_type": "markdown", {
"metadata": {}, "metadata": {},
"source": [ "outputs": [],
"### Register the Fitted Model for Deployment\n", "execution_count": null,
"If neither `metric` nor `iteration` are specified in the `register_model` call, the iteration with the best primary metric is registered." "source": [
] "local_run"
}, ],
{ "cell_type": "code"
"cell_type": "code", },
"execution_count": null, {
"metadata": {}, "metadata": {},
"outputs": [], "source": [
"source": [ "## Deploy\n",
"description = 'AutoML Model'\n", "\n",
"tags = None\n", "### Retrieve the Best Model\n",
"model = local_run.register_model(description = description, tags = tags)\n", "\n",
"\n", "Below we select the best pipeline from our iterations. The `get_output` method on `automl_classifier` returns the best 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*."
"print(local_run.model_id) # This will be written to the script file later in the notebook." ],
] "cell_type": "markdown"
}, },
{ {
"cell_type": "markdown", "metadata": {},
"metadata": {}, "outputs": [],
"source": [ "execution_count": null,
"### Create Scoring Script" "source": [
] "best_run, fitted_model = local_run.get_output()"
}, ],
{ "cell_type": "code"
"cell_type": "code", },
"execution_count": null, {
"metadata": {}, "metadata": {},
"outputs": [], "source": [
"source": [ "### Register the Fitted Model for Deployment\n",
"%%writefile score.py\n", "If neither `metric` nor `iteration` are specified in the `register_model` call, the iteration with the best primary metric is registered."
"import pickle\n", ],
"import json\n", "cell_type": "markdown"
"import numpy\n", },
"import azureml.train.automl\n", {
"from sklearn.externals import joblib\n", "metadata": {},
"from azureml.core.model import Model\n", "outputs": [],
"\n", "execution_count": null,
"\n", "source": [
"def init():\n", "description = 'AutoML Model'\n",
" global model\n", "tags = None\n",
" model_path = Model.get_model_path(model_name = '<<modelid>>') # this name is model.id of model that we want to deploy\n", "model = local_run.register_model(description = description, tags = tags)\n",
" # deserialize the model file back into a sklearn model\n", "\n",
" model = joblib.load(model_path)\n", "print(local_run.model_id) # This will be written to the script file later in the notebook."
"\n", ],
"def run(rawdata):\n", "cell_type": "code"
" try:\n", },
" data = json.loads(rawdata)['data']\n", {
" data = numpy.array(data)\n", "metadata": {},
" result = model.predict(data)\n", "source": [
" except Exception as e:\n", "### Create Scoring Script"
" result = str(e)\n", ],
" return json.dumps({\"error\": result})\n", "cell_type": "markdown"
" return json.dumps({\"result\":result.tolist()})" },
] {
}, "metadata": {},
{ "outputs": [],
"cell_type": "markdown", "execution_count": null,
"metadata": {}, "source": [
"source": [ "%%writefile score.py\n",
"### Create a YAML File for the Environment" "import pickle\n",
] "import json\n",
}, "import numpy\n",
{ "import azureml.train.automl\n",
"cell_type": "markdown", "from sklearn.externals import joblib\n",
"metadata": {}, "from azureml.core.model import Model\n",
"source": [ "\n",
"To ensure the fit results are consistent with the training results, the SDK dependency versions need to be the same as the environment that trains the model. The following cells create a file, myenv.yml, which specifies the dependencies from the run." "\n",
] "def init():\n",
}, " global model\n",
{ " model_path = Model.get_model_path(model_name = '<<modelid>>') # this name is model.id of model that we want to deploy\n",
"cell_type": "code", " # deserialize the model file back into a sklearn model\n",
"execution_count": null, " model = joblib.load(model_path)\n",
"metadata": {}, "\n",
"outputs": [], "def run(rawdata):\n",
"source": [ " try:\n",
"experiment = Experiment(ws, experiment_name)\n", " data = json.loads(rawdata)['data']\n",
"ml_run = AutoMLRun(experiment = experiment, run_id = local_run.id)" " data = numpy.array(data)\n",
] " result = model.predict(data)\n",
}, " except Exception as e:\n",
{ " result = str(e)\n",
"cell_type": "code", " return json.dumps({\"error\": result})\n",
"execution_count": null, " return json.dumps({\"result\":result.tolist()})"
"metadata": {}, ],
"outputs": [], "cell_type": "code"
"source": [ },
"dependencies = ml_run.get_run_sdk_dependencies(iteration = 7)" {
] "metadata": {},
}, "source": [
{ "### Create a YAML File for the Environment"
"cell_type": "code", ],
"execution_count": null, "cell_type": "markdown"
"metadata": {}, },
"outputs": [], {
"source": [ "metadata": {},
"for p in ['azureml-train-automl', 'azureml-core']:\n", "source": [
" print('{}\\t{}'.format(p, dependencies[p]))" "To ensure the fit results are consistent with the training results, the SDK dependency versions need to be the same as the environment that trains the model. The following cells create a file, myenv.yml, which specifies the dependencies from the run."
] ],
}, "cell_type": "markdown"
{ },
"cell_type": "code", {
"execution_count": null, "metadata": {},
"metadata": {}, "outputs": [],
"outputs": [], "execution_count": null,
"source": [ "source": [
"from azureml.core.conda_dependencies import CondaDependencies\n", "experiment = Experiment(ws, experiment_name)\n",
"\n", "ml_run = AutoMLRun(experiment = experiment, run_id = local_run.id)"
"myenv = CondaDependencies.create(conda_packages=['numpy','scikit-learn','py-xgboost<=0.80'],\n", ],
" pip_packages=['azureml-defaults','azureml-train-automl'])\n", "cell_type": "code"
"\n", },
"conda_env_file_name = 'myenv.yml'\n", {
"myenv.save_to_file('.', conda_env_file_name)" "metadata": {},
] "outputs": [],
}, "execution_count": null,
{ "source": [
"cell_type": "code", "dependencies = ml_run.get_run_sdk_dependencies(iteration = 7)"
"execution_count": null, ],
"metadata": {}, "cell_type": "code"
"outputs": [], },
"source": [ {
"# Substitute the actual version number in the environment file.\n", "metadata": {},
"# This is not strictly needed in this notebook because the model should have been generated using the current SDK version.\n", "outputs": [],
"# However, we include this in case this code is used on an experiment from a previous SDK version.\n", "execution_count": null,
"\n", "source": [
"with open(conda_env_file_name, 'r') as cefr:\n", "for p in ['azureml-train-automl', 'azureml-sdk', 'azureml-core']:\n",
" content = cefr.read()\n", " print('{}\\t{}'.format(p, dependencies[p]))"
"\n", ],
"with open(conda_env_file_name, 'w') as cefw:\n", "cell_type": "code"
" cefw.write(content.replace(azureml.core.VERSION, dependencies['azureml-train-automl']))\n", },
"\n", {
"# Substitute the actual model id in the script file.\n", "metadata": {},
"\n", "outputs": [],
"script_file_name = 'score.py'\n", "execution_count": null,
"\n", "source": [
"with open(script_file_name, 'r') as cefr:\n", "from azureml.core.conda_dependencies import CondaDependencies\n",
" content = cefr.read()\n", "\n",
"\n", "myenv = CondaDependencies.create(conda_packages=['numpy','scikit-learn','py-xgboost<=0.80'],\n",
"with open(script_file_name, 'w') as cefw:\n", " pip_packages=['azureml-sdk[automl]'])\n",
" cefw.write(content.replace('<<modelid>>', local_run.model_id))" "\n",
] "conda_env_file_name = 'myenv.yml'\n",
}, "myenv.save_to_file('.', conda_env_file_name)"
{ ],
"cell_type": "markdown", "cell_type": "code"
"metadata": {}, },
"source": [ {
"### Deploy the model as a Web Service on Azure Container Instance\n", "metadata": {},
"\n", "outputs": [],
"Create the configuration needed for deploying the model as a web service service." "execution_count": null,
] "source": [
}, "# Substitute the actual version number in the environment file.\n",
{ "# This is not strictly needed in this notebook because the model should have been generated using the current SDK version.\n",
"cell_type": "code", "# However, we include this in case this code is used on an experiment from a previous SDK version.\n",
"execution_count": null, "\n",
"metadata": {}, "with open(conda_env_file_name, 'r') as cefr:\n",
"outputs": [], " content = cefr.read()\n",
"source": [ "\n",
"from azureml.core.model import InferenceConfig\n", "with open(conda_env_file_name, 'w') as cefw:\n",
"from azureml.core.webservice import AciWebservice\n", " cefw.write(content.replace(azureml.core.VERSION, dependencies['azureml-sdk']))\n",
"\n", "\n",
"inference_config = InferenceConfig(runtime = \"python\", \n", "# Substitute the actual model id in the script file.\n",
" entry_script = script_file_name,\n", "\n",
" conda_file = conda_env_file_name)\n", "script_file_name = 'score.py'\n",
"\n", "\n",
"aciconfig = AciWebservice.deploy_configuration(cpu_cores = 1, \n", "with open(script_file_name, 'r') as cefr:\n",
" memory_gb = 1, \n", " content = cefr.read()\n",
" tags = {'area': \"digits\", 'type': \"automl_classification\"}, \n", "\n",
" description = 'sample service for Automl Classification')" "with open(script_file_name, 'w') as cefw:\n",
] " cefw.write(content.replace('<<modelid>>', local_run.model_id))"
}, ],
{ "cell_type": "code"
"cell_type": "code", },
"execution_count": null, {
"metadata": {}, "metadata": {},
"outputs": [], "source": [
"source": [ "### Create a Container Image"
"from azureml.core.webservice import Webservice\n", ],
"from azureml.core.model import Model\n", "cell_type": "markdown"
"\n", },
"aci_service_name = 'automl-sample-01'\n", {
"print(aci_service_name)\n", "metadata": {},
"aci_service = Model.deploy(ws, aci_service_name, [model], inference_config, aciconfig)\n", "outputs": [],
"aci_service.wait_for_deployment(True)\n", "execution_count": null,
"print(aci_service.state)" "source": [
] "from azureml.core.image import Image, ContainerImage\n",
}, "\n",
{ "image_config = ContainerImage.image_configuration(runtime= \"python\",\n",
"cell_type": "markdown", " execution_script = script_file_name,\n",
"metadata": {}, " conda_file = conda_env_file_name,\n",
"source": [ " tags = {'area': \"digits\", 'type': \"automl_classification\"},\n",
"### Get the logs from service deployment" " description = \"Image for automl classification sample\")\n",
] "\n",
}, "image = Image.create(name = \"automlsampleimage\",\n",
{ " # this is the model object \n",
"cell_type": "code", " models = [model],\n",
"execution_count": null, " image_config = image_config, \n",
"metadata": {}, " workspace = ws)\n",
"outputs": [], "\n",
"source": [ "image.wait_for_creation(show_output = True)\n",
"if aci_service.state != 'Healthy':\n", "\n",
" # run this command for debugging.\n", "if image.creation_state == 'Failed':\n",
" print(aci_service.get_logs())" " print(\"Image build log at: \" + image.image_build_log_uri)"
] ],
}, "cell_type": "code"
{ },
"cell_type": "markdown", {
"metadata": {}, "metadata": {},
"source": [ "source": [
"### Delete a Web Service" "### Deploy the Image as a Web Service on Azure Container Instance"
] ],
}, "cell_type": "markdown"
{ },
"cell_type": "code", {
"execution_count": null, "metadata": {},
"metadata": {}, "outputs": [],
"outputs": [], "execution_count": null,
"source": [ "source": [
"#aci_service.delete()" "from azureml.core.webservice import AciWebservice\n",
] "\n",
}, "aciconfig = AciWebservice.deploy_configuration(cpu_cores = 1, \n",
{ " memory_gb = 1, \n",
"cell_type": "markdown", " tags = {'area': \"digits\", 'type': \"automl_classification\"}, \n",
"metadata": {}, " description = 'sample service for Automl Classification')"
"source": [ ],
"## Test" "cell_type": "code"
] },
}, {
{ "metadata": {},
"cell_type": "code", "outputs": [],
"execution_count": null, "execution_count": null,
"metadata": {}, "source": [
"outputs": [], "from azureml.core.webservice import Webservice\n",
"source": [ "\n",
"#Randomly select digits and test\n", "aci_service_name = 'automl-sample-01'\n",
"digits = datasets.load_digits()\n", "print(aci_service_name)\n",
"X_test = digits.data[:10, :]\n", "aci_service = Webservice.deploy_from_image(deployment_config = aciconfig,\n",
"y_test = digits.target[:10]\n", " image = image,\n",
"images = digits.images[:10]\n", " name = aci_service_name,\n",
"\n", " workspace = ws)\n",
"for index in np.random.choice(len(y_test), 3, replace = False):\n", "aci_service.wait_for_deployment(True)\n",
" print(index)\n", "print(aci_service.state)"
" test_sample = json.dumps({'data':X_test[index:index + 1].tolist()})\n", ],
" predicted = aci_service.run(input_data = test_sample)\n", "cell_type": "code"
" label = y_test[index]\n", },
" predictedDict = json.loads(predicted)\n", {
" title = \"Label value = %d Predicted value = %s \" % ( label,predictedDict['result'][0])\n", "metadata": {},
" fig = plt.figure(1, figsize = (3,3))\n", "source": [
" ax1 = fig.add_axes((0,0,.8,.8))\n", "### Delete a Web Service"
" ax1.set_title(title)\n", ],
" plt.imshow(images[index], cmap = plt.cm.gray_r, interpolation = 'nearest')\n", "cell_type": "markdown"
" plt.show()" },
] {
} "metadata": {},
], "outputs": [],
"metadata": { "execution_count": null,
"authors": [ "source": [
{ "#aci_service.delete()"
"name": "savitam" ],
} "cell_type": "code"
], },
"kernelspec": { {
"display_name": "Python 3.6", "metadata": {},
"language": "python", "source": [
"name": "python36" "### Get Logs from a Deployed Web Service"
}, ],
"language_info": { "cell_type": "markdown"
"codemirror_mode": { },
"name": "ipython", {
"version": 3 "metadata": {},
}, "outputs": [],
"file_extension": ".py", "execution_count": null,
"mimetype": "text/x-python", "source": [
"name": "python", "#aci_service.get_logs()"
"nbconvert_exporter": "python", ],
"pygments_lexer": "ipython3", "cell_type": "code"
"version": "3.6.6" },
} {
}, "metadata": {},
"nbformat": 4, "source": [
"nbformat_minor": 2 "## Test"
],
"cell_type": "markdown"
},
{
"metadata": {},
"outputs": [],
"execution_count": null,
"source": [
"#Randomly select digits and test\n",
"digits = datasets.load_digits()\n",
"X_test = digits.data[:10, :]\n",
"y_test = digits.target[:10]\n",
"images = digits.images[:10]\n",
"\n",
"for index in np.random.choice(len(y_test), 3, replace = False):\n",
" print(index)\n",
" test_sample = json.dumps({'data':X_test[index:index + 1].tolist()})\n",
" predicted = aci_service.run(input_data = test_sample)\n",
" label = y_test[index]\n",
" predictedDict = json.loads(predicted)\n",
" title = \"Label value = %d Predicted value = %s \" % ( label,predictedDict['result'][0])\n",
" fig = plt.figure(1, figsize = (3,3))\n",
" ax1 = fig.add_axes((0,0,.8,.8))\n",
" ax1.set_title(title)\n",
" plt.imshow(images[index], cmap = plt.cm.gray_r, interpolation = 'nearest')\n",
" plt.show()"
],
"cell_type": "code"
}
],
"nbformat_minor": 2
} }

View File

@@ -1,8 +1,8 @@
name: auto-ml-classification-with-deployment name: auto-ml-classification-with-deployment
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- azureml-train-automl - azureml-train-automl
- azureml-widgets - azureml-widgets
- matplotlib - matplotlib
- pandas_ml - pandas_ml

View File

@@ -1,375 +1,381 @@
{ {
"cells": [ "metadata": {
{ "kernelspec": {
"cell_type": "markdown", "display_name": "Python 3.6",
"metadata": {}, "name": "python36",
"source": [ "language": "python"
"Copyright (c) Microsoft Corporation. All rights reserved.\n", },
"\n", "authors": [
"Licensed under the MIT License." {
] "name": "savitam"
}, }
{ ],
"cell_type": "markdown", "language_info": {
"metadata": {}, "mimetype": "text/x-python",
"source": [ "codemirror_mode": {
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/classification-with-onnx/auto-ml-classification-with-onnx.png)" "name": "ipython",
] "version": 3
}, },
{ "pygments_lexer": "ipython3",
"cell_type": "markdown", "name": "python",
"metadata": {}, "file_extension": ".py",
"source": [ "nbconvert_exporter": "python",
"# Automated Machine Learning\n", "version": "3.6.6"
"_**Classification with Local Compute**_\n", }
"\n", },
"## Contents\n", "nbformat": 4,
"1. [Introduction](#Introduction)\n", "cells": [
"1. [Setup](#Setup)\n", {
"1. [Data](#Data)\n", "metadata": {},
"1. [Train](#Train)\n", "source": [
"1. [Results](#Results)\n", "Copyright (c) Microsoft Corporation. All rights reserved.\n",
"\n" "\n",
] "Licensed under the MIT License."
}, ],
{ "cell_type": "markdown"
"cell_type": "markdown", },
"metadata": {}, {
"source": [ "metadata": {},
"## Introduction\n", "source": [
"\n", "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/classification-with-onnx/auto-ml-classification-with-onnx.png)"
"In this example we use the scikit-learn's [iris dataset](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_iris.html) to showcase how you can use AutoML for a simple classification problem.\n", ],
"\n", "cell_type": "markdown"
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n", },
"\n", {
"Please find the ONNX related documentations [here](https://github.com/onnx/onnx).\n", "metadata": {},
"\n", "source": [
"In this notebook you will learn how to:\n", "# Automated Machine Learning\n",
"1. Create an `Experiment` in an existing `Workspace`.\n", "_**Classification with Local Compute**_\n",
"2. Configure AutoML using `AutoMLConfig`.\n", "\n",
"3. Train the model using local compute with ONNX compatible config on.\n", "## Contents\n",
"4. Explore the results and save the ONNX model.\n", "1. [Introduction](#Introduction)\n",
"5. Inference with the ONNX model." "1. [Setup](#Setup)\n",
] "1. [Data](#Data)\n",
}, "1. [Train](#Train)\n",
{ "1. [Results](#Results)\n",
"cell_type": "markdown", "1. [Test](#Test)\n",
"metadata": {}, "\n"
"source": [ ],
"## Setup\n", "cell_type": "markdown"
"\n", },
"As part of the setup you have already created an Azure ML `Workspace` object. For AutoML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments." {
] "metadata": {},
}, "source": [
{ "## Introduction\n",
"cell_type": "code", "\n",
"execution_count": null, "In this example we use the scikit-learn's [digit dataset](http://scikit-learn.org/stable/datasets/index.html#optical-recognition-of-handwritten-digits-dataset) to showcase how you can use AutoML for a simple classification problem.\n",
"metadata": {}, "\n",
"outputs": [], "Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
"source": [ "\n",
"import logging\n", "Please find the ONNX related documentations [here](https://github.com/onnx/onnx).\n",
"\n", "\n",
"from matplotlib import pyplot as plt\n", "In this notebook you will learn how to:\n",
"import numpy as np\n", "1. Create an `Experiment` in an existing `Workspace`.\n",
"import pandas as pd\n", "2. Configure AutoML using `AutoMLConfig`.\n",
"from sklearn import datasets\n", "3. Train the model using local compute with ONNX compatible config on.\n",
"from sklearn.model_selection import train_test_split\n", "4. Explore the results and save the ONNX model."
"\n", ],
"import azureml.core\n", "cell_type": "markdown"
"from azureml.core.experiment import Experiment\n", },
"from azureml.core.workspace import Workspace\n", {
"from azureml.train.automl import AutoMLConfig, constants" "metadata": {},
] "source": [
}, "## Setup\n",
{ "\n",
"cell_type": "code", "As part of the setup you have already created an Azure ML `Workspace` object. For AutoML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments."
"execution_count": null, ],
"metadata": {}, "cell_type": "markdown"
"outputs": [], },
"source": [ {
"ws = Workspace.from_config()\n", "metadata": {},
"\n", "outputs": [],
"# Choose a name for the experiment.\n", "execution_count": null,
"experiment_name = 'automl-classification-onnx'\n", "source": [
"\n", "import logging\n",
"experiment = Experiment(ws, experiment_name)\n", "\n",
"\n", "from matplotlib import pyplot as plt\n",
"output = {}\n", "import numpy as np\n",
"output['SDK version'] = azureml.core.VERSION\n", "import pandas as pd\n",
"output['Subscription ID'] = ws.subscription_id\n", "from sklearn import datasets\n",
"output['Workspace Name'] = ws.name\n", "from sklearn.model_selection import train_test_split\n",
"output['Resource Group'] = ws.resource_group\n", "\n",
"output['Location'] = ws.location\n", "import azureml.core\n",
"output['Experiment Name'] = experiment.name\n", "from azureml.core.experiment import Experiment\n",
"pd.set_option('display.max_colwidth', -1)\n", "from azureml.core.workspace import Workspace\n",
"outputDf = pd.DataFrame(data = output, index = [''])\n", "from azureml.train.automl import AutoMLConfig, constants"
"outputDf.T" ],
] "cell_type": "code"
}, },
{ {
"cell_type": "markdown", "metadata": {},
"metadata": {}, "outputs": [],
"source": [ "execution_count": null,
"## Data\n", "source": [
"\n", "ws = Workspace.from_config()\n",
"This uses scikit-learn's [load_iris](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_iris.html) method." "\n",
] "# Choose a name for the experiment and specify the project folder.\n",
}, "experiment_name = 'automl-classification-onnx'\n",
{ "project_folder = './sample_projects/automl-classification-onnx'\n",
"cell_type": "code", "\n",
"execution_count": null, "experiment = Experiment(ws, experiment_name)\n",
"metadata": {}, "\n",
"outputs": [], "output = {}\n",
"source": [ "output['SDK version'] = azureml.core.VERSION\n",
"iris = datasets.load_iris()\n", "output['Subscription ID'] = ws.subscription_id\n",
"X_train, X_test, y_train, y_test = train_test_split(iris.data, \n", "output['Workspace Name'] = ws.name\n",
" iris.target, \n", "output['Resource Group'] = ws.resource_group\n",
" test_size=0.2, \n", "output['Location'] = ws.location\n",
" random_state=0)" "output['Project Directory'] = project_folder\n",
] "output['Experiment Name'] = experiment.name\n",
}, "pd.set_option('display.max_colwidth', -1)\n",
{ "outputDf = pd.DataFrame(data = output, index = [''])\n",
"cell_type": "markdown", "outputDf.T"
"metadata": {}, ],
"source": [ "cell_type": "code"
"### Ensure the x_train and x_test are pandas DataFrame." },
] {
}, "metadata": {},
{ "source": [
"cell_type": "code", "## Data\n",
"execution_count": null, "\n",
"metadata": {}, "This uses scikit-learn's [load_iris](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_iris.html) method."
"outputs": [], ],
"source": [ "cell_type": "markdown"
"# Convert the X_train and X_test to pandas DataFrame and set column names,\n", },
"# This is needed for initializing the input variable names of ONNX model, \n", {
"# and the prediction with the ONNX model using the inference helper.\n", "metadata": {},
"X_train = pd.DataFrame(X_train, columns=['c1', 'c2', 'c3', 'c4'])\n", "outputs": [],
"X_test = pd.DataFrame(X_test, columns=['c1', 'c2', 'c3', 'c4'])" "execution_count": null,
] "source": [
}, "iris = datasets.load_iris()\n",
{ "X_train, X_test, y_train, y_test = train_test_split(iris.data, \n",
"cell_type": "markdown", " iris.target, \n",
"metadata": {}, " test_size=0.2, \n",
"source": [ " random_state=0)\n",
"## Train\n", "\n",
"\n", "\n"
"Instantiate an `AutoMLConfig` object to specify the settings and data used to run the experiment.\n", ],
"\n", "cell_type": "code"
"**Note:** Set the parameter enable_onnx_compatible_models=True, if you also want to generate the ONNX compatible models. Please note, the forecasting task and TensorFlow models are not ONNX compatible yet.\n", },
"\n", {
"|Property|Description|\n", "metadata": {},
"|-|-|\n", "source": [
"|**task**|classification or regression|\n", "### Ensure the x_train and x_test are pandas DataFrame."
"|**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", ],
"|**iteration_timeout_minutes**|Time limit in minutes for each iteration.|\n", "cell_type": "markdown"
"|**iterations**|Number of iterations. In each iteration AutoML trains a specific pipeline with the data.|\n", },
"|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n", {
"|**y**|(sparse) array-like, shape = [n_samples, ], Multi-class targets.|\n", "metadata": {},
"|**enable_onnx_compatible_models**|Enable the ONNX compatible models in the experiment.|" "outputs": [],
] "execution_count": null,
}, "source": [
{ "# Convert the X_train and X_test to pandas DataFrame and set column names,\n",
"cell_type": "markdown", "# This is needed for initializing the input variable names of ONNX model, \n",
"metadata": {}, "# and the prediction with the ONNX model using the inference helper.\n",
"source": [ "X_train = pd.DataFrame(X_train, columns=['c1', 'c2', 'c3', 'c4'])\n",
"### Set the preprocess=True, currently the InferenceHelper only supports this mode." "X_test = pd.DataFrame(X_test, columns=['c1', 'c2', 'c3', 'c4'])"
] ],
}, "cell_type": "code"
{ },
"cell_type": "code", {
"execution_count": null, "metadata": {},
"metadata": {}, "source": [
"outputs": [], "## Train with enable ONNX compatible models config on\n",
"source": [ "\n",
"automl_config = AutoMLConfig(task = 'classification',\n", "Instantiate an `AutoMLConfig` object to specify the settings and data used to run the experiment.\n",
" debug_log = 'automl_errors.log',\n", "\n",
" primary_metric = 'AUC_weighted',\n", "Set the parameter enable_onnx_compatible_models=True, if you also want to generate the ONNX compatible models. Please note, the forecasting task and TensorFlow models are not ONNX compatible yet.\n",
" iteration_timeout_minutes = 60,\n", "\n",
" iterations = 10,\n", "|Property|Description|\n",
" verbosity = logging.INFO, \n", "|-|-|\n",
" X = X_train, \n", "|**task**|classification or regression|\n",
" y = y_train,\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",
" preprocess=True,\n", "|**iteration_timeout_minutes**|Time limit in minutes for each iteration.|\n",
" enable_onnx_compatible_models=True)" "|**iterations**|Number of iterations. In each iteration AutoML trains a specific pipeline with the data.|\n",
] "|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n",
}, "|**y**|(sparse) array-like, shape = [n_samples, ], Multi-class targets.|\n",
{ "|**enable_onnx_compatible_models**|Enable the ONNX compatible models in the experiment.|\n",
"cell_type": "markdown", "|**path**|Relative path to the project folder. AutoML stores configuration files for the experiment under this folder. You can specify a new empty folder.|"
"metadata": {}, ],
"source": [ "cell_type": "markdown"
"Call the `submit` method on the experiment object and pass the run configuration. Execution of local runs is synchronous. Depending on the data and the number of iterations this can run for a while.\n", },
"In this example, we specify `show_output = True` to print currently running iterations to the console." {
] "metadata": {},
}, "source": [
{ "### Set the preprocess=True, currently the InferenceHelper only supports this mode."
"cell_type": "code", ],
"execution_count": null, "cell_type": "markdown"
"metadata": {}, },
"outputs": [], {
"source": [ "metadata": {},
"local_run = experiment.submit(automl_config, show_output = True)" "outputs": [],
] "execution_count": null,
}, "source": [
{ "automl_config = AutoMLConfig(task = 'classification',\n",
"cell_type": "code", " debug_log = 'automl_errors.log',\n",
"execution_count": null, " primary_metric = 'AUC_weighted',\n",
"metadata": {}, " iteration_timeout_minutes = 60,\n",
"outputs": [], " iterations = 10,\n",
"source": [ " verbosity = logging.INFO, \n",
"local_run" " X = X_train, \n",
] " y = y_train,\n",
}, " preprocess=True,\n",
{ " enable_onnx_compatible_models=True,\n",
"cell_type": "markdown", " path = project_folder)"
"metadata": {}, ],
"source": [ "cell_type": "code"
"## Results" },
] {
}, "metadata": {},
{ "source": [
"cell_type": "markdown", "Call the `submit` method on the experiment object and pass the run configuration. Execution of local runs is synchronous. Depending on the data and the number of iterations this can run for a while.\n",
"metadata": {}, "In this example, we specify `show_output = True` to print currently running iterations to the console."
"source": [ ],
"#### Widget for Monitoring Runs\n", "cell_type": "markdown"
"\n", },
"The widget will first report a \"loading\" status while running the first iteration. After completing the first iteration, an auto-updating graph and table will be shown. The widget will refresh once per minute, so you should see the graph update as child runs complete.\n", {
"\n", "metadata": {},
"**Note:** The widget displays a link at the bottom. Use this link to open a web interface to explore the individual run details." "outputs": [],
] "execution_count": null,
}, "source": [
{ "local_run = experiment.submit(automl_config, show_output = True)"
"cell_type": "code", ],
"execution_count": null, "cell_type": "code"
"metadata": {}, },
"outputs": [], {
"source": [ "metadata": {},
"from azureml.widgets import RunDetails\n", "outputs": [],
"RunDetails(local_run).show() " "execution_count": null,
] "source": [
}, "local_run"
{ ],
"cell_type": "markdown", "cell_type": "code"
"metadata": {}, },
"source": [ {
"### Retrieve the Best ONNX Model\n", "metadata": {},
"\n", "source": [
"Below we select the best pipeline from our iterations. The `get_output` method returns the best run and the fitted model. The Model includes the pipeline and any pre-processing. Overloads on `get_output` allow you to retrieve the best run and fitted model for *any* logged metric or for a particular *iteration*.\n", "## Results"
"\n", ],
"Set the parameter return_onnx_model=True to retrieve the best ONNX model, instead of the Python model." "cell_type": "markdown"
] },
}, {
{ "metadata": {},
"cell_type": "code", "source": [
"execution_count": null, "#### Widget for Monitoring Runs\n",
"metadata": {}, "\n",
"outputs": [], "The widget will first report a \"loading\" status while running the first iteration. After completing the first iteration, an auto-updating graph and table will be shown. The widget will refresh once per minute, so you should see the graph update as child runs complete.\n",
"source": [ "\n",
"best_run, onnx_mdl = local_run.get_output(return_onnx_model=True)" "**Note:** The widget displays a link at the bottom. Use this link to open a web interface to explore the individual run details."
] ],
}, "cell_type": "markdown"
{ },
"cell_type": "markdown", {
"metadata": {}, "metadata": {},
"source": [ "outputs": [],
"### Save the best ONNX model" "execution_count": null,
] "source": [
}, "from azureml.widgets import RunDetails\n",
{ "RunDetails(local_run).show() "
"cell_type": "code", ],
"execution_count": null, "cell_type": "code"
"metadata": {}, },
"outputs": [], {
"source": [ "metadata": {},
"from azureml.automl.core.onnx_convert import OnnxConverter\n", "source": [
"onnx_fl_path = \"./best_model.onnx\"\n", "### Retrieve the Best ONNX Model\n",
"OnnxConverter.save_onnx_model(onnx_mdl, onnx_fl_path)" "\n",
] "Below we select the best pipeline from our iterations. The `get_output` method returns the best run and the fitted model. The Model includes the pipeline and any pre-processing. Overloads on `get_output` allow you to retrieve the best run and fitted model for *any* logged metric or for a particular *iteration*.\n",
}, "\n",
{ "Set the parameter return_onnx_model=True to retrieve the best ONNX model, instead of the Python model."
"cell_type": "markdown", ],
"metadata": {}, "cell_type": "markdown"
"source": [ },
"### Predict with the ONNX model, using onnxruntime package" {
] "metadata": {},
}, "outputs": [],
{ "execution_count": null,
"cell_type": "code", "source": [
"execution_count": null, "best_run, onnx_mdl = local_run.get_output(return_onnx_model=True)"
"metadata": {}, ],
"outputs": [], "cell_type": "code"
"source": [ },
"import sys\n", {
"import json\n", "metadata": {},
"from azureml.automl.core.onnx_convert import OnnxConvertConstants\n", "source": [
"\n", "### Save the best ONNX model"
"if sys.version_info < OnnxConvertConstants.OnnxIncompatiblePythonVersion:\n", ],
" python_version_compatible = True\n", "cell_type": "markdown"
"else:\n", },
" python_version_compatible = False\n", {
"\n", "metadata": {},
"try:\n", "outputs": [],
" import onnxruntime\n", "execution_count": null,
" from azureml.automl.core.onnx_convert import OnnxInferenceHelper \n", "source": [
" onnxrt_present = True\n", "from azureml.automl.core.onnx_convert import OnnxConverter\n",
"except ImportError:\n", "onnx_fl_path = \"./best_model.onnx\"\n",
" onnxrt_present = False\n", "OnnxConverter.save_onnx_model(onnx_mdl, onnx_fl_path)"
"\n", ],
"def get_onnx_res(run):\n", "cell_type": "code"
" res_path = 'onnx_resource.json'\n", },
" run.download_file(name=constants.MODEL_RESOURCE_PATH_ONNX, output_file_path=res_path)\n", {
" with open(res_path) as f:\n", "metadata": {},
" onnx_res = json.load(f)\n", "source": [
" return onnx_res\n", "### Predict with the ONNX model, using onnxruntime package"
"\n", ],
"if onnxrt_present and python_version_compatible: \n", "cell_type": "markdown"
" mdl_bytes = onnx_mdl.SerializeToString()\n", },
" onnx_res = get_onnx_res(best_run)\n", {
"\n", "metadata": {},
" onnxrt_helper = OnnxInferenceHelper(mdl_bytes, onnx_res)\n", "outputs": [],
" pred_onnx, pred_prob_onnx = onnxrt_helper.predict(X_test)\n", "execution_count": null,
"\n", "source": [
" print(pred_onnx)\n", "import sys\n",
" print(pred_prob_onnx)\n", "import json\n",
"else:\n", "from azureml.automl.core.onnx_convert import OnnxConvertConstants\n",
" if not python_version_compatible:\n", "\n",
" print('Please use Python version 3.6 or 3.7 to run the inference helper.') \n", "if sys.version_info < OnnxConvertConstants.OnnxIncompatiblePythonVersion:\n",
" if not onnxrt_present:\n", " python_version_compatible = True\n",
" print('Please install the onnxruntime package to do the prediction with ONNX model.')" "else:\n",
] " python_version_compatible = False\n",
}, "\n",
{ "try:\n",
"cell_type": "code", " import onnxruntime\n",
"execution_count": null, " from azureml.automl.core.onnx_convert import OnnxInferenceHelper \n",
"metadata": {}, " onnxrt_present = True\n",
"outputs": [], "except ImportError:\n",
"source": [] " onnxrt_present = False\n",
} "\n",
], "def get_onnx_res(run):\n",
"metadata": { " res_path = 'onnx_resource.json'\n",
"authors": [ " run.download_file(name=constants.MODEL_RESOURCE_PATH_ONNX, output_file_path=res_path)\n",
{ " with open(res_path) as f:\n",
"name": "savitam" " onnx_res = json.load(f)\n",
} " return onnx_res\n",
], "\n",
"kernelspec": { "if onnxrt_present and python_version_compatible: \n",
"display_name": "Python 3.6", " mdl_bytes = onnx_mdl.SerializeToString()\n",
"language": "python", " onnx_res = get_onnx_res(best_run)\n",
"name": "python36" "\n",
}, " onnxrt_helper = OnnxInferenceHelper(mdl_bytes, onnx_res)\n",
"language_info": { " pred_onnx, pred_prob_onnx = onnxrt_helper.predict(X_test)\n",
"codemirror_mode": { "\n",
"name": "ipython", " print(pred_onnx)\n",
"version": 3 " print(pred_prob_onnx)\n",
}, "else:\n",
"file_extension": ".py", " if not python_version_compatible:\n",
"mimetype": "text/x-python", " print('Please use Python version 3.6 or 3.7 to run the inference helper.') \n",
"name": "python", " if not onnxrt_present:\n",
"nbconvert_exporter": "python", " print('Please install the onnxruntime package to do the prediction with ONNX model.')"
"pygments_lexer": "ipython3", ],
"version": "3.6.6" "cell_type": "code"
} },
}, {
"nbformat": 4, "metadata": {},
"nbformat_minor": 2 "outputs": [],
"execution_count": null,
"source": [],
"cell_type": "code"
}
],
"nbformat_minor": 2
} }

View File

@@ -1,9 +1,9 @@
name: auto-ml-classification-with-onnx name: auto-ml-classification-with-onnx
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- azureml-train-automl - azureml-train-automl
- azureml-widgets - azureml-widgets
- matplotlib - matplotlib
- pandas_ml - pandas_ml
- onnxruntime - onnxruntime

View File

@@ -1,395 +1,399 @@
{ {
"cells": [ "metadata": {
{ "kernelspec": {
"cell_type": "markdown", "display_name": "Python 3.6",
"metadata": {}, "name": "python36",
"source": [ "language": "python"
"Copyright (c) Microsoft Corporation. All rights reserved.\n", },
"\n", "authors": [
"Licensed under the MIT License." {
] "name": "savitam"
}, }
{ ],
"cell_type": "markdown", "language_info": {
"metadata": {}, "mimetype": "text/x-python",
"source": [ "codemirror_mode": {
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/classification-with-whitelisting/auto-ml-classification-with-whitelisting.png)" "name": "ipython",
] "version": 3
}, },
{ "pygments_lexer": "ipython3",
"cell_type": "markdown", "name": "python",
"metadata": {}, "file_extension": ".py",
"source": [ "nbconvert_exporter": "python",
"# Automated Machine Learning\n", "version": "3.6.6"
"_**Classification using whitelist models**_\n", }
"\n", },
"## Contents\n", "nbformat": 4,
"1. [Introduction](#Introduction)\n", "cells": [
"1. [Setup](#Setup)\n", {
"1. [Data](#Data)\n", "metadata": {},
"1. [Train](#Train)\n", "source": [
"1. [Results](#Results)\n", "Copyright (c) Microsoft Corporation. All rights reserved.\n",
"1. [Test](#Test)" "\n",
] "Licensed under the MIT License."
}, ],
{ "cell_type": "markdown"
"cell_type": "markdown", },
"metadata": {}, {
"source": [ "metadata": {},
"## Introduction\n", "source": [
"\n", "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/classification-with-whitelisting/auto-ml-classification-with-whitelisting.png)"
"In this example we use the scikit-learn's [digit dataset](http://scikit-learn.org/stable/datasets/index.html#optical-recognition-of-handwritten-digits-dataset) to showcase how you can use AutoML for a simple classification problem.\n", ],
"\n", "cell_type": "markdown"
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n", },
"This notebooks shows how can automl can be trained on a selected list of models, see the readme.md for the models.\n", {
"This trains the model exclusively on tensorflow based models.\n", "metadata": {},
"\n", "source": [
"In this notebook you will learn how to:\n", "# Automated Machine Learning\n",
"1. Create an `Experiment` in an existing `Workspace`.\n", "_**Classification using whitelist models**_\n",
"2. Configure AutoML using `AutoMLConfig`.\n", "\n",
"3. Train the model on a whilelisted models using local compute. \n", "## Contents\n",
"4. Explore the results.\n", "1. [Introduction](#Introduction)\n",
"5. Test the best fitted model." "1. [Setup](#Setup)\n",
] "1. [Data](#Data)\n",
}, "1. [Train](#Train)\n",
{ "1. [Results](#Results)\n",
"cell_type": "markdown", "1. [Test](#Test)"
"metadata": {}, ],
"source": [ "cell_type": "markdown"
"## Setup\n", },
"\n", {
"As part of the setup you have already created an Azure ML `Workspace` object. For AutoML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments." "metadata": {},
] "source": [
}, "## Introduction\n",
{ "\n",
"cell_type": "code", "In this example we use the scikit-learn's [digit dataset](http://scikit-learn.org/stable/datasets/index.html#optical-recognition-of-handwritten-digits-dataset) to showcase how you can use AutoML for a simple classification problem.\n",
"execution_count": null, "\n",
"metadata": {}, "Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
"outputs": [], "This notebooks shows how can automl can be trained on a a selected list of models,see the readme.md for the models.\n",
"source": [ "This trains the model exclusively on tensorflow based models.\n",
"#Note: This notebook will install tensorflow if not already installed in the enviornment..\n", "\n",
"import logging\n", "In this notebook you will learn how to:\n",
"\n", "1. Create an `Experiment` in an existing `Workspace`.\n",
"from matplotlib import pyplot as plt\n", "2. Configure AutoML using `AutoMLConfig`.\n",
"import numpy as np\n", "3. Train the model on a whilelisted models using local compute. \n",
"import pandas as pd\n", "4. Explore the results.\n",
"from sklearn import datasets\n", "5. Test the best fitted model."
"\n", ],
"import azureml.core\n", "cell_type": "markdown"
"from azureml.core.experiment import Experiment\n", },
"from azureml.core.workspace import Workspace\n", {
"import sys\n", "metadata": {},
"whitelist_models=[\"LightGBM\"]\n", "source": [
"if \"3.7\" != sys.version[0:3]:\n", "## Setup\n",
" try:\n", "\n",
" import tensorflow as tf1\n", "As part of the setup you have already created an Azure ML `Workspace` object. For AutoML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments."
" except ImportError:\n", ],
" from pip._internal import main\n", "cell_type": "markdown"
" main(['install', 'tensorflow>=1.10.0,<=1.12.0'])\n", },
" logging.getLogger().setLevel(logging.ERROR)\n", {
" whitelist_models=[\"TensorFlowLinearClassifier\", \"TensorFlowDNN\"]\n", "metadata": {},
"\n", "outputs": [],
"from azureml.train.automl import AutoMLConfig" "execution_count": null,
] "source": [
}, "#Note: This notebook will install tensorflow if not already installed in the enviornment..\n",
{ "import logging\n",
"cell_type": "code", "\n",
"execution_count": null, "from matplotlib import pyplot as plt\n",
"metadata": {}, "import numpy as np\n",
"outputs": [], "import pandas as pd\n",
"source": [ "from sklearn import datasets\n",
"ws = Workspace.from_config()\n", "\n",
"\n", "import azureml.core\n",
"# Choose a name for the experiment.\n", "from azureml.core.experiment import Experiment\n",
"experiment_name = 'automl-local-whitelist'\n", "from azureml.core.workspace import Workspace\n",
"\n", "import sys\n",
"experiment = Experiment(ws, experiment_name)\n", "whitelist_models=[\"LightGBM\"]\n",
"\n", "if \"3.7\" != sys.version[0:3]:\n",
"output = {}\n", " try:\n",
"output['SDK version'] = azureml.core.VERSION\n", " import tensorflow as tf1\n",
"output['Subscription ID'] = ws.subscription_id\n", " except ImportError:\n",
"output['Workspace Name'] = ws.name\n", " from pip._internal import main\n",
"output['Resource Group'] = ws.resource_group\n", " main(['install', 'tensorflow>=1.10.0,<=1.12.0'])\n",
"output['Location'] = ws.location\n", " logging.getLogger().setLevel(logging.ERROR)\n",
"output['Experiment Name'] = experiment.name\n", " whitelist_models=[\"TensorFlowLinearClassifier\", \"TensorFlowDNN\"]\n",
"pd.set_option('display.max_colwidth', -1)\n", "\n",
"outputDf = pd.DataFrame(data = output, index = [''])\n", "from azureml.train.automl import AutoMLConfig"
"outputDf.T" ],
] "cell_type": "code"
}, },
{ {
"cell_type": "markdown", "metadata": {},
"metadata": {}, "outputs": [],
"source": [ "execution_count": null,
"## Data\n", "source": [
"\n", "ws = Workspace.from_config()\n",
"This uses scikit-learn's [load_digits](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html) method." "\n",
] "# Choose a name for the experiment and specify the project folder.\n",
}, "experiment_name = 'automl-local-whitelist'\n",
{ "project_folder = './sample_projects/automl-local-whitelist'\n",
"cell_type": "code", "\n",
"execution_count": null, "experiment = Experiment(ws, experiment_name)\n",
"metadata": {}, "\n",
"outputs": [], "output = {}\n",
"source": [ "output['SDK version'] = azureml.core.VERSION\n",
"digits = datasets.load_digits()\n", "output['Subscription ID'] = ws.subscription_id\n",
"\n", "output['Workspace Name'] = ws.name\n",
"# Exclude the first 100 rows from training so that they can be used for test.\n", "output['Resource Group'] = ws.resource_group\n",
"X_train = digits.data[100:,:]\n", "output['Location'] = ws.location\n",
"y_train = digits.target[100:]" "output['Project Directory'] = project_folder\n",
] "output['Experiment Name'] = experiment.name\n",
}, "pd.set_option('display.max_colwidth', -1)\n",
{ "outputDf = pd.DataFrame(data = output, index = [''])\n",
"cell_type": "markdown", "outputDf.T"
"metadata": {}, ],
"source": [ "cell_type": "code"
"## Train\n", },
"\n", {
"Instantiate an `AutoMLConfig` object to specify the settings and data used to run the experiment.\n", "metadata": {},
"\n", "source": [
"|Property|Description|\n", "## Data\n",
"|-|-|\n", "\n",
"|**task**|classification or regression|\n", "This uses scikit-learn's [load_digits](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html) method."
"|**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>balanced_accuracy</i><br><i>average_precision_score_weighted</i><br><i>precision_score_weighted</i>|\n", ],
"|**iteration_timeout_minutes**|Time limit in minutes for each iteration.|\n", "cell_type": "markdown"
"|**iterations**|Number of iterations. In each iteration AutoML trains a specific pipeline with the data.|\n", },
"|**n_cross_validations**|Number of cross validation splits.|\n", {
"|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n", "metadata": {},
"|**y**|(sparse) array-like, shape = [n_samples, ], Multi-class targets.|\n", "outputs": [],
"|**whitelist_models**|List of models that AutoML should use. The possible values are listed [here](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-configure-auto-train#configure-your-experiment-settings).|" "execution_count": null,
] "source": [
}, "digits = datasets.load_digits()\n",
{ "\n",
"cell_type": "code", "# Exclude the first 100 rows from training so that they can be used for test.\n",
"execution_count": null, "X_train = digits.data[100:,:]\n",
"metadata": {}, "y_train = digits.target[100:]"
"outputs": [], ],
"source": [ "cell_type": "code"
"automl_config = AutoMLConfig(task = 'classification',\n", },
" debug_log = 'automl_errors.log',\n", {
" primary_metric = 'AUC_weighted',\n", "metadata": {},
" iteration_timeout_minutes = 60,\n", "source": [
" iterations = 10,\n", "## Train\n",
" verbosity = logging.INFO,\n", "\n",
" X = X_train, \n", "Instantiate an `AutoMLConfig` object to specify the settings and data used to run the experiment.\n",
" y = y_train,\n", "\n",
" enable_tf=True,\n", "|Property|Description|\n",
" whitelist_models=whitelist_models)" "|-|-|\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>balanced_accuracy</i><br><i>average_precision_score_weighted</i><br><i>precision_score_weighted</i>|\n",
{ "|**iteration_timeout_minutes**|Time limit in minutes for each iteration.|\n",
"cell_type": "markdown", "|**iterations**|Number of iterations. In each iteration AutoML trains a specific pipeline with the data.|\n",
"metadata": {}, "|**n_cross_validations**|Number of cross validation splits.|\n",
"source": [ "|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n",
"Call the `submit` method on the experiment object and pass the run configuration. Execution of local runs is synchronous. Depending on the data and the number of iterations this can run for a while.\n", "|**y**|(sparse) array-like, shape = [n_samples, ], Multi-class targets.|\n",
"In this example, we specify `show_output = True` to print currently running iterations to the console." "|**path**|Relative path to the project folder. AutoML stores configuration files for the experiment under this folder. You can specify a new empty folder.|\n",
] "|**whitelist_models**|List of models that AutoML should use. The possible values are listed [here](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-configure-auto-train#configure-your-experiment-settings).|"
}, ],
{ "cell_type": "markdown"
"cell_type": "code", },
"execution_count": null, {
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "execution_count": null,
"local_run = experiment.submit(automl_config, show_output = True)" "source": [
] "automl_config = AutoMLConfig(task = 'classification',\n",
}, " debug_log = 'automl_errors.log',\n",
{ " primary_metric = 'AUC_weighted',\n",
"cell_type": "code", " iteration_timeout_minutes = 60,\n",
"execution_count": null, " iterations = 10,\n",
"metadata": {}, " verbosity = logging.INFO,\n",
"outputs": [], " X = X_train, \n",
"source": [ " y = y_train,\n",
"local_run" " enable_tf=True,\n",
] " whitelist_models=whitelist_models,\n",
}, " path = project_folder)"
{ ],
"cell_type": "markdown", "cell_type": "code"
"metadata": {}, },
"source": [ {
"## Results" "metadata": {},
] "source": [
}, "Call the `submit` method on the experiment object and pass the run configuration. Execution of local runs is synchronous. Depending on the data and the number of iterations this can run for a while.\n",
{ "In this example, we specify `show_output = True` to print currently running iterations to the console."
"cell_type": "markdown", ],
"metadata": {}, "cell_type": "markdown"
"source": [ },
"#### Widget for Monitoring Runs\n", {
"\n", "metadata": {},
"The widget will first report a \"loading\" status while running the first iteration. After completing the first iteration, an auto-updating graph and table will be shown. The widget will refresh once per minute, so you should see the graph update as child runs complete.\n", "outputs": [],
"\n", "execution_count": null,
"**Note:** The widget displays a link at the bottom. Use this link to open a web interface to explore the individual run details." "source": [
] "local_run = experiment.submit(automl_config, show_output = True)"
}, ],
{ "cell_type": "code"
"cell_type": "code", },
"execution_count": null, {
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "execution_count": null,
"from azureml.widgets import RunDetails\n", "source": [
"RunDetails(local_run).show() " "local_run"
] ],
}, "cell_type": "code"
{ },
"cell_type": "markdown", {
"metadata": {}, "metadata": {},
"source": [ "source": [
"\n", "## Results"
"#### Retrieve All Child Runs\n", ],
"You can also use SDK methods to fetch all the child runs and see individual metrics that we log." "cell_type": "markdown"
] },
}, {
{ "metadata": {},
"cell_type": "code", "source": [
"execution_count": null, "#### Widget for Monitoring Runs\n",
"metadata": {}, "\n",
"outputs": [], "The widget will first report a \"loading\" status while running the first iteration. After completing the first iteration, an auto-updating graph and table will be shown. The widget will refresh once per minute, so you should see the graph update as child runs complete.\n",
"source": [ "\n",
"children = list(local_run.get_children())\n", "**Note:** The widget displays a link at the bottom. Use this link to open a web interface to explore the individual run details."
"metricslist = {}\n", ],
"for run in children:\n", "cell_type": "markdown"
" 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", "metadata": {},
"\n", "outputs": [],
"rundata = pd.DataFrame(metricslist).sort_index(1)\n", "execution_count": null,
"rundata" "source": [
] "from azureml.widgets import RunDetails\n",
}, "RunDetails(local_run).show() "
{ ],
"cell_type": "markdown", "cell_type": "code"
"metadata": {}, },
"source": [ {
"### Retrieve the Best Model\n", "metadata": {},
"\n", "source": [
"Below we select the best pipeline from our iterations. The `get_output` method returns the best run and the fitted model. The Model includes the pipeline and any pre-processing. Overloads on `get_output` allow you to retrieve the best run and fitted model for *any* logged metric or for a particular *iteration*." "\n",
] "#### Retrieve All Child Runs\n",
}, "You can also use SDK methods to fetch all the child runs and see individual metrics that we log."
{ ],
"cell_type": "code", "cell_type": "markdown"
"execution_count": null, },
"metadata": {}, {
"outputs": [], "metadata": {},
"source": [ "outputs": [],
"best_run, fitted_model = local_run.get_output()\n", "execution_count": null,
"print(best_run)\n", "source": [
"print(fitted_model)" "children = list(local_run.get_children())\n",
] "metricslist = {}\n",
}, "for run in children:\n",
{ " properties = run.get_properties()\n",
"cell_type": "markdown", " metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)}\n",
"metadata": {}, " metricslist[int(properties['iteration'])] = metrics\n",
"source": [ "\n",
"#### Best Model Based on Any Other Metric\n", "rundata = pd.DataFrame(metricslist).sort_index(1)\n",
"Show the run and the model that has the smallest `log_loss` value:" "rundata"
] ],
}, "cell_type": "code"
{ },
"cell_type": "code", {
"execution_count": null, "metadata": {},
"metadata": {}, "source": [
"outputs": [], "### Retrieve the Best Model\n",
"source": [ "\n",
"lookup_metric = \"log_loss\"\n", "Below we select the best pipeline from our iterations. The `get_output` method returns the best run and the fitted model. The Model includes the pipeline and any pre-processing. Overloads on `get_output` allow you to retrieve the best run and fitted model for *any* logged metric or for a particular *iteration*."
"best_run, fitted_model = local_run.get_output(metric = lookup_metric)\n", ],
"print(best_run)\n", "cell_type": "markdown"
"print(fitted_model)" },
] {
}, "metadata": {},
{ "outputs": [],
"cell_type": "markdown", "execution_count": null,
"metadata": {}, "source": [
"source": [ "best_run, fitted_model = local_run.get_output()\n",
"#### Model from a Specific Iteration\n", "print(best_run)\n",
"Show the run and the model from the third iteration:" "print(fitted_model)"
] ],
}, "cell_type": "code"
{ },
"cell_type": "code", {
"execution_count": null, "metadata": {},
"metadata": {}, "source": [
"outputs": [], "#### Best Model Based on Any Other Metric\n",
"source": [ "Show the run and the model that has the smallest `log_loss` value:"
"iteration = 3\n", ],
"third_run, third_model = local_run.get_output(iteration = iteration)\n", "cell_type": "markdown"
"print(third_run)\n", },
"print(third_model)" {
] "metadata": {},
}, "outputs": [],
{ "execution_count": null,
"cell_type": "markdown", "source": [
"metadata": {}, "lookup_metric = \"log_loss\"\n",
"source": [ "best_run, fitted_model = local_run.get_output(metric = lookup_metric)\n",
"## Test\n", "print(best_run)\n",
"\n", "print(fitted_model)"
"#### Load Test Data" ],
] "cell_type": "code"
}, },
{ {
"cell_type": "code", "metadata": {},
"execution_count": null, "source": [
"metadata": {}, "#### Model from a Specific Iteration\n",
"outputs": [], "Show the run and the model from the third iteration:"
"source": [ ],
"digits = datasets.load_digits()\n", "cell_type": "markdown"
"X_test = digits.data[:10, :]\n", },
"y_test = digits.target[:10]\n", {
"images = digits.images[:10]" "metadata": {},
] "outputs": [],
}, "execution_count": null,
{ "source": [
"cell_type": "markdown", "iteration = 3\n",
"metadata": {}, "third_run, third_model = local_run.get_output(iteration = iteration)\n",
"source": [ "print(third_run)\n",
"#### Testing Our Best Fitted Model\n", "print(third_model)"
"We will try to predict 2 digits and see how our model works." ],
] "cell_type": "code"
}, },
{ {
"cell_type": "code", "metadata": {},
"execution_count": null, "source": [
"metadata": {}, "## Test\n",
"outputs": [], "\n",
"source": [ "#### Load Test Data"
"# Randomly select digits and test.\n", ],
"for index in np.random.choice(len(y_test), 2, replace = False):\n", "cell_type": "markdown"
" print(index)\n", },
" predicted = fitted_model.predict(X_test[index:index + 1])[0]\n", {
" label = y_test[index]\n", "metadata": {},
" title = \"Label value = %d Predicted value = %d \" % (label, predicted)\n", "outputs": [],
" fig = plt.figure(1, figsize = (3,3))\n", "execution_count": null,
" ax1 = fig.add_axes((0,0,.8,.8))\n", "source": [
" ax1.set_title(title)\n", "digits = datasets.load_digits()\n",
" plt.imshow(images[index], cmap = plt.cm.gray_r, interpolation = 'nearest')\n", "X_test = digits.data[:10, :]\n",
" plt.show()" "y_test = digits.target[:10]\n",
] "images = digits.images[:10]"
} ],
], "cell_type": "code"
"metadata": { },
"authors": [ {
{ "metadata": {},
"name": "savitam" "source": [
} "#### Testing Our Best Fitted Model\n",
], "We will try to predict 2 digits and see how our model works."
"kernelspec": { ],
"display_name": "Python 3.6", "cell_type": "markdown"
"language": "python", },
"name": "python36" {
}, "metadata": {},
"language_info": { "outputs": [],
"codemirror_mode": { "execution_count": null,
"name": "ipython", "source": [
"version": 3 "# Randomly select digits and test.\n",
}, "for index in np.random.choice(len(y_test), 2, replace = False):\n",
"file_extension": ".py", " print(index)\n",
"mimetype": "text/x-python", " predicted = fitted_model.predict(X_test[index:index + 1])[0]\n",
"name": "python", " label = y_test[index]\n",
"nbconvert_exporter": "python", " title = \"Label value = %d Predicted value = %d \" % (label, predicted)\n",
"pygments_lexer": "ipython3", " fig = plt.figure(1, figsize = (3,3))\n",
"version": "3.6.6" " ax1 = fig.add_axes((0,0,.8,.8))\n",
} " ax1.set_title(title)\n",
}, " plt.imshow(images[index], cmap = plt.cm.gray_r, interpolation = 'nearest')\n",
"nbformat": 4, " plt.show()"
"nbformat_minor": 2 ],
"cell_type": "code"
}
],
"nbformat_minor": 2
} }

View File

@@ -1,8 +1,8 @@
name: auto-ml-classification-with-whitelisting name: auto-ml-classification-with-whitelisting
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- azureml-train-automl - azureml-train-automl
- azureml-widgets - azureml-widgets
- matplotlib - matplotlib
- pandas_ml - pandas_ml

View File

@@ -1,484 +1,482 @@
{ {
"cells": [ "metadata": {
{ "kernelspec": {
"cell_type": "markdown", "display_name": "Python 3.6",
"metadata": {}, "name": "python36",
"source": [ "language": "python"
"Copyright (c) Microsoft Corporation. All rights reserved.\n", },
"\n", "authors": [
"Licensed under the MIT License." {
] "name": "savitam"
}, }
{ ],
"cell_type": "markdown", "language_info": {
"metadata": {}, "mimetype": "text/x-python",
"source": [ "codemirror_mode": {
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/classification/auto-ml-classification.png)" "name": "ipython",
] "version": 3
}, },
{ "pygments_lexer": "ipython3",
"cell_type": "markdown", "name": "python",
"metadata": {}, "file_extension": ".py",
"source": [ "nbconvert_exporter": "python",
"# Automated Machine Learning\n", "version": "3.6.6"
"_**Classification with Local Compute**_\n", }
"\n", },
"## Contents\n", "nbformat": 4,
"1. [Introduction](#Introduction)\n", "cells": [
"1. [Setup](#Setup)\n", {
"1. [Data](#Data)\n", "metadata": {},
"1. [Train](#Train)\n", "source": [
"1. [Results](#Results)\n", "Copyright (c) Microsoft Corporation. All rights reserved.\n",
"1. [Test](#Test)\n", "\n",
"\n" "Licensed under the MIT License."
] ],
}, "cell_type": "markdown"
{ },
"cell_type": "markdown", {
"metadata": {}, "metadata": {},
"source": [ "source": [
"## Introduction\n", "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/classification/auto-ml-classification.png)"
"\n", ],
"In this example we use the scikit-learn's [digit dataset](http://scikit-learn.org/stable/datasets/index.html#optical-recognition-of-handwritten-digits-dataset) to showcase how you can use AutoML for a simple classification problem.\n", "cell_type": "markdown"
"\n", },
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n", {
"\n", "metadata": {},
"In this notebook you will learn how to:\n", "source": [
"1. Create an `Experiment` in an existing `Workspace`.\n", "# Automated Machine Learning\n",
"2. Configure AutoML using `AutoMLConfig`.\n", "_**Classification with Local Compute**_\n",
"3. Train the model using local compute.\n", "\n",
"4. Explore the results.\n", "## Contents\n",
"5. Test the best fitted model." "1. [Introduction](#Introduction)\n",
] "1. [Setup](#Setup)\n",
}, "1. [Data](#Data)\n",
{ "1. [Train](#Train)\n",
"cell_type": "markdown", "1. [Results](#Results)\n",
"metadata": {}, "1. [Test](#Test)\n",
"source": [ "\n"
"## Setup\n", ],
"\n", "cell_type": "markdown"
"As part of the setup you have already created an Azure ML `Workspace` object. For AutoML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments." },
] {
}, "metadata": {},
{ "source": [
"cell_type": "code", "## Introduction\n",
"execution_count": null, "\n",
"metadata": {}, "In this example we use the scikit-learn's [digit dataset](http://scikit-learn.org/stable/datasets/index.html#optical-recognition-of-handwritten-digits-dataset) to showcase how you can use AutoML for a simple classification problem.\n",
"outputs": [], "\n",
"source": [ "Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
"import logging\n", "\n",
"\n", "In this notebook you will learn how to:\n",
"from matplotlib import pyplot as plt\n", "1. Create an `Experiment` in an existing `Workspace`.\n",
"import numpy as np\n", "2. Configure AutoML using `AutoMLConfig`.\n",
"import pandas as pd\n", "3. Train the model using local compute.\n",
"from sklearn import datasets\n", "4. Explore the results.\n",
"\n", "5. Test the best fitted model."
"import azureml.core\n", ],
"from azureml.core.experiment import Experiment\n", "cell_type": "markdown"
"from azureml.core.workspace import Workspace\n", },
"from azureml.train.automl import AutoMLConfig" {
] "metadata": {},
}, "source": [
{ "## Setup\n",
"cell_type": "markdown", "\n",
"metadata": {}, "As part of the setup you have already created an Azure ML `Workspace` object. For AutoML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments."
"source": [ ],
"Accessing the Azure ML workspace requires authentication with Azure.\n", "cell_type": "markdown"
"\n", },
"The default authentication is interactive authentication using the default tenant. Executing the `ws = Workspace.from_config()` line in the cell below will prompt for authentication the first time that it is run.\n", {
"\n", "metadata": {},
"If you have multiple Azure tenants, you can specify the tenant by replacing the `ws = Workspace.from_config()` line in the cell below with the following:\n", "outputs": [],
"\n", "execution_count": null,
"```\n", "source": [
"from azureml.core.authentication import InteractiveLoginAuthentication\n", "import logging\n",
"auth = InteractiveLoginAuthentication(tenant_id = 'mytenantid')\n", "\n",
"ws = Workspace.from_config(auth = auth)\n", "from matplotlib import pyplot as plt\n",
"```\n", "import numpy as np\n",
"\n", "import pandas as pd\n",
"If you need to run in an environment where interactive login is not possible, you can use Service Principal authentication by replacing the `ws = Workspace.from_config()` line in the cell below with the following:\n", "from sklearn import datasets\n",
"\n", "\n",
"```\n", "import azureml.core\n",
"from azureml.core.authentication import ServicePrincipalAuthentication\n", "from azureml.core.experiment import Experiment\n",
"auth = auth = ServicePrincipalAuthentication('mytenantid', 'myappid', 'mypassword')\n", "from azureml.core.workspace import Workspace\n",
"ws = Workspace.from_config(auth = auth)\n", "from azureml.train.automl import AutoMLConfig"
"```\n", ],
"For more details, see [aka.ms/aml-notebook-auth](http://aka.ms/aml-notebook-auth)" "cell_type": "code"
] },
}, {
{ "metadata": {},
"cell_type": "code", "source": [
"execution_count": null, "Accessing the Azure ML workspace requires authentication with Azure.\n",
"metadata": {}, "\n",
"outputs": [], "The default authentication is interactive authentication using the default tenant. Executing the `ws = Workspace.from_config()` line in the cell below will prompt for authentication the first time that it is run.\n",
"source": [ "\n",
"ws = Workspace.from_config()\n", "If you have multiple Azure tenants, you can specify the tenant by replacing the `ws = Workspace.from_config()` line in the cell below with the following:\n",
"\n", "\n",
"# Choose a name for the experiment.\n", "```\n",
"experiment_name = 'automl-classification'\n", "from azureml.core.authentication import InteractiveLoginAuthentication\n",
"\n", "auth = InteractiveLoginAuthentication(tenant_id = 'mytenantid')\n",
"experiment = Experiment(ws, experiment_name)\n", "ws = Workspace.from_config(auth = auth)\n",
"\n", "```\n",
"output = {}\n", "\n",
"output['SDK version'] = azureml.core.VERSION\n", "If you need to run in an environment where interactive login is not possible, you can use Service Principal authentication by replacing the `ws = Workspace.from_config()` line in the cell below with the following:\n",
"output['Subscription ID'] = ws.subscription_id\n", "\n",
"output['Workspace Name'] = ws.name\n", "```\n",
"output['Resource Group'] = ws.resource_group\n", "from azureml.core.authentication import ServicePrincipalAuthentication\n",
"output['Location'] = ws.location\n", "auth = auth = ServicePrincipalAuthentication('mytenantid', 'myappid', 'mypassword')\n",
"output['Experiment Name'] = experiment.name\n", "ws = Workspace.from_config(auth = auth)\n",
"pd.set_option('display.max_colwidth', -1)\n", "```\n",
"outputDf = pd.DataFrame(data = output, index = [''])\n", "For more details, see [aka.ms/aml-notebook-auth](http://aka.ms/aml-notebook-auth)"
"outputDf.T" ],
] "cell_type": "markdown"
}, },
{ {
"cell_type": "markdown", "metadata": {},
"metadata": {}, "outputs": [],
"source": [ "execution_count": null,
"## Data\n", "source": [
"\n", "ws = Workspace.from_config()\n",
"This uses scikit-learn's [load_digits](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html) method." "\n",
] "# Choose a name for the experiment and specify the project folder.\n",
}, "experiment_name = 'automl-classification'\n",
{ "project_folder = './sample_projects/automl-classification'\n",
"cell_type": "code", "\n",
"execution_count": null, "experiment = Experiment(ws, experiment_name)\n",
"metadata": {}, "\n",
"outputs": [], "output = {}\n",
"source": [ "output['SDK version'] = azureml.core.VERSION\n",
"digits = datasets.load_digits()\n", "output['Subscription ID'] = ws.subscription_id\n",
"\n", "output['Workspace Name'] = ws.name\n",
"# Exclude the first 100 rows from training so that they can be used for test.\n", "output['Resource Group'] = ws.resource_group\n",
"X_train = digits.data[100:,:]\n", "output['Location'] = ws.location\n",
"y_train = digits.target[100:]" "output['Project Directory'] = project_folder\n",
] "output['Experiment Name'] = experiment.name\n",
}, "pd.set_option('display.max_colwidth', -1)\n",
{ "outputDf = pd.DataFrame(data = output, index = [''])\n",
"cell_type": "markdown", "outputDf.T"
"metadata": {}, ],
"source": [ "cell_type": "code"
"## Train\n", },
"\n", {
"Instantiate an `AutoMLConfig` object to specify the settings and data used to run the experiment.\n", "metadata": {},
"\n", "source": [
"|Property|Description|\n", "## Data\n",
"|-|-|\n", "\n",
"|**task**|classification or regression|\n", "This uses scikit-learn's [load_digits](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html) method."
"|**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", ],
"|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n", "cell_type": "markdown"
"|**y**|(sparse) array-like, shape = [n_samples, ], Multi-class targets.|\n", },
"|**n_cross_validations**|Number of cross validation splits.|\n", {
"|\n", "metadata": {},
"\n", "outputs": [],
"Automated machine learning trains multiple machine learning pipelines. Each pipelines training is known as an iteration.\n", "execution_count": null,
"* You can specify a maximum number of iterations using the `iterations` parameter.\n", "source": [
"* You can specify a maximum time for the run using the `experiment_timeout_minutes` parameter.\n", "digits = datasets.load_digits()\n",
"* If you specify neither the `iterations` nor the `experiment_timeout_minutes`, automated ML keeps running iterations while it continues to see improvements in the scores.\n", "\n",
"\n", "# Exclude the first 100 rows from training so that they can be used for test.\n",
"The following example doesn't specify `iterations` or `experiment_timeout_minutes` and so runs until the scores stop improving.\n" "X_train = digits.data[100:,:]\n",
] "y_train = digits.target[100:]"
}, ],
{ "cell_type": "code"
"cell_type": "code", },
"execution_count": null, {
"metadata": {}, "metadata": {},
"outputs": [], "source": [
"source": [ "## Train\n",
"automl_config = AutoMLConfig(task = 'classification',\n", "\n",
" primary_metric = 'AUC_weighted',\n", "Instantiate an `AutoMLConfig` object to specify the settings and data used to run the experiment.\n",
" X = X_train, \n", "\n",
" y = y_train,\n", "|Property|Description|\n",
" n_cross_validations = 3)" "|-|-|\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",
{ "|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n",
"cell_type": "markdown", "|**y**|(sparse) array-like, shape = [n_samples, ], Multi-class targets.|\n",
"metadata": {}, "|**n_cross_validations**|Number of cross validation splits.|\n",
"source": [ "|\n",
"Call the `submit` method on the experiment object and pass the run configuration. Execution of local runs is synchronous. Depending on the data and the number of iterations this can run for a while.\n", "\n",
"In this example, we specify `show_output = True` to print currently running iterations to the console." "Automated machine learning trains multiple machine learning pipelines. Each pipelines training is known as an iteration.\n",
] "* You can specify a maximum number of iterations using the `iterations` parameter.\n",
}, "* You can specify a maximum time for the run using the `experiment_timeout_minutes` parameter.\n",
{ "* If you specify neither the `iterations` nor the `experiment_timeout_minutes`, automated ML keeps running iterations while it continues to see improvements in the scores.\n",
"cell_type": "code", "\n",
"execution_count": null, "The following example doesn't specify `iterations` or `experiment_timeout_minutes` and so runs until the scores stop improving.\n"
"metadata": {}, ],
"outputs": [], "cell_type": "markdown"
"source": [ },
"local_run = experiment.submit(automl_config, show_output = True)" {
] "metadata": {},
}, "outputs": [],
{ "execution_count": null,
"cell_type": "code", "source": [
"execution_count": null, "automl_config = AutoMLConfig(task = 'classification',\n",
"metadata": {}, " primary_metric = 'AUC_weighted',\n",
"outputs": [], " X = X_train, \n",
"source": [ " y = y_train,\n",
"local_run" " n_cross_validations = 3)"
] ],
}, "cell_type": "code"
{ },
"cell_type": "markdown", {
"metadata": {}, "metadata": {},
"source": [ "source": [
"Optionally, you can continue an interrupted local run by calling `continue_experiment` without the `iterations` parameter, or run more iterations for a completed run by specifying the `iterations` parameter:" "Call the `submit` method on the experiment object and pass the run configuration. Execution of local runs is synchronous. Depending on the data and the number of iterations this can run for a while.\n",
] "In this example, we specify `show_output = True` to print currently running iterations to the console."
}, ],
{ "cell_type": "markdown"
"cell_type": "code", },
"execution_count": null, {
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "execution_count": null,
"local_run = local_run.continue_experiment(X = X_train, \n", "source": [
" y = y_train, \n", "local_run = experiment.submit(automl_config, show_output = True)"
" show_output = True,\n", ],
" iterations = 5)" "cell_type": "code"
] },
}, {
{ "metadata": {},
"cell_type": "markdown", "outputs": [],
"metadata": {}, "execution_count": null,
"source": [ "source": [
"## Results" "local_run"
] ],
}, "cell_type": "code"
{ },
"cell_type": "markdown", {
"metadata": {}, "metadata": {},
"source": [ "source": [
"#### Widget for Monitoring Runs\n", "Optionally, you can continue an interrupted local run by calling `continue_experiment` without the `iterations` parameter, or run more iterations for a completed run by specifying the `iterations` parameter:"
"\n", ],
"The widget will first report a \"loading\" status while running the first iteration. After completing the first iteration, an auto-updating graph and table will be shown. The widget will refresh once per minute, so you should see the graph update as child runs complete.\n", "cell_type": "markdown"
"\n", },
"**Note:** The widget displays a link at the bottom. Use this link to open a web interface to explore the individual run details." {
] "metadata": {},
}, "outputs": [],
{ "execution_count": null,
"cell_type": "code", "source": [
"execution_count": null, "local_run = local_run.continue_experiment(X = X_train, \n",
"metadata": { " y = y_train, \n",
"tags": [ " show_output = True,\n",
"widget-rundetails-sample" " iterations = 5)"
] ],
}, "cell_type": "code"
"outputs": [], },
"source": [ {
"from azureml.widgets import RunDetails\n", "metadata": {},
"RunDetails(local_run).show() " "source": [
] "## Results"
}, ],
{ "cell_type": "markdown"
"cell_type": "markdown", },
"metadata": {}, {
"source": [ "metadata": {},
"\n", "source": [
"#### Retrieve All Child Runs\n", "#### Widget for Monitoring Runs\n",
"You can also use SDK methods to fetch all the child runs and see individual metrics that we log." "\n",
] "The widget will first report a \"loading\" status while running the first iteration. After completing the first iteration, an auto-updating graph and table will be shown. The widget will refresh once per minute, so you should see the graph update as child runs complete.\n",
}, "\n",
{ "**Note:** The widget displays a link at the bottom. Use this link to open a web interface to explore the individual run details."
"cell_type": "code", ],
"execution_count": null, "cell_type": "markdown"
"metadata": {}, },
"outputs": [], {
"source": [ "metadata": {},
"children = list(local_run.get_children())\n", "outputs": [],
"metricslist = {}\n", "execution_count": null,
"for run in children:\n", "source": [
" properties = run.get_properties()\n", "from azureml.widgets import RunDetails\n",
" metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)}\n", "RunDetails(local_run).show() "
" metricslist[int(properties['iteration'])] = metrics\n", ],
"\n", "cell_type": "code"
"rundata = pd.DataFrame(metricslist).sort_index(1)\n", },
"rundata" {
] "metadata": {},
}, "source": [
{ "\n",
"cell_type": "markdown", "#### Retrieve All Child Runs\n",
"metadata": {}, "You can also use SDK methods to fetch all the child runs and see individual metrics that we log."
"source": [ ],
"### Retrieve the Best Model\n", "cell_type": "markdown"
"\n", },
"Below we select the best pipeline from our iterations. The `get_output` method returns the best run and the fitted model. The Model includes the pipeline and any pre-processing. Overloads on `get_output` allow you to retrieve the best run and fitted model for *any* logged metric or for a particular *iteration*." {
] "metadata": {},
}, "outputs": [],
{ "execution_count": null,
"cell_type": "code", "source": [
"execution_count": null, "children = list(local_run.get_children())\n",
"metadata": {}, "metricslist = {}\n",
"outputs": [], "for run in children:\n",
"source": [ " properties = run.get_properties()\n",
"best_run, fitted_model = local_run.get_output()\n", " metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)}\n",
"print(best_run)" " metricslist[int(properties['iteration'])] = metrics\n",
] "\n",
}, "rundata = pd.DataFrame(metricslist).sort_index(1)\n",
{ "rundata"
"cell_type": "markdown", ],
"metadata": {}, "cell_type": "code"
"source": [ },
"#### Print the properties of the model\n", {
"The fitted_model is a python object and you can read the different properties of the object.\n", "metadata": {},
"The following shows printing hyperparameters for each step in the pipeline." "source": [
] "### Retrieve the Best Model\n",
}, "\n",
{ "Below we select the best pipeline from our iterations. The `get_output` method returns the best run and the fitted model. The Model includes the pipeline and any pre-processing. Overloads on `get_output` allow you to retrieve the best run and fitted model for *any* logged metric or for a particular *iteration*."
"cell_type": "code", ],
"execution_count": null, "cell_type": "markdown"
"metadata": {}, },
"outputs": [], {
"source": [ "metadata": {},
"from pprint import pprint\n", "outputs": [],
"\n", "execution_count": null,
"def print_model(model, prefix=\"\"):\n", "source": [
" for step in model.steps:\n", "best_run, fitted_model = local_run.get_output()\n",
" print(prefix + step[0])\n", "print(best_run)"
" if hasattr(step[1], 'estimators') and hasattr(step[1], 'weights'):\n", ],
" pprint({'estimators': list(e[0] for e in step[1].estimators), 'weights': step[1].weights})\n", "cell_type": "code"
" print()\n", },
" for estimator in step[1].estimators:\n", {
" print_model(estimator[1], estimator[0]+ ' - ')\n", "metadata": {},
" elif hasattr(step[1], '_base_learners') and hasattr(step[1], '_meta_learner'):\n", "source": [
" print(\"\\nMeta Learner\")\n", "#### Print the properties of the model\n",
" pprint(step[1]._meta_learner)\n", "The fitted_model is a python object and you can read the different properties of the object.\n",
" print()\n", "The following shows printing hyperparameters for each step in the pipeline."
" for estimator in step[1]._base_learners:\n", ],
" print_model(estimator[1], estimator[0]+ ' - ')\n", "cell_type": "markdown"
" else:\n", },
" pprint(step[1].get_params())\n", {
" print()\n", "metadata": {},
" \n", "outputs": [],
"print_model(fitted_model)" "execution_count": null,
] "source": [
}, "from pprint import pprint\n",
{ "\n",
"cell_type": "markdown", "def print_model(model, prefix=\"\"):\n",
"metadata": {}, " for step in model.steps:\n",
"source": [ " print(prefix + step[0])\n",
"#### Best Model Based on Any Other Metric\n", " if hasattr(step[1], 'estimators') and hasattr(step[1], 'weights'):\n",
"Show the run and the model that has the smallest `log_loss` value:" " pprint({'estimators': list(e[0] for e in step[1].estimators), 'weights': step[1].weights})\n",
] " print()\n",
}, " for estimator in step[1].estimators:\n",
{ " print_model(estimator[1], estimator[0]+ ' - ')\n",
"cell_type": "code", " elif hasattr(step[1], '_base_learners') and hasattr(step[1], '_meta_learner'):\n",
"execution_count": null, " print(\"\\nMeta Learner\")\n",
"metadata": {}, " pprint(step[1]._meta_learner)\n",
"outputs": [], " print()\n",
"source": [ " for estimator in step[1]._base_learners:\n",
"lookup_metric = \"log_loss\"\n", " print_model(estimator[1], estimator[0]+ ' - ')\n",
"best_run, fitted_model = local_run.get_output(metric = lookup_metric)\n", " else:\n",
"print(best_run)" " pprint(step[1].get_params())\n",
] " print()\n",
}, " \n",
{ "print_model(fitted_model)"
"cell_type": "code", ],
"execution_count": null, "cell_type": "code"
"metadata": {}, },
"outputs": [], {
"source": [ "metadata": {},
"print_model(fitted_model)" "source": [
] "#### Best Model Based on Any Other Metric\n",
}, "Show the run and the model that has the smallest `log_loss` value:"
{ ],
"cell_type": "markdown", "cell_type": "markdown"
"metadata": {}, },
"source": [ {
"#### Model from a Specific Iteration\n", "metadata": {},
"Show the run and the model from the third iteration:" "outputs": [],
] "execution_count": null,
}, "source": [
{ "lookup_metric = \"log_loss\"\n",
"cell_type": "code", "best_run, fitted_model = local_run.get_output(metric = lookup_metric)\n",
"execution_count": null, "print(best_run)"
"metadata": {}, ],
"outputs": [], "cell_type": "code"
"source": [ },
"iteration = 3\n", {
"third_run, third_model = local_run.get_output(iteration = iteration)\n", "metadata": {},
"print(third_run)" "outputs": [],
] "execution_count": null,
}, "source": [
{ "print_model(fitted_model)"
"cell_type": "code", ],
"execution_count": null, "cell_type": "code"
"metadata": {}, },
"outputs": [], {
"source": [ "metadata": {},
"print_model(third_model)" "source": [
] "#### Model from a Specific Iteration\n",
}, "Show the run and the model from the third iteration:"
{ ],
"cell_type": "markdown", "cell_type": "markdown"
"metadata": {}, },
"source": [ {
"## Test \n", "metadata": {},
"\n", "outputs": [],
"#### Load Test Data" "execution_count": null,
] "source": [
}, "iteration = 3\n",
{ "third_run, third_model = local_run.get_output(iteration = iteration)\n",
"cell_type": "code", "print(third_run)"
"execution_count": null, ],
"metadata": {}, "cell_type": "code"
"outputs": [], },
"source": [ {
"digits = datasets.load_digits()\n", "metadata": {},
"X_test = digits.data[:10, :]\n", "outputs": [],
"y_test = digits.target[:10]\n", "execution_count": null,
"images = digits.images[:10]" "source": [
] "print_model(third_model)"
}, ],
{ "cell_type": "code"
"cell_type": "markdown", },
"metadata": {}, {
"source": [ "metadata": {},
"#### Testing Our Best Fitted Model\n", "source": [
"We will try to predict 2 digits and see how our model works." "## Test \n",
] "\n",
}, "#### Load Test Data"
{ ],
"cell_type": "code", "cell_type": "markdown"
"execution_count": null, },
"metadata": {}, {
"outputs": [], "metadata": {},
"source": [ "outputs": [],
"# Randomly select digits and test.\n", "execution_count": null,
"for index in np.random.choice(len(y_test), 2, replace = False):\n", "source": [
" print(index)\n", "digits = datasets.load_digits()\n",
" predicted = fitted_model.predict(X_test[index:index + 1])[0]\n", "X_test = digits.data[:10, :]\n",
" label = y_test[index]\n", "y_test = digits.target[:10]\n",
" title = \"Label value = %d Predicted value = %d \" % (label, predicted)\n", "images = digits.images[:10]"
" fig = plt.figure(1, figsize = (3,3))\n", ],
" ax1 = fig.add_axes((0,0,.8,.8))\n", "cell_type": "code"
" ax1.set_title(title)\n", },
" plt.imshow(images[index], cmap = plt.cm.gray_r, interpolation = 'nearest')\n", {
" plt.show()" "metadata": {},
] "source": [
} "#### Testing Our Best Fitted Model\n",
], "We will try to predict 2 digits and see how our model works."
"metadata": { ],
"authors": [ "cell_type": "markdown"
{ },
"name": "savitam" {
} "metadata": {},
], "outputs": [],
"kernelspec": { "execution_count": null,
"display_name": "Python 3.6", "source": [
"language": "python", "# Randomly select digits and test.\n",
"name": "python36" "for index in np.random.choice(len(y_test), 2, replace = False):\n",
}, " print(index)\n",
"language_info": { " predicted = fitted_model.predict(X_test[index:index + 1])[0]\n",
"codemirror_mode": { " label = y_test[index]\n",
"name": "ipython", " title = \"Label value = %d Predicted value = %d \" % (label, predicted)\n",
"version": 3 " fig = plt.figure(1, figsize = (3,3))\n",
}, " ax1 = fig.add_axes((0,0,.8,.8))\n",
"file_extension": ".py", " ax1.set_title(title)\n",
"mimetype": "text/x-python", " plt.imshow(images[index], cmap = plt.cm.gray_r, interpolation = 'nearest')\n",
"name": "python", " plt.show()"
"nbconvert_exporter": "python", ],
"pygments_lexer": "ipython3", "cell_type": "code"
"version": "3.6.6" }
} ],
}, "nbformat_minor": 2
"nbformat": 4,
"nbformat_minor": 2
} }

View File

@@ -1,8 +1,8 @@
name: auto-ml-classification name: auto-ml-classification
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- azureml-train-automl - azureml-train-automl
- azureml-widgets - azureml-widgets
- matplotlib - matplotlib
- pandas_ml - pandas_ml

View File

@@ -1,9 +1,8 @@
name: automl-forecasting-function name: auto-ml-dataprep-remote-execution
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- azureml-train-automl - azureml-train-automl
- azureml-widgets - azureml-widgets
- pandas_ml - matplotlib
- statsmodels - pandas_ml
- matplotlib

View File

@@ -1,399 +1,417 @@
{ {
"cells": [ "metadata": {
{ "kernelspec": {
"cell_type": "markdown", "display_name": "Python 3.6",
"metadata": {}, "name": "python36",
"source": [ "language": "python"
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/dataprep/auto-ml-dataprep.png)" },
] "authors": [
}, {
{ "name": "savitam"
"cell_type": "markdown", }
"metadata": {}, ],
"source": [ "language_info": {
"Copyright (c) Microsoft Corporation. All rights reserved.\n", "mimetype": "text/x-python",
"\n", "codemirror_mode": {
"Licensed under the MIT License." "name": "ipython",
] "version": 3
}, },
{ "pygments_lexer": "ipython3",
"cell_type": "markdown", "name": "python",
"metadata": {}, "file_extension": ".py",
"source": [ "nbconvert_exporter": "python",
"# Automated Machine Learning\n", "version": "3.6.5"
"_**Load Data using `TabularDataset` for Local Execution**_\n", }
"\n", },
"## Contents\n", "nbformat": 4,
"1. [Introduction](#Introduction)\n", "cells": [
"1. [Setup](#Setup)\n", {
"1. [Data](#Data)\n", "metadata": {},
"1. [Train](#Train)\n", "source": [
"1. [Results](#Results)\n", "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/dataprep/auto-ml-dataprep.png)"
"1. [Test](#Test)" ],
] "cell_type": "markdown"
}, },
{ {
"cell_type": "markdown", "metadata": {},
"metadata": {}, "source": [
"source": [ "Copyright (c) Microsoft Corporation. All rights reserved.\n",
"## Introduction\n", "\n",
"In this example we showcase how you can use AzureML Dataset to load data for AutoML.\n", "Licensed under the MIT License."
"\n", ],
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n", "cell_type": "markdown"
"\n", },
"In this notebook you will learn how to:\n", {
"1. Create a `TabularDataset` pointing to the training data.\n", "metadata": {},
"2. Pass the `TabularDataset` to AutoML for a local run." "source": [
] "# Automated Machine Learning\n",
}, "_**Prepare Data using `azureml.dataprep` for Local Execution**_\n",
{ "\n",
"cell_type": "markdown", "## Contents\n",
"metadata": {}, "1. [Introduction](#Introduction)\n",
"source": [ "1. [Setup](#Setup)\n",
"## Setup" "1. [Data](#Data)\n",
] "1. [Train](#Train)\n",
}, "1. [Results](#Results)\n",
{ "1. [Test](#Test)"
"cell_type": "markdown", ],
"metadata": {}, "cell_type": "markdown"
"source": [ },
"As part of the setup you have already created an Azure ML `Workspace` object. For AutoML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments." {
] "metadata": {},
}, "source": [
{ "## Introduction\n",
"cell_type": "code", "In this example we showcase how you can use the `azureml.dataprep` SDK to load and prepare data for AutoML. `azureml.dataprep` can also be used standalone; full documentation can be found [here](https://github.com/Microsoft/PendletonDocs).\n",
"execution_count": null, "\n",
"metadata": {}, "Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
"outputs": [], "\n",
"source": [ "In this notebook you will learn how to:\n",
"import logging\n", "1. Define data loading and preparation steps in a `Dataflow` using `azureml.dataprep`.\n",
"\n", "2. Pass the `Dataflow` to AutoML for a local run.\n",
"import pandas as pd\n", "3. Pass the `Dataflow` to AutoML for a remote run."
"\n", ],
"import azureml.core\n", "cell_type": "markdown"
"from azureml.core.experiment import Experiment\n", },
"from azureml.core.workspace import Workspace\n", {
"from azureml.core.dataset import Dataset\n", "metadata": {},
"from azureml.train.automl import AutoMLConfig" "source": [
] "## Setup\n",
}, "\n",
{ "Currently, Data Prep only supports __Ubuntu 16__ and __Red Hat Enterprise Linux 7__. We are working on supporting more linux distros."
"cell_type": "code", ],
"execution_count": null, "cell_type": "markdown"
"metadata": {}, },
"outputs": [], {
"source": [ "metadata": {},
"ws = Workspace.from_config()\n", "source": [
" \n", "As part of the setup you have already created an Azure ML `Workspace` object. For AutoML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments."
"# choose a name for experiment\n", ],
"experiment_name = 'automl-dataset-local'\n", "cell_type": "markdown"
" \n", },
"experiment = Experiment(ws, experiment_name)\n", {
" \n", "metadata": {},
"output = {}\n", "outputs": [],
"output['SDK version'] = azureml.core.VERSION\n", "execution_count": null,
"output['Subscription ID'] = ws.subscription_id\n", "source": [
"output['Workspace Name'] = ws.name\n", "import logging\n",
"output['Resource Group'] = ws.resource_group\n", "\n",
"output['Location'] = ws.location\n", "import pandas as pd\n",
"output['Experiment Name'] = experiment.name\n", "\n",
"pd.set_option('display.max_colwidth', -1)\n", "import azureml.core\n",
"outputDf = pd.DataFrame(data = output, index = [''])\n", "from azureml.core.experiment import Experiment\n",
"outputDf.T" "from azureml.core.workspace import Workspace\n",
] "import azureml.dataprep as dprep\n",
}, "from azureml.train.automl import AutoMLConfig"
{ ],
"cell_type": "markdown", "cell_type": "code"
"metadata": {}, },
"source": [ {
"## Data" "metadata": {},
] "outputs": [],
}, "execution_count": null,
{ "source": [
"cell_type": "code", "ws = Workspace.from_config()\n",
"execution_count": null, " \n",
"metadata": {}, "# choose a name for experiment\n",
"outputs": [], "experiment_name = 'automl-dataprep-local'\n",
"source": [ "# project folder\n",
"# The data referenced here was a 1MB simple random sample of the Chicago Crime data into a local temporary directory.\n", "project_folder = './sample_projects/automl-dataprep-local'\n",
"example_data = 'https://dprepdata.blob.core.windows.net/demo/crime0-random.csv'\n", " \n",
"dataset = Dataset.Tabular.from_delimited_files(example_data)\n", "experiment = Experiment(ws, experiment_name)\n",
"dataset.take(5).to_pandas_dataframe()" " \n",
] "output = {}\n",
}, "output['SDK version'] = azureml.core.VERSION\n",
{ "output['Subscription ID'] = ws.subscription_id\n",
"cell_type": "markdown", "output['Workspace Name'] = ws.name\n",
"metadata": {}, "output['Resource Group'] = ws.resource_group\n",
"source": [ "output['Location'] = ws.location\n",
"### Review the data\n", "output['Project Directory'] = project_folder\n",
"\n", "output['Experiment Name'] = experiment.name\n",
"You can peek the result of a `TabularDataset` at any range using `skip(i)` and `take(j).to_pandas_dataframe()`. Doing so evaluates only `j` records, which makes it fast even against large datasets.\n", "pd.set_option('display.max_colwidth', -1)\n",
"\n", "outputDf = pd.DataFrame(data = output, index = [''])\n",
"`TabularDataset` objects are immutable and are composed of a list of subsetting transformations (optional)." "outputDf.T"
] ],
}, "cell_type": "code"
{ },
"cell_type": "code", {
"execution_count": null, "metadata": {},
"metadata": {}, "source": [
"outputs": [], "## Data"
"source": [ ],
"training_data = dataset.drop_columns(columns=['FBI Code'])\n", "cell_type": "markdown"
"label_column_name = 'Primary Type'" },
] {
}, "metadata": {},
{ "outputs": [],
"cell_type": "markdown", "execution_count": null,
"metadata": {}, "source": [
"source": [ "# You can use `auto_read_file` which intelligently figures out delimiters and datatypes of a file.\n",
"## Train\n", "# The data referenced here was a 1MB simple random sample of the Chicago Crime data into a local temporary directory.\n",
"\n", "# You can also use `read_csv` and `to_*` transformations to read (with overridable delimiter)\n",
"This creates a general AutoML settings object applicable for both local and remote runs." "# and convert column types manually.\n",
] "example_data = 'https://dprepdata.blob.core.windows.net/demo/crime0-random.csv'\n",
}, "dflow = dprep.auto_read_file(example_data).skip(1) # Remove the header row.\n",
{ "dflow.get_profile()"
"cell_type": "code", ],
"execution_count": null, "cell_type": "code"
"metadata": {}, },
"outputs": [], {
"source": [ "metadata": {},
"automl_settings = {\n", "outputs": [],
" \"iteration_timeout_minutes\" : 10,\n", "execution_count": null,
" \"iterations\" : 2,\n", "source": [
" \"primary_metric\" : 'AUC_weighted',\n", "# As `Primary Type` is our y data, we need to drop the values those are null in this column.\n",
" \"preprocess\" : True,\n", "dflow = dflow.drop_nulls('Primary Type')\n",
" \"verbosity\" : logging.INFO\n", "dflow.head(5)"
"}" ],
] "cell_type": "code"
}, },
{ {
"cell_type": "markdown", "metadata": {},
"metadata": {}, "source": [
"source": [ "### Review the Data Preparation Result\n",
"### Pass Data with `TabularDataset` Objects\n", "\n",
"\n", "You can peek the result of a Dataflow at any range using `skip(i)` and `head(j)`. Doing so evaluates only `j` records for all the steps in the Dataflow, which makes it fast even against large datasets.\n",
"The `TabularDataset` objects captured above can be passed to the `submit` method for a local run. AutoML will retrieve the results from the `TabularDataset` for model training." "\n",
] "`Dataflow` objects are immutable and are composed of a list of data preparation steps. A `Dataflow` object can be branched at any point for further usage."
}, ],
{ "cell_type": "markdown"
"cell_type": "code", },
"execution_count": null, {
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "execution_count": null,
"automl_config = AutoMLConfig(task = 'classification',\n", "source": [
" debug_log = 'automl_errors.log',\n", "X = dflow.drop_columns(columns=['Primary Type', 'FBI Code'])\n",
" training_data = training_data,\n", "y = dflow.keep_columns(columns=['Primary Type'], validate_column_exists=True)"
" label_column_name = label_column_name,\n", ],
" **automl_settings)" "cell_type": "code"
] },
}, {
{ "metadata": {},
"cell_type": "code", "source": [
"execution_count": null, "## Train\n",
"metadata": {}, "\n",
"outputs": [], "This creates a general AutoML settings object applicable for both local and remote runs."
"source": [ ],
"local_run = experiment.submit(automl_config, show_output = True)" "cell_type": "markdown"
] },
}, {
{ "metadata": {},
"cell_type": "code", "outputs": [],
"execution_count": null, "execution_count": null,
"metadata": {}, "source": [
"outputs": [], "automl_settings = {\n",
"source": [ " \"iteration_timeout_minutes\" : 10,\n",
"local_run" " \"iterations\" : 2,\n",
] " \"primary_metric\" : 'AUC_weighted',\n",
}, " \"preprocess\" : True,\n",
{ " \"verbosity\" : logging.INFO\n",
"cell_type": "markdown", "}"
"metadata": {}, ],
"source": [ "cell_type": "code"
"## Results" },
] {
}, "metadata": {},
{ "source": [
"cell_type": "markdown", "### Pass Data with `Dataflow` Objects\n",
"metadata": {}, "\n",
"source": [ "The `Dataflow` objects captured above can be passed to the `submit` method for a local run. AutoML will retrieve the results from the `Dataflow` for model training."
"#### Widget for Monitoring Runs\n", ],
"\n", "cell_type": "markdown"
"The widget will first report a \"loading\" status while running the first iteration. After completing the first iteration, an auto-updating graph and table will be shown. The widget will refresh once per minute, so you should see the graph update as child runs complete.\n", },
"\n", {
"**Note:** The widget displays a link at the bottom. Use this link to open a web interface to explore the individual run details." "metadata": {},
] "outputs": [],
}, "execution_count": null,
{ "source": [
"cell_type": "code", "automl_config = AutoMLConfig(task = 'classification',\n",
"execution_count": null, " debug_log = 'automl_errors.log',\n",
"metadata": {}, " X = X,\n",
"outputs": [], " y = y,\n",
"source": [ " **automl_settings)"
"from azureml.widgets import RunDetails\n", ],
"RunDetails(local_run).show()" "cell_type": "code"
] },
}, {
{ "metadata": {},
"cell_type": "markdown", "outputs": [],
"metadata": {}, "execution_count": null,
"source": [ "source": [
"#### Retrieve All Child Runs\n", "local_run = experiment.submit(automl_config, show_output = True)"
"You can also use SDK methods to fetch all the child runs and see individual metrics that we log." ],
] "cell_type": "code"
}, },
{ {
"cell_type": "code", "metadata": {},
"execution_count": null, "outputs": [],
"metadata": {}, "execution_count": null,
"outputs": [], "source": [
"source": [ "local_run"
"children = list(local_run.get_children())\n", ],
"metricslist = {}\n", "cell_type": "code"
"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", "metadata": {},
" metricslist[int(properties['iteration'])] = metrics\n", "source": [
" \n", "## Results"
"rundata = pd.DataFrame(metricslist).sort_index(1)\n", ],
"rundata" "cell_type": "markdown"
] },
}, {
{ "metadata": {},
"cell_type": "markdown", "source": [
"metadata": {}, "#### Widget for Monitoring Runs\n",
"source": [ "\n",
"### Retrieve the Best Model\n", "The widget will first report a \"loading\" status while running the first iteration. After completing the first iteration, an auto-updating graph and table will be shown. The widget will refresh once per minute, so you should see the graph update as child runs complete.\n",
"\n", "\n",
"Below we select the best pipeline from our iterations. The `get_output` method returns the best run and the fitted model. Overloads on `get_output` allow you to retrieve the best run and fitted model for *any* logged metric or for a particular *iteration*." "**Note:** The widget displays a link at the bottom. Use this link to open a web interface to explore the individual run details."
] ],
}, "cell_type": "markdown"
{ },
"cell_type": "code", {
"execution_count": null, "metadata": {},
"metadata": {}, "outputs": [],
"outputs": [], "execution_count": null,
"source": [ "source": [
"best_run, fitted_model = local_run.get_output()\n", "from azureml.widgets import RunDetails\n",
"print(best_run)\n", "RunDetails(local_run).show()"
"print(fitted_model)" ],
] "cell_type": "code"
}, },
{ {
"cell_type": "markdown", "metadata": {},
"metadata": {}, "source": [
"source": [ "#### Retrieve All Child Runs\n",
"#### Best Model Based on Any Other Metric\n", "You can also use SDK methods to fetch all the child runs and see individual metrics that we log."
"Show the run and the model that has the smallest `log_loss` value:" ],
] "cell_type": "markdown"
}, },
{ {
"cell_type": "code", "metadata": {},
"execution_count": null, "outputs": [],
"metadata": {}, "execution_count": null,
"outputs": [], "source": [
"source": [ "children = list(local_run.get_children())\n",
"lookup_metric = \"log_loss\"\n", "metricslist = {}\n",
"best_run, fitted_model = local_run.get_output(metric = lookup_metric)\n", "for run in children:\n",
"print(best_run)\n", " properties = run.get_properties()\n",
"print(fitted_model)" " 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",
"cell_type": "markdown", "rundata"
"metadata": {}, ],
"source": [ "cell_type": "code"
"#### Model from a Specific Iteration\n", },
"Show the run and the model from the first iteration:" {
] "metadata": {},
}, "source": [
{ "### Retrieve the Best Model\n",
"cell_type": "code", "\n",
"execution_count": null, "Below we select the best pipeline from our iterations. The `get_output` method returns the best run and the fitted model. Overloads on `get_output` allow you to retrieve the best run and fitted model for *any* logged metric or for a particular *iteration*."
"metadata": {}, ],
"outputs": [], "cell_type": "markdown"
"source": [ },
"iteration = 0\n", {
"best_run, fitted_model = local_run.get_output(iteration = iteration)\n", "metadata": {},
"print(best_run)\n", "outputs": [],
"print(fitted_model)" "execution_count": null,
] "source": [
}, "best_run, fitted_model = local_run.get_output()\n",
{ "print(best_run)\n",
"cell_type": "markdown", "print(fitted_model)"
"metadata": {}, ],
"source": [ "cell_type": "code"
"## Test\n", },
"\n", {
"#### Load Test Data\n", "metadata": {},
"For the test data, it should have the same preparation step as the train data. Otherwise it might get failed at the preprocessing step." "source": [
] "#### Best Model Based on Any Other Metric\n",
}, "Show the run and the model that has the smallest `log_loss` value:"
{ ],
"cell_type": "code", "cell_type": "markdown"
"execution_count": null, },
"metadata": {}, {
"outputs": [], "metadata": {},
"source": [ "outputs": [],
"dataset_test = Dataset.Tabular.from_delimited_files(path='https://dprepdata.blob.core.windows.net/demo/crime0-test.csv')\n", "execution_count": null,
"\n", "source": [
"df_test = dataset_test.to_pandas_dataframe()\n", "lookup_metric = \"log_loss\"\n",
"df_test = df_test[pd.notnull(df_test['Primary Type'])]\n", "best_run, fitted_model = local_run.get_output(metric = lookup_metric)\n",
"\n", "print(best_run)\n",
"y_test = df_test[['Primary Type']]\n", "print(fitted_model)"
"X_test = df_test.drop(['Primary Type', 'FBI Code'], axis=1)" ],
] "cell_type": "code"
}, },
{ {
"cell_type": "markdown", "metadata": {},
"metadata": {}, "source": [
"source": [ "#### Model from a Specific Iteration\n",
"#### Testing Our Best Fitted Model\n", "Show the run and the model from the first iteration:"
"We will use confusion matrix to see how our model works." ],
] "cell_type": "markdown"
}, },
{ {
"cell_type": "code", "metadata": {},
"execution_count": null, "outputs": [],
"metadata": {}, "execution_count": null,
"outputs": [], "source": [
"source": [ "iteration = 0\n",
"from pandas_ml import ConfusionMatrix\n", "best_run, fitted_model = local_run.get_output(iteration = iteration)\n",
"\n", "print(best_run)\n",
"ypred = fitted_model.predict(X_test)\n", "print(fitted_model)"
"\n", ],
"cm = ConfusionMatrix(y_test['Primary Type'], ypred)\n", "cell_type": "code"
"\n", },
"print(cm)\n", {
"\n", "metadata": {},
"cm.plot()" "source": [
] "## Test\n",
} "\n",
], "#### Load Test Data\n",
"metadata": { "For the test data, it should have the same preparation step as the train data. Otherwise it might get failed at the preprocessing step."
"authors": [ ],
{ "cell_type": "markdown"
"name": "savitam" },
} {
], "metadata": {},
"kernelspec": { "outputs": [],
"display_name": "Python 3.6", "execution_count": null,
"language": "python", "source": [
"name": "python36" "dflow_test = dprep.auto_read_file(path='https://dprepdata.blob.core.windows.net/demo/crime0-test.csv').skip(1)\n",
}, "dflow_test = dflow_test.drop_nulls('Primary Type')"
"language_info": { ],
"codemirror_mode": { "cell_type": "code"
"name": "ipython", },
"version": 3 {
}, "metadata": {},
"file_extension": ".py", "source": [
"mimetype": "text/x-python", "#### Testing Our Best Fitted Model\n",
"name": "python", "We will use confusion matrix to see how our model works."
"nbconvert_exporter": "python", ],
"pygments_lexer": "ipython3", "cell_type": "markdown"
"version": "3.6.5" },
} {
}, "metadata": {},
"nbformat": 4, "outputs": [],
"nbformat_minor": 2 "execution_count": null,
"source": [
"from pandas_ml import ConfusionMatrix\n",
"\n",
"y_test = dflow_test.keep_columns(columns=['Primary Type']).to_pandas_dataframe()\n",
"X_test = dflow_test.drop_columns(columns=['Primary Type', 'FBI Code']).to_pandas_dataframe()\n",
"\n",
"ypred = fitted_model.predict(X_test)\n",
"\n",
"cm = ConfusionMatrix(y_test['Primary Type'], ypred)\n",
"\n",
"print(cm)\n",
"\n",
"cm.plot()"
],
"cell_type": "code"
}
],
"nbformat_minor": 2
} }

View File

@@ -1,9 +1,8 @@
name: auto-ml-dataset name: auto-ml-dataprep
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- azureml-train-automl - azureml-train-automl
- azureml-widgets - azureml-widgets
- matplotlib - matplotlib
- pandas_ml - pandas_ml
- azureml-dataprep[pandas]

View File

@@ -1,349 +1,349 @@
{ {
"cells": [ "metadata": {
{ "kernelspec": {
"cell_type": "markdown", "display_name": "Python 3.6",
"metadata": {}, "name": "python36",
"source": [ "language": "python"
"Copyright (c) Microsoft Corporation. All rights reserved.\n", },
"\n", "authors": [
"Licensed under the MIT License." {
] "name": "savitam"
}, }
{ ],
"cell_type": "markdown", "language_info": {
"metadata": {}, "mimetype": "text/x-python",
"source": [ "codemirror_mode": {
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/exploring-previous-runs/auto-ml-exploring-previous-runs.png)" "name": "ipython",
] "version": 3
}, },
{ "pygments_lexer": "ipython3",
"cell_type": "markdown", "name": "python",
"metadata": {}, "file_extension": ".py",
"source": [ "nbconvert_exporter": "python",
"# Automated Machine Learning\n", "version": "3.6.6"
"_**Exploring Previous Runs**_\n", }
"\n", },
"## Contents\n", "nbformat": 4,
"1. [Introduction](#Introduction)\n", "cells": [
"1. [Setup](#Setup)\n", {
"1. [Explore](#Explore)\n", "metadata": {},
"1. [Download](#Download)\n", "source": [
"1. [Register](#Register)" "Copyright (c) Microsoft Corporation. All rights reserved.\n",
] "\n",
}, "Licensed under the MIT License."
{ ],
"cell_type": "markdown", "cell_type": "markdown"
"metadata": {}, },
"source": [ {
"## Introduction\n", "metadata": {},
"In this example we present some examples on navigating previously executed runs. We also show how you can download a fitted model for any previous run.\n", "source": [
"\n", "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/exploring-previous-runs/auto-ml-exploring-previous-runs.png)"
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n", ],
"\n", "cell_type": "markdown"
"In this notebook you will learn how to:\n", },
"1. List all experiments in a workspace.\n", {
"2. List all AutoML runs in an experiment.\n", "metadata": {},
"3. Get details for an AutoML run, including settings, run widget, and all metrics.\n", "source": [
"4. Download a fitted pipeline for any iteration." "# Automated Machine Learning\n",
] "_**Exploring Previous Runs**_\n",
}, "\n",
{ "## Contents\n",
"cell_type": "markdown", "1. [Introduction](#Introduction)\n",
"metadata": {}, "1. [Setup](#Setup)\n",
"source": [ "1. [Explore](#Explore)\n",
"## Setup" "1. [Download](#Download)\n",
] "1. [Register](#Register)"
}, ],
{ "cell_type": "markdown"
"cell_type": "code", },
"execution_count": null, {
"metadata": {}, "metadata": {},
"outputs": [], "source": [
"source": [ "## Introduction\n",
"import pandas as pd\n", "In this example we present some examples on navigating previously executed runs. We also show how you can download a fitted model for any previous run.\n",
"import json\n", "\n",
"\n", "Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
"from azureml.core.experiment import Experiment\n", "\n",
"from azureml.core.workspace import Workspace\n", "In this notebook you will learn how to:\n",
"from azureml.train.automl.run import AutoMLRun" "1. List all experiments in a workspace.\n",
] "2. List all AutoML runs in an experiment.\n",
}, "3. Get details for an AutoML run, including settings, run widget, and all metrics.\n",
{ "4. Download a fitted pipeline for any iteration."
"cell_type": "code", ],
"execution_count": null, "cell_type": "markdown"
"metadata": {}, },
"outputs": [], {
"source": [ "metadata": {},
"ws = Workspace.from_config()" "source": [
] "## Setup"
}, ],
{ "cell_type": "markdown"
"cell_type": "markdown", },
"metadata": {}, {
"source": [ "metadata": {},
"## Explore" "outputs": [],
] "execution_count": null,
}, "source": [
{ "import pandas as pd\n",
"cell_type": "markdown", "import json\n",
"metadata": {}, "\n",
"source": [ "from azureml.core.experiment import Experiment\n",
"### List Experiments" "from azureml.core.workspace import Workspace\n",
] "from azureml.train.automl.run import AutoMLRun"
}, ],
{ "cell_type": "code"
"cell_type": "code", },
"execution_count": null, {
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "execution_count": null,
"experiment_list = Experiment.list(workspace=ws)\n", "source": [
"\n", "ws = Workspace.from_config()"
"summary_df = pd.DataFrame(index = ['No of Runs'])\n", ],
"for experiment in experiment_list:\n", "cell_type": "code"
" automl_runs = list(experiment.get_runs(type='automl'))\n", },
" summary_df[experiment.name] = [len(automl_runs)]\n", {
" \n", "metadata": {},
"pd.set_option('display.max_colwidth', -1)\n", "source": [
"summary_df.T" "## Explore"
] ],
}, "cell_type": "markdown"
{ },
"cell_type": "markdown", {
"metadata": {}, "metadata": {},
"source": [ "source": [
"### List runs for an experiment\n", "### List Experiments"
"Set `experiment_name` to any experiment name from the result of the Experiment.list cell to load the AutoML runs." ],
] "cell_type": "markdown"
}, },
{ {
"cell_type": "code", "metadata": {},
"execution_count": null, "outputs": [],
"metadata": {}, "execution_count": null,
"outputs": [], "source": [
"source": [ "experiment_list = Experiment.list(workspace=ws)\n",
"experiment_name = 'automl-local-classification' # Replace this with any project name from previous cell.\n", "\n",
"\n", "summary_df = pd.DataFrame(index = ['No of Runs'])\n",
"proj = ws.experiments[experiment_name]\n", "for experiment in experiment_list:\n",
"summary_df = pd.DataFrame(index = ['Type', 'Status', 'Primary Metric', 'Iterations', 'Compute', 'Name'])\n", " automl_runs = list(experiment.get_runs(type='automl'))\n",
"automl_runs = list(proj.get_runs(type='automl'))\n", " summary_df[experiment.name] = [len(automl_runs)]\n",
"automl_runs_project = []\n", " \n",
"for run in automl_runs:\n", "pd.set_option('display.max_colwidth', -1)\n",
" properties = run.get_properties()\n", "summary_df.T"
" tags = run.get_tags()\n", ],
" amlsettings = json.loads(properties['AMLSettingsJsonString'])\n", "cell_type": "code"
" if 'iterations' in tags:\n", },
" iterations = tags['iterations']\n", {
" else:\n", "metadata": {},
" iterations = properties['num_iterations']\n", "source": [
" summary_df[run.id] = [amlsettings['task_type'], run.get_details()['status'], properties['primary_metric'], iterations, properties['target'], amlsettings['name']]\n", "### List runs for an experiment\n",
" if run.get_details()['status'] == 'Completed':\n", "Set `experiment_name` to any experiment name from the result of the Experiment.list cell to load the AutoML runs."
" automl_runs_project.append(run.id)\n", ],
" \n", "cell_type": "markdown"
"from IPython.display import HTML\n", },
"projname_html = HTML(\"<h3>{}</h3>\".format(proj.name))\n", {
"\n", "metadata": {},
"from IPython.display import display\n", "outputs": [],
"display(projname_html)\n", "execution_count": null,
"display(summary_df.T)" "source": [
] "experiment_name = 'automl-local-classification' # Replace this with any project name from previous cell.\n",
}, "\n",
{ "proj = ws.experiments[experiment_name]\n",
"cell_type": "markdown", "summary_df = pd.DataFrame(index = ['Type', 'Status', 'Primary Metric', 'Iterations', 'Compute', 'Name'])\n",
"metadata": {}, "automl_runs = list(proj.get_runs(type='automl'))\n",
"source": [ "automl_runs_project = []\n",
"### Get details for a run\n", "for run in automl_runs:\n",
"\n", " properties = run.get_properties()\n",
"Copy the project name and run id from the previous cell output to find more details on a particular run." " tags = run.get_tags()\n",
] " amlsettings = json.loads(properties['AMLSettingsJsonString'])\n",
}, " if 'iterations' in tags:\n",
{ " iterations = tags['iterations']\n",
"cell_type": "code", " else:\n",
"execution_count": null, " iterations = properties['num_iterations']\n",
"metadata": {}, " summary_df[run.id] = [amlsettings['task_type'], run.get_details()['status'], properties['primary_metric'], iterations, properties['target'], amlsettings['name']]\n",
"outputs": [], " if run.get_details()['status'] == 'Completed':\n",
"source": [ " automl_runs_project.append(run.id)\n",
"run_id = automl_runs_project[0] # Replace with your own run_id from above run ids\n", " \n",
"assert (run_id in summary_df.keys()), \"Run id not found! Please set run id to a value from above run ids\"\n", "from IPython.display import HTML\n",
"\n", "projname_html = HTML(\"<h3>{}</h3>\".format(proj.name))\n",
"from azureml.widgets import RunDetails\n", "\n",
"\n", "from IPython.display import display\n",
"experiment = Experiment(ws, experiment_name)\n", "display(projname_html)\n",
"ml_run = AutoMLRun(experiment = experiment, run_id = run_id)\n", "display(summary_df.T)"
"\n", ],
"summary_df = pd.DataFrame(index = ['Type', 'Status', 'Primary Metric', 'Iterations', 'Compute', 'Name', 'Start Time', 'End Time'])\n", "cell_type": "code"
"properties = ml_run.get_properties()\n", },
"tags = ml_run.get_tags()\n", {
"status = ml_run.get_details()\n", "metadata": {},
"amlsettings = json.loads(properties['AMLSettingsJsonString'])\n", "source": [
"if 'iterations' in tags:\n", "### Get details for a run\n",
" iterations = tags['iterations']\n", "\n",
"else:\n", "Copy the project name and run id from the previous cell output to find more details on a particular run."
" iterations = properties['num_iterations']\n", ],
"start_time = None\n", "cell_type": "markdown"
"if 'startTimeUtc' in status:\n", },
" start_time = status['startTimeUtc']\n", {
"end_time = None\n", "metadata": {},
"if 'endTimeUtc' in status:\n", "outputs": [],
" end_time = status['endTimeUtc']\n", "execution_count": null,
"summary_df[ml_run.id] = [amlsettings['task_type'], status['status'], properties['primary_metric'], iterations, properties['target'], amlsettings['name'], start_time, end_time]\n", "source": [
"display(HTML('<h3>Runtime Details</h3>'))\n", "run_id = automl_runs_project[0] # Replace with your own run_id from above run ids\n",
"display(summary_df)\n", "assert (run_id in summary_df.keys()), \"Run id not found! Please set run id to a value from above run ids\"\n",
"\n", "\n",
"#settings_df = pd.DataFrame(data = amlsettings, index = [''])\n", "from azureml.widgets import RunDetails\n",
"display(HTML('<h3>AutoML Settings</h3>'))\n", "\n",
"display(amlsettings)\n", "experiment = Experiment(ws, experiment_name)\n",
"\n", "ml_run = AutoMLRun(experiment = experiment, run_id = run_id)\n",
"display(HTML('<h3>Iterations</h3>'))\n", "\n",
"RunDetails(ml_run).show() \n", "summary_df = pd.DataFrame(index = ['Type', 'Status', 'Primary Metric', 'Iterations', 'Compute', 'Name', 'Start Time', 'End Time'])\n",
"\n", "properties = ml_run.get_properties()\n",
"all_metrics = ml_run.get_metrics(recursive=True)\n", "tags = ml_run.get_tags()\n",
"metricslist = {}\n", "status = ml_run.get_details()\n",
"for run_id, metrics in all_metrics.items():\n", "amlsettings = json.loads(properties['AMLSettingsJsonString'])\n",
" iteration = int(run_id.split('_')[-1])\n", "if 'iterations' in tags:\n",
" float_metrics = {k: v for k, v in metrics.items() if isinstance(v, float)}\n", " iterations = tags['iterations']\n",
" metricslist[iteration] = float_metrics\n", "else:\n",
"\n", " iterations = properties['num_iterations']\n",
"rundata = pd.DataFrame(metricslist).sort_index(1)\n", "start_time = None\n",
"display(HTML('<h3>Metrics</h3>'))\n", "if 'startTimeUtc' in status:\n",
"display(rundata)\n" " start_time = status['startTimeUtc']\n",
] "end_time = None\n",
}, "if 'endTimeUtc' in status:\n",
{ " end_time = status['endTimeUtc']\n",
"cell_type": "markdown", "summary_df[ml_run.id] = [amlsettings['task_type'], status['status'], properties['primary_metric'], iterations, properties['target'], amlsettings['name'], start_time, end_time]\n",
"metadata": {}, "display(HTML('<h3>Runtime Details</h3>'))\n",
"source": [ "display(summary_df)\n",
"## Download" "\n",
] "#settings_df = pd.DataFrame(data = amlsettings, index = [''])\n",
}, "display(HTML('<h3>AutoML Settings</h3>'))\n",
{ "display(amlsettings)\n",
"cell_type": "markdown", "\n",
"metadata": {}, "display(HTML('<h3>Iterations</h3>'))\n",
"source": [ "RunDetails(ml_run).show() \n",
"### Download the Best Model for Any Given Metric" "\n",
] "children = list(ml_run.get_children())\n",
}, "metricslist = {}\n",
{ "for run in children:\n",
"cell_type": "code", " properties = run.get_properties()\n",
"execution_count": null, " metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)}\n",
"metadata": {}, " metricslist[int(properties['iteration'])] = metrics\n",
"outputs": [], "\n",
"source": [ "rundata = pd.DataFrame(metricslist).sort_index(1)\n",
"metric = 'AUC_weighted' # Replace with a metric name.\n", "display(HTML('<h3>Metrics</h3>'))\n",
"best_run, fitted_model = ml_run.get_output(metric = metric)\n", "display(rundata)\n"
"fitted_model" ],
] "cell_type": "code"
}, },
{ {
"cell_type": "markdown", "metadata": {},
"metadata": {}, "source": [
"source": [ "## Download"
"### Download the Model for Any Given Iteration" ],
] "cell_type": "markdown"
}, },
{ {
"cell_type": "code", "metadata": {},
"execution_count": null, "source": [
"metadata": {}, "### Download the Best Model for Any Given Metric"
"outputs": [], ],
"source": [ "cell_type": "markdown"
"iteration = 1 # Replace with an iteration number.\n", },
"best_run, fitted_model = ml_run.get_output(iteration = iteration)\n", {
"fitted_model" "metadata": {},
] "outputs": [],
}, "execution_count": null,
{ "source": [
"cell_type": "markdown", "metric = 'AUC_weighted' # Replace with a metric name.\n",
"metadata": {}, "best_run, fitted_model = ml_run.get_output(metric = metric)\n",
"source": [ "fitted_model"
"## Register" ],
] "cell_type": "code"
}, },
{ {
"cell_type": "markdown", "metadata": {},
"metadata": {}, "source": [
"source": [ "### Download the Model for Any Given Iteration"
"### Register fitted model for deployment\n", ],
"If neither `metric` nor `iteration` are specified in the `register_model` call, the iteration with the best primary metric is registered." "cell_type": "markdown"
] },
}, {
{ "metadata": {},
"cell_type": "code", "outputs": [],
"execution_count": null, "execution_count": null,
"metadata": {}, "source": [
"outputs": [], "iteration = 1 # Replace with an iteration number.\n",
"source": [ "best_run, fitted_model = ml_run.get_output(iteration = iteration)\n",
"description = 'AutoML Model'\n", "fitted_model"
"tags = None\n", ],
"ml_run.register_model(description = description, tags = tags)\n", "cell_type": "code"
"print(ml_run.model_id) # Use this id to deploy the model as a web service in Azure." },
] {
}, "metadata": {},
{ "source": [
"cell_type": "markdown", "## Register"
"metadata": {}, ],
"source": [ "cell_type": "markdown"
"### Register the Best Model for Any Given Metric" },
] {
}, "metadata": {},
{ "source": [
"cell_type": "code", "### Register fitted model for deployment\n",
"execution_count": null, "If neither `metric` nor `iteration` are specified in the `register_model` call, the iteration with the best primary metric is registered."
"metadata": {}, ],
"outputs": [], "cell_type": "markdown"
"source": [ },
"metric = 'AUC_weighted' # Replace with a metric name.\n", {
"description = 'AutoML Model'\n", "metadata": {},
"tags = None\n", "outputs": [],
"ml_run.register_model(description = description, tags = tags, metric = metric)\n", "execution_count": null,
"print(ml_run.model_id) # Use this id to deploy the model as a web service in Azure." "source": [
] "description = 'AutoML Model'\n",
}, "tags = None\n",
{ "ml_run.register_model(description = description, tags = tags)\n",
"cell_type": "markdown", "print(ml_run.model_id) # Use this id to deploy the model as a web service in Azure."
"metadata": {}, ],
"source": [ "cell_type": "code"
"### Register the Model for Any Given Iteration" },
] {
}, "metadata": {},
{ "source": [
"cell_type": "code", "### Register the Best Model for Any Given Metric"
"execution_count": null, ],
"metadata": {}, "cell_type": "markdown"
"outputs": [], },
"source": [ {
"iteration = 1 # Replace with an iteration number.\n", "metadata": {},
"description = 'AutoML Model'\n", "outputs": [],
"tags = None\n", "execution_count": null,
"ml_run.register_model(description = description, tags = tags, iteration = iteration)\n", "source": [
"print(ml_run.model_id) # Use this id to deploy the model as a web service in Azure." "metric = 'AUC_weighted' # Replace with a metric name.\n",
] "description = 'AutoML Model'\n",
} "tags = None\n",
], "ml_run.register_model(description = description, tags = tags, metric = metric)\n",
"metadata": { "print(ml_run.model_id) # Use this id to deploy the model as a web service in Azure."
"authors": [ ],
{ "cell_type": "code"
"name": "savitam" },
} {
], "metadata": {},
"kernelspec": { "source": [
"display_name": "Python 3.6", "### Register the Model for Any Given Iteration"
"language": "python", ],
"name": "python36" "cell_type": "markdown"
}, },
"language_info": { {
"codemirror_mode": { "metadata": {},
"name": "ipython", "outputs": [],
"version": 3 "execution_count": null,
}, "source": [
"file_extension": ".py", "iteration = 1 # Replace with an iteration number.\n",
"mimetype": "text/x-python", "description = 'AutoML Model'\n",
"name": "python", "tags = None\n",
"nbconvert_exporter": "python", "ml_run.register_model(description = description, tags = tags, iteration = iteration)\n",
"pygments_lexer": "ipython3", "print(ml_run.model_id) # Use this id to deploy the model as a web service in Azure."
"version": "3.6.6" ],
} "cell_type": "code"
}, }
"nbformat": 4, ],
"nbformat_minor": 2 "nbformat_minor": 2
} }

View File

@@ -1,8 +1,8 @@
name: auto-ml-exploring-previous-runs name: auto-ml-exploring-previous-runs
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- azureml-train-automl - azureml-train-automl
- azureml-widgets - azureml-widgets
- matplotlib - matplotlib
- pandas_ml - pandas_ml

View File

@@ -1,9 +1,9 @@
name: auto-ml-forecasting-bike-share name: auto-ml-forecasting-bike-share
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- azureml-train-automl - azureml-train-automl
- azureml-widgets - azureml-widgets
- matplotlib - matplotlib
- pandas_ml - pandas_ml
- statsmodels - statsmodels

View File

@@ -1,12 +1,10 @@
name: auto-ml-forecasting-energy-demand name: auto-ml-forecasting-energy-demand
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- interpret - azureml-train-automl
- azureml-train-automl - azureml-widgets
- azureml-widgets - matplotlib
- matplotlib - pandas_ml
- pandas_ml - statsmodels
- statsmodels - azureml-explain-model
- azureml-explain-model
- azureml-contrib-interpret

View File

@@ -1,615 +0,0 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Automated Machine Learning\n",
"\n",
"## Forecasting away from training data\n",
"\n",
"This notebook demonstrates the full interface to the `forecast()` function. \n",
"\n",
"The best known and most frequent usage of `forecast` enables forecasting on test sets that immediately follows training data. \n",
"\n",
"However, in many use cases it is necessary to continue using the model for some time before retraining it. This happens especially in **high frequency forecasting** when forecasts need to be made more frequently than the model can be retrained. Examples are in Internet of Things and predictive cloud resource scaling.\n",
"\n",
"Here we show how to use the `forecast()` function when a time gap exists between training data and prediction period.\n",
"\n",
"Terminology:\n",
"* forecast origin: the last period when the target value is known\n",
"* forecast periods(s): the period(s) for which the value of the target is desired.\n",
"* forecast horizon: the number of forecast periods\n",
"* lookback: how many past periods (before forecast origin) the model function depends on. The larger of number of lags and length of rolling window.\n",
"* prediction context: `lookback` periods immediately preceding the forecast origin\n",
"\n",
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/automl-forecasting-function.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Setup"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Please make sure you have followed the `configuration.ipynb` notebook so that your ML workspace information is saved in the config file."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"import numpy as np\n",
"import logging\n",
"import warnings\n",
"\n",
"from pandas.tseries.frequencies import to_offset\n",
"\n",
"# Squash warning messages for cleaner output in the notebook\n",
"warnings.showwarning = lambda *args, **kwargs: None\n",
"\n",
"np.set_printoptions(precision=4, suppress=True, linewidth=120)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import azureml.core\n",
"from azureml.core.workspace import Workspace\n",
"from azureml.core.experiment import Experiment\n",
"from azureml.train.automl import AutoMLConfig\n",
"\n",
"ws = Workspace.from_config()\n",
"\n",
"# choose a name for the run history container in the workspace\n",
"experiment_name = 'automl-forecast-function-demo'\n",
"\n",
"experiment = Experiment(ws, experiment_name)\n",
"\n",
"output = {}\n",
"output['SDK version'] = azureml.core.VERSION\n",
"output['Subscription ID'] = ws.subscription_id\n",
"output['Workspace'] = ws.name\n",
"output['Resource Group'] = ws.resource_group\n",
"output['Location'] = ws.location\n",
"output['Run History Name'] = experiment_name\n",
"pd.set_option('display.max_colwidth', -1)\n",
"outputDf = pd.DataFrame(data = output, index = [''])\n",
"outputDf.T"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Data\n",
"For the demonstration purposes we will generate the data artificially and use them for the forecasting."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"TIME_COLUMN_NAME = 'date'\n",
"GRAIN_COLUMN_NAME = 'grain'\n",
"TARGET_COLUMN_NAME = 'y'\n",
"\n",
"def get_timeseries(train_len: int,\n",
" test_len: int,\n",
" time_column_name: str,\n",
" target_column_name: str,\n",
" grain_column_name: str,\n",
" grains: int = 1,\n",
" freq: str = 'H'):\n",
" \"\"\"\n",
" Return the time series of designed length.\n",
"\n",
" :param train_len: The length of training data (one series).\n",
" :type train_len: int\n",
" :param test_len: The length of testing data (one series).\n",
" :type test_len: int\n",
" :param time_column_name: The desired name of a time column.\n",
" :type time_column_name: str\n",
" :param\n",
" :param grains: The number of grains.\n",
" :type grains: int\n",
" :param freq: The frequency string representing pandas offset.\n",
" see https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html\n",
" :type freq: str\n",
" :returns: the tuple of train and test data sets.\n",
" :rtype: tuple\n",
"\n",
" \"\"\"\n",
" data_train = [] # type: List[pd.DataFrame]\n",
" data_test = [] # type: List[pd.DataFrame]\n",
" data_length = train_len + test_len\n",
" for i in range(grains):\n",
" X = pd.DataFrame({\n",
" time_column_name: pd.date_range(start='2000-01-01',\n",
" periods=data_length,\n",
" freq=freq),\n",
" target_column_name: np.arange(data_length).astype(float) + np.random.rand(data_length) + i*5,\n",
" 'ext_predictor': np.asarray(range(42, 42 + data_length)),\n",
" grain_column_name: np.repeat('g{}'.format(i), data_length)\n",
" })\n",
" data_train.append(X[:train_len])\n",
" data_test.append(X[train_len:])\n",
" X_train = pd.concat(data_train)\n",
" y_train = X_train.pop(target_column_name).values\n",
" X_test = pd.concat(data_test)\n",
" y_test = X_test.pop(target_column_name).values\n",
" return X_train, y_train, X_test, y_test\n",
"\n",
"n_test_periods = 6\n",
"n_train_periods = 30\n",
"X_train, y_train, X_test, y_test = get_timeseries(train_len=n_train_periods,\n",
" test_len=n_test_periods,\n",
" time_column_name=TIME_COLUMN_NAME,\n",
" target_column_name=TARGET_COLUMN_NAME,\n",
" grain_column_name=GRAIN_COLUMN_NAME,\n",
" grains=2)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's see what the training data looks like."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"X_train.tail()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# plot the example time series\n",
"import matplotlib.pyplot as plt\n",
"whole_data = X_train.copy()\n",
"whole_data['y'] = y_train\n",
"for g in whole_data.groupby('grain'): \n",
" plt.plot(g[1]['date'].values, g[1]['y'].values, label=g[0])\n",
"plt.legend()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Create the configuration and train a forecaster\n",
"First generate the configuration, in which we:\n",
"* Set metadata columns: target, time column and grain column names.\n",
"* Ask for 10 iterations through models, last of which will represent the Ensemble of previous ones.\n",
"* Validate our data using cross validation with rolling window method.\n",
"* Set normalized root mean squared error as a metric to select the best model.\n",
"\n",
"* Finally, we set the task to be forecasting.\n",
"* By default, we apply the lag lead operator and rolling window to the target value i.e. we use the previous values as a predictor for the future ones."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"lags = [1,2,3]\n",
"rolling_window_length = 0 # don't do rolling windows\n",
"max_horizon = n_test_periods\n",
"time_series_settings = { \n",
" 'time_column_name': TIME_COLUMN_NAME,\n",
" 'grain_column_names': [ GRAIN_COLUMN_NAME ],\n",
" 'max_horizon': max_horizon,\n",
" 'target_lags': lags\n",
"}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Run the model selection and training process."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.core.workspace import Workspace\n",
"from azureml.core.experiment import Experiment\n",
"from azureml.train.automl import AutoMLConfig\n",
"\n",
"\n",
"automl_config = AutoMLConfig(task='forecasting',\n",
" debug_log='automl_forecasting_function.log',\n",
" primary_metric='normalized_root_mean_squared_error', \n",
" iterations=10, \n",
" X=X_train,\n",
" y=y_train,\n",
" n_cross_validations=3,\n",
" verbosity = logging.INFO,\n",
" **time_series_settings)\n",
"\n",
"local_run = experiment.submit(automl_config, show_output=True)\n",
"\n",
"# Retrieve the best model to use it further.\n",
"_, fitted_model = local_run.get_output()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Forecasting from the trained model"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In this section we will review the `forecast` interface for two main scenarios: forecasting right after the training data, and the more complex interface for forecasting when there is a gap (in the time sense) between training and testing data."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### X_train is directly followed by the X_test\n",
"\n",
"Let's first consider the case when the prediction period immediately follows the training data. This is typical in scenarios where we have the time to retrain the model every time we wish to forecast. Forecasts that are made on daily and slower cadence typically fall into this category. Retraining the model every time benefits the accuracy because the most recent data is often the most informative.\n",
"\n",
"![Forecasting after training](forecast_function_at_train.png)\n",
"\n",
"The `X_test` and `y_query` below, taken together, form the **forecast request**. The two are interpreted as aligned - `y_query` could actally be a column in `X_test`. `NaN`s in `y_query` are the question marks. These will be filled with the forecasts.\n",
"\n",
"When the forecast period immediately follows the training period, the models retain the last few points of data. You can simply fill `y_query` filled with question marks - the model has the data for the lookback already.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Typical path: X_test is known, forecast all upcoming periods"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# The data set contains hourly data, the training set ends at 01/02/2000 at 05:00\n",
"\n",
"# These are predictions we are asking the model to make (does not contain thet target column y),\n",
"# for 6 periods beginning with 2000-01-02 06:00, which immediately follows the training data\n",
"X_test"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"y_query = np.repeat(np.NaN, X_test.shape[0])\n",
"y_pred_no_gap, xy_nogap = fitted_model.forecast(X_test, y_query)\n",
"\n",
"# xy_nogap contains the predictions in the _automl_target_col column.\n",
"# Those same numbers are output in y_pred_no_gap\n",
"xy_nogap"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Distribution forecasts\n",
"\n",
"Often the figure of interest is not just the point prediction, but the prediction at some quantile of the distribution. \n",
"This arises when the forecast is used to control some kind of inventory, for example of grocery items of virtual machines for a cloud service. In such case, the control point is usually something like \"we want the item to be in stock and not run out 99% of the time\". This is called a \"service level\". Here is how you get quantile forecasts."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# specify which quantiles you would like \n",
"fitted_model.quantiles = [0.01, 0.5, 0.95]\n",
"# use forecast_quantiles function, not the forecast() one\n",
"y_pred_quantiles = fitted_model.forecast_quantiles(X_test, y_query)\n",
"\n",
"# it all nicely aligns column-wise\n",
"pd.concat([X_test.reset_index(), pd.DataFrame({'query' : y_query}), y_pred_quantiles], axis=1)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Destination-date forecast: \"just do something\"\n",
"\n",
"In some scenarios, the X_test is not known. The forecast is likely to be weak, becaus eit is missing contemporaneous predictors, which we will need to impute. If you still wish to predict forward under the assumption that the last known values will be carried forward, you can forecast out to \"destination date\". The destination date still needs to fit within the maximum horizon from training."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# We will take the destination date as a last date in the test set.\n",
"dest = max(X_test[TIME_COLUMN_NAME])\n",
"y_pred_dest, xy_dest = fitted_model.forecast(forecast_destination=dest)\n",
"\n",
"# This form also shows how we imputed the predictors which were not given. (Not so well! Use with caution!)\n",
"xy_dest"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Forecasting away from training data\n",
"\n",
"Suppose we trained a model, some time passed, and now we want to apply the model without re-training. If the model \"looks back\" -- uses previous values of the target -- then we somehow need to provide those values to the model.\n",
"\n",
"![Forecasting after training](forecast_function_away_from_train.png)\n",
"\n",
"The notion of forecast origin comes into play: the forecast origin is **the last period for which we have seen the target value**. This applies per grain, so each grain can have a different forecast origin. \n",
"\n",
"The part of data before the forecast origin is the **prediction context**. To provide the context values the model needs when it looks back, we pass definite values in `y_test` (aligned with corresponding times in `X_test`)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# generate the same kind of test data we trained on, \n",
"# but now make the train set much longer, so that the test set will be in the future\n",
"X_context, y_context, X_away, y_away = get_timeseries(train_len=42, # train data was 30 steps long\n",
" test_len=4,\n",
" time_column_name=TIME_COLUMN_NAME,\n",
" target_column_name=TARGET_COLUMN_NAME,\n",
" grain_column_name=GRAIN_COLUMN_NAME,\n",
" grains=2)\n",
"\n",
"# end of the data we trained on\n",
"print(X_train.groupby(GRAIN_COLUMN_NAME)[TIME_COLUMN_NAME].max())\n",
"# start of the data we want to predict on\n",
"print(X_away.groupby(GRAIN_COLUMN_NAME)[TIME_COLUMN_NAME].min())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"There is a gap of 12 hours between end of training and beginning of `X_away`. (It looks like 13 because all timestamps point to the start of the one hour periods.) Using only `X_away` will fail without adding context data for the model to consume."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"try: \n",
" y_query = y_away.copy()\n",
" y_query.fill(np.NaN)\n",
" y_pred_away, xy_away = fitted_model.forecast(X_away, y_query)\n",
" xy_away\n",
"except Exception as e:\n",
" print(e)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"How should we read that eror message? The forecast origin is at the last time themodel saw an actual values of `y` (the target). That was at the end of the training data! Because the model received all `NaN` (and not an actual target value), it is attempting to forecast from the end of training data. But the requested forecast periods are past the maximum horizon. We need to provide a define `y` value to establish the forecast origin.\n",
"\n",
"We will use this helper function to take the required amount of context from the data preceding the testing data. It's definition is intentionally simplified to keep the idea in the clear."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def make_forecasting_query(fulldata, time_column_name, target_column_name, forecast_origin, horizon, lookback):\n",
"\n",
" \"\"\"\n",
" This function will take the full dataset, and create the query\n",
" to predict all values of the grain from the `forecast_origin`\n",
" forward for the next `horizon` horizons. Context from previous\n",
" `lookback` periods will be included.\n",
"\n",
" \n",
"\n",
" fulldata: pandas.DataFrame a time series dataset. Needs to contain X and y.\n",
" time_column_name: string which column (must be in fulldata) is the time axis\n",
" target_column_name: string which column (must be in fulldata) is to be forecast\n",
" forecast_origin: datetime type the last time we (pretend to) have target values \n",
" horizon: timedelta how far forward, in time units (not periods)\n",
" lookback: timedelta how far back does the model look?\n",
"\n",
" Example:\n",
"\n",
"\n",
" ```\n",
"\n",
" forecast_origin = pd.to_datetime('2012-09-01') + pd.DateOffset(days=5) # forecast 5 days after end of training\n",
" print(forecast_origin)\n",
"\n",
" X_query, y_query = make_forecasting_query(data, \n",
" forecast_origin = forecast_origin,\n",
" horizon = pd.DateOffset(days=7), # 7 days into the future\n",
" lookback = pd.DateOffset(days=1), # model has lag 1 period (day)\n",
" )\n",
"\n",
" ```\n",
" \"\"\"\n",
"\n",
" X_past = fulldata[ (fulldata[ time_column_name ] > forecast_origin - lookback) &\n",
" (fulldata[ time_column_name ] <= forecast_origin)\n",
" ]\n",
"\n",
" X_future = fulldata[ (fulldata[ time_column_name ] > forecast_origin) &\n",
" (fulldata[ time_column_name ] <= forecast_origin + horizon)\n",
" ]\n",
"\n",
" y_past = X_past.pop(target_column_name).values.astype(np.float)\n",
" y_future = X_future.pop(target_column_name).values.astype(np.float)\n",
"\n",
" # Now take y_future and turn it into question marks\n",
" y_query = y_future.copy().astype(np.float) # because sometimes life hands you an int\n",
" y_query.fill(np.NaN)\n",
"\n",
"\n",
" print(\"X_past is \" + str(X_past.shape) + \" - shaped\")\n",
" print(\"X_future is \" + str(X_future.shape) + \" - shaped\")\n",
" print(\"y_past is \" + str(y_past.shape) + \" - shaped\")\n",
" print(\"y_query is \" + str(y_query.shape) + \" - shaped\")\n",
"\n",
"\n",
" X_pred = pd.concat([X_past, X_future])\n",
" y_pred = np.concatenate([y_past, y_query])\n",
" return X_pred, y_pred"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's see where the context data ends - it ends, by construction, just before the testing data starts."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(X_context.groupby(GRAIN_COLUMN_NAME)[TIME_COLUMN_NAME].agg(['min','max','count']))\n",
"print( X_away.groupby(GRAIN_COLUMN_NAME)[TIME_COLUMN_NAME].agg(['min','max','count']))\n",
"X_context.tail(5)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Since the length of the lookback is 3, \n",
"# we need to add 3 periods from the context to the request\n",
"# so that the model has the data it needs\n",
"\n",
"# Put the X and y back together for a while. \n",
"# They like each other and it makes them happy.\n",
"X_context[TARGET_COLUMN_NAME] = y_context\n",
"X_away[TARGET_COLUMN_NAME] = y_away\n",
"fulldata = pd.concat([X_context, X_away])\n",
"\n",
"# forecast origin is the last point of data, which is one 1-hr period before test\n",
"forecast_origin = X_away[TIME_COLUMN_NAME].min() - pd.DateOffset(hours=1)\n",
"# it is indeed the last point of the context\n",
"assert forecast_origin == X_context[TIME_COLUMN_NAME].max()\n",
"print(\"Forecast origin: \" + str(forecast_origin))\n",
" \n",
"# the model uses lags and rolling windows to look back in time\n",
"n_lookback_periods = max(max(lags), rolling_window_length)\n",
"lookback = pd.DateOffset(hours=n_lookback_periods)\n",
"\n",
"horizon = pd.DateOffset(hours=max_horizon)\n",
"\n",
"# now make the forecast query from context (refer to figure)\n",
"X_pred, y_pred = make_forecasting_query(fulldata, TIME_COLUMN_NAME, TARGET_COLUMN_NAME,\n",
" forecast_origin, horizon, lookback)\n",
"\n",
"# show the forecast request aligned\n",
"X_show = X_pred.copy()\n",
"X_show[TARGET_COLUMN_NAME] = y_pred\n",
"X_show"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note that the forecast origin is at 17:00 for both grains, and periods from 18:00 are to be forecast."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Now everything works\n",
"y_pred_away, xy_away = fitted_model.forecast(X_pred, y_pred)\n",
"\n",
"# show the forecast aligned\n",
"X_show = xy_away.reset_index()\n",
"# without the generated features\n",
"X_show[['date', 'grain', 'ext_predictor', '_automl_target_col']]\n",
"# prediction is in _automl_target_col"
]
}
],
"metadata": {
"authors": [
{
"name": "erwright, nirovins"
}
],
"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"
}
},
"nbformat": 4,
"nbformat_minor": 2
}

View File

@@ -1,9 +1,9 @@
name: auto-ml-forecasting-orange-juice-sales name: auto-ml-forecasting-orange-juice-sales
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- azureml-train-automl - azureml-train-automl
- azureml-widgets - azureml-widgets
- matplotlib - matplotlib
- pandas_ml - pandas_ml
- statsmodels - statsmodels

View File

@@ -1,423 +1,424 @@
{ {
"cells": [ "metadata": {
{ "kernelspec": {
"cell_type": "markdown", "display_name": "Python 3.6",
"metadata": {}, "name": "python36",
"source": [ "language": "python"
"Copyright (c) Microsoft Corporation. All rights reserved.\n", },
"\n", "authors": [
"Licensed under the MIT License." {
] "name": "savitam"
}, }
{ ],
"cell_type": "markdown", "language_info": {
"metadata": {}, "mimetype": "text/x-python",
"source": [ "codemirror_mode": {
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/missing-data-blacklist-early-termination/auto-ml-missing-data-blacklist-early-termination.png)" "name": "ipython",
] "version": 3
}, },
{ "pygments_lexer": "ipython3",
"cell_type": "markdown", "name": "python",
"metadata": {}, "file_extension": ".py",
"source": [ "nbconvert_exporter": "python",
"# Automated Machine Learning\n", "version": "3.6.6"
"_**Blacklisting Models, Early Termination, and Handling Missing Data**_\n", }
"\n", },
"## Contents\n", "nbformat": 4,
"1. [Introduction](#Introduction)\n", "cells": [
"1. [Setup](#Setup)\n", {
"1. [Data](#Data)\n", "metadata": {},
"1. [Train](#Train)\n", "source": [
"1. [Results](#Results)\n", "Copyright (c) Microsoft Corporation. All rights reserved.\n",
"1. [Test](#Test)\n" "\n",
] "Licensed under the MIT License."
}, ],
{ "cell_type": "markdown"
"cell_type": "markdown", },
"metadata": {}, {
"source": [ "metadata": {},
"## Introduction\n", "source": [
"In this example we use the scikit-learn's [digit dataset](http://scikit-learn.org/stable/datasets/index.html#optical-recognition-of-handwritten-digits-dataset) to showcase how you can use AutoML for handling missing values in data. We also provide a stopping metric indicating a target for the primary metrics so that AutoML can terminate the run without necessarly going through all the iterations. Finally, if you want to avoid a certain pipeline, we allow you to specify a blacklist of algorithms that AutoML will ignore for this run.\n", "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/missing-data-blacklist-early-termination/auto-ml-missing-data-blacklist-early-termination.png)"
"\n", ],
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n", "cell_type": "markdown"
"\n", },
"In this notebook you will learn how to:\n", {
"1. Create an `Experiment` in an existing `Workspace`.\n", "metadata": {},
"2. Configure AutoML using `AutoMLConfig`.\n", "source": [
"3. Train the model.\n", "# Automated Machine Learning\n",
"4. Explore the results.\n", "_**Blacklisting Models, Early Termination, and Handling Missing Data**_\n",
"5. Viewing the engineered names for featurized data and featurization summary for all raw features.\n", "\n",
"6. Test the best fitted model.\n", "## Contents\n",
"\n", "1. [Introduction](#Introduction)\n",
"In addition this notebook showcases the following features\n", "1. [Setup](#Setup)\n",
"- **Blacklisting** certain pipelines\n", "1. [Data](#Data)\n",
"- Specifying **target metrics** to indicate stopping criteria\n", "1. [Train](#Train)\n",
"- Handling **missing data** in the input" "1. [Results](#Results)\n",
] "1. [Test](#Test)\n"
}, ],
{ "cell_type": "markdown"
"cell_type": "markdown", },
"metadata": {}, {
"source": [ "metadata": {},
"## Setup\n", "source": [
"\n", "## Introduction\n",
"As part of the setup you have already created an Azure ML `Workspace` object. For AutoML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments." "In this example we use the scikit-learn's [digit dataset](http://scikit-learn.org/stable/datasets/index.html#optical-recognition-of-handwritten-digits-dataset) to showcase how you can use AutoML for handling missing values in data. We also provide a stopping metric indicating a target for the primary metrics so that AutoML can terminate the run without necessarly going through all the iterations. Finally, if you want to avoid a certain pipeline, we allow you to specify a blacklist of algorithms that AutoML will ignore for this run.\n",
] "\n",
}, "Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
{ "\n",
"cell_type": "code", "In this notebook you will learn how to:\n",
"execution_count": null, "1. Create an `Experiment` in an existing `Workspace`.\n",
"metadata": {}, "2. Configure AutoML using `AutoMLConfig`.\n",
"outputs": [], "3. Train the model.\n",
"source": [ "4. Explore the results.\n",
"import logging\n", "5. Viewing the engineered names for featurized data and featurization summary for all raw features.\n",
"\n", "6. Test the best fitted model.\n",
"from matplotlib import pyplot as plt\n", "\n",
"import numpy as np\n", "In addition this notebook showcases the following features\n",
"import pandas as pd\n", "- **Blacklisting** certain pipelines\n",
"from sklearn import datasets\n", "- Specifying **target metrics** to indicate stopping criteria\n",
"\n", "- Handling **missing data** in the input"
"import azureml.core\n", ],
"from azureml.core.experiment import Experiment\n", "cell_type": "markdown"
"from azureml.core.workspace import Workspace\n", },
"from azureml.train.automl import AutoMLConfig" {
] "metadata": {},
}, "source": [
{ "## Setup\n",
"cell_type": "code", "\n",
"execution_count": null, "As part of the setup you have already created an Azure ML `Workspace` object. For AutoML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments."
"metadata": {}, ],
"outputs": [], "cell_type": "markdown"
"source": [ },
"ws = Workspace.from_config()\n", {
"\n", "metadata": {},
"# Choose a name for the experiment.\n", "outputs": [],
"experiment_name = 'automl-local-missing-data'\n", "execution_count": null,
"\n", "source": [
"experiment = Experiment(ws, experiment_name)\n", "import logging\n",
"\n", "\n",
"output = {}\n", "from matplotlib import pyplot as plt\n",
"output['SDK version'] = azureml.core.VERSION\n", "import numpy as np\n",
"output['Subscription ID'] = ws.subscription_id\n", "import pandas as pd\n",
"output['Workspace'] = ws.name\n", "from sklearn import datasets\n",
"output['Resource Group'] = ws.resource_group\n", "\n",
"output['Location'] = ws.location\n", "import azureml.core\n",
"output['Experiment Name'] = experiment.name\n", "from azureml.core.experiment import Experiment\n",
"pd.set_option('display.max_colwidth', -1)\n", "from azureml.core.workspace import Workspace\n",
"outputDf = pd.DataFrame(data = output, index = [''])\n", "from azureml.train.automl import AutoMLConfig"
"outputDf.T" ],
] "cell_type": "code"
}, },
{ {
"cell_type": "markdown", "metadata": {},
"metadata": {}, "outputs": [],
"source": [ "execution_count": null,
"## Data" "source": [
] "ws = Workspace.from_config()\n",
}, "\n",
{ "# Choose a name for the experiment.\n",
"cell_type": "code", "experiment_name = 'automl-local-missing-data'\n",
"execution_count": null, "project_folder = './sample_projects/automl-local-missing-data'\n",
"metadata": {}, "\n",
"outputs": [], "experiment = Experiment(ws, experiment_name)\n",
"source": [ "\n",
"digits = datasets.load_digits()\n", "output = {}\n",
"X_train = digits.data[10:,:]\n", "output['SDK version'] = azureml.core.VERSION\n",
"y_train = digits.target[10:]\n", "output['Subscription ID'] = ws.subscription_id\n",
"\n", "output['Workspace'] = ws.name\n",
"# Add missing values in 75% of the lines.\n", "output['Resource Group'] = ws.resource_group\n",
"missing_rate = 0.75\n", "output['Location'] = ws.location\n",
"n_missing_samples = int(np.floor(X_train.shape[0] * missing_rate))\n", "output['Project Directory'] = project_folder\n",
"missing_samples = np.hstack((np.zeros(X_train.shape[0] - n_missing_samples, dtype=np.bool), np.ones(n_missing_samples, dtype=np.bool)))\n", "output['Experiment Name'] = experiment.name\n",
"rng = np.random.RandomState(0)\n", "pd.set_option('display.max_colwidth', -1)\n",
"rng.shuffle(missing_samples)\n", "outputDf = pd.DataFrame(data = output, index = [''])\n",
"missing_features = rng.randint(0, X_train.shape[1], n_missing_samples)\n", "outputDf.T"
"X_train[np.where(missing_samples)[0], missing_features] = np.nan" ],
] "cell_type": "code"
}, },
{ {
"cell_type": "code", "metadata": {},
"execution_count": null, "source": [
"metadata": {}, "## Data"
"outputs": [], ],
"source": [ "cell_type": "markdown"
"df = pd.DataFrame(data = X_train)\n", },
"df['Label'] = pd.Series(y_train, index=df.index)\n", {
"df.head()" "metadata": {},
] "outputs": [],
}, "execution_count": null,
{ "source": [
"cell_type": "markdown", "digits = datasets.load_digits()\n",
"metadata": {}, "X_train = digits.data[10:,:]\n",
"source": [ "y_train = digits.target[10:]\n",
"## Train\n", "\n",
"\n", "# Add missing values in 75% of the lines.\n",
"Instantiate an `AutoMLConfig` object to specify the settings and data used to run the experiment. This includes setting `experiment_exit_score`, which should cause the run to complete before the `iterations` count is reached.\n", "missing_rate = 0.75\n",
"\n", "n_missing_samples = int(np.floor(X_train.shape[0] * missing_rate))\n",
"|Property|Description|\n", "missing_samples = np.hstack((np.zeros(X_train.shape[0] - n_missing_samples, dtype=np.bool), np.ones(n_missing_samples, dtype=np.bool)))\n",
"|-|-|\n", "rng = np.random.RandomState(0)\n",
"|**task**|classification or regression|\n", "rng.shuffle(missing_samples)\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", "missing_features = rng.randint(0, X_train.shape[1], n_missing_samples)\n",
"|**iteration_timeout_minutes**|Time limit in minutes for each iteration.|\n", "X_train[np.where(missing_samples)[0], missing_features] = np.nan"
"|**iterations**|Number of iterations. In each iteration AutoML trains a specific pipeline with the data.|\n", ],
"|**preprocess**|Setting this to *True* enables AutoML to perform preprocessing on the input to handle *missing data*, and to perform some common *feature extraction*.|\n", "cell_type": "code"
"|**experiment_exit_score**|*double* value indicating the target for *primary_metric*. <br>Once the target is surpassed the run terminates.|\n", },
"|**blacklist_models**|*List* of *strings* indicating machine learning algorithms for AutoML to avoid in this run.<br><br> Allowed values for **Classification**<br><i>LogisticRegression</i><br><i>SGD</i><br><i>MultinomialNaiveBayes</i><br><i>BernoulliNaiveBayes</i><br><i>SVM</i><br><i>LinearSVM</i><br><i>KNN</i><br><i>DecisionTree</i><br><i>RandomForest</i><br><i>ExtremeRandomTrees</i><br><i>LightGBM</i><br><i>GradientBoosting</i><br><i>TensorFlowDNN</i><br><i>TensorFlowLinearClassifier</i><br><br>Allowed values for **Regression**<br><i>ElasticNet</i><br><i>GradientBoosting</i><br><i>DecisionTree</i><br><i>KNN</i><br><i>LassoLars</i><br><i>SGD</i><br><i>RandomForest</i><br><i>ExtremeRandomTrees</i><br><i>LightGBM</i><br><i>TensorFlowLinearRegressor</i><br><i>TensorFlowDNN</i>|\n", {
"|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n", "metadata": {},
"|**y**|(sparse) array-like, shape = [n_samples, ], Multi-class targets.|" "outputs": [],
] "execution_count": null,
}, "source": [
{ "df = pd.DataFrame(data = X_train)\n",
"cell_type": "code", "df['Label'] = pd.Series(y_train, index=df.index)\n",
"execution_count": null, "df.head()"
"metadata": {}, ],
"outputs": [], "cell_type": "code"
"source": [ },
"automl_config = AutoMLConfig(task = 'classification',\n", {
" debug_log = 'automl_errors.log',\n", "metadata": {},
" primary_metric = 'AUC_weighted',\n", "source": [
" iteration_timeout_minutes = 60,\n", "## Train\n",
" iterations = 20,\n", "\n",
" preprocess = True,\n", "Instantiate an `AutoMLConfig` object to specify the settings and data used to run the experiment. This includes setting `experiment_exit_score`, which should cause the run to complete before the `iterations` count is reached.\n",
" experiment_exit_score = 0.9984,\n", "\n",
" blacklist_models = ['KNN','LinearSVM'],\n", "|Property|Description|\n",
" verbosity = logging.INFO,\n", "|-|-|\n",
" X = X_train, \n", "|**task**|classification or regression|\n",
" y = y_train)" "|**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",
] "|**iteration_timeout_minutes**|Time limit in minutes for each iteration.|\n",
}, "|**iterations**|Number of iterations. In each iteration AutoML trains a specific pipeline with the data.|\n",
{ "|**preprocess**|Setting this to *True* enables AutoML to perform preprocessing on the input to handle *missing data*, and to perform some common *feature extraction*.|\n",
"cell_type": "markdown", "|**experiment_exit_score**|*double* value indicating the target for *primary_metric*. <br>Once the target is surpassed the run terminates.|\n",
"metadata": {}, "|**blacklist_models**|*List* of *strings* indicating machine learning algorithms for AutoML to avoid in this run.<br><br> Allowed values for **Classification**<br><i>LogisticRegression</i><br><i>SGD</i><br><i>MultinomialNaiveBayes</i><br><i>BernoulliNaiveBayes</i><br><i>SVM</i><br><i>LinearSVM</i><br><i>KNN</i><br><i>DecisionTree</i><br><i>RandomForest</i><br><i>ExtremeRandomTrees</i><br><i>LightGBM</i><br><i>GradientBoosting</i><br><i>TensorFlowDNN</i><br><i>TensorFlowLinearClassifier</i><br><br>Allowed values for **Regression**<br><i>ElasticNet</i><br><i>GradientBoosting</i><br><i>DecisionTree</i><br><i>KNN</i><br><i>LassoLars</i><br><i>SGD</i><br><i>RandomForest</i><br><i>ExtremeRandomTrees</i><br><i>LightGBM</i><br><i>TensorFlowLinearRegressor</i><br><i>TensorFlowDNN</i>|\n",
"source": [ "|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n",
"Call the `submit` method on the experiment object and pass the run configuration. Execution of local runs is synchronous. Depending on the data and the number of iterations this can run for a while.\n", "|**y**|(sparse) array-like, shape = [n_samples, ], Multi-class targets.|\n",
"In this example, we specify `show_output = True` to print currently running iterations to the console." "|**path**|Relative path to the project folder. AutoML stores configuration files for the experiment under this folder. You can specify a new empty folder.|"
] ],
}, "cell_type": "markdown"
{ },
"cell_type": "code", {
"execution_count": null, "metadata": {},
"metadata": {}, "outputs": [],
"outputs": [], "execution_count": null,
"source": [ "source": [
"local_run = experiment.submit(automl_config, show_output = True)" "automl_config = AutoMLConfig(task = 'classification',\n",
] " debug_log = 'automl_errors.log',\n",
}, " primary_metric = 'AUC_weighted',\n",
{ " iteration_timeout_minutes = 60,\n",
"cell_type": "code", " iterations = 20,\n",
"execution_count": null, " preprocess = True,\n",
"metadata": {}, " experiment_exit_score = 0.9984,\n",
"outputs": [], " blacklist_models = ['KNN','LinearSVM'],\n",
"source": [ " verbosity = logging.INFO,\n",
"local_run" " X = X_train, \n",
] " y = y_train,\n",
}, " path = project_folder)"
{ ],
"cell_type": "markdown", "cell_type": "code"
"metadata": {}, },
"source": [ {
"## Results" "metadata": {},
] "source": [
}, "Call the `submit` method on the experiment object and pass the run configuration. Execution of local runs is synchronous. Depending on the data and the number of iterations this can run for a while.\n",
{ "In this example, we specify `show_output = True` to print currently running iterations to the console."
"cell_type": "markdown", ],
"metadata": {}, "cell_type": "markdown"
"source": [ },
"#### Widget for Monitoring Runs\n", {
"\n", "metadata": {},
"The widget will first report a \"loading\" status while running the first iteration. After completing the first iteration, an auto-updating graph and table will be shown. The widget will refresh once per minute, so you should see the graph update as child runs complete.\n", "outputs": [],
"\n", "execution_count": null,
"**Note:** The widget displays a link at the bottom. Use this link to open a web interface to explore the individual run details." "source": [
] "local_run = experiment.submit(automl_config, show_output = True)"
}, ],
{ "cell_type": "code"
"cell_type": "code", },
"execution_count": null, {
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "execution_count": null,
"from azureml.widgets import RunDetails\n", "source": [
"RunDetails(local_run).show() " "local_run"
] ],
}, "cell_type": "code"
{ },
"cell_type": "markdown", {
"metadata": {}, "metadata": {},
"source": [ "source": [
"\n", "## Results"
"#### Retrieve All Child Runs\n", ],
"You can also use SDK methods to fetch all the child runs and see individual metrics that we log." "cell_type": "markdown"
] },
}, {
{ "metadata": {},
"cell_type": "code", "source": [
"execution_count": null, "#### Widget for Monitoring Runs\n",
"metadata": {}, "\n",
"outputs": [], "The widget will first report a \"loading\" status while running the first iteration. After completing the first iteration, an auto-updating graph and table will be shown. The widget will refresh once per minute, so you should see the graph update as child runs complete.\n",
"source": [ "\n",
"children = list(local_run.get_children())\n", "**Note:** The widget displays a link at the bottom. Use this link to open a web interface to explore the individual run details."
"metricslist = {}\n", ],
"for run in children:\n", "cell_type": "markdown"
" 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", "metadata": {},
"\n", "outputs": [],
"rundata = pd.DataFrame(metricslist).sort_index(1)\n", "execution_count": null,
"rundata" "source": [
] "from azureml.widgets import RunDetails\n",
}, "RunDetails(local_run).show() "
{ ],
"cell_type": "markdown", "cell_type": "code"
"metadata": {}, },
"source": [ {
"### Retrieve the Best Model\n", "metadata": {},
"\n", "source": [
"Below we select the best pipeline from our iterations. The `get_output` method returns the best run and the fitted model. The Model includes the pipeline and any pre-processing. Overloads on `get_output` allow you to retrieve the best run and fitted model for *any* logged metric or for a particular *iteration*." "\n",
] "#### Retrieve All Child Runs\n",
}, "You can also use SDK methods to fetch all the child runs and see individual metrics that we log."
{ ],
"cell_type": "code", "cell_type": "markdown"
"execution_count": null, },
"metadata": {}, {
"outputs": [], "metadata": {},
"source": [ "outputs": [],
"best_run, fitted_model = local_run.get_output()" "execution_count": null,
] "source": [
}, "children = list(local_run.get_children())\n",
{ "metricslist = {}\n",
"cell_type": "markdown", "for run in children:\n",
"metadata": {}, " properties = run.get_properties()\n",
"source": [ " metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)}\n",
"#### Best Model Based on Any Other Metric\n", " metricslist[int(properties['iteration'])] = metrics\n",
"Show the run and the model which has the smallest `accuracy` value:" "\n",
] "rundata = pd.DataFrame(metricslist).sort_index(1)\n",
}, "rundata"
{ ],
"cell_type": "code", "cell_type": "code"
"execution_count": null, },
"metadata": {}, {
"outputs": [], "metadata": {},
"source": [ "source": [
"# lookup_metric = \"accuracy\"\n", "### Retrieve the Best Model\n",
"# best_run, fitted_model = local_run.get_output(metric = lookup_metric)" "\n",
] "Below we select the best pipeline from our iterations. The `get_output` method returns the best run and the fitted model. The Model includes the pipeline and any pre-processing. Overloads on `get_output` allow you to retrieve the best run and fitted model for *any* logged metric or for a particular *iteration*."
}, ],
{ "cell_type": "markdown"
"cell_type": "markdown", },
"metadata": {}, {
"source": [ "metadata": {},
"#### Model from a Specific Iteration\n", "outputs": [],
"Show the run and the model from the third iteration:" "execution_count": null,
] "source": [
}, "best_run, fitted_model = local_run.get_output()"
{ ],
"cell_type": "code", "cell_type": "code"
"execution_count": null, },
"metadata": {}, {
"outputs": [], "metadata": {},
"source": [ "source": [
"# iteration = 3\n", "#### Best Model Based on Any Other Metric\n",
"# best_run, fitted_model = local_run.get_output(iteration = iteration)" "Show the run and the model which has the smallest `accuracy` value:"
] ],
}, "cell_type": "markdown"
{ },
"cell_type": "markdown", {
"metadata": {}, "metadata": {},
"source": [ "outputs": [],
"#### View the engineered names for featurized data\n", "execution_count": null,
"Below we display the engineered feature names generated for the featurized data using the preprocessing featurization." "source": [
] "# lookup_metric = \"accuracy\"\n",
}, "# best_run, fitted_model = local_run.get_output(metric = lookup_metric)"
{ ],
"cell_type": "code", "cell_type": "code"
"execution_count": null, },
"metadata": {}, {
"outputs": [], "metadata": {},
"source": [ "source": [
"fitted_model.named_steps['datatransformer'].get_engineered_feature_names()" "#### Model from a Specific Iteration\n",
] "Show the run and the model from the third iteration:"
}, ],
{ "cell_type": "markdown"
"cell_type": "markdown", },
"metadata": {}, {
"source": [ "metadata": {},
"#### View the featurization summary\n", "outputs": [],
"Below we display the featurization that was performed on different raw features in the user data. For each raw feature in the user data, the following information is displayed:-\n", "execution_count": null,
"- Raw feature name\n", "source": [
"- Number of engineered features formed out of this raw feature\n", "# iteration = 3\n",
"- Type detected\n", "# best_run, fitted_model = local_run.get_output(iteration = iteration)"
"- If feature was dropped\n", ],
"- List of feature transformations for the raw feature" "cell_type": "code"
] },
}, {
{ "metadata": {},
"cell_type": "code", "source": [
"execution_count": null, "#### View the engineered names for featurized data\n",
"metadata": {}, "Below we display the engineered feature names generated for the featurized data using the preprocessing featurization."
"outputs": [], ],
"source": [ "cell_type": "markdown"
"# Get the featurization summary as a list of JSON\n", },
"featurization_summary = fitted_model.named_steps['datatransformer'].get_featurization_summary()\n", {
"# View the featurization summary as a pandas dataframe\n", "metadata": {},
"pd.DataFrame.from_records(featurization_summary)" "outputs": [],
] "execution_count": null,
}, "source": [
{ "fitted_model.named_steps['datatransformer'].get_engineered_feature_names()"
"cell_type": "markdown", ],
"metadata": {}, "cell_type": "code"
"source": [ },
"## Test" {
] "metadata": {},
}, "source": [
{ "#### View the featurization summary\n",
"cell_type": "code", "Below we display the featurization that was performed on different raw features in the user data. For each raw feature in the user data, the following information is displayed:-\n",
"execution_count": null, "- Raw feature name\n",
"metadata": {}, "- Number of engineered features formed out of this raw feature\n",
"outputs": [], "- Type detected\n",
"source": [ "- If feature was dropped\n",
"digits = datasets.load_digits()\n", "- List of feature transformations for the raw feature"
"X_test = digits.data[:10, :]\n", ],
"y_test = digits.target[:10]\n", "cell_type": "markdown"
"images = digits.images[:10]\n", },
"\n", {
"# Randomly select digits and test.\n", "metadata": {},
"for index in np.random.choice(len(y_test), 2, replace = False):\n", "outputs": [],
" print(index)\n", "execution_count": null,
" predicted = fitted_model.predict(X_test[index:index + 1])[0]\n", "source": [
" label = y_test[index]\n", "fitted_model.named_steps['datatransformer'].get_featurization_summary()"
" title = \"Label value = %d Predicted value = %d \" % (label, predicted)\n", ],
" fig = plt.figure(1, figsize=(3,3))\n", "cell_type": "code"
" ax1 = fig.add_axes((0,0,.8,.8))\n", },
" ax1.set_title(title)\n", {
" plt.imshow(images[index], cmap = plt.cm.gray_r, interpolation = 'nearest')\n", "metadata": {},
" plt.show()\n" "source": [
] "## Test"
} ],
], "cell_type": "markdown"
"metadata": { },
"authors": [ {
{ "metadata": {},
"name": "savitam" "outputs": [],
} "execution_count": null,
], "source": [
"kernelspec": { "digits = datasets.load_digits()\n",
"display_name": "Python 3.6", "X_test = digits.data[:10, :]\n",
"language": "python", "y_test = digits.target[:10]\n",
"name": "python36" "images = digits.images[:10]\n",
}, "\n",
"language_info": { "# Randomly select digits and test.\n",
"codemirror_mode": { "for index in np.random.choice(len(y_test), 2, replace = False):\n",
"name": "ipython", " print(index)\n",
"version": 3 " predicted = fitted_model.predict(X_test[index:index + 1])[0]\n",
}, " label = y_test[index]\n",
"file_extension": ".py", " title = \"Label value = %d Predicted value = %d \" % (label, predicted)\n",
"mimetype": "text/x-python", " fig = plt.figure(1, figsize=(3,3))\n",
"name": "python", " ax1 = fig.add_axes((0,0,.8,.8))\n",
"nbconvert_exporter": "python", " ax1.set_title(title)\n",
"pygments_lexer": "ipython3", " plt.imshow(images[index], cmap = plt.cm.gray_r, interpolation = 'nearest')\n",
"version": "3.6.6" " plt.show()\n"
} ],
}, "cell_type": "code"
"nbformat": 4, }
"nbformat_minor": 2 ],
"nbformat_minor": 2
} }

View File

@@ -1,8 +1,8 @@
name: auto-ml-missing-data-blacklist-early-termination name: auto-ml-missing-data-blacklist-early-termination
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- azureml-train-automl - azureml-train-automl
- azureml-widgets - azureml-widgets
- matplotlib - matplotlib
- pandas_ml - pandas_ml

View File

@@ -1,593 +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": [
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/classification-bank-marketing/auto-ml-classification-bank-marketing.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Automated Machine Learning\n",
"_**Regression on remote compute using Computer Hardware dataset with model explanations**_\n",
"\n",
"## Contents\n",
"1. [Introduction](#Introduction)\n",
"1. [Setup](#Setup)\n",
"1. [Train](#Train)\n",
"1. [Results](#Results)\n",
"1. [Explanations](#Explanations)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Introduction\n",
"\n",
"In this example we use the Hardware Performance Dataset to showcase how you can use AutoML for a simple regression problem. After training AutoML models for this regression data set, we show how you can compute model explanations on your remote compute using a sample explainer script.\n",
"\n",
"If you are using an Azure Machine Learning Notebook VM, you are all set. Otherwise, go through the [configuration](../../../configuration.ipynb) notebook first if you haven't already to establish your connection to the AzureML Workspace. \n",
"\n",
"In this notebook you will learn how to:\n",
"1. Create an `Experiment` in an existing `Workspace`.\n",
"2. Configure AutoML using `AutoMLConfig`.\n",
"3. Train the model using remote compute.\n",
"4. Explore the results.\n",
"5. Setup remote compute for computing the model explanations for a given AutoML model.\n",
"6. Start an AzureML experiment on your remote compute to compute explanations for an AutoML model.\n",
"7. Download the feature importance for engineered features and visualize the explanations for engineered features. \n",
"8. Download the feature importance for raw features and visualize the explanations for raw features. \n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Setup\n",
"\n",
"As part of the setup you have already created an Azure ML `Workspace` object. For AutoML 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",
"from matplotlib import pyplot as plt\n",
"import pandas as pd\n",
"import os\n",
"\n",
"import azureml.core\n",
"from azureml.core.experiment import Experiment\n",
"from azureml.core.workspace import Workspace\n",
"from azureml.core.dataset import Dataset\n",
"from azureml.train.automl import AutoMLConfig"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"ws = Workspace.from_config()\n",
"\n",
"# choose a name for experiment\n",
"experiment_name = 'automl-regression-computer-hardware'\n",
"\n",
"experiment=Experiment(ws, experiment_name)\n",
"\n",
"output = {}\n",
"output['SDK version'] = azureml.core.VERSION\n",
"output['Subscription ID'] = ws.subscription_id\n",
"output['Workspace'] = ws.name\n",
"output['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": [
"### 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",
"#### 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",
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read this article on the default limits and how to request more quota."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.core.compute import AmlCompute\n",
"from azureml.core.compute import ComputeTarget\n",
"\n",
"# Choose a name for your cluster.\n",
"amlcompute_cluster_name = \"automlcl\"\n",
"\n",
"found = False\n",
"# Check if this compute target already exists in the workspace.\n",
"cts = ws.compute_targets\n",
"if amlcompute_cluster_name in cts and cts[amlcompute_cluster_name].type == 'AmlCompute':\n",
" found = True\n",
" print('Found existing compute target.')\n",
" compute_target = cts[amlcompute_cluster_name]\n",
" \n",
"if not found:\n",
" print('Creating a new compute target...')\n",
" provisioning_config = AmlCompute.provisioning_configuration(vm_size = \"STANDARD_D2_V2\", # for GPU, use \"STANDARD_NC6\"\n",
" #vm_priority = 'lowpriority', # optional\n",
" max_nodes = 6)\n",
"\n",
" # Create the cluster.\n",
" compute_target = ComputeTarget.create(ws, amlcompute_cluster_name, provisioning_config)\n",
" \n",
"print('Checking cluster status...')\n",
"# Can poll for a minimum number of nodes and for a specific timeout.\n",
"# If no min_node_count is provided, it will use the scale settings for the cluster.\n",
"compute_target.wait_for_completion(show_output = True, min_node_count = None, timeout_in_minutes = 20)\n",
" \n",
"# For a more detailed view of current AmlCompute status, use get_status()."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Conda Dependecies for AutoML training experiment\n",
"\n",
"Create the conda dependencies for running AutoML experiment on remote compute."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.core.runconfig import RunConfiguration\n",
"from azureml.core.conda_dependencies import CondaDependencies\n",
"import pkg_resources\n",
"\n",
"# create a new RunConfig object\n",
"conda_run_config = RunConfiguration(framework=\"python\")\n",
"\n",
"# Set compute target to AmlCompute\n",
"conda_run_config.target = compute_target\n",
"conda_run_config.environment.docker.enabled = True\n",
"\n",
"cd = CondaDependencies.create(conda_packages=['numpy','py-xgboost<=0.80'])\n",
"conda_run_config.environment.python.conda_dependencies = cd"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Setup Training and Test Data for AutoML experiment\n",
"\n",
"Here we create the train and test datasets for hardware performance dataset. We also register the datasets in your workspace using a name so that these datasets may be accessed from the remote compute."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Data source\n",
"data = \"https://automlsamplenotebookdata.blob.core.windows.net/automl-sample-notebook-data/machineData.csv\"\n",
"\n",
"# Create dataset from the url\n",
"dataset = Dataset.Tabular.from_delimited_files(data)\n",
"\n",
"# Split the dataset into train and test datasets\n",
"train_dataset, test_dataset = dataset.random_split(percentage=0.8, seed=223)\n",
"\n",
"# Register the train dataset with your workspace\n",
"train_dataset.register(workspace = ws, name = 'hardware_performance_train_dataset',\n",
" description = 'hardware performance training data',\n",
" create_new_version=True)\n",
"\n",
"# Register the test dataset with your workspace\n",
"test_dataset.register(workspace = ws, name = 'hardware_performance_test_dataset',\n",
" description = 'hardware performance test data',\n",
" create_new_version=True)\n",
"\n",
"# Drop the labeled column from the train dataset\n",
"X_train = train_dataset.drop_columns(columns=['ERP'])\n",
"y_train = train_dataset.keep_columns(columns=['ERP'], validate=True)\n",
"\n",
"# Drop the labeled column from the test dataset\n",
"X_test = test_dataset.drop_columns(columns=['ERP']) \n",
"\n",
"# Display the top rows in the train dataset\n",
"X_train.take(5).to_pandas_dataframe()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Train\n",
"\n",
"Instantiate an `AutoMLConfig` object to specify the settings and data used to run the experiment.\n",
"\n",
"|Property|Description|\n",
"|-|-|\n",
"|**task**|classification or regression|\n",
"|**primary_metric**|This is the metric that you want to optimize. Regression supports the following primary metrics: <br><i>spearman_correlation</i><br><i>normalized_root_mean_squared_error</i><br><i>r2_score</i><br><i>normalized_mean_absolute_error</i>|\n",
"|**iteration_timeout_minutes**|Time limit in minutes for each iteration.|\n",
"|**iterations**|Number of iterations. In each iteration AutoML trains a specific pipeline with the data.|\n",
"|**n_cross_validations**|Number of cross validation splits.|\n",
"|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n",
"|**y**|(sparse) array-like, shape = [n_samples, ], targets values.|\n",
"\n",
"**_You can find more information about primary metrics_** [here](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-configure-auto-train#primary-metric)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"automl_settings = {\n",
" \"iteration_timeout_minutes\": 5,\n",
" \"iterations\": 10,\n",
" \"n_cross_validations\": 2,\n",
" \"primary_metric\": 'spearman_correlation',\n",
" \"preprocess\": True,\n",
" \"max_concurrent_iterations\": 1,\n",
" \"verbosity\": logging.INFO,\n",
"}\n",
"\n",
"automl_config = AutoMLConfig(task = 'regression',\n",
" debug_log = 'automl_errors_model_exp.log',\n",
" run_configuration=conda_run_config,\n",
" X = X_train,\n",
" y = y_train,\n",
" **automl_settings\n",
" )"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Call the `submit` method on the experiment object and pass the run configuration. Execution of local runs is synchronous. Depending on the data and the number of iterations this can run for a while.\n",
"In this example, we specify `show_output = True` to print currently running iterations to the console."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"remote_run = experiment.submit(automl_config, show_output = True)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"remote_run"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Results"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Widget for Monitoring Runs\n",
"\n",
"The widget will first report a \"loading\" status while running the first iteration. After completing the first iteration, an auto-updating graph and table will be shown. The widget will refresh once per minute, so you should see the graph update as child runs complete.\n",
"\n",
"**Note:** The widget displays a link at the bottom. Use this link to open a web interface to explore the individual run details"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.widgets import RunDetails\n",
"RunDetails(remote_run).show() "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Explanations\n",
"This section will walk you through the workflow to compute model explanations for an AutoML model on your remote compute.\n",
"\n",
"### Retrieve any AutoML Model for explanations\n",
"\n",
"Below we select the some AutoML pipeline from our iterations. The `get_output` method returns the a AutoML run and the fitted model for the last invocation. Overloads on `get_output` allow you to retrieve the best run and fitted model for *any* logged metric or for a particular *iteration*."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"automl_run, fitted_model = remote_run.get_output(iteration=5)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Setup model explanation run on the remote compute\n",
"The following section provides details on how to setup an AzureML experiment to run model explanations for an AutoML model on your remote compute."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Sample script used for computing explanations\n",
"View the sample script for computing the model explanations for your AutoML model on remote compute."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"with open('train_explainer.py', 'r') as cefr:\n",
" print(cefr.read())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Substitute values in your sample script\n",
"The following cell shows how you change the values in the sample script so that you can change the sample script according to your experiment and dataset."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import shutil\n",
"\n",
"# create script folder\n",
"script_folder = './sample_projects/automl-regression-computer-hardware'\n",
"if not os.path.exists(script_folder):\n",
" os.makedirs(script_folder)\n",
"\n",
"# Copy the sample script to script folder.\n",
"shutil.copy('train_explainer.py', script_folder)\n",
"\n",
"# Create the explainer script that will run on the remote compute.\n",
"script_file_name = script_folder + '/train_explainer.py'\n",
"\n",
"# Open the sample script for modification\n",
"with open(script_file_name, 'r') as cefr:\n",
" content = cefr.read()\n",
"\n",
"# Replace the values in train_explainer.py file with the appropriate values\n",
"content = content.replace('<<experimnet_name>>', automl_run.experiment.name) # your experiment name.\n",
"content = content.replace('<<run_id>>', automl_run.id) # Run-id of the AutoML run for which you want to explain the model.\n",
"content = content.replace('<<target_column_name>>', 'ERP') # Your target column name\n",
"content = content.replace('<<task>>', 'regression') # Training task type\n",
"# Name of your training dataset register with your workspace\n",
"content = content.replace('<<train_dataset_name>>', 'hardware_performance_train_dataset') \n",
"# Name of your test dataset register with your workspace\n",
"content = content.replace('<<test_dataset_name>>', 'hardware_performance_test_dataset')\n",
"\n",
"# Write sample file into your script folder.\n",
"with open(script_file_name, 'w') as cefw:\n",
" cefw.write(content)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Create conda configuration for model explanations experiment\n",
"We need `azureml-explain-model`, `azureml-train-automl` and `azureml-core` packages for computing model explanations for your AutoML model on remote compute."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.core.runconfig import RunConfiguration\n",
"from azureml.core.conda_dependencies import CondaDependencies\n",
"import pkg_resources\n",
"\n",
"# create a new RunConfig object\n",
"conda_run_config = RunConfiguration(framework=\"python\")\n",
"\n",
"# Set compute target to AmlCompute\n",
"conda_run_config.target = compute_target\n",
"conda_run_config.environment.docker.enabled = True\n",
"azureml_pip_packages = [\n",
" 'azureml-train-automl', 'azureml-core', 'azureml-explain-model'\n",
"]\n",
"\n",
"# specify CondaDependencies obj\n",
"conda_run_config.environment.python.conda_dependencies = CondaDependencies.create(\n",
" conda_packages=['scikit-learn', 'numpy','py-xgboost<=0.80'],\n",
" pip_packages=azureml_pip_packages)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Submit the experiment for model explanations\n",
"Submit the experiment with the above `run_config` and the sample script for computing explanations."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Now submit a run on AmlCompute for model explanations\n",
"from azureml.core.script_run_config import ScriptRunConfig\n",
"\n",
"script_run_config = ScriptRunConfig(source_directory=script_folder,\n",
" script='train_explainer.py',\n",
" run_config=conda_run_config)\n",
"\n",
"run = experiment.submit(script_run_config)\n",
"\n",
"# Show run details\n",
"run"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%%time\n",
"# Shows output of the run on stdout.\n",
"run.wait_for_completion(show_output=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Feature importance and explanation dashboard\n",
"In this section we describe how you can download the explanation results from the explanations experiment and visualize the feature importance for your AutoML model. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Setup for visualizing the model explanation results\n",
"For visualizing the explanation results for the *fitted_model* we need to perform the following steps:-\n",
"1. Featurize test data samples.\n",
"\n",
"The *automl_explainer_setup_obj* contains all the structures from above list. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.train.automl.automl_explain_utilities import AutoMLExplainerSetupClass, automl_setup_model_explanations\n",
"explainer_setup_class = automl_setup_model_explanations(fitted_model, 'regression', X_test=X_test)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Download engineered feature importance from artifact store\n",
"You can use *ExplanationClient* to download the engineered feature explanations from the artifact store of the *automl_run*. You can also use ExplanationDashboard to view the dash board visualization of the feature importance values of the engineered features."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.explain.model._internal.explanation_client import ExplanationClient\n",
"from azureml.contrib.interpret.visualize import ExplanationDashboard\n",
"client = ExplanationClient.from_run(automl_run)\n",
"engineered_explanations = client.download_model_explanation(raw=False)\n",
"print(engineered_explanations.get_feature_importance_dict())\n",
"ExplanationDashboard(engineered_explanations, explainer_setup_class.automl_estimator, explainer_setup_class.X_test_transform)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Download raw feature importance from artifact store\n",
"You can use *ExplanationClient* to download the raw feature explanations from the artifact store of the *automl_run*. You can also use ExplanationDashboard to view the dash board visualization of the feature importance values of the raw features."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"raw_explanations = client.download_model_explanation(raw=True)\n",
"print(raw_explanations.get_feature_importance_dict())\n",
"ExplanationDashboard(raw_explanations, explainer_setup_class.automl_pipeline, explainer_setup_class.X_test_raw)"
]
}
],
"metadata": {
"authors": [
{
"name": "v-rasav"
}
],
"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"
}
},
"nbformat": 4,
"nbformat_minor": 2
}

View File

@@ -1,11 +0,0 @@
name: auto-ml-model-explanations-remote-compute
dependencies:
- pip:
- azureml-sdk
- interpret
- azureml-train-automl
- azureml-widgets
- matplotlib
- pandas_ml
- azureml-explain-model
- azureml-contrib-interpret

View File

@@ -1,64 +0,0 @@
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license.
import os
from azureml.core.run import Run
from azureml.core.experiment import Experiment
from sklearn.externals import joblib
from azureml.core.dataset import Dataset
from azureml.train.automl.automl_explain_utilities import AutoMLExplainerSetupClass, automl_setup_model_explanations
from azureml.explain.model.mimic.models.lightgbm_model import LGBMExplainableModel
from azureml.explain.model.mimic_wrapper import MimicWrapper
from automl.client.core.common.constants import MODEL_PATH
OUTPUT_DIR = './outputs/'
os.makedirs(OUTPUT_DIR, exist_ok=True)
# Get workspace from the run context
run = Run.get_context()
ws = run.experiment.workspace
# Get the AutoML run object from the experiment name and the workspace
experiment = Experiment(ws, '<<experimnet_name>>')
automl_run = Run(experiment=experiment, run_id='<<run_id>>')
# Download the best model from the artifact store
automl_run.download_file(name=MODEL_PATH, output_file_path='model.pkl')
# Load the AutoML model into memory
fitted_model = joblib.load('model.pkl')
# Get the train dataset from the workspace
train_dataset = Dataset.get_by_name(workspace=ws, name='<<train_dataset_name>>')
# Drop the lablled column to get the training set.
X_train = train_dataset.drop_columns(columns=['<<target_column_name>>'])
y_train = train_dataset.keep_columns(columns=['<<target_column_name>>'], validate=True)
# Get the train dataset from the workspace
test_dataset = Dataset.get_by_name(workspace=ws, name='<<test_dataset_name>>')
# Drop the lablled column to get the testing set.
X_test = test_dataset.drop_columns(columns=['<<target_column_name>>'])
# Setup the class for explaining the AtuoML models
automl_explainer_setup_obj = automl_setup_model_explanations(fitted_model, '<<task>>',
X=X_train, X_test=X_test,
y=y_train)
# Initialize the Mimic Explainer
explainer = MimicWrapper(ws, automl_explainer_setup_obj.automl_estimator, LGBMExplainableModel,
init_dataset=automl_explainer_setup_obj.X_transform, run=automl_run,
features=automl_explainer_setup_obj.engineered_feature_names,
feature_maps=[automl_explainer_setup_obj.feature_map],
classes=automl_explainer_setup_obj.classes)
# Compute the engineered explanations
engineered_explanations = explainer.explain(['local', 'global'],
eval_dataset=automl_explainer_setup_obj.X_test_transform)
# Compute the raw explanations
raw_explanations = explainer.explain(['local', 'global'], get_raw=True,
raw_feature_names=automl_explainer_setup_obj.raw_feature_names,
eval_dataset=automl_explainer_setup_obj.X_test_transform)
print("Engineered and raw explanations computed successfully")

View File

@@ -1,632 +1,357 @@
{ {
"cells": [ "metadata": {
{ "kernelspec": {
"cell_type": "markdown", "display_name": "Python 3.6",
"metadata": {}, "name": "python36",
"source": [ "language": "python"
"Copyright (c) Microsoft Corporation. All rights reserved.\n", },
"\n", "authors": [
"Licensed under the MIT License." {
] "name": "xif"
}, }
{ ],
"cell_type": "markdown", "language_info": {
"metadata": {}, "mimetype": "text/x-python",
"source": [ "codemirror_mode": {
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/model-explanation/auto-ml-model-explanation.png)" "name": "ipython",
] "version": 3
}, },
{ "pygments_lexer": "ipython3",
"cell_type": "markdown", "name": "python",
"metadata": {}, "file_extension": ".py",
"source": [ "nbconvert_exporter": "python",
"# Automated Machine Learning\n", "version": "3.6.6"
"_**Explain classification model, visualize the explanation and operationalize the explainer along with AutoML model**_\n", }
"\n", },
"## Contents\n", "nbformat": 4,
"1. [Introduction](#Introduction)\n", "cells": [
"1. [Setup](#Setup)\n", {
"1. [Data](#Data)\n", "metadata": {},
"1. [Train](#Train)\n", "source": [
"1. [Results](#Results)\n", "Copyright (c) Microsoft Corporation. All rights reserved.\n",
"1. [Explanations](#Explanations)\n", "\n",
"1. [Operationailze](#Operationailze)" "Licensed under the MIT License."
] ],
}, "cell_type": "markdown"
{ },
"cell_type": "markdown", {
"metadata": {}, "metadata": {},
"source": [ "source": [
"## Introduction\n", "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/model-explanation/auto-ml-model-explanation.png)"
"In this example we use the sklearn's [iris dataset](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_iris.html) to showcase how you can use the AutoML Classifier for a simple classification problem.\n", ],
"\n", "cell_type": "markdown"
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n", },
"\n", {
"In this notebook you would see\n", "metadata": {},
"1. Creating an Experiment in an existing Workspace\n", "source": [
"2. Instantiating AutoMLConfig\n", "# Automated Machine Learning\n",
"3. Training the Model using local compute and explain the model\n", "_**Explain classification model and visualize the explanation**_\n",
"4. Visualization model's feature importance in widget\n", "\n",
"5. Explore any model's explanation\n", "## Contents\n",
"6. Operationalize the AutoML model and the explaination model" "1. [Introduction](#Introduction)\n",
] "1. [Setup](#Setup)\n",
}, "1. [Data](#Data)\n",
{ "1. [Train](#Train)\n",
"cell_type": "markdown", "1. [Results](#Results)"
"metadata": {}, ],
"source": [ "cell_type": "markdown"
"## Setup\n", },
"\n", {
"As part of the setup you have already created a <b>Workspace</b>. For AutoML you would need to create an <b>Experiment</b>. An <b>Experiment</b> is a named object in a <b>Workspace</b>, which is used to run experiments." "metadata": {},
] "source": [
}, "## Introduction\n",
{ "In this example we use the sklearn's [iris dataset](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_iris.html) to showcase how you can use the AutoML Classifier for a simple classification problem.\n",
"cell_type": "code", "\n",
"execution_count": null, "Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
"metadata": {}, "\n",
"outputs": [], "In this notebook you would see\n",
"source": [ "1. Creating an Experiment in an existing Workspace\n",
"import logging\n", "2. Instantiating AutoMLConfig\n",
"\n", "3. Training the Model using local compute and explain the model\n",
"import pandas as pd\n", "4. Visualization model's feature importance in widget\n",
"import azureml.core\n", "5. Explore best model's explanation"
"from azureml.core.experiment import Experiment\n", ],
"from azureml.core.workspace import Workspace\n", "cell_type": "markdown"
"from azureml.train.automl import AutoMLConfig\n", },
"from azureml.core.dataset import Dataset\n", {
"from azureml.explain.model._internal.explanation_client import ExplanationClient" "metadata": {},
] "source": [
}, "## Setup\n",
{ "\n",
"cell_type": "code", "As part of the setup you have already created a <b>Workspace</b>. For AutoML you would need to create an <b>Experiment</b>. An <b>Experiment</b> is a named object in a <b>Workspace</b>, which is used to run experiments."
"execution_count": null, ],
"metadata": {}, "cell_type": "markdown"
"outputs": [], },
"source": [ {
"ws = Workspace.from_config()\n", "metadata": {},
"\n", "outputs": [],
"# choose a name for experiment\n", "execution_count": null,
"experiment_name = 'automl-model-explanation'\n", "source": [
"\n", "import logging\n",
"experiment=Experiment(ws, experiment_name)\n", "\n",
"\n", "import pandas as pd\n",
"output = {}\n", "import azureml.core\n",
"output['SDK version'] = azureml.core.VERSION\n", "from azureml.core.experiment import Experiment\n",
"output['Subscription ID'] = ws.subscription_id\n", "from azureml.core.workspace import Workspace\n",
"output['Workspace Name'] = ws.name\n", "from azureml.train.automl import AutoMLConfig"
"output['Resource Group'] = ws.resource_group\n", ],
"output['Location'] = ws.location\n", "cell_type": "code"
"output['Experiment Name'] = experiment.name\n", },
"pd.set_option('display.max_colwidth', -1)\n", {
"outputDf = pd.DataFrame(data = output, index = [''])\n", "metadata": {},
"outputDf.T" "outputs": [],
] "execution_count": null,
}, "source": [
{ "ws = Workspace.from_config()\n",
"cell_type": "markdown", "\n",
"metadata": {}, "# choose a name for experiment\n",
"source": [ "experiment_name = 'automl-model-explanation'\n",
"## Data" "# project folder\n",
] "project_folder = './sample_projects/automl-model-explanation'\n",
}, "\n",
{ "experiment=Experiment(ws, experiment_name)\n",
"cell_type": "markdown", "\n",
"metadata": {}, "output = {}\n",
"source": [ "output['SDK version'] = azureml.core.VERSION\n",
"### Training Data" "output['Subscription ID'] = ws.subscription_id\n",
] "output['Workspace Name'] = ws.name\n",
}, "output['Resource Group'] = ws.resource_group\n",
{ "output['Location'] = ws.location\n",
"cell_type": "code", "output['Project Directory'] = project_folder\n",
"execution_count": null, "output['Experiment Name'] = experiment.name\n",
"metadata": {}, "pd.set_option('display.max_colwidth', -1)\n",
"outputs": [], "outputDf = pd.DataFrame(data = output, index = [''])\n",
"source": [ "outputDf.T"
"train_data = \"https://automlsamplenotebookdata.blob.core.windows.net/automl-sample-notebook-data/bankmarketing_train.csv\"\n", ],
"train_dataset = Dataset.Tabular.from_delimited_files(train_data)\n", "cell_type": "code"
"X_train = train_dataset.drop_columns(columns=['y']).to_pandas_dataframe()\n", },
"y_train = train_dataset.keep_columns(columns=['y'], validate=True).to_pandas_dataframe()" {
] "metadata": {},
}, "source": [
{ "## Data"
"cell_type": "markdown", ],
"metadata": {}, "cell_type": "markdown"
"source": [ },
"### Test Data" {
] "metadata": {},
}, "outputs": [],
{ "execution_count": null,
"cell_type": "code", "source": [
"execution_count": null, "from sklearn import datasets\n",
"metadata": {}, "\n",
"outputs": [], "iris = datasets.load_iris()\n",
"source": [ "y = iris.target\n",
"test_data = \"https://automlsamplenotebookdata.blob.core.windows.net/automl-sample-notebook-data/bankmarketing_test.csv\"\n", "X = iris.data\n",
"test_dataset = Dataset.Tabular.from_delimited_files(test_data)\n", "\n",
"X_test = test_dataset.drop_columns(columns=['y']).to_pandas_dataframe()\n", "features = iris.feature_names\n",
"y_test = test_dataset.keep_columns(columns=['y'], validate=True).to_pandas_dataframe()" "\n",
] "from sklearn.model_selection import train_test_split\n",
}, "X_train, X_test, y_train, y_test = train_test_split(X,\n",
{ " y,\n",
"cell_type": "markdown", " test_size=0.1,\n",
"metadata": {}, " random_state=100,\n",
"source": [ " stratify=y)\n",
"## Train\n", "\n",
"\n", "X_train = pd.DataFrame(X_train, columns=features)\n",
"Instantiate a AutoMLConfig object. This defines the settings and data used to run the experiment.\n", "X_test = pd.DataFrame(X_test, columns=features)"
"\n", ],
"|Property|Description|\n", "cell_type": "code"
"|-|-|\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", "metadata": {},
"|**max_time_sec**|Time limit in minutes for each iterations|\n", "source": [
"|**iterations**|Number of iterations. In each iteration Auto ML trains the data with a specific pipeline|\n", "## Train\n",
"|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n", "\n",
"|**y**|(sparse) array-like, shape = [n_samples, ], Multi-class targets.|\n", "Instantiate a AutoMLConfig object. This defines the settings and data used to run the experiment.\n",
"|**model_explainability**|Indicate to explain each trained pipeline or not |" "\n",
] "|Property|Description|\n",
}, "|-|-|\n",
{ "|**task**|classification or regression|\n",
"cell_type": "code", "|**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",
"execution_count": null, "|**max_time_sec**|Time limit in minutes for each iterations|\n",
"metadata": {}, "|**iterations**|Number of iterations. In each iteration Auto ML trains the data with a specific pipeline|\n",
"outputs": [], "|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n",
"source": [ "|**y**|(sparse) array-like, shape = [n_samples, ], Multi-class targets.|\n",
"automl_config = AutoMLConfig(task = 'classification',\n", "|**X_valid**|(sparse) array-like, shape = [n_samples, n_features]|\n",
" debug_log = 'automl_errors.log',\n", "|**y_valid**|(sparse) array-like, shape = [n_samples, ], Multi-class targets.|\n",
" primary_metric = 'AUC_weighted',\n", "|**model_explainability**|Indicate to explain each trained pipeline or not |\n",
" iteration_timeout_minutes = 200,\n", "|**path**|Relative path to the project folder. AutoML stores configuration files for the experiment under this folder. You can specify a new empty folder. |"
" iterations = 10,\n", ],
" verbosity = logging.INFO,\n", "cell_type": "markdown"
" preprocess = True,\n", },
" X = X_train, \n", {
" y = y_train,\n", "metadata": {},
" n_cross_validations = 5,\n", "outputs": [],
" model_explainability=True)" "execution_count": null,
] "source": [
}, "automl_config = AutoMLConfig(task = 'classification',\n",
{ " debug_log = 'automl_errors.log',\n",
"cell_type": "markdown", " primary_metric = 'AUC_weighted',\n",
"metadata": {}, " iteration_timeout_minutes = 200,\n",
"source": [ " iterations = 10,\n",
"You can call the submit method on the experiment object and pass the run configuration. For Local runs the execution is synchronous. Depending on the data and number of iterations this can run for while.\n", " verbosity = logging.INFO,\n",
"You will see the currently running iterations printing to the console." " X = X_train, \n",
] " y = y_train,\n",
}, " X_valid = X_test,\n",
{ " y_valid = y_test,\n",
"cell_type": "code", " model_explainability=True,\n",
"execution_count": null, " path=project_folder)"
"metadata": {}, ],
"outputs": [], "cell_type": "code"
"source": [ },
"local_run = experiment.submit(automl_config, show_output=True)" {
] "metadata": {},
}, "source": [
{ "You can call the submit method on the experiment object and pass the run configuration. For Local runs the execution is synchronous. Depending on the data and number of iterations this can run for while.\n",
"cell_type": "code", "You will see the currently running iterations printing to the console."
"execution_count": null, ],
"metadata": {}, "cell_type": "markdown"
"outputs": [], },
"source": [ {
"local_run" "metadata": {},
] "outputs": [],
}, "execution_count": null,
{ "source": [
"cell_type": "markdown", "local_run = experiment.submit(automl_config, show_output=True)"
"metadata": {}, ],
"source": [ "cell_type": "code"
"## Results" },
] {
}, "metadata": {},
{ "outputs": [],
"cell_type": "markdown", "execution_count": null,
"metadata": {}, "source": [
"source": [ "local_run"
"### Widget for monitoring runs\n", ],
"\n", "cell_type": "code"
"The widget will sit on \"loading\" until the first iteration completed, then you will see an auto-updating graph and table show up. It refreshed once per minute, so you should see the graph update as child runs complete.\n", },
"\n", {
"NOTE: The widget displays a link at the bottom. This links to a web-ui to explore the individual run details." "metadata": {},
] "source": [
}, "## Results"
{ ],
"cell_type": "code", "cell_type": "markdown"
"execution_count": null, },
"metadata": {}, {
"outputs": [], "metadata": {},
"source": [ "source": [
"from azureml.widgets import RunDetails\n", "### Widget for monitoring runs\n",
"RunDetails(local_run).show() " "\n",
] "The widget will sit on \"loading\" until the first iteration completed, then you will see an auto-updating graph and table show up. It refreshed once per minute, so you should see the graph update as child runs complete.\n",
}, "\n",
{ "NOTE: The widget displays a link at the bottom. This links to a web-ui to explore the individual run details."
"cell_type": "markdown", ],
"metadata": {}, "cell_type": "markdown"
"source": [ },
"### Retrieve the Best Model\n", {
"\n", "metadata": {},
"Below we select the best pipeline from our iterations. The *get_output* method on automl_classifier returns the best run and the fitted model for the last *fit* invocation. There are overloads on *get_output* that allow you to retrieve the best run and fitted model for *any* logged metric or a particular *iteration*." "outputs": [],
] "execution_count": null,
}, "source": [
{ "from azureml.widgets import RunDetails\n",
"cell_type": "code", "RunDetails(local_run).show() "
"execution_count": null, ],
"metadata": {}, "cell_type": "code"
"outputs": [], },
"source": [ {
"best_run, fitted_model = local_run.get_output()\n", "metadata": {},
"print(best_run)\n", "source": [
"print(fitted_model)" "### Retrieve the Best Model\n",
] "\n",
}, "Below we select the best pipeline from our iterations. The *get_output* method on automl_classifier returns the best run and the fitted model for the last *fit* invocation. There are overloads on *get_output* that allow you to retrieve the best run and fitted model for *any* logged metric or a particular *iteration*."
{ ],
"cell_type": "markdown", "cell_type": "markdown"
"metadata": {}, },
"source": [ {
"### Best Model 's explanation\n", "metadata": {},
"\n", "outputs": [],
"Retrieve the explanation from the *best_run* which includes explanations for engineered features and raw features." "execution_count": null,
] "source": [
}, "best_run, fitted_model = local_run.get_output()\n",
{ "print(best_run)\n",
"cell_type": "markdown", "print(fitted_model)"
"metadata": {}, ],
"source": [ "cell_type": "code"
"#### Download engineered feature importance from artifact store\n", },
"You can use *ExplanationClient* to download the engineered feature explanations from the artifact store of the *best_run*." {
] "metadata": {},
}, "source": [
{ "### Best Model 's explanation\n",
"cell_type": "code", "\n",
"execution_count": null, "Retrieve the explanation from the best_run. And explanation information includes:\n",
"metadata": {}, "\n",
"outputs": [], "1.\tshap_values: The explanation information generated by shap lib\n",
"source": [ "2.\texpected_values: The expected value of the model applied to set of X_train data.\n",
"client = ExplanationClient.from_run(best_run)\n", "3.\toverall_summary: The model level feature importance values sorted in descending order\n",
"engineered_explanations = client.download_model_explanation(raw=False)\n", "4.\toverall_imp: The feature names sorted in the same order as in overall_summary\n",
"print(engineered_explanations.get_feature_importance_dict())" "5.\tper_class_summary: The class level feature importance values sorted in descending order. Only available for the classification case\n",
] "6.\tper_class_imp: The feature names sorted in the same order as in per_class_summary. Only available for the classification case\n",
}, "\n",
{ "Note:- The **retrieve_model_explanation()** API only works in case AutoML has been configured with **'model_explainability'** flag set to **True**. "
"cell_type": "markdown", ],
"metadata": {}, "cell_type": "markdown"
"source": [ },
"#### Download raw feature importance from artifact store\n", {
"You can use *ExplanationClient* to download the raw feature explanations from the artifact store of the *best_run*." "metadata": {},
] "outputs": [],
}, "execution_count": null,
{ "source": [
"cell_type": "code", "from azureml.train.automl.automlexplainer import retrieve_model_explanation\n",
"execution_count": null, "\n",
"metadata": {}, "shap_values, expected_values, overall_summary, overall_imp, per_class_summary, per_class_imp = \\\n",
"outputs": [], " retrieve_model_explanation(best_run)"
"source": [ ],
"client = ExplanationClient.from_run(best_run)\n", "cell_type": "code"
"raw_explanations = client.download_model_explanation(raw=True)\n", },
"print(raw_explanations.get_feature_importance_dict())" {
] "metadata": {},
}, "outputs": [],
{ "execution_count": null,
"cell_type": "markdown", "source": [
"metadata": {}, "print(overall_summary)\n",
"source": [ "print(overall_imp)"
"## Explanations\n", ],
"In this section, we will show how to compute model explanations and visualize the explanations using azureml-explain-model package. Besides retrieving an existing model explanation for an AutoML model, you can also explain your AutoML model with different test data. The following steps will allow you to compute and visualize engineered feature importance and raw feature importance based on your test data. " "cell_type": "code"
] },
}, {
{ "metadata": {},
"cell_type": "markdown", "outputs": [],
"metadata": {}, "execution_count": null,
"source": [ "source": [
"#### Retrieve any other AutoML model from training" "print(per_class_summary)\n",
] "print(per_class_imp)"
}, ],
{ "cell_type": "code"
"cell_type": "code", },
"execution_count": null, {
"metadata": {}, "metadata": {},
"outputs": [], "source": [
"source": [ "Beside retrieve the existed model explanation information, explain the model with different train/test data"
"automl_run, fitted_model = local_run.get_output(iteration=0)" ],
] "cell_type": "markdown"
}, },
{ {
"cell_type": "markdown", "metadata": {},
"metadata": {}, "outputs": [],
"source": [ "execution_count": null,
"#### Setup the model explanations for AutoML models\n", "source": [
"The *fitted_model* can generate the following which will be used for getting the engineered and raw feature explanations using *automl_setup_model_explanations*:-\n", "from azureml.train.automl.automlexplainer import explain_model\n",
"1. Featurized data from train samples/test samples \n", "\n",
"2. Gather engineered and raw feature name lists\n", "shap_values, expected_values, overall_summary, overall_imp, per_class_summary, per_class_imp = \\\n",
"3. Find the classes in your labeled column in classification scenarios\n", " explain_model(fitted_model, X_train, X_test, features=features)"
"\n", ],
"The *automl_explainer_setup_obj* contains all the structures from above list. " "cell_type": "code"
] },
}, {
{ "metadata": {},
"cell_type": "code", "outputs": [],
"execution_count": null, "execution_count": null,
"metadata": {}, "source": [
"outputs": [], "print(overall_summary)\n",
"source": [ "print(overall_imp)"
"from azureml.train.automl.automl_explain_utilities import AutoMLExplainerSetupClass, automl_setup_model_explanations\n", ],
"\n", "cell_type": "code"
"automl_explainer_setup_obj = automl_setup_model_explanations(fitted_model, X=X_train, \n", }
" X_test=X_test, y=y_train, \n", ],
" task='classification')" "nbformat_minor": 2
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Initialize the Mimic Explainer for feature importance\n",
"For explaining the AutoML models, use the *MimicWrapper* from *azureml.explain.model* package. The *MimicWrapper* can be initialized with fields in *automl_explainer_setup_obj*, your workspace and a LightGBM model which acts as a surrogate model to explain the AutoML model (*fitted_model* here). The *MimicWrapper* also takes the *automl_run* object where the raw and engineered explanations will be uploaded."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.explain.model.mimic.models.lightgbm_model import LGBMExplainableModel\n",
"from azureml.explain.model.mimic_wrapper import MimicWrapper\n",
"explainer = MimicWrapper(ws, automl_explainer_setup_obj.automl_estimator, LGBMExplainableModel, \n",
" init_dataset=automl_explainer_setup_obj.X_transform, run=automl_run,\n",
" features=automl_explainer_setup_obj.engineered_feature_names, \n",
" feature_maps=[automl_explainer_setup_obj.feature_map],\n",
" classes=automl_explainer_setup_obj.classes)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Use Mimic Explainer for computing and visualizing engineered feature importance\n",
"The *explain()* method in *MimicWrapper* can be called with the transformed test samples to get the feature importance for the generated engineered features. You can also use *ExplanationDashboard* to view the dash board visualization of the feature importance values of the generated engineered features by AutoML featurizers."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"engineered_explanations = explainer.explain(['local', 'global'], eval_dataset=automl_explainer_setup_obj.X_test_transform)\n",
"print(engineered_explanations.get_feature_importance_dict())\n",
"from azureml.contrib.interpret.visualize import ExplanationDashboard\n",
"ExplanationDashboard(engineered_explanations, automl_explainer_setup_obj.automl_estimator, automl_explainer_setup_obj.X_test_transform)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Use Mimic Explainer for computing and visualizing raw feature importance\n",
"The *explain()* method in *MimicWrapper* can be again called with the transformed test samples and setting *get_raw* to *True* to get the feature importance for the raw features. You can also use *ExplanationDashboard* to view the dash board visualization of the feature importance values of the raw features."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"raw_explanations = explainer.explain(['local', 'global'], get_raw=True, \n",
" raw_feature_names=automl_explainer_setup_obj.raw_feature_names,\n",
" eval_dataset=automl_explainer_setup_obj.X_test_transform)\n",
"print(raw_explanations.get_feature_importance_dict())\n",
"from azureml.contrib.interpret.visualize import ExplanationDashboard\n",
"ExplanationDashboard(raw_explanations, automl_explainer_setup_obj.automl_pipeline, automl_explainer_setup_obj.X_test_raw)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Operationailze\n",
"In this section we will show how you can operationalize an AutoML model and the explainer which was used to compute the explanations in the previous section.\n",
"\n",
"#### Register the AutoML model and the scoring explainer\n",
"We use the *TreeScoringExplainer* from *azureml.explain.model* package to create the scoring explainer which will be used to compute the raw and engineered feature importances at the inference time. Note that, we initialize the scoring explainer with the *feature_map* that was computed previously. The *feature_map* will be used by the scoring explainer to return the raw feature importance.\n",
"\n",
"In the cell below, we pickle the scoring explainer and register the AutoML model and the scoring explainer with the Model Management Service."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.explain.model.scoring.scoring_explainer import TreeScoringExplainer, save\n",
"\n",
"# Initialize the ScoringExplainer\n",
"scoring_explainer = TreeScoringExplainer(explainer.explainer, feature_maps=[automl_explainer_setup_obj.feature_map])\n",
"\n",
"# Pickle scoring explainer locally\n",
"save(scoring_explainer, exist_ok=True)\n",
"\n",
"# Register trained automl model present in the 'outputs' folder in the artifacts\n",
"original_model = automl_run.register_model(model_name='automl_model', \n",
" model_path='outputs/model.pkl')\n",
"\n",
"# Register scoring explainer\n",
"automl_run.upload_file('scoring_explainer.pkl', 'scoring_explainer.pkl')\n",
"scoring_explainer_model = automl_run.register_model(model_name='scoring_explainer', model_path='scoring_explainer.pkl')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Create the conda dependencies for setting up the service\n",
"We need to create the conda dependencies comprising of the *azureml-explain-model*, *azureml-train-automl* and *azureml-defaults* packages. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.core.conda_dependencies import CondaDependencies \n",
"\n",
"azureml_pip_packages = [\n",
" 'azureml-explain-model', 'azureml-train-automl', 'azureml-defaults'\n",
"]\n",
" \n",
"\n",
"# specify CondaDependencies obj\n",
"myenv = CondaDependencies.create(conda_packages=['scikit-learn', 'pandas', 'numpy', 'py-xgboost<=0.80'],\n",
" pip_packages=azureml_pip_packages,\n",
" pin_sdk_version=True)\n",
"\n",
"with open(\"myenv.yml\",\"w\") as f:\n",
" f.write(myenv.serialize_to_string())\n",
"\n",
"with open(\"myenv.yml\",\"r\") as f:\n",
" print(f.read())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### View your scoring file"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"with open(\"score_local_explain.py\",\"r\") as f:\n",
" print(f.read())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Deploy the service\n",
"In the cell below, we deploy the service using the conda file and the scoring file from the previous steps. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.core.webservice import Webservice\n",
"from azureml.core.model import InferenceConfig\n",
"from azureml.core.webservice import AciWebservice\n",
"from azureml.core.model import Model\n",
"\n",
"aciconfig = AciWebservice.deploy_configuration(cpu_cores=1, \n",
" memory_gb=1, \n",
" tags={\"data\": \"Bank Marketing\", \n",
" \"method\" : \"local_explanation\"}, \n",
" description='Get local explanations for Bank marketing test data')\n",
"\n",
"inference_config = InferenceConfig(runtime= \"python\", \n",
" entry_script=\"score_local_explain.py\",\n",
" conda_file=\"myenv.yml\")\n",
"\n",
"# Use configs and models generated above\n",
"service = Model.deploy(ws, 'model-scoring', [scoring_explainer_model, original_model], inference_config, aciconfig)\n",
"service.wait_for_deployment(show_output=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### View the service logs"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"service.get_logs()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Inference using some test data\n",
"Inference using some test data to see the predicted value from autml model, view the engineered feature importance for the predicted value and raw feature importance for the predicted value."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"if service.state == 'Healthy':\n",
" # Serialize the first row of the test data into json\n",
" X_test_json = X_test[:1].to_json(orient='records')\n",
" print(X_test_json)\n",
" # Call the service to get the predictions and the engineered and raw explanations\n",
" output = service.run(X_test_json)\n",
" # Print the predicted value\n",
" print(output['predictions'])\n",
" # Print the engineered feature importances for the predicted value\n",
" print(output['engineered_local_importance_values'])\n",
" # Print the raw feature importances for the predicted value\n",
" print(output['raw_local_importance_values'])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Delete the service\n",
"Delete the service once you have finished inferencing."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"service.delete()"
]
}
],
"metadata": {
"authors": [
{
"name": "xif"
}
],
"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"
}
},
"nbformat": 4,
"nbformat_minor": 2
} }

View File

@@ -1,11 +1,9 @@
name: auto-ml-model-explanation name: auto-ml-model-explanation
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- interpret - azureml-train-automl
- azureml-train-automl - azureml-widgets
- azureml-widgets - matplotlib
- matplotlib - pandas_ml
- pandas_ml - azureml-explain-model
- azureml-explain-model
- azureml-contrib-interpret

View File

@@ -1,42 +0,0 @@
import json
import numpy as np
import pandas as pd
import os
import pickle
import azureml.train.automl
import azureml.explain.model
from azureml.train.automl.automl_explain_utilities import AutoMLExplainerSetupClass, automl_setup_model_explanations
from sklearn.externals import joblib
from azureml.core.model import Model
def init():
global automl_model
global scoring_explainer
# Retrieve the path to the model file using the model name
# Assume original model is named original_prediction_model
automl_model_path = Model.get_model_path('automl_model')
scoring_explainer_path = Model.get_model_path('scoring_explainer')
automl_model = joblib.load(automl_model_path)
scoring_explainer = joblib.load(scoring_explainer_path)
def run(raw_data):
# Get predictions and explanations for each data point
data = pd.read_json(raw_data, orient='records')
# Make prediction
predictions = automl_model.predict(data)
# Setup for inferencing explanations
automl_explainer_setup_obj = automl_setup_model_explanations(automl_model,
X_test=data, task='classification')
# Retrieve model explanations for engineered explanations
engineered_local_importance_values = scoring_explainer.explain(automl_explainer_setup_obj.X_test_transform)
# Retrieve model explanations for raw explanations
raw_local_importance_values = scoring_explainer.explain(automl_explainer_setup_obj.X_test_transform, get_raw=True)
# You can return any data type as long as it is JSON-serializable
return {'predictions': predictions.tolist(),
'engineered_local_importance_values': engineered_local_importance_values,
'raw_local_importance_values': raw_local_importance_values}

View File

@@ -1,12 +1,8 @@
name: auto-ml-regression-concrete-strength name: auto-ml-regression-concrete-strength
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- interpret - azureml-train-automl
- azureml-defaults - azureml-widgets
- azureml-explain-model - matplotlib
- azureml-train-automl - pandas_ml
- azureml-widgets
- matplotlib
- pandas_ml
- azureml-dataprep[pandas]

View File

@@ -1,12 +1,8 @@
name: auto-ml-regression-hardware-performance name: auto-ml-regression-hardware-performance
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- interpret - azureml-train-automl
- azureml-defaults - azureml-widgets
- azureml-explain-model - matplotlib
- azureml-train-automl - pandas_ml
- azureml-widgets
- matplotlib
- pandas_ml
- azureml-dataprep[pandas]

View File

@@ -1,403 +1,407 @@
{ {
"cells": [ "metadata": {
{ "kernelspec": {
"cell_type": "markdown", "display_name": "Python 3.6",
"metadata": {}, "name": "python36",
"source": [ "language": "python"
"Copyright (c) Microsoft Corporation. All rights reserved.\n", },
"\n", "authors": [
"Licensed under the MIT License." {
] "name": "savitam"
}, }
{ ],
"cell_type": "markdown", "language_info": {
"metadata": {}, "mimetype": "text/x-python",
"source": [ "codemirror_mode": {
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/regression/auto-ml-regression.png)" "name": "ipython",
] "version": 3
}, },
{ "pygments_lexer": "ipython3",
"cell_type": "markdown", "name": "python",
"metadata": {}, "file_extension": ".py",
"source": [ "nbconvert_exporter": "python",
"# Automated Machine Learning\n", "version": "3.6.6"
"_**Regression with Local Compute**_\n", }
"\n", },
"## Contents\n", "nbformat": 4,
"1. [Introduction](#Introduction)\n", "cells": [
"1. [Setup](#Setup)\n", {
"1. [Data](#Data)\n", "metadata": {},
"1. [Train](#Train)\n", "source": [
"1. [Results](#Results)\n", "Copyright (c) Microsoft Corporation. All rights reserved.\n",
"1. [Test](#Test)\n" "\n",
] "Licensed under the MIT License."
}, ],
{ "cell_type": "markdown"
"cell_type": "markdown", },
"metadata": {}, {
"source": [ "metadata": {},
"## Introduction\n", "source": [
"In this example we use the scikit-learn's [diabetes dataset](http://scikit-learn.org/stable/datasets/index.html#diabetes-dataset) to showcase how you can use AutoML for a simple regression problem.\n", "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/regression/auto-ml-regression.png)"
"\n", ],
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n", "cell_type": "markdown"
"\n", },
"In this notebook you will learn how to:\n", {
"1. Create an `Experiment` in an existing `Workspace`.\n", "metadata": {},
"2. Configure AutoML using `AutoMLConfig`.\n", "source": [
"3. Train the model using local compute.\n", "# Automated Machine Learning\n",
"4. Explore the results.\n", "_**Regression with Local Compute**_\n",
"5. Test the best fitted model." "\n",
] "## Contents\n",
}, "1. [Introduction](#Introduction)\n",
{ "1. [Setup](#Setup)\n",
"cell_type": "markdown", "1. [Data](#Data)\n",
"metadata": {}, "1. [Train](#Train)\n",
"source": [ "1. [Results](#Results)\n",
"## Setup\n", "1. [Test](#Test)\n"
"\n", ],
"As part of the setup you have already created an Azure ML `Workspace` object. For AutoML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments." "cell_type": "markdown"
] },
}, {
{ "metadata": {},
"cell_type": "code", "source": [
"execution_count": null, "## Introduction\n",
"metadata": {}, "In this example we use the scikit-learn's [diabetes dataset](http://scikit-learn.org/stable/datasets/index.html#diabetes-dataset) to showcase how you can use AutoML for a simple regression problem.\n",
"outputs": [], "\n",
"source": [ "Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
"import logging\n", "\n",
"\n", "In this notebook you will learn how to:\n",
"from matplotlib import pyplot as plt\n", "1. Create an `Experiment` in an existing `Workspace`.\n",
"import numpy as np\n", "2. Configure AutoML using `AutoMLConfig`.\n",
"import pandas as pd\n", "3. Train the model using local compute.\n",
"\n", "4. Explore the results.\n",
"import azureml.core\n", "5. Test the best fitted model."
"from azureml.core.experiment import Experiment\n", ],
"from azureml.core.workspace import Workspace\n", "cell_type": "markdown"
"from azureml.train.automl import AutoMLConfig" },
] {
}, "metadata": {},
{ "source": [
"cell_type": "code", "## Setup\n",
"execution_count": null, "\n",
"metadata": {}, "As part of the setup you have already created an Azure ML `Workspace` object. For AutoML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments."
"outputs": [], ],
"source": [ "cell_type": "markdown"
"ws = Workspace.from_config()\n", },
"\n", {
"# Choose a name for the experiment.\n", "metadata": {},
"experiment_name = 'automl-local-regression'\n", "outputs": [],
"\n", "execution_count": null,
"experiment = Experiment(ws, experiment_name)\n", "source": [
"\n", "import logging\n",
"output = {}\n", "\n",
"output['SDK version'] = azureml.core.VERSION\n", "from matplotlib import pyplot as plt\n",
"output['Subscription ID'] = ws.subscription_id\n", "import numpy as np\n",
"output['Workspace Name'] = ws.name\n", "import pandas as pd\n",
"output['Resource Group'] = ws.resource_group\n", "\n",
"output['Location'] = ws.location\n", "import azureml.core\n",
"output['Experiment Name'] = experiment.name\n", "from azureml.core.experiment import Experiment\n",
"pd.set_option('display.max_colwidth', -1)\n", "from azureml.core.workspace import Workspace\n",
"outputDf = pd.DataFrame(data = output, index = [''])\n", "from azureml.train.automl import AutoMLConfig"
"outputDf.T" ],
] "cell_type": "code"
}, },
{ {
"cell_type": "markdown", "metadata": {},
"metadata": {}, "outputs": [],
"source": [ "execution_count": null,
"## Data\n", "source": [
"This uses scikit-learn's [load_diabetes](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_diabetes.html) method." "ws = Workspace.from_config()\n",
] "\n",
}, "# Choose a name for the experiment and specify the project folder.\n",
{ "experiment_name = 'automl-local-regression'\n",
"cell_type": "code", "project_folder = './sample_projects/automl-local-regression'\n",
"execution_count": null, "\n",
"metadata": {}, "experiment = Experiment(ws, experiment_name)\n",
"outputs": [], "\n",
"source": [ "output = {}\n",
"# Load the diabetes dataset, a well-known built-in small dataset that comes with scikit-learn.\n", "output['SDK version'] = azureml.core.VERSION\n",
"from sklearn.datasets import load_diabetes\n", "output['Subscription ID'] = ws.subscription_id\n",
"from sklearn.model_selection import train_test_split\n", "output['Workspace Name'] = ws.name\n",
"\n", "output['Resource Group'] = ws.resource_group\n",
"X, y = load_diabetes(return_X_y = True)\n", "output['Location'] = ws.location\n",
"\n", "output['Project Directory'] = project_folder\n",
"columns = ['age', 'gender', 'bmi', 'bp', 's1', 's2', 's3', 's4', 's5', 's6']\n", "output['Experiment Name'] = experiment.name\n",
"\n", "pd.set_option('display.max_colwidth', -1)\n",
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)" "outputDf = pd.DataFrame(data = output, index = [''])\n",
] "outputDf.T"
}, ],
{ "cell_type": "code"
"cell_type": "markdown", },
"metadata": {}, {
"source": [ "metadata": {},
"## Train\n", "source": [
"\n", "## Data\n",
"Instantiate an `AutoMLConfig` object to specify the settings and data used to run the experiment.\n", "This uses scikit-learn's [load_diabetes](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_diabetes.html) method."
"\n", ],
"|Property|Description|\n", "cell_type": "markdown"
"|-|-|\n", },
"|**task**|classification or regression|\n", {
"|**primary_metric**|This is the metric that you want to optimize. Regression supports the following primary metrics: <br><i>spearman_correlation</i><br><i>normalized_root_mean_squared_error</i><br><i>r2_score</i><br><i>normalized_mean_absolute_error</i>|\n", "metadata": {},
"|**iteration_timeout_minutes**|Time limit in minutes for each iteration.|\n", "outputs": [],
"|**iterations**|Number of iterations. In each iteration AutoML trains a specific pipeline with the data.|\n", "execution_count": null,
"|**n_cross_validations**|Number of cross validation splits.|\n", "source": [
"|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n", "# Load the diabetes dataset, a well-known built-in small dataset that comes with scikit-learn.\n",
"|**y**|(sparse) array-like, shape = [n_samples, ], targets values.|" "from sklearn.datasets import load_diabetes\n",
] "from sklearn.model_selection import train_test_split\n",
}, "\n",
{ "X, y = load_diabetes(return_X_y = True)\n",
"cell_type": "code", "\n",
"execution_count": null, "columns = ['age', 'gender', 'bmi', 'bp', 's1', 's2', 's3', 's4', 's5', 's6']\n",
"metadata": {}, "\n",
"outputs": [], "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)"
"source": [ ],
"automl_config = AutoMLConfig(task = 'regression',\n", "cell_type": "code"
" iteration_timeout_minutes = 10,\n", },
" iterations = 10,\n", {
" primary_metric = 'spearman_correlation',\n", "metadata": {},
" n_cross_validations = 5,\n", "source": [
" debug_log = 'automl.log',\n", "## Train\n",
" verbosity = logging.INFO,\n", "\n",
" X = X_train, \n", "Instantiate an `AutoMLConfig` object to specify the settings and data used to run the experiment.\n",
" y = y_train)" "\n",
] "|Property|Description|\n",
}, "|-|-|\n",
{ "|**task**|classification or regression|\n",
"cell_type": "markdown", "|**primary_metric**|This is the metric that you want to optimize. Regression supports the following primary metrics: <br><i>spearman_correlation</i><br><i>normalized_root_mean_squared_error</i><br><i>r2_score</i><br><i>normalized_mean_absolute_error</i>|\n",
"metadata": {}, "|**iteration_timeout_minutes**|Time limit in minutes for each iteration.|\n",
"source": [ "|**iterations**|Number of iterations. In each iteration AutoML trains a specific pipeline with the data.|\n",
"Call the `submit` method on the experiment object and pass the run configuration. Execution of local runs is synchronous. Depending on the data and the number of iterations this can run for a while.\n", "|**n_cross_validations**|Number of cross validation splits.|\n",
"In this example, we specify `show_output = True` to print currently running iterations to the console." "|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n",
] "|**y**|(sparse) array-like, shape = [n_samples, ], targets values.|\n",
}, "|**path**|Relative path to the project folder. AutoML stores configuration files for the experiment under this folder. You can specify a new empty folder.|"
{ ],
"cell_type": "code", "cell_type": "markdown"
"execution_count": null, },
"metadata": {}, {
"outputs": [], "metadata": {},
"source": [ "outputs": [],
"local_run = experiment.submit(automl_config, show_output = True)" "execution_count": null,
] "source": [
}, "automl_config = AutoMLConfig(task = 'regression',\n",
{ " iteration_timeout_minutes = 10,\n",
"cell_type": "code", " iterations = 10,\n",
"execution_count": null, " primary_metric = 'spearman_correlation',\n",
"metadata": {}, " n_cross_validations = 5,\n",
"outputs": [], " debug_log = 'automl.log',\n",
"source": [ " verbosity = logging.INFO,\n",
"local_run" " X = X_train, \n",
] " y = y_train,\n",
}, " path = project_folder)"
{ ],
"cell_type": "markdown", "cell_type": "code"
"metadata": {}, },
"source": [ {
"## Results" "metadata": {},
] "source": [
}, "Call the `submit` method on the experiment object and pass the run configuration. Execution of local runs is synchronous. Depending on the data and the number of iterations this can run for a while.\n",
{ "In this example, we specify `show_output = True` to print currently running iterations to the console."
"cell_type": "markdown", ],
"metadata": {}, "cell_type": "markdown"
"source": [ },
"#### Widget for Monitoring Runs\n", {
"\n", "metadata": {},
"The widget will first report a \"loading\" status while running the first iteration. After completing the first iteration, an auto-updating graph and table will be shown. The widget will refresh once per minute, so you should see the graph update as child runs complete.\n", "outputs": [],
"\n", "execution_count": null,
"**Note:** The widget displays a link at the bottom. Use this link to open a web interface to explore the individual run details." "source": [
] "local_run = experiment.submit(automl_config, show_output = True)"
}, ],
{ "cell_type": "code"
"cell_type": "code", },
"execution_count": null, {
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "execution_count": null,
"from azureml.widgets import RunDetails\n", "source": [
"RunDetails(local_run).show() " "local_run"
] ],
}, "cell_type": "code"
{ },
"cell_type": "markdown", {
"metadata": {}, "metadata": {},
"source": [ "source": [
"\n", "## Results"
"#### Retrieve All Child Runs\n", ],
"You can also use SDK methods to fetch all the child runs and see individual metrics that we log." "cell_type": "markdown"
] },
}, {
{ "metadata": {},
"cell_type": "code", "source": [
"execution_count": null, "#### Widget for Monitoring Runs\n",
"metadata": {}, "\n",
"outputs": [], "The widget will first report a \"loading\" status while running the first iteration. After completing the first iteration, an auto-updating graph and table will be shown. The widget will refresh once per minute, so you should see the graph update as child runs complete.\n",
"source": [ "\n",
"children = list(local_run.get_children())\n", "**Note:** The widget displays a link at the bottom. Use this link to open a web interface to explore the individual run details."
"metricslist = {}\n", ],
"for run in children:\n", "cell_type": "markdown"
" 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", "metadata": {},
"\n", "outputs": [],
"rundata = pd.DataFrame(metricslist).sort_index(1)\n", "execution_count": null,
"rundata" "source": [
] "from azureml.widgets import RunDetails\n",
}, "RunDetails(local_run).show() "
{ ],
"cell_type": "markdown", "cell_type": "code"
"metadata": {}, },
"source": [ {
"### Retrieve the Best Model\n", "metadata": {},
"\n", "source": [
"Below we select the best pipeline from our iterations. The `get_output` method returns the best run and the fitted model. The Model includes the pipeline and any pre-processing. Overloads on `get_output` allow you to retrieve the best run and fitted model for *any* logged metric or for a particular *iteration*." "\n",
] "#### Retrieve All Child Runs\n",
}, "You can also use SDK methods to fetch all the child runs and see individual metrics that we log."
{ ],
"cell_type": "code", "cell_type": "markdown"
"execution_count": null, },
"metadata": {}, {
"outputs": [], "metadata": {},
"source": [ "outputs": [],
"best_run, fitted_model = local_run.get_output()\n", "execution_count": null,
"print(best_run)\n", "source": [
"print(fitted_model)" "children = list(local_run.get_children())\n",
] "metricslist = {}\n",
}, "for run in children:\n",
{ " properties = run.get_properties()\n",
"cell_type": "markdown", " metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)}\n",
"metadata": {}, " metricslist[int(properties['iteration'])] = metrics\n",
"source": [ "\n",
"#### Best Model Based on Any Other Metric\n", "rundata = pd.DataFrame(metricslist).sort_index(1)\n",
"Show the run and the model that has the smallest `root_mean_squared_error` value (which turned out to be the same as the one with largest `spearman_correlation` value):" "rundata"
] ],
}, "cell_type": "code"
{ },
"cell_type": "code", {
"execution_count": null, "metadata": {},
"metadata": {}, "source": [
"outputs": [], "### Retrieve the Best Model\n",
"source": [ "\n",
"lookup_metric = \"root_mean_squared_error\"\n", "Below we select the best pipeline from our iterations. The `get_output` method returns the best run and the fitted model. The Model includes the pipeline and any pre-processing. Overloads on `get_output` allow you to retrieve the best run and fitted model for *any* logged metric or for a particular *iteration*."
"best_run, fitted_model = local_run.get_output(metric = lookup_metric)\n", ],
"print(best_run)\n", "cell_type": "markdown"
"print(fitted_model)" },
] {
}, "metadata": {},
{ "outputs": [],
"cell_type": "markdown", "execution_count": null,
"metadata": {}, "source": [
"source": [ "best_run, fitted_model = local_run.get_output()\n",
"#### Model from a Specific Iteration\n", "print(best_run)\n",
"Show the run and the model from the third iteration:" "print(fitted_model)"
] ],
}, "cell_type": "code"
{ },
"cell_type": "code", {
"execution_count": null, "metadata": {},
"metadata": {}, "source": [
"outputs": [], "#### Best Model Based on Any Other Metric\n",
"source": [ "Show the run and the model that has the smallest `root_mean_squared_error` value (which turned out to be the same as the one with largest `spearman_correlation` value):"
"iteration = 3\n", ],
"third_run, third_model = local_run.get_output(iteration = iteration)\n", "cell_type": "markdown"
"print(third_run)\n", },
"print(third_model)" {
] "metadata": {},
}, "outputs": [],
{ "execution_count": null,
"cell_type": "markdown", "source": [
"metadata": {}, "lookup_metric = \"root_mean_squared_error\"\n",
"source": [ "best_run, fitted_model = local_run.get_output(metric = lookup_metric)\n",
"## Test" "print(best_run)\n",
] "print(fitted_model)"
}, ],
{ "cell_type": "code"
"cell_type": "markdown", },
"metadata": {}, {
"source": [ "metadata": {},
"Predict on training and test set, and calculate residual values." "source": [
] "#### Model from a Specific Iteration\n",
}, "Show the run and the model from the third iteration:"
{ ],
"cell_type": "code", "cell_type": "markdown"
"execution_count": null, },
"metadata": {}, {
"outputs": [], "metadata": {},
"source": [ "outputs": [],
"y_pred_train = fitted_model.predict(X_train)\n", "execution_count": null,
"y_residual_train = y_train - y_pred_train\n", "source": [
"\n", "iteration = 3\n",
"y_pred_test = fitted_model.predict(X_test)\n", "third_run, third_model = local_run.get_output(iteration = iteration)\n",
"y_residual_test = y_test - y_pred_test" "print(third_run)\n",
] "print(third_model)"
}, ],
{ "cell_type": "code"
"cell_type": "code", },
"execution_count": null, {
"metadata": {}, "metadata": {},
"outputs": [], "source": [
"source": [ "## Test"
"%matplotlib inline\n", ],
"from sklearn.metrics import mean_squared_error, r2_score\n", "cell_type": "markdown"
"\n", },
"# Set up a multi-plot chart.\n", {
"f, (a0, a1) = plt.subplots(1, 2, gridspec_kw = {'width_ratios':[1, 1], 'wspace':0, 'hspace': 0})\n", "metadata": {},
"f.suptitle('Regression Residual Values', fontsize = 18)\n", "source": [
"f.set_figheight(6)\n", "Predict on training and test set, and calculate residual values."
"f.set_figwidth(16)\n", ],
"\n", "cell_type": "markdown"
"# Plot residual values of training set.\n", },
"a0.axis([0, 360, -200, 200])\n", {
"a0.plot(y_residual_train, 'bo', alpha = 0.5)\n", "metadata": {},
"a0.plot([-10,360],[0,0], 'r-', lw = 3)\n", "outputs": [],
"a0.text(16,170,'RMSE = {0:.2f}'.format(np.sqrt(mean_squared_error(y_train, y_pred_train))), fontsize = 12)\n", "execution_count": null,
"a0.text(16,140,'R2 score = {0:.2f}'.format(r2_score(y_train, y_pred_train)), fontsize = 12)\n", "source": [
"a0.set_xlabel('Training samples', fontsize = 12)\n", "y_pred_train = fitted_model.predict(X_train)\n",
"a0.set_ylabel('Residual Values', fontsize = 12)\n", "y_residual_train = y_train - y_pred_train\n",
"\n", "\n",
"# Plot a histogram.\n", "y_pred_test = fitted_model.predict(X_test)\n",
"a0.hist(y_residual_train, orientation = 'horizontal', color = 'b', bins = 10, histtype = 'step')\n", "y_residual_test = y_test - y_pred_test"
"a0.hist(y_residual_train, orientation = 'horizontal', color = 'b', alpha = 0.2, bins = 10)\n", ],
"\n", "cell_type": "code"
"# Plot residual values of test set.\n", },
"a1.axis([0, 90, -200, 200])\n", {
"a1.plot(y_residual_test, 'bo', alpha = 0.5)\n", "metadata": {},
"a1.plot([-10,360],[0,0], 'r-', lw = 3)\n", "outputs": [],
"a1.text(5,170,'RMSE = {0:.2f}'.format(np.sqrt(mean_squared_error(y_test, y_pred_test))), fontsize = 12)\n", "execution_count": null,
"a1.text(5,140,'R2 score = {0:.2f}'.format(r2_score(y_test, y_pred_test)), fontsize = 12)\n", "source": [
"a1.set_xlabel('Test samples', fontsize = 12)\n", "%matplotlib inline\n",
"a1.set_yticklabels([])\n", "from sklearn.metrics import mean_squared_error, r2_score\n",
"\n", "\n",
"# Plot a histogram.\n", "# Set up a multi-plot chart.\n",
"a1.hist(y_residual_test, orientation = 'horizontal', color = 'b', bins = 10, histtype = 'step')\n", "f, (a0, a1) = plt.subplots(1, 2, gridspec_kw = {'width_ratios':[1, 1], 'wspace':0, 'hspace': 0})\n",
"a1.hist(y_residual_test, orientation = 'horizontal', color = 'b', alpha = 0.2, bins = 10)\n", "f.suptitle('Regression Residual Values', fontsize = 18)\n",
"\n", "f.set_figheight(6)\n",
"plt.show()" "f.set_figwidth(16)\n",
] "\n",
} "# Plot residual values of training set.\n",
], "a0.axis([0, 360, -200, 200])\n",
"metadata": { "a0.plot(y_residual_train, 'bo', alpha = 0.5)\n",
"authors": [ "a0.plot([-10,360],[0,0], 'r-', lw = 3)\n",
{ "a0.text(16,170,'RMSE = {0:.2f}'.format(np.sqrt(mean_squared_error(y_train, y_pred_train))), fontsize = 12)\n",
"name": "savitam" "a0.text(16,140,'R2 score = {0:.2f}'.format(r2_score(y_train, y_pred_train)), fontsize = 12)\n",
} "a0.set_xlabel('Training samples', fontsize = 12)\n",
], "a0.set_ylabel('Residual Values', fontsize = 12)\n",
"kernelspec": { "\n",
"display_name": "Python 3.6", "# Plot a histogram.\n",
"language": "python", "a0.hist(y_residual_train, orientation = 'horizontal', color = 'b', bins = 10, histtype = 'step')\n",
"name": "python36" "a0.hist(y_residual_train, orientation = 'horizontal', color = 'b', alpha = 0.2, bins = 10)\n",
}, "\n",
"language_info": { "# Plot residual values of test set.\n",
"codemirror_mode": { "a1.axis([0, 90, -200, 200])\n",
"name": "ipython", "a1.plot(y_residual_test, 'bo', alpha = 0.5)\n",
"version": 3 "a1.plot([-10,360],[0,0], 'r-', lw = 3)\n",
}, "a1.text(5,170,'RMSE = {0:.2f}'.format(np.sqrt(mean_squared_error(y_test, y_pred_test))), fontsize = 12)\n",
"file_extension": ".py", "a1.text(5,140,'R2 score = {0:.2f}'.format(r2_score(y_test, y_pred_test)), fontsize = 12)\n",
"mimetype": "text/x-python", "a1.set_xlabel('Test samples', fontsize = 12)\n",
"name": "python", "a1.set_yticklabels([])\n",
"nbconvert_exporter": "python", "\n",
"pygments_lexer": "ipython3", "# Plot a histogram.\n",
"version": "3.6.6" "a1.hist(y_residual_test, orientation = 'horizontal', color = 'b', bins = 10, histtype = 'step')\n",
} "a1.hist(y_residual_test, orientation = 'horizontal', color = 'b', alpha = 0.2, bins = 10)\n",
}, "\n",
"nbformat": 4, "plt.show()"
"nbformat_minor": 2 ],
"cell_type": "code"
}
],
"nbformat_minor": 2
} }

View File

@@ -1,9 +1,9 @@
name: auto-ml-regression name: auto-ml-regression
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- azureml-train-automl - azureml-train-automl
- azureml-widgets - azureml-widgets
- matplotlib - matplotlib
- pandas_ml - pandas_ml
- paramiko<2.5.0 - paramiko<2.5.0

View File

@@ -1,542 +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": [
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/remote-amlcompute/auto-ml-remote-amlcompute.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Automated Machine Learning\n",
"_**Remote Execution using AmlCompute**_\n",
"\n",
"## Contents\n",
"1. [Introduction](#Introduction)\n",
"1. [Setup](#Setup)\n",
"1. [Data](#Data)\n",
"1. [Train](#Train)\n",
"1. [Results](#Results)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Introduction\n",
"In this example we use the scikit-learn's [iris dataset](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_iris.html) to showcase how you can use AutoML for a simple classification problem.\n",
"\n",
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
"\n",
"In this notebook you would see\n",
"1. Create an `Experiment` in an existing `Workspace`.\n",
"2. Create or Attach existing AmlCompute to a workspace.\n",
"3. Configure AutoML using `AutoMLConfig`.\n",
"4. Train the model using AmlCompute with ONNX compatible config on.\n",
"5. Explore the results and save the ONNX model.\n",
"6. Inference with the ONNX model.\n",
"\n",
"In addition this notebook showcases the following features\n",
"- **Parallel** executions for iterations\n",
"- **Asynchronous** tracking of progress\n",
"- **Cancellation** of individual iterations or the entire run\n",
"- Retrieving models for any iteration or logged metric\n",
"- Specifying AutoML settings as `**kwargs`"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Setup\n",
"\n",
"As part of the setup you have already created an Azure ML `Workspace` object. For AutoML 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",
"import os\n",
"\n",
"import pandas as pd\n",
"from sklearn import datasets\n",
"from sklearn.model_selection import train_test_split\n",
"\n",
"import azureml.core\n",
"from azureml.core.experiment import Experiment\n",
"from azureml.core.workspace import Workspace\n",
"from azureml.core.dataset import Dataset\n",
"from azureml.train.automl import AutoMLConfig"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"ws = Workspace.from_config()\n",
"\n",
"# Choose an experiment name.\n",
"experiment_name = 'automl-remote-amlcompute-with-onnx'\n",
"\n",
"experiment = Experiment(ws, experiment_name)\n",
"\n",
"output = {}\n",
"output['SDK version'] = azureml.core.VERSION\n",
"output['Subscription ID'] = ws.subscription_id\n",
"output['Workspace Name'] = 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": [
"### 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",
"\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",
"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."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.core.compute import AmlCompute\n",
"from azureml.core.compute import ComputeTarget\n",
"\n",
"# Choose a name for your cluster.\n",
"amlcompute_cluster_name = \"automlc2\"\n",
"\n",
"found = False\n",
"# Check if this compute target already exists in the workspace.\n",
"cts = ws.compute_targets\n",
"if amlcompute_cluster_name in cts and cts[amlcompute_cluster_name].type == 'AmlCompute':\n",
" found = True\n",
" print('Found existing compute target.')\n",
" compute_target = cts[amlcompute_cluster_name]\n",
"\n",
"if not found:\n",
" print('Creating a new compute target...')\n",
" provisioning_config = AmlCompute.provisioning_configuration(vm_size = \"STANDARD_D2_V2\", # for GPU, use \"STANDARD_NC6\"\n",
" #vm_priority = 'lowpriority', # optional\n",
" max_nodes = 6)\n",
"\n",
" # Create the cluster.\\n\",\n",
" compute_target = ComputeTarget.create(ws, amlcompute_cluster_name, provisioning_config)\n",
"\n",
"print('Checking cluster status...')\n",
"# Can poll for a minimum number of nodes and for a specific timeout.\n",
"# If no min_node_count is provided, it will use the scale settings for the cluster.\n",
"compute_target.wait_for_completion(show_output = True, min_node_count = None, timeout_in_minutes = 20)\n",
"\n",
"# For a more detailed view of current AmlCompute status, use get_status()."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Data\n",
"For remote executions, you need to make the data accessible from the remote compute.\n",
"This can be done by uploading the data to DataStore.\n",
"In this example, we upload scikit-learn's [load_iris](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_iris.html) data."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"iris = datasets.load_iris()\n",
"\n",
"X_train, X_test, y_train, y_test = train_test_split(iris.data, \n",
" iris.target, \n",
" test_size=0.2, \n",
" random_state=0)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Ensure the x_train and x_test are pandas DataFrame."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Convert the X_train and X_test to pandas DataFrame and set column names,\n",
"# This is needed for initializing the input variable names of ONNX model, \n",
"# and the prediction with the ONNX model using the inference helper.\n",
"X_train = pd.DataFrame(X_train, columns=['c1', 'c2', 'c3', 'c4'])\n",
"X_test = pd.DataFrame(X_test, columns=['c1', 'c2', 'c3', 'c4'])\n",
"y_train = pd.DataFrame(y_train, columns=['label'])\n",
"\n",
"if not os.path.isdir('data'):\n",
" os.mkdir('data')\n",
"\n",
"X_train.to_csv(\"data/X_train.csv\", index=False)\n",
"y_train.to_csv(\"data/y_train.csv\", index=False)\n",
"\n",
"ds = ws.get_default_datastore()\n",
"ds.upload(src_dir='./data', target_path='irisdata', overwrite=True, show_progress=True)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.core.runconfig import RunConfiguration\n",
"from azureml.core.conda_dependencies import CondaDependencies\n",
"import pkg_resources\n",
"\n",
"# create a new RunConfig object\n",
"conda_run_config = RunConfiguration(framework=\"python\")\n",
"\n",
"# Set compute target to AmlCompute\n",
"conda_run_config.target = compute_target\n",
"conda_run_config.environment.docker.enabled = True\n",
"\n",
"cd = CondaDependencies.create(conda_packages=['numpy','py-xgboost<=0.80'])\n",
"conda_run_config.environment.python.conda_dependencies = cd"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Creating a TabularDataset\n",
"\n",
"Defined X and y as `TabularDataset`s, which are passed to automated machine learning in the AutoMLConfig."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"X = Dataset.Tabular.from_delimited_files(path=ds.path('irisdata/X_train.csv'))\n",
"y = Dataset.Tabular.from_delimited_files(path=ds.path('irisdata/y_train.csv'))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Train\n",
"\n",
"You can specify `automl_settings` as `**kwargs` as well. \n",
"\n",
"**Note:** Set the parameter enable_onnx_compatible_models=True, if you also want to generate the ONNX compatible models. Please note, the forecasting task and TensorFlow models are not ONNX compatible yet.\n",
"\n",
"**Note:** When using AmlCompute, you can't pass Numpy arrays directly to the fit method.\n",
"\n",
"|Property|Description|\n",
"|-|-|\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",
"|**iteration_timeout_minutes**|Time limit in minutes for each iteration.|\n",
"|**iterations**|Number of iterations. In each iteration AutoML trains a specific pipeline with the data.|\n",
"|**n_cross_validations**|Number of cross validation splits.|\n",
"|**max_concurrent_iterations**|Maximum number of iterations that would be executed in parallel. This should be less than the number of nodes in the AmlCompute cluster.|\n",
"|**enable_onnx_compatible_models**|Enable the ONNX compatible models in the experiment.|"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Set the preprocess=True, currently the InferenceHelper only supports this mode."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"automl_settings = {\n",
" \"iteration_timeout_minutes\": 10,\n",
" \"iterations\": 10,\n",
" \"n_cross_validations\": 5,\n",
" \"primary_metric\": 'AUC_weighted',\n",
" \"preprocess\": True,\n",
" \"max_concurrent_iterations\": 5,\n",
" \"verbosity\": logging.INFO\n",
"}\n",
"\n",
"automl_config = AutoMLConfig(task = 'classification',\n",
" debug_log = 'automl_errors.log',\n",
" run_configuration=conda_run_config,\n",
" X = X,\n",
" y = y,\n",
" enable_onnx_compatible_models=True, # This will generate ONNX compatible models.\n",
" **automl_settings\n",
" )"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Call the `submit` method on the experiment object and pass the run configuration. For remote runs the execution is asynchronous, so you will see the iterations get populated as they complete. You can interact with the widgets and models even when the experiment is running to retrieve the best model up to that point. Once you are satisfied with the model, you can cancel a particular iteration or the whole run.\n",
"In this example, we specify `show_output = False` to suppress console output while the run is in progress."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"remote_run = experiment.submit(automl_config, show_output = False)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"remote_run"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Results\n",
"\n",
"#### Loading executed runs\n",
"In case you need to load a previously executed run, enable the cell below and replace the `run_id` value."
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"remote_run = AutoMLRun(experiment = experiment, run_id = 'AutoML_5db13491-c92a-4f1d-b622-8ab8d973a058')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Widget for Monitoring Runs\n",
"\n",
"The widget will first report a \"loading\" status while running the first iteration. After completing the first iteration, an auto-updating graph and table will be shown. The widget will refresh once per minute, so you should see the graph update as child runs complete.\n",
"\n",
"You can click on a pipeline to see run properties and output logs. Logs are also available on the DSVM under `/tmp/azureml_run/{iterationid}/azureml-logs`\n",
"\n",
"**Note:** The widget displays a link at the bottom. Use this link to open a web interface to explore the individual run details."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"remote_run"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.widgets import RunDetails\n",
"RunDetails(remote_run).show() "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Wait until the run finishes.\n",
"remote_run.wait_for_completion(show_output = True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Cancelling Runs\n",
"\n",
"You can cancel ongoing remote runs using the `cancel` and `cancel_iteration` functions."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Cancel the ongoing experiment and stop scheduling new iterations.\n",
"# remote_run.cancel()\n",
"\n",
"# Cancel iteration 1 and move onto iteration 2.\n",
"# remote_run.cancel_iteration(1)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Retrieve the Best ONNX Model\n",
"\n",
"Below we select the best pipeline from our iterations. The `get_output` method returns the best run and the fitted model. The Model includes the pipeline and any pre-processing. Overloads on `get_output` allow you to retrieve the best run and fitted model for *any* logged metric or for a particular *iteration*.\n",
"\n",
"Set the parameter return_onnx_model=True to retrieve the best ONNX model, instead of the Python model."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"best_run, onnx_mdl = remote_run.get_output(return_onnx_model=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Save the best ONNX model"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.automl.core.onnx_convert import OnnxConverter\n",
"onnx_fl_path = \"./best_model.onnx\"\n",
"OnnxConverter.save_onnx_model(onnx_mdl, onnx_fl_path)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Predict with the ONNX model, using onnxruntime package"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import sys\n",
"import json\n",
"from azureml.automl.core.onnx_convert import OnnxConvertConstants\n",
"from azureml.train.automl import constants\n",
"\n",
"if sys.version_info < OnnxConvertConstants.OnnxIncompatiblePythonVersion:\n",
" python_version_compatible = True\n",
"else:\n",
" python_version_compatible = False\n",
"\n",
"try:\n",
" import onnxruntime\n",
" from azureml.automl.core.onnx_convert import OnnxInferenceHelper \n",
" onnxrt_present = True\n",
"except ImportError:\n",
" onnxrt_present = False\n",
"\n",
"def get_onnx_res(run):\n",
" res_path = 'onnx_resource.json'\n",
" run.download_file(name=constants.MODEL_RESOURCE_PATH_ONNX, output_file_path=res_path)\n",
" with open(res_path) as f:\n",
" return json.load(f)\n",
"\n",
"if onnxrt_present and python_version_compatible: \n",
" mdl_bytes = onnx_mdl.SerializeToString()\n",
" onnx_res = get_onnx_res(best_run)\n",
"\n",
" onnxrt_helper = OnnxInferenceHelper(mdl_bytes, onnx_res)\n",
" pred_onnx, pred_prob_onnx = onnxrt_helper.predict(X_test)\n",
"\n",
" print(pred_onnx)\n",
" print(pred_prob_onnx)\n",
"else:\n",
" if not python_version_compatible:\n",
" print('Please use Python version 3.6 or 3.7 to run the inference helper.') \n",
" if not onnxrt_present:\n",
" print('Please install the onnxruntime package to do the prediction with ONNX model.')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"authors": [
{
"name": "savitam"
}
],
"kernelspec": {
"display_name": "Python 3.6",
"language": "python",
"name": "python36"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.6"
}
},
"nbformat": 4,
"nbformat_minor": 2
}

View File

@@ -1,12 +0,0 @@
name: auto-ml-remote-amlcompute-with-onnx
dependencies:
- pip:
- azureml-sdk
- interpret
- azureml-defaults
- azureml-explain-model
- azureml-train-automl
- azureml-widgets
- matplotlib
- pandas_ml
- onnxruntime

View File

@@ -1,11 +1,8 @@
name: auto-ml-remote-amlcompute name: auto-ml-remote-amlcompute
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- interpret - azureml-train-automl
- azureml-defaults - azureml-widgets
- azureml-explain-model - matplotlib
- azureml-train-automl - pandas_ml
- azureml-widgets
- matplotlib
- pandas_ml

View File

@@ -1,242 +1,247 @@
{ {
"cells": [ "metadata": {
{ "kernelspec": {
"cell_type": "markdown", "display_name": "Python 3.6",
"metadata": {}, "name": "python36",
"source": [ "language": "python"
"Copyright (c) Microsoft Corporation. All rights reserved.\n", },
"\n", "authors": [
"Licensed under the MIT License." {
] "name": "savitam"
}, }
{ ],
"cell_type": "markdown", "language_info": {
"metadata": {}, "mimetype": "text/x-python",
"source": [ "codemirror_mode": {
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/sample-weight/auto-ml-sample-weight.png)" "name": "ipython",
] "version": 3
}, },
{ "pygments_lexer": "ipython3",
"cell_type": "markdown", "name": "python",
"metadata": {}, "file_extension": ".py",
"source": [ "nbconvert_exporter": "python",
"# Automated Machine Learning\n", "version": "3.6.5"
"_**Sample Weight**_\n", }
"\n", },
"## Contents\n", "nbformat": 4,
"1. [Introduction](#Introduction)\n", "cells": [
"1. [Setup](#Setup)\n", {
"1. [Train](#Train)\n", "metadata": {},
"1. [Test](#Test)\n" "source": [
] "Copyright (c) Microsoft Corporation. All rights reserved.\n",
}, "\n",
{ "Licensed under the MIT License."
"cell_type": "markdown", ],
"metadata": {}, "cell_type": "markdown"
"source": [ },
"## Introduction\n", {
"In this example we use the scikit-learn's [digit dataset](http://scikit-learn.org/stable/datasets/index.html#optical-recognition-of-handwritten-digits-dataset) to showcase how you can use sample weight with AutoML. Sample weight is used where some sample values are more important than others.\n", "metadata": {},
"\n", "source": [
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n", "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/sample-weight/auto-ml-sample-weight.png)"
"\n", ],
"In this notebook you will learn how to configure AutoML to use `sample_weight` and you will see the difference sample weight makes to the test results." "cell_type": "markdown"
] },
}, {
{ "metadata": {},
"cell_type": "markdown", "source": [
"metadata": {}, "# Automated Machine Learning\n",
"source": [ "_**Sample Weight**_\n",
"## Setup\n", "\n",
"\n", "## Contents\n",
"As part of the setup you have already created an Azure ML `Workspace` object. For AutoML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments." "1. [Introduction](#Introduction)\n",
] "1. [Setup](#Setup)\n",
}, "1. [Train](#Train)\n",
{ "1. [Test](#Test)\n"
"cell_type": "code", ],
"execution_count": null, "cell_type": "markdown"
"metadata": {}, },
"outputs": [], {
"source": [ "metadata": {},
"import logging\n", "source": [
"\n", "## Introduction\n",
"from matplotlib import pyplot as plt\n", "In this example we use the scikit-learn's [digit dataset](http://scikit-learn.org/stable/datasets/index.html#optical-recognition-of-handwritten-digits-dataset) to showcase how you can use sample weight with AutoML. Sample weight is used where some sample values are more important than others.\n",
"import numpy as np\n", "\n",
"import pandas as pd\n", "Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
"from sklearn import datasets\n", "\n",
"\n", "In this notebook you will learn how to configure AutoML to use `sample_weight` and you will see the difference sample weight makes to the test results."
"import azureml.core\n", ],
"from azureml.core.experiment import Experiment\n", "cell_type": "markdown"
"from azureml.core.workspace import Workspace\n", },
"from azureml.train.automl import AutoMLConfig" {
] "metadata": {},
}, "source": [
{ "## Setup\n",
"cell_type": "code", "\n",
"execution_count": null, "As part of the setup you have already created an Azure ML `Workspace` object. For AutoML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments."
"metadata": {}, ],
"outputs": [], "cell_type": "markdown"
"source": [ },
"ws = Workspace.from_config()\n", {
"\n", "metadata": {},
"# Choose names for the regular and the sample weight experiments.\n", "outputs": [],
"experiment_name = 'non_sample_weight_experiment'\n", "execution_count": null,
"sample_weight_experiment_name = 'sample_weight_experiment'\n", "source": [
"\n", "import logging\n",
"experiment = Experiment(ws, experiment_name)\n", "\n",
"sample_weight_experiment=Experiment(ws, sample_weight_experiment_name)\n", "from matplotlib import pyplot as plt\n",
"\n", "import numpy as np\n",
"output = {}\n", "import pandas as pd\n",
"output['SDK version'] = azureml.core.VERSION\n", "from sklearn import datasets\n",
"output['Subscription ID'] = ws.subscription_id\n", "\n",
"output['Workspace Name'] = ws.name\n", "import azureml.core\n",
"output['Resource Group'] = ws.resource_group\n", "from azureml.core.experiment import Experiment\n",
"output['Location'] = ws.location\n", "from azureml.core.workspace import Workspace\n",
"output['Experiment Name'] = experiment.name\n", "from azureml.train.automl import AutoMLConfig"
"pd.set_option('display.max_colwidth', -1)\n", ],
"outputDf = pd.DataFrame(data = output, index = [''])\n", "cell_type": "code"
"outputDf.T" },
] {
}, "metadata": {},
{ "outputs": [],
"cell_type": "markdown", "execution_count": null,
"metadata": {}, "source": [
"source": [ "ws = Workspace.from_config()\n",
"## Train\n", "\n",
"\n", "# Choose names for the regular and the sample weight experiments.\n",
"Instantiate two `AutoMLConfig` objects. One will be used with `sample_weight` and one without." "experiment_name = 'non_sample_weight_experiment'\n",
] "sample_weight_experiment_name = 'sample_weight_experiment'\n",
}, "\n",
{ "project_folder = './sample_projects/sample_weight'\n",
"cell_type": "code", "\n",
"execution_count": null, "experiment = Experiment(ws, experiment_name)\n",
"metadata": {}, "sample_weight_experiment=Experiment(ws, sample_weight_experiment_name)\n",
"outputs": [], "\n",
"source": [ "output = {}\n",
"digits = datasets.load_digits()\n", "output['SDK version'] = azureml.core.VERSION\n",
"X_train = digits.data[100:,:]\n", "output['Subscription ID'] = ws.subscription_id\n",
"y_train = digits.target[100:]\n", "output['Workspace Name'] = ws.name\n",
"\n", "output['Resource Group'] = ws.resource_group\n",
"# The example makes the sample weight 0.9 for the digit 4 and 0.1 for all other digits.\n", "output['Location'] = ws.location\n",
"# This makes the model more likely to classify as 4 if the image it not clear.\n", "output['Project Directory'] = project_folder\n",
"sample_weight = np.array([(0.9 if x == 4 else 0.01) for x in y_train])\n", "output['Experiment Name'] = experiment.name\n",
"\n", "pd.set_option('display.max_colwidth', -1)\n",
"automl_classifier = AutoMLConfig(task = 'classification',\n", "outputDf = pd.DataFrame(data = output, index = [''])\n",
" debug_log = 'automl_errors.log',\n", "outputDf.T"
" primary_metric = 'AUC_weighted',\n", ],
" iteration_timeout_minutes = 60,\n", "cell_type": "code"
" iterations = 10,\n", },
" n_cross_validations = 2,\n", {
" verbosity = logging.INFO,\n", "metadata": {},
" X = X_train, \n", "source": [
" y = y_train)\n", "## Train\n",
"\n", "\n",
"automl_sample_weight = AutoMLConfig(task = 'classification',\n", "Instantiate two `AutoMLConfig` objects. One will be used with `sample_weight` and one without."
" debug_log = 'automl_errors.log',\n", ],
" primary_metric = 'AUC_weighted',\n", "cell_type": "markdown"
" iteration_timeout_minutes = 60,\n", },
" iterations = 10,\n", {
" n_cross_validations = 2,\n", "metadata": {},
" verbosity = logging.INFO,\n", "outputs": [],
" X = X_train, \n", "execution_count": null,
" y = y_train,\n", "source": [
" sample_weight = sample_weight)" "digits = datasets.load_digits()\n",
] "X_train = digits.data[100:,:]\n",
}, "y_train = digits.target[100:]\n",
{ "\n",
"cell_type": "markdown", "# The example makes the sample weight 0.9 for the digit 4 and 0.1 for all other digits.\n",
"metadata": {}, "# This makes the model more likely to classify as 4 if the image it not clear.\n",
"source": [ "sample_weight = np.array([(0.9 if x == 4 else 0.01) for x in y_train])\n",
"Call the `submit` method on the experiment objects and pass the run configuration. Execution of local runs is synchronous. Depending on the data and the number of iterations this can run for a while.\n", "\n",
"In this example, we specify `show_output = True` to print currently running iterations to the console." "automl_classifier = AutoMLConfig(task = 'classification',\n",
] " debug_log = 'automl_errors.log',\n",
}, " primary_metric = 'AUC_weighted',\n",
{ " iteration_timeout_minutes = 60,\n",
"cell_type": "code", " iterations = 10,\n",
"execution_count": null, " n_cross_validations = 2,\n",
"metadata": {}, " verbosity = logging.INFO,\n",
"outputs": [], " X = X_train, \n",
"source": [ " y = y_train,\n",
"local_run = experiment.submit(automl_classifier, show_output = True)\n", " path = project_folder)\n",
"sample_weight_run = sample_weight_experiment.submit(automl_sample_weight, show_output = True)\n", "\n",
"\n", "automl_sample_weight = AutoMLConfig(task = 'classification',\n",
"best_run, fitted_model = local_run.get_output()\n", " debug_log = 'automl_errors.log',\n",
"best_run_sample_weight, fitted_model_sample_weight = sample_weight_run.get_output()" " primary_metric = 'AUC_weighted',\n",
] " iteration_timeout_minutes = 60,\n",
}, " iterations = 10,\n",
{ " n_cross_validations = 2,\n",
"cell_type": "markdown", " verbosity = logging.INFO,\n",
"metadata": {}, " X = X_train, \n",
"source": [ " y = y_train,\n",
"## Test\n", " sample_weight = sample_weight,\n",
"\n", " path = project_folder)"
"#### Load Test Data" ],
] "cell_type": "code"
}, },
{ {
"cell_type": "code", "metadata": {},
"execution_count": null, "source": [
"metadata": {}, "Call the `submit` method on the experiment objects and pass the run configuration. Execution of local runs is synchronous. Depending on the data and the number of iterations this can run for a while.\n",
"outputs": [], "In this example, we specify `show_output = True` to print currently running iterations to the console."
"source": [ ],
"digits = datasets.load_digits()\n", "cell_type": "markdown"
"X_test = digits.data[:100, :]\n", },
"y_test = digits.target[:100]\n", {
"images = digits.images[:100]" "metadata": {},
] "outputs": [],
}, "execution_count": null,
{ "source": [
"cell_type": "markdown", "local_run = experiment.submit(automl_classifier, show_output = True)\n",
"metadata": {}, "sample_weight_run = sample_weight_experiment.submit(automl_sample_weight, show_output = True)\n",
"source": [ "\n",
"#### Compare the Models\n", "best_run, fitted_model = local_run.get_output()\n",
"The prediction from the sample weight model is more likely to correctly predict 4's. However, it is also more likely to predict 4 for some images that are not labelled as 4." "best_run_sample_weight, fitted_model_sample_weight = sample_weight_run.get_output()"
] ],
}, "cell_type": "code"
{ },
"cell_type": "code", {
"execution_count": null, "metadata": {},
"metadata": {}, "source": [
"outputs": [], "## Test\n",
"source": [ "\n",
"# Randomly select digits and test.\n", "#### Load Test Data"
"for index in range(0,len(y_test)):\n", ],
" predicted = fitted_model.predict(X_test[index:index + 1])[0]\n", "cell_type": "markdown"
" predicted_sample_weight = fitted_model_sample_weight.predict(X_test[index:index + 1])[0]\n", },
" label = y_test[index]\n", {
" if predicted == 4 or predicted_sample_weight == 4 or label == 4:\n", "metadata": {},
" title = \"Label value = %d Predicted value = %d Prediced with sample weight = %d\" % (label, predicted, predicted_sample_weight)\n", "outputs": [],
" fig = plt.figure(1, figsize=(3,3))\n", "execution_count": null,
" ax1 = fig.add_axes((0,0,.8,.8))\n", "source": [
" ax1.set_title(title)\n", "digits = datasets.load_digits()\n",
" plt.imshow(images[index], cmap = plt.cm.gray_r, interpolation = 'nearest')\n", "X_test = digits.data[:100, :]\n",
" plt.show()" "y_test = digits.target[:100]\n",
] "images = digits.images[:100]"
} ],
], "cell_type": "code"
"metadata": { },
"authors": [ {
{ "metadata": {},
"name": "savitam" "source": [
} "#### Compare the Models\n",
], "The prediction from the sample weight model is more likely to correctly predict 4's. However, it is also more likely to predict 4 for some images that are not labelled as 4."
"kernelspec": { ],
"display_name": "Python 3.6", "cell_type": "markdown"
"language": "python", },
"name": "python36" {
}, "metadata": {},
"language_info": { "outputs": [],
"codemirror_mode": { "execution_count": null,
"name": "ipython", "source": [
"version": 3 "# Randomly select digits and test.\n",
}, "for index in range(0,len(y_test)):\n",
"file_extension": ".py", " predicted = fitted_model.predict(X_test[index:index + 1])[0]\n",
"mimetype": "text/x-python", " predicted_sample_weight = fitted_model_sample_weight.predict(X_test[index:index + 1])[0]\n",
"name": "python", " label = y_test[index]\n",
"nbconvert_exporter": "python", " if predicted == 4 or predicted_sample_weight == 4 or label == 4:\n",
"pygments_lexer": "ipython3", " title = \"Label value = %d Predicted value = %d Prediced with sample weight = %d\" % (label, predicted, predicted_sample_weight)\n",
"version": "3.6.5" " fig = plt.figure(1, figsize=(3,3))\n",
} " ax1 = fig.add_axes((0,0,.8,.8))\n",
}, " ax1.set_title(title)\n",
"nbformat": 4, " plt.imshow(images[index], cmap = plt.cm.gray_r, interpolation = 'nearest')\n",
"nbformat_minor": 2 " plt.show()"
],
"cell_type": "code"
}
],
"nbformat_minor": 2
} }

View File

@@ -1,8 +1,8 @@
name: auto-ml-sample-weight name: auto-ml-sample-weight
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- azureml-train-automl - azureml-train-automl
- azureml-widgets - azureml-widgets
- matplotlib - matplotlib
- pandas_ml - pandas_ml

View File

@@ -1,382 +1,387 @@
{ {
"cells": [ "metadata": {
{ "kernelspec": {
"cell_type": "markdown", "display_name": "Python 3.6",
"metadata": {}, "name": "python36",
"source": [ "language": "python"
"Copyright (c) Microsoft Corporation. All rights reserved.\n", },
"\n", "authors": [
"Licensed under the MIT License." {
] "name": "savitam"
}, }
{ ],
"cell_type": "markdown", "language_info": {
"metadata": {}, "mimetype": "text/x-python",
"source": [ "codemirror_mode": {
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/sparse-data-train-test-split/auto-ml-sparse-data-train-test-split.png)" "name": "ipython",
] "version": 3
}, },
{ "pygments_lexer": "ipython3",
"cell_type": "markdown", "name": "python",
"metadata": {}, "file_extension": ".py",
"source": [ "nbconvert_exporter": "python",
"# Automated Machine Learning\n", "version": "3.6.6"
"_**Train Test Split and Handling Sparse Data**_\n", }
"\n", },
"## Contents\n", "nbformat": 4,
"1. [Introduction](#Introduction)\n", "cells": [
"1. [Setup](#Setup)\n", {
"1. [Data](#Data)\n", "metadata": {},
"1. [Train](#Train)\n", "source": [
"1. [Results](#Results)\n", "Copyright (c) Microsoft Corporation. All rights reserved.\n",
"1. [Test](#Test)\n" "\n",
] "Licensed under the MIT License."
}, ],
{ "cell_type": "markdown"
"cell_type": "markdown", },
"metadata": {}, {
"source": [ "metadata": {},
"## Introduction\n", "source": [
"In this example we use the scikit-learn's [20newsgroup](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.fetch_20newsgroups.html) to showcase how you can use AutoML for handling sparse data and how to specify custom cross validations splits.\n", "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/sparse-data-train-test-split/auto-ml-sparse-data-train-test-split.png)"
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n", ],
"\n", "cell_type": "markdown"
"In this notebook you will learn how to:\n", },
"1. Create an `Experiment` in an existing `Workspace`.\n", {
"2. Configure AutoML using `AutoMLConfig`.\n", "metadata": {},
"4. Train the model.\n", "source": [
"5. Explore the results.\n", "# Automated Machine Learning\n",
"6. Test the best fitted model.\n", "_**Train Test Split and Handling Sparse Data**_\n",
"\n", "\n",
"In addition this notebook showcases the following features\n", "## Contents\n",
"- Explicit train test splits \n", "1. [Introduction](#Introduction)\n",
"- Handling **sparse data** in the input" "1. [Setup](#Setup)\n",
] "1. [Data](#Data)\n",
}, "1. [Train](#Train)\n",
{ "1. [Results](#Results)\n",
"cell_type": "markdown", "1. [Test](#Test)\n"
"metadata": {}, ],
"source": [ "cell_type": "markdown"
"## Setup\n", },
"\n", {
"As part of the setup you have already created an Azure ML `Workspace` object. For AutoML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments." "metadata": {},
] "source": [
}, "## Introduction\n",
{ "In this example we use the scikit-learn's [20newsgroup](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.fetch_20newsgroups.html) to showcase how you can use AutoML for handling sparse data and how to specify custom cross validations splits.\n",
"cell_type": "code", "Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
"execution_count": null, "\n",
"metadata": {}, "In this notebook you will learn how to:\n",
"outputs": [], "1. Create an `Experiment` in an existing `Workspace`.\n",
"source": [ "2. Configure AutoML using `AutoMLConfig`.\n",
"import logging\n", "4. Train the model.\n",
"\n", "5. Explore the results.\n",
"import pandas as pd\n", "6. Test the best fitted model.\n",
"\n", "\n",
"import azureml.core\n", "In addition this notebook showcases the following features\n",
"from azureml.core.experiment import Experiment\n", "- Explicit train test splits \n",
"from azureml.core.workspace import Workspace\n", "- Handling **sparse data** in the input"
"from azureml.train.automl import AutoMLConfig" ],
] "cell_type": "markdown"
}, },
{ {
"cell_type": "code", "metadata": {},
"execution_count": null, "source": [
"metadata": {}, "## Setup\n",
"outputs": [], "\n",
"source": [ "As part of the setup you have already created an Azure ML `Workspace` object. For AutoML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments."
"ws = Workspace.from_config()\n", ],
"\n", "cell_type": "markdown"
"# choose a name for the experiment\n", },
"experiment_name = 'sparse-data-train-test-split'\n", {
"\n", "metadata": {},
"experiment = Experiment(ws, experiment_name)\n", "outputs": [],
"\n", "execution_count": null,
"output = {}\n", "source": [
"output['SDK version'] = azureml.core.VERSION\n", "import logging\n",
"output['Subscription ID'] = ws.subscription_id\n", "\n",
"output['Workspace'] = ws.name\n", "import pandas as pd\n",
"output['Resource Group'] = ws.resource_group\n", "\n",
"output['Location'] = ws.location\n", "import azureml.core\n",
"output['Experiment Name'] = experiment.name\n", "from azureml.core.experiment import Experiment\n",
"pd.set_option('display.max_colwidth', -1)\n", "from azureml.core.workspace import Workspace\n",
"outputDf = pd.DataFrame(data = output, index = [''])\n", "from azureml.train.automl import AutoMLConfig"
"outputDf.T" ],
] "cell_type": "code"
}, },
{ {
"cell_type": "markdown", "metadata": {},
"metadata": {}, "outputs": [],
"source": [ "execution_count": null,
"## Data" "source": [
] "ws = Workspace.from_config()\n",
}, "\n",
{ "# choose a name for the experiment\n",
"cell_type": "code", "experiment_name = 'sparse-data-train-test-split'\n",
"execution_count": null, "# project folder\n",
"metadata": {}, "project_folder = './sample_projects/sparse-data-train-test-split'\n",
"outputs": [], "\n",
"source": [ "experiment = Experiment(ws, experiment_name)\n",
"from sklearn.datasets import fetch_20newsgroups\n", "\n",
"from sklearn.feature_extraction.text import HashingVectorizer\n", "output = {}\n",
"from sklearn.model_selection import train_test_split\n", "output['SDK version'] = azureml.core.VERSION\n",
"\n", "output['Subscription ID'] = ws.subscription_id\n",
"remove = ('headers', 'footers', 'quotes')\n", "output['Workspace'] = ws.name\n",
"categories = [\n", "output['Resource Group'] = ws.resource_group\n",
" 'alt.atheism',\n", "output['Location'] = ws.location\n",
" 'talk.religion.misc',\n", "output['Project Directory'] = project_folder\n",
" 'comp.graphics',\n", "output['Experiment Name'] = experiment.name\n",
" 'sci.space',\n", "pd.set_option('display.max_colwidth', -1)\n",
"]\n", "outputDf = pd.DataFrame(data = output, index = [''])\n",
"data_train = fetch_20newsgroups(subset = 'train', categories = categories,\n", "outputDf.T"
" shuffle = True, random_state = 42,\n", ],
" remove = remove)\n", "cell_type": "code"
"\n", },
"X_train, X_valid, y_train, y_valid = train_test_split(data_train.data, data_train.target, test_size = 0.33, random_state = 42)\n", {
"\n", "metadata": {},
"\n", "source": [
"vectorizer = HashingVectorizer(stop_words = 'english', alternate_sign = False,\n", "## Data"
" n_features = 2**16)\n", ],
"X_train = vectorizer.transform(X_train)\n", "cell_type": "markdown"
"X_valid = vectorizer.transform(X_valid)\n", },
"\n", {
"summary_df = pd.DataFrame(index = ['No of Samples', 'No of Features'])\n", "metadata": {},
"summary_df['Train Set'] = [X_train.shape[0], X_train.shape[1]]\n", "outputs": [],
"summary_df['Validation Set'] = [X_valid.shape[0], X_valid.shape[1]]\n", "execution_count": null,
"summary_df" "source": [
] "from sklearn.datasets import fetch_20newsgroups\n",
}, "from sklearn.feature_extraction.text import HashingVectorizer\n",
{ "from sklearn.model_selection import train_test_split\n",
"cell_type": "markdown", "\n",
"metadata": {}, "remove = ('headers', 'footers', 'quotes')\n",
"source": [ "categories = [\n",
"## Train\n", " 'alt.atheism',\n",
"\n", " 'talk.religion.misc',\n",
"Instantiate an `AutoMLConfig` object to specify the settings and data used to run the experiment.\n", " 'comp.graphics',\n",
"\n", " 'sci.space',\n",
"|Property|Description|\n", "]\n",
"|-|-|\n", "data_train = fetch_20newsgroups(subset = 'train', categories = categories,\n",
"|**task**|classification or regression|\n", " shuffle = True, random_state = 42,\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", " remove = remove)\n",
"|**iteration_timeout_minutes**|Time limit in minutes for each iteration.|\n", "\n",
"|**iterations**|Number of iterations. In each iteration AutoML trains a specific pipeline with the data.|\n", "X_train, X_valid, y_train, y_valid = train_test_split(data_train.data, data_train.target, test_size = 0.33, random_state = 42)\n",
"|**preprocess**|Setting this to *True* enables AutoML to perform preprocessing on the input to handle *missing data*, and to perform some common *feature extraction*.<br>**Note:** If input data is sparse, you cannot use *True*.|\n", "\n",
"|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n", "\n",
"|**y**|(sparse) array-like, shape = [n_samples, ], Multi-class targets.|\n", "vectorizer = HashingVectorizer(stop_words = 'english', alternate_sign = False,\n",
"|**X_valid**|(sparse) array-like, shape = [n_samples, n_features] for the custom validation set.|\n", " n_features = 2**16)\n",
"|**y_valid**|(sparse) array-like, shape = [n_samples, ], Multi-class targets.|" "X_train = vectorizer.transform(X_train)\n",
] "X_valid = vectorizer.transform(X_valid)\n",
}, "\n",
{ "summary_df = pd.DataFrame(index = ['No of Samples', 'No of Features'])\n",
"cell_type": "code", "summary_df['Train Set'] = [X_train.shape[0], X_train.shape[1]]\n",
"execution_count": null, "summary_df['Validation Set'] = [X_valid.shape[0], X_valid.shape[1]]\n",
"metadata": {}, "summary_df"
"outputs": [], ],
"source": [ "cell_type": "code"
"automl_config = AutoMLConfig(task = 'classification',\n", },
" debug_log = 'automl_errors.log',\n", {
" primary_metric = 'AUC_weighted',\n", "metadata": {},
" iteration_timeout_minutes = 60,\n", "source": [
" iterations = 5,\n", "## Train\n",
" preprocess = False,\n", "\n",
" verbosity = logging.INFO,\n", "Instantiate an `AutoMLConfig` object to specify the settings and data used to run the experiment.\n",
" X = X_train, \n", "\n",
" y = y_train,\n", "|Property|Description|\n",
" X_valid = X_valid, \n", "|-|-|\n",
" y_valid = y_valid)" "|**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",
}, "|**iteration_timeout_minutes**|Time limit in minutes for each iteration.|\n",
{ "|**iterations**|Number of iterations. In each iteration AutoML trains a specific pipeline with the data.|\n",
"cell_type": "markdown", "|**preprocess**|Setting this to *True* enables AutoML to perform preprocessing on the input to handle *missing data*, and to perform some common *feature extraction*.<br>**Note:** If input data is sparse, you cannot use *True*.|\n",
"metadata": {}, "|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n",
"source": [ "|**y**|(sparse) array-like, shape = [n_samples, ], Multi-class targets.|\n",
"Call the `submit` method on the experiment object and pass the run configuration. Execution of local runs is synchronous. Depending on the data and the number of iterations this can run for a while.\n", "|**X_valid**|(sparse) array-like, shape = [n_samples, n_features] for the custom validation set.|\n",
"In this example, we specify `show_output = True` to print currently running iterations to the console." "|**y_valid**|(sparse) array-like, shape = [n_samples, ], Multi-class targets.|\n",
] "|**path**|Relative path to the project folder. AutoML stores configuration files for the experiment under this folder. You can specify a new empty folder.|"
}, ],
{ "cell_type": "markdown"
"cell_type": "code", },
"execution_count": null, {
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "execution_count": null,
"local_run = experiment.submit(automl_config, show_output=True)" "source": [
] "automl_config = AutoMLConfig(task = 'classification',\n",
}, " debug_log = 'automl_errors.log',\n",
{ " primary_metric = 'AUC_weighted',\n",
"cell_type": "code", " iteration_timeout_minutes = 60,\n",
"execution_count": null, " iterations = 5,\n",
"metadata": {}, " preprocess = False,\n",
"outputs": [], " verbosity = logging.INFO,\n",
"source": [ " X = X_train, \n",
"local_run" " y = y_train,\n",
] " X_valid = X_valid, \n",
}, " y_valid = y_valid, \n",
{ " path = project_folder)"
"cell_type": "markdown", ],
"metadata": {}, "cell_type": "code"
"source": [ },
"## Results" {
] "metadata": {},
}, "source": [
{ "Call the `submit` method on the experiment object and pass the run configuration. Execution of local runs is synchronous. Depending on the data and the number of iterations this can run for a while.\n",
"cell_type": "markdown", "In this example, we specify `show_output = True` to print currently running iterations to the console."
"metadata": {}, ],
"source": [ "cell_type": "markdown"
"#### Widget for Monitoring Runs\n", },
"\n", {
"The widget will first report a \"loading\" status while running the first iteration. After completing the first iteration, an auto-updating graph and table will be shown. The widget will refresh once per minute, so you should see the graph update as child runs complete.\n", "metadata": {},
"\n", "outputs": [],
"**Note:** The widget displays a link at the bottom. Use this link to open a web interface to explore the individual run details." "execution_count": null,
] "source": [
}, "local_run = experiment.submit(automl_config, show_output=True)"
{ ],
"cell_type": "code", "cell_type": "code"
"execution_count": null, },
"metadata": {}, {
"outputs": [], "metadata": {},
"source": [ "outputs": [],
"from azureml.widgets import RunDetails\n", "execution_count": null,
"RunDetails(local_run).show() " "source": [
] "local_run"
}, ],
{ "cell_type": "code"
"cell_type": "markdown", },
"metadata": {}, {
"source": [ "metadata": {},
"\n", "source": [
"#### Retrieve All Child Runs\n", "## Results"
"You can also use SDK methods to fetch all the child runs and see individual metrics that we log." ],
] "cell_type": "markdown"
}, },
{ {
"cell_type": "code", "metadata": {},
"execution_count": null, "source": [
"metadata": {}, "#### Widget for Monitoring Runs\n",
"outputs": [], "\n",
"source": [ "The widget will first report a \"loading\" status while running the first iteration. After completing the first iteration, an auto-updating graph and table will be shown. The widget will refresh once per minute, so you should see the graph update as child runs complete.\n",
"children = list(local_run.get_children())\n", "\n",
"metricslist = {}\n", "**Note:** The widget displays a link at the bottom. Use this link to open a web interface to explore the individual run details."
"for run in children:\n", ],
" properties = run.get_properties()\n", "cell_type": "markdown"
" metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)}\n", },
" metricslist[int(properties['iteration'])] = metrics\n", {
" \n", "metadata": {},
"rundata = pd.DataFrame(metricslist).sort_index(1)\n", "outputs": [],
"rundata" "execution_count": null,
] "source": [
}, "from azureml.widgets import RunDetails\n",
{ "RunDetails(local_run).show() "
"cell_type": "markdown", ],
"metadata": {}, "cell_type": "code"
"source": [ },
"### Retrieve the Best Model\n", {
"\n", "metadata": {},
"Below we select the best pipeline from our iterations. The `get_output` method returns the best run and the fitted model. The Model includes the pipeline and any pre-processing. Overloads on `get_output` allow you to retrieve the best run and fitted model for *any* logged metric or for a particular *iteration*." "source": [
] "\n",
}, "#### Retrieve All Child Runs\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, "cell_type": "markdown"
"metadata": {}, },
"outputs": [], {
"source": [ "metadata": {},
"best_run, fitted_model = local_run.get_output()" "outputs": [],
] "execution_count": null,
}, "source": [
{ "children = list(local_run.get_children())\n",
"cell_type": "markdown", "metricslist = {}\n",
"metadata": {}, "for run in children:\n",
"source": [ " properties = run.get_properties()\n",
"#### Best Model Based on Any Other Metric\n", " metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)}\n",
"Show the run and the model which has the smallest `accuracy` value:" " metricslist[int(properties['iteration'])] = metrics\n",
] " \n",
}, "rundata = pd.DataFrame(metricslist).sort_index(1)\n",
{ "rundata"
"cell_type": "code", ],
"execution_count": null, "cell_type": "code"
"metadata": {}, },
"outputs": [], {
"source": [ "metadata": {},
"# lookup_metric = \"accuracy\"\n", "source": [
"# best_run, fitted_model = local_run.get_output(metric = lookup_metric)" "### Retrieve the Best Model\n",
] "\n",
}, "Below we select the best pipeline from our iterations. The `get_output` method returns the best run and the fitted model. The Model includes the pipeline and any pre-processing. Overloads on `get_output` allow you to retrieve the best run and fitted model for *any* logged metric or for a particular *iteration*."
{ ],
"cell_type": "markdown", "cell_type": "markdown"
"metadata": {}, },
"source": [ {
"#### Model from a Specific Iteration\n", "metadata": {},
"Show the run and the model from the third iteration:" "outputs": [],
] "execution_count": null,
}, "source": [
{ "best_run, fitted_model = local_run.get_output()"
"cell_type": "code", ],
"execution_count": null, "cell_type": "code"
"metadata": {}, },
"outputs": [], {
"source": [ "metadata": {},
"# iteration = 3\n", "source": [
"# best_run, fitted_model = local_run.get_output(iteration = iteration)" "#### Best Model Based on Any Other Metric\n",
] "Show the run and the model which has the smallest `accuracy` value:"
}, ],
{ "cell_type": "markdown"
"cell_type": "markdown", },
"metadata": {}, {
"source": [ "metadata": {},
"## Test" "outputs": [],
] "execution_count": null,
}, "source": [
{ "# lookup_metric = \"accuracy\"\n",
"cell_type": "code", "# best_run, fitted_model = local_run.get_output(metric = lookup_metric)"
"execution_count": null, ],
"metadata": {}, "cell_type": "code"
"outputs": [], },
"source": [ {
"# Load test data.\n", "metadata": {},
"from pandas_ml import ConfusionMatrix\n", "source": [
"\n", "#### Model from a Specific Iteration\n",
"data_test = fetch_20newsgroups(subset = 'test', categories = categories,\n", "Show the run and the model from the third iteration:"
" shuffle = True, random_state = 42,\n", ],
" remove = remove)\n", "cell_type": "markdown"
"\n", },
"X_test = vectorizer.transform(data_test.data)\n", {
"y_test = data_test.target\n", "metadata": {},
"\n", "outputs": [],
"# Test our best pipeline.\n", "execution_count": null,
"\n", "source": [
"y_pred = fitted_model.predict(X_test)\n", "# iteration = 3\n",
"y_pred_strings = [data_test.target_names[i] for i in y_pred]\n", "# best_run, fitted_model = local_run.get_output(iteration = iteration)"
"y_test_strings = [data_test.target_names[i] for i in y_test]\n", ],
"\n", "cell_type": "code"
"cm = ConfusionMatrix(y_test_strings, y_pred_strings)\n", },
"print(cm)\n", {
"cm.plot()" "metadata": {},
] "source": [
} "## Test"
], ],
"metadata": { "cell_type": "markdown"
"authors": [ },
{ {
"name": "savitam" "metadata": {},
} "outputs": [],
], "execution_count": null,
"kernelspec": { "source": [
"display_name": "Python 3.6", "# Load test data.\n",
"language": "python", "from pandas_ml import ConfusionMatrix\n",
"name": "python36" "\n",
}, "data_test = fetch_20newsgroups(subset = 'test', categories = categories,\n",
"language_info": { " shuffle = True, random_state = 42,\n",
"codemirror_mode": { " remove = remove)\n",
"name": "ipython", "\n",
"version": 3 "X_test = vectorizer.transform(data_test.data)\n",
}, "y_test = data_test.target\n",
"file_extension": ".py", "\n",
"mimetype": "text/x-python", "# Test our best pipeline.\n",
"name": "python", "\n",
"nbconvert_exporter": "python", "y_pred = fitted_model.predict(X_test)\n",
"pygments_lexer": "ipython3", "y_pred_strings = [data_test.target_names[i] for i in y_pred]\n",
"version": "3.6.6" "y_test_strings = [data_test.target_names[i] for i in y_test]\n",
} "\n",
}, "cm = ConfusionMatrix(y_test_strings, y_pred_strings)\n",
"nbformat": 4, "print(cm)\n",
"nbformat_minor": 2 "cm.plot()"
],
"cell_type": "code"
}
],
"nbformat_minor": 2
} }

View File

@@ -1,8 +1,8 @@
name: auto-ml-sparse-data-train-test-split name: auto-ml-sparse-data-train-test-split
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- azureml-train-automl - azureml-train-automl
- azureml-widgets - azureml-widgets
- matplotlib - matplotlib
- pandas_ml - pandas_ml

View File

@@ -1,113 +1,113 @@
# Table of Contents # Table of Contents
1. [Introduction](#introduction) 1. [Introduction](#introduction)
1. [Setup using Azure Data Studio](#azuredatastudiosetup) 1. [Setup using Azure Data Studio](#azuredatastudiosetup)
1. [Energy demand example using Azure Data Studio](#azuredatastudioenergydemand) 1. [Energy demand example using Azure Data Studio](#azuredatastudioenergydemand)
1. [Set using SQL Server Management Studio for SQL Server 2017 on Windows](#ssms2017) 1. [Set using SQL Server Management Studio for SQL Server 2017 on Windows](#ssms2017)
1. [Set using SQL Server Management Studio for SQL Server 2019 on Linux](#ssms2019) 1. [Set using SQL Server Management Studio for SQL Server 2019 on Linux](#ssms2019)
1. [Energy demand example using SQL Server Management Studio](#ssmsenergydemand) 1. [Energy demand example using SQL Server Management Studio](#ssmsenergydemand)
<a name="introduction"></a> <a name="introduction"></a>
# Introduction # Introduction
SQL Server 2017 or 2019 can call Azure ML automated machine learning to create models trained on data from SQL Server. SQL Server 2017 or 2019 can call Azure ML automated machine learning to create models trained on data from SQL Server.
This uses the sp_execute_external_script stored procedure, which can call Python scripts. This uses the sp_execute_external_script stored procedure, which can call Python scripts.
SQL Server 2017 and SQL Server 2019 can both run on Windows or Linux. SQL Server 2017 and SQL Server 2019 can both run on Windows or Linux.
However, this integration is not available for SQL Server 2017 on Linux. However, this integration is not available for SQL Server 2017 on Linux.
This folder shows how to setup the integration and has a sample that uses the integration to train and predict based on an energy demand dataset. This folder shows how to setup the integration and has a sample that uses the integration to train and predict based on an energy demand dataset.
This integration is part of SQL Server and so can be used from any SQL client. This integration is part of SQL Server and so can be used from any SQL client.
These instructions show using it from Azure Data Studio or SQL Server Managment Studio. These instructions show using it from Azure Data Studio or SQL Server Managment Studio.
<a name="azuredatastudiosetup"></a> <a name="azuredatastudiosetup"></a>
## Setup using Azure Data Studio ## Setup using Azure Data Studio
These step show setting up the integration using Azure Data Studio. These step show setting up the integration using Azure Data Studio.
1. If you don't already have SQL Server, you can install it from [https://www.microsoft.com/en-us/sql-server/sql-server-downloads](https://www.microsoft.com/en-us/sql-server/sql-server-downloads) 1. If you don't already have SQL Server, you can install it from [https://www.microsoft.com/en-us/sql-server/sql-server-downloads](https://www.microsoft.com/en-us/sql-server/sql-server-downloads)
1. Install Azure Data Studio from [https://docs.microsoft.com/en-us/sql/azure-data-studio/download?view=sql-server-2017](https://docs.microsoft.com/en-us/sql/azure-data-studio/download?view=sql-server-2017) 1. Install Azure Data Studio from [https://docs.microsoft.com/en-us/sql/azure-data-studio/download?view=sql-server-2017](https://docs.microsoft.com/en-us/sql/azure-data-studio/download?view=sql-server-2017)
1. Start Azure Data Studio and connect to SQL Server. [https://docs.microsoft.com/en-us/sql/azure-data-studio/sql-notebooks?view=sql-server-2017](https://docs.microsoft.com/en-us/sql/azure-data-studio/sql-notebooks?view=sql-server-2017) 1. Start Azure Data Studio and connect to SQL Server. [https://docs.microsoft.com/en-us/sql/azure-data-studio/sql-notebooks?view=sql-server-2017](https://docs.microsoft.com/en-us/sql/azure-data-studio/sql-notebooks?view=sql-server-2017)
1. Create a database named "automl". 1. Create a database named "automl".
1. Open the notebook how-to-use-azureml\automated-machine-learning\sql-server\setup\auto-ml-sql-setup.ipynb and follow the instructions in it. 1. Open the notebook how-to-use-azureml\automated-machine-learning\sql-server\setup\auto-ml-sql-setup.ipynb and follow the instructions in it.
<a name="azuredatastudioenergydemand"></a> <a name="azuredatastudioenergydemand"></a>
## Energy demand example using Azure Data Studio ## Energy demand example using Azure Data Studio
Once you have completed the setup, you can try the energy demand sample in the notebook energy-demand\auto-ml-sql-energy-demand.ipynb. Once you have completed the setup, you can try the energy demand sample in the notebook energy-demand\auto-ml-sql-energy-demand.ipynb.
This has cells to train a model, predict based on the model and show metrics for each pipeline run in training the model. This has cells to train a model, predict based on the model and show metrics for each pipeline run in training the model.
<a name="ssms2017"></a> <a name="ssms2017"></a>
## Setup using SQL Server Management Studio for SQL Server 2017 on Windows ## Setup using SQL Server Management Studio for SQL Server 2017 on Windows
These instruction setup the integration for SQL Server 2017 on Windows. These instruction setup the integration for SQL Server 2017 on Windows.
1. If you don't already have SQL Server, you can install it from [https://www.microsoft.com/en-us/sql-server/sql-server-downloads](https://www.microsoft.com/en-us/sql-server/sql-server-downloads) 1. If you don't already have SQL Server, you can install it from [https://www.microsoft.com/en-us/sql-server/sql-server-downloads](https://www.microsoft.com/en-us/sql-server/sql-server-downloads)
2. Enable external scripts with the following commands: 2. Enable external scripts with the following commands:
```sh ```sh
sp_configure 'external scripts enabled',1 sp_configure 'external scripts enabled',1
reconfigure with override reconfigure with override
``` ```
3. Stop SQL Server. 3. Stop SQL Server.
4. Install the automated machine learning libraries using the following commands from Administrator command prompt (If you are using a non-default SQL Server instance name, replace MSSQLSERVER in the second command with the instance name) 4. Install the automated machine learning libraries using the following commands from Administrator command prompt (If you are using a non-default SQL Server instance name, replace MSSQLSERVER in the second command with the instance name)
```sh ```sh
cd "C:\Program Files\Microsoft SQL Server" cd "C:\Program Files\Microsoft SQL Server"
cd "MSSQL14.MSSQLSERVER\PYTHON_SERVICES" cd "MSSQL14.MSSQLSERVER\PYTHON_SERVICES"
python.exe -m pip install azureml-sdk[automl] python.exe -m pip install azureml-sdk[automl]
python.exe -m pip install --upgrade numpy python.exe -m pip install --upgrade numpy
python.exe -m pip install --upgrade sklearn python.exe -m pip install --upgrade sklearn
``` ```
5. Start SQL Server and the service "SQL Server Launchpad service". 5. Start SQL Server and the service "SQL Server Launchpad service".
6. In Windows Firewall, click on advanced settings and in Outbound Rules, disable "Block network access for R local user accounts in SQL Server instance xxxx". 6. In Windows Firewall, click on advanced settings and in Outbound Rules, disable "Block network access for R local user accounts in SQL Server instance xxxx".
7. Execute the files in the setup folder in SQL Server Management Studio: aml_model.sql, aml_connection.sql, AutoMLGetMetrics.sql, AutoMLPredict.sql and AutoMLTrain.sql 7. Execute the files in the setup folder in SQL Server Management Studio: aml_model.sql, aml_connection.sql, AutoMLGetMetrics.sql, AutoMLPredict.sql and AutoMLTrain.sql
8. Create an Azure Machine Learning Workspace. You can use the instructions at: [https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-workspace ](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-workspace) 8. Create an Azure Machine Learning Workspace. You can use the instructions at: [https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-workspace ](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-workspace)
9. Create a config.json file file using the subscription id, resource group name and workspace name that you used to create the workspace. The file is described at: [https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-configure-environment#workspace](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-configure-environment#workspace) 9. Create a config.json file file using the subscription id, resource group name and workspace name that you used to create the workspace. The file is described at: [https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-configure-environment#workspace](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-configure-environment#workspace)
10. Create an Azure service principal. You can do this with the commands: 10. Create an Azure service principal. You can do this with the commands:
```sh ```sh
az login az login
az account set --subscription subscriptionid az account set --subscription subscriptionid
az ad sp create-for-rbac --name principlename --password password az ad sp create-for-rbac --name principlename --password password
``` ```
11. Insert the values \<tenant\>, \<AppId\> and \<password\> returned by create-for-rbac above into the aml_connection table. Set \<path\> as the absolute path to your config.json file. Set the name to “Default”. 11. Insert the values \<tenant\>, \<AppId\> and \<password\> returned by create-for-rbac above into the aml_connection table. Set \<path\> as the absolute path to your config.json file. Set the name to “Default”.
<a name="ssms2019"></a> <a name="ssms2019"></a>
## Setup using SQL Server Management Studio for SQL Server 2019 on Linux ## Setup using SQL Server Management Studio for SQL Server 2019 on Linux
1. Install SQL Server 2019 from: [https://www.microsoft.com/en-us/sql-server/sql-server-downloads](https://www.microsoft.com/en-us/sql-server/sql-server-downloads) 1. Install SQL Server 2019 from: [https://www.microsoft.com/en-us/sql-server/sql-server-downloads](https://www.microsoft.com/en-us/sql-server/sql-server-downloads)
2. Install machine learning support from: [https://docs.microsoft.com/en-us/sql/linux/sql-server-linux-setup-machine-learning?view=sqlallproducts-allversions#ubuntu](https://docs.microsoft.com/en-us/sql/linux/sql-server-linux-setup-machine-learning?view=sqlallproducts-allversions#ubuntu) 2. Install machine learning support from: [https://docs.microsoft.com/en-us/sql/linux/sql-server-linux-setup-machine-learning?view=sqlallproducts-allversions#ubuntu](https://docs.microsoft.com/en-us/sql/linux/sql-server-linux-setup-machine-learning?view=sqlallproducts-allversions#ubuntu)
3. Then install SQL Server management Studio from [https://docs.microsoft.com/en-us/sql/ssms/download-sql-server-management-studio-ssms?view=sql-server-2017](https://docs.microsoft.com/en-us/sql/ssms/download-sql-server-management-studio-ssms?view=sql-server-2017) 3. Then install SQL Server management Studio from [https://docs.microsoft.com/en-us/sql/ssms/download-sql-server-management-studio-ssms?view=sql-server-2017](https://docs.microsoft.com/en-us/sql/ssms/download-sql-server-management-studio-ssms?view=sql-server-2017)
4. Enable external scripts with the following commands: 4. Enable external scripts with the following commands:
```sh ```sh
sp_configure 'external scripts enabled',1 sp_configure 'external scripts enabled',1
reconfigure with override reconfigure with override
``` ```
5. Stop SQL Server. 5. Stop SQL Server.
6. Install the automated machine learning libraries using the following commands from Administrator command (If you are using a non-default SQL Server instance name, replace MSSQLSERVER in the second command with the instance name): 6. Install the automated machine learning libraries using the following commands from Administrator command (If you are using a non-default SQL Server instance name, replace MSSQLSERVER in the second command with the instance name):
```sh ```sh
sudo /opt/mssql/mlservices/bin/python/python -m pip install azureml-sdk[automl] sudo /opt/mssql/mlservices/bin/python/python -m pip install azureml-sdk[automl]
sudo /opt/mssql/mlservices/bin/python/python -m pip install --upgrade numpy sudo /opt/mssql/mlservices/bin/python/python -m pip install --upgrade numpy
sudo /opt/mssql/mlservices/bin/python/python -m pip install --upgrade sklearn sudo /opt/mssql/mlservices/bin/python/python -m pip install --upgrade sklearn
``` ```
7. Start SQL Server. 7. Start SQL Server.
8. Execute the files aml_model.sql, aml_connection.sql, AutoMLGetMetrics.sql, AutoMLPredict.sql, AutoMLForecast.sql and AutoMLTrain.sql in SQL Server Management Studio. 8. Execute the files aml_model.sql, aml_connection.sql, AutoMLGetMetrics.sql, AutoMLPredict.sql and AutoMLTrain.sql in SQL Server Management Studio.
9. Create an Azure Machine Learning Workspace. You can use the instructions at: [https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-workspace](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-workspace) 9. Create an Azure Machine Learning Workspace. You can use the instructions at: [https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-workspace](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-workspace)
10. Create a config.json file file using the subscription id, resource group name and workspace name that you use to create the workspace. The file is described at: [https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-configure-environment#workspace](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-configure-environment#workspace) 10. Create a config.json file file using the subscription id, resource group name and workspace name that you use to create the workspace. The file is described at: [https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-configure-environment#workspace](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-configure-environment#workspace)
11. Create an Azure service principal. You can do this with the commands: 11. Create an Azure service principal. You can do this with the commands:
```sh ```sh
az login az login
az account set --subscription subscriptionid az account set --subscription subscriptionid
az ad sp create-for-rbac --name principlename --password password az ad sp create-for-rbac --name principlename --password password
``` ```
12. Insert the values \<tenant\>, \<AppId\> and \<password\> returned by create-for-rbac above into the aml_connection table. Set \<path\> as the absolute path to your config.json file. Set the name to “Default”. 12. Insert the values \<tenant\>, \<AppId\> and \<password\> returned by create-for-rbac above into the aml_connection table. Set \<path\> as the absolute path to your config.json file. Set the name to “Default”.
<a name="ssmsenergydemand"></a> <a name="ssmsenergydemand"></a>
## Energy demand example using SQL Server Management Studio ## Energy demand example using SQL Server Management Studio
Once you have completed the setup, you can try the energy demand sample queries. Once you have completed the setup, you can try the energy demand sample queries.
First you need to load the sample data in the database. First you need to load the sample data in the database.
1. In SQL Server Management Studio, you can right-click the database, select Tasks, then Import Flat file. 1. In SQL Server Management Studio, you can right-click the database, select Tasks, then Import Flat file.
1. Select the file MachineLearningNotebooks\notebooks\how-to-use-azureml\automated-machine-learning\forecasting-energy-demand\nyc_energy.csv. 1. Select the file MachineLearningNotebooks\notebooks\how-to-use-azureml\automated-machine-learning\forecasting-energy-demand\nyc_energy.csv.
1. When you get to the column definition page, allow nulls for all columns. 1. When you get to the column definition page, allow nulls for all columns.
You can then run the queries in the energy-demand folder: You can then run the queries in the energy-demand folder:
* TrainEnergyDemand.sql runs AutoML, trains multiple models on data and selects the best model. * TrainEnergyDemand.sql runs AutoML, trains multiple models on data and selects the best model.
* ForecastEnergyDemand.sql forecasts based on the most recent training run. * PredictEnergyDemand.sql predicts based on the most recent training run.
* GetMetrics.sql returns all the metrics for each model in the most recent training run. * GetMetrics.sql returns all the metrics for each model in the most recent training run.

View File

@@ -1,23 +1,23 @@
-- This shows using the AutoMLForecast stored procedure to predict using a forecasting model for the nyc_energy dataset. -- This shows using the AutoMLForecast stored procedure to predict using a forecasting model for the nyc_energy dataset.
DECLARE @Model NVARCHAR(MAX) = (SELECT TOP 1 Model FROM dbo.aml_model DECLARE @Model NVARCHAR(MAX) = (SELECT TOP 1 Model FROM dbo.aml_model
WHERE ExperimentName = 'automl-sql-forecast' WHERE ExperimentName = 'automl-sql-forecast'
ORDER BY CreatedDate DESC) ORDER BY CreatedDate DESC)
DECLARE @max_horizon INT = 48 DECLARE @max_horizon INT = 48
DECLARE @split_time NVARCHAR(22) = (SELECT DATEADD(hour, -@max_horizon, MAX(timeStamp)) FROM nyc_energy WHERE demand IS NOT NULL) DECLARE @split_time NVARCHAR(22) = (SELECT DATEADD(hour, -@max_horizon, MAX(timeStamp)) FROM nyc_energy WHERE demand IS NOT NULL)
DECLARE @TestDataQuery NVARCHAR(MAX) = ' DECLARE @TestDataQuery NVARCHAR(MAX) = '
SELECT CAST(timeStamp AS NVARCHAR(30)) AS timeStamp, SELECT CAST(timeStamp AS NVARCHAR(30)) AS timeStamp,
demand, demand,
precip, precip,
temp temp
FROM nyc_energy FROM nyc_energy
WHERE demand IS NOT NULL AND precip IS NOT NULL AND temp IS NOT NULL WHERE demand IS NOT NULL AND precip IS NOT NULL AND temp IS NOT NULL
AND timeStamp > ''' + @split_time + '''' AND timeStamp > ''' + @split_time + ''''
EXEC dbo.AutoMLForecast @input_query=@TestDataQuery, EXEC dbo.AutoMLForecast @input_query=@TestDataQuery,
@label_column='demand', @label_column='demand',
@time_column_name='timeStamp', @time_column_name='timeStamp',
@model=@model @model=@model
WITH RESULT SETS ((timeStamp DATETIME, grain NVARCHAR(255), predicted_demand FLOAT, precip FLOAT, temp FLOAT, actual_demand FLOAT)) WITH RESULT SETS ((timeStamp DATETIME, grain NVARCHAR(255), predicted_demand FLOAT, precip FLOAT, temp FLOAT, actual_demand FLOAT))

View File

@@ -1,25 +1,25 @@
-- This shows using the AutoMLTrain stored procedure to create a forecasting model for the nyc_energy dataset. -- This shows using the AutoMLTrain stored procedure to create a forecasting model for the nyc_energy dataset.
DECLARE @max_horizon INT = 48 DECLARE @max_horizon INT = 48
DECLARE @split_time NVARCHAR(22) = (SELECT DATEADD(hour, -@max_horizon, MAX(timeStamp)) FROM nyc_energy WHERE demand IS NOT NULL) DECLARE @split_time NVARCHAR(22) = (SELECT DATEADD(hour, -@max_horizon, MAX(timeStamp)) FROM nyc_energy WHERE demand IS NOT NULL)
DECLARE @TrainDataQuery NVARCHAR(MAX) = ' DECLARE @TrainDataQuery NVARCHAR(MAX) = '
SELECT CAST(timeStamp as NVARCHAR(30)) as timeStamp, SELECT CAST(timeStamp as NVARCHAR(30)) as timeStamp,
demand, demand,
precip, precip,
temp temp
FROM nyc_energy FROM nyc_energy
WHERE demand IS NOT NULL AND precip IS NOT NULL AND temp IS NOT NULL WHERE demand IS NOT NULL AND precip IS NOT NULL AND temp IS NOT NULL
and timeStamp < ''' + @split_time + '''' and timeStamp < ''' + @split_time + ''''
INSERT INTO dbo.aml_model(RunId, ExperimentName, Model, LogFileText, WorkspaceName) INSERT INTO dbo.aml_model(RunId, ExperimentName, Model, LogFileText, WorkspaceName)
EXEC dbo.AutoMLTrain @input_query= @TrainDataQuery, EXEC dbo.AutoMLTrain @input_query= @TrainDataQuery,
@label_column='demand', @label_column='demand',
@task='forecasting', @task='forecasting',
@iterations=10, @iterations=10,
@iteration_timeout_minutes=5, @iteration_timeout_minutes=5,
@time_column_name='timeStamp', @time_column_name='timeStamp',
@max_horizon=@max_horizon, @max_horizon=@max_horizon,
@experiment_name='automl-sql-forecast', @experiment_name='automl-sql-forecast',
@primary_metric='normalized_root_mean_squared_error' @primary_metric='normalized_root_mean_squared_error'

View File

@@ -1,141 +1,141 @@
{ {
"cells": [ "metadata": {
{ "kernelspec": {
"cell_type": "markdown", "display_name": "Python 3.6",
"metadata": {}, "name": "python36",
"source": [ "language": "sql"
"# Train a model and use it for prediction\r\n", },
"\r\n", "authors": [
"Before running this notebook, run the auto-ml-sql-setup.ipynb notebook." {
] "name": "jeffshep"
}, }
{ ],
"cell_type": "markdown", "language_info": {
"metadata": {}, "name": "sql",
"source": [ "version": ""
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/sql-server/energy-demand/auto-ml-sql-energy-demand.png)" }
] },
}, "nbformat": 4,
{ "cells": [
"cell_type": "markdown", {
"metadata": {}, "metadata": {},
"source": [ "source": [
"## Set the default database" "# Train a model and use it for prediction\r\n",
] "\r\n",
}, "Before running this notebook, run the auto-ml-sql-setup.ipynb notebook."
{ ],
"cell_type": "code", "cell_type": "markdown"
"execution_count": null, },
"metadata": {}, {
"outputs": [], "metadata": {},
"source": [ "source": [
"USE [automl]\r\n", "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/sql-server/energy-demand/auto-ml-sql-energy-demand.png)"
"GO" ],
] "cell_type": "markdown"
}, },
{ {
"cell_type": "markdown", "metadata": {},
"metadata": {}, "source": [
"source": [ "## Set the default database"
"## Use the AutoMLTrain stored procedure to create a forecasting model for the nyc_energy dataset." ],
] "cell_type": "markdown"
}, },
{ {
"cell_type": "code", "metadata": {},
"execution_count": null, "outputs": [],
"metadata": {}, "execution_count": null,
"outputs": [], "source": [
"source": [ "USE [automl]\r\n",
"INSERT INTO dbo.aml_model(RunId, ExperimentName, Model, LogFileText, WorkspaceName)\r\n", "GO"
"EXEC dbo.AutoMLTrain @input_query='\r\n", ],
"SELECT CAST(timeStamp as NVARCHAR(30)) as timeStamp,\r\n", "cell_type": "code"
" demand,\r\n", },
"\t precip,\r\n", {
"\t temp,\r\n", "metadata": {},
"\t CASE WHEN timeStamp < ''2017-01-01'' THEN 0 ELSE 1 END AS is_validate_column\r\n", "source": [
"FROM nyc_energy\r\n", "## Use the AutoMLTrain stored procedure to create a forecasting model for the nyc_energy dataset."
"WHERE demand IS NOT NULL AND precip IS NOT NULL AND temp IS NOT NULL\r\n", ],
"and timeStamp < ''2017-02-01''',\r\n", "cell_type": "markdown"
"@label_column='demand',\r\n", },
"@task='forecasting',\r\n", {
"@iterations=10,\r\n", "metadata": {},
"@iteration_timeout_minutes=5,\r\n", "outputs": [],
"@time_column_name='timeStamp',\r\n", "execution_count": null,
"@is_validate_column='is_validate_column',\r\n", "source": [
"@experiment_name='automl-sql-forecast',\r\n", "INSERT INTO dbo.aml_model(RunId, ExperimentName, Model, LogFileText, WorkspaceName)\r\n",
"@primary_metric='normalized_root_mean_squared_error'" "EXEC dbo.AutoMLTrain @input_query='\r\n",
] "SELECT CAST(timeStamp as NVARCHAR(30)) as timeStamp,\r\n",
}, " demand,\r\n",
{ "\t precip,\r\n",
"cell_type": "markdown", "\t temp,\r\n",
"metadata": {}, "\t CASE WHEN timeStamp < ''2017-01-01'' THEN 0 ELSE 1 END AS is_validate_column\r\n",
"source": [ "FROM nyc_energy\r\n",
"## Use the AutoMLPredict stored procedure to predict using the forecasting model for the nyc_energy dataset." "WHERE demand IS NOT NULL AND precip IS NOT NULL AND temp IS NOT NULL\r\n",
] "and timeStamp < ''2017-02-01''',\r\n",
}, "@label_column='demand',\r\n",
{ "@task='forecasting',\r\n",
"cell_type": "code", "@iterations=10,\r\n",
"execution_count": null, "@iteration_timeout_minutes=5,\r\n",
"metadata": {}, "@time_column_name='timeStamp',\r\n",
"outputs": [], "@is_validate_column='is_validate_column',\r\n",
"source": [ "@experiment_name='automl-sql-forecast',\r\n",
"DECLARE @Model NVARCHAR(MAX) = (SELECT TOP 1 Model FROM dbo.aml_model\r\n", "@primary_metric='normalized_root_mean_squared_error'"
" WHERE ExperimentName = 'automl-sql-forecast'\r\n", ],
"\t\t\t\t\t\t\t\tORDER BY CreatedDate DESC)\r\n", "cell_type": "code"
"\r\n", },
"EXEC dbo.AutoMLPredict @input_query='\r\n", {
"SELECT CAST(timeStamp AS NVARCHAR(30)) AS timeStamp,\r\n", "metadata": {},
" demand,\r\n", "source": [
"\t precip,\r\n", "## Use the AutoMLPredict stored procedure to predict using the forecasting model for the nyc_energy dataset."
"\t temp\r\n", ],
"FROM nyc_energy\r\n", "cell_type": "markdown"
"WHERE demand IS NOT NULL AND precip IS NOT NULL AND temp IS NOT NULL\r\n", },
"AND timeStamp >= ''2017-02-01''',\r\n", {
"@label_column='demand',\r\n", "metadata": {},
"@model=@model\r\n", "outputs": [],
"WITH RESULT SETS ((timeStamp NVARCHAR(30), actual_demand FLOAT, precip FLOAT, temp FLOAT, predicted_demand FLOAT))" "execution_count": null,
] "source": [
}, "DECLARE @Model NVARCHAR(MAX) = (SELECT TOP 1 Model FROM dbo.aml_model\r\n",
{ " WHERE ExperimentName = 'automl-sql-forecast'\r\n",
"cell_type": "markdown", "\t\t\t\t\t\t\t\tORDER BY CreatedDate DESC)\r\n",
"metadata": {}, "\r\n",
"source": [ "EXEC dbo.AutoMLPredict @input_query='\r\n",
"## List all the metrics for all iterations for the most recent training run." "SELECT CAST(timeStamp AS NVARCHAR(30)) AS timeStamp,\r\n",
] " demand,\r\n",
}, "\t precip,\r\n",
{ "\t temp\r\n",
"cell_type": "code", "FROM nyc_energy\r\n",
"execution_count": null, "WHERE demand IS NOT NULL AND precip IS NOT NULL AND temp IS NOT NULL\r\n",
"metadata": {}, "AND timeStamp >= ''2017-02-01''',\r\n",
"outputs": [], "@label_column='demand',\r\n",
"source": [ "@model=@model\r\n",
"DECLARE @RunId NVARCHAR(43)\r\n", "WITH RESULT SETS ((timeStamp NVARCHAR(30), actual_demand FLOAT, precip FLOAT, temp FLOAT, predicted_demand FLOAT))"
"DECLARE @ExperimentName NVARCHAR(255)\r\n", ],
"\r\n", "cell_type": "code"
"SELECT TOP 1 @ExperimentName=ExperimentName, @RunId=SUBSTRING(RunId, 1, 43)\r\n", },
"FROM aml_model\r\n", {
"ORDER BY CreatedDate DESC\r\n", "metadata": {},
"\r\n", "source": [
"EXEC dbo.AutoMLGetMetrics @RunId, @ExperimentName" "## List all the metrics for all iterations for the most recent training run."
] ],
} "cell_type": "markdown"
], },
"metadata": { {
"authors": [ "metadata": {},
{ "outputs": [],
"name": "jeffshep" "execution_count": null,
} "source": [
], "DECLARE @RunId NVARCHAR(43)\r\n",
"kernelspec": { "DECLARE @ExperimentName NVARCHAR(255)\r\n",
"display_name": "Python 3.6", "\r\n",
"language": "sql", "SELECT TOP 1 @ExperimentName=ExperimentName, @RunId=SUBSTRING(RunId, 1, 43)\r\n",
"name": "python36" "FROM aml_model\r\n",
}, "ORDER BY CreatedDate DESC\r\n",
"language_info": { "\r\n",
"name": "sql", "EXEC dbo.AutoMLGetMetrics @RunId, @ExperimentName"
"version": "" ],
} "cell_type": "code"
}, }
"nbformat": 4, ],
"nbformat_minor": 2 "nbformat_minor": 2
} }

View File

@@ -1,92 +1,92 @@
-- This procedure forecast values based on a forecasting model returned by AutoMLTrain. -- This procedure forecast values based on a forecasting model returned by AutoMLTrain.
-- It returns a dataset with the forecasted values. -- It returns a dataset with the forecasted values.
SET ANSI_NULLS ON SET ANSI_NULLS ON
GO GO
SET QUOTED_IDENTIFIER ON SET QUOTED_IDENTIFIER ON
GO GO
CREATE OR ALTER PROCEDURE [dbo].[AutoMLForecast] CREATE OR ALTER PROCEDURE [dbo].[AutoMLForecast]
( (
@input_query NVARCHAR(MAX), -- A SQL query returning data to predict on. @input_query NVARCHAR(MAX), -- A SQL query returning data to predict on.
@model NVARCHAR(MAX), -- A model returned from AutoMLTrain. @model NVARCHAR(MAX), -- A model returned from AutoMLTrain.
@time_column_name NVARCHAR(255)='', -- The name of the timestamp column for forecasting. @time_column_name NVARCHAR(255)='', -- The name of the timestamp column for forecasting.
@label_column NVARCHAR(255)='', -- Optional name of the column from input_query, which should be ignored when predicting @label_column NVARCHAR(255)='', -- Optional name of the column from input_query, which should be ignored when predicting
@y_query_column NVARCHAR(255)='', -- Optional value column that can be used for predicting. @y_query_column NVARCHAR(255)='', -- Optional value column that can be used for predicting.
-- If specified, this can contain values for past times (after the model was trained) -- If specified, this can contain values for past times (after the model was trained)
-- and contain Nan for future times. -- and contain Nan for future times.
@forecast_column_name NVARCHAR(255) = 'predicted' @forecast_column_name NVARCHAR(255) = 'predicted'
-- The name of the output column containing the forecast value. -- The name of the output column containing the forecast value.
) AS ) AS
BEGIN BEGIN
EXEC sp_execute_external_script @language = N'Python', @script = N'import pandas as pd EXEC sp_execute_external_script @language = N'Python', @script = N'import pandas as pd
import azureml.core import azureml.core
import numpy as np import numpy as np
from azureml.train.automl import AutoMLConfig from azureml.train.automl import AutoMLConfig
import pickle import pickle
import codecs import codecs
model_obj = pickle.loads(codecs.decode(model.encode(), "base64")) model_obj = pickle.loads(codecs.decode(model.encode(), "base64"))
test_data = input_data.copy() test_data = input_data.copy()
if label_column != "" and label_column is not None: if label_column != "" and label_column is not None:
y_test = test_data.pop(label_column).values y_test = test_data.pop(label_column).values
else: else:
y_test = None y_test = None
if y_query_column != "" and y_query_column is not None: if y_query_column != "" and y_query_column is not None:
y_query = test_data.pop(y_query_column).values y_query = test_data.pop(y_query_column).values
else: else:
y_query = np.repeat(np.nan, len(test_data)) y_query = np.repeat(np.nan, len(test_data))
X_test = test_data X_test = test_data
if time_column_name != "" and time_column_name is not None: if time_column_name != "" and time_column_name is not None:
X_test[time_column_name] = pd.to_datetime(X_test[time_column_name]) X_test[time_column_name] = pd.to_datetime(X_test[time_column_name])
y_fcst, X_trans = model_obj.forecast(X_test, y_query) y_fcst, X_trans = model_obj.forecast(X_test, y_query)
def align_outputs(y_forecast, X_trans, X_test, y_test, forecast_column_name): def align_outputs(y_forecast, X_trans, X_test, y_test, forecast_column_name):
# Demonstrates how to get the output aligned to the inputs # Demonstrates how to get the output aligned to the inputs
# using pandas indexes. Helps understand what happened if # using pandas indexes. Helps understand what happened if
# the output shape differs from the input shape, or if # the output shape differs from the input shape, or if
# the data got re-sorted by time and grain during forecasting. # the data got re-sorted by time and grain during forecasting.
# Typical causes of misalignment are: # Typical causes of misalignment are:
# * we predicted some periods that were missing in actuals -> drop from eval # * we predicted some periods that were missing in actuals -> drop from eval
# * model was asked to predict past max_horizon -> increase max horizon # * model was asked to predict past max_horizon -> increase max horizon
# * data at start of X_test was needed for lags -> provide previous periods # * data at start of X_test was needed for lags -> provide previous periods
df_fcst = pd.DataFrame({forecast_column_name : y_forecast}) df_fcst = pd.DataFrame({forecast_column_name : y_forecast})
# y and X outputs are aligned by forecast() function contract # y and X outputs are aligned by forecast() function contract
df_fcst.index = X_trans.index df_fcst.index = X_trans.index
# align original X_test to y_test # align original X_test to y_test
X_test_full = X_test.copy() X_test_full = X_test.copy()
if y_test is not None: if y_test is not None:
X_test_full[label_column] = y_test X_test_full[label_column] = y_test
# X_test_full does not include origin, so reset for merge # X_test_full does not include origin, so reset for merge
df_fcst.reset_index(inplace=True) df_fcst.reset_index(inplace=True)
X_test_full = X_test_full.reset_index().drop(columns=''index'') X_test_full = X_test_full.reset_index().drop(columns=''index'')
together = df_fcst.merge(X_test_full, how=''right'') together = df_fcst.merge(X_test_full, how=''right'')
# drop rows where prediction or actuals are nan # drop rows where prediction or actuals are nan
# happens because of missing actuals # happens because of missing actuals
# or at edges of time due to lags/rolling windows # or at edges of time due to lags/rolling windows
clean = together[together[[label_column, forecast_column_name]].notnull().all(axis=1)] clean = together[together[[label_column, forecast_column_name]].notnull().all(axis=1)]
return(clean) return(clean)
combined_output = align_outputs(y_fcst, X_trans, X_test, y_test, forecast_column_name) combined_output = align_outputs(y_fcst, X_trans, X_test, y_test, forecast_column_name)
' '
, @input_data_1 = @input_query , @input_data_1 = @input_query
, @input_data_1_name = N'input_data' , @input_data_1_name = N'input_data'
, @output_data_1_name = N'combined_output' , @output_data_1_name = N'combined_output'
, @params = N'@model NVARCHAR(MAX), @time_column_name NVARCHAR(255), @label_column NVARCHAR(255), @y_query_column NVARCHAR(255), @forecast_column_name NVARCHAR(255)' , @params = N'@model NVARCHAR(MAX), @time_column_name NVARCHAR(255), @label_column NVARCHAR(255), @y_query_column NVARCHAR(255), @forecast_column_name NVARCHAR(255)'
, @model = @model , @model = @model
, @time_column_name = @time_column_name , @time_column_name = @time_column_name
, @label_column = @label_column , @label_column = @label_column
, @y_query_column = @y_query_column , @y_query_column = @y_query_column
, @forecast_column_name = @forecast_column_name , @forecast_column_name = @forecast_column_name
END END

View File

@@ -1,41 +1,41 @@
-- This procedure predicts values based on a model returned by AutoMLTrain and a dataset. -- This procedure predicts values based on a model returned by AutoMLTrain and a dataset.
-- It returns the dataset with a new column added, which is the predicted value. -- It returns the dataset with a new column added, which is the predicted value.
SET ANSI_NULLS ON SET ANSI_NULLS ON
GO GO
SET QUOTED_IDENTIFIER ON SET QUOTED_IDENTIFIER ON
GO GO
CREATE OR ALTER PROCEDURE [dbo].[AutoMLPredict] CREATE OR ALTER PROCEDURE [dbo].[AutoMLPredict]
( (
@input_query NVARCHAR(MAX), -- A SQL query returning data to predict on. @input_query NVARCHAR(MAX), -- A SQL query returning data to predict on.
@model NVARCHAR(MAX), -- A model returned from AutoMLTrain. @model NVARCHAR(MAX), -- A model returned from AutoMLTrain.
@label_column NVARCHAR(255)='' -- Optional name of the column from input_query, which should be ignored when predicting @label_column NVARCHAR(255)='' -- Optional name of the column from input_query, which should be ignored when predicting
) AS ) AS
BEGIN BEGIN
EXEC sp_execute_external_script @language = N'Python', @script = N'import pandas as pd EXEC sp_execute_external_script @language = N'Python', @script = N'import pandas as pd
import azureml.core import azureml.core
import numpy as np import numpy as np
from azureml.train.automl import AutoMLConfig from azureml.train.automl import AutoMLConfig
import pickle import pickle
import codecs import codecs
model_obj = pickle.loads(codecs.decode(model.encode(), "base64")) model_obj = pickle.loads(codecs.decode(model.encode(), "base64"))
test_data = input_data.copy() test_data = input_data.copy()
if label_column != "" and label_column is not None: if label_column != "" and label_column is not None:
y_test = test_data.pop(label_column).values y_test = test_data.pop(label_column).values
X_test = test_data X_test = test_data
predicted = model_obj.predict(X_test) predicted = model_obj.predict(X_test)
combined_output = input_data.assign(predicted=predicted) combined_output = input_data.assign(predicted=predicted)
' '
, @input_data_1 = @input_query , @input_data_1 = @input_query
, @input_data_1_name = N'input_data' , @input_data_1_name = N'input_data'
, @output_data_1_name = N'combined_output' , @output_data_1_name = N'combined_output'
, @params = N'@model NVARCHAR(MAX), @label_column NVARCHAR(255)' , @params = N'@model NVARCHAR(MAX), @label_column NVARCHAR(255)'
, @model = @model , @model = @model
, @label_column = @label_column , @label_column = @label_column
END END

View File

@@ -1,240 +1,240 @@
-- This stored procedure uses automated machine learning to train several models -- This stored procedure uses automated machine learning to train several models
-- and returns the best model. -- and returns the best model.
-- --
-- The result set has several columns: -- The result set has several columns:
-- best_run - iteration ID for the best model -- best_run - iteration ID for the best model
-- experiment_name - experiment name pass in with the @experiment_name parameter -- experiment_name - experiment name pass in with the @experiment_name parameter
-- fitted_model - best model found -- fitted_model - best model found
-- log_file_text - AutoML debug_log contents -- log_file_text - AutoML debug_log contents
-- workspace - name of the Azure ML workspace where run history is stored -- workspace - name of the Azure ML workspace where run history is stored
-- --
-- An example call for a classification problem is: -- An example call for a classification problem is:
-- insert into dbo.aml_model(RunId, ExperimentName, Model, LogFileText, WorkspaceName) -- insert into dbo.aml_model(RunId, ExperimentName, Model, LogFileText, WorkspaceName)
-- exec dbo.AutoMLTrain @input_query=' -- exec dbo.AutoMLTrain @input_query='
-- SELECT top 100000 -- SELECT top 100000
-- CAST([pickup_datetime] AS NVARCHAR(30)) AS pickup_datetime -- CAST([pickup_datetime] AS NVARCHAR(30)) AS pickup_datetime
-- ,CAST([dropoff_datetime] AS NVARCHAR(30)) AS dropoff_datetime -- ,CAST([dropoff_datetime] AS NVARCHAR(30)) AS dropoff_datetime
-- ,[passenger_count] -- ,[passenger_count]
-- ,[trip_time_in_secs] -- ,[trip_time_in_secs]
-- ,[trip_distance] -- ,[trip_distance]
-- ,[payment_type] -- ,[payment_type]
-- ,[tip_class] -- ,[tip_class]
-- FROM [dbo].[nyctaxi_sample] order by [hack_license] ', -- FROM [dbo].[nyctaxi_sample] order by [hack_license] ',
-- @label_column = 'tip_class', -- @label_column = 'tip_class',
-- @iterations=10 -- @iterations=10
-- --
-- An example call for forecasting is: -- An example call for forecasting is:
-- insert into dbo.aml_model(RunId, ExperimentName, Model, LogFileText, WorkspaceName) -- insert into dbo.aml_model(RunId, ExperimentName, Model, LogFileText, WorkspaceName)
-- exec dbo.AutoMLTrain @input_query=' -- exec dbo.AutoMLTrain @input_query='
-- select cast(timeStamp as nvarchar(30)) as timeStamp, -- select cast(timeStamp as nvarchar(30)) as timeStamp,
-- demand, -- demand,
-- precip, -- precip,
-- temp, -- temp,
-- case when timeStamp < ''2017-01-01'' then 0 else 1 end as is_validate_column -- case when timeStamp < ''2017-01-01'' then 0 else 1 end as is_validate_column
-- from nyc_energy -- from nyc_energy
-- where demand is not null and precip is not null and temp is not null -- where demand is not null and precip is not null and temp is not null
-- and timeStamp < ''2017-02-01''', -- and timeStamp < ''2017-02-01''',
-- @label_column='demand', -- @label_column='demand',
-- @task='forecasting', -- @task='forecasting',
-- @iterations=10, -- @iterations=10,
-- @iteration_timeout_minutes=5, -- @iteration_timeout_minutes=5,
-- @time_column_name='timeStamp', -- @time_column_name='timeStamp',
-- @is_validate_column='is_validate_column', -- @is_validate_column='is_validate_column',
-- @experiment_name='automl-sql-forecast', -- @experiment_name='automl-sql-forecast',
-- @primary_metric='normalized_root_mean_squared_error' -- @primary_metric='normalized_root_mean_squared_error'
SET ANSI_NULLS ON SET ANSI_NULLS ON
GO GO
SET QUOTED_IDENTIFIER ON SET QUOTED_IDENTIFIER ON
GO GO
CREATE OR ALTER PROCEDURE [dbo].[AutoMLTrain] CREATE OR ALTER PROCEDURE [dbo].[AutoMLTrain]
( (
@input_query NVARCHAR(MAX), -- The SQL Query that will return the data to train and validate the model. @input_query NVARCHAR(MAX), -- The SQL Query that will return the data to train and validate the model.
@label_column NVARCHAR(255)='Label', -- The name of the column in the result of @input_query that is the label. @label_column NVARCHAR(255)='Label', -- The name of the column in the result of @input_query that is the label.
@primary_metric NVARCHAR(40)='AUC_weighted', -- The metric to optimize. @primary_metric NVARCHAR(40)='AUC_weighted', -- The metric to optimize.
@iterations INT=100, -- The maximum number of pipelines to train. @iterations INT=100, -- The maximum number of pipelines to train.
@task NVARCHAR(40)='classification', -- The type of task. Can be classification, regression or forecasting. @task NVARCHAR(40)='classification', -- The type of task. Can be classification, regression or forecasting.
@experiment_name NVARCHAR(32)='automl-sql-test', -- This can be used to find the experiment in the Azure Portal. @experiment_name NVARCHAR(32)='automl-sql-test', -- This can be used to find the experiment in the Azure Portal.
@iteration_timeout_minutes INT = 15, -- The maximum time in minutes for training a single pipeline. @iteration_timeout_minutes INT = 15, -- The maximum time in minutes for training a single pipeline.
@experiment_timeout_minutes INT = 60, -- The maximum time in minutes for training all pipelines. @experiment_timeout_minutes INT = 60, -- The maximum time in minutes for training all pipelines.
@n_cross_validations INT = 3, -- The number of cross validations. @n_cross_validations INT = 3, -- The number of cross validations.
@blacklist_models NVARCHAR(MAX) = '', -- A comma separated list of algos that will not be used. @blacklist_models NVARCHAR(MAX) = '', -- A comma separated list of algos that will not be used.
-- The list of possible models can be found at: -- The list of possible models can be found at:
-- https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-configure-auto-train#configure-your-experiment-settings -- https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-configure-auto-train#configure-your-experiment-settings
@whitelist_models NVARCHAR(MAX) = '', -- A comma separated list of algos that can be used. @whitelist_models NVARCHAR(MAX) = '', -- A comma separated list of algos that can be used.
-- The list of possible models can be found at: -- The list of possible models can be found at:
-- https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-configure-auto-train#configure-your-experiment-settings -- https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-configure-auto-train#configure-your-experiment-settings
@experiment_exit_score FLOAT = 0, -- Stop the experiment if this score is acheived. @experiment_exit_score FLOAT = 0, -- Stop the experiment if this score is acheived.
@sample_weight_column NVARCHAR(255)='', -- The name of the column in the result of @input_query that gives a sample weight. @sample_weight_column NVARCHAR(255)='', -- The name of the column in the result of @input_query that gives a sample weight.
@is_validate_column NVARCHAR(255)='', -- The name of the column in the result of @input_query that indicates if the row is for training or validation. @is_validate_column NVARCHAR(255)='', -- The name of the column in the result of @input_query that indicates if the row is for training or validation.
-- In the values of the column, 0 means for training and 1 means for validation. -- In the values of the column, 0 means for training and 1 means for validation.
@time_column_name NVARCHAR(255)='', -- The name of the timestamp column for forecasting. @time_column_name NVARCHAR(255)='', -- The name of the timestamp column for forecasting.
@connection_name NVARCHAR(255)='default', -- The AML connection to use. @connection_name NVARCHAR(255)='default', -- The AML connection to use.
@max_horizon INT = 0 -- A forecast horizon is a time span into the future (or just beyond the latest date in the training data) @max_horizon INT = 0 -- A forecast horizon is a time span into the future (or just beyond the latest date in the training data)
-- where forecasts of the target quantity are needed. -- where forecasts of the target quantity are needed.
-- For example, if data is recorded daily and max_horizon is 5, we will predict 5 days ahead. -- For example, if data is recorded daily and max_horizon is 5, we will predict 5 days ahead.
) AS ) AS
BEGIN BEGIN
DECLARE @tenantid NVARCHAR(255) DECLARE @tenantid NVARCHAR(255)
DECLARE @appid NVARCHAR(255) DECLARE @appid NVARCHAR(255)
DECLARE @password NVARCHAR(255) DECLARE @password NVARCHAR(255)
DECLARE @config_file NVARCHAR(255) DECLARE @config_file NVARCHAR(255)
SELECT @tenantid=TenantId, @appid=AppId, @password=Password, @config_file=ConfigFile SELECT @tenantid=TenantId, @appid=AppId, @password=Password, @config_file=ConfigFile
FROM aml_connection FROM aml_connection
WHERE ConnectionName = @connection_name; WHERE ConnectionName = @connection_name;
EXEC sp_execute_external_script @language = N'Python', @script = N'import pandas as pd EXEC sp_execute_external_script @language = N'Python', @script = N'import pandas as pd
import logging import logging
import azureml.core import azureml.core
import pandas as pd import pandas as pd
import numpy as np import numpy as np
from azureml.core.experiment import Experiment from azureml.core.experiment import Experiment
from azureml.train.automl import AutoMLConfig from azureml.train.automl import AutoMLConfig
from sklearn import datasets from sklearn import datasets
import pickle import pickle
import codecs import codecs
from azureml.core.authentication import ServicePrincipalAuthentication from azureml.core.authentication import ServicePrincipalAuthentication
from azureml.core.workspace import Workspace from azureml.core.workspace import Workspace
if __name__.startswith("sqlindb"): if __name__.startswith("sqlindb"):
auth = ServicePrincipalAuthentication(tenantid, appid, password) auth = ServicePrincipalAuthentication(tenantid, appid, password)
ws = Workspace.from_config(path=config_file, auth=auth) ws = Workspace.from_config(path=config_file, auth=auth)
project_folder = "./sample_projects/" + experiment_name project_folder = "./sample_projects/" + experiment_name
experiment = Experiment(ws, experiment_name) experiment = Experiment(ws, experiment_name)
data_train = input_data data_train = input_data
X_valid = None X_valid = None
y_valid = None y_valid = None
sample_weight_valid = None sample_weight_valid = None
if is_validate_column != "" and is_validate_column is not None: if is_validate_column != "" and is_validate_column is not None:
data_train = input_data[input_data[is_validate_column] <= 0] data_train = input_data[input_data[is_validate_column] <= 0]
data_valid = input_data[input_data[is_validate_column] > 0] data_valid = input_data[input_data[is_validate_column] > 0]
data_train.pop(is_validate_column) data_train.pop(is_validate_column)
data_valid.pop(is_validate_column) data_valid.pop(is_validate_column)
y_valid = data_valid.pop(label_column).values y_valid = data_valid.pop(label_column).values
if sample_weight_column != "" and sample_weight_column is not None: if sample_weight_column != "" and sample_weight_column is not None:
sample_weight_valid = data_valid.pop(sample_weight_column).values sample_weight_valid = data_valid.pop(sample_weight_column).values
X_valid = data_valid X_valid = data_valid
n_cross_validations = None n_cross_validations = None
y_train = data_train.pop(label_column).values y_train = data_train.pop(label_column).values
sample_weight = None sample_weight = None
if sample_weight_column != "" and sample_weight_column is not None: if sample_weight_column != "" and sample_weight_column is not None:
sample_weight = data_train.pop(sample_weight_column).values sample_weight = data_train.pop(sample_weight_column).values
X_train = data_train X_train = data_train
if experiment_timeout_minutes == 0: if experiment_timeout_minutes == 0:
experiment_timeout_minutes = None experiment_timeout_minutes = None
if experiment_exit_score == 0: if experiment_exit_score == 0:
experiment_exit_score = None experiment_exit_score = None
if blacklist_models == "": if blacklist_models == "":
blacklist_models = None blacklist_models = None
if blacklist_models is not None: if blacklist_models is not None:
blacklist_models = blacklist_models.replace(" ", "").split(",") blacklist_models = blacklist_models.replace(" ", "").split(",")
if whitelist_models == "": if whitelist_models == "":
whitelist_models = None whitelist_models = None
if whitelist_models is not None: if whitelist_models is not None:
whitelist_models = whitelist_models.replace(" ", "").split(",") whitelist_models = whitelist_models.replace(" ", "").split(",")
automl_settings = {} automl_settings = {}
preprocess = True preprocess = True
if time_column_name != "" and time_column_name is not None: if time_column_name != "" and time_column_name is not None:
automl_settings = { "time_column_name": time_column_name } automl_settings = { "time_column_name": time_column_name }
preprocess = False preprocess = False
if max_horizon > 0: if max_horizon > 0:
automl_settings["max_horizon"] = max_horizon automl_settings["max_horizon"] = max_horizon
log_file_name = "automl_sqlindb_errors.log" log_file_name = "automl_sqlindb_errors.log"
automl_config = AutoMLConfig(task = task, automl_config = AutoMLConfig(task = task,
debug_log = log_file_name, debug_log = log_file_name,
primary_metric = primary_metric, primary_metric = primary_metric,
iteration_timeout_minutes = iteration_timeout_minutes, iteration_timeout_minutes = iteration_timeout_minutes,
experiment_timeout_minutes = experiment_timeout_minutes, experiment_timeout_minutes = experiment_timeout_minutes,
iterations = iterations, iterations = iterations,
n_cross_validations = n_cross_validations, n_cross_validations = n_cross_validations,
preprocess = preprocess, preprocess = preprocess,
verbosity = logging.INFO, verbosity = logging.INFO,
X = X_train, X = X_train,
y = y_train, y = y_train,
path = project_folder, path = project_folder,
blacklist_models = blacklist_models, blacklist_models = blacklist_models,
whitelist_models = whitelist_models, whitelist_models = whitelist_models,
experiment_exit_score = experiment_exit_score, experiment_exit_score = experiment_exit_score,
sample_weight = sample_weight, sample_weight = sample_weight,
X_valid = X_valid, X_valid = X_valid,
y_valid = y_valid, y_valid = y_valid,
sample_weight_valid = sample_weight_valid, sample_weight_valid = sample_weight_valid,
**automl_settings) **automl_settings)
local_run = experiment.submit(automl_config, show_output = True) local_run = experiment.submit(automl_config, show_output = True)
best_run, fitted_model = local_run.get_output() best_run, fitted_model = local_run.get_output()
pickled_model = codecs.encode(pickle.dumps(fitted_model), "base64").decode() pickled_model = codecs.encode(pickle.dumps(fitted_model), "base64").decode()
log_file_text = "" log_file_text = ""
try: try:
with open(log_file_name, "r") as log_file: with open(log_file_name, "r") as log_file:
log_file_text = log_file.read() log_file_text = log_file.read()
except: except:
log_file_text = "Log file not found" log_file_text = "Log file not found"
returned_model = pd.DataFrame({"best_run": [best_run.id], "experiment_name": [experiment_name], "fitted_model": [pickled_model], "log_file_text": [log_file_text], "workspace": [ws.name]}, dtype=np.dtype(np.str)) returned_model = pd.DataFrame({"best_run": [best_run.id], "experiment_name": [experiment_name], "fitted_model": [pickled_model], "log_file_text": [log_file_text], "workspace": [ws.name]}, dtype=np.dtype(np.str))
' '
, @input_data_1 = @input_query , @input_data_1 = @input_query
, @input_data_1_name = N'input_data' , @input_data_1_name = N'input_data'
, @output_data_1_name = N'returned_model' , @output_data_1_name = N'returned_model'
, @params = N'@label_column NVARCHAR(255), , @params = N'@label_column NVARCHAR(255),
@primary_metric NVARCHAR(40), @primary_metric NVARCHAR(40),
@iterations INT, @task NVARCHAR(40), @iterations INT, @task NVARCHAR(40),
@experiment_name NVARCHAR(32), @experiment_name NVARCHAR(32),
@iteration_timeout_minutes INT, @iteration_timeout_minutes INT,
@experiment_timeout_minutes INT, @experiment_timeout_minutes INT,
@n_cross_validations INT, @n_cross_validations INT,
@blacklist_models NVARCHAR(MAX), @blacklist_models NVARCHAR(MAX),
@whitelist_models NVARCHAR(MAX), @whitelist_models NVARCHAR(MAX),
@experiment_exit_score FLOAT, @experiment_exit_score FLOAT,
@sample_weight_column NVARCHAR(255), @sample_weight_column NVARCHAR(255),
@is_validate_column NVARCHAR(255), @is_validate_column NVARCHAR(255),
@time_column_name NVARCHAR(255), @time_column_name NVARCHAR(255),
@tenantid NVARCHAR(255), @tenantid NVARCHAR(255),
@appid NVARCHAR(255), @appid NVARCHAR(255),
@password NVARCHAR(255), @password NVARCHAR(255),
@config_file NVARCHAR(255), @config_file NVARCHAR(255),
@max_horizon INT' @max_horizon INT'
, @label_column = @label_column , @label_column = @label_column
, @primary_metric = @primary_metric , @primary_metric = @primary_metric
, @iterations = @iterations , @iterations = @iterations
, @task = @task , @task = @task
, @experiment_name = @experiment_name , @experiment_name = @experiment_name
, @iteration_timeout_minutes = @iteration_timeout_minutes , @iteration_timeout_minutes = @iteration_timeout_minutes
, @experiment_timeout_minutes = @experiment_timeout_minutes , @experiment_timeout_minutes = @experiment_timeout_minutes
, @n_cross_validations = @n_cross_validations , @n_cross_validations = @n_cross_validations
, @blacklist_models = @blacklist_models , @blacklist_models = @blacklist_models
, @whitelist_models = @whitelist_models , @whitelist_models = @whitelist_models
, @experiment_exit_score = @experiment_exit_score , @experiment_exit_score = @experiment_exit_score
, @sample_weight_column = @sample_weight_column , @sample_weight_column = @sample_weight_column
, @is_validate_column = @is_validate_column , @is_validate_column = @is_validate_column
, @time_column_name = @time_column_name , @time_column_name = @time_column_name
, @tenantid = @tenantid , @tenantid = @tenantid
, @appid = @appid , @appid = @appid
, @password = @password , @password = @password
, @config_file = @config_file , @config_file = @config_file
, @max_horizon = @max_horizon , @max_horizon = @max_horizon
WITH RESULT SETS ((best_run NVARCHAR(250), experiment_name NVARCHAR(100), fitted_model VARCHAR(MAX), log_file_text NVARCHAR(MAX), workspace NVARCHAR(100))) WITH RESULT SETS ((best_run NVARCHAR(250), experiment_name NVARCHAR(100), fitted_model VARCHAR(MAX), log_file_text NVARCHAR(MAX), workspace NVARCHAR(100)))
END END

View File

@@ -1,18 +1,18 @@
-- This is a table to store the Azure ML connection information. -- This is a table to store the Azure ML connection information.
SET ANSI_NULLS ON SET ANSI_NULLS ON
GO GO
SET QUOTED_IDENTIFIER ON SET QUOTED_IDENTIFIER ON
GO GO
CREATE TABLE [dbo].[aml_connection]( CREATE TABLE [dbo].[aml_connection](
[Id] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY, [Id] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
[ConnectionName] [nvarchar](255) NULL, [ConnectionName] [nvarchar](255) NULL,
[TenantId] [nvarchar](255) NULL, [TenantId] [nvarchar](255) NULL,
[AppId] [nvarchar](255) NULL, [AppId] [nvarchar](255) NULL,
[Password] [nvarchar](255) NULL, [Password] [nvarchar](255) NULL,
[ConfigFile] [nvarchar](255) NULL [ConfigFile] [nvarchar](255) NULL
) ON [PRIMARY] ) ON [PRIMARY]
GO GO

View File

@@ -1,198 +1,208 @@
{ {
"cells": [ "metadata": {
{ "kernelspec": {
"cell_type": "markdown", "display_name": "Python 3.6",
"metadata": {}, "name": "python36",
"source": [ "language": "python"
"Copyright (c) Microsoft Corporation. All rights reserved.\n", },
"\n", "authors": [
"Licensed under the MIT License." {
] "name": "rogehe"
}, }
{ ],
"cell_type": "markdown", "language_info": {
"metadata": {}, "mimetype": "text/x-python",
"source": [ "codemirror_mode": {
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/subsampling/auto-ml-subsampling-local.png)" "name": "ipython",
] "version": 3
}, },
{ "pygments_lexer": "ipython3",
"cell_type": "markdown", "name": "python",
"metadata": {}, "file_extension": ".py",
"source": [ "nbconvert_exporter": "python",
"# Automated Machine Learning\n", "version": "3.6.6"
"_**Classification with Local Compute**_\n", }
"\n", },
"## Contents\n", "nbformat": 4,
"1. [Introduction](#Introduction)\n", "cells": [
"1. [Setup](#Setup)\n", {
"1. [Data](#Data)\n", "metadata": {},
"1. [Train](#Train)\n", "source": [
"\n" "Copyright (c) Microsoft Corporation. All rights reserved.\n",
] "\n",
}, "Licensed under the MIT License."
{ ],
"cell_type": "markdown", "cell_type": "markdown"
"metadata": {}, },
"source": [ {
"## Introduction\n", "metadata": {},
"\n", "source": [
"In this example we will explore AutoML's subsampling feature. This is useful for training on large datasets to speed up the convergence.\n", "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/subsampling/auto-ml-subsampling-local.png)"
"\n", ],
"The setup is quiet similar to a normal classification, with the exception of the `enable_subsampling` option. Keep in mind that even with the `enable_subsampling` flag set, subsampling will only be run for large datasets (>= 50k rows) and large (>= 85) or no iteration restrictions.\n" "cell_type": "markdown"
] },
}, {
{ "metadata": {},
"cell_type": "markdown", "source": [
"metadata": {}, "# Automated Machine Learning\n",
"source": [ "_**Classification with Local Compute**_\n",
"## Setup\n", "\n",
"\n", "## Contents\n",
"As part of the setup you have already created an Azure ML `Workspace` object. For AutoML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments." "1. [Introduction](#Introduction)\n",
] "1. [Setup](#Setup)\n",
}, "1. [Data](#Data)\n",
{ "1. [Train](#Train)\n",
"cell_type": "code", "\n"
"execution_count": null, ],
"metadata": {}, "cell_type": "markdown"
"outputs": [], },
"source": [ {
"import logging\n", "metadata": {},
"\n", "source": [
"import numpy as np\n", "## Introduction\n",
"import pandas as pd\n", "\n",
"\n", "In this example we will explore AutoML's subsampling feature. This is useful for training on large datasets to speed up the convergence.\n",
"import azureml.core\n", "\n",
"from azureml.core.experiment import Experiment\n", "The setup is quiet similar to a normal classification, with the exception of the `enable_subsampling` option. Keep in mind that even with the `enable_subsampling` flag set, subsampling will only be run for large datasets (>= 50k rows) and large (>= 85) or no iteration restrictions.\n"
"from azureml.core.workspace import Workspace\n", ],
"from azureml.train.automl import AutoMLConfig\n", "cell_type": "markdown"
"from azureml.train.automl.run import AutoMLRun" },
] {
}, "metadata": {},
{ "source": [
"cell_type": "code", "## Setup\n",
"execution_count": null, "\n",
"metadata": {}, "As part of the setup you have already created an Azure ML `Workspace` object. For AutoML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments."
"outputs": [], ],
"source": [ "cell_type": "markdown"
"ws = Workspace.from_config()\n", },
"\n", {
"# Choose a name for the experiment.\n", "metadata": {},
"experiment_name = 'automl-subsampling'\n", "outputs": [],
"\n", "execution_count": null,
"experiment = Experiment(ws, experiment_name)\n", "source": [
"\n", "import logging\n",
"output = {}\n", "\n",
"output['SDK version'] = azureml.core.VERSION\n", "import numpy as np\n",
"output['Subscription ID'] = ws.subscription_id\n", "import pandas as pd\n",
"output['Workspace Name'] = ws.name\n", "\n",
"output['Resource Group'] = ws.resource_group\n", "import azureml.core\n",
"output['Location'] = ws.location\n", "from azureml.core.experiment import Experiment\n",
"output['Experiment Name'] = experiment.name\n", "from azureml.core.workspace import Workspace\n",
"pd.set_option('display.max_colwidth', -1)\n", "from azureml.train.automl import AutoMLConfig\n",
"pd.DataFrame(data = output, index = ['']).T" "from azureml.train.automl.run import AutoMLRun"
] ],
}, "cell_type": "code"
{ },
"cell_type": "markdown", {
"metadata": {}, "metadata": {},
"source": [ "outputs": [],
"## Data\n", "execution_count": null,
"\n", "source": [
"We will create a simple dataset using the numpy sin function just for this example. We need just over 50k rows." "ws = Workspace.from_config()\n",
] "\n",
}, "# Choose a name for the experiment and specify the project folder.\n",
{ "experiment_name = 'automl-subsampling'\n",
"cell_type": "code", "project_folder = './sample_projects/automl-subsampling'\n",
"execution_count": null, "\n",
"metadata": {}, "experiment = Experiment(ws, experiment_name)\n",
"outputs": [], "\n",
"source": [ "output = {}\n",
"base = np.arange(60000)\n", "output['SDK version'] = azureml.core.VERSION\n",
"cos = np.cos(base)\n", "output['Subscription ID'] = ws.subscription_id\n",
"y = np.round(np.sin(base)).astype('int')\n", "output['Workspace Name'] = ws.name\n",
"\n", "output['Resource Group'] = ws.resource_group\n",
"# Exclude the first 100 rows from training so that they can be used for test.\n", "output['Location'] = ws.location\n",
"X_train = np.hstack((base.reshape(-1, 1), cos.reshape(-1, 1)))\n", "output['Project Directory'] = project_folder\n",
"y_train = y" "output['Experiment Name'] = experiment.name\n",
] "pd.set_option('display.max_colwidth', -1)\n",
}, "pd.DataFrame(data = output, index = ['']).T"
{ ],
"cell_type": "markdown", "cell_type": "code"
"metadata": {}, },
"source": [ {
"## Train\n", "metadata": {},
"\n", "source": [
"Instantiate an `AutoMLConfig` object to specify the settings and data used to run the experiment.\n", "## Data\n",
"\n", "\n",
"|Property|Description|\n", "We will create a simple dataset using the numpy sin function just for this example. We need just over 50k rows."
"|-|-|\n", ],
"|**enable_subsampling**|This enables subsampling as an option. However it does not guarantee subsampling will be used. It also depends on how large the dataset is and how many iterations it's expected to run at a minimum.|\n", "cell_type": "markdown"
"|**iterations**|Number of iterations. Subsampling requires a lot of iterations at smaller percent so in order for subsampling to be used we need to set iterations to be a high number.|\n", },
"|**experiment_timeout_minutes**|The experiment timeout, it's set to 5 right now to shorten the demo but it should probably be higher if we want to finish all the iterations.|\n", {
"\n" "metadata": {},
] "outputs": [],
}, "execution_count": null,
{ "source": [
"cell_type": "code", "base = np.arange(60000)\n",
"execution_count": null, "cos = np.cos(base)\n",
"metadata": {}, "y = np.round(np.sin(base)).astype('int')\n",
"outputs": [], "\n",
"source": [ "# Exclude the first 100 rows from training so that they can be used for test.\n",
"automl_config = AutoMLConfig(task = 'classification',\n", "X_train = np.hstack((base.reshape(-1, 1), cos.reshape(-1, 1)))\n",
" debug_log = 'automl_errors.log',\n", "y_train = y"
" primary_metric = 'accuracy',\n", ],
" iterations = 85,\n", "cell_type": "code"
" experiment_timeout_minutes = 5,\n", },
" n_cross_validations = 2,\n", {
" verbosity = logging.INFO,\n", "metadata": {},
" X = X_train, \n", "source": [
" y = y_train,\n", "## Train\n",
" enable_subsampling=True)" "\n",
] "Instantiate an `AutoMLConfig` object to specify the settings and data used to run the experiment.\n",
}, "\n",
{ "|Property|Description|\n",
"cell_type": "markdown", "|-|-|\n",
"metadata": {}, "|**enable_subsampling**|This enables subsampling as an option. However it does not guarantee subsampling will be used. It also depends on how large the dataset is and how many iterations it's expected to run at a minimum.|\n",
"source": [ "|**iterations**|Number of iterations. Subsampling requires a lot of iterations at smaller percent so in order for subsampling to be used we need to set iterations to be a high number.|\n",
"Call the `submit` method on the experiment object and pass the run configuration. Execution of local runs is synchronous. Depending on the data and the number of iterations this can run for a while.\n", "|**experiment_timeout_minutes**|The experiment timeout, it's set to 5 right now to shorten the demo but it should probably be higher if we want to finish all the iterations.|\n",
"In this example, we specify `show_output = True` to print currently running iterations to the console." "\n"
] ],
}, "cell_type": "markdown"
{ },
"cell_type": "code", {
"execution_count": null, "metadata": {},
"metadata": {}, "outputs": [],
"outputs": [], "execution_count": null,
"source": [ "source": [
"local_run = experiment.submit(automl_config, show_output = True)" "automl_config = AutoMLConfig(task = 'classification',\n",
] " debug_log = 'automl_errors.log',\n",
} " primary_metric = 'accuracy',\n",
], " iterations = 85,\n",
"metadata": { " experiment_timeout_minutes = 5,\n",
"authors": [ " n_cross_validations = 2,\n",
{ " verbosity = logging.INFO,\n",
"name": "rogehe" " X = X_train, \n",
} " y = y_train,\n",
], " enable_subsampling=True,\n",
"kernelspec": { " path = project_folder)"
"display_name": "Python 3.6", ],
"language": "python", "cell_type": "code"
"name": "python36" },
}, {
"language_info": { "metadata": {},
"codemirror_mode": { "source": [
"name": "ipython", "Call the `submit` method on the experiment object and pass the run configuration. Execution of local runs is synchronous. Depending on the data and the number of iterations this can run for a while.\n",
"version": 3 "In this example, we specify `show_output = True` to print currently running iterations to the console."
}, ],
"file_extension": ".py", "cell_type": "markdown"
"mimetype": "text/x-python", },
"name": "python", {
"nbconvert_exporter": "python", "metadata": {},
"pygments_lexer": "ipython3", "outputs": [],
"version": "3.6.6" "execution_count": null,
} "source": [
}, "local_run = experiment.submit(automl_config, show_output = True)"
"nbformat": 4, ],
"nbformat_minor": 2 "cell_type": "code"
},
{
"metadata": {},
"outputs": [],
"execution_count": null,
"source": [],
"cell_type": "code"
}
],
"nbformat_minor": 2
} }

View File

@@ -1,8 +1,8 @@
name: auto-ml-subsampling-local name: auto-ml-subsampling-local
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk
- azureml-train-automl - azureml-train-automl
- azureml-widgets - azureml-widgets
- matplotlib - matplotlib
- pandas_ml - pandas_ml

View File

@@ -1,73 +1,33 @@
Azure Databricks is a managed Spark offering on Azure and customers already use it for advanced analytics. It provides a collaborative Notebook based environment with CPU or GPU based compute cluster. Azure Databricks is a managed Spark offering on Azure and customers already use it for advanced analytics. It provides a collaborative Notebook based environment with CPU or GPU based compute cluster.
In this section, you will find sample notebooks on how to use Azure Machine Learning SDK with Azure Databricks. You can train a model using Spark MLlib and then deploy the model to ACI/AKS from within Azure Databricks. You can also use Automated ML capability (**public preview**) of Azure ML SDK with Azure Databricks. In this section, you will find sample notebooks on how to use Azure Machine Learning SDK with Azure Databricks. You can train a model using Spark MLlib and then deploy the model to ACI/AKS from within Azure Databricks. You can also use Automated ML capability (**public preview**) of Azure ML SDK with Azure Databricks.
- Customers who use Azure Databricks for advanced analytics can now use the same cluster to run experiments with or without automated machine learning. - Customers who use Azure Databricks for advanced analytics can now use the same cluster to run experiments with or without automated machine learning.
- You can keep the data within the same cluster. - You can keep the data within the same cluster.
- You can leverage the local worker nodes with autoscale and auto termination capabilities. - You can leverage the local worker nodes with autoscale and auto termination capabilities.
- You can use multiple cores of your Azure Databricks cluster to perform simultenous training. - You can use multiple cores of your Azure Databricks cluster to perform simultenous training.
- You can further tune the model generated by automated machine learning if you chose to. - You can further tune the model generated by automated machine learning if you chose to.
- Every run (including the best run) is available as a pipeline, which you can tune further if needed. - Every run (including the best run) is available as a pipeline, which you can tune further if needed.
- The model trained using Azure Databricks can be registered in Azure ML SDK workspace and then deployed to Azure managed compute (ACI or AKS) using the Azure Machine learning SDK. - The model trained using Azure Databricks can be registered in Azure ML SDK workspace and then deployed to Azure managed compute (ACI or AKS) using the Azure Machine learning SDK.
Please follow our [Azure doc](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-configure-environment#azure-databricks) to install the sdk in your Azure Databricks cluster before trying any of the sample notebooks. Please follow our [Azure doc](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-configure-environment#azure-databricks) to install the sdk in your Azure Databricks cluster before trying any of the sample notebooks.
**Single file** - **Single file** -
The following archive contains all the sample notebooks. You can the run notebooks after importing [DBC](Databricks_AMLSDK_1-4_6.dbc) in your Databricks workspace instead of downloading individually. The following archive contains all the sample notebooks. You can the run notebooks after importing [DBC](Databricks_AMLSDK_1-4_6.dbc) in your Databricks workspace instead of downloading individually.
Notebooks 1-4 have to be run sequentially & are related to Income prediction experiment based on this [dataset](https://archive.ics.uci.edu/ml/datasets/adult) and demonstrate how to data prep, train and operationalize a Spark ML model with Azure ML Python SDK from within Azure Databricks. Notebooks 1-4 have to be run sequentially & are related to Income prediction experiment based on this [dataset](https://archive.ics.uci.edu/ml/datasets/adult) and demonstrate how to data prep, train and operationalize a Spark ML model with Azure ML Python SDK from within Azure Databricks.
Notebook 6 is an Automated ML sample notebook for Classification. Notebook 6 is an Automated ML sample notebook for Classification.
Learn more about [how to use Azure Databricks as a development environment](https://docs.microsoft.com/azure/machine-learning/service/how-to-configure-environment#azure-databricks) for Azure Machine Learning service. Learn more about [how to use Azure Databricks as a development environment](https://docs.microsoft.com/azure/machine-learning/service/how-to-configure-environment#azure-databricks) for Azure Machine Learning service.
**Databricks as a Compute Target from Azure ML Pipelines** **Databricks as a Compute Target from AML Pipelines**
You can use Azure Databricks as a compute target from [Azure Machine Learning Pipelines](https://docs.microsoft.com/en-us/azure/machine-learning/service/concept-ml-pipelines). Take a look at this notebook for details: [aml-pipelines-use-databricks-as-compute-target.ipynb](https://github.com/Azure/MachineLearningNotebooks/tree/master/how-to-use-azureml/azure-databricks/databricks-as-remote-compute-target/aml-pipelines-use-databricks-as-compute-target.ipynb). You can use Azure Databricks as a compute target from [Azure Machine Learning Pipelines](https://docs.microsoft.com/en-us/azure/machine-learning/service/concept-ml-pipelines). Take a look at this notebook for details: [aml-pipelines-use-databricks-as-compute-target.ipynb](https://github.com/Azure/MachineLearningNotebooks/tree/master/how-to-use-azureml/azure-databricks/databricks-as-remote-compute-target/aml-pipelines-use-databricks-as-compute-target.ipynb).
# Linked Azure Databricks and Azure Machine Learning Workspaces (Preview) For more on SDK concepts, please refer to [notebooks](https://github.com/Azure/MachineLearningNotebooks).
Customers can now link Azure Databricks and AzureML Workspaces to better enable cross-Azure ML scenarios by [managing their tracking data in a single place when using the MLflow client](https://mlflow.org/docs/latest/tracking.html#mlflow-tracking) - the Azure ML workspace.
**Please let us know your feedback.**
## Linking the Workspaces (Admin operation)
1. The Azure Databricks Azure portal blade now includes a new button to link an Azure ML workspace.
![New ADB Portal Link button](./img/adb-link-button.png) ![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/azure-databricks/README.png)
2. Both a new or existing Azure ML Workspace can be linked in the resulting prompt. Follow any instructions to set up the Azure ML Workspace.
![Link Prompt](./img/link-prompt.png)
3. After a successful link operation, you should see the Azure Databricks overview reflect the linked status
![Linked Successfully](./img/adb-successful-link.png)
## Configure MLflow to send data to Azure ML (All roles)
1. Add azureml-mlflow as a library to any notebook or cluster that should send data to Azure ML. You can do this via:
1. [DBUtils](https://docs.azuredatabricks.net/user-guide/dev-tools/dbutils.html#dbutils-library)
```
dbutils.library.installPyPI("azureml-mlflow")
dbutils.library.restartPython() # Removes Python state
```
2. [Cluster Libraries](https://docs.azuredatabricks.net/user-guide/libraries.html#install-a-library-on-a-cluster)
![Cluster Library](./img/cluster-library.png)
2. [Set the MLflow tracking URI](https://mlflow.org/docs/latest/tracking.html#where-runs-are-recorded) to the following scheme:
```
adbazureml://${azuremlRegion}.experiments.azureml.net/history/v1.0/subscriptions/${azuremlSubscriptionId}/resourceGroups/${azuremlResourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/${azuremlWorkspaceName}
```
1. You can automatically configure this on your clusters for all subsequent notebook sessions using this helper script instead of manually setting the tracking URI in the notebook:
* [AzureML Tracking Cluster Init Script](./linking/README.md)
3. If configured correctly, you'll now be able to see your MLflow tracking data in both Azure ML (via the REST API and all clients) and Azure Databricks (in the MLflow UI and using the MLflow client)
## Known Preview Limitations
While we roll this experience out to customers for feedback, there are some known limitations we'd love comments on in addition to any other issues seen in your workflow.
### 1-to-1 Workspace linking
Currently, an Azure ML Workspace can only be linked to one Azure Databricks Workspace at a time.
### Data synchronization
At the moment, data is only generated in the Azure Machine Learning workspace for tracking. Editing tags via the Azure Databricks MLflow UI won't be reflected in the Azure ML UI.
### Java and R support
The experience currently is only available from the Python MLflow client.
For more on SDK concepts, please refer to [notebooks](https://github.com/Azure/MachineLearningNotebooks).
**Please let us know your feedback.**
![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/azure-databricks/README.png)

View File

@@ -1,373 +1,380 @@
{ {
"cells": [ "metadata": {
{ "name": "build-model-run-history-03",
"cell_type": "markdown", "kernelspec": {
"metadata": {}, "display_name": "Python 3.6",
"source": [ "name": "python36",
"Azure ML & Azure Databricks notebooks by Parashar Shah.\n", "language": "python"
"\n", },
"Copyright (c) Microsoft Corporation. All rights reserved.\n", "authors": [
"\n", {
"Licensed under the MIT License." "name": "pasha"
] }
}, ],
{ "language_info": {
"cell_type": "markdown", "mimetype": "text/x-python",
"metadata": {}, "codemirror_mode": {
"source": [ "name": "ipython",
"#Model Building" "version": 3
] },
}, "pygments_lexer": "ipython3",
{ "name": "python",
"cell_type": "code", "file_extension": ".py",
"execution_count": null, "nbconvert_exporter": "python",
"metadata": {}, "version": "3.6.6"
"outputs": [], },
"source": [ "notebookId": 3836944406456339
"import os\n", },
"import pprint\n", "nbformat": 4,
"import numpy as np\n", "cells": [
"\n", {
"from pyspark.ml import Pipeline, PipelineModel\n", "metadata": {},
"from pyspark.ml.feature import OneHotEncoder, StringIndexer, VectorAssembler\n", "source": [
"from pyspark.ml.classification import LogisticRegression\n", "Azure ML & Azure Databricks notebooks by Parashar Shah.\n",
"from pyspark.ml.evaluation import BinaryClassificationEvaluator\n", "\n",
"from pyspark.ml.tuning import CrossValidator, ParamGridBuilder" "Copyright (c) Microsoft Corporation. All rights reserved.\n",
] "\n",
}, "Licensed under the MIT License."
{ ],
"cell_type": "code", "cell_type": "markdown"
"execution_count": null, },
"metadata": {}, {
"outputs": [], "metadata": {},
"source": [ "source": [
"import azureml.core\n", "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/azure-databricks/amlsdk/build-model-run-history-03.png)"
"\n", ],
"# Check core SDK version number\n", "cell_type": "markdown"
"print(\"SDK version:\", azureml.core.VERSION)" },
] {
}, "metadata": {},
{ "source": [
"cell_type": "code", "#Model Building"
"execution_count": null, ],
"metadata": {}, "cell_type": "markdown"
"outputs": [], },
"source": [ {
"# Set auth to be used by workspace related APIs.\n", "metadata": {},
"# For automation or CI/CD ServicePrincipalAuthentication can be used.\n", "outputs": [],
"# https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.authentication.serviceprincipalauthentication?view=azure-ml-py\n", "execution_count": null,
"auth = None" "source": [
] "import os\n",
}, "import pprint\n",
{ "import numpy as np\n",
"cell_type": "code", "\n",
"execution_count": null, "from pyspark.ml import Pipeline, PipelineModel\n",
"metadata": {}, "from pyspark.ml.feature import OneHotEncoder, StringIndexer, VectorAssembler\n",
"outputs": [], "from pyspark.ml.classification import LogisticRegression\n",
"source": [ "from pyspark.ml.evaluation import BinaryClassificationEvaluator\n",
"# import the Workspace class and check the azureml SDK version\n", "from pyspark.ml.tuning import CrossValidator, ParamGridBuilder"
"from azureml.core import Workspace\n", ],
"\n", "cell_type": "code"
"ws = Workspace.from_config(auth = auth)\n", },
"print('Workspace name: ' + ws.name, \n", {
" 'Azure region: ' + ws.location, \n", "metadata": {},
" 'Subscription id: ' + ws.subscription_id, \n", "outputs": [],
" 'Resource group: ' + ws.resource_group, sep = '\\n')" "execution_count": null,
] "source": [
}, "import azureml.core\n",
{ "\n",
"cell_type": "code", "# Check core SDK version number\n",
"execution_count": null, "print(\"SDK version:\", azureml.core.VERSION)"
"metadata": {}, ],
"outputs": [], "cell_type": "code"
"source": [ },
"#get the train and test datasets\n", {
"train_data_path = \"AdultCensusIncomeTrain\"\n", "metadata": {},
"test_data_path = \"AdultCensusIncomeTest\"\n", "outputs": [],
"\n", "execution_count": null,
"train = spark.read.parquet(train_data_path)\n", "source": [
"test = spark.read.parquet(test_data_path)\n", "# Set auth to be used by workspace related APIs.\n",
"\n", "# For automation or CI/CD ServicePrincipalAuthentication can be used.\n",
"print(\"train: ({}, {})\".format(train.count(), len(train.columns)))\n", "# https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.authentication.serviceprincipalauthentication?view=azure-ml-py\n",
"print(\"test: ({}, {})\".format(test.count(), len(test.columns)))\n", "auth = None"
"\n", ],
"train.printSchema()" "cell_type": "code"
] },
}, {
{ "metadata": {},
"cell_type": "markdown", "outputs": [],
"metadata": {}, "execution_count": null,
"source": [ "source": [
"#Define Model" "# import the Workspace class and check the azureml SDK version\n",
] "from azureml.core import Workspace\n",
}, "\n",
{ "ws = Workspace.from_config(auth = auth)\n",
"cell_type": "code", "print('Workspace name: ' + ws.name, \n",
"execution_count": null, " 'Azure region: ' + ws.location, \n",
"metadata": {}, " 'Subscription id: ' + ws.subscription_id, \n",
"outputs": [], " 'Resource group: ' + ws.resource_group, sep = '\\n')"
"source": [ ],
"label = \"income\"\n", "cell_type": "code"
"dtypes = dict(train.dtypes)\n", },
"dtypes.pop(label)\n", {
"\n", "metadata": {},
"si_xvars = []\n", "outputs": [],
"ohe_xvars = []\n", "execution_count": null,
"featureCols = []\n", "source": [
"for idx,key in enumerate(dtypes):\n", "#get the train and test datasets\n",
" if dtypes[key] == \"string\":\n", "train_data_path = \"AdultCensusIncomeTrain\"\n",
" featureCol = \"-\".join([key, \"encoded\"])\n", "test_data_path = \"AdultCensusIncomeTest\"\n",
" featureCols.append(featureCol)\n", "\n",
" \n", "train = spark.read.parquet(train_data_path)\n",
" tmpCol = \"-\".join([key, \"tmp\"])\n", "test = spark.read.parquet(test_data_path)\n",
" # string-index and one-hot encode the string column\n", "\n",
" #https://spark.apache.org/docs/2.3.0/api/java/org/apache/spark/ml/feature/StringIndexer.html\n", "print(\"train: ({}, {})\".format(train.count(), len(train.columns)))\n",
" #handleInvalid: Param for how to handle invalid data (unseen labels or NULL values). \n", "print(\"test: ({}, {})\".format(test.count(), len(test.columns)))\n",
" #Options are 'skip' (filter out rows with invalid data), 'error' (throw an error), \n", "\n",
" #or 'keep' (put invalid data in a special additional bucket, at index numLabels). Default: \"error\"\n", "train.printSchema()"
" si_xvars.append(StringIndexer(inputCol=key, outputCol=tmpCol, handleInvalid=\"skip\"))\n", ],
" ohe_xvars.append(OneHotEncoder(inputCol=tmpCol, outputCol=featureCol))\n", "cell_type": "code"
" else:\n", },
" featureCols.append(key)\n", {
"\n", "metadata": {},
"# string-index the label column into a column named \"label\"\n", "source": [
"si_label = StringIndexer(inputCol=label, outputCol='label')\n", "#Define Model"
"\n", ],
"# assemble the encoded feature columns in to a column named \"features\"\n", "cell_type": "markdown"
"assembler = VectorAssembler(inputCols=featureCols, outputCol=\"features\")" },
] {
}, "metadata": {},
{ "outputs": [],
"cell_type": "code", "execution_count": null,
"execution_count": null, "source": [
"metadata": {}, "label = \"income\"\n",
"outputs": [], "dtypes = dict(train.dtypes)\n",
"source": [ "dtypes.pop(label)\n",
"from azureml.core.run import Run\n", "\n",
"from azureml.core.experiment import Experiment\n", "si_xvars = []\n",
"import numpy as np\n", "ohe_xvars = []\n",
"import os\n", "featureCols = []\n",
"import shutil\n", "for idx,key in enumerate(dtypes):\n",
"\n", " if dtypes[key] == \"string\":\n",
"model_name = \"AdultCensus_runHistory.mml\"\n", " featureCol = \"-\".join([key, \"encoded\"])\n",
"model_dbfs = os.path.join(\"/dbfs\", model_name)\n", " featureCols.append(featureCol)\n",
"run_history_name = 'spark-ml-notebook'\n", " \n",
"\n", " tmpCol = \"-\".join([key, \"tmp\"])\n",
"# start a training run by defining an experiment\n", " # string-index and one-hot encode the string column\n",
"myexperiment = Experiment(ws, \"Ignite_AI_Talk\")\n", " #https://spark.apache.org/docs/2.3.0/api/java/org/apache/spark/ml/feature/StringIndexer.html\n",
"root_run = myexperiment.start_logging()\n", " #handleInvalid: Param for how to handle invalid data (unseen labels or NULL values). \n",
"\n", " #Options are 'skip' (filter out rows with invalid data), 'error' (throw an error), \n",
"# Regularization Rates - \n", " #or 'keep' (put invalid data in a special additional bucket, at index numLabels). Default: \"error\"\n",
"regs = [0.0001, 0.001, 0.01, 0.1]\n", " si_xvars.append(StringIndexer(inputCol=key, outputCol=tmpCol, handleInvalid=\"skip\"))\n",
" \n", " ohe_xvars.append(OneHotEncoder(inputCol=tmpCol, outputCol=featureCol))\n",
"# try a bunch of regularization rate in a Logistic Regression model\n", " else:\n",
"for reg in regs:\n", " featureCols.append(key)\n",
" print(\"Regularization rate: {}\".format(reg))\n", "\n",
" # create a bunch of child runs\n", "# string-index the label column into a column named \"label\"\n",
" with root_run.child_run(\"reg-\" + str(reg)) as run:\n", "si_label = StringIndexer(inputCol=label, outputCol='label')\n",
" # create a new Logistic Regression model.\n", "\n",
" lr = LogisticRegression(regParam=reg)\n", "# assemble the encoded feature columns in to a column named \"features\"\n",
" \n", "assembler = VectorAssembler(inputCols=featureCols, outputCol=\"features\")"
" # put together the pipeline\n", ],
" pipe = Pipeline(stages=[*si_xvars, *ohe_xvars, si_label, assembler, lr])\n", "cell_type": "code"
"\n", },
" # train the model\n", {
" model_p = pipe.fit(train)\n", "metadata": {},
" \n", "outputs": [],
" # make prediction\n", "execution_count": null,
" pred = model_p.transform(test)\n", "source": [
" \n", "from azureml.core.run import Run\n",
" # evaluate. note only 2 metrics are supported out of the box by Spark ML.\n", "from azureml.core.experiment import Experiment\n",
" bce = BinaryClassificationEvaluator(rawPredictionCol='rawPrediction')\n", "import numpy as np\n",
" au_roc = bce.setMetricName('areaUnderROC').evaluate(pred)\n", "import os\n",
" au_prc = bce.setMetricName('areaUnderPR').evaluate(pred)\n", "import shutil\n",
"\n", "\n",
" print(\"Area under ROC: {}\".format(au_roc))\n", "model_name = \"AdultCensus_runHistory.mml\"\n",
" print(\"Area Under PR: {}\".format(au_prc))\n", "model_dbfs = os.path.join(\"/dbfs\", model_name)\n",
" \n", "run_history_name = 'spark-ml-notebook'\n",
" # log reg, au_roc, au_prc and feature names in run history\n", "\n",
" run.log(\"reg\", reg)\n", "# start a training run by defining an experiment\n",
" run.log(\"au_roc\", au_roc)\n", "myexperiment = Experiment(ws, \"Ignite_AI_Talk\")\n",
" run.log(\"au_prc\", au_prc)\n", "root_run = myexperiment.start_logging()\n",
" run.log_list(\"columns\", train.columns)\n", "\n",
"\n", "# Regularization Rates - \n",
" # save model\n", "regs = [0.0001, 0.001, 0.01, 0.1]\n",
" model_p.write().overwrite().save(model_name)\n", " \n",
" \n", "# try a bunch of regularization rate in a Logistic Regression model\n",
" # upload the serialized model into run history record\n", "for reg in regs:\n",
" mdl, ext = model_name.split(\".\")\n", " print(\"Regularization rate: {}\".format(reg))\n",
" model_zip = mdl + \".zip\"\n", " # create a bunch of child runs\n",
" shutil.make_archive(mdl, 'zip', model_dbfs)\n", " with root_run.child_run(\"reg-\" + str(reg)) as run:\n",
" run.upload_file(\"outputs/\" + model_name, model_zip) \n", " # create a new Logistic Regression model.\n",
" #run.upload_file(\"outputs/\" + model_name, path_or_stream = model_dbfs) #cannot deal with folders\n", " lr = LogisticRegression(regParam=reg)\n",
"\n", " \n",
" # now delete the serialized model from local folder since it is already uploaded to run history \n", " # put together the pipeline\n",
" shutil.rmtree(model_dbfs)\n", " pipe = Pipeline(stages=[*si_xvars, *ohe_xvars, si_label, assembler, lr])\n",
" os.remove(model_zip)\n", "\n",
" \n", " # train the model\n",
"# Declare run completed\n", " model_p = pipe.fit(train)\n",
"root_run.complete()\n", " \n",
"root_run_id = root_run.id\n", " # make prediction\n",
"print (\"run id:\", root_run.id)" " pred = model_p.transform(test)\n",
] " \n",
}, " # evaluate. note only 2 metrics are supported out of the box by Spark ML.\n",
{ " bce = BinaryClassificationEvaluator(rawPredictionCol='rawPrediction')\n",
"cell_type": "code", " au_roc = bce.setMetricName('areaUnderROC').evaluate(pred)\n",
"execution_count": null, " au_prc = bce.setMetricName('areaUnderPR').evaluate(pred)\n",
"metadata": {}, "\n",
"outputs": [], " print(\"Area under ROC: {}\".format(au_roc))\n",
"source": [ " print(\"Area Under PR: {}\".format(au_prc))\n",
"metrics = root_run.get_metrics(recursive=True)\n", " \n",
"best_run_id = max(metrics, key = lambda k: metrics[k]['au_roc'])\n", " # log reg, au_roc, au_prc and feature names in run history\n",
"print(best_run_id, metrics[best_run_id]['au_roc'], metrics[best_run_id]['reg'])" " run.log(\"reg\", reg)\n",
] " run.log(\"au_roc\", au_roc)\n",
}, " run.log(\"au_prc\", au_prc)\n",
{ " run.log_list(\"columns\", train.columns)\n",
"cell_type": "code", "\n",
"execution_count": null, " # save model\n",
"metadata": {}, " model_p.write().overwrite().save(model_name)\n",
"outputs": [], " \n",
"source": [ " # upload the serialized model into run history record\n",
"#Get the best run\n", " mdl, ext = model_name.split(\".\")\n",
"child_runs = {}\n", " model_zip = mdl + \".zip\"\n",
"\n", " shutil.make_archive(mdl, 'zip', model_dbfs)\n",
"for r in root_run.get_children():\n", " run.upload_file(\"outputs/\" + model_name, model_zip) \n",
" child_runs[r.id] = r\n", " #run.upload_file(\"outputs/\" + model_name, path_or_stream = model_dbfs) #cannot deal with folders\n",
" \n", "\n",
"best_run = child_runs[best_run_id]" " # now delete the serialized model from local folder since it is already uploaded to run history \n",
] " shutil.rmtree(model_dbfs)\n",
}, " os.remove(model_zip)\n",
{ " \n",
"cell_type": "code", "# Declare run completed\n",
"execution_count": null, "root_run.complete()\n",
"metadata": {}, "root_run_id = root_run.id\n",
"outputs": [], "print (\"run id:\", root_run.id)"
"source": [ ],
"#Download the model from the best run to a local folder\n", "cell_type": "code"
"best_model_file_name = \"best_model.zip\"\n", },
"best_run.download_file(name = 'outputs/' + model_name, output_file_path = best_model_file_name)" {
] "metadata": {},
}, "outputs": [],
{ "execution_count": null,
"cell_type": "markdown", "source": [
"metadata": {}, "metrics = root_run.get_metrics(recursive=True)\n",
"source": [ "best_run_id = max(metrics, key = lambda k: metrics[k]['au_roc'])\n",
"#Model Evaluation" "print(best_run_id, metrics[best_run_id]['au_roc'], metrics[best_run_id]['reg'])"
] ],
}, "cell_type": "code"
{ },
"cell_type": "code", {
"execution_count": null, "metadata": {},
"metadata": {}, "outputs": [],
"outputs": [], "execution_count": null,
"source": [ "source": [
"##unzip the model to dbfs (as load() seems to require that) and load it.\n", "#Get the best run\n",
"if os.path.isfile(model_dbfs) or os.path.isdir(model_dbfs):\n", "child_runs = {}\n",
" shutil.rmtree(model_dbfs)\n", "\n",
"shutil.unpack_archive(best_model_file_name, model_dbfs)\n", "for r in root_run.get_children():\n",
"\n", " child_runs[r.id] = r\n",
"model_p_best = PipelineModel.load(model_name)" " \n",
] "best_run = child_runs[best_run_id]"
}, ],
{ "cell_type": "code"
"cell_type": "code", },
"execution_count": null, {
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "execution_count": null,
"# make prediction\n", "source": [
"pred = model_p_best.transform(test)\n", "#Download the model from the best run to a local folder\n",
"output = pred[['hours_per_week','age','workclass','marital_status','income','prediction']]\n", "best_model_file_name = \"best_model.zip\"\n",
"display(output.limit(5))" "best_run.download_file(name = 'outputs/' + model_name, output_file_path = best_model_file_name)"
] ],
}, "cell_type": "code"
{ },
"cell_type": "code", {
"execution_count": null, "metadata": {},
"metadata": {}, "source": [
"outputs": [], "#Model Evaluation"
"source": [ ],
"# evaluate. note only 2 metrics are supported out of the box by Spark ML.\n", "cell_type": "markdown"
"bce = BinaryClassificationEvaluator(rawPredictionCol='rawPrediction')\n", },
"au_roc = bce.setMetricName('areaUnderROC').evaluate(pred)\n", {
"au_prc = bce.setMetricName('areaUnderPR').evaluate(pred)\n", "metadata": {},
"\n", "outputs": [],
"print(\"Area under ROC: {}\".format(au_roc))\n", "execution_count": null,
"print(\"Area Under PR: {}\".format(au_prc))" "source": [
] "##unzip the model to dbfs (as load() seems to require that) and load it.\n",
}, "if os.path.isfile(model_dbfs) or os.path.isdir(model_dbfs):\n",
{ " shutil.rmtree(model_dbfs)\n",
"cell_type": "markdown", "shutil.unpack_archive(best_model_file_name, model_dbfs)\n",
"metadata": {}, "\n",
"source": [ "model_p_best = PipelineModel.load(model_name)"
"#Model Persistence" ],
] "cell_type": "code"
}, },
{ {
"cell_type": "code", "metadata": {},
"execution_count": null, "outputs": [],
"metadata": {}, "execution_count": null,
"outputs": [], "source": [
"source": [ "# make prediction\n",
"##NOTE: by default the model is saved to and loaded from /dbfs/ instead of cwd!\n", "pred = model_p_best.transform(test)\n",
"model_p_best.write().overwrite().save(model_name)\n", "output = pred[['hours_per_week','age','workclass','marital_status','income','prediction']]\n",
"print(\"saved model to {}\".format(model_dbfs))" "display(output.limit(5))"
] ],
}, "cell_type": "code"
{ },
"cell_type": "code", {
"execution_count": null, "metadata": {},
"metadata": {}, "outputs": [],
"outputs": [], "execution_count": null,
"source": [ "source": [
"%sh\n", "# evaluate. note only 2 metrics are supported out of the box by Spark ML.\n",
"\n", "bce = BinaryClassificationEvaluator(rawPredictionCol='rawPrediction')\n",
"ls -la /dbfs/AdultCensus_runHistory.mml/*" "au_roc = bce.setMetricName('areaUnderROC').evaluate(pred)\n",
] "au_prc = bce.setMetricName('areaUnderPR').evaluate(pred)\n",
}, "\n",
{ "print(\"Area under ROC: {}\".format(au_roc))\n",
"cell_type": "code", "print(\"Area Under PR: {}\".format(au_prc))"
"execution_count": null, ],
"metadata": {}, "cell_type": "code"
"outputs": [], },
"source": [ {
"dbutils.notebook.exit(\"success\")" "metadata": {},
] "source": [
}, "#Model Persistence"
{ ],
"cell_type": "markdown", "cell_type": "markdown"
"metadata": {}, },
"source": [ {
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/azure-databricks/amlsdk/build-model-run-history-03.png)" "metadata": {},
] "outputs": [],
} "execution_count": null,
], "source": [
"metadata": { "##NOTE: by default the model is saved to and loaded from /dbfs/ instead of cwd!\n",
"authors": [ "model_p_best.write().overwrite().save(model_name)\n",
{ "print(\"saved model to {}\".format(model_dbfs))"
"name": "pasha" ],
} "cell_type": "code"
], },
"kernelspec": { {
"display_name": "Python 3.6", "metadata": {},
"language": "python", "outputs": [],
"name": "python36" "execution_count": null,
}, "source": [
"language_info": { "%sh\n",
"codemirror_mode": { "\n",
"name": "ipython", "ls -la /dbfs/AdultCensus_runHistory.mml/*"
"version": 3 ],
}, "cell_type": "code"
"file_extension": ".py", },
"mimetype": "text/x-python", {
"name": "python", "metadata": {},
"nbconvert_exporter": "python", "outputs": [],
"pygments_lexer": "ipython3", "execution_count": null,
"version": "3.6.6" "source": [
}, "dbutils.notebook.exit(\"success\")"
"name": "build-model-run-history-03", ],
"notebookId": 3836944406456339 "cell_type": "code"
}, },
"nbformat": 4, {
"nbformat_minor": 1 "metadata": {},
"source": [
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/azure-databricks/amlsdk/build-model-run-history-03.png)"
],
"cell_type": "markdown"
}
],
"nbformat_minor": 1
} }

View File

@@ -1,293 +1,324 @@
{ {
"cells": [ "metadata": {
{ "name": "deploy-to-aci-04",
"cell_type": "markdown", "kernelspec": {
"metadata": {}, "display_name": "Python 3.6",
"source": [ "name": "python36",
"Azure ML & Azure Databricks notebooks by Parashar Shah.\n", "language": "python"
"\n", },
"Copyright (c) Microsoft Corporation. All rights reserved.\n", "authors": [
"\n", {
"Licensed under the MIT License." "name": "pasha"
] }
}, ],
{ "language_info": {
"cell_type": "markdown", "mimetype": "text/x-python",
"metadata": {}, "codemirror_mode": {
"source": [ "name": "ipython",
"Please ensure you have run all previous notebooks in sequence before running this.\n", "version": 3
"\n", },
"Please Register Azure Container Instance(ACI) using Azure Portal: https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-supported-services#portal in your subscription before using the SDK to deploy your ML model to ACI." "pygments_lexer": "ipython3",
] "name": "python",
}, "file_extension": ".py",
{ "nbconvert_exporter": "python",
"cell_type": "code", "version": "3.6.6"
"execution_count": null, },
"metadata": {}, "notebookId": 3836944406456376
"outputs": [], },
"source": [ "nbformat": 4,
"import azureml.core\n", "cells": [
"\n", {
"# Check core SDK version number\n", "metadata": {},
"print(\"SDK version:\", azureml.core.VERSION)" "source": [
] "Azure ML & Azure Databricks notebooks by Parashar Shah.\n",
}, "\n",
{ "Copyright (c) Microsoft Corporation. All rights reserved.\n",
"cell_type": "code", "\n",
"execution_count": null, "Licensed under the MIT License."
"metadata": {}, ],
"outputs": [], "cell_type": "markdown"
"source": [ },
"# Set auth to be used by workspace related APIs.\n", {
"# For automation or CI/CD ServicePrincipalAuthentication can be used.\n", "metadata": {},
"# https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.authentication.serviceprincipalauthentication?view=azure-ml-py\n", "source": [
"auth = None" "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/azure-databricks/amlsdk/deploy-to-aci-04.png)"
] ],
}, "cell_type": "markdown"
{ },
"cell_type": "code", {
"execution_count": null, "metadata": {},
"metadata": {}, "source": [
"outputs": [], "Please ensure you have run all previous notebooks in sequence before running this.\n",
"source": [ "\n",
"from azureml.core import Workspace\n", "Please Register Azure Container Instance(ACI) using Azure Portal: https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-supported-services#portal in your subscription before using the SDK to deploy your ML model to ACI."
"\n", ],
"ws = Workspace.from_config(auth = auth)\n", "cell_type": "markdown"
"print('Workspace name: ' + ws.name, \n", },
" 'Azure region: ' + ws.location, \n", {
" 'Subscription id: ' + ws.subscription_id, \n", "metadata": {},
" 'Resource group: ' + ws.resource_group, sep = '\\n')" "outputs": [],
] "execution_count": null,
}, "source": [
{ "import azureml.core\n",
"cell_type": "code", "\n",
"execution_count": null, "# Check core SDK version number\n",
"metadata": {}, "print(\"SDK version:\", azureml.core.VERSION)"
"outputs": [], ],
"source": [ "cell_type": "code"
"##NOTE: service deployment always gets the model from the current working dir.\n", },
"import os\n", {
"\n", "metadata": {},
"model_name = \"AdultCensus_runHistory.mml\" # \n", "outputs": [],
"model_name_dbfs = os.path.join(\"/dbfs\", model_name)\n", "execution_count": null,
"\n", "source": [
"print(\"copy model from dbfs to local\")\n", "# Set auth to be used by workspace related APIs.\n",
"model_local = \"file:\" + os.getcwd() + \"/\" + model_name\n", "# For automation or CI/CD ServicePrincipalAuthentication can be used.\n",
"dbutils.fs.cp(model_name, model_local, True)" "# https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.authentication.serviceprincipalauthentication?view=azure-ml-py\n",
] "auth = None"
}, ],
{ "cell_type": "code"
"cell_type": "code", },
"execution_count": null, {
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "execution_count": null,
"#Register the model\n", "source": [
"from azureml.core.model import Model\n", "from azureml.core import Workspace\n",
"mymodel = Model.register(model_path = model_name, # this points to a local file\n", "\n",
" model_name = model_name, # this is the name the model is registered as, am using same name for both path and name. \n", "ws = Workspace.from_config(auth = auth)\n",
" description = \"ADB trained model by Parashar\",\n", "print('Workspace name: ' + ws.name, \n",
" workspace = ws)\n", " 'Azure region: ' + ws.location, \n",
"\n", " 'Subscription id: ' + ws.subscription_id, \n",
"print(mymodel.name, mymodel.description, mymodel.version)" " 'Resource group: ' + ws.resource_group, sep = '\\n')"
] ],
}, "cell_type": "code"
{ },
"cell_type": "code", {
"execution_count": null, "metadata": {},
"metadata": {}, "outputs": [],
"outputs": [], "execution_count": null,
"source": [ "source": [
"#%%writefile score_sparkml.py\n", "##NOTE: service deployment always gets the model from the current working dir.\n",
"score_sparkml = \"\"\"\n", "import os\n",
" \n", "\n",
"import json\n", "model_name = \"AdultCensus_runHistory.mml\" # \n",
" \n", "model_name_dbfs = os.path.join(\"/dbfs\", model_name)\n",
"def init():\n", "\n",
" # One-time initialization of PySpark and predictive model\n", "print(\"copy model from dbfs to local\")\n",
" import pyspark\n", "model_local = \"file:\" + os.getcwd() + \"/\" + model_name\n",
" from azureml.core.model import Model\n", "dbutils.fs.cp(model_name, model_local, True)"
" from pyspark.ml import PipelineModel\n", ],
" \n", "cell_type": "code"
" global trainedModel\n", },
" global spark\n", {
" \n", "metadata": {},
" spark = pyspark.sql.SparkSession.builder.appName(\"ADB and AML notebook by Parashar\").getOrCreate()\n", "outputs": [],
" model_name = \"{model_name}\" #interpolated\n", "execution_count": null,
" model_path = Model.get_model_path(model_name)\n", "source": [
" trainedModel = PipelineModel.load(model_path)\n", "#Register the model\n",
" \n", "from azureml.core.model import Model\n",
"def run(input_json):\n", "mymodel = Model.register(model_path = model_name, # this points to a local file\n",
" if isinstance(trainedModel, Exception):\n", " model_name = model_name, # this is the name the model is registered as, am using same name for both path and name. \n",
" return json.dumps({{\"trainedModel\":str(trainedModel)}})\n", " description = \"ADB trained model by Parashar\",\n",
" \n", " workspace = ws)\n",
" try:\n", "\n",
" sc = spark.sparkContext\n", "print(mymodel.name, mymodel.description, mymodel.version)"
" input_list = json.loads(input_json)\n", ],
" input_rdd = sc.parallelize(input_list)\n", "cell_type": "code"
" input_df = spark.read.json(input_rdd)\n", },
" \n", {
" # Compute prediction\n", "metadata": {},
" prediction = trainedModel.transform(input_df)\n", "outputs": [],
" #result = prediction.first().prediction\n", "execution_count": null,
" predictions = prediction.collect()\n", "source": [
" \n", "#%%writefile score_sparkml.py\n",
" #Get each scored result\n", "score_sparkml = \"\"\"\n",
" preds = [str(x['prediction']) for x in predictions]\n", " \n",
" result = \",\".join(preds)\n", "import json\n",
" # you can return any data type as long as it is JSON-serializable\n", " \n",
" return result.tolist()\n", "def init():\n",
" except Exception as e:\n", " # One-time initialization of PySpark and predictive model\n",
" result = str(e)\n", " import pyspark\n",
" return result\n", " from azureml.core.model import Model\n",
" \n", " from pyspark.ml import PipelineModel\n",
"\"\"\".format(model_name=model_name)\n", " \n",
" \n", " global trainedModel\n",
"exec(score_sparkml)\n", " global spark\n",
" \n", " \n",
"with open(\"score_sparkml.py\", \"w\") as file:\n", " spark = pyspark.sql.SparkSession.builder.appName(\"ADB and AML notebook by Parashar\").getOrCreate()\n",
" file.write(score_sparkml)" " model_name = \"{model_name}\" #interpolated\n",
] " model_path = Model.get_model_path(model_name)\n",
}, " trainedModel = PipelineModel.load(model_path)\n",
{ " \n",
"cell_type": "code", "def run(input_json):\n",
"execution_count": null, " if isinstance(trainedModel, Exception):\n",
"metadata": {}, " return json.dumps({{\"trainedModel\":str(trainedModel)}})\n",
"outputs": [], " \n",
"source": [ " try:\n",
"from azureml.core.conda_dependencies import CondaDependencies \n", " sc = spark.sparkContext\n",
"\n", " input_list = json.loads(input_json)\n",
"myacienv = CondaDependencies.create(conda_packages=['scikit-learn','numpy','pandas']) #showing how to add libs as an eg. - not needed for this model.\n", " input_rdd = sc.parallelize(input_list)\n",
"\n", " input_df = spark.read.json(input_rdd)\n",
"with open(\"mydeployenv.yml\",\"w\") as f:\n", " \n",
" f.write(myacienv.serialize_to_string())" " # Compute prediction\n",
] " prediction = trainedModel.transform(input_df)\n",
}, " #result = prediction.first().prediction\n",
{ " predictions = prediction.collect()\n",
"cell_type": "code", " \n",
"execution_count": null, " #Get each scored result\n",
"metadata": {}, " preds = [str(x['prediction']) for x in predictions]\n",
"outputs": [], " result = \",\".join(preds)\n",
"source": [ " # you can return any data type as long as it is JSON-serializable\n",
"#deploy to ACI\n", " return result.tolist()\n",
"from azureml.core.webservice import AciWebservice, Webservice\n", " except Exception as e:\n",
"from azureml.core.model import InferenceConfig\n", " result = str(e)\n",
"\n", " return result\n",
"myaci_config = AciWebservice.deploy_configuration(cpu_cores = 2, \n", " \n",
" memory_gb = 2, \n", "\"\"\".format(model_name=model_name)\n",
" tags = {'name':'Databricks Azure ML ACI'}, \n", " \n",
" description = 'This is for ADB and AML example.')\n", "exec(score_sparkml)\n",
"\n", " \n",
"inference_config = InferenceConfig(runtime= 'spark-py', \n", "with open(\"score_sparkml.py\", \"w\") as file:\n",
" entry_script='score_sparkml.py',\n", " file.write(score_sparkml)"
" conda_file='mydeployenv.yml')\n", ],
"\n", "cell_type": "code"
"myservice = Model.deploy(ws, 'aciws', [mymodel], inference_config, myaci_config)\n", },
"myservice.wait_for_deployment(show_output=True)" {
] "metadata": {},
}, "outputs": [],
{ "execution_count": null,
"cell_type": "code", "source": [
"execution_count": null, "from azureml.core.conda_dependencies import CondaDependencies \n",
"metadata": {}, "\n",
"outputs": [], "myacienv = CondaDependencies.create(conda_packages=['scikit-learn','numpy','pandas']) #showing how to add libs as an eg. - not needed for this model.\n",
"source": [ "\n",
"help(Webservice)" "with open(\"mydeployenv.yml\",\"w\") as f:\n",
] " f.write(myacienv.serialize_to_string())"
}, ],
{ "cell_type": "code"
"cell_type": "code", },
"execution_count": null, {
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "execution_count": null,
"# List images by ws\n", "source": [
"\n", "#deploy to ACI\n",
"for i in ContainerImage.list(workspace = ws):\n", "from azureml.core.webservice import AciWebservice, Webservice\n",
" print('{}(v.{} [{}]) stored at {} with build log {}'.format(i.name, i.version, i.creation_state, i.image_location, i.image_build_log_uri))" "\n",
] "myaci_config = AciWebservice.deploy_configuration(\n",
}, " cpu_cores = 2, \n",
{ " memory_gb = 2, \n",
"cell_type": "code", " tags = {'name':'Databricks Azure ML ACI'}, \n",
"execution_count": null, " description = 'This is for ADB and AML example. Azure Databricks & Azure ML SDK demo with ACI by Parashar.')"
"metadata": {}, ],
"outputs": [], "cell_type": "code"
"source": [ },
"#for using the Web HTTP API \n", {
"print(myservice.scoring_uri)" "metadata": {},
] "outputs": [],
}, "execution_count": null,
{ "source": [
"cell_type": "code", "# this will take 10-15 minutes to finish\n",
"execution_count": null, "\n",
"metadata": {}, "service_name = \"aciws\"\n",
"outputs": [], "runtime = \"spark-py\" \n",
"source": [ "driver_file = \"score_sparkml.py\"\n",
"import json\n", "my_conda_file = \"mydeployenv.yml\"\n",
"\n", "\n",
"#get the some sample data\n", "# image creation\n",
"test_data_path = \"AdultCensusIncomeTest\"\n", "from azureml.core.image import ContainerImage\n",
"test = spark.read.parquet(test_data_path).limit(5)\n", "myimage_config = ContainerImage.image_configuration(execution_script = driver_file, \n",
"\n", " runtime = runtime, \n",
"test_json = json.dumps(test.toJSON().collect())\n", " conda_file = my_conda_file)\n",
"\n", "\n",
"print(test_json)" "# Webservice creation\n",
] "myservice = Webservice.deploy_from_model(\n",
}, " workspace=ws, \n",
{ " name=service_name,\n",
"cell_type": "code", " deployment_config = myaci_config,\n",
"execution_count": null, " models = [mymodel],\n",
"metadata": {}, " image_config = myimage_config\n",
"outputs": [], " )\n",
"source": [ "\n",
"#using data defined above predict if income is >50K (1) or <=50K (0)\n", "myservice.wait_for_deployment(show_output=True)"
"myservice.run(input_data=test_json)" ],
] "cell_type": "code"
}, },
{ {
"cell_type": "code", "metadata": {},
"execution_count": null, "outputs": [],
"metadata": {}, "execution_count": null,
"outputs": [], "source": [
"source": [ "help(Webservice)"
"#comment to not delete the web service\n", ],
"myservice.delete()" "cell_type": "code"
] },
}, {
{ "metadata": {},
"cell_type": "markdown", "outputs": [],
"metadata": {}, "execution_count": null,
"source": [ "source": [
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/azure-databricks/amlsdk/deploy-to-aci-04.png)" "# List images by ws\n",
] "\n",
} "for i in ContainerImage.list(workspace = ws):\n",
], " print('{}(v.{} [{}]) stored at {} with build log {}'.format(i.name, i.version, i.creation_state, i.image_location, i.image_build_log_uri))"
"metadata": { ],
"authors": [ "cell_type": "code"
{ },
"name": "pasha" {
} "metadata": {},
], "outputs": [],
"kernelspec": { "execution_count": null,
"display_name": "Python 3.6", "source": [
"language": "python", "#for using the Web HTTP API \n",
"name": "python36" "print(myservice.scoring_uri)"
}, ],
"language_info": { "cell_type": "code"
"codemirror_mode": { },
"name": "ipython", {
"version": 3 "metadata": {},
}, "outputs": [],
"file_extension": ".py", "execution_count": null,
"mimetype": "text/x-python", "source": [
"name": "python", "import json\n",
"nbconvert_exporter": "python", "\n",
"pygments_lexer": "ipython3", "#get the some sample data\n",
"version": "3.6.6" "test_data_path = \"AdultCensusIncomeTest\"\n",
}, "test = spark.read.parquet(test_data_path).limit(5)\n",
"name": "deploy-to-aci-04", "\n",
"notebookId": 3836944406456376 "test_json = json.dumps(test.toJSON().collect())\n",
}, "\n",
"nbformat": 4, "print(test_json)"
"nbformat_minor": 1 ],
"cell_type": "code"
},
{
"metadata": {},
"outputs": [],
"execution_count": null,
"source": [
"#using data defined above predict if income is >50K (1) or <=50K (0)\n",
"myservice.run(input_data=test_json)"
],
"cell_type": "code"
},
{
"metadata": {},
"outputs": [],
"execution_count": null,
"source": [
"#comment to not delete the web service\n",
"myservice.delete()"
],
"cell_type": "code"
},
{
"metadata": {},
"source": [
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/azure-databricks/amlsdk/deploy-to-aci-04.png)"
],
"cell_type": "markdown"
}
],
"nbformat_minor": 1
} }

View File

@@ -1,298 +1,250 @@
{ {
"cells": [ "metadata": {
{ "name": "deploy-to-aks-existingimage-05",
"cell_type": "markdown", "kernelspec": {
"metadata": {}, "display_name": "Python 3.6",
"source": [ "name": "python36",
"Azure ML & Azure Databricks notebooks by Parashar Shah.\n", "language": "python"
"\n", },
"Copyright (c) Microsoft Corporation. All rights reserved.\n", "authors": [
"\n", {
"Licensed under the MIT License." "name": "pasha"
] }
}, ],
{ "language_info": {
"cell_type": "markdown", "mimetype": "text/x-python",
"metadata": {}, "codemirror_mode": {
"source": [ "name": "ipython",
"This notebook uses image from ACI notebook for deploying to AKS." "version": 3
] },
}, "pygments_lexer": "ipython3",
{ "name": "python",
"cell_type": "code", "file_extension": ".py",
"execution_count": null, "nbconvert_exporter": "python",
"metadata": {}, "version": "3.6.6"
"outputs": [], },
"source": [ "notebookId": 1030695628045968
"import azureml.core\n", },
"\n", "nbformat": 4,
"# Check core SDK version number\n", "cells": [
"print(\"SDK version:\", azureml.core.VERSION)" {
] "metadata": {},
}, "source": [
{ "Azure ML & Azure Databricks notebooks by Parashar Shah.\n",
"cell_type": "code", "\n",
"execution_count": null, "Copyright (c) Microsoft Corporation. All rights reserved.\n",
"metadata": {}, "\n",
"outputs": [], "Licensed under the MIT License."
"source": [ ],
"# Set auth to be used by workspace related APIs.\n", "cell_type": "markdown"
"# For automation or CI/CD ServicePrincipalAuthentication can be used.\n", },
"# https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.authentication.serviceprincipalauthentication?view=azure-ml-py\n", {
"auth = None" "metadata": {},
] "source": [
}, "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/azure-databricks/amlsdk/deploy-to-aks-existingimage-05.png)"
{ ],
"cell_type": "code", "cell_type": "markdown"
"execution_count": null, },
"metadata": {}, {
"outputs": [], "metadata": {},
"source": [ "source": [
"from azureml.core import Workspace\n", "This notebook uses image from ACI notebook for deploying to AKS."
"\n", ],
"ws = Workspace.from_config(auth = auth)\n", "cell_type": "markdown"
"print('Workspace name: ' + ws.name, \n", },
" 'Azure region: ' + ws.location, \n", {
" 'Subscription id: ' + ws.subscription_id, \n", "metadata": {},
" 'Resource group: ' + ws.resource_group, sep = '\\n')" "outputs": [],
] "execution_count": null,
}, "source": [
{ "import azureml.core\n",
"cell_type": "code", "\n",
"execution_count": null, "# Check core SDK version number\n",
"metadata": {}, "print(\"SDK version:\", azureml.core.VERSION)"
"outputs": [], ],
"source": [ "cell_type": "code"
"#Register the model\n", },
"import os\n", {
"from azureml.core.model import Model\n", "metadata": {},
"\n", "outputs": [],
"model_name = \"AdultCensus_runHistory_aks.mml\" # \n", "execution_count": null,
"model_name_dbfs = os.path.join(\"/dbfs\", model_name)\n", "source": [
"\n", "# Set auth to be used by workspace related APIs.\n",
"print(\"copy model from dbfs to local\")\n", "# For automation or CI/CD ServicePrincipalAuthentication can be used.\n",
"model_local = \"file:\" + os.getcwd() + \"/\" + model_name\n", "# https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.authentication.serviceprincipalauthentication?view=azure-ml-py\n",
"dbutils.fs.cp(model_name, model_local, True)\n", "auth = None"
"\n", ],
"mymodel = Model.register(model_path = model_name, # this points to a local file\n", "cell_type": "code"
" model_name = model_name, # this is the name the model is registered as, am using same name for both path and name. \n", },
" description = \"ADB trained model by Parashar\",\n", {
" workspace = ws)\n", "metadata": {},
"\n", "outputs": [],
"print(mymodel.name, mymodel.description, mymodel.version)" "execution_count": null,
] "source": [
}, "from azureml.core import Workspace\n",
{ "\n",
"cell_type": "code", "ws = Workspace.from_config(auth = auth)\n",
"execution_count": null, "print('Workspace name: ' + ws.name, \n",
"metadata": {}, " 'Azure region: ' + ws.location, \n",
"outputs": [], " 'Subscription id: ' + ws.subscription_id, \n",
"source": [ " 'Resource group: ' + ws.resource_group, sep = '\\n')"
"#%%writefile score_sparkml.py\n", ],
"score_sparkml = \"\"\"\n", "cell_type": "code"
" \n", },
"import json\n", {
" \n", "metadata": {},
"def init():\n", "outputs": [],
" # One-time initialization of PySpark and predictive model\n", "execution_count": null,
" import pyspark\n", "source": [
" from azureml.core.model import Model\n", "# List images by ws\n",
" from pyspark.ml import PipelineModel\n", "\n",
" \n", "from azureml.core.image import ContainerImage\n",
" global trainedModel\n", "for i in ContainerImage.list(workspace = ws):\n",
" global spark\n", " print('{}(v.{} [{}]) stored at {} with build log {}'.format(i.name, i.version, i.creation_state, i.image_location, i.image_build_log_uri))"
" \n", ],
" spark = pyspark.sql.SparkSession.builder.appName(\"ADB and AML notebook by Parashar\").getOrCreate()\n", "cell_type": "code"
" model_name = \"{model_name}\" #interpolated\n", },
" model_path = Model.get_model_path(model_name)\n", {
" trainedModel = PipelineModel.load(model_path)\n", "metadata": {},
" \n", "outputs": [],
"def run(input_json):\n", "execution_count": null,
" if isinstance(trainedModel, Exception):\n", "source": [
" return json.dumps({{\"trainedModel\":str(trainedModel)}})\n", "from azureml.core.image import Image\n",
" \n", "myimage = Image(workspace=ws, name=\"aciws\")"
" try:\n", ],
" sc = spark.sparkContext\n", "cell_type": "code"
" input_list = json.loads(input_json)\n", },
" input_rdd = sc.parallelize(input_list)\n", {
" input_df = spark.read.json(input_rdd)\n", "metadata": {},
" \n", "outputs": [],
" # Compute prediction\n", "execution_count": null,
" prediction = trainedModel.transform(input_df)\n", "source": [
" #result = prediction.first().prediction\n", "#create AKS compute\n",
" predictions = prediction.collect()\n", "#it may take 20-25 minutes to create a new cluster\n",
" \n", "\n",
" #Get each scored result\n", "from azureml.core.compute import AksCompute, ComputeTarget\n",
" preds = [str(x['prediction']) for x in predictions]\n", "\n",
" result = \",\".join(preds)\n", "# Use the default configuration (can also provide parameters to customize)\n",
" # you can return any data type as long as it is JSON-serializable\n", "prov_config = AksCompute.provisioning_configuration()\n",
" return result.tolist()\n", "\n",
" except Exception as e:\n", "aks_name = 'ps-aks-demo2' \n",
" result = str(e)\n", "\n",
" return result\n", "# Create the cluster\n",
" \n", "aks_target = ComputeTarget.create(workspace = ws, \n",
"\"\"\".format(model_name=model_name)\n", " name = aks_name, \n",
" \n", " provisioning_configuration = prov_config)\n",
"exec(score_sparkml)\n", "\n",
" \n", "aks_target.wait_for_completion(show_output = True)\n",
"with open(\"score_sparkml.py\", \"w\") as file:\n", "\n",
" file.write(score_sparkml)" "print(aks_target.provisioning_state)\n",
] "print(aks_target.provisioning_errors)"
}, ],
{ "cell_type": "code"
"cell_type": "code", },
"execution_count": null, {
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "execution_count": null,
"from azureml.core.conda_dependencies import CondaDependencies \n", "source": [
"\n", "from azureml.core.webservice import Webservice\n",
"myacienv = CondaDependencies.create(conda_packages=['scikit-learn','numpy','pandas']) #showing how to add libs as an eg. - not needed for this model.\n", "help( Webservice.deploy_from_image)"
"\n", ],
"with open(\"mydeployenv.yml\",\"w\") as f:\n", "cell_type": "code"
" f.write(myacienv.serialize_to_string())" },
] {
}, "metadata": {},
{ "outputs": [],
"cell_type": "code", "execution_count": null,
"execution_count": null, "source": [
"metadata": {}, "from azureml.core.webservice import Webservice, AksWebservice\n",
"outputs": [], "from azureml.core.image import ContainerImage\n",
"source": [ "\n",
"#create AKS compute\n", "#Set the web service configuration (using default here with app insights)\n",
"#it may take 20-25 minutes to create a new cluster\n", "aks_config = AksWebservice.deploy_configuration(enable_app_insights=True)\n",
"\n", "\n",
"from azureml.core.compute import AksCompute, ComputeTarget\n", "#unique service name\n",
"\n", "service_name ='ps-aks-service'\n",
"# Use the default configuration (can also provide parameters to customize)\n", "\n",
"prov_config = AksCompute.provisioning_configuration()\n", "# Webservice creation using single command, there is a variant to use image directly as well.\n",
"\n", "aks_service = Webservice.deploy_from_image(\n",
"aks_name = 'ps-aks-demo2' \n", " workspace=ws, \n",
"\n", " name=service_name,\n",
"# Create the cluster\n", " deployment_config = aks_config,\n",
"aks_target = ComputeTarget.create(workspace = ws, \n", " image = myimage,\n",
" name = aks_name, \n", " deployment_target = aks_target\n",
" provisioning_configuration = prov_config)\n", " )\n",
"\n", "\n",
"aks_target.wait_for_completion(show_output = True)\n", "aks_service.wait_for_deployment(show_output=True)"
"\n", ],
"print(aks_target.provisioning_state)\n", "cell_type": "code"
"print(aks_target.provisioning_errors)" },
] {
}, "metadata": {},
{ "outputs": [],
"cell_type": "code", "execution_count": null,
"execution_count": null, "source": [
"metadata": {}, "aks_service.deployment_status"
"outputs": [], ],
"source": [ "cell_type": "code"
"#deploy to AKS\n", },
"from azureml.core.webservice import AksWebservice, Webservice\n", {
"from azureml.core.model import InferenceConfig\n", "metadata": {},
"\n", "outputs": [],
"aks_config = AksWebservice.deploy_configuration(enable_app_insights=True)\n", "execution_count": null,
"\n", "source": [
"inference_config = InferenceConfig(runtime = 'spark-py', \n", "#for using the Web HTTP API \n",
" entry_script ='score_sparkml.py',\n", "print(aks_service.scoring_uri)\n",
" conda_file ='mydeployenv.yml')\n", "print(aks_service.get_keys())"
"\n", ],
"aks_service = Model.deploy(ws, 'ps-aks-service', [mymodel], inference_config, aks_config, aks_target)\n", "cell_type": "code"
"aks_service.wait_for_deployment(show_output=True)" },
] {
}, "metadata": {},
{ "outputs": [],
"cell_type": "code", "execution_count": null,
"execution_count": null, "source": [
"metadata": {}, "import json\n",
"outputs": [], "\n",
"source": [ "#get the some sample data\n",
"aks_service.deployment_status" "test_data_path = \"AdultCensusIncomeTest\"\n",
] "test = spark.read.parquet(test_data_path).limit(5)\n",
}, "\n",
{ "test_json = json.dumps(test.toJSON().collect())\n",
"cell_type": "code", "\n",
"execution_count": null, "print(test_json)"
"metadata": {}, ],
"outputs": [], "cell_type": "code"
"source": [ },
"#for using the Web HTTP API \n", {
"print(aks_service.scoring_uri)\n", "metadata": {},
"print(aks_service.get_keys())" "outputs": [],
] "execution_count": null,
}, "source": [
{ "#using data defined above predict if income is >50K (1) or <=50K (0)\n",
"cell_type": "code", "aks_service.run(input_data=test_json)"
"execution_count": null, ],
"metadata": {}, "cell_type": "code"
"outputs": [], },
"source": [ {
"import json\n", "metadata": {},
"\n", "outputs": [],
"#get the some sample data\n", "execution_count": null,
"test_data_path = \"AdultCensusIncomeTest\"\n", "source": [
"test = spark.read.parquet(test_data_path).limit(5)\n", "#comment to not delete the web service\n",
"\n", "aks_service.delete()\n",
"test_json = json.dumps(test.toJSON().collect())\n", "#image.delete()\n",
"\n", "#model.delete()\n",
"print(test_json)" "aks_target.delete() "
] ],
}, "cell_type": "code"
{ },
"cell_type": "code", {
"execution_count": null, "metadata": {},
"metadata": {}, "source": [
"outputs": [], "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/azure-databricks/amlsdk/deploy-to-aks-existingimage-05.png)"
"source": [ ],
"#using data defined above predict if income is >50K (1) or <=50K (0)\n", "cell_type": "markdown"
"aks_service.run(input_data=test_json)" }
] ],
}, "nbformat_minor": 1
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#comment to not delete the web service\n",
"aks_service.delete()\n",
"#model.delete()\n",
"aks_target.delete() "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/azure-databricks/amlsdk/deploy-to-aks-existingimage-05.png)"
]
}
],
"metadata": {
"authors": [
{
"name": "pasha"
}
],
"kernelspec": {
"display_name": "Python 3.6",
"language": "python",
"name": "python36"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.6"
},
"name": "deploy-to-aks-existingimage-05",
"notebookId": 1030695628045968
},
"nbformat": 4,
"nbformat_minor": 1
} }

View File

@@ -1,179 +1,186 @@
{ {
"cells": [ "metadata": {
{ "name": "ingest-data-02",
"cell_type": "markdown", "kernelspec": {
"metadata": {}, "display_name": "Python 3.6",
"source": [ "name": "python36",
"Azure ML & Azure Databricks notebooks by Parashar Shah.\n", "language": "python"
"\n", },
"Copyright (c) Microsoft Corporation. All rights reserved.\n", "authors": [
"\n", {
"Licensed under the MIT License." "name": "pasha"
] }
}, ],
{ "language_info": {
"cell_type": "markdown", "mimetype": "text/x-python",
"metadata": {}, "codemirror_mode": {
"source": [ "name": "ipython",
"#Data Ingestion" "version": 3
] },
}, "pygments_lexer": "ipython3",
{ "name": "python",
"cell_type": "code", "file_extension": ".py",
"execution_count": null, "nbconvert_exporter": "python",
"metadata": {}, "version": "3.6.6"
"outputs": [], },
"source": [ "notebookId": 3836944406456362
"import os\n", },
"import urllib" "nbformat": 4,
] "cells": [
}, {
{ "metadata": {},
"cell_type": "code", "source": [
"execution_count": null, "Azure ML & Azure Databricks notebooks by Parashar Shah.\n",
"metadata": {}, "\n",
"outputs": [], "Copyright (c) Microsoft Corporation. All rights reserved.\n",
"source": [ "\n",
"# Download AdultCensusIncome.csv from Azure CDN. This file has 32,561 rows.\n", "Licensed under the MIT License."
"dataurl = \"https://amldockerdatasets.azureedge.net/AdultCensusIncome.csv\"\n", ],
"datafile = \"AdultCensusIncome.csv\"\n", "cell_type": "markdown"
"datafile_dbfs = os.path.join(\"/dbfs\", datafile)\n", },
"\n", {
"if os.path.isfile(datafile_dbfs):\n", "metadata": {},
" print(\"found {} at {}\".format(datafile, datafile_dbfs))\n", "source": [
"else:\n", "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/azure-databricks/amlsdk/ingest-data-02.png)"
" print(\"downloading {} to {}\".format(datafile, datafile_dbfs))\n", ],
" urllib.request.urlretrieve(dataurl, datafile_dbfs)" "cell_type": "markdown"
] },
}, {
{ "metadata": {},
"cell_type": "code", "source": [
"execution_count": null, "#Data Ingestion"
"metadata": {}, ],
"outputs": [], "cell_type": "markdown"
"source": [ },
"# Create a Spark dataframe out of the csv file.\n", {
"data_all = sqlContext.read.format('csv').options(header='true', inferSchema='true', ignoreLeadingWhiteSpace='true', ignoreTrailingWhiteSpace='true').load(datafile)\n", "metadata": {},
"print(\"({}, {})\".format(data_all.count(), len(data_all.columns)))\n", "outputs": [],
"data_all.printSchema()" "execution_count": null,
] "source": [
}, "import os\n",
{ "import urllib"
"cell_type": "code", ],
"execution_count": null, "cell_type": "code"
"metadata": {}, },
"outputs": [], {
"source": [ "metadata": {},
"#renaming columns\n", "outputs": [],
"columns_new = [col.replace(\"-\", \"_\") for col in data_all.columns]\n", "execution_count": null,
"data_all = data_all.toDF(*columns_new)\n", "source": [
"data_all.printSchema()" "# Download AdultCensusIncome.csv from Azure CDN. This file has 32,561 rows.\n",
] "dataurl = \"https://amldockerdatasets.azureedge.net/AdultCensusIncome.csv\"\n",
}, "datafile = \"AdultCensusIncome.csv\"\n",
{ "datafile_dbfs = os.path.join(\"/dbfs\", datafile)\n",
"cell_type": "code", "\n",
"execution_count": null, "if os.path.isfile(datafile_dbfs):\n",
"metadata": {}, " print(\"found {} at {}\".format(datafile, datafile_dbfs))\n",
"outputs": [], "else:\n",
"source": [ " print(\"downloading {} to {}\".format(datafile, datafile_dbfs))\n",
"display(data_all.limit(5))" " urllib.request.urlretrieve(dataurl, datafile_dbfs)"
] ],
}, "cell_type": "code"
{ },
"cell_type": "markdown", {
"metadata": {}, "metadata": {},
"source": [ "outputs": [],
"#Data Preparation" "execution_count": null,
] "source": [
}, "# Create a Spark dataframe out of the csv file.\n",
{ "data_all = sqlContext.read.format('csv').options(header='true', inferSchema='true', ignoreLeadingWhiteSpace='true', ignoreTrailingWhiteSpace='true').load(datafile)\n",
"cell_type": "code", "print(\"({}, {})\".format(data_all.count(), len(data_all.columns)))\n",
"execution_count": null, "data_all.printSchema()"
"metadata": {}, ],
"outputs": [], "cell_type": "code"
"source": [ },
"# Choose feature columns and the label column.\n", {
"label = \"income\"\n", "metadata": {},
"xvars = set(data_all.columns) - {label}\n", "outputs": [],
"\n", "execution_count": null,
"print(\"label = {}\".format(label))\n", "source": [
"print(\"features = {}\".format(xvars))\n", "#renaming columns\n",
"\n", "columns_new = [col.replace(\"-\", \"_\") for col in data_all.columns]\n",
"data = data_all.select([*xvars, label])\n", "data_all = data_all.toDF(*columns_new)\n",
"\n", "data_all.printSchema()"
"# Split data into train and test.\n", ],
"train, test = data.randomSplit([0.75, 0.25], seed=123)\n", "cell_type": "code"
"\n", },
"print(\"train ({}, {})\".format(train.count(), len(train.columns)))\n", {
"print(\"test ({}, {})\".format(test.count(), len(test.columns)))" "metadata": {},
] "outputs": [],
}, "execution_count": null,
{ "source": [
"cell_type": "markdown", "display(data_all.limit(5))"
"metadata": {}, ],
"source": [ "cell_type": "code"
"#Data Persistence" },
] {
}, "metadata": {},
{ "source": [
"cell_type": "code", "#Data Preparation"
"execution_count": null, ],
"metadata": {}, "cell_type": "markdown"
"outputs": [], },
"source": [ {
"# Write the train and test data sets to intermediate storage\n", "metadata": {},
"train_data_path = \"AdultCensusIncomeTrain\"\n", "outputs": [],
"test_data_path = \"AdultCensusIncomeTest\"\n", "execution_count": null,
"\n", "source": [
"train_data_path_dbfs = os.path.join(\"/dbfs\", \"AdultCensusIncomeTrain\")\n", "# Choose feature columns and the label column.\n",
"test_data_path_dbfs = os.path.join(\"/dbfs\", \"AdultCensusIncomeTest\")\n", "label = \"income\"\n",
"\n", "xvars = set(data_all.columns) - {label}\n",
"train.write.mode('overwrite').parquet(train_data_path)\n", "\n",
"test.write.mode('overwrite').parquet(test_data_path)\n", "print(\"label = {}\".format(label))\n",
"print(\"train and test datasets saved to {} and {}\".format(train_data_path_dbfs, test_data_path_dbfs))" "print(\"features = {}\".format(xvars))\n",
] "\n",
}, "data = data_all.select([*xvars, label])\n",
{ "\n",
"cell_type": "code", "# Split data into train and test.\n",
"execution_count": null, "train, test = data.randomSplit([0.75, 0.25], seed=123)\n",
"metadata": {}, "\n",
"outputs": [], "print(\"train ({}, {})\".format(train.count(), len(train.columns)))\n",
"source": [] "print(\"test ({}, {})\".format(test.count(), len(test.columns)))"
}, ],
{ "cell_type": "code"
"cell_type": "markdown", },
"metadata": {}, {
"source": [ "metadata": {},
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/azure-databricks/amlsdk/ingest-data-02.png)" "source": [
] "#Data Persistence"
} ],
], "cell_type": "markdown"
"metadata": { },
"authors": [ {
{ "metadata": {},
"name": "pasha" "outputs": [],
} "execution_count": null,
], "source": [
"kernelspec": { "# Write the train and test data sets to intermediate storage\n",
"display_name": "Python 3.6", "train_data_path = \"AdultCensusIncomeTrain\"\n",
"language": "python", "test_data_path = \"AdultCensusIncomeTest\"\n",
"name": "python36" "\n",
}, "train_data_path_dbfs = os.path.join(\"/dbfs\", \"AdultCensusIncomeTrain\")\n",
"language_info": { "test_data_path_dbfs = os.path.join(\"/dbfs\", \"AdultCensusIncomeTest\")\n",
"codemirror_mode": { "\n",
"name": "ipython", "train.write.mode('overwrite').parquet(train_data_path)\n",
"version": 3 "test.write.mode('overwrite').parquet(test_data_path)\n",
}, "print(\"train and test datasets saved to {} and {}\".format(train_data_path_dbfs, test_data_path_dbfs))"
"file_extension": ".py", ],
"mimetype": "text/x-python", "cell_type": "code"
"name": "python", },
"nbconvert_exporter": "python", {
"pygments_lexer": "ipython3", "metadata": {},
"version": "3.6.6" "outputs": [],
}, "execution_count": null,
"name": "ingest-data-02", "source": [],
"notebookId": 3836944406456362 "cell_type": "code"
}, },
"nbformat": 4, {
"nbformat_minor": 1 "metadata": {},
"source": [
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/azure-databricks/amlsdk/ingest-data-02.png)"
],
"cell_type": "markdown"
}
],
"nbformat_minor": 1
} }

View File

@@ -1,183 +1,190 @@
{ {
"cells": [ "metadata": {
{ "name": "installation-and-configuration-01",
"cell_type": "markdown", "kernelspec": {
"metadata": {}, "display_name": "Python 3.6",
"source": [ "name": "python36",
"Azure ML & Azure Databricks notebooks by Parashar Shah.\n", "language": "python"
"\n", },
"Copyright (c) Microsoft Corporation. All rights reserved.\n", "authors": [
"\n", {
"Licensed under the MIT License." "name": "pasha"
] }
}, ],
{ "language_info": {
"cell_type": "markdown", "mimetype": "text/x-python",
"metadata": {}, "codemirror_mode": {
"source": [ "name": "ipython",
"We support installing AML SDK as library from GUI. When attaching a library follow this https://docs.databricks.com/user-guide/libraries.html and add the below string as your PyPi package. You can select the option to attach the library to all clusters or just one cluster.\n", "version": 3
"\n", },
"**install azureml-sdk**\n", "pygments_lexer": "ipython3",
"* Source: Upload Python Egg or PyPi\n", "name": "python",
"* PyPi Name: `azureml-sdk[databricks]`\n", "file_extension": ".py",
"* Select Install Library" "nbconvert_exporter": "python",
] "version": "3.6.6"
}, },
{ "notebookId": 3688394266452835
"cell_type": "code", },
"execution_count": null, "nbformat": 4,
"metadata": {}, "cells": [
"outputs": [], {
"source": [ "metadata": {},
"import azureml.core\n", "source": [
"\n", "Azure ML & Azure Databricks notebooks by Parashar Shah.\n",
"# Check core SDK version number - based on build number of preview/master.\n", "\n",
"print(\"SDK version:\", azureml.core.VERSION)" "Copyright (c) Microsoft Corporation. All rights reserved.\n",
] "\n",
}, "Licensed under the MIT License."
{ ],
"cell_type": "markdown", "cell_type": "markdown"
"metadata": {}, },
"source": [ {
"Please specify the Azure subscription Id, resource group name, workspace name, and the region in which you want to create the Azure Machine Learning Workspace.\n", "metadata": {},
"\n", "source": [
"You can get the value of your Azure subscription ID from the Azure Portal, and then selecting Subscriptions from the menu on the left.\n", "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/azure-databricks/amlsdk/installation-and-configuration-01.png)"
"\n", ],
"For the resource_group, use the name of the resource group that contains your Azure Databricks Workspace.\n", "cell_type": "markdown"
"\n", },
"NOTE: If you provide a resource group name that does not exist, the resource group will be automatically created. This may or may not succeed in your environment, depending on the permissions you have on your Azure Subscription." {
] "metadata": {},
}, "source": [
{ "We support installing AML SDK as library from GUI. When attaching a library follow this https://docs.databricks.com/user-guide/libraries.html and add the below string as your PyPi package. You can select the option to attach the library to all clusters or just one cluster.\n",
"cell_type": "code", "\n",
"execution_count": null, "**install azureml-sdk**\n",
"metadata": {}, "* Source: Upload Python Egg or PyPi\n",
"outputs": [], "* PyPi Name: `azureml-sdk[databricks]`\n",
"source": [ "* Select Install Library"
"# subscription_id = \"<your-subscription-id>\"\n", ],
"# resource_group = \"<your-existing-resource-group>\"\n", "cell_type": "markdown"
"# workspace_name = \"<a-new-or-existing-workspace; it is unrelated to Databricks workspace>\"\n", },
"# workspace_region = \"<your-resource group-region>\"" {
] "metadata": {},
}, "outputs": [],
{ "execution_count": null,
"cell_type": "code", "source": [
"execution_count": null, "import azureml.core\n",
"metadata": {}, "\n",
"outputs": [], "# Check core SDK version number - based on build number of preview/master.\n",
"source": [ "print(\"SDK version:\", azureml.core.VERSION)"
"# Set auth to be used by workspace related APIs.\n", ],
"# For automation or CI/CD ServicePrincipalAuthentication can be used.\n", "cell_type": "code"
"# https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.authentication.serviceprincipalauthentication?view=azure-ml-py\n", },
"auth = None" {
] "metadata": {},
}, "source": [
{ "Please specify the Azure subscription Id, resource group name, workspace name, and the region in which you want to create the Azure Machine Learning Workspace.\n",
"cell_type": "code", "\n",
"execution_count": null, "You can get the value of your Azure subscription ID from the Azure Portal, and then selecting Subscriptions from the menu on the left.\n",
"metadata": {}, "\n",
"outputs": [], "For the resource_group, use the name of the resource group that contains your Azure Databricks Workspace.\n",
"source": [ "\n",
"# import the Workspace class and check the azureml SDK version\n", "NOTE: If you provide a resource group name that does not exist, the resource group will be automatically created. This may or may not succeed in your environment, depending on the permissions you have on your Azure Subscription."
"# exist_ok checks if workspace exists or not.\n", ],
"\n", "cell_type": "markdown"
"from azureml.core import Workspace\n", },
"\n", {
"ws = Workspace.create(name = workspace_name,\n", "metadata": {},
" subscription_id = subscription_id,\n", "outputs": [],
" resource_group = resource_group, \n", "execution_count": null,
" location = workspace_region,\n", "source": [
" auth = auth,\n", "# subscription_id = \"<your-subscription-id>\"\n",
" exist_ok=True)" "# resource_group = \"<your-existing-resource-group>\"\n",
] "# workspace_name = \"<a-new-or-existing-workspace; it is unrelated to Databricks workspace>\"\n",
}, "# workspace_region = \"<your-resource group-region>\""
{ ],
"cell_type": "code", "cell_type": "code"
"execution_count": null, },
"metadata": {}, {
"outputs": [], "metadata": {},
"source": [ "outputs": [],
"#get workspace details\n", "execution_count": null,
"ws.get_details()" "source": [
] "# Set auth to be used by workspace related APIs.\n",
}, "# For automation or CI/CD ServicePrincipalAuthentication can be used.\n",
{ "# https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.authentication.serviceprincipalauthentication?view=azure-ml-py\n",
"cell_type": "code", "auth = None"
"execution_count": null, ],
"metadata": {}, "cell_type": "code"
"outputs": [], },
"source": [ {
"ws = Workspace(workspace_name = workspace_name,\n", "metadata": {},
" subscription_id = subscription_id,\n", "outputs": [],
" resource_group = resource_group,\n", "execution_count": null,
" auth = auth)\n", "source": [
"\n", "# import the Workspace class and check the azureml SDK version\n",
"# persist the subscription id, resource group name, and workspace name in aml_config/config.json.\n", "# exist_ok checks if workspace exists or not.\n",
"ws.write_config()\n", "\n",
"#if you need to give a different path/filename please use this\n", "from azureml.core import Workspace\n",
"#write_config(path=\"/databricks/driver/aml_config/\",file_name=<alias_conf.cfg>)" "\n",
] "ws = Workspace.create(name = workspace_name,\n",
}, " subscription_id = subscription_id,\n",
{ " resource_group = resource_group, \n",
"cell_type": "code", " location = workspace_region,\n",
"execution_count": null, " auth = auth,\n",
"metadata": {}, " exist_ok=True)"
"outputs": [], ],
"source": [ "cell_type": "code"
"help(Workspace)" },
] {
}, "metadata": {},
{ "outputs": [],
"cell_type": "code", "execution_count": null,
"execution_count": null, "source": [
"metadata": {}, "#get workspace details\n",
"outputs": [], "ws.get_details()"
"source": [ ],
"# import the Workspace class and check the azureml SDK version\n", "cell_type": "code"
"from azureml.core import Workspace\n", },
"\n", {
"ws = Workspace.from_config(auth = auth)\n", "metadata": {},
"#ws = Workspace.from_config(<full path>)\n", "outputs": [],
"print('Workspace name: ' + ws.name, \n", "execution_count": null,
" 'Azure region: ' + ws.location, \n", "source": [
" 'Subscription id: ' + ws.subscription_id, \n", "ws = Workspace(workspace_name = workspace_name,\n",
" 'Resource group: ' + ws.resource_group, sep = '\\n')" " subscription_id = subscription_id,\n",
] " resource_group = resource_group,\n",
}, " auth = auth)\n",
{ "\n",
"cell_type": "markdown", "# persist the subscription id, resource group name, and workspace name in aml_config/config.json.\n",
"metadata": {}, "ws.write_config()\n",
"source": [ "#if you need to give a different path/filename please use this\n",
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/azure-databricks/amlsdk/installation-and-configuration-01.png)" "#write_config(path=\"/databricks/driver/aml_config/\",file_name=<alias_conf.cfg>)"
] ],
} "cell_type": "code"
], },
"metadata": { {
"authors": [ "metadata": {},
{ "outputs": [],
"name": "pasha" "execution_count": null,
} "source": [
], "help(Workspace)"
"kernelspec": { ],
"display_name": "Python 3.6", "cell_type": "code"
"language": "python", },
"name": "python36" {
}, "metadata": {},
"language_info": { "outputs": [],
"codemirror_mode": { "execution_count": null,
"name": "ipython", "source": [
"version": 3 "# import the Workspace class and check the azureml SDK version\n",
}, "from azureml.core import Workspace\n",
"file_extension": ".py", "\n",
"mimetype": "text/x-python", "ws = Workspace.from_config(auth = auth)\n",
"name": "python", "#ws = Workspace.from_config(<full path>)\n",
"nbconvert_exporter": "python", "print('Workspace name: ' + ws.name, \n",
"pygments_lexer": "ipython3", " 'Azure region: ' + ws.location, \n",
"version": "3.6.6" " 'Subscription id: ' + ws.subscription_id, \n",
}, " 'Resource group: ' + ws.resource_group, sep = '\\n')"
"name": "installation-and-configuration-01", ],
"notebookId": 3688394266452835 "cell_type": "code"
}, },
"nbformat": 4, {
"nbformat_minor": 1 "metadata": {},
"source": [
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/azure-databricks/amlsdk/installation-and-configuration-01.png)"
],
"cell_type": "markdown"
}
],
"nbformat_minor": 1
} }

Binary file not shown.

Before

Width:  |  Height:  |  Size: 173 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 187 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 84 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 111 KiB

View File

@@ -1,56 +0,0 @@
# Adding an init script to an Azure Databricks cluster
The [azureml-cluster-init.sh](./azureml-cluster-init.sh) script configures the environment to
1. Use the configured AzureML Workspace with Workspace.from_config()
2. Set the default MLflow Tracking Server to be the AzureML managed one
Modify azureml-cluster-init.sh by providing the values for region, subscriptionId, resourceGroupName, and workspaceName of your target Azure ML workspace in the highlighted section at the top of the script.
To create the Azure Databricks cluster-scoped init script
1. Create the base directory you want to store the init script in if it does not exist.
```
dbutils.fs.mkdirs("dbfs:/databricks/<directory>/")
```
2. Create the script by copying the contents of azureml-cluster-init.sh
```
dbutils.fs.put("/databricks/<directory>/azureml-cluster-init.sh","""
<configured_contents_of_azureml-cluster-init.sh>
""", True)
3. Check that the script exists.
```
display(dbutils.fs.ls("dbfs:/databricks/<directory>/azureml-cluster-init.sh"))
```
1. Configure the cluster to run the script.
* Using the cluster configuration page
1. On the cluster configuration page, click the Advanced Options toggle.
1. At the bottom of the page, click the Init Scripts tab.
1. In the Destination drop-down, select a destination type. Example: 'DBFS'
1. Specify a path to the init script.
```
dbfs:/databricks/<directory>/azureml-cluster-init.sh
```
1. Click Add
* Using the API.
```
curl -n -X POST -H 'Content-Type: application/json' -d '{
"cluster_id": "<cluster_id>",
"num_workers": <num_workers>,
"spark_version": "<spark_version>",
"node_type_id": "<node_type_id>",
"cluster_log_conf": {
"dbfs" : {
"destination": "dbfs:/cluster-logs"
}
},
"init_scripts": [ {
"dbfs": {
"destination": "dbfs:/databricks/<directory>/azureml-cluster-init.sh"
}
} ]
}' https://<databricks-instance>/api/2.0/clusters/edit
```

View File

@@ -1,24 +0,0 @@
#!/bin/bash
# This script configures the environment to
# 1. Use the configured AzureML Workspace with azureml.core.Workspace.from_config()
# 2. Set the default MLflow Tracking Server to be the AzureML managed one
############## START CONFIGURATION #################
# Provide the required *AzureML* workspace information
region="" # example: westus2
subscriptionId="" # example: bcb65f42-f234-4bff-91cf-9ef816cd9936
resourceGroupName="" # example: dev-rg
workspaceName="" # example: myazuremlws
# Optional config directory
configLocation="/databricks/config.json"
############### END CONFIGURATION #################
# Drop the workspace configuration on the cluster
sudo touch $configLocation
sudo echo {\\"subscription_id\\": \\"${subscriptionId}\\", \\"resource_group\\": \\"${resourceGroupName}\\", \\"workspace_name\\": \\"${workspaceName}\\"} > $configLocation
# Set the MLflow Tracking URI
trackingUri="adbazureml://${region}.experiments.azureml.net/history/v1.0/subscriptions/${subscriptionId}/resourceGroups/${resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/${workspaceName}"
sudo echo export MLFLOW_TRACKING_URI=${trackingUri} >> /databricks/spark/conf/spark-env.sh

View File

@@ -1,336 +1,289 @@
{ {
"cells": [ "metadata": {
{ "kernelspec": {
"cell_type": "markdown", "display_name": "Python 3.6",
"metadata": {}, "name": "python36",
"source": [ "language": "python"
"Copyright (c) Microsoft Corporation. All rights reserved.\n", },
"\n", "authors": [
"Licensed under the MIT License." {
] "name": "aashishb"
}, }
{ ],
"cell_type": "markdown", "language_info": {
"metadata": {}, "mimetype": "text/x-python",
"source": [ "codemirror_mode": {
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/deployment/deploy-to-cloud/model-register-and-deploy.png)" "name": "ipython",
] "version": 3
}, },
{ "pygments_lexer": "ipython3",
"cell_type": "markdown", "name": "python",
"metadata": {}, "file_extension": ".py",
"source": [ "nbconvert_exporter": "python",
"# Register Model and deploy as Webservice\n", "version": "3.7.0"
"\n", }
"This example shows how to deploy a Webservice in step-by-step fashion:\n", },
"\n", "nbformat": 4,
" 1. Register Model\n", "cells": [
" 2. Deploy Model as Webservice" {
] "metadata": {},
}, "source": [
{ "Copyright (c) Microsoft Corporation. All rights reserved.\n",
"cell_type": "markdown", "\n",
"metadata": {}, "Licensed under the MIT License."
"source": [ ],
"## Prerequisites\n", "cell_type": "markdown"
"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": {},
{ "source": [
"cell_type": "code", "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/deploy-to-cloud/model-register-and-deploy.png)"
"execution_count": null, ],
"metadata": {}, "cell_type": "markdown"
"outputs": [], },
"source": [ {
"# Check core SDK version number\n", "metadata": {},
"import azureml.core\n", "source": [
"\n", "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/deploy-to-cloud/model-register-and-deploy.png)"
"print(\"SDK version:\", azureml.core.VERSION)" ],
] "cell_type": "markdown"
}, },
{ {
"cell_type": "markdown", "metadata": {},
"metadata": {}, "source": [
"source": [ "# Register Model and deploy as Webservice\n",
"## Initialize Workspace\n", "\n",
"\n", "This example shows how to deploy a Webservice in step-by-step fashion:\n",
"Initialize a workspace object from persisted configuration." "\n",
] " 1. Register Model\n",
}, " 2. Deploy Model as Webservice"
{ ],
"cell_type": "code", "cell_type": "markdown"
"execution_count": null, },
"metadata": { {
"tags": [ "metadata": {},
"create workspace" "source": [
] "## 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."
"outputs": [], ],
"source": [ "cell_type": "markdown"
"from azureml.core import Workspace\n", },
"\n", {
"ws = Workspace.from_config()\n", "metadata": {},
"print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep='\\n')" "outputs": [],
] "execution_count": null,
}, "source": [
{ "# Check core SDK version number\n",
"cell_type": "markdown", "import azureml.core\n",
"metadata": {}, "\n",
"source": [ "print(\"SDK version:\", azureml.core.VERSION)"
"### Register Model" ],
] "cell_type": "code"
}, },
{ {
"cell_type": "markdown", "metadata": {},
"metadata": {}, "source": [
"source": [ "## Initialize Workspace\n",
"You can add tags and descriptions to your Models. Note you need to have a `sklearn_regression_model.pkl` file in the current directory. This file is generated by the 01 notebook. The below call registers that file as a Model with the same name `sklearn_regression_model.pkl` in the workspace.\n", "\n",
"\n", "Initialize a workspace object from persisted configuration."
"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." ],
] "cell_type": "markdown"
}, },
{ {
"cell_type": "code", "metadata": {
"execution_count": null, "tags": [
"metadata": { "create workspace"
"tags": [ ]
"register model from file" },
] "outputs": [],
}, "execution_count": null,
"outputs": [], "source": [
"source": [ "from azureml.core import Workspace\n",
"from azureml.core.model import Model\n", "\n",
"\n", "ws = Workspace.from_config()\n",
"model = Model.register(model_path=\"sklearn_regression_model.pkl\",\n", "print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep = '\\n')"
" model_name=\"sklearn_regression_model.pkl\",\n", ],
" tags={'area': \"diabetes\", 'type': \"regression\"},\n", "cell_type": "code"
" description=\"Ridge regression model to predict diabetes\",\n", },
" workspace=ws)" {
] "metadata": {},
}, "source": [
{ "### Register Model"
"cell_type": "markdown", ],
"metadata": {}, "cell_type": "markdown"
"source": [ },
"### Create Environment" {
] "metadata": {},
}, "source": [
{ "You can add tags and descriptions to your Models. Note you need to have a `sklearn_regression_model.pkl` file in the current directory. This file is generated by the 01 notebook. The below call registers that file as a Model with the same name `sklearn_regression_model.pkl` in the workspace.\n",
"cell_type": "markdown", "\n",
"metadata": {}, "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."
"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. Only Environments that were created using azureml-defaults version 1.0.48 or later will work with this new handling however.\n", "cell_type": "markdown"
"\n", },
"More information can be found in our [using environments notebook](../training/using-environments/using-environments.ipynb)." {
] "metadata": {
}, "tags": [
{ "register model from file"
"cell_type": "code", ]
"execution_count": null, },
"metadata": {}, "outputs": [],
"outputs": [], "execution_count": null,
"source": [ "source": [
"from azureml.core import Environment\n", "from azureml.core.model import Model\n",
"\n", "\n",
"env = Environment.from_conda_specification(name='deploytocloudenv', file_path='myenv.yml')\n", "model = Model.register(model_path = \"sklearn_regression_model.pkl\",\n",
"\n", " model_name = \"sklearn_regression_model.pkl\",\n",
"# This is optional at this point\n", " tags = {'area': \"diabetes\", 'type': \"regression\"},\n",
"# env.register(workspace=ws)" " description = \"Ridge regression model to predict diabetes\",\n",
] " workspace = ws)"
}, ],
{ "cell_type": "code"
"cell_type": "markdown", },
"metadata": {}, {
"source": [ "metadata": {},
"## Create Inference Configuration\n", "source": [
"\n", "## Create Inference Configuration\n",
"There is now support for a source directory, you can upload an entire folder from your local machine as dependencies for the Webservice.\n", "\n",
"Note: in that case, your entry_script, conda_file, and extra_docker_file_steps paths are relative paths to the source_directory path.\n", "There is now support for a source directory, you can upload an entire folder from your local machine as dependencies for the Webservice.\n",
"\n", "Note: in that case, your entry_script, conda_file, and extra_docker_file_steps paths are relative paths to the source_directory path.\n",
"Sample code for using a source directory:\n", "\n",
"\n", "Sample code for using a source directory:\n",
"```python\n", "\n",
"inference_config = InferenceConfig(source_directory=\"C:/abc\",\n", "```python\n",
" runtime= \"python\", \n", "inference_config = InferenceConfig(source_directory=\"C:/abc\",\n",
" entry_script=\"x/y/score.py\",\n", " runtime= \"python\", \n",
" conda_file=\"env/myenv.yml\", \n", " entry_script=\"x/y/score.py\",\n",
" extra_docker_file_steps=\"helloworld.txt\")\n", " conda_file=\"env/myenv.yml\", \n",
"```\n", " extra_docker_file_steps=\"helloworld.txt\")\n",
"\n", "```\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", "\n",
" - runtime = Which runtime to use for the image. Current supported runtimes are 'spark-py' and 'python\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", " - runtime = Which runtime to use for the image. Current supported runtimes are 'spark-py' and 'python\n",
" - conda_file = manages conda and python package dependencies.\n", " - entry_script = contains logic specific to initializing your model and running predictions\n",
" - extra_docker_file_steps = optional: any extra steps you want to inject into docker file" " - conda_file = manages conda and python package dependencies.\n",
] " - extra_docker_file_steps = optional: any extra steps you want to inject into docker file"
}, ],
{ "cell_type": "markdown"
"cell_type": "code", },
"execution_count": null, {
"metadata": { "metadata": {
"tags": [ "tags": [
"create image" "create image"
] ]
}, },
"outputs": [], "outputs": [],
"source": [ "execution_count": null,
"from azureml.core.model import InferenceConfig\n", "source": [
"\n", "from azureml.core.model import InferenceConfig\n",
"inference_config = InferenceConfig(entry_script=\"score.py\", environment=env)" "\n",
] "inference_config = InferenceConfig(runtime= \"python\", \n",
}, " entry_script=\"score.py\",\n",
{ " conda_file=\"myenv.yml\", \n",
"cell_type": "markdown", " extra_docker_file_steps=\"helloworld.txt\")"
"metadata": {}, ],
"source": [ "cell_type": "code"
"### Deploy Model as Webservice on Azure Container Instance\n", },
"\n", {
"Note that the service creation can take few minutes." "metadata": {},
] "source": [
}, "### Deploy Model as Webservice on Azure Container Instance\n",
{ "\n",
"cell_type": "code", "Note that the service creation can take few minutes."
"execution_count": null, ],
"metadata": { "cell_type": "markdown"
"tags": [ },
"azuremlexception-remarks-sample" {
] "metadata": {},
}, "outputs": [],
"outputs": [], "execution_count": null,
"source": [ "source": [
"from azureml.core.webservice import AciWebservice, Webservice\n", "from azureml.core.webservice import AciWebservice, Webservice\n",
"from azureml.exceptions import WebserviceException\n", "from azureml.exceptions import WebserviceException\n",
"\n", "\n",
"deployment_config = AciWebservice.deploy_configuration(cpu_cores=1, memory_gb=1)\n", "deployment_config = AciWebservice.deploy_configuration(cpu_cores = 1, memory_gb = 1)\n",
"aci_service_name = 'aciservice1'\n", "aci_service_name = 'aciservice1'\n",
"\n", "\n",
"try:\n", "try:\n",
" # if you want to get existing service below is the command\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", " # 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", " # we use aci_service_name to create azure aci\n",
" service = Webservice(ws, name=aci_service_name)\n", " service = Webservice(ws, name=aci_service_name)\n",
" if service:\n", " if service:\n",
" service.delete()\n", " service.delete()\n",
"except WebserviceException as e:\n", "except WebserviceException as e:\n",
" print()\n", " print()\n",
"\n", "\n",
"service = Model.deploy(ws, aci_service_name, [model], inference_config, deployment_config)\n", "service = Model.deploy(ws, aci_service_name, [model], inference_config, deployment_config)\n",
"\n", "\n",
"service.wait_for_deployment(True)\n", "service.wait_for_deployment(True)\n",
"print(service.state)" "print(service.state)"
] ],
}, "cell_type": "code"
{ },
"cell_type": "markdown", {
"metadata": {}, "metadata": {},
"source": [ "source": [
"#### Test web service" "#### Test web service"
] ],
}, "cell_type": "markdown"
{ },
"cell_type": "code", {
"execution_count": null, "metadata": {},
"metadata": {}, "outputs": [],
"outputs": [], "execution_count": null,
"source": [ "source": [
"import json\n", "import json\n",
"test_sample = json.dumps({'data': [\n", "test_sample = json.dumps({'data': [\n",
" [1,2,3,4,5,6,7,8,9,10], \n", " [1,2,3,4,5,6,7,8,9,10], \n",
" [10,9,8,7,6,5,4,3,2,1]\n", " [10,9,8,7,6,5,4,3,2,1]\n",
"]})\n", "]})\n",
"\n", "\n",
"test_sample_encoded = bytes(test_sample, encoding='utf8')\n", "test_sample_encoded = bytes(test_sample,encoding = 'utf8')\n",
"prediction = service.run(input_data=test_sample_encoded)\n", "prediction = service.run(input_data=test_sample_encoded)\n",
"print(prediction)" "print(prediction)"
] ],
}, "cell_type": "code"
{ },
"cell_type": "markdown", {
"metadata": {}, "metadata": {},
"source": [ "source": [
"#### Delete ACI to clean up" "#### Delete ACI to clean up"
] ],
}, "cell_type": "markdown"
{ },
"cell_type": "code", {
"execution_count": null, "metadata": {
"metadata": { "tags": [
"tags": [ "deploy service",
"deploy service", "aci"
"aci" ]
] },
}, "outputs": [],
"outputs": [], "execution_count": null,
"source": [ "source": [
"service.delete()" "service.delete()"
] ],
}, "cell_type": "code"
{ },
"cell_type": "markdown", {
"metadata": {}, "metadata": {},
"source": [ "source": [
"### Model Profiling\n", "### Model Profiling\n",
"\n", "\n",
"You can also take advantage of the profiling feature to estimate CPU and memory requirements for models.\n", "you can also take advantage of profiling feature for model\n",
"\n", "\n",
"```python\n", "```python\n",
"profile = Model.profile(ws, \"profilename\", [model], inference_config, test_sample)\n", "\n",
"profile.wait_for_profiling(True)\n", "profile = model.profile(ws, \"profilename\", [model], inference_config, test_sample)\n",
"profiling_results = profile.get_results()\n", "profile.wait_for_profiling(True)\n",
"print(profiling_results)\n", "profiling_results = profile.get_results()\n",
"```" "print(profiling_results)\n",
] "\n",
}, "```"
{ ],
"cell_type": "markdown", "cell_type": "markdown"
"metadata": {}, }
"source": [ ],
"### Model Packaging\n", "nbformat_minor": 2
"\n",
"If you want to build a Docker image that encapsulates your model and its dependencies, you can use the model packaging option. The output image will be pushed to your workspace's ACR.\n",
"\n",
"You must include an Environment object in your inference configuration to use `Model.package()`.\n",
"\n",
"```python\n",
"package = Model.package(ws, [model], inference_config)\n",
"package.wait_for_creation(show_output=True) # Or show_output=False to hide the Docker build logs.\n",
"package.pull()\n",
"```\n",
"\n",
"Instead of a fully-built image, you can also generate a Dockerfile and download all the assets needed to build an image on top of your Environment.\n",
"\n",
"```python\n",
"package = Model.package(ws, [model], inference_config, generate_dockerfile=True)\n",
"package.wait_for_creation(show_output=True)\n",
"package.save(\"./local_context_dir\")\n",
"```"
]
}
],
"metadata": {
"authors": [
{
"name": "aashishb"
}
],
"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.7.0"
}
},
"nbformat": 4,
"nbformat_minor": 2
} }

View File

@@ -1,4 +1,4 @@
name: model-register-and-deploy name: model-register-and-deploy
dependencies: dependencies:
- pip: - pip:
- azureml-sdk - azureml-sdk

Some files were not shown because too many files have changed in this diff Show More