mirror of
https://github.com/Azure/MachineLearningNotebooks.git
synced 2025-12-20 17:45:10 -05:00
Compare commits
179 Commits
azureml-sd
...
shwinne1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cf0490ab92 | ||
|
|
9f0e817c70 | ||
|
|
a4d713d19b | ||
|
|
91a20a0ff9 | ||
|
|
a0c510bf42 | ||
|
|
116d57c012 | ||
|
|
660708db63 | ||
|
|
206df82f9b | ||
|
|
7cfb2da5b8 | ||
|
|
e5adb4af3a | ||
|
|
b849267220 | ||
|
|
9891080b70 | ||
|
|
2974e86aa0 | ||
|
|
0a18161193 | ||
|
|
c676cc9969 | ||
|
|
50f4bc9643 | ||
|
|
f3c7072735 | ||
|
|
44295d9e16 | ||
|
|
710fc0bb4b | ||
|
|
c44dba427f | ||
|
|
8066a9263c | ||
|
|
054aadffed | ||
|
|
8f418b216d | ||
|
|
2d549ecad3 | ||
|
|
4dbb024529 | ||
|
|
142a1a510e | ||
|
|
2522486c26 | ||
|
|
6d5226e47c | ||
|
|
e7676d7cdc | ||
|
|
a84f6636f1 | ||
|
|
41be10d1c1 | ||
|
|
429eb43914 | ||
|
|
c0dae0c645 | ||
|
|
e4d9a2b4c5 | ||
|
|
7648e8f516 | ||
|
|
b5ed94b4eb | ||
|
|
85e487f74f | ||
|
|
c0a5b2de79 | ||
|
|
0a9e076e5f | ||
|
|
e3b974811d | ||
|
|
381d1a6f35 | ||
|
|
adaa55675e | ||
|
|
5e3c592d4b | ||
|
|
9c6f1e2571 | ||
|
|
bd1bedd563 | ||
|
|
9716f3614e | ||
|
|
d2c72ca149 | ||
|
|
4f62f64207 | ||
|
|
16473eb33e | ||
|
|
d10474c249 | ||
|
|
6389cc16f9 | ||
|
|
bc0a8e0152 | ||
|
|
39384aea52 | ||
|
|
5bf4b0bafe | ||
|
|
f22adb7949 | ||
|
|
8409ab7133 | ||
|
|
32acd55774 | ||
|
|
7f65c1a255 | ||
|
|
bc7ccc7ef3 | ||
|
|
1cc79a71e9 | ||
|
|
c0bec5f110 | ||
|
|
77e5664482 | ||
|
|
e2eb64372a | ||
|
|
03cbb6a3a2 | ||
|
|
44d3d998a8 | ||
|
|
c626f37057 | ||
|
|
0175574864 | ||
|
|
f6e8d57da3 | ||
|
|
01cd31ce44 | ||
|
|
eb2024b3e0 | ||
|
|
6bce41b3d7 | ||
|
|
bbdabbb552 | ||
|
|
65343fc263 | ||
|
|
b6b27fded6 | ||
|
|
7e492cbeb6 | ||
|
|
4cc8f4c6af | ||
|
|
9fba46821b | ||
|
|
a45954a58f | ||
|
|
f16dfb0e5b | ||
|
|
edabbf9031 | ||
|
|
63d1d57dfb | ||
|
|
10f7004161 | ||
|
|
86ba4e7406 | ||
|
|
33bda032b8 | ||
|
|
0fd4bfbc56 | ||
|
|
3fe08c944e | ||
|
|
d587ea5676 | ||
|
|
edd8562102 | ||
|
|
5ac2c63336 | ||
|
|
1f4e4cdda2 | ||
|
|
2e245c1691 | ||
|
|
e1b09f71fa | ||
|
|
8e2220d397 | ||
|
|
f74ccf5048 | ||
|
|
97a6d9ca43 | ||
|
|
a0ff1c6b64 | ||
|
|
08f15ef4cf | ||
|
|
7160416c0b | ||
|
|
218fed3d65 | ||
|
|
b8499dfb98 | ||
|
|
6bfd472cc2 | ||
|
|
ecefb229e9 | ||
|
|
883ad806ba | ||
|
|
848b5bc302 | ||
|
|
58087b53a0 | ||
|
|
ff4d5450a7 | ||
|
|
e2b2b89842 | ||
|
|
390be2ba24 | ||
|
|
cd1258f81d | ||
|
|
8a0b48ea48 | ||
|
|
b0dc904189 | ||
|
|
82bede239a | ||
|
|
774517e173 | ||
|
|
c3ce2bc7fe | ||
|
|
5dd09a1f7c | ||
|
|
ee1da0ee19 | ||
|
|
ddfce6b24c | ||
|
|
31dfc3dc55 | ||
|
|
168c45b188 | ||
|
|
159948db67 | ||
|
|
d842731a3b | ||
|
|
7822fd4c13 | ||
|
|
d9fbe4cd87 | ||
|
|
a64f4d331a | ||
|
|
c41f449208 | ||
|
|
4fe8c1702d | ||
|
|
18cd152591 | ||
|
|
4170a394ed | ||
|
|
475ea36106 | ||
|
|
9e0fc4f0e7 | ||
|
|
b025816c92 | ||
|
|
c75e820107 | ||
|
|
e97e4742ba | ||
|
|
14ecfb0bf3 | ||
|
|
61b396be4f | ||
|
|
3d2552174d | ||
|
|
cd3c980a6e | ||
|
|
249bcac3c7 | ||
|
|
4a6bcebccc | ||
|
|
56e0ebc5ac | ||
|
|
2aa39f2f4a | ||
|
|
4d247c1877 | ||
|
|
f6682f6f6d | ||
|
|
26ecf25233 | ||
|
|
44c3a486c0 | ||
|
|
c574f429b8 | ||
|
|
77d557a5dc | ||
|
|
13dedec4a4 | ||
|
|
6f5c52676f | ||
|
|
90c105537c | ||
|
|
ef264b1073 | ||
|
|
824ac5e021 | ||
|
|
e9a7b95716 | ||
|
|
789ee26357 | ||
|
|
fc541706e7 | ||
|
|
64b8aa2a55 | ||
|
|
d3dc35dbb6 | ||
|
|
b55ac368e7 | ||
|
|
de162316d7 | ||
|
|
4ecc58dfe2 | ||
|
|
daf27a76e4 | ||
|
|
a05444845b | ||
|
|
79c9f50c15 | ||
|
|
67e10e0f6b | ||
|
|
1ef0331a0f | ||
|
|
5e91c836b9 | ||
|
|
661762854a | ||
|
|
fbc90ba74f | ||
|
|
0d9c83d0a8 | ||
|
|
ca4cab1de9 | ||
|
|
ddbb3c45f6 | ||
|
|
8eed4e39d0 | ||
|
|
b37c0297db | ||
|
|
968cc798d0 | ||
|
|
5c9ca452fb | ||
|
|
5e82680272 | ||
|
|
41841fc8c0 | ||
|
|
896bf63736 | ||
|
|
d4751bf6ec |
30
.github/ISSUE_TEMPLATE/bug_report.md
vendored
Normal file
30
.github/ISSUE_TEMPLATE/bug_report.md
vendored
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
---
|
||||||
|
name: Bug report
|
||||||
|
about: Create a report to help us improve
|
||||||
|
title: "[Notebook issue]"
|
||||||
|
labels: ''
|
||||||
|
assignees: ''
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Describe the bug**
|
||||||
|
A clear and concise description of what the bug is.
|
||||||
|
|
||||||
|
Provide the following if applicable:
|
||||||
|
+ Your Python & SDK version
|
||||||
|
+ Python Scripts or the full notebook name
|
||||||
|
+ Pipeline definition
|
||||||
|
+ Environment definition
|
||||||
|
+ Example data
|
||||||
|
+ Any log files.
|
||||||
|
+ Run and Workspace Id
|
||||||
|
|
||||||
|
**To Reproduce**
|
||||||
|
Steps to reproduce the behavior:
|
||||||
|
1.
|
||||||
|
|
||||||
|
**Expected behavior**
|
||||||
|
A clear and concise description of what you expected to happen.
|
||||||
|
|
||||||
|
**Additional context**
|
||||||
|
Add any other context about the problem here.
|
||||||
30
.github/ISSUE_TEMPLATE/notebook-issue.md
vendored
Normal file
30
.github/ISSUE_TEMPLATE/notebook-issue.md
vendored
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
---
|
||||||
|
name: Notebook issue
|
||||||
|
about: Create a report to help us improve
|
||||||
|
title: "[Notebook issue]"
|
||||||
|
labels: ''
|
||||||
|
assignees: ''
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Describe the bug**
|
||||||
|
A clear and concise description of what the bug is.
|
||||||
|
|
||||||
|
Provide the following if applicable:
|
||||||
|
+ Your Python & SDK version
|
||||||
|
+ Python Scripts or the full notebook name
|
||||||
|
+ Pipeline definition
|
||||||
|
+ Environment definition
|
||||||
|
+ Example data
|
||||||
|
+ Any log files.
|
||||||
|
+ Run and Workspace Id
|
||||||
|
|
||||||
|
**To Reproduce**
|
||||||
|
Steps to reproduce the behavior:
|
||||||
|
1.
|
||||||
|
|
||||||
|
**Expected behavior**
|
||||||
|
A clear and concise description of what you expected to happen.
|
||||||
|
|
||||||
|
**Additional context**
|
||||||
|
Add any other context about the problem here.
|
||||||
29
Dockerfiles/1.0.41/Dockerfile
Normal file
29
Dockerfiles/1.0.41/Dockerfile
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
FROM continuumio/miniconda:4.5.11
|
||||||
|
|
||||||
|
# install git
|
||||||
|
RUN apt-get update && apt-get upgrade -y && apt-get install -y git
|
||||||
|
|
||||||
|
# create a new conda environment named azureml
|
||||||
|
RUN conda create -n azureml -y -q Python=3.6
|
||||||
|
|
||||||
|
# install additional packages used by sample notebooks. this is optional
|
||||||
|
RUN ["/bin/bash", "-c", "source activate azureml && conda install -y tqdm cython matplotlib scikit-learn"]
|
||||||
|
|
||||||
|
# install azurmel-sdk components
|
||||||
|
RUN ["/bin/bash", "-c", "source activate azureml && pip install azureml-sdk[notebooks]==1.0.41"]
|
||||||
|
|
||||||
|
# clone Azure ML GitHub sample notebooks
|
||||||
|
RUN cd /home && git clone -b "azureml-sdk-1.0.41" --single-branch https://github.com/Azure/MachineLearningNotebooks.git
|
||||||
|
|
||||||
|
# generate jupyter configuration file
|
||||||
|
RUN ["/bin/bash", "-c", "source activate azureml && mkdir ~/.jupyter && cd ~/.jupyter && jupyter notebook --generate-config"]
|
||||||
|
|
||||||
|
# set an emtpy token for Jupyter to remove authentication.
|
||||||
|
# this is NOT recommended for production environment
|
||||||
|
RUN echo "c.NotebookApp.token = ''" >> ~/.jupyter/jupyter_notebook_config.py
|
||||||
|
|
||||||
|
# open up port 8887 on the container
|
||||||
|
EXPOSE 8887
|
||||||
|
|
||||||
|
# start Jupyter notebook server on port 8887 when the container starts
|
||||||
|
CMD /bin/bash -c "cd /home/MachineLearningNotebooks && source activate azureml && jupyter notebook --port 8887 --no-browser --ip 0.0.0.0 --allow-root"
|
||||||
29
Dockerfiles/1.0.43/Dockerfile
Normal file
29
Dockerfiles/1.0.43/Dockerfile
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
FROM continuumio/miniconda:4.5.11
|
||||||
|
|
||||||
|
# install git
|
||||||
|
RUN apt-get update && apt-get upgrade -y && apt-get install -y git
|
||||||
|
|
||||||
|
# create a new conda environment named azureml
|
||||||
|
RUN conda create -n azureml -y -q Python=3.6
|
||||||
|
|
||||||
|
# install additional packages used by sample notebooks. this is optional
|
||||||
|
RUN ["/bin/bash", "-c", "source activate azureml && conda install -y tqdm cython matplotlib scikit-learn"]
|
||||||
|
|
||||||
|
# install azurmel-sdk components
|
||||||
|
RUN ["/bin/bash", "-c", "source activate azureml && pip install azureml-sdk[notebooks]==1.0.43"]
|
||||||
|
|
||||||
|
# clone Azure ML GitHub sample notebooks
|
||||||
|
RUN cd /home && git clone -b "azureml-sdk-1.0.43" --single-branch https://github.com/Azure/MachineLearningNotebooks.git
|
||||||
|
|
||||||
|
# generate jupyter configuration file
|
||||||
|
RUN ["/bin/bash", "-c", "source activate azureml && mkdir ~/.jupyter && cd ~/.jupyter && jupyter notebook --generate-config"]
|
||||||
|
|
||||||
|
# set an emtpy token for Jupyter to remove authentication.
|
||||||
|
# this is NOT recommended for production environment
|
||||||
|
RUN echo "c.NotebookApp.token = ''" >> ~/.jupyter/jupyter_notebook_config.py
|
||||||
|
|
||||||
|
# open up port 8887 on the container
|
||||||
|
EXPOSE 8887
|
||||||
|
|
||||||
|
# start Jupyter notebook server on port 8887 when the container starts
|
||||||
|
CMD /bin/bash -c "cd /home/MachineLearningNotebooks && source activate azureml && jupyter notebook --port 8887 --no-browser --ip 0.0.0.0 --allow-root"
|
||||||
12
README.md
12
README.md
@@ -38,6 +38,7 @@ The [How to use Azure ML](./how-to-use-azureml) folder contains specific example
|
|||||||
- [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
|
||||||
@@ -52,6 +53,7 @@ The [How to use Azure ML](./how-to-use-azureml) folder contains specific example
|
|||||||
|
|
||||||
Visit following repos to see projects contributed by Azure ML users:
|
Visit following repos to see projects contributed by Azure ML users:
|
||||||
|
|
||||||
|
- [AMLSamples](https://github.com/Azure/AMLSamples) Number of end-to-end examples, including face recognition, predictive maintenance, customer churn and sentiment analysis.
|
||||||
- [Fine tune natural language processing models using Azure Machine Learning service](https://github.com/Microsoft/AzureML-BERT)
|
- [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)
|
- [Fashion MNIST with Azure ML SDK](https://github.com/amynic/azureml-sdk-fashion)
|
||||||
|
|
||||||
@@ -60,16 +62,6 @@ This repository collects usage data and sends it to Mircosoft to help improve ou
|
|||||||
|
|
||||||
To opt out of tracking, please go to the raw markdown or .ipynb files and remove the following line of code:
|
To opt out of tracking, please go to the raw markdown or .ipynb files and remove the following line of code:
|
||||||
|
|
||||||
```sh
|
|
||||||
""
|
|
||||||
```
|
|
||||||
This URL will be slightly different depending on the file.
|
|
||||||
|
|
||||||
## Data/Telemetry
|
|
||||||
This repository collects usage data and sends it to Mircosoft to help improve our products and services. Read Microsoft's [privacy statement to learn more](https://privacy.microsoft.com/en-US/privacystatement)
|
|
||||||
|
|
||||||
To opt out of tracking, please go to the raw markdown or .ipynb files and remove the following line of code:
|
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
""
|
""
|
||||||
```
|
```
|
||||||
|
|||||||
215
build_nb_index.py
Normal file
215
build_nb_index.py
Normal file
@@ -0,0 +1,215 @@
|
|||||||
|
# ---------------------------------------------------------
|
||||||
|
# Copyright (c) Microsoft Corporation. All rights reserved.
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
|
||||||
|
### USAGE
|
||||||
|
#
|
||||||
|
# 1. Add following metadata elements to the notebook
|
||||||
|
#
|
||||||
|
# "friendly_name": "string", friendly name for notebook
|
||||||
|
# "exclude_from_index": true/false, setting true excludes the notebook from index
|
||||||
|
# "order_index": integer, smaller value moves notebook closer to beginning
|
||||||
|
# "category": "starter", "tutorial", "training", "deployment" or "other"
|
||||||
|
# "tags": [ "featured" ], optional, only supported tag to highlight notebook with :star: symbol
|
||||||
|
# "task": "string", description of notebook task
|
||||||
|
# "datasets": [ "dataset 1", "dataset 2"], list of datasets, can be ["None"]
|
||||||
|
# "compute": [ "compute 1", "compute 2" ], list of computes, can be ["None"]
|
||||||
|
# "deployment": ["deployment 1", "deployment 2"], list of deployment targets, can be ["None"]
|
||||||
|
# "framework": ["fw 1", "fw2"], list of ml framework, can be ["None"]
|
||||||
|
#
|
||||||
|
# 2. Then run
|
||||||
|
#
|
||||||
|
# build_nb_index.py <root folder of notebooks>
|
||||||
|
#
|
||||||
|
# 3. The script should produce index.md file with tables of notebook indices
|
||||||
|
|
||||||
|
### Example metadata section
|
||||||
|
|
||||||
|
'''
|
||||||
|
"metadata": {
|
||||||
|
"authors": [
|
||||||
|
{
|
||||||
|
"name": "cforbe"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"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"
|
||||||
|
},
|
||||||
|
"msauthor": "trbye",
|
||||||
|
"friendly_name": "Prepare data for regression modeling",
|
||||||
|
"exclude_from_index": false,
|
||||||
|
"order_index": 1,
|
||||||
|
"category": "tutorial",
|
||||||
|
"tags": [
|
||||||
|
"featured"
|
||||||
|
],
|
||||||
|
"task": "Regression",
|
||||||
|
"datasets": [
|
||||||
|
"NYC Taxi"
|
||||||
|
],
|
||||||
|
"compute": [
|
||||||
|
"local"
|
||||||
|
],
|
||||||
|
"deployment": [
|
||||||
|
"None"
|
||||||
|
],
|
||||||
|
"framework": [
|
||||||
|
"Azure ML AutoML"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
'''
|
||||||
|
|
||||||
|
import os, json, sys
|
||||||
|
from shutil import copyfile, copytree, rmtree
|
||||||
|
|
||||||
|
|
||||||
|
# Index building walk over notebook folder
|
||||||
|
def post_process(notebooks_dir):
|
||||||
|
indexer = NotebookIndex()
|
||||||
|
n_dest = len(notebooks_dir)
|
||||||
|
for r, d, f in os.walk(notebooks_dir):
|
||||||
|
for file in f:
|
||||||
|
# Handle only notebooks
|
||||||
|
if file.endswith(".ipynb") and not file.endswith('checkpoint.ipynb'):
|
||||||
|
try:
|
||||||
|
file_path = os.path.join(r, file)
|
||||||
|
with open(file_path, 'r') as fin:
|
||||||
|
content = json.load(fin)
|
||||||
|
print(file)
|
||||||
|
indexer.add_to_index(os.path.join(r[n_dest:],file), content["metadata"])
|
||||||
|
except Exception as e:
|
||||||
|
print("Problem: ",str(e))
|
||||||
|
indexer.write_index("./index.md")
|
||||||
|
|
||||||
|
### Customize these make index look different
|
||||||
|
|
||||||
|
index_template = '''
|
||||||
|
# Index
|
||||||
|
Azure Machine Learning is a cloud service that you use to train, deploy, automate, and manage machine learning models. This index should assist in navigating the Azure Machine Learning notebook samples and encourage efficient retrieval of topics and content.
|
||||||
|
|
||||||
|
|
||||||
|
## Getting Started
|
||||||
|
|
||||||
|
|Title| Task | Dataset | Training Compute | Deployment Target | ML Framework |
|
||||||
|
|:----|:-----|:-------:|:----------------:|:-----------------:|:------------:|
|
||||||
|
GETTING_STARTED_NBS
|
||||||
|
|
||||||
|
## Tutorials
|
||||||
|
|
||||||
|
|Title| Task | Dataset | Training Compute | Deployment Target | ML Framework |
|
||||||
|
|:----|:-----|:-------:|:----------------:|:-----------------:|:------------:|
|
||||||
|
TUTORIAL_NBS
|
||||||
|
|
||||||
|
## Training
|
||||||
|
|
||||||
|
|Title| Task | Dataset | Training Compute | Deployment Target | ML Framework |
|
||||||
|
|:----|:-----|:-------:|:----------------:|:-----------------:|:------------:|
|
||||||
|
TRAINING_NBS
|
||||||
|
|
||||||
|
## Deployment
|
||||||
|
|
||||||
|
|Title| Task | Dataset | Training Compute | Deployment Target | ML Framework |
|
||||||
|
|:----|:-----|:-------:|:----------------:|:-----------------:|:------------:|
|
||||||
|
DEPLOYMENT_NBS
|
||||||
|
|
||||||
|
## Other Notebooks
|
||||||
|
|Title| Task | Dataset | Training Compute | Deployment Target | ML Framework |
|
||||||
|
|:----|:-----|:-------:|:----------------:|:-----------------:|:------------:|
|
||||||
|
OTHER_NBS
|
||||||
|
'''
|
||||||
|
|
||||||
|
index_row = '''| NB_SYMBOL[NB_NAME](NB_PATH) | NB_TASK | NB_DATASET | NB_COMPUTE | NB_DEPLOYMENT | NB_FRAMEWORK |'''
|
||||||
|
|
||||||
|
index_file = "index.md"
|
||||||
|
|
||||||
|
nb_types = ["starter", "tutorial", "training", "deployment", "other"]
|
||||||
|
replace_strings = ["GETTING_STARTED_NBS", "TUTORIAL_NBS", "TRAINING_NBS", "DEPLOYMENT_NBS", "OTHER_NBS"]
|
||||||
|
|
||||||
|
class NotebookIndex:
|
||||||
|
def __init__(self):
|
||||||
|
self.index = index_template
|
||||||
|
self.nb_rows = {}
|
||||||
|
for elem in nb_types:
|
||||||
|
self.nb_rows[elem] = []
|
||||||
|
|
||||||
|
def add_to_index(self, path_to_notebook, metadata):
|
||||||
|
repo_url = "https://github.com/Azure/MachineLearningNotebooks/blob/master/"
|
||||||
|
|
||||||
|
if "exclude_from_index" in metadata:
|
||||||
|
if metadata["exclude_from_index"]:
|
||||||
|
return
|
||||||
|
|
||||||
|
if "friendly_name" in metadata:
|
||||||
|
this_row = index_row.replace("NB_NAME",metadata["friendly_name"])
|
||||||
|
else:
|
||||||
|
this_name = os.path.basename(path_to_notebook)
|
||||||
|
this_row = index_row.replace("NB_NAME", this_name[:-6])
|
||||||
|
|
||||||
|
path_to_notebook = path_to_notebook.replace("\\","/")
|
||||||
|
this_row = this_row.replace("NB_PATH", repo_url + path_to_notebook)
|
||||||
|
|
||||||
|
if "task" in metadata:
|
||||||
|
this_row = this_row.replace("NB_TASK", metadata["task"])
|
||||||
|
if "datasets" in metadata:
|
||||||
|
this_row = this_row.replace("NB_DATASET", ", ".join(metadata["datasets"]))
|
||||||
|
if "compute" in metadata:
|
||||||
|
this_row = this_row.replace("NB_COMPUTE", ", ".join(metadata["compute"]))
|
||||||
|
if "deployment" in metadata:
|
||||||
|
this_row = this_row.replace("NB_DEPLOYMENT", ", ".join(metadata["deployment"]))
|
||||||
|
if "framework" in metadata:
|
||||||
|
this_row = this_row.replace("NB_FRAMEWORK", ", ".join(metadata["framework"]))
|
||||||
|
## Fall back
|
||||||
|
this_row = this_row.replace("NB_TASK","")
|
||||||
|
this_row = this_row.replace("NB_DATASET","")
|
||||||
|
this_row = this_row.replace("NB_COMPUTE","")
|
||||||
|
this_row = this_row.replace("NB_DEPLOYMENT","")
|
||||||
|
this_row = this_row.replace("NB_FRAMEWORK","")
|
||||||
|
|
||||||
|
if "tags" in metadata:
|
||||||
|
if "featured" in metadata["tags"]:
|
||||||
|
this_row = this_row.replace("NB_SYMBOL",":star:")
|
||||||
|
## Fall back
|
||||||
|
this_row =this_row.replace("NB_SYMBOL","")
|
||||||
|
|
||||||
|
index_order = 9999999
|
||||||
|
if "index_order" in metadata:
|
||||||
|
index_order = metadata["index_order"]
|
||||||
|
|
||||||
|
if "category" in metadata:
|
||||||
|
self.nb_rows[metadata["category"]].append((index_order, this_row))
|
||||||
|
else:
|
||||||
|
self.nb_rows["other"].append((index_order, this_row))
|
||||||
|
|
||||||
|
def sort_and_stringify(self,section):
|
||||||
|
sorted_index = sorted(self.nb_rows[section], key = lambda x: x[0])
|
||||||
|
sorted_index = [x[1] for x in sorted_index]
|
||||||
|
## TODO: Make this portable
|
||||||
|
return "\n".join(sorted_index)
|
||||||
|
|
||||||
|
def write_index(self, index_file):
|
||||||
|
for nb_type, replace_string in zip(nb_types, replace_strings):
|
||||||
|
nb_string = self.sort_and_stringify(nb_type)
|
||||||
|
self.index = self.index.replace(replace_string, nb_string)
|
||||||
|
with open(index_file,"w") as fin:
|
||||||
|
fin.write(self.index)
|
||||||
|
|
||||||
|
try:
|
||||||
|
dest_repo = sys.argv[1]
|
||||||
|
except:
|
||||||
|
dest_repo = "./MachineLearningNotebooks"
|
||||||
|
|
||||||
|
post_process(dest_repo)
|
||||||
@@ -1,293 +1,387 @@
|
|||||||
{
|
{
|
||||||
"cells": [
|
"cells": [
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Licensed under the MIT License."
|
"Licensed under the MIT License."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
""
|
""
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"# Configuration\n",
|
"# Configuration\n",
|
||||||
"\n",
|
"\n",
|
||||||
"_**Setting up your Azure Machine Learning services workspace and configuring your notebook library**_\n",
|
"_**Setting up your Azure Machine Learning services workspace and configuring your notebook library**_\n",
|
||||||
"\n",
|
"\n",
|
||||||
"---\n",
|
"---\n",
|
||||||
"---\n",
|
"---\n",
|
||||||
"\n",
|
"\n",
|
||||||
"## Table of Contents\n",
|
"## Table of Contents\n",
|
||||||
"\n",
|
"\n",
|
||||||
"1. [Introduction](#Introduction)\n",
|
"1. [Introduction](#Introduction)\n",
|
||||||
" 1. What is an Azure Machine Learning workspace\n",
|
" 1. What is an Azure Machine Learning workspace\n",
|
||||||
"1. [Setup](#Setup)\n",
|
"1. [Setup](#Setup)\n",
|
||||||
" 1. Azure subscription\n",
|
" 1. Azure subscription\n",
|
||||||
" 1. Azure ML SDK and other library installation\n",
|
" 1. Azure ML SDK and other library installation\n",
|
||||||
" 1. Azure Container Instance registration\n",
|
" 1. Azure Container Instance registration\n",
|
||||||
"1. [Configure your Azure ML Workspace](#Configure%20your%20Azure%20ML%20workspace)\n",
|
"1. [Configure your Azure ML Workspace](#Configure%20your%20Azure%20ML%20workspace)\n",
|
||||||
" 1. Workspace parameters\n",
|
" 1. Workspace parameters\n",
|
||||||
" 1. Access your workspace\n",
|
" 1. Access your workspace\n",
|
||||||
" 1. Create a new workspace\n",
|
" 1. Create a new workspace\n",
|
||||||
"1. [Next steps](#Next%20steps)\n",
|
" 1. Create compute resources\n",
|
||||||
"\n",
|
"1. [Next steps](#Next%20steps)\n",
|
||||||
"---\n",
|
"\n",
|
||||||
"\n",
|
"---\n",
|
||||||
"## Introduction\n",
|
"\n",
|
||||||
"\n",
|
"## Introduction\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",
|
"\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",
|
||||||
"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",
|
"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",
|
||||||
"In this notebook you will\n",
|
"\n",
|
||||||
"* Learn about getting an Azure subscription\n",
|
"In this notebook you will\n",
|
||||||
"* Specify your workspace parameters\n",
|
"* Learn about getting an Azure subscription\n",
|
||||||
"* Access or create your workspace\n",
|
"* Specify your workspace parameters\n",
|
||||||
"* Add a default compute cluster for your workspace\n",
|
"* Access or create your workspace\n",
|
||||||
"\n",
|
"* Add a default compute cluster for your workspace\n",
|
||||||
"### What is an Azure Machine Learning workspace\n",
|
"\n",
|
||||||
"\n",
|
"### What is an Azure Machine Learning workspace\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, inferencing, and the monitoring of deployed models."
|
"\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."
|
||||||
},
|
]
|
||||||
{
|
},
|
||||||
"cell_type": "markdown",
|
{
|
||||||
"metadata": {},
|
"cell_type": "markdown",
|
||||||
"source": [
|
"metadata": {},
|
||||||
"## Setup\n",
|
"source": [
|
||||||
"\n",
|
"## Setup\n",
|
||||||
"This section describes activities required before you can access any Azure ML services functionality."
|
"\n",
|
||||||
]
|
"This section describes activities required before you can access any Azure ML services functionality."
|
||||||
},
|
]
|
||||||
{
|
},
|
||||||
"cell_type": "markdown",
|
{
|
||||||
"metadata": {},
|
"cell_type": "markdown",
|
||||||
"source": [
|
"metadata": {},
|
||||||
"### 1. Azure Subscription\n",
|
"source": [
|
||||||
"\n",
|
"### 1. 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",
|
"\n",
|
||||||
"\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",
|
||||||
"### 2. Azure ML SDK and other library installation\n",
|
"\n",
|
||||||
"\n",
|
"### 2. Azure ML SDK and other library installation\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",
|
"\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",
|
||||||
"Also install following libraries to your environment. Many of the example notebooks depend on them\n",
|
"\n",
|
||||||
"\n",
|
"Also install following libraries to your environment. Many of the example notebooks depend on them\n",
|
||||||
"```\n",
|
"\n",
|
||||||
"(myenv) $ conda install -y matplotlib tqdm scikit-learn\n",
|
"```\n",
|
||||||
"```\n",
|
"(myenv) $ conda install -y matplotlib tqdm scikit-learn\n",
|
||||||
"\n",
|
"```\n",
|
||||||
"Once installation is complete, the following cell checks the Azure ML SDK version:"
|
"\n",
|
||||||
]
|
"Once installation is complete, the following cell checks the Azure ML SDK version:"
|
||||||
},
|
]
|
||||||
{
|
},
|
||||||
"cell_type": "code",
|
{
|
||||||
"execution_count": null,
|
"cell_type": "code",
|
||||||
"metadata": {
|
"execution_count": null,
|
||||||
"tags": [
|
"metadata": {
|
||||||
"install"
|
"tags": [
|
||||||
]
|
"install"
|
||||||
},
|
]
|
||||||
"outputs": [],
|
},
|
||||||
"source": [
|
"outputs": [],
|
||||||
"import azureml.core\n",
|
"source": [
|
||||||
"\n",
|
"import azureml.core\n",
|
||||||
"print(\"This notebook was created using version 1.0.41 of the Azure ML SDK\")\n",
|
"\n",
|
||||||
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
"print(\"This notebook was created using version 1.0.55 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": "markdown",
|
||||||
"source": [
|
"metadata": {},
|
||||||
"If you are using an older version of the SDK then this notebook was created using, you should upgrade your SDK.\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",
|
||||||
"### 3. Azure Container Instance registration\n",
|
"\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",
|
"### 3. Azure Container Instance registration\n",
|
||||||
"\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",
|
||||||
"```shell\n",
|
"\n",
|
||||||
"# check to see if ACI is already registered\n",
|
"```shell\n",
|
||||||
"(myenv) $ az provider show -n Microsoft.ContainerInstance -o table\n",
|
"# check to see if ACI is already registered\n",
|
||||||
"\n",
|
"(myenv) $ az provider show -n Microsoft.ContainerInstance -o table\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",
|
"# if ACI is not registered, run this command.\n",
|
||||||
"(myenv) $ az provider register -n Microsoft.ContainerInstance\n",
|
"# note you need to be the subscription owner in order to execute this command successfully.\n",
|
||||||
"```\n",
|
"(myenv) $ az provider register -n Microsoft.ContainerInstance\n",
|
||||||
"\n",
|
"```\n",
|
||||||
"---"
|
"\n",
|
||||||
]
|
"---"
|
||||||
},
|
]
|
||||||
{
|
},
|
||||||
"cell_type": "markdown",
|
{
|
||||||
"metadata": {},
|
"cell_type": "markdown",
|
||||||
"source": [
|
"metadata": {},
|
||||||
"## Configure your Azure ML workspace\n",
|
"source": [
|
||||||
"\n",
|
"## Configure your Azure ML workspace\n",
|
||||||
"### Workspace parameters\n",
|
"\n",
|
||||||
"\n",
|
"### Workspace parameters\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",
|
"To use an AML Workspace, you will need to import the Azure ML SDK and supply the following information:\n",
|
||||||
"* A resource group name\n",
|
"* Your subscription id\n",
|
||||||
"* (optional) The region that will host your workspace\n",
|
"* A resource group name\n",
|
||||||
"* A name for your workspace\n",
|
"* (optional) The region that will host your workspace\n",
|
||||||
"\n",
|
"* A name for your workspace\n",
|
||||||
"You can get your subscription ID from the [Azure portal](https://portal.azure.com).\n",
|
"\n",
|
||||||
"\n",
|
"You can get your subscription ID from the [Azure portal](https://portal.azure.com).\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",
|
"\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",
|
||||||
"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",
|
||||||
"\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",
|
||||||
"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 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",
|
||||||
"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",
|
||||||
"\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",
|
||||||
"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",
|
||||||
"\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",
|
||||||
"Replace the default values in the cell below with your workspace parameters"
|
"\n",
|
||||||
]
|
"Replace the default values in the cell below with your workspace parameters"
|
||||||
},
|
]
|
||||||
{
|
},
|
||||||
"cell_type": "code",
|
{
|
||||||
"execution_count": null,
|
"cell_type": "code",
|
||||||
"metadata": {},
|
"execution_count": null,
|
||||||
"outputs": [],
|
"metadata": {},
|
||||||
"source": [
|
"outputs": [],
|
||||||
"import os\n",
|
"source": [
|
||||||
"\n",
|
"import os\n",
|
||||||
"subscription_id = os.getenv(\"SUBSCRIPTION_ID\", default=\"<my-subscription-id>\")\n",
|
"\n",
|
||||||
"resource_group = os.getenv(\"RESOURCE_GROUP\", default=\"<my-resource-group>\")\n",
|
"subscription_id = os.getenv(\"SUBSCRIPTION_ID\", default=\"<my-subscription-id>\")\n",
|
||||||
"workspace_name = os.getenv(\"WORKSPACE_NAME\", default=\"<my-workspace-name>\")\n",
|
"resource_group = os.getenv(\"RESOURCE_GROUP\", default=\"<my-resource-group>\")\n",
|
||||||
"workspace_region = os.getenv(\"WORKSPACE_REGION\", default=\"eastus2\")"
|
"workspace_name = os.getenv(\"WORKSPACE_NAME\", default=\"<my-workspace-name>\")\n",
|
||||||
]
|
"workspace_region = os.getenv(\"WORKSPACE_REGION\", default=\"eastus2\")"
|
||||||
},
|
]
|
||||||
{
|
},
|
||||||
"cell_type": "markdown",
|
{
|
||||||
"metadata": {},
|
"cell_type": "markdown",
|
||||||
"source": [
|
"metadata": {},
|
||||||
"### Access your workspace\n",
|
"source": [
|
||||||
"\n",
|
"### Access your 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",
|
||||||
]
|
"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. "
|
||||||
},
|
]
|
||||||
{
|
},
|
||||||
"cell_type": "code",
|
{
|
||||||
"execution_count": null,
|
"cell_type": "code",
|
||||||
"metadata": {},
|
"execution_count": null,
|
||||||
"outputs": [],
|
"metadata": {},
|
||||||
"source": [
|
"outputs": [],
|
||||||
"from azureml.core import Workspace\n",
|
"source": [
|
||||||
"\n",
|
"from azureml.core import Workspace\n",
|
||||||
"try:\n",
|
"\n",
|
||||||
" ws = Workspace(subscription_id = subscription_id, resource_group = resource_group, workspace_name = workspace_name)\n",
|
"try:\n",
|
||||||
" # write the details of the workspace to a configuration file to the notebook library\n",
|
" ws = Workspace(subscription_id = subscription_id, resource_group = resource_group, workspace_name = workspace_name)\n",
|
||||||
" ws.write_config()\n",
|
" # write the details of the workspace to a configuration file to the notebook library\n",
|
||||||
" print(\"Workspace configuration succeeded. Skip the workspace creation steps below\")\n",
|
" ws.write_config()\n",
|
||||||
"except:\n",
|
" print(\"Workspace configuration succeeded. Skip the workspace creation steps below\")\n",
|
||||||
" print(\"Workspace not accessible. Change your parameters or create a new workspace below\")"
|
"except:\n",
|
||||||
]
|
" print(\"Workspace not accessible. Change your parameters or create a new workspace below\")"
|
||||||
},
|
]
|
||||||
{
|
},
|
||||||
"cell_type": "markdown",
|
{
|
||||||
"metadata": {},
|
"cell_type": "markdown",
|
||||||
"source": [
|
"metadata": {},
|
||||||
"### Create a new workspace\n",
|
"source": [
|
||||||
"\n",
|
"### Create a new 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",
|
"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",
|
||||||
"**Note**: The Workspace creation command will create default CPU and GPU compute clusters for you. 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",
|
||||||
"\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",
|
||||||
"This cell will create an Azure ML workspace for you in a subscription provided you have the correct permissions.\n",
|
"\n",
|
||||||
"\n",
|
"This cell will create an Azure ML workspace for you in a subscription provided you have the correct permissions.\n",
|
||||||
"This will fail if:\n",
|
"\n",
|
||||||
"* You do not have permission to create a workspace in the resource group\n",
|
"This will fail if:\n",
|
||||||
"* You do not have permission to create a resource group if it's non-existing.\n",
|
"* You do not have permission to create a workspace in the resource group\n",
|
||||||
"* You are not a subscription owner or contributor and no Azure ML workspaces have ever been created in this subscription\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",
|
||||||
"If workspace creation fails, please work with your IT admin to provide you with the appropriate permissions or to provision the required resources."
|
"\n",
|
||||||
]
|
"If workspace creation fails, please work with your IT admin to provide you with the appropriate permissions or to provision the required resources.\n",
|
||||||
},
|
"To learn more about the Enterprise SKU, please visit the Pricing and SKU details page."
|
||||||
{
|
]
|
||||||
"cell_type": "code",
|
},
|
||||||
"execution_count": null,
|
{
|
||||||
"metadata": {
|
"cell_type": "code",
|
||||||
"tags": [
|
"execution_count": null,
|
||||||
"create workspace"
|
"metadata": {
|
||||||
]
|
"tags": [
|
||||||
},
|
"create workspace"
|
||||||
"outputs": [],
|
]
|
||||||
"source": [
|
},
|
||||||
"from azureml.core import Workspace\n",
|
"outputs": [],
|
||||||
"\n",
|
"source": [
|
||||||
"# Create the workspace using the specified parameters\n",
|
"from azureml.core import Workspace\n",
|
||||||
"ws = Workspace.create(name = workspace_name,\n",
|
"\n",
|
||||||
" subscription_id = subscription_id,\n",
|
"# Create the workspace using the specified parameters\n",
|
||||||
" resource_group = resource_group, \n",
|
"# To create an Enterprise workspace, please specify the sku = enterprise\n",
|
||||||
" location = workspace_region,\n",
|
|
||||||
" default_cpu_compute_target=Workspace.DEFAULT_CPU_CLUSTER_CONFIGURATION,\n",
|
"ws = Workspace.create(name = workspace_name,\n",
|
||||||
" default_gpu_compute_target=Workspace.DEFAULT_GPU_CLUSTER_CONFIGURATION,\n",
|
" subscription_id = subscription_id,\n",
|
||||||
" create_resource_group = True,\n",
|
" resource_group = resource_group, \n",
|
||||||
" exist_ok = True)\n",
|
" location = workspace_region,\n",
|
||||||
"ws.get_details()\n",
|
" create_resource_group = True,\n",
|
||||||
"\n",
|
" sku = basic,\n",
|
||||||
"# write the details of the workspace to a configuration file to the notebook library\n",
|
" exist_ok = True)\n",
|
||||||
"ws.write_config()"
|
"ws.get_details()\n",
|
||||||
]
|
"\n",
|
||||||
},
|
"# write the details of the workspace to a configuration file to the notebook library\n",
|
||||||
{
|
"ws.write_config()"
|
||||||
"cell_type": "markdown",
|
]
|
||||||
"metadata": {},
|
},
|
||||||
"source": [
|
{
|
||||||
"---\n",
|
"cell_type": "markdown",
|
||||||
"\n",
|
"metadata": {},
|
||||||
"## Next steps\n",
|
"source": [
|
||||||
"\n",
|
"### Create compute resources for your training experiments\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",
|
"\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",
|
||||||
"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."
|
"\n",
|
||||||
]
|
"To create a cluster, you need to specify a compute configuration that specifies the type of machine to be used and the scalability behaviors. Then you choose a name for the cluster that is unique within the workspace that can be used to address the cluster later.\n",
|
||||||
},
|
"\n",
|
||||||
{
|
"The cluster parameters are:\n",
|
||||||
"cell_type": "code",
|
"* 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",
|
||||||
"execution_count": null,
|
"\n",
|
||||||
"metadata": {},
|
"```shell\n",
|
||||||
"outputs": [],
|
"az vm list-skus -o tsv\n",
|
||||||
"source": []
|
"```\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",
|
||||||
],
|
"* 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",
|
||||||
"metadata": {
|
"\n",
|
||||||
"authors": [
|
"\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."
|
||||||
"name": "roastala"
|
]
|
||||||
}
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core.compute import ComputeTarget, AmlCompute\n",
|
||||||
|
"from azureml.core.compute_target import ComputeTargetException\n",
|
||||||
|
"\n",
|
||||||
|
"# Choose a name for your CPU cluster\n",
|
||||||
|
"cpu_cluster_name = \"cpu-cluster\"\n",
|
||||||
|
"\n",
|
||||||
|
"# Verify that cluster does not exist already\n",
|
||||||
|
"try:\n",
|
||||||
|
" cpu_cluster = ComputeTarget(workspace=ws, name=cpu_cluster_name)\n",
|
||||||
|
" print(\"Found existing cpu-cluster\")\n",
|
||||||
|
"except ComputeTargetException:\n",
|
||||||
|
" print(\"Creating new cpu-cluster\")\n",
|
||||||
|
" \n",
|
||||||
|
" # Specify the configuration for the new cluster\n",
|
||||||
|
" compute_config = AmlCompute.provisioning_configuration(vm_size=\"STANDARD_D2_V2\",\n",
|
||||||
|
" min_nodes=0,\n",
|
||||||
|
" max_nodes=4)\n",
|
||||||
|
"\n",
|
||||||
|
" # Create the cluster with the specified name and configuration\n",
|
||||||
|
" cpu_cluster = ComputeTarget.create(ws, cpu_cluster_name, compute_config)\n",
|
||||||
|
" \n",
|
||||||
|
" # Wait for the cluster to complete, show the output log\n",
|
||||||
|
" cpu_cluster.wait_for_completion(show_output=True)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"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). "
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core.compute import ComputeTarget, AmlCompute\n",
|
||||||
|
"from azureml.core.compute_target import ComputeTargetException\n",
|
||||||
|
"\n",
|
||||||
|
"# Choose a name for your GPU cluster\n",
|
||||||
|
"gpu_cluster_name = \"gpu-cluster\"\n",
|
||||||
|
"\n",
|
||||||
|
"# Verify that cluster does not exist already\n",
|
||||||
|
"try:\n",
|
||||||
|
" gpu_cluster = ComputeTarget(workspace=ws, name=gpu_cluster_name)\n",
|
||||||
|
" print(\"Found existing gpu cluster\")\n",
|
||||||
|
"except ComputeTargetException:\n",
|
||||||
|
" print(\"Creating new gpu-cluster\")\n",
|
||||||
|
" \n",
|
||||||
|
" # Specify the configuration for the new cluster\n",
|
||||||
|
" compute_config = AmlCompute.provisioning_configuration(vm_size=\"STANDARD_NC6\",\n",
|
||||||
|
" min_nodes=0,\n",
|
||||||
|
" max_nodes=4)\n",
|
||||||
|
" # Create the cluster with the specified name and configuration\n",
|
||||||
|
" gpu_cluster = ComputeTarget.create(ws, gpu_cluster_name, compute_config)\n",
|
||||||
|
"\n",
|
||||||
|
" # Wait for the cluster to complete, show the output log\n",
|
||||||
|
" gpu_cluster.wait_for_completion(show_output=True)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"---\n",
|
||||||
|
"\n",
|
||||||
|
"## Next steps\n",
|
||||||
|
"\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",
|
||||||
|
"\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."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
}
|
||||||
],
|
],
|
||||||
"kernelspec": {
|
"metadata": {
|
||||||
"display_name": "Python 3.6",
|
"authors": [
|
||||||
"language": "python",
|
{
|
||||||
"name": "python36"
|
"name": "roastala"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 3.6",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python36"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"codemirror_mode": {
|
||||||
|
"name": "ipython",
|
||||||
|
"version": 3
|
||||||
|
},
|
||||||
|
"file_extension": ".py",
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython3",
|
||||||
|
"version": "3.6.5"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"language_info": {
|
"nbformat": 4,
|
||||||
"codemirror_mode": {
|
"nbformat_minor": 2
|
||||||
"name": "ipython",
|
|
||||||
"version": 3
|
|
||||||
},
|
|
||||||
"file_extension": ".py",
|
|
||||||
"mimetype": "text/x-python",
|
|
||||||
"name": "python",
|
|
||||||
"nbconvert_exporter": "python",
|
|
||||||
"pygments_lexer": "ipython3",
|
|
||||||
"version": "3.6.5"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"nbformat": 4,
|
|
||||||
"nbformat_minor": 2
|
|
||||||
}
|
}
|
||||||
|
|||||||
4
configuration.yml
Normal file
4
configuration.yml
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
name: configuration
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
File diff suppressed because it is too large
Load Diff
723
contrib/datadrift/azure-ml-datadrift.ipynb
Normal file
723
contrib/datadrift/azure-ml-datadrift.ipynb
Normal file
@@ -0,0 +1,723 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Track Data Drift between Training and Inference Data in Production \n",
|
||||||
|
"\n",
|
||||||
|
"With this notebook, you will learn how to enable the DataDrift service to automatically track and determine whether your inference data is drifting from the data your model was initially trained on. The DataDrift service provides metrics and visualizations to help stakeholders identify which specific features cause the concept drift to occur.\n",
|
||||||
|
"\n",
|
||||||
|
"Please email driftfeedback@microsoft.com with any issues. A member from the DataDrift team will respond shortly. \n",
|
||||||
|
"\n",
|
||||||
|
"The DataDrift Public Preview API can be found [here](https://docs.microsoft.com/en-us/python/api/azureml-contrib-datadrift/?view=azure-ml-py). "
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
""
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Prerequisites and Setup"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Install the DataDrift package\n",
|
||||||
|
"\n",
|
||||||
|
"Install the azureml-contrib-datadrift, azureml-opendatasets and lightgbm packages before running this notebook.\n",
|
||||||
|
"```\n",
|
||||||
|
"pip install azureml-contrib-datadrift\n",
|
||||||
|
"pip install lightgbm\n",
|
||||||
|
"```"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Import Dependencies"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"import json\n",
|
||||||
|
"import os\n",
|
||||||
|
"import time\n",
|
||||||
|
"from datetime import datetime, timedelta\n",
|
||||||
|
"\n",
|
||||||
|
"import numpy as np\n",
|
||||||
|
"import pandas as pd\n",
|
||||||
|
"import requests\n",
|
||||||
|
"from azureml.contrib.datadrift import DataDriftDetector, AlertConfiguration\n",
|
||||||
|
"from azureml.opendatasets import NoaaIsdWeather\n",
|
||||||
|
"from azureml.core import Dataset, Workspace, Run\n",
|
||||||
|
"from azureml.core.compute import AksCompute, ComputeTarget\n",
|
||||||
|
"from azureml.core.conda_dependencies import CondaDependencies\n",
|
||||||
|
"from azureml.core.experiment import Experiment\n",
|
||||||
|
"from azureml.core.image import ContainerImage\n",
|
||||||
|
"from azureml.core.model import Model\n",
|
||||||
|
"from azureml.core.webservice import Webservice, AksWebservice\n",
|
||||||
|
"from azureml.widgets import RunDetails\n",
|
||||||
|
"from sklearn.externals import joblib\n",
|
||||||
|
"from sklearn.model_selection import train_test_split\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Set up Configuraton and Create Azure ML Workspace\n",
|
||||||
|
"\n",
|
||||||
|
"If you are using an Azure Machine Learning Notebook VM, you are all set. Otherwise, go through the [configuration notebook](../../../configuration.ipynb) first if you haven't already to establish your connection to the AzureML Workspace."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Please type in your initials/alias. The prefix is prepended to the names of resources created by this notebook. \n",
|
||||||
|
"prefix = \"dd\"\n",
|
||||||
|
"\n",
|
||||||
|
"# NOTE: Please do not change the model_name, as it's required by the score.py file\n",
|
||||||
|
"model_name = \"driftmodel\"\n",
|
||||||
|
"image_name = \"{}driftimage\".format(prefix)\n",
|
||||||
|
"service_name = \"{}driftservice\".format(prefix)\n",
|
||||||
|
"\n",
|
||||||
|
"# optionally, set email address to receive an email alert for DataDrift\n",
|
||||||
|
"email_address = \"\""
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"ws = Workspace.from_config()\n",
|
||||||
|
"print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep = '\\n')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Generate Train/Testing Data\n",
|
||||||
|
"\n",
|
||||||
|
"For this demo, we will use NOAA weather data from [Azure Open Datasets](https://azure.microsoft.com/services/open-datasets/). You may replace this step with your own dataset. "
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"usaf_list = ['725724', '722149', '723090', '722159', '723910', '720279',\n",
|
||||||
|
" '725513', '725254', '726430', '720381', '723074', '726682',\n",
|
||||||
|
" '725486', '727883', '723177', '722075', '723086', '724053',\n",
|
||||||
|
" '725070', '722073', '726060', '725224', '725260', '724520',\n",
|
||||||
|
" '720305', '724020', '726510', '725126', '722523', '703333',\n",
|
||||||
|
" '722249', '722728', '725483', '722972', '724975', '742079',\n",
|
||||||
|
" '727468', '722193', '725624', '722030', '726380', '720309',\n",
|
||||||
|
" '722071', '720326', '725415', '724504', '725665', '725424',\n",
|
||||||
|
" '725066']\n",
|
||||||
|
"\n",
|
||||||
|
"columns = ['usaf', 'wban', 'datetime', 'latitude', 'longitude', 'elevation', 'windAngle', 'windSpeed', 'temperature', 'stationName', 'p_k']\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"def enrich_weather_noaa_data(noaa_df):\n",
|
||||||
|
" hours_in_day = 23\n",
|
||||||
|
" week_in_year = 52\n",
|
||||||
|
" \n",
|
||||||
|
" noaa_df[\"hour\"] = noaa_df[\"datetime\"].dt.hour\n",
|
||||||
|
" noaa_df[\"weekofyear\"] = noaa_df[\"datetime\"].dt.week\n",
|
||||||
|
" \n",
|
||||||
|
" noaa_df[\"sine_weekofyear\"] = noaa_df['datetime'].transform(lambda x: np.sin((2*np.pi*x.dt.week-1)/week_in_year))\n",
|
||||||
|
" noaa_df[\"cosine_weekofyear\"] = noaa_df['datetime'].transform(lambda x: np.cos((2*np.pi*x.dt.week-1)/week_in_year))\n",
|
||||||
|
"\n",
|
||||||
|
" noaa_df[\"sine_hourofday\"] = noaa_df['datetime'].transform(lambda x: np.sin(2*np.pi*x.dt.hour/hours_in_day))\n",
|
||||||
|
" noaa_df[\"cosine_hourofday\"] = noaa_df['datetime'].transform(lambda x: np.cos(2*np.pi*x.dt.hour/hours_in_day))\n",
|
||||||
|
" \n",
|
||||||
|
" return noaa_df\n",
|
||||||
|
"\n",
|
||||||
|
"def add_window_col(input_df):\n",
|
||||||
|
" shift_interval = pd.Timedelta('-7 days') # your X days interval\n",
|
||||||
|
" df_shifted = input_df.copy()\n",
|
||||||
|
" df_shifted['datetime'] = df_shifted['datetime'] - shift_interval\n",
|
||||||
|
" df_shifted.drop(list(input_df.columns.difference(['datetime', 'usaf', 'wban', 'sine_hourofday', 'temperature'])), axis=1, inplace=True)\n",
|
||||||
|
"\n",
|
||||||
|
" # merge, keeping only observations where -1 lag is present\n",
|
||||||
|
" df2 = pd.merge(input_df,\n",
|
||||||
|
" df_shifted,\n",
|
||||||
|
" on=['datetime', 'usaf', 'wban', 'sine_hourofday'],\n",
|
||||||
|
" how='inner', # use 'left' to keep observations without lags\n",
|
||||||
|
" suffixes=['', '-7'])\n",
|
||||||
|
" return df2\n",
|
||||||
|
"\n",
|
||||||
|
"def get_noaa_data(start_time, end_time, cols, station_list):\n",
|
||||||
|
" isd = NoaaIsdWeather(start_time, end_time, cols=cols)\n",
|
||||||
|
" # Read into Pandas data frame.\n",
|
||||||
|
" noaa_df = isd.to_pandas_dataframe()\n",
|
||||||
|
" noaa_df = noaa_df.rename(columns={\"stationName\": \"station_name\"})\n",
|
||||||
|
" \n",
|
||||||
|
" df_filtered = noaa_df[noaa_df[\"usaf\"].isin(station_list)]\n",
|
||||||
|
" df_filtered.reset_index(drop=True)\n",
|
||||||
|
" \n",
|
||||||
|
" # Enrich with time features\n",
|
||||||
|
" df_enriched = enrich_weather_noaa_data(df_filtered)\n",
|
||||||
|
" \n",
|
||||||
|
" return df_enriched\n",
|
||||||
|
"\n",
|
||||||
|
"def get_featurized_noaa_df(start_time, end_time, cols, station_list):\n",
|
||||||
|
" df_1 = get_noaa_data(start_time - timedelta(days=7), start_time - timedelta(seconds=1), cols, station_list)\n",
|
||||||
|
" df_2 = get_noaa_data(start_time, end_time, cols, station_list)\n",
|
||||||
|
" noaa_df = pd.concat([df_1, df_2])\n",
|
||||||
|
" \n",
|
||||||
|
" print(\"Adding window feature\")\n",
|
||||||
|
" df_window = add_window_col(noaa_df)\n",
|
||||||
|
" \n",
|
||||||
|
" cat_columns = df_window.dtypes == object\n",
|
||||||
|
" cat_columns = cat_columns[cat_columns == True]\n",
|
||||||
|
" \n",
|
||||||
|
" print(\"Encoding categorical columns\")\n",
|
||||||
|
" df_encoded = pd.get_dummies(df_window, columns=cat_columns.keys().tolist())\n",
|
||||||
|
" \n",
|
||||||
|
" print(\"Dropping unnecessary columns\")\n",
|
||||||
|
" df_featurized = df_encoded.drop(['windAngle', 'windSpeed', 'datetime', 'elevation'], axis=1).dropna().drop_duplicates()\n",
|
||||||
|
" \n",
|
||||||
|
" return df_featurized"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Train model on Jan 1 - 14, 2009 data\n",
|
||||||
|
"df = get_featurized_noaa_df(datetime(2009, 1, 1), datetime(2009, 1, 14, 23, 59, 59), columns, usaf_list)\n",
|
||||||
|
"df.head()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"label = \"temperature\"\n",
|
||||||
|
"x_df = df.drop(label, axis=1)\n",
|
||||||
|
"y_df = df[[label]]\n",
|
||||||
|
"x_train, x_test, y_train, y_test = train_test_split(df, y_df, test_size=0.2, random_state=223)\n",
|
||||||
|
"print(x_train.shape, x_test.shape, y_train.shape, y_test.shape)\n",
|
||||||
|
"\n",
|
||||||
|
"training_dir = 'outputs/training'\n",
|
||||||
|
"training_file = \"training.csv\"\n",
|
||||||
|
"\n",
|
||||||
|
"# Generate training dataframe to register as Training Dataset\n",
|
||||||
|
"os.makedirs(training_dir, exist_ok=True)\n",
|
||||||
|
"training_df = pd.merge(x_train.drop(label, axis=1), y_train, left_index=True, right_index=True)\n",
|
||||||
|
"training_df.to_csv(training_dir + \"/\" + training_file)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Create/Register Training Dataset"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"dataset_name = \"dataset\"\n",
|
||||||
|
"name_suffix = datetime.utcnow().strftime(\"%Y-%m-%d-%H-%M-%S\")\n",
|
||||||
|
"snapshot_name = \"snapshot-{}\".format(name_suffix)\n",
|
||||||
|
"\n",
|
||||||
|
"dstore = ws.get_default_datastore()\n",
|
||||||
|
"dstore.upload(training_dir, \"data/training\", show_progress=True)\n",
|
||||||
|
"dpath = dstore.path(\"data/training/training.csv\")\n",
|
||||||
|
"trainingDataset = Dataset.auto_read_files(dpath, include_path=True)\n",
|
||||||
|
"trainingDataset = trainingDataset.register(workspace=ws, name=dataset_name, description=\"dset\", exist_ok=True)\n",
|
||||||
|
"\n",
|
||||||
|
"datasets = [(Dataset.Scenario.TRAINING, trainingDataset)]\n",
|
||||||
|
"print(\"dataset registration done.\\n\")\n",
|
||||||
|
"datasets"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Train and Save Model"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"import lightgbm as lgb\n",
|
||||||
|
"\n",
|
||||||
|
"train = lgb.Dataset(data=x_train, \n",
|
||||||
|
" label=y_train)\n",
|
||||||
|
"\n",
|
||||||
|
"test = lgb.Dataset(data=x_test, \n",
|
||||||
|
" label=y_test,\n",
|
||||||
|
" reference=train)\n",
|
||||||
|
"\n",
|
||||||
|
"params = {'learning_rate' : 0.1,\n",
|
||||||
|
" 'boosting' : 'gbdt',\n",
|
||||||
|
" 'metric' : 'rmse',\n",
|
||||||
|
" 'feature_fraction' : 1,\n",
|
||||||
|
" 'bagging_fraction' : 1,\n",
|
||||||
|
" 'max_depth': 6,\n",
|
||||||
|
" 'num_leaves' : 31,\n",
|
||||||
|
" 'objective' : 'regression',\n",
|
||||||
|
" 'bagging_freq' : 1,\n",
|
||||||
|
" \"verbose\": -1,\n",
|
||||||
|
" 'min_data_per_leaf': 100}\n",
|
||||||
|
"\n",
|
||||||
|
"model = lgb.train(params, \n",
|
||||||
|
" num_boost_round=500,\n",
|
||||||
|
" train_set=train,\n",
|
||||||
|
" valid_sets=[train, test],\n",
|
||||||
|
" verbose_eval=50,\n",
|
||||||
|
" early_stopping_rounds=25)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"model_file = 'outputs/{}.pkl'.format(model_name)\n",
|
||||||
|
"\n",
|
||||||
|
"os.makedirs('outputs', exist_ok=True)\n",
|
||||||
|
"joblib.dump(model, model_file)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Register Model"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"model = Model.register(model_path=model_file,\n",
|
||||||
|
" model_name=model_name,\n",
|
||||||
|
" workspace=ws,\n",
|
||||||
|
" datasets=datasets)\n",
|
||||||
|
"\n",
|
||||||
|
"print(model_name, image_name, service_name, model)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Deploy Model To AKS"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Prepare Environment"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"myenv = CondaDependencies.create(conda_packages=['numpy','scikit-learn', 'joblib', 'lightgbm', 'pandas'],\n",
|
||||||
|
" pip_packages=['azureml-monitoring', 'azureml-sdk[automl]'])\n",
|
||||||
|
"\n",
|
||||||
|
"with open(\"myenv.yml\",\"w\") as f:\n",
|
||||||
|
" f.write(myenv.serialize_to_string())"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Create Image"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Image creation may take up to 15 minutes.\n",
|
||||||
|
"\n",
|
||||||
|
"image_name = image_name + str(model.version)\n",
|
||||||
|
"\n",
|
||||||
|
"if not image_name in ws.images:\n",
|
||||||
|
" # Use the score.py defined in this directory as the execution script\n",
|
||||||
|
" # NOTE: The Model Data Collector must be enabled in the execution script for DataDrift to run correctly\n",
|
||||||
|
" image_config = ContainerImage.image_configuration(execution_script=\"score.py\",\n",
|
||||||
|
" runtime=\"python\",\n",
|
||||||
|
" conda_file=\"myenv.yml\",\n",
|
||||||
|
" description=\"Image with weather dataset model\")\n",
|
||||||
|
" image = ContainerImage.create(name=image_name,\n",
|
||||||
|
" models=[model],\n",
|
||||||
|
" image_config=image_config,\n",
|
||||||
|
" workspace=ws)\n",
|
||||||
|
"\n",
|
||||||
|
" image.wait_for_creation(show_output=True)\n",
|
||||||
|
"else:\n",
|
||||||
|
" image = ws.images[image_name]"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Create Compute Target"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"aks_name = 'dd-demo-e2e'\n",
|
||||||
|
"prov_config = AksCompute.provisioning_configuration()\n",
|
||||||
|
"\n",
|
||||||
|
"if not aks_name in ws.compute_targets:\n",
|
||||||
|
" aks_target = ComputeTarget.create(workspace=ws,\n",
|
||||||
|
" name=aks_name,\n",
|
||||||
|
" provisioning_configuration=prov_config)\n",
|
||||||
|
"\n",
|
||||||
|
" aks_target.wait_for_completion(show_output=True)\n",
|
||||||
|
" print(aks_target.provisioning_state)\n",
|
||||||
|
" print(aks_target.provisioning_errors)\n",
|
||||||
|
"else:\n",
|
||||||
|
" aks_target=ws.compute_targets[aks_name]"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Deploy Service"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"aks_service_name = service_name\n",
|
||||||
|
"\n",
|
||||||
|
"if not aks_service_name in ws.webservices:\n",
|
||||||
|
" aks_config = AksWebservice.deploy_configuration(collect_model_data=True, enable_app_insights=True)\n",
|
||||||
|
" aks_service = Webservice.deploy_from_image(workspace=ws,\n",
|
||||||
|
" name=aks_service_name,\n",
|
||||||
|
" image=image,\n",
|
||||||
|
" deployment_config=aks_config,\n",
|
||||||
|
" deployment_target=aks_target)\n",
|
||||||
|
" aks_service.wait_for_deployment(show_output=True)\n",
|
||||||
|
" print(aks_service.state)\n",
|
||||||
|
"else:\n",
|
||||||
|
" aks_service = ws.webservices[aks_service_name]"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Run DataDrift Analysis"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Send Scoring Data to Service"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Download Scoring Data"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Score Model on March 15, 2016 data\n",
|
||||||
|
"scoring_df = get_noaa_data(datetime(2016, 3, 15) - timedelta(days=7), datetime(2016, 3, 16), columns, usaf_list)\n",
|
||||||
|
"# Add the window feature column\n",
|
||||||
|
"scoring_df = add_window_col(scoring_df)\n",
|
||||||
|
"\n",
|
||||||
|
"# Drop features not used by the model\n",
|
||||||
|
"print(\"Dropping unnecessary columns\")\n",
|
||||||
|
"scoring_df = scoring_df.drop(['windAngle', 'windSpeed', 'datetime', 'elevation'], axis=1).dropna()\n",
|
||||||
|
"scoring_df.head()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# One Hot Encode the scoring dataset to match the training dataset schema\n",
|
||||||
|
"columns_dict = model.datasets[\"training\"][0].get_profile().columns\n",
|
||||||
|
"extra_cols = ('Path', 'Column1')\n",
|
||||||
|
"for k in extra_cols:\n",
|
||||||
|
" columns_dict.pop(k, None)\n",
|
||||||
|
"training_columns = list(columns_dict.keys())\n",
|
||||||
|
"\n",
|
||||||
|
"categorical_columns = scoring_df.dtypes == object\n",
|
||||||
|
"categorical_columns = categorical_columns[categorical_columns == True]\n",
|
||||||
|
"\n",
|
||||||
|
"test_df = pd.get_dummies(scoring_df[categorical_columns.keys().tolist()])\n",
|
||||||
|
"encoded_df = scoring_df.join(test_df)\n",
|
||||||
|
"\n",
|
||||||
|
"# Populate missing OHE columns with 0 values to match traning dataset schema\n",
|
||||||
|
"difference = list(set(training_columns) - set(encoded_df.columns.tolist()))\n",
|
||||||
|
"for col in difference:\n",
|
||||||
|
" encoded_df[col] = 0\n",
|
||||||
|
"encoded_df.head()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Serialize dataframe to list of row dictionaries\n",
|
||||||
|
"encoded_dict = encoded_df.to_dict('records')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Submit Scoring Data to Service"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"%%time\n",
|
||||||
|
"\n",
|
||||||
|
"# retreive the API keys. AML generates two keys.\n",
|
||||||
|
"key1, key2 = aks_service.get_keys()\n",
|
||||||
|
"\n",
|
||||||
|
"total_count = len(scoring_df)\n",
|
||||||
|
"i = 0\n",
|
||||||
|
"load = []\n",
|
||||||
|
"for row in encoded_dict:\n",
|
||||||
|
" load.append(row)\n",
|
||||||
|
" i = i + 1\n",
|
||||||
|
" if i % 100 == 0:\n",
|
||||||
|
" payload = json.dumps({\"data\": load})\n",
|
||||||
|
" \n",
|
||||||
|
" # construct raw HTTP request and send to the service\n",
|
||||||
|
" payload_binary = bytes(payload,encoding = 'utf8')\n",
|
||||||
|
" headers = {'Content-Type':'application/json', 'Authorization': 'Bearer ' + key1}\n",
|
||||||
|
" resp = requests.post(aks_service.scoring_uri, payload_binary, headers=headers)\n",
|
||||||
|
" \n",
|
||||||
|
" print(\"prediction:\", resp.content, \"Progress: {}/{}\".format(i, total_count)) \n",
|
||||||
|
"\n",
|
||||||
|
" load = []\n",
|
||||||
|
" time.sleep(3)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"We need to wait up to 10 minutes for the Model Data Collector to dump the model input and inference data to storage in the Workspace, where it's used by the DataDriftDetector job."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"time.sleep(600)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Configure DataDrift"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"services = [service_name]\n",
|
||||||
|
"start = datetime.now() - timedelta(days=2)\n",
|
||||||
|
"end = datetime(year=2020, month=1, day=22, hour=15, minute=16)\n",
|
||||||
|
"feature_list = ['usaf', 'wban', 'latitude', 'longitude', 'station_name', 'p_k', 'sine_hourofday', 'cosine_hourofday', 'temperature-7']\n",
|
||||||
|
"alert_config = AlertConfiguration([email_address]) if email_address else None\n",
|
||||||
|
"\n",
|
||||||
|
"# there will be an exception indicating using get() method if DataDrift object already exist\n",
|
||||||
|
"try:\n",
|
||||||
|
" datadrift = DataDriftDetector.create(ws, model.name, model.version, services, frequency=\"Day\", alert_config=alert_config)\n",
|
||||||
|
"except KeyError:\n",
|
||||||
|
" datadrift = DataDriftDetector.get(ws, model.name, model.version)\n",
|
||||||
|
" \n",
|
||||||
|
"print(\"Details of DataDrift Object:\\n{}\".format(datadrift))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Run an Adhoc DataDriftDetector Run"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"target_date = datetime.today()\n",
|
||||||
|
"run = datadrift.run(target_date, services, feature_list=feature_list, create_compute_target=True)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"exp = Experiment(ws, datadrift._id)\n",
|
||||||
|
"dd_run = Run(experiment=exp, run_id=run)\n",
|
||||||
|
"RunDetails(dd_run).show()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Get Drift Analysis Results"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"children = list(dd_run.get_children())\n",
|
||||||
|
"for child in children:\n",
|
||||||
|
" child.wait_for_completion()\n",
|
||||||
|
"\n",
|
||||||
|
"drift_metrics = datadrift.get_output(start_time=start, end_time=end)\n",
|
||||||
|
"drift_metrics"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Show all drift figures, one per serivice.\n",
|
||||||
|
"# If setting with_details is False (by default), only drift will be shown; if it's True, all details will be shown.\n",
|
||||||
|
"\n",
|
||||||
|
"drift_figures = datadrift.show(with_details=True)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Enable DataDrift Schedule"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"datadrift.enable_schedule()"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"authors": [
|
||||||
|
{
|
||||||
|
"name": "rafarmah"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"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
|
||||||
|
}
|
||||||
8
contrib/datadrift/azure-ml-datadrift.yml
Normal file
8
contrib/datadrift/azure-ml-datadrift.yml
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
name: azure-ml-datadrift
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
|
- azureml-contrib-datadrift
|
||||||
|
- azureml-opendatasets
|
||||||
|
- lightgbm
|
||||||
|
- azureml-widgets
|
||||||
58
contrib/datadrift/score.py
Normal file
58
contrib/datadrift/score.py
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
import pickle
|
||||||
|
import json
|
||||||
|
import numpy
|
||||||
|
import azureml.train.automl
|
||||||
|
from sklearn.externals import joblib
|
||||||
|
from sklearn.linear_model import Ridge
|
||||||
|
from azureml.core.model import Model
|
||||||
|
from azureml.core.run import Run
|
||||||
|
from azureml.monitoring import ModelDataCollector
|
||||||
|
import time
|
||||||
|
import pandas as pd
|
||||||
|
|
||||||
|
|
||||||
|
def init():
|
||||||
|
global model, inputs_dc, prediction_dc, feature_names, categorical_features
|
||||||
|
|
||||||
|
print("Model is initialized" + time.strftime("%H:%M:%S"))
|
||||||
|
model_path = Model.get_model_path(model_name="driftmodel")
|
||||||
|
model = joblib.load(model_path)
|
||||||
|
|
||||||
|
feature_names = ["usaf", "wban", "latitude", "longitude", "station_name", "p_k",
|
||||||
|
"sine_weekofyear", "cosine_weekofyear", "sine_hourofday", "cosine_hourofday",
|
||||||
|
"temperature-7"]
|
||||||
|
|
||||||
|
categorical_features = ["usaf", "wban", "p_k", "station_name"]
|
||||||
|
|
||||||
|
inputs_dc = ModelDataCollector(model_name="driftmodel",
|
||||||
|
identifier="inputs",
|
||||||
|
feature_names=feature_names)
|
||||||
|
|
||||||
|
prediction_dc = ModelDataCollector("driftmodel",
|
||||||
|
identifier="predictions",
|
||||||
|
feature_names=["temperature"])
|
||||||
|
|
||||||
|
|
||||||
|
def run(raw_data):
|
||||||
|
global inputs_dc, prediction_dc
|
||||||
|
|
||||||
|
try:
|
||||||
|
data = json.loads(raw_data)["data"]
|
||||||
|
data = pd.DataFrame(data)
|
||||||
|
|
||||||
|
# Remove the categorical features as the model expects OHE values
|
||||||
|
input_data = data.drop(categorical_features, axis=1)
|
||||||
|
|
||||||
|
result = model.predict(input_data)
|
||||||
|
|
||||||
|
# Collect the non-OHE dataframe
|
||||||
|
collected_df = data[feature_names]
|
||||||
|
|
||||||
|
inputs_dc.collect(collected_df.values)
|
||||||
|
prediction_dc.collect(result)
|
||||||
|
return result.tolist()
|
||||||
|
except Exception as e:
|
||||||
|
error = str(e)
|
||||||
|
|
||||||
|
print(error + time.strftime("%H:%M:%S"))
|
||||||
|
return error
|
||||||
@@ -115,16 +115,7 @@ jupyter notebook
|
|||||||
- 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-execution.ipynb](remote-execution/auto-ml-remote-execution.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)
|
|
||||||
- Example of using automated ML for classification using a remote linux DSVM for training
|
|
||||||
- Parallel execution of iterations
|
|
||||||
- Async tracking of progress
|
|
||||||
- Cancelling individual iterations or entire run
|
|
||||||
- Retrieving models for any iteration or logged metric
|
|
||||||
- Specify automated ML settings as kwargs
|
|
||||||
|
|
||||||
- [auto-ml-remote-amlcompute.ipynb](remote-batchai/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
|
||||||
@@ -133,12 +124,6 @@ jupyter notebook
|
|||||||
- 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-remote-attach.ipynb](remote-attach/auto-ml-remote-attach.ipynb)
|
|
||||||
- Dataset: Scikit learn's [20newsgroup](http://scikit-learn.org/stable/datasets/twenty_newsgroups.html)
|
|
||||||
- handling text data with preprocess flag
|
|
||||||
- Reading data from a blob store for remote executions
|
|
||||||
- using pandas dataframes for reading data
|
|
||||||
|
|
||||||
- [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
|
||||||
@@ -156,10 +141,6 @@ jupyter notebook
|
|||||||
- 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-remote-execution-with-datastore.ipynb](remote-execution-with-datastore/auto-ml-remote-execution-with-datastore.ipynb)
|
|
||||||
- Dataset: Scikit learn's [20newsgroup](http://scikit-learn.org/stable/datasets/twenty_newsgroups.html)
|
|
||||||
- Download the data and store it in DataStore.
|
|
||||||
|
|
||||||
- [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
|
||||||
@@ -194,10 +175,39 @@ jupyter notebook
|
|||||||
- 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 [digit dataset](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html#sklearn.datasets.load_digits)
|
- Dataset: scikit learn's [iris dataset](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_iris.html)
|
||||||
- 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)
|
||||||
|
- Dataset: scikit learn's [iris dataset](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_iris.html)
|
||||||
|
- Example of using automated ML for classification using remote AmlCompute for training
|
||||||
|
- Train the models with ONNX compatible config on
|
||||||
|
- Parallel execution of iterations
|
||||||
|
- Async tracking of progress
|
||||||
|
- Cancelling individual iterations or entire run
|
||||||
|
- Retrieving the ONNX models and do the inference with them
|
||||||
|
|
||||||
|
- [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)
|
||||||
|
- Simple example of using automated ML for classification to predict term deposit subscriptions for a bank
|
||||||
|
- 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)
|
||||||
|
- Simple example of using automated ML for classification to fraudulent credit card transactions
|
||||||
|
- 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)
|
||||||
|
- 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-concrete-strength-with-deployment.ipynb](predicting-concrete-strength-with-deployment/auto-ml-concrete-strength-with-deployment.ipynb)
|
||||||
|
- Dataset: UCI's [concrete compressive strength dataset](https://www.kaggle.com/pavanraj159/concrete-compressive-strength-data-set)
|
||||||
|
- 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
|
||||||
|
|
||||||
<a name="documentation"></a>
|
<a name="documentation"></a>
|
||||||
See [Configure automated machine learning experiments](https://docs.microsoft.com/azure/machine-learning/service/how-to-configure-auto-train) to learn how more about the the settings and features available for automated machine learning experiments.
|
See [Configure automated machine learning experiments](https://docs.microsoft.com/azure/machine-learning/service/how-to-configure-auto-train) to learn how more about the the settings and features available for automated machine learning experiments.
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ name: azure_automl
|
|||||||
dependencies:
|
dependencies:
|
||||||
# The python interpreter version.
|
# The python interpreter version.
|
||||||
# Currently Azure ML only supports 3.5.2 and later.
|
# Currently Azure ML only supports 3.5.2 and later.
|
||||||
|
- pip
|
||||||
- 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
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ name: azure_automl
|
|||||||
dependencies:
|
dependencies:
|
||||||
# The python interpreter version.
|
# The python interpreter version.
|
||||||
# Currently Azure ML only supports 3.5.2 and later.
|
# Currently Azure ML only supports 3.5.2 and later.
|
||||||
|
- pip
|
||||||
- nomkl
|
- nomkl
|
||||||
- python>=3.5.2,<3.6.8
|
- python>=3.5.2,<3.6.8
|
||||||
- nb_conda
|
- nb_conda
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ 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
|
||||||
|
|
||||||
call conda activate %conda_env_name% 2>nul:
|
call conda activate %conda_env_name% 2>nul:
|
||||||
|
|
||||||
if not errorlevel 1 (
|
if not errorlevel 1 (
|
||||||
@@ -42,6 +44,15 @@ IF NOT "%options%"=="nolaunch" (
|
|||||||
|
|
||||||
goto End
|
goto End
|
||||||
|
|
||||||
|
:CondaMissing
|
||||||
|
echo Please run this script from an Anaconda Prompt window.
|
||||||
|
echo You can start an Anaconda Prompt window by
|
||||||
|
echo typing Anaconda Prompt on the Start menu.
|
||||||
|
echo If you don't see the Anaconda Prompt app, install Miniconda.
|
||||||
|
echo If you are running an older version of Miniconda or Anaconda,
|
||||||
|
echo you can upgrade using the command: conda update conda
|
||||||
|
goto End
|
||||||
|
|
||||||
:YmlMissing
|
:YmlMissing
|
||||||
echo File %automl_env_file% not found.
|
echo File %automl_env_file% not found.
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,224 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
""
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
||||||
|
"\n",
|
||||||
|
"Licensed under the MIT License."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Unique Descriptive Title\n",
|
||||||
|
"_**Unique Subtitle**_\n",
|
||||||
|
"\n",
|
||||||
|
"Introduction that describes in a customer friendly language, what they will do and accomplish.\n".
|
||||||
|
"## Contents\n",
|
||||||
|
"1. [Introduction](#Introduction)\n",
|
||||||
|
"1. [Prerequisites](#Prerequisites)\n",
|
||||||
|
"1. [Configuration and Setup](#Setup)\n",
|
||||||
|
"1. [Working with Data](#Working with Data)\n",
|
||||||
|
"1. [Training](#Training)\n",
|
||||||
|
"1. [Productionizing](#Productionizing)\n",
|
||||||
|
"1. [Model Monitoring](#Model Monitoring)\n",
|
||||||
|
"1. [Clean up resources](#Clean up resources)\n",
|
||||||
|
"1. [Next Steps](#Next Steps)\n",
|
||||||
|
"1. [Acknowledgements](#Acknowledgements)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Configuration\n",
|
||||||
|
"\n",
|
||||||
|
"If you are using an Azure Machine Learning Compute Instance, you are all set. Otherwise, go through the [configuration](../../../configuration.ipynb) notebook first if you haven't already to establish your connection to the AzureML Workspace. \n",
|
||||||
|
"Please note that a Basic edition workspace is created by default in the configuration.ipynb file.\n",
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Setup\n",
|
||||||
|
"\n",
|
||||||
|
"As part of the setup you have already created an Azure ML `Workspace` object....\n",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"import azureml.core\n",
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"tenant_id = os.environ['TENANT_ID’]\n",
|
||||||
|
"client_id = os.environ['CLIENT_ID’]\n",
|
||||||
|
"run = Run.get_context()\n",
|
||||||
|
"secret_name = “{0}-secret”.format(client_id)\n",
|
||||||
|
"secret = run.get_secret(name=secret_name)\n",
|
||||||
|
"sp_auth = ServicePrincipalAuthentication(tenant_id, client_id, secret)\n",
|
||||||
|
"ws = Workspace.from_config(auth=sp_auth)\n",
|
||||||
|
"\n",
|
||||||
|
"# choose a unique name for experiment\n",
|
||||||
|
"experiment_name = 'unique-name'\n",
|
||||||
|
"# project folder\n",
|
||||||
|
"project_folder = './sample_projects/test'\n",
|
||||||
|
"\n",
|
||||||
|
"experiment=Experiment(ws, experiment_name)\n",
|
||||||
|
"\n",
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Create or Attach existing AmlCompute\n",
|
||||||
|
"You will need to create a compute target for your 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": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Working with Data\n",
|
||||||
|
"\n",
|
||||||
|
"Here you would learn how to perform Data labeling and use Open Datasets etc..\n",
|
||||||
|
"To do this first load....\n",
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Training\n",
|
||||||
|
"\n",
|
||||||
|
"Here you would learn how to train a DNN using...\n",
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Productionizing\n",
|
||||||
|
"\n",
|
||||||
|
"Here you would learn how to deploy your model to ACI to perform...\n",
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Model Monitoring\n",
|
||||||
|
"\n",
|
||||||
|
"Here you would learn how to detect datadrift etc...\n",
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Clean up resources\n",
|
||||||
|
"\n",
|
||||||
|
"Now, let's clean up the resources we created...\n",
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Next Steps\n",
|
||||||
|
"\n",
|
||||||
|
"In this notebook, you’ve done x, y, z. You can learn more with these resources:\n",
|
||||||
|
"+ [SDK reference documentation for `MyClass`]()\n",
|
||||||
|
"+ [About this feature](https://docs.microsoft.com/azure/machine-learning/service/thisfeature)\n",
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"This dataset is made available under the Creative Commons (CCO: Public Domain) License: https://creativecommons.org/publicdomain/zero/1.0/. Any rights in individual contents of the database are licensed under the Database Contents License: https://creativecommons.org/publicdomain/zero/1.0/ and is available at: https://www.kaggle.com/janiobachmann/bank-marketing-dataset .\n",
|
||||||
|
"\n",
|
||||||
|
"_**Acknowledgements**_\n",
|
||||||
|
"This dataset is originally available within the UCI Machine Learning Database: https://archive.ics.uci.edu/ml/datasets/bank+marketing\n",
|
||||||
|
"\n",
|
||||||
|
"[Moro et al., 2014] S. Moro, P. Cortez and P. Rita. A Data-Driven Approach to Predict the Success of Bank Telemarketing. Decision Support Systems, Elsevier, 62:22-31, June 2014"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"authors": [
|
||||||
|
{
|
||||||
|
"name": "YOUR ALIAS"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"category": "tutorial",
|
||||||
|
"compute": [
|
||||||
|
"AML Compute"
|
||||||
|
],
|
||||||
|
"datasets": [
|
||||||
|
"MNIST"
|
||||||
|
],
|
||||||
|
"deployment": [
|
||||||
|
"AKS"
|
||||||
|
],
|
||||||
|
"exclude_from_index": false,
|
||||||
|
"framework": [
|
||||||
|
"PyTorch"
|
||||||
|
],
|
||||||
|
"friendly_name": "How to use ModuleStep with AML Pipelines",
|
||||||
|
},
|
||||||
|
"order_index": 14,
|
||||||
|
"star_tag": [],
|
||||||
|
"tags": [
|
||||||
|
"Pipeline Builder"
|
||||||
|
],
|
||||||
|
"task": "Demonstrates the use of ModuleStep"
|
||||||
|
},
|
||||||
|
"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
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
name: auto-ml-classification-bank-marketing
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
|
- azureml-train-automl
|
||||||
|
- azureml-widgets
|
||||||
|
- matplotlib
|
||||||
|
- pandas_ml
|
||||||
@@ -0,0 +1,714 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
||||||
|
"\n",
|
||||||
|
"Licensed under the MIT License."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
""
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Automated Machine Learning\n",
|
||||||
|
"_**Classification with Deployment using Credit Card Dataset**_\n",
|
||||||
|
"\n",
|
||||||
|
"## Contents\n",
|
||||||
|
"1. [Introduction](#Introduction)\n",
|
||||||
|
"1. [Setup](#Setup)\n",
|
||||||
|
"1. [Train](#Train)\n",
|
||||||
|
"1. [Results](#Results)\n",
|
||||||
|
"1. [Deploy](#Deploy)\n",
|
||||||
|
"1. [Test](#Test)\n",
|
||||||
|
"1. [Acknowledgements](#Acknowledgements)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Introduction\n",
|
||||||
|
"\n",
|
||||||
|
"In this example we use the associated credit card dataset to showcase how you can use AutoML for a simple classification problem and deploy it to an Azure Container Instance (ACI). The classification goal is to predict if a creditcard transaction is or is not considered a fraudulent charge.\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 using an existing workspace.\n",
|
||||||
|
"2. Configure AutoML using `AutoMLConfig`.\n",
|
||||||
|
"3. Train the model using local compute.\n",
|
||||||
|
"4. Explore the results.\n",
|
||||||
|
"5. Register the model.\n",
|
||||||
|
"6. Create a container image.\n",
|
||||||
|
"7. Create an Azure Container Instance (ACI) service.\n",
|
||||||
|
"8. Test the ACI service."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"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",
|
||||||
|
"from sklearn.model_selection import train_test_split\n",
|
||||||
|
"import azureml.dataprep as dprep\n",
|
||||||
|
"\n",
|
||||||
|
"import azureml.core\n",
|
||||||
|
"from azureml.core.experiment import Experiment\n",
|
||||||
|
"from azureml.core.workspace import Workspace\n",
|
||||||
|
"from azureml.train.automl import AutoMLConfig\n",
|
||||||
|
"from azureml.train.automl.run import AutoMLRun"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"ws = Workspace.from_config()\n",
|
||||||
|
"\n",
|
||||||
|
"# choose a name for experiment\n",
|
||||||
|
"experiment_name = 'automl-classification-ccard'\n",
|
||||||
|
"# project folder\n",
|
||||||
|
"project_folder = './sample_projects/automl-classification-creditcard'\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['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",
|
||||||
|
"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",
|
||||||
|
" # 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",
|
||||||
|
"\n",
|
||||||
|
"Here load the data in the get_data script to be utilized in azure compute. To do this, first load all the necessary libraries and dependencies to set up paths for the data and to create the conda_run_config."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"if not os.path.isdir('data'):\n",
|
||||||
|
" os.mkdir('data')\n",
|
||||||
|
" \n",
|
||||||
|
"if not os.path.exists(project_folder):\n",
|
||||||
|
" os.makedirs(project_folder)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"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",
|
||||||
|
"conda_run_config.environment.docker.base_image = azureml.core.runconfig.DEFAULT_CPU_IMAGE\n",
|
||||||
|
"\n",
|
||||||
|
"dprep_dependency = 'azureml-dataprep==' + pkg_resources.get_distribution(\"azureml-dataprep\").version\n",
|
||||||
|
"\n",
|
||||||
|
"cd = CondaDependencies.create(pip_packages=['azureml-sdk[automl]', dprep_dependency], conda_packages=['numpy','py-xgboost<=0.80'])\n",
|
||||||
|
"conda_run_config.environment.python.conda_dependencies = cd"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Load Data\n",
|
||||||
|
"\n",
|
||||||
|
"Here create the script to be run in azure compute for loading the data, load the credit card dataset into cards and store the Class column (y) in the y variable and store the remaining data in the x variable. Next split the data using train_test_split and return X_train and y_train for training the model."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"data = \"https://automlsamplenotebookdata.blob.core.windows.net/automl-sample-notebook-data/creditcard.csv\"\n",
|
||||||
|
"dflow = dprep.read_csv(data, infer_column_types=True)\n",
|
||||||
|
"dflow.get_profile()\n",
|
||||||
|
"X = dflow.drop_columns(columns=['Class'])\n",
|
||||||
|
"y = dflow.keep_columns(columns=['Class'], validate_column_exists=True)\n",
|
||||||
|
"X_train, X_test = X.random_split(percentage=0.8, seed=223)\n",
|
||||||
|
"y_train, y_test = y.random_split(percentage=0.8, seed=223)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Train\n",
|
||||||
|
"\n",
|
||||||
|
"Instantiate a AutoMLConfig object. This defines the settings and data used to run the experiment.\n",
|
||||||
|
"\n",
|
||||||
|
"|Property|Description|\n",
|
||||||
|
"|-|-|\n",
|
||||||
|
"|**task**|classification or regression|\n",
|
||||||
|
"|**primary_metric**|This is the metric that you want to optimize. Classification supports the following primary metrics: <br><i>accuracy</i><br><i>AUC_weighted</i><br><i>average_precision_score_weighted</i><br><i>norm_macro_recall</i><br><i>precision_score_weighted</i>|\n",
|
||||||
|
"|**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, ], 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.|\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": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"##### If you would like to see even better results increase \"iteration_time_out minutes\" to 10+ mins and increase \"iterations\" to a minimum of 30"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"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\": 'average_precision_score_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_20190417.log',\n",
|
||||||
|
" path = project_folder,\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": [
|
||||||
|
"## Deploy\n",
|
||||||
|
"\n",
|
||||||
|
"### 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 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": [
|
||||||
|
"best_run, fitted_model = remote_run.get_output()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Register the 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": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"description = 'AutoML Model'\n",
|
||||||
|
"tags = None\n",
|
||||||
|
"model = remote_run.register_model(description = description, tags = tags)\n",
|
||||||
|
"\n",
|
||||||
|
"print(remote_run.model_id) # This will be written to the script file later in the notebook."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Create Scoring Script\n",
|
||||||
|
"The scoring script is required to generate the image for deployment. It contains the code to do the predictions on input data."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"%%writefile score.py\n",
|
||||||
|
"import pickle\n",
|
||||||
|
"import json\n",
|
||||||
|
"import numpy\n",
|
||||||
|
"import azureml.train.automl\n",
|
||||||
|
"from sklearn.externals import joblib\n",
|
||||||
|
"from azureml.core.model import Model\n",
|
||||||
|
"\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",
|
||||||
|
" # deserialize the model file back into a sklearn model\n",
|
||||||
|
" model = joblib.load(model_path)\n",
|
||||||
|
"\n",
|
||||||
|
"def run(rawdata):\n",
|
||||||
|
" try:\n",
|
||||||
|
" data = json.loads(rawdata)['data']\n",
|
||||||
|
" data = numpy.array(data)\n",
|
||||||
|
" result = model.predict(data)\n",
|
||||||
|
" except Exception as e:\n",
|
||||||
|
" result = str(e)\n",
|
||||||
|
" return json.dumps({\"error\": result})\n",
|
||||||
|
" return json.dumps({\"result\":result.tolist()})"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Create a YAML File for the Environment"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"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. Details about retrieving the versions can be found in notebook [12.auto-ml-retrieve-the-training-sdk-versions](12.auto-ml-retrieve-the-training-sdk-versions.ipynb)."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"dependencies = remote_run.get_run_sdk_dependencies(iteration = 1)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"for p in ['azureml-train-automl', 'azureml-sdk', 'azureml-core']:\n",
|
||||||
|
" print('{}\\t{}'.format(p, dependencies[p]))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"myenv = CondaDependencies.create(conda_packages=['numpy','scikit-learn','py-xgboost<=0.80'],\n",
|
||||||
|
" pip_packages=['azureml-sdk[automl]'])\n",
|
||||||
|
"\n",
|
||||||
|
"conda_env_file_name = 'myenv.yml'\n",
|
||||||
|
"myenv.save_to_file('.', conda_env_file_name)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"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",
|
||||||
|
"# However, we include this in case this code is used on an experiment from a previous SDK version.\n",
|
||||||
|
"\n",
|
||||||
|
"with open(conda_env_file_name, 'r') as cefr:\n",
|
||||||
|
" content = cefr.read()\n",
|
||||||
|
"\n",
|
||||||
|
"with open(conda_env_file_name, 'w') as cefw:\n",
|
||||||
|
" cefw.write(content.replace(azureml.core.VERSION, dependencies['azureml-sdk']))\n",
|
||||||
|
"\n",
|
||||||
|
"# Substitute the actual model id in the script file.\n",
|
||||||
|
"\n",
|
||||||
|
"script_file_name = 'score.py'\n",
|
||||||
|
"\n",
|
||||||
|
"with open(script_file_name, 'r') as cefr:\n",
|
||||||
|
" content = cefr.read()\n",
|
||||||
|
"\n",
|
||||||
|
"with open(script_file_name, 'w') as cefw:\n",
|
||||||
|
" cefw.write(content.replace('<<modelid>>', remote_run.model_id))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Create a Container Image\n",
|
||||||
|
"\n",
|
||||||
|
"Next use Azure Container Instances for deploying models as a web service for quickly deploying and validating your model\n",
|
||||||
|
"or when testing a model that is under development."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core.image import Image, ContainerImage\n",
|
||||||
|
"\n",
|
||||||
|
"image_config = ContainerImage.image_configuration(runtime= \"python\",\n",
|
||||||
|
" execution_script = script_file_name,\n",
|
||||||
|
" conda_file = conda_env_file_name,\n",
|
||||||
|
" tags = {'area': \"cards\", 'type': \"automl_classification\"},\n",
|
||||||
|
" description = \"Image for automl classification sample\")\n",
|
||||||
|
"\n",
|
||||||
|
"image = Image.create(name = \"automlsampleimage\",\n",
|
||||||
|
" # this is the model object \n",
|
||||||
|
" models = [model],\n",
|
||||||
|
" image_config = image_config, \n",
|
||||||
|
" workspace = ws)\n",
|
||||||
|
"\n",
|
||||||
|
"image.wait_for_creation(show_output = True)\n",
|
||||||
|
"\n",
|
||||||
|
"if image.creation_state == 'Failed':\n",
|
||||||
|
" print(\"Image build log at: \" + image.image_build_log_uri)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Deploy the Image as a Web Service on Azure Container Instance\n",
|
||||||
|
"\n",
|
||||||
|
"Deploy an image that contains the model and other assets needed by the service."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core.webservice import AciWebservice\n",
|
||||||
|
"\n",
|
||||||
|
"aciconfig = AciWebservice.deploy_configuration(cpu_cores = 1, \n",
|
||||||
|
" memory_gb = 1, \n",
|
||||||
|
" tags = {'area': \"cards\", 'type': \"automl_classification\"}, \n",
|
||||||
|
" description = 'sample service for Automl Classification')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core.webservice import Webservice\n",
|
||||||
|
"\n",
|
||||||
|
"aci_service_name = 'automl-sample-creditcard'\n",
|
||||||
|
"print(aci_service_name)\n",
|
||||||
|
"aci_service = Webservice.deploy_from_image(deployment_config = aciconfig,\n",
|
||||||
|
" image = image,\n",
|
||||||
|
" name = aci_service_name,\n",
|
||||||
|
" workspace = ws)\n",
|
||||||
|
"aci_service.wait_for_deployment(True)\n",
|
||||||
|
"print(aci_service.state)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Delete a Web Service\n",
|
||||||
|
"\n",
|
||||||
|
"Deletes the specified web service."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"#aci_service.delete()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Get Logs from a Deployed Web Service\n",
|
||||||
|
"\n",
|
||||||
|
"Gets logs from a deployed web service."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"#aci_service.get_logs()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Test\n",
|
||||||
|
"\n",
|
||||||
|
"Now that the model is trained, split the data in the same way the data was split for training (The difference here is the data is being split locally) and then run the test data through the trained model to get the predicted values."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"#Randomly select and test\n",
|
||||||
|
"X_test = X_test.to_pandas_dataframe()\n",
|
||||||
|
"y_test = y_test.to_pandas_dataframe()\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"y_pred = fitted_model.predict(X_test)\n",
|
||||||
|
"y_pred"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Calculate metrics for the prediction\n",
|
||||||
|
"\n",
|
||||||
|
"Now visualize the data on a scatter plot to show what our truth (actual) values are compared to the predicted values \n",
|
||||||
|
"from the trained model that was returned."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"#Randomly select and test\n",
|
||||||
|
"# Plot outputs\n",
|
||||||
|
"%matplotlib notebook\n",
|
||||||
|
"test_pred = plt.scatter(y_test, y_pred, color='b')\n",
|
||||||
|
"test_test = plt.scatter(y_test, y_test, color='g')\n",
|
||||||
|
"plt.legend((test_pred, test_test), ('prediction', 'truth'), loc='upper left', fontsize=8)\n",
|
||||||
|
"plt.show()\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Acknowledgements"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"This Credit Card fraud Detection dataset is made available under the Open Database License: http://opendatacommons.org/licenses/odbl/1.0/. Any rights in individual contents of the database are licensed under the Database Contents License: http://opendatacommons.org/licenses/dbcl/1.0/ and is available at: https://www.kaggle.com/mlg-ulb/creditcardfraud\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"The dataset has been collected and analysed during a research collaboration of Worldline and the Machine Learning Group (http://mlg.ulb.ac.be) of ULB (Universit\u00c3\u00a9 Libre de Bruxelles) on big data mining and fraud detection. More details on current and past projects on related topics are available on https://www.researchgate.net/project/Fraud-detection-5 and the page of the DefeatFraud project\n",
|
||||||
|
"Please cite the following works: \n",
|
||||||
|
"\u00e2\u20ac\u00a2\tAndrea Dal Pozzolo, Olivier Caelen, Reid A. Johnson and Gianluca Bontempi. Calibrating Probability with Undersampling for Unbalanced Classification. In Symposium on Computational Intelligence and Data Mining (CIDM), IEEE, 2015\n",
|
||||||
|
"\u00e2\u20ac\u00a2\tDal Pozzolo, Andrea; Caelen, Olivier; Le Borgne, Yann-Ael; Waterschoot, Serge; Bontempi, Gianluca. Learned lessons in credit card fraud detection from a practitioner perspective, Expert systems with applications,41,10,4915-4928,2014, Pergamon\n",
|
||||||
|
"\u00e2\u20ac\u00a2\tDal Pozzolo, Andrea; Boracchi, Giacomo; Caelen, Olivier; Alippi, Cesare; Bontempi, Gianluca. Credit card fraud detection: a realistic modeling and a novel learning strategy, IEEE transactions on neural networks and learning systems,29,8,3784-3797,2018,IEEE\n",
|
||||||
|
"o\tDal Pozzolo, Andrea Adaptive Machine learning for credit card fraud detection ULB MLG PhD thesis (supervised by G. Bontempi)\n",
|
||||||
|
"\u00e2\u20ac\u00a2\tCarcillo, Fabrizio; Dal Pozzolo, Andrea; Le Borgne, Yann-A\u00c3\u00abl; Caelen, Olivier; Mazzer, Yannis; Bontempi, Gianluca. Scarff: a scalable framework for streaming credit card fraud detection with Spark, Information fusion,41, 182-194,2018,Elsevier\n",
|
||||||
|
"\u00e2\u20ac\u00a2\tCarcillo, Fabrizio; Le Borgne, Yann-A\u00c3\u00abl; Caelen, Olivier; Bontempi, Gianluca. Streaming active learning strategies for real-life credit card fraud detection: assessment and visualization, International Journal of Data Science and Analytics, 5,4,285-300,2018,Springer International Publishing"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"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
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
name: auto-ml-classification-credit-card-fraud
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
|
- azureml-train-automl
|
||||||
|
- azureml-widgets
|
||||||
|
- matplotlib
|
||||||
|
- pandas_ml
|
||||||
@@ -41,6 +41,8 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
|
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"An Enterprise workspace is required for this notebook. To learn more about creating an Enterprise workspace or upgrading to an Enterprise workspace from the Azure portal, please visit our [Workspace page](https://docs.microsoft.com/en-us/azure/machine-learning/service/concept-workspace#upgrade).\n",
|
||||||
|
|
||||||
"In this notebook you will learn how to:\n",
|
"In this notebook you will learn how to:\n",
|
||||||
"1. Create an experiment using an existing workspace.\n",
|
"1. Create an experiment using an existing workspace.\n",
|
||||||
"2. Configure AutoML using `AutoMLConfig`.\n",
|
"2. Configure AutoML using `AutoMLConfig`.\n",
|
||||||
@@ -61,61 +63,13 @@
|
|||||||
"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."
|
"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 json\n",
|
|
||||||
"import logging\n",
|
|
||||||
"\n",
|
|
||||||
"from matplotlib import pyplot as plt\n",
|
|
||||||
"import numpy as np\n",
|
|
||||||
"import pandas as pd\n",
|
|
||||||
"from sklearn import datasets\n",
|
|
||||||
"\n",
|
|
||||||
"import azureml.core\n",
|
|
||||||
"from azureml.core.experiment import Experiment\n",
|
|
||||||
"from azureml.core.workspace import Workspace\n",
|
|
||||||
"from azureml.train.automl import AutoMLConfig\n",
|
|
||||||
"from azureml.train.automl.run import AutoMLRun"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"ws = Workspace.from_config()\n",
|
|
||||||
"\n",
|
|
||||||
"# choose a name for experiment\n",
|
|
||||||
"experiment_name = 'automl-classification-deployment'\n",
|
|
||||||
"# project folder\n",
|
|
||||||
"project_folder = './sample_projects/automl-classification-deployment'\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['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",
|
|
||||||
"outputDf.T"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Train\n",
|
"## Train\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"The following steps require an Enterprise workspace to gain access to these features.To learn more about creating an Enterprise workspace or upgrading to an Enterprise workspace from the Azure portal, please visit our [Workspace page](https://docs.microsoft.com/en-us/azure/machine-learning/service/concept-workspace#upgrade).\n",
|
||||||
"Instantiate a AutoMLConfig object. This defines the settings and data used to run the experiment.\n",
|
"Instantiate a AutoMLConfig object. This defines the settings and data used to run the experiment.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"|Property|Description|\n",
|
"|Property|Description|\n",
|
||||||
@@ -484,7 +438,7 @@
|
|||||||
"metadata": {
|
"metadata": {
|
||||||
"authors": [
|
"authors": [
|
||||||
{
|
{
|
||||||
"name": "savitam"
|
"name": "shwinne"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"kernelspec": {
|
"kernelspec": {
|
||||||
@@ -507,4 +461,4 @@
|
|||||||
},
|
},
|
||||||
"nbformat": 4,
|
"nbformat": 4,
|
||||||
"nbformat_minor": 2
|
"nbformat_minor": 2
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
name: auto-ml-classification-with-deployment
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
|
- azureml-train-automl
|
||||||
|
- azureml-widgets
|
||||||
|
- matplotlib
|
||||||
|
- pandas_ml
|
||||||
@@ -29,7 +29,6 @@
|
|||||||
"1. [Data](#Data)\n",
|
"1. [Data](#Data)\n",
|
||||||
"1. [Train](#Train)\n",
|
"1. [Train](#Train)\n",
|
||||||
"1. [Results](#Results)\n",
|
"1. [Results](#Results)\n",
|
||||||
"1. [Test](#Test)\n",
|
|
||||||
"\n"
|
"\n"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -39,7 +38,7 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"## Introduction\n",
|
"## Introduction\n",
|
||||||
"\n",
|
"\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",
|
"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",
|
"\n",
|
||||||
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
|
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -49,7 +48,8 @@
|
|||||||
"1. Create an `Experiment` in an existing `Workspace`.\n",
|
"1. Create an `Experiment` in an existing `Workspace`.\n",
|
||||||
"2. Configure AutoML using `AutoMLConfig`.\n",
|
"2. Configure AutoML using `AutoMLConfig`.\n",
|
||||||
"3. Train the model using local compute with ONNX compatible config on.\n",
|
"3. Train the model using local compute with ONNX compatible config on.\n",
|
||||||
"4. Explore the results and save the ONNX model."
|
"4. Explore the results and save the ONNX model.\n",
|
||||||
|
"5. Inference with the ONNX model."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -129,6 +129,22 @@
|
|||||||
" test_size=0.2, \n",
|
" test_size=0.2, \n",
|
||||||
" random_state=0)\n",
|
" random_state=0)\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"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",
|
"# 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",
|
"# 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",
|
"# and the prediction with the ONNX model using the inference helper.\n",
|
||||||
@@ -140,11 +156,11 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Train with enable ONNX compatible models config on\n",
|
"## Train\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Instantiate an `AutoMLConfig` object to specify the settings and data used to run the experiment.\n",
|
"Instantiate an `AutoMLConfig` object to specify the settings and data used to run the experiment.\n",
|
||||||
"\n",
|
"\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",
|
"**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",
|
"\n",
|
||||||
"|Property|Description|\n",
|
"|Property|Description|\n",
|
||||||
"|-|-|\n",
|
"|-|-|\n",
|
||||||
@@ -158,6 +174,13 @@
|
|||||||
"|**path**|Relative path to the project folder. AutoML stores configuration files for the experiment under this folder. You can specify a new empty folder.|"
|
"|**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",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Set the preprocess=True, currently the InferenceHelper only supports this mode."
|
||||||
|
]
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
@@ -299,7 +322,7 @@
|
|||||||
" onnxrt_present = False\n",
|
" onnxrt_present = False\n",
|
||||||
"\n",
|
"\n",
|
||||||
"def get_onnx_res(run):\n",
|
"def get_onnx_res(run):\n",
|
||||||
" res_path = '_debug_y_trans_converter.json'\n",
|
" res_path = 'onnx_resource.json'\n",
|
||||||
" run.download_file(name=constants.MODEL_RESOURCE_PATH_ONNX, output_file_path=res_path)\n",
|
" run.download_file(name=constants.MODEL_RESOURCE_PATH_ONNX, output_file_path=res_path)\n",
|
||||||
" with open(res_path) as f:\n",
|
" with open(res_path) as f:\n",
|
||||||
" onnx_res = json.load(f)\n",
|
" onnx_res = json.load(f)\n",
|
||||||
@@ -316,7 +339,7 @@
|
|||||||
" print(pred_prob_onnx)\n",
|
" print(pred_prob_onnx)\n",
|
||||||
"else:\n",
|
"else:\n",
|
||||||
" if not python_version_compatible:\n",
|
" if not python_version_compatible:\n",
|
||||||
" print('Please use Python version 3.6 to run the inference helper.') \n",
|
" print('Please use Python version 3.6 or 3.7 to run the inference helper.') \n",
|
||||||
" if not onnxrt_present:\n",
|
" if not onnxrt_present:\n",
|
||||||
" print('Please install the onnxruntime package to do the prediction with ONNX model.')"
|
" print('Please install the onnxruntime package to do the prediction with ONNX model.')"
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
name: auto-ml-classification-with-onnx
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
|
- azureml-train-automl
|
||||||
|
- azureml-widgets
|
||||||
|
- matplotlib
|
||||||
|
- pandas_ml
|
||||||
|
- onnxruntime
|
||||||
@@ -41,7 +41,7 @@
|
|||||||
"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",
|
"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",
|
"\n",
|
||||||
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
|
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
|
||||||
"This notebooks shows how can automl can be trained on a a selected list of models,see the readme.md for the models.\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",
|
"This trains the model exclusively on tensorflow based models.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"In this notebook you will learn how to:\n",
|
"In this notebook you will learn how to:\n",
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
name: auto-ml-classification-with-whitelisting
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
|
- azureml-train-automl
|
||||||
|
- azureml-widgets
|
||||||
|
- matplotlib
|
||||||
|
- pandas_ml
|
||||||
@@ -258,7 +258,11 @@
|
|||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
"metadata": {},
|
"metadata": {
|
||||||
|
"tags": [
|
||||||
|
"widget-rundetails-sample"
|
||||||
|
]
|
||||||
|
},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from azureml.widgets import RunDetails\n",
|
"from azureml.widgets import RunDetails\n",
|
||||||
@@ -475,7 +479,27 @@
|
|||||||
"nbconvert_exporter": "python",
|
"nbconvert_exporter": "python",
|
||||||
"pygments_lexer": "ipython3",
|
"pygments_lexer": "ipython3",
|
||||||
"version": "3.6.6"
|
"version": "3.6.6"
|
||||||
}
|
},
|
||||||
|
"friendly_name": "Testing index",
|
||||||
|
"exclude_from_index": false,
|
||||||
|
"order_index": 1,
|
||||||
|
"category": "tutorial",
|
||||||
|
"tags": [
|
||||||
|
"featured"
|
||||||
|
],
|
||||||
|
"task": "Regression",
|
||||||
|
"datasets": [
|
||||||
|
"NYC Taxi"
|
||||||
|
],
|
||||||
|
"compute": [
|
||||||
|
"local"
|
||||||
|
],
|
||||||
|
"deployment": [
|
||||||
|
"None"
|
||||||
|
],
|
||||||
|
"framework": [
|
||||||
|
"Azure ML AutoML"
|
||||||
|
],
|
||||||
},
|
},
|
||||||
"nbformat": 4,
|
"nbformat": 4,
|
||||||
"nbformat_minor": 2
|
"nbformat_minor": 2
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
name: auto-ml-classification
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
|
- azureml-train-automl
|
||||||
|
- azureml-widgets
|
||||||
|
- matplotlib
|
||||||
|
- pandas_ml
|
||||||
@@ -21,7 +21,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"# Automated Machine Learning\n",
|
"# Automated Machine Learning\n",
|
||||||
"_**Prepare Data using `azureml.dataprep` for Remote Execution (DSVM)**_\n",
|
"_**Prepare Data using `azureml.dataprep` for Remote Execution (AmlCompute)**_\n",
|
||||||
"\n",
|
"\n",
|
||||||
"## Contents\n",
|
"## Contents\n",
|
||||||
"1. [Introduction](#Introduction)\n",
|
"1. [Introduction](#Introduction)\n",
|
||||||
@@ -128,7 +128,7 @@
|
|||||||
"# You can also use `read_csv` and `to_*` transformations to read (with overridable delimiter)\n",
|
"# You can also use `read_csv` and `to_*` transformations to read (with overridable delimiter)\n",
|
||||||
"# and convert column types manually.\n",
|
"# and convert column types manually.\n",
|
||||||
"example_data = 'https://dprepdata.blob.core.windows.net/demo/crime0-random.csv'\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 = dprep.read_csv(example_data, infer_column_types=True)\n",
|
||||||
"dflow.get_profile()"
|
"dflow.get_profile()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -192,7 +192,7 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"### Create or Attach a Remote Linux DSVM"
|
"### Create or Attach an AmlCompute cluster"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -201,21 +201,36 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"dsvm_name = 'mydsvmb'\n",
|
"from azureml.core.compute import AmlCompute\n",
|
||||||
|
"from azureml.core.compute import ComputeTarget\n",
|
||||||
"\n",
|
"\n",
|
||||||
"try:\n",
|
"# Choose a name for your cluster.\n",
|
||||||
" while ws.compute_targets[dsvm_name].provisioning_state == 'Creating':\n",
|
"amlcompute_cluster_name = \"cpu-cluster\"\n",
|
||||||
" time.sleep(1)\n",
|
"\n",
|
||||||
" \n",
|
"found = False\n",
|
||||||
" dsvm_compute = DsvmCompute(ws, dsvm_name)\n",
|
"\n",
|
||||||
" print('Found existing DVSM.')\n",
|
"# Check if this compute target already exists in the workspace.\n",
|
||||||
"except:\n",
|
"\n",
|
||||||
" print('Creating a new DSVM.')\n",
|
"cts = ws.compute_targets\n",
|
||||||
" dsvm_config = DsvmCompute.provisioning_configuration(vm_size = \"Standard_D2_v2\")\n",
|
"if amlcompute_cluster_name in cts and cts[amlcompute_cluster_name].type == 'AmlCompute':\n",
|
||||||
" dsvm_compute = DsvmCompute.create(ws, name = dsvm_name, provisioning_configuration = dsvm_config)\n",
|
" found = True\n",
|
||||||
" dsvm_compute.wait_for_completion(show_output = True)\n",
|
" print('Found existing compute target.')\n",
|
||||||
" print(\"Waiting one minute for ssh to be accessible\")\n",
|
" compute_target = cts[amlcompute_cluster_name]\n",
|
||||||
" time.sleep(90) # Wait for ssh to be accessible"
|
"\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",
|
||||||
|
" # 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()."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -226,12 +241,19 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"from azureml.core.runconfig import RunConfiguration\n",
|
"from azureml.core.runconfig import RunConfiguration\n",
|
||||||
"from azureml.core.conda_dependencies import CondaDependencies\n",
|
"from azureml.core.conda_dependencies import CondaDependencies\n",
|
||||||
|
"import pkg_resources\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"# create a new RunConfig object\n",
|
||||||
"conda_run_config = RunConfiguration(framework=\"python\")\n",
|
"conda_run_config = RunConfiguration(framework=\"python\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"conda_run_config.target = dsvm_compute\n",
|
"# Set compute target to AmlCompute\n",
|
||||||
|
"conda_run_config.target = compute_target\n",
|
||||||
|
"conda_run_config.environment.docker.enabled = True\n",
|
||||||
|
"conda_run_config.environment.docker.base_image = azureml.core.runconfig.DEFAULT_CPU_IMAGE\n",
|
||||||
"\n",
|
"\n",
|
||||||
"cd = CondaDependencies.create(pip_packages=['azureml-sdk[automl]'], conda_packages=['numpy','py-xgboost<=0.80'])\n",
|
"dprep_dependency = 'azureml-dataprep==' + pkg_resources.get_distribution(\"azureml-dataprep\").version\n",
|
||||||
|
"\n",
|
||||||
|
"cd = CondaDependencies.create(pip_packages=['azureml-sdk[automl]', dprep_dependency], conda_packages=['numpy','py-xgboost<=0.80'])\n",
|
||||||
"conda_run_config.environment.python.conda_dependencies = cd"
|
"conda_run_config.environment.python.conda_dependencies = cd"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -294,6 +316,27 @@
|
|||||||
"remote_run.clean_preprocessor_cache()"
|
"remote_run.clean_preprocessor_cache()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Cancelling Runs\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",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
name: auto-ml-dataprep-remote-execution
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
|
- azureml-train-automl
|
||||||
|
- azureml-widgets
|
||||||
|
- matplotlib
|
||||||
|
- pandas_ml
|
||||||
@@ -1,5 +1,12 @@
|
|||||||
{
|
{
|
||||||
"cells": [
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
""
|
||||||
|
]
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
@@ -9,13 +16,6 @@
|
|||||||
"Licensed under the MIT License."
|
"Licensed under the MIT License."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
""
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
name: auto-ml-dataprep
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
|
- azureml-train-automl
|
||||||
|
- azureml-widgets
|
||||||
|
- matplotlib
|
||||||
|
- pandas_ml
|
||||||
@@ -197,12 +197,12 @@
|
|||||||
"display(HTML('<h3>Iterations</h3>'))\n",
|
"display(HTML('<h3>Iterations</h3>'))\n",
|
||||||
"RunDetails(ml_run).show() \n",
|
"RunDetails(ml_run).show() \n",
|
||||||
"\n",
|
"\n",
|
||||||
"children = list(ml_run.get_children())\n",
|
"all_metrics = ml_run.get_metrics(recursive=True)\n",
|
||||||
"metricslist = {}\n",
|
"metricslist = {}\n",
|
||||||
"for run in children:\n",
|
"for run_id, metrics in all_metrics.items():\n",
|
||||||
" properties = run.get_properties()\n",
|
" iteration = int(run_id.split('_')[-1])\n",
|
||||||
" metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)}\n",
|
" float_metrics = {k: v for k, v in metrics.items() if isinstance(v, float)}\n",
|
||||||
" metricslist[int(properties['iteration'])] = metrics\n",
|
" metricslist[iteration] = float_metrics\n",
|
||||||
"\n",
|
"\n",
|
||||||
"rundata = pd.DataFrame(metricslist).sort_index(1)\n",
|
"rundata = pd.DataFrame(metricslist).sort_index(1)\n",
|
||||||
"display(HTML('<h3>Metrics</h3>'))\n",
|
"display(HTML('<h3>Metrics</h3>'))\n",
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
name: auto-ml-exploring-previous-runs
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
|
- azureml-train-automl
|
||||||
|
- azureml-widgets
|
||||||
|
- matplotlib
|
||||||
|
- pandas_ml
|
||||||
@@ -36,19 +36,17 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Introduction\n",
|
"## Introduction\n",
|
||||||
"In this example, we show how AutoML can be used for bike share forecasting.\n",
|
"This notebook demonstrates demand forecasting for a bike-sharing service using AutoML.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"The purpose is to demonstrate how to take advantage of the built-in holiday featurization, access the feature names, and further demonstrate how to work with the `forecast` function. Please also look at the additional forecasting notebooks, which document lagging, rolling windows, forecast quantiles, other ways to use the forecast function, and forecaster deployment.\n",
|
"AutoML highlights here include built-in holiday featurization, accessing engineered feature names, and working with the `forecast` function. Please also look at the additional forecasting notebooks, which document lagging, rolling windows, forecast quantiles, other ways to use the forecast function, and forecaster deployment.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
|
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"In this notebook you would see\n",
|
"Notebook synopsis:\n",
|
||||||
"1. Creating an Experiment in an existing Workspace\n",
|
"1. Creating an Experiment in an existing Workspace\n",
|
||||||
"2. Instantiating AutoMLConfig with new task type \"forecasting\" for timeseries data training, and other timeseries related settings: for this dataset we use the basic one: \"time_column_name\" \n",
|
"2. Configuration and local run of AutoML for a time-series model with lag and holiday features \n",
|
||||||
"3. Training the Model using local compute\n",
|
"3. Viewing the engineered names for featurized data and featurization summary for all raw features\n",
|
||||||
"4. Exploring the results\n",
|
"4. Evaluating the fitted model using a rolling test "
|
||||||
"5. Viewing the engineered names for featurized data and featurization summary for all raw features\n",
|
|
||||||
"6. Testing the fitted model"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -69,10 +67,12 @@
|
|||||||
"import numpy as np\n",
|
"import numpy as np\n",
|
||||||
"import logging\n",
|
"import logging\n",
|
||||||
"import warnings\n",
|
"import warnings\n",
|
||||||
|
"\n",
|
||||||
|
"from pandas.tseries.frequencies import to_offset\n",
|
||||||
|
"\n",
|
||||||
"# Squash warning messages for cleaner output in the notebook\n",
|
"# Squash warning messages for cleaner output in the notebook\n",
|
||||||
"warnings.showwarning = lambda *args, **kwargs: None\n",
|
"warnings.showwarning = lambda *args, **kwargs: None\n",
|
||||||
"\n",
|
"\n",
|
||||||
"\n",
|
|
||||||
"from azureml.core.workspace import Workspace\n",
|
"from azureml.core.workspace import Workspace\n",
|
||||||
"from azureml.core.experiment import Experiment\n",
|
"from azureml.core.experiment import Experiment\n",
|
||||||
"from azureml.train.automl import AutoMLConfig\n",
|
"from azureml.train.automl import AutoMLConfig\n",
|
||||||
@@ -84,7 +84,7 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"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."
|
"As part of the setup you have already created a <b>Workspace</b>. To run AutoML, you also need to create an <b>Experiment</b>. An Experiment corresponds to a prediction problem you are trying to solve, while a Run corresponds to a specific approach to the problem."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -129,14 +129,15 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"data = pd.read_csv('bike-no.csv', parse_dates=['date'])"
|
"data = pd.read_csv('bike-no.csv', parse_dates=['date'])\n",
|
||||||
|
"data.head()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"Let's set up what we know abou the dataset. \n",
|
"Let's set up what we know about the dataset. \n",
|
||||||
"\n",
|
"\n",
|
||||||
"**Target column** is what we want to forecast.\n",
|
"**Target column** is what we want to forecast.\n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -194,8 +195,7 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"### Setting forecaster maximum horizon \n",
|
"### Setting forecaster maximum horizon \n",
|
||||||
"\n",
|
"\n",
|
||||||
"Assuming your test data forms a full and regular time series(regular time intervals and no holes), \n",
|
"The forecast horizon is the number of periods into the future that the model should predict. Here, we set the horizon to 14 periods (i.e. 14 days). Notice that this is much shorter than the number of days in the test set; we will need to use a rolling test to evaluate the performance on the whole test set. For more discussion of forecast horizons and guiding principles for setting them, please see the [energy demand notebook](https://github.com/Azure/MachineLearningNotebooks/tree/master/how-to-use-azureml/automated-machine-learning/forecasting-energy-demand). "
|
||||||
"the maximum horizon you will need to forecast is the length of the longest grain in your test set."
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -204,10 +204,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"if len(grain_column_names) == 0:\n",
|
"max_horizon = 14"
|
||||||
" max_horizon = len(X_test)\n",
|
|
||||||
"else:\n",
|
|
||||||
" max_horizon = X_test.groupby(grain_column_names)[time_column_name].count().max()"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -237,26 +234,25 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"time_column_name = 'date'\n",
|
|
||||||
"automl_settings = {\n",
|
"automl_settings = {\n",
|
||||||
" \"time_column_name\": time_column_name,\n",
|
" 'time_column_name': time_column_name,\n",
|
||||||
" # these columns are a breakdown of the total and therefore a leak\n",
|
" 'max_horizon': max_horizon,\n",
|
||||||
" \"drop_column_names\": ['casual', 'registered'],\n",
|
|
||||||
" # knowing the country/region allows Automated ML to bring in holidays\n",
|
" # knowing the country/region allows Automated ML to bring in holidays\n",
|
||||||
" \"country_or_region\" : 'US',\n",
|
" 'country_or_region': 'US',\n",
|
||||||
" \"max_horizon\" : max_horizon,\n",
|
" 'target_lags': 1,\n",
|
||||||
" \"target_lags\": 1 \n",
|
" # these columns are a breakdown of the total and therefore a leak\n",
|
||||||
|
" 'drop_column_names': ['casual', 'registered']\n",
|
||||||
"}\n",
|
"}\n",
|
||||||
"\n",
|
"\n",
|
||||||
"automl_config = AutoMLConfig(task = 'forecasting', \n",
|
"automl_config = AutoMLConfig(task='forecasting', \n",
|
||||||
" primary_metric='normalized_root_mean_squared_error',\n",
|
" primary_metric='normalized_root_mean_squared_error',\n",
|
||||||
" iterations = 10,\n",
|
" iterations=10,\n",
|
||||||
" iteration_timeout_minutes = 5,\n",
|
" iteration_timeout_minutes=5,\n",
|
||||||
" X = X_train,\n",
|
" X=X_train,\n",
|
||||||
" y = y_train,\n",
|
" y=y_train,\n",
|
||||||
" n_cross_validations = 3, \n",
|
" n_cross_validations=3, \n",
|
||||||
" path=project_folder,\n",
|
" path=project_folder,\n",
|
||||||
" verbosity = logging.INFO,\n",
|
" verbosity=logging.INFO,\n",
|
||||||
" **automl_settings)"
|
" **automl_settings)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -264,7 +260,7 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"We will now run the experiment, starting with 10 iterations of model search. Experiment can be continued for more iterations if the results are not yet good. You will see the currently running iterations printing to the console."
|
"We will now run the experiment, starting with 10 iterations of model search. The experiment can be continued for more iterations if more accurate results are required. You will see the currently running iterations printing to the console."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -349,18 +345,26 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"fitted_model.named_steps['timeseriestransformer'].get_featurization_summary()"
|
"# Get the featurization summary as a list of JSON\n",
|
||||||
|
"featurization_summary = fitted_model.named_steps['timeseriestransformer'].get_featurization_summary()\n",
|
||||||
|
"# View the featurization summary as a pandas dataframe\n",
|
||||||
|
"pd.DataFrame.from_records(featurization_summary)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"### Test the Best Fitted Model\n",
|
"## Evaluate"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"We now use the best fitted model from the AutoML Run to make forecasts for the test set. \n",
|
||||||
"\n",
|
"\n",
|
||||||
"Predict on training and test set, and calculate residual values.\n",
|
"We always score on the original dataset whose schema matches the training set schema."
|
||||||
"\n",
|
|
||||||
"We always score on the original dataset whose schema matches the scheme of the training dataset."
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -372,21 +376,12 @@
|
|||||||
"X_test.head()"
|
"X_test.head()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"y_query = y_test.copy().astype(np.float)\n",
|
|
||||||
"y_query.fill(np.NaN)\n",
|
|
||||||
"y_fcst, X_trans = fitted_model.forecast(X_test, y_query)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
|
"We now define some functions for aligning output to input and for producing rolling forecasts over the full test set. As previously stated, the forecast horizon of 14 days is shorter than the length of the test set - which is about 120 days. To get predictions over the full test set, we iterate over the test set, making forecasts 14 days at a time and combining the results. We also make sure that each 14-day forecast uses up-to-date actuals - the current context - to construct lag features. \n",
|
||||||
|
"\n",
|
||||||
"It is a good practice to always align the output explicitly to the input, as the count and order of the rows may have changed during transformations that span multiple rows."
|
"It is a good practice to always align the output explicitly to the input, as the count and order of the rows may have changed during transformations that span multiple rows."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -396,7 +391,8 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"def align_outputs(y_predicted, X_trans, X_test, y_test, predicted_column_name = 'predicted'):\n",
|
"def align_outputs(y_predicted, X_trans, X_test, y_test, predicted_column_name='predicted',\n",
|
||||||
|
" horizon_colname='horizon_origin'):\n",
|
||||||
" \"\"\"\n",
|
" \"\"\"\n",
|
||||||
" Demonstrates how to get the output aligned to the inputs\n",
|
" Demonstrates how to get the output aligned to the inputs\n",
|
||||||
" using pandas indexes. Helps understand what happened if\n",
|
" using pandas indexes. Helps understand what happened if\n",
|
||||||
@@ -408,7 +404,8 @@
|
|||||||
" * model was asked to predict past max_horizon -> increase max horizon\n",
|
" * model was asked to predict past max_horizon -> increase max horizon\n",
|
||||||
" * data at start of X_test was needed for lags -> provide previous periods\n",
|
" * data at start of X_test was needed for lags -> provide previous periods\n",
|
||||||
" \"\"\"\n",
|
" \"\"\"\n",
|
||||||
" df_fcst = pd.DataFrame({predicted_column_name : y_predicted})\n",
|
" df_fcst = pd.DataFrame({predicted_column_name : y_predicted,\n",
|
||||||
|
" horizon_colname: X_trans[horizon_colname]})\n",
|
||||||
" # y and X outputs are aligned by forecast() function contract\n",
|
" # y and X outputs are aligned by forecast() function contract\n",
|
||||||
" df_fcst.index = X_trans.index\n",
|
" df_fcst.index = X_trans.index\n",
|
||||||
" \n",
|
" \n",
|
||||||
@@ -427,7 +424,49 @@
|
|||||||
" clean = together[together[[target_column_name, predicted_column_name]].notnull().all(axis=1)]\n",
|
" clean = together[together[[target_column_name, predicted_column_name]].notnull().all(axis=1)]\n",
|
||||||
" return(clean)\n",
|
" return(clean)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"df_all = align_outputs(y_fcst, X_trans, X_test, y_test)\n"
|
"def do_rolling_forecast(fitted_model, X_test, y_test, max_horizon, freq='D'):\n",
|
||||||
|
" \"\"\"\n",
|
||||||
|
" Produce forecasts on a rolling origin over the given test set.\n",
|
||||||
|
" \n",
|
||||||
|
" Each iteration makes a forecast for the next 'max_horizon' periods \n",
|
||||||
|
" with respect to the current origin, then advances the origin by the horizon time duration. \n",
|
||||||
|
" The prediction context for each forecast is set so that the forecaster uses \n",
|
||||||
|
" the actual target values prior to the current origin time for constructing lag features.\n",
|
||||||
|
" \n",
|
||||||
|
" This function returns a concatenated DataFrame of rolling forecasts.\n",
|
||||||
|
" \"\"\"\n",
|
||||||
|
" df_list = []\n",
|
||||||
|
" origin_time = X_test[time_column_name].min()\n",
|
||||||
|
" while origin_time <= X_test[time_column_name].max():\n",
|
||||||
|
" # Set the horizon time - end date of the forecast\n",
|
||||||
|
" horizon_time = origin_time + max_horizon * to_offset(freq)\n",
|
||||||
|
" \n",
|
||||||
|
" # Extract test data from an expanding window up-to the horizon \n",
|
||||||
|
" expand_wind = (X_test[time_column_name] < horizon_time)\n",
|
||||||
|
" X_test_expand = X_test[expand_wind]\n",
|
||||||
|
" y_query_expand = np.zeros(len(X_test_expand)).astype(np.float)\n",
|
||||||
|
" y_query_expand.fill(np.NaN)\n",
|
||||||
|
" \n",
|
||||||
|
" if origin_time != X_test[time_column_name].min():\n",
|
||||||
|
" # Set the context by including actuals up-to the origin time\n",
|
||||||
|
" test_context_expand_wind = (X_test[time_column_name] < origin_time)\n",
|
||||||
|
" context_expand_wind = (X_test_expand[time_column_name] < origin_time)\n",
|
||||||
|
" y_query_expand[context_expand_wind] = y_test[test_context_expand_wind]\n",
|
||||||
|
" \n",
|
||||||
|
" # Make a forecast out to the maximum horizon\n",
|
||||||
|
" y_fcst, X_trans = fitted_model.forecast(X_test_expand, y_query_expand)\n",
|
||||||
|
" \n",
|
||||||
|
" # Align forecast with test set for dates within the current rolling window \n",
|
||||||
|
" trans_tindex = X_trans.index.get_level_values(time_column_name)\n",
|
||||||
|
" trans_roll_wind = (trans_tindex >= origin_time) & (trans_tindex < horizon_time)\n",
|
||||||
|
" test_roll_wind = expand_wind & (X_test[time_column_name] >= origin_time)\n",
|
||||||
|
" df_list.append(align_outputs(y_fcst[trans_roll_wind], X_trans[trans_roll_wind],\n",
|
||||||
|
" X_test[test_roll_wind], y_test[test_roll_wind]))\n",
|
||||||
|
" \n",
|
||||||
|
" # Advance the origin time\n",
|
||||||
|
" origin_time = horizon_time\n",
|
||||||
|
" \n",
|
||||||
|
" return pd.concat(df_list, ignore_index=True)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -436,6 +475,30 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
|
"df_all = do_rolling_forecast(fitted_model, X_test, y_test, max_horizon)\n",
|
||||||
|
"df_all"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"We now calculate some error metrics for the forecasts and vizualize the predictions vs. the actuals."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"def APE(actual, pred):\n",
|
||||||
|
" \"\"\"\n",
|
||||||
|
" Calculate absolute percentage error.\n",
|
||||||
|
" Returns a vector of APE values with same length as actual/pred.\n",
|
||||||
|
" \"\"\"\n",
|
||||||
|
" return 100*np.abs((actual - pred)/actual)\n",
|
||||||
|
"\n",
|
||||||
"def MAPE(actual, pred):\n",
|
"def MAPE(actual, pred):\n",
|
||||||
" \"\"\"\n",
|
" \"\"\"\n",
|
||||||
" Calculate mean absolute percentage error.\n",
|
" Calculate mean absolute percentage error.\n",
|
||||||
@@ -445,8 +508,7 @@
|
|||||||
" not_zero = ~np.isclose(actual, 0.0)\n",
|
" not_zero = ~np.isclose(actual, 0.0)\n",
|
||||||
" actual_safe = actual[not_na & not_zero]\n",
|
" actual_safe = actual[not_na & not_zero]\n",
|
||||||
" pred_safe = pred[not_na & not_zero]\n",
|
" pred_safe = pred[not_na & not_zero]\n",
|
||||||
" APE = 100*np.abs((actual_safe - pred_safe)/actual_safe)\n",
|
" return np.mean(APE(actual_safe, pred_safe))"
|
||||||
" return np.mean(APE)"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -463,18 +525,63 @@
|
|||||||
"print('MAPE: %.2f' % MAPE(df_all[target_column_name], df_all['predicted']))\n",
|
"print('MAPE: %.2f' % MAPE(df_all[target_column_name], df_all['predicted']))\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# Plot outputs\n",
|
"# Plot outputs\n",
|
||||||
"%matplotlib notebook\n",
|
"%matplotlib inline\n",
|
||||||
"test_pred = plt.scatter(df_all[target_column_name], df_all['predicted'], color='b')\n",
|
"test_pred = plt.scatter(df_all[target_column_name], df_all['predicted'], color='b')\n",
|
||||||
"test_test = plt.scatter(y_test, y_test, color='g')\n",
|
"test_test = plt.scatter(y_test, y_test, color='g')\n",
|
||||||
"plt.legend((test_pred, test_test), ('prediction', 'truth'), loc='upper left', fontsize=8)\n",
|
"plt.legend((test_pred, test_test), ('prediction', 'truth'), loc='upper left', fontsize=8)\n",
|
||||||
"plt.show()"
|
"plt.show()"
|
||||||
]
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"The MAPE seems high; it is being skewed by an actual with a small absolute value. For a more informative evaluation, we can calculate the metrics by forecast horizon:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"df_all.groupby('horizon_origin').apply(\n",
|
||||||
|
" lambda df: pd.Series({'MAPE': MAPE(df[target_column_name], df['predicted']),\n",
|
||||||
|
" 'RMSE': np.sqrt(mean_squared_error(df[target_column_name], df['predicted'])),\n",
|
||||||
|
" 'MAE': mean_absolute_error(df[target_column_name], df['predicted'])}))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"It's also interesting to see the distributions of APE (absolute percentage error) by horizon. On a log scale, the outlying APE in the horizon-3 group is clear."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"df_all_APE = df_all.assign(APE=APE(df_all[target_column_name], df_all['predicted']))\n",
|
||||||
|
"APEs = [df_all_APE[df_all['horizon_origin'] == h].APE.values for h in range(1, max_horizon + 1)]\n",
|
||||||
|
"\n",
|
||||||
|
"%matplotlib inline\n",
|
||||||
|
"plt.boxplot(APEs)\n",
|
||||||
|
"plt.yscale('log')\n",
|
||||||
|
"plt.xlabel('horizon')\n",
|
||||||
|
"plt.ylabel('APE (%)')\n",
|
||||||
|
"plt.title('Absolute Percentage Errors by Forecast Horizon')\n",
|
||||||
|
"\n",
|
||||||
|
"plt.show()"
|
||||||
|
]
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"authors": [
|
"authors": [
|
||||||
{
|
{
|
||||||
"name": "xiaga@microsoft.com, tosingli@microsoft.com"
|
"name": "erwright"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"kernelspec": {
|
"kernelspec": {
|
||||||
@@ -492,7 +599,7 @@
|
|||||||
"name": "python",
|
"name": "python",
|
||||||
"nbconvert_exporter": "python",
|
"nbconvert_exporter": "python",
|
||||||
"pygments_lexer": "ipython3",
|
"pygments_lexer": "ipython3",
|
||||||
"version": "3.6.7"
|
"version": "3.6.8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"nbformat": 4,
|
"nbformat": 4,
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
name: auto-ml-forecasting-bike-share
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
|
- azureml-train-automl
|
||||||
|
- azureml-widgets
|
||||||
|
- matplotlib
|
||||||
|
- pandas_ml
|
||||||
|
- statsmodels
|
||||||
@@ -35,17 +35,16 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Introduction\n",
|
"## Introduction\n",
|
||||||
"In this example, we show how AutoML can be used for energy demand forecasting.\n",
|
"In this example, we show how AutoML can be used to forecast a single time-series in the energy demand application area. \n",
|
||||||
"\n",
|
"\n",
|
||||||
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
|
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"In this notebook you would see\n",
|
"Notebook synopsis:\n",
|
||||||
"1. Creating an Experiment in an existing Workspace\n",
|
"1. Creating an Experiment in an existing Workspace\n",
|
||||||
"2. Instantiating AutoMLConfig with new task type \"forecasting\" for timeseries data training, and other timeseries related settings: for this dataset we use the basic one: \"time_column_name\" \n",
|
"2. Configuration and local run of AutoML for a simple time-series model\n",
|
||||||
"3. Training the Model using local compute\n",
|
"3. View engineered features and prediction results\n",
|
||||||
"4. Exploring the results\n",
|
"4. Configuration and local run of AutoML for a time-series model with lag and rolling window features\n",
|
||||||
"5. Viewing the engineered names for featurized data and featurization summary for all raw features\n",
|
"5. Estimate feature importance"
|
||||||
"6. Testing the fitted model"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -66,10 +65,10 @@
|
|||||||
"import numpy as np\n",
|
"import numpy as np\n",
|
||||||
"import logging\n",
|
"import logging\n",
|
||||||
"import warnings\n",
|
"import warnings\n",
|
||||||
|
"\n",
|
||||||
"# Squash warning messages for cleaner output in the notebook\n",
|
"# Squash warning messages for cleaner output in the notebook\n",
|
||||||
"warnings.showwarning = lambda *args, **kwargs: None\n",
|
"warnings.showwarning = lambda *args, **kwargs: None\n",
|
||||||
"\n",
|
"\n",
|
||||||
"\n",
|
|
||||||
"from azureml.core.workspace import Workspace\n",
|
"from azureml.core.workspace import Workspace\n",
|
||||||
"from azureml.core.experiment import Experiment\n",
|
"from azureml.core.experiment import Experiment\n",
|
||||||
"from azureml.train.automl import AutoMLConfig\n",
|
"from azureml.train.automl import AutoMLConfig\n",
|
||||||
@@ -81,7 +80,7 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"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."
|
"As part of the setup you have already created a <b>Workspace</b>. To run AutoML, you also need to create an <b>Experiment</b>. An Experiment corresponds to a prediction problem you are trying to solve, while a Run corresponds to a specific approach to the problem."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -117,7 +116,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Data\n",
|
"## Data\n",
|
||||||
"Read energy demanding data from file, and preview data."
|
"We will use energy consumption data from New York City for model training. The data is stored in a tabular format and includes energy demand and basic weather data at an hourly frequency. Pandas CSV reader is used to read the file into memory. Special attention is given to the \"timeStamp\" column in the data since it contains text which should be parsed as datetime-type objects. "
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -130,13 +129,20 @@
|
|||||||
"data.head()"
|
"data.head()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"We must now define the schema of this dataset. Every time-series must have a time column and a target. The target quantity is what will be eventually forecasted by a trained model. In this case, the target is the \"demand\" column. The other columns, \"temp\" and \"precip,\" are implicitly designated as features."
|
||||||
|
]
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"# let's take note of what columns means what in the data\n",
|
"# Dataset schema\n",
|
||||||
"time_column_name = 'timeStamp'\n",
|
"time_column_name = 'timeStamp'\n",
|
||||||
"target_column_name = 'demand'"
|
"target_column_name = 'demand'"
|
||||||
]
|
]
|
||||||
@@ -145,7 +151,14 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"### Split the data into train and test sets\n"
|
"### Forecast Horizon\n",
|
||||||
|
"\n",
|
||||||
|
"In addition to the data schema, we must also specify the forecast horizon. 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. Choosing a forecast horizon is application specific, but a rule-of-thumb is that **the horizon should be the time-frame where you need actionable decisions based on the forecast.** The horizon usually has a strong relationship with the frequency of the time-series data, that is, the sampling interval of the target quantity and the features. For instance, the NYC energy demand data has an hourly frequency. A decision that requires a demand forecast to the hour is unlikely to be made weeks or months in advance, particularly if we expect weather to be a strong determinant of demand. We may have fairly accurate meteorological forecasts of the hourly temperature and precipitation on a the time-scale of a day or two, however.\n",
|
||||||
|
"\n",
|
||||||
|
"Given the above discussion, we generally recommend that users set forecast horizons to less than 100 time periods (i.e. less than 100 hours in the NYC energy example). Furthermore, **AutoML's memory use and computation time increase in proportion to the length of the horizon**, so the user should consider carefully how they set this value. If a long horizon forecast really is necessary, it may be good practice to aggregate the series to a coarser time scale. \n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"Forecast horizons in AutoML are given as integer multiples of the time-series frequency. In this example, we set the horizon to 48 hours."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -154,8 +167,32 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"X_train = data[data[time_column_name] < '2017-02-01']\n",
|
"max_horizon = 48"
|
||||||
"X_test = data[data[time_column_name] >= '2017-02-01']\n",
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Split the data into train and test sets\n",
|
||||||
|
"We now split the data into a train and a test set so that we may evaluate model performance. We note that the tail of the dataset contains a large number of NA values in the target column, so we designate the test set as the 48 hour window ending on the latest date of known energy demand. "
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Find time point to split on\n",
|
||||||
|
"latest_known_time = data[~pd.isnull(data[target_column_name])][time_column_name].max()\n",
|
||||||
|
"split_time = latest_known_time - pd.Timedelta(hours=max_horizon)\n",
|
||||||
|
"\n",
|
||||||
|
"# Split into train/test sets\n",
|
||||||
|
"X_train = data[data[time_column_name] <= split_time]\n",
|
||||||
|
"X_test = data[(data[time_column_name] > split_time) & (data[time_column_name] <= latest_known_time)]\n",
|
||||||
|
"\n",
|
||||||
|
"# Move the target values into their own arrays \n",
|
||||||
"y_train = X_train.pop(target_column_name).values\n",
|
"y_train = X_train.pop(target_column_name).values\n",
|
||||||
"y_test = X_test.pop(target_column_name).values"
|
"y_test = X_test.pop(target_column_name).values"
|
||||||
]
|
]
|
||||||
@@ -166,7 +203,7 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"## Train\n",
|
"## Train\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Instantiate a AutoMLConfig object. This defines the settings and data used to run the experiment.\n",
|
"We now instantiate an AutoMLConfig object. This config defines the settings and data used to run the experiment. For forecasting tasks, we must provide extra configuration related to the time-series data schema and forecasting context. Here, only the name of the time column and the maximum forecast horizon are needed. Other settings are described below:\n",
|
||||||
"\n",
|
"\n",
|
||||||
"|Property|Description|\n",
|
"|Property|Description|\n",
|
||||||
"|-|-|\n",
|
"|-|-|\n",
|
||||||
@@ -176,7 +213,7 @@
|
|||||||
"|**iteration_timeout_minutes**|Time limit in minutes for each iteration.|\n",
|
"|**iteration_timeout_minutes**|Time limit in minutes for each iteration.|\n",
|
||||||
"|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n",
|
"|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n",
|
||||||
"|**y**|(sparse) array-like, shape = [n_samples, ], targets values.|\n",
|
"|**y**|(sparse) array-like, shape = [n_samples, ], targets values.|\n",
|
||||||
"|**n_cross_validations**|Number of cross validation splits.|\n",
|
"|**n_cross_validations**|Number of cross validation splits. Rolling Origin Validation is used to split time-series in a temporally consistent way.|\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. "
|
"|**path**|Relative path to the project folder. AutoML stores configuration files for the experiment under this folder. You can specify a new empty folder. "
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -186,22 +223,22 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"automl_settings = {\n",
|
"time_series_settings = {\n",
|
||||||
" \"time_column_name\": time_column_name \n",
|
" 'time_column_name': time_column_name,\n",
|
||||||
|
" 'max_horizon': max_horizon\n",
|
||||||
"}\n",
|
"}\n",
|
||||||
"\n",
|
"\n",
|
||||||
"\n",
|
"automl_config = AutoMLConfig(task='forecasting',\n",
|
||||||
"automl_config = AutoMLConfig(task = 'forecasting',\n",
|
" debug_log='automl_nyc_energy_errors.log',\n",
|
||||||
" debug_log = 'automl_nyc_energy_errors.log',\n",
|
|
||||||
" primary_metric='normalized_root_mean_squared_error',\n",
|
" primary_metric='normalized_root_mean_squared_error',\n",
|
||||||
" iterations = 10,\n",
|
" iterations=10,\n",
|
||||||
" iteration_timeout_minutes = 5,\n",
|
" iteration_timeout_minutes=5,\n",
|
||||||
" X = X_train,\n",
|
" X=X_train,\n",
|
||||||
" y = y_train,\n",
|
" y=y_train,\n",
|
||||||
" n_cross_validations = 3,\n",
|
" n_cross_validations=3,\n",
|
||||||
" path=project_folder,\n",
|
" path=project_folder,\n",
|
||||||
" verbosity = logging.INFO,\n",
|
" verbosity = logging.INFO,\n",
|
||||||
" **automl_settings)"
|
" **time_series_settings)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -358,7 +395,8 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"### Calculate accuracy metrics\n"
|
"### Calculate accuracy metrics\n",
|
||||||
|
"Finally, we calculate some accuracy metrics for the forecast and plot the predictions vs. the actuals over the time range in the test set."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -394,10 +432,13 @@
|
|||||||
"print('MAPE: %.2f' % MAPE(df_all[target_column_name], df_all['predicted']))\n",
|
"print('MAPE: %.2f' % MAPE(df_all[target_column_name], df_all['predicted']))\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# Plot outputs\n",
|
"# Plot outputs\n",
|
||||||
"%matplotlib notebook\n",
|
"%matplotlib inline\n",
|
||||||
"test_pred = plt.scatter(df_all[target_column_name], df_all['predicted'], color='b')\n",
|
"pred, = plt.plot(df_all[time_column_name], df_all['predicted'], color='b')\n",
|
||||||
"test_test = plt.scatter(y_test, y_test, color='g')\n",
|
"actual, = plt.plot(df_all[time_column_name], df_all[target_column_name], color='g')\n",
|
||||||
"plt.legend((test_pred, test_test), ('prediction', 'truth'), loc='upper left', fontsize=8)\n",
|
"plt.xticks(fontsize=8)\n",
|
||||||
|
"plt.legend((pred, actual), ('prediction', 'truth'), loc='upper left', fontsize=8)\n",
|
||||||
|
"plt.title('Prediction vs. Actual Time-Series')\n",
|
||||||
|
"\n",
|
||||||
"plt.show()"
|
"plt.show()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -412,16 +453,16 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"### Using lags and rolling window features to improve the forecast"
|
"### Using lags and rolling window features"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"We did not use lags in the previous model specification. In effect, the prediction was the result of a simple regression on date, grain and any additional features. This is often a very good prediction as common time series patterns like seasonality and trends can be captured in this manner. Such simple regression is horizon-less: it doesn't matter how far into the future we are predicting, because we are not using past data.\n",
|
"We did not use lags in the previous model specification. In effect, the prediction was the result of a simple regression on date, grain and any additional features. This is often a very good prediction as common time series patterns like seasonality and trends can be captured in this manner. Such simple regression is horizon-less: it doesn't matter how far into the future we are predicting, because we are not using past data. In the previous example, the horizon was only used to split the data for cross-validation.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Now that we configured target lags, that is the previous values of the target variables, and the prediction is no longer horizon-less. We therefore must specify the `max_horizon` that the model will learn to forecast. The `target_lags` keyword specifies how far back we will construct the lags of the target variable, and the `target_rolling_window_size` specifies the size of the rolling window over which we will generate the `max`, `min` and `sum` features."
|
"Now that we configured target lags, that is the previous values of the target variables, and the prediction is no longer horizon-less. We therefore must still specify the `max_horizon` that the model will learn to forecast. The `target_lags` keyword specifies how far back we will construct the lags of the target variable, and the `target_rolling_window_size` specifies the size of the rolling window over which we will generate the `max`, `min` and `sum` features."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -430,27 +471,32 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"automl_settings_lags = {\n",
|
"time_series_settings_with_lags = {\n",
|
||||||
" 'time_column_name': time_column_name,\n",
|
" 'time_column_name': time_column_name,\n",
|
||||||
" 'target_lags': 1,\n",
|
" 'max_horizon': max_horizon,\n",
|
||||||
" 'target_rolling_window_size': 5,\n",
|
" 'target_lags': 12,\n",
|
||||||
" # you MUST set the max_horizon when using lags and rolling windows\n",
|
" 'target_rolling_window_size': 4\n",
|
||||||
" # it is optional when looking-back features are not used \n",
|
|
||||||
" 'max_horizon': len(y_test), # only one grain\n",
|
|
||||||
"}\n",
|
"}\n",
|
||||||
"\n",
|
"\n",
|
||||||
"\n",
|
"automl_config_lags = AutoMLConfig(task='forecasting',\n",
|
||||||
"automl_config_lags = AutoMLConfig(task = 'forecasting',\n",
|
" debug_log='automl_nyc_energy_errors.log',\n",
|
||||||
" debug_log = 'automl_nyc_energy_errors.log',\n",
|
" primary_metric='normalized_root_mean_squared_error',\n",
|
||||||
" primary_metric='normalized_root_mean_squared_error',\n",
|
" blacklist_models=['ElasticNet'],\n",
|
||||||
" iterations = 10,\n",
|
" iterations=10,\n",
|
||||||
" iteration_timeout_minutes = 5,\n",
|
" iteration_timeout_minutes=10,\n",
|
||||||
" X = X_train,\n",
|
" X=X_train,\n",
|
||||||
" y = y_train,\n",
|
" y=y_train,\n",
|
||||||
" n_cross_validations = 3,\n",
|
" n_cross_validations=3,\n",
|
||||||
" path=project_folder,\n",
|
" path=project_folder,\n",
|
||||||
" verbosity = logging.INFO,\n",
|
" verbosity=logging.INFO,\n",
|
||||||
" **automl_settings_lags)"
|
" **time_series_settings_with_lags)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"We now start a new local run, this time with lag and rolling window featurization. AutoML applies featurizations in the setup stage, prior to iterating over ML models. The full training set is featurized first, followed by featurization of each of the CV splits. Lag and rolling window features introduce additional complexity, so the run will take longer than in the previous example that lacked these featurizations."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -497,10 +543,11 @@
|
|||||||
"print('MAPE: %.2f' % MAPE(df_lags[target_column_name], df_lags['predicted']))\n",
|
"print('MAPE: %.2f' % MAPE(df_lags[target_column_name], df_lags['predicted']))\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# Plot outputs\n",
|
"# Plot outputs\n",
|
||||||
"%matplotlib notebook\n",
|
"%matplotlib inline\n",
|
||||||
"test_pred = plt.scatter(df_lags[target_column_name], df_lags['predicted'], color='b')\n",
|
"pred, = plt.plot(df_lags[time_column_name], df_lags['predicted'], color='b')\n",
|
||||||
"test_test = plt.scatter(y_test, y_test, color='g')\n",
|
"actual, = plt.plot(df_lags[time_column_name], df_lags[target_column_name], color='g')\n",
|
||||||
"plt.legend((test_pred, test_test), ('prediction', 'truth'), loc='upper left', fontsize=8)\n",
|
"plt.xticks(fontsize=8)\n",
|
||||||
|
"plt.legend((pred, actual), ('prediction', 'truth'), loc='upper left', fontsize=8)\n",
|
||||||
"plt.show()"
|
"plt.show()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -520,8 +567,8 @@
|
|||||||
"from azureml.train.automl.automlexplainer import explain_model\n",
|
"from azureml.train.automl.automlexplainer import explain_model\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# feature names are everything in the transformed data except the target\n",
|
"# feature names are everything in the transformed data except the target\n",
|
||||||
"features = X_trans.columns[:-1]\n",
|
"features = X_trans_lags.columns[:-1]\n",
|
||||||
"expl = explain_model(fitted_model, X_train, X_test, features = features, best_run=best_run_lags, y_train = y_train)\n",
|
"expl = explain_model(fitted_model_lags, X_train.copy(), X_test.copy(), features=features, best_run=best_run_lags, y_train=y_train)\n",
|
||||||
"# unpack the tuple\n",
|
"# unpack the tuple\n",
|
||||||
"shap_values, expected_values, feat_overall_imp, feat_names, per_class_summary, per_class_imp = expl\n",
|
"shap_values, expected_values, feat_overall_imp, feat_names, per_class_summary, per_class_imp = expl\n",
|
||||||
"best_run_lags"
|
"best_run_lags"
|
||||||
@@ -540,7 +587,7 @@
|
|||||||
"metadata": {
|
"metadata": {
|
||||||
"authors": [
|
"authors": [
|
||||||
{
|
{
|
||||||
"name": "xiaga, tosingli"
|
"name": "erwright"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"kernelspec": {
|
"kernelspec": {
|
||||||
@@ -558,7 +605,7 @@
|
|||||||
"name": "python",
|
"name": "python",
|
||||||
"nbconvert_exporter": "python",
|
"nbconvert_exporter": "python",
|
||||||
"pygments_lexer": "ipython3",
|
"pygments_lexer": "ipython3",
|
||||||
"version": "3.6.7"
|
"version": "3.6.8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"nbformat": 4,
|
"nbformat": 4,
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
name: auto-ml-forecasting-energy-demand
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
|
- azureml-train-automl
|
||||||
|
- azureml-widgets
|
||||||
|
- matplotlib
|
||||||
|
- pandas_ml
|
||||||
|
- statsmodels
|
||||||
|
- azureml-explain-model
|
||||||
@@ -37,16 +37,10 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Introduction\n",
|
"## Introduction\n",
|
||||||
"In this example, we use AutoML to find and tune a time-series forecasting model.\n",
|
"In this example, we use AutoML to train, select, and operationalize a time-series forecasting model for multiple time-series.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Make sure you have executed the [configuration notebook](../../../configuration.ipynb) before running this notebook.\n",
|
"Make sure you have executed the [configuration notebook](../../../configuration.ipynb) before running this notebook.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"In this notebook, you will:\n",
|
|
||||||
"1. Create an Experiment in an existing Workspace\n",
|
|
||||||
"2. Instantiate an AutoMLConfig \n",
|
|
||||||
"3. Find and train a forecasting model using local compute\n",
|
|
||||||
"4. Evaluate the performance of the model\n",
|
|
||||||
"\n",
|
|
||||||
"The examples in the follow code samples use the University of Chicago's Dominick's Finer Foods dataset to forecast orange juice sales. Dominick's was a grocery chain in the Chicago metropolitan area."
|
"The examples in the follow code samples use the University of Chicago's Dominick's Finer Foods dataset to forecast orange juice sales. Dominick's was a grocery chain in the Chicago metropolitan area."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -68,10 +62,10 @@
|
|||||||
"import numpy as np\n",
|
"import numpy as np\n",
|
||||||
"import logging\n",
|
"import logging\n",
|
||||||
"import warnings\n",
|
"import warnings\n",
|
||||||
|
"\n",
|
||||||
"# Squash warning messages for cleaner output in the notebook\n",
|
"# Squash warning messages for cleaner output in the notebook\n",
|
||||||
"warnings.showwarning = lambda *args, **kwargs: None\n",
|
"warnings.showwarning = lambda *args, **kwargs: None\n",
|
||||||
"\n",
|
"\n",
|
||||||
"\n",
|
|
||||||
"from azureml.core.workspace import Workspace\n",
|
"from azureml.core.workspace import Workspace\n",
|
||||||
"from azureml.core.experiment import Experiment\n",
|
"from azureml.core.experiment import Experiment\n",
|
||||||
"from azureml.train.automl import AutoMLConfig\n",
|
"from azureml.train.automl import AutoMLConfig\n",
|
||||||
@@ -82,7 +76,7 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"As part of the setup you have already created a <b>Workspace</b>. To run AutoML, you also need to create an <b>Experiment</b>. An Experiment is a named object in a Workspace which represents a predictive task, the output of which is a trained model and a set of evaluation metrics for the model. "
|
"As part of the setup you have already created a <b>Workspace</b>. To run AutoML, you also need to create an <b>Experiment</b>. An Experiment corresponds to a prediction problem you are trying to solve, while a Run corresponds to a specific approach to the problem. "
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -236,7 +230,7 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"For forecasting tasks, there are some additional parameters that can be set: the name of the column holding the date/time, the grain column names, and the maximum forecast horizon. A time column is required for forecasting, while the grain is optional. If a grain is not given, AutoML assumes that the whole dataset is a single time-series. We also pass a list of columns to drop prior to modeling. The _logQuantity_ column is completely correlated with the target quantity, so it must be removed to prevent a target leak.\n",
|
"For forecasting tasks, there are some additional parameters that can be set: the name of the column holding the date/time, the grain column names, and the maximum forecast horizon. A time column is required for forecasting, while the grain is optional. If a grain is not given, AutoML assumes that the whole dataset is a single time-series. We also pass a list of columns to drop prior to modeling. The _logQuantity_ column is completely correlated with the target quantity, so it must be removed to prevent a target leak.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"The forecast horizon is given in units of the time-series frequency; for instance, the OJ series frequency is weekly, so a horizon of 20 means that a trained model will estimate sales up-to 20 weeks beyond the latest date in the training data for each series. In this example, we set the maximum horizon to the number of samples per series in the test set (n_test_periods). Generally, the value of this parameter will be dictated by business needs. For example, a demand planning organizaion that needs to estimate the next month of sales would set the horizon accordingly. \n",
|
"The forecast horizon is given in units of the time-series frequency; for instance, the OJ series frequency is weekly, so a horizon of 20 means that a trained model will estimate sales up-to 20 weeks beyond the latest date in the training data for each series. In this example, we set the maximum horizon to the number of samples per series in the test set (n_test_periods). Generally, the value of this parameter will be dictated by business needs. For example, a demand planning organizaion that needs to estimate the next month of sales would set the horizon accordingly. Please see the [energy_demand notebook](https://github.com/Azure/MachineLearningNotebooks/tree/master/how-to-use-azureml/automated-machine-learning/forecasting-energy-demand) for more discussion of forecast horizon.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Finally, a note about the cross-validation (CV) procedure for time-series data. AutoML uses out-of-sample error estimates to select a best pipeline/model, so it is important that the CV fold splitting is done correctly. Time-series can violate the basic statistical assumptions of the canonical K-Fold CV strategy, so AutoML implements a [rolling origin validation](https://robjhyndman.com/hyndsight/tscv/) procedure to create CV folds for time-series data. To use this procedure, you just need to specify the desired number of CV folds in the AutoMLConfig object. It is also possible to bypass CV and use your own validation set by setting the *X_valid* and *y_valid* parameters of AutoMLConfig.\n",
|
"Finally, a note about the cross-validation (CV) procedure for time-series data. AutoML uses out-of-sample error estimates to select a best pipeline/model, so it is important that the CV fold splitting is done correctly. Time-series can violate the basic statistical assumptions of the canonical K-Fold CV strategy, so AutoML implements a [rolling origin validation](https://robjhyndman.com/hyndsight/tscv/) procedure to create CV folds for time-series data. To use this procedure, you just need to specify the desired number of CV folds in the AutoMLConfig object. It is also possible to bypass CV and use your own validation set by setting the *X_valid* and *y_valid* parameters of AutoMLConfig.\n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -269,7 +263,7 @@
|
|||||||
" 'time_column_name': time_column_name,\n",
|
" 'time_column_name': time_column_name,\n",
|
||||||
" 'grain_column_names': grain_column_names,\n",
|
" 'grain_column_names': grain_column_names,\n",
|
||||||
" 'drop_column_names': ['logQuantity'],\n",
|
" 'drop_column_names': ['logQuantity'],\n",
|
||||||
" 'max_horizon': n_test_periods # optional\n",
|
" 'max_horizon': n_test_periods\n",
|
||||||
"}\n",
|
"}\n",
|
||||||
"\n",
|
"\n",
|
||||||
"automl_config = AutoMLConfig(task='forecasting',\n",
|
"automl_config = AutoMLConfig(task='forecasting',\n",
|
||||||
@@ -278,7 +272,7 @@
|
|||||||
" iterations=10,\n",
|
" iterations=10,\n",
|
||||||
" X=X_train,\n",
|
" X=X_train,\n",
|
||||||
" y=y_train,\n",
|
" y=y_train,\n",
|
||||||
" n_cross_validations=5,\n",
|
" n_cross_validations=3,\n",
|
||||||
" enable_ensembling=False,\n",
|
" enable_ensembling=False,\n",
|
||||||
" path=project_folder,\n",
|
" path=project_folder,\n",
|
||||||
" verbosity=logging.INFO,\n",
|
" verbosity=logging.INFO,\n",
|
||||||
@@ -324,7 +318,8 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"# Predict\n",
|
"# Forecasting\n",
|
||||||
|
"\n",
|
||||||
"Now that we have retrieved the best pipeline/model, it can be used to make predictions on test data. First, we remove the target values from the test set:"
|
"Now that we have retrieved the best pipeline/model, it can be used to make predictions on test data. First, we remove the target values from the test set:"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -468,7 +463,7 @@
|
|||||||
"# Plot outputs\n",
|
"# Plot outputs\n",
|
||||||
"import matplotlib.pyplot as plt\n",
|
"import matplotlib.pyplot as plt\n",
|
||||||
"\n",
|
"\n",
|
||||||
"%matplotlib notebook\n",
|
"%matplotlib inline\n",
|
||||||
"test_pred = plt.scatter(df_all[target_column_name], df_all['predicted'], color='b')\n",
|
"test_pred = plt.scatter(df_all[target_column_name], df_all['predicted'], color='b')\n",
|
||||||
"test_test = plt.scatter(y_test, y_test, color='g')\n",
|
"test_test = plt.scatter(y_test, y_test, color='g')\n",
|
||||||
"plt.legend((test_pred, test_test), ('prediction', 'truth'), loc='upper left', fontsize=8)\n",
|
"plt.legend((test_pred, test_test), ('prediction', 'truth'), loc='upper left', fontsize=8)\n",
|
||||||
@@ -834,7 +829,7 @@
|
|||||||
"metadata": {
|
"metadata": {
|
||||||
"authors": [
|
"authors": [
|
||||||
{
|
{
|
||||||
"name": "erwright, tosingli"
|
"name": "erwright"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"kernelspec": {
|
"kernelspec": {
|
||||||
@@ -852,7 +847,7 @@
|
|||||||
"name": "python",
|
"name": "python",
|
||||||
"nbconvert_exporter": "python",
|
"nbconvert_exporter": "python",
|
||||||
"pygments_lexer": "ipython3",
|
"pygments_lexer": "ipython3",
|
||||||
"version": "3.6.7"
|
"version": "3.6.8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"nbformat": 4,
|
"nbformat": 4,
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
name: auto-ml-forecasting-orange-juice-sales
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
|
- azureml-train-automl
|
||||||
|
- azureml-widgets
|
||||||
|
- matplotlib
|
||||||
|
- pandas_ml
|
||||||
|
- statsmodels
|
||||||
@@ -360,7 +360,10 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"fitted_model.named_steps['datatransformer'].get_featurization_summary()"
|
"# 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",
|
||||||
|
"pd.DataFrame.from_records(featurization_summary)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
name: auto-ml-missing-data-blacklist-early-termination
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
|
- azureml-train-automl
|
||||||
|
- azureml-widgets
|
||||||
|
- matplotlib
|
||||||
|
- pandas_ml
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
name: auto-ml-model-explanation
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
|
- azureml-train-automl
|
||||||
|
- azureml-widgets
|
||||||
|
- matplotlib
|
||||||
|
- pandas_ml
|
||||||
|
- azureml-explain-model
|
||||||
@@ -0,0 +1,802 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
||||||
|
"\n",
|
||||||
|
"Licensed under the MIT License."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
""
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Automated Machine Learning\n",
|
||||||
|
"_**Regression with Deployment using Hardware Performance Dataset**_\n",
|
||||||
|
"\n",
|
||||||
|
"## Contents\n",
|
||||||
|
"1. [Introduction](#Introduction)\n",
|
||||||
|
"1. [Setup](#Setup)\n",
|
||||||
|
"1. [Data](#Data)\n",
|
||||||
|
"1. [Train](#Train)\n",
|
||||||
|
"1. [Results](#Results)\n",
|
||||||
|
"1. [Test](#Test)\n",
|
||||||
|
"1. [Acknowledgements](#Acknowledgements)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Introduction\n",
|
||||||
|
"In this example we use the Predicting Compressive Strength of Concrete Dataset to showcase how you can use AutoML for a regression problem. The regression goal is to predict the compressive strength of concrete based off of different ingredient combinations and the quantities of those ingredients.\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 local compute.\n",
|
||||||
|
"4. Explore the results.\n",
|
||||||
|
"5. Test the best fitted model."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Setup\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 numpy as np\n",
|
||||||
|
"import pandas as pd\n",
|
||||||
|
"import os\n",
|
||||||
|
"from sklearn.model_selection import train_test_split\n",
|
||||||
|
"import azureml.dataprep as dprep\n",
|
||||||
|
" \n",
|
||||||
|
"\n",
|
||||||
|
"import azureml.core\n",
|
||||||
|
"from azureml.core.experiment import Experiment\n",
|
||||||
|
"from azureml.core.workspace import Workspace\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 the experiment and specify the project folder.\n",
|
||||||
|
"experiment_name = 'automl-regression-concrete'\n",
|
||||||
|
"project_folder = './sample_projects/automl-regression-concrete'\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['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",
|
||||||
|
"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",
|
||||||
|
" # 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",
|
||||||
|
"\n",
|
||||||
|
"Here load the data in the get_data script to be utilized in azure compute. To do this, first load all the necessary libraries and dependencies to set up paths for the data and to create the conda_run_config."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"if not os.path.isdir('data'):\n",
|
||||||
|
" os.mkdir('data')\n",
|
||||||
|
" \n",
|
||||||
|
"if not os.path.exists(project_folder):\n",
|
||||||
|
" os.makedirs(project_folder)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"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",
|
||||||
|
"conda_run_config.environment.docker.base_image = azureml.core.runconfig.DEFAULT_CPU_IMAGE\n",
|
||||||
|
"\n",
|
||||||
|
"dprep_dependency = 'azureml-dataprep==' + pkg_resources.get_distribution(\"azureml-dataprep\").version\n",
|
||||||
|
"\n",
|
||||||
|
"cd = CondaDependencies.create(pip_packages=['azureml-sdk[automl]', dprep_dependency], conda_packages=['numpy'])\n",
|
||||||
|
"conda_run_config.environment.python.conda_dependencies = cd"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Load Data\n",
|
||||||
|
"\n",
|
||||||
|
"Here create the script to be run in azure compute for loading the data, load the concrete strength dataset into the X and y variables. Next, split the data using train_test_split and return X_train and y_train for training the model. Finally, return X_train and y_train for training the model."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"data = \"https://automlsamplenotebookdata.blob.core.windows.net/automl-sample-notebook-data/compresive_strength_concrete.csv\"\n",
|
||||||
|
"dflow = dprep.read_csv(data, infer_column_types=True)\n",
|
||||||
|
"dflow.get_profile()\n",
|
||||||
|
"X = dflow.drop_columns(columns=['CONCRETE'])\n",
|
||||||
|
"y = dflow.keep_columns(columns=['CONCRETE'], validate_column_exists=True)\n",
|
||||||
|
"X_train, X_test = X.random_split(percentage=0.8, seed=223)\n",
|
||||||
|
"y_train, y_test = y.random_split(percentage=0.8, seed=223) \n",
|
||||||
|
"dflow.head()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"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",
|
||||||
|
"|**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",
|
||||||
|
"\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": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"##### If you would like to see even better results increase \"iteration_time_out minutes\" to 10+ mins and increase \"iterations\" to a minimum of 30"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"automl_settings = {\n",
|
||||||
|
" \"iteration_timeout_minutes\": 5,\n",
|
||||||
|
" \"iterations\": 10,\n",
|
||||||
|
" \"n_cross_validations\": 5,\n",
|
||||||
|
" \"primary_metric\": 'spearman_correlation',\n",
|
||||||
|
" \"preprocess\": True,\n",
|
||||||
|
" \"max_concurrent_iterations\": 5,\n",
|
||||||
|
" \"verbosity\": logging.INFO,\n",
|
||||||
|
"}\n",
|
||||||
|
"\n",
|
||||||
|
"automl_config = AutoMLConfig(task = 'regression',\n",
|
||||||
|
" debug_log = 'automl.log',\n",
|
||||||
|
" path = project_folder,\n",
|
||||||
|
" run_configuration=conda_run_config,\n",
|
||||||
|
" X = X_train,\n",
|
||||||
|
" y = y_train,\n",
|
||||||
|
" **automl_settings\n",
|
||||||
|
" )"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"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\n",
|
||||||
|
"Widget for Monitoring Runs\n",
|
||||||
|
"The widget will first report a \u00e2\u20ac\u0153loading 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",
|
||||||
|
"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": [
|
||||||
|
"\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,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"children = list(remote_run.get_children())\n",
|
||||||
|
"metricslist = {}\n",
|
||||||
|
"for run in children:\n",
|
||||||
|
" properties = run.get_properties()\n",
|
||||||
|
" metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)}\n",
|
||||||
|
" metricslist[int(properties['iteration'])] = metrics\n",
|
||||||
|
"\n",
|
||||||
|
"rundata = pd.DataFrame(metricslist).sort_index(1)\n",
|
||||||
|
"rundata"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Retrieve the Best Model\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,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"best_run, fitted_model = remote_run.get_output()\n",
|
||||||
|
"print(best_run)\n",
|
||||||
|
"print(fitted_model)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Best Model Based on Any Other Metric\n",
|
||||||
|
"Show the run and the model that has the smallest root_mean_squared_error value (which turned out to be the same as the one with largest spearman_correlation value):"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"lookup_metric = \"root_mean_squared_error\"\n",
|
||||||
|
"best_run, fitted_model = remote_run.get_output(metric = lookup_metric)\n",
|
||||||
|
"print(best_run)\n",
|
||||||
|
"print(fitted_model)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"iteration = 3\n",
|
||||||
|
"third_run, third_model = remote_run.get_output(iteration = iteration)\n",
|
||||||
|
"print(third_run)\n",
|
||||||
|
"print(third_model)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Register the 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": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"description = 'AutoML Model'\n",
|
||||||
|
"tags = None\n",
|
||||||
|
"model = remote_run.register_model(description = description, tags = tags)\n",
|
||||||
|
"\n",
|
||||||
|
"print(remote_run.model_id) # This will be written to the script file later in the notebook."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Create Scoring Script\n",
|
||||||
|
"The scoring script is required to generate the image for deployment. It contains the code to do the predictions on input data."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"%%writefile score.py\n",
|
||||||
|
"import pickle\n",
|
||||||
|
"import json\n",
|
||||||
|
"import numpy\n",
|
||||||
|
"import azureml.train.automl\n",
|
||||||
|
"from sklearn.externals import joblib\n",
|
||||||
|
"from azureml.core.model import Model\n",
|
||||||
|
"\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",
|
||||||
|
" # deserialize the model file back into a sklearn model\n",
|
||||||
|
" model = joblib.load(model_path)\n",
|
||||||
|
"\n",
|
||||||
|
"def run(rawdata):\n",
|
||||||
|
" try:\n",
|
||||||
|
" data = json.loads(rawdata)['data']\n",
|
||||||
|
" data = numpy.array(data)\n",
|
||||||
|
" result = model.predict(data)\n",
|
||||||
|
" except Exception as e:\n",
|
||||||
|
" result = str(e)\n",
|
||||||
|
" return json.dumps({\"error\": result})\n",
|
||||||
|
" return json.dumps({\"result\":result.tolist()})"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Create a YAML File for the Environment"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"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. Details about retrieving the versions can be found in notebook [12.auto-ml-retrieve-the-training-sdk-versions](12.auto-ml-retrieve-the-training-sdk-versions.ipynb)."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"dependencies = remote_run.get_run_sdk_dependencies(iteration = 1)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"for p in ['azureml-train-automl', 'azureml-sdk', 'azureml-core']:\n",
|
||||||
|
" print('{}\\t{}'.format(p, dependencies[p]))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core.conda_dependencies import CondaDependencies\n",
|
||||||
|
"\n",
|
||||||
|
"myenv = CondaDependencies.create(conda_packages=['numpy','scikit-learn'], pip_packages=['azureml-sdk[automl]'])\n",
|
||||||
|
"\n",
|
||||||
|
"conda_env_file_name = 'myenv.yml'\n",
|
||||||
|
"myenv.save_to_file('.', conda_env_file_name)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"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",
|
||||||
|
"# However, we include this in case this code is used on an experiment from a previous SDK version.\n",
|
||||||
|
"\n",
|
||||||
|
"with open(conda_env_file_name, 'r') as cefr:\n",
|
||||||
|
" content = cefr.read()\n",
|
||||||
|
"\n",
|
||||||
|
"with open(conda_env_file_name, 'w') as cefw:\n",
|
||||||
|
" cefw.write(content.replace(azureml.core.VERSION, dependencies['azureml-sdk']))\n",
|
||||||
|
"\n",
|
||||||
|
"# Substitute the actual model id in the script file.\n",
|
||||||
|
"\n",
|
||||||
|
"script_file_name = 'score.py'\n",
|
||||||
|
"\n",
|
||||||
|
"with open(script_file_name, 'r') as cefr:\n",
|
||||||
|
" content = cefr.read()\n",
|
||||||
|
"\n",
|
||||||
|
"with open(script_file_name, 'w') as cefw:\n",
|
||||||
|
" cefw.write(content.replace('<<modelid>>', remote_run.model_id))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Create a Container Image\n",
|
||||||
|
"\n",
|
||||||
|
"Next use Azure Container Instances for deploying models as a web service for quickly deploying and validating your model\n",
|
||||||
|
"or when testing a model that is under development."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core.image import Image, ContainerImage\n",
|
||||||
|
"\n",
|
||||||
|
"image_config = ContainerImage.image_configuration(runtime= \"python\",\n",
|
||||||
|
" execution_script = script_file_name,\n",
|
||||||
|
" conda_file = conda_env_file_name,\n",
|
||||||
|
" tags = {'area': \"digits\", 'type': \"automl_regression\"},\n",
|
||||||
|
" description = \"Image for automl regression sample\")\n",
|
||||||
|
"\n",
|
||||||
|
"image = Image.create(name = \"automlsampleimage\",\n",
|
||||||
|
" # this is the model object \n",
|
||||||
|
" models = [model],\n",
|
||||||
|
" image_config = image_config, \n",
|
||||||
|
" workspace = ws)\n",
|
||||||
|
"\n",
|
||||||
|
"image.wait_for_creation(show_output = True)\n",
|
||||||
|
"\n",
|
||||||
|
"if image.creation_state == 'Failed':\n",
|
||||||
|
" print(\"Image build log at: \" + image.image_build_log_uri)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Deploy the Image as a Web Service on Azure Container Instance\n",
|
||||||
|
"\n",
|
||||||
|
"Deploy an image that contains the model and other assets needed by the service."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core.webservice import AciWebservice\n",
|
||||||
|
"\n",
|
||||||
|
"aciconfig = AciWebservice.deploy_configuration(cpu_cores = 1, \n",
|
||||||
|
" memory_gb = 1, \n",
|
||||||
|
" tags = {'area': \"digits\", 'type': \"automl_regression\"}, \n",
|
||||||
|
" description = 'sample service for Automl Regression')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core.webservice import Webservice\n",
|
||||||
|
"\n",
|
||||||
|
"aci_service_name = 'automl-sample-concrete'\n",
|
||||||
|
"print(aci_service_name)\n",
|
||||||
|
"aci_service = Webservice.deploy_from_image(deployment_config = aciconfig,\n",
|
||||||
|
" image = image,\n",
|
||||||
|
" name = aci_service_name,\n",
|
||||||
|
" workspace = ws)\n",
|
||||||
|
"aci_service.wait_for_deployment(True)\n",
|
||||||
|
"print(aci_service.state)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Delete a Web Service\n",
|
||||||
|
"\n",
|
||||||
|
"Deletes the specified web service."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"#aci_service.delete()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Get Logs from a Deployed Web Service\n",
|
||||||
|
"\n",
|
||||||
|
"Gets logs from a deployed web service."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"#aci_service.get_logs()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Test\n",
|
||||||
|
"\n",
|
||||||
|
"Now that the model is trained, split the data in the same way the data was split for training (The difference here is the data is being split locally) and then run the test data through the trained model to get the predicted values."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"X_test = X_test.to_pandas_dataframe()\n",
|
||||||
|
"y_test = y_test.to_pandas_dataframe()\n",
|
||||||
|
"y_test = np.array(y_test)\n",
|
||||||
|
"y_test = y_test[:,0]\n",
|
||||||
|
"X_train = X_train.to_pandas_dataframe()\n",
|
||||||
|
"y_train = y_train.to_pandas_dataframe()\n",
|
||||||
|
"y_train = np.array(y_train)\n",
|
||||||
|
"y_train = y_train[:,0]"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"##### Predict on training and test set, and calculate residual values."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"y_pred_train = fitted_model.predict(X_train)\n",
|
||||||
|
"y_residual_train = y_train - y_pred_train\n",
|
||||||
|
"\n",
|
||||||
|
"y_pred_test = fitted_model.predict(X_test)\n",
|
||||||
|
"y_residual_test = y_test - y_pred_test\n",
|
||||||
|
"\n",
|
||||||
|
"y_residual_train.shape"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"%matplotlib inline\n",
|
||||||
|
"from sklearn.metrics import mean_squared_error, r2_score\n",
|
||||||
|
"\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",
|
||||||
|
"f.suptitle('Regression Residual Values', fontsize = 18)\n",
|
||||||
|
"f.set_figheight(6)\n",
|
||||||
|
"f.set_figwidth(16)\n",
|
||||||
|
"\n",
|
||||||
|
"# Plot residual values of training set.\n",
|
||||||
|
"a0.axis([0, 360, -200, 200])\n",
|
||||||
|
"a0.plot(y_residual_train, 'bo', alpha = 0.5)\n",
|
||||||
|
"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",
|
||||||
|
"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",
|
||||||
|
"\n",
|
||||||
|
"# Plot a histogram.\n",
|
||||||
|
"#a0.hist(y_residual_train, orientation = 'horizontal', color = ['b']*len(y_residual_train), bins = 10, histtype = 'step')\n",
|
||||||
|
"#a0.hist(y_residual_train, orientation = 'horizontal', color = ['b']*len(y_residual_train), alpha = 0.2, bins = 10)\n",
|
||||||
|
"\n",
|
||||||
|
"# Plot residual values of test set.\n",
|
||||||
|
"a1.axis([0, 90, -200, 200])\n",
|
||||||
|
"a1.plot(y_residual_test, 'bo', alpha = 0.5)\n",
|
||||||
|
"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",
|
||||||
|
"a1.text(5,140,'R2 score = {0:.2f}'.format(r2_score(y_test, y_pred_test)), fontsize = 12)\n",
|
||||||
|
"a1.set_xlabel('Test samples', fontsize = 12)\n",
|
||||||
|
"a1.set_yticklabels([])\n",
|
||||||
|
"\n",
|
||||||
|
"# Plot a histogram.\n",
|
||||||
|
"#a1.hist(y_residual_test, orientation = 'horizontal', color = ['b']*len(y_residual_test), bins = 10, histtype = 'step')\n",
|
||||||
|
"#a1.hist(y_residual_test, orientation = 'horizontal', color = ['b']*len(y_residual_test), alpha = 0.2, bins = 10)\n",
|
||||||
|
"\n",
|
||||||
|
"plt.show()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Calculate metrics for the prediction\n",
|
||||||
|
"\n",
|
||||||
|
"Now visualize the data on a scatter plot to show what our truth (actual) values are compared to the predicted values \n",
|
||||||
|
"from the trained model that was returned."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Plot outputs\n",
|
||||||
|
"%matplotlib notebook\n",
|
||||||
|
"test_pred = plt.scatter(y_test, y_pred_test, color='b')\n",
|
||||||
|
"test_test = plt.scatter(y_test, y_test, color='g')\n",
|
||||||
|
"plt.legend((test_pred, test_test), ('prediction', 'truth'), loc='upper left', fontsize=8)\n",
|
||||||
|
"plt.show()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Acknowledgements\n",
|
||||||
|
"\n",
|
||||||
|
"This Predicting Compressive Strength of Concrete Dataset is made available under the CC0 1.0 Universal (CC0 1.0)\n",
|
||||||
|
"Public Domain Dedication License: https://creativecommons.org/publicdomain/zero/1.0/. Any rights in individual contents of the database are licensed under the CC0 1.0 Universal (CC0 1.0)\n",
|
||||||
|
"Public Domain Dedication License: https://creativecommons.org/publicdomain/zero/1.0/ . The dataset itself can be found here: https://www.kaggle.com/pavanraj159/concrete-compressive-strength-data-set and http://archive.ics.uci.edu/ml/datasets/concrete+compressive+strength\n",
|
||||||
|
"\n",
|
||||||
|
"I-Cheng Yeh, \"Modeling of strength of high performance concrete using artificial neural networks,\" Cement and Concrete Research, Vol. 28, No. 12, pp. 1797-1808 (1998). \n",
|
||||||
|
"\n",
|
||||||
|
"Dua, D. and Graff, C. (2019). UCI Machine Learning Repository [http://archive.ics.uci.edu/ml]. Irvine, CA: University of California, School of Information and Computer Science."
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"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.7.1"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 2
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
name: auto-ml-regression-concrete-strength
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
|
- azureml-train-automl
|
||||||
|
- azureml-widgets
|
||||||
|
- matplotlib
|
||||||
|
- pandas_ml
|
||||||
@@ -0,0 +1,802 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
||||||
|
"\n",
|
||||||
|
"Licensed under the MIT License."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
""
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Automated Machine Learning\n",
|
||||||
|
"_**Regression with Deployment using Hardware Performance Dataset**_\n",
|
||||||
|
"\n",
|
||||||
|
"## Contents\n",
|
||||||
|
"1. [Introduction](#Introduction)\n",
|
||||||
|
"1. [Setup](#Setup)\n",
|
||||||
|
"1. [Data](#Data)\n",
|
||||||
|
"1. [Train](#Train)\n",
|
||||||
|
"1. [Results](#Results)\n",
|
||||||
|
"1. [Test](#Test)\n",
|
||||||
|
"1. [Acknowledgements](#Acknowledgements)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Introduction\n",
|
||||||
|
"In this example we use the Hardware Performance Dataset to showcase how you can use AutoML for a simple regression problem. The Regression goal is to predict the performance of certain combinations of hardware parts.\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 local compute.\n",
|
||||||
|
"4. Explore the results.\n",
|
||||||
|
"5. Test the best fitted model."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Setup\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 numpy as np\n",
|
||||||
|
"import pandas as pd\n",
|
||||||
|
"import os\n",
|
||||||
|
"from sklearn.model_selection import train_test_split\n",
|
||||||
|
"import azureml.dataprep as dprep\n",
|
||||||
|
" \n",
|
||||||
|
"\n",
|
||||||
|
"import azureml.core\n",
|
||||||
|
"from azureml.core.experiment import Experiment\n",
|
||||||
|
"from azureml.core.workspace import Workspace\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 the experiment and specify the project folder.\n",
|
||||||
|
"experiment_name = 'automl-regression-hardware'\n",
|
||||||
|
"project_folder = './sample_projects/automl-remote-regression'\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['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",
|
||||||
|
"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",
|
||||||
|
" # 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",
|
||||||
|
"\n",
|
||||||
|
"Here load the data in the get_data script to be utilized in azure compute. To do this, first load all the necessary libraries and dependencies to set up paths for the data and to create the conda_run_config."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"if not os.path.isdir('data'):\n",
|
||||||
|
" os.mkdir('data')\n",
|
||||||
|
" \n",
|
||||||
|
"if not os.path.exists(project_folder):\n",
|
||||||
|
" os.makedirs(project_folder)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"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",
|
||||||
|
"conda_run_config.environment.docker.base_image = azureml.core.runconfig.DEFAULT_CPU_IMAGE\n",
|
||||||
|
"\n",
|
||||||
|
"dprep_dependency = 'azureml-dataprep==' + pkg_resources.get_distribution(\"azureml-dataprep\").version\n",
|
||||||
|
"\n",
|
||||||
|
"cd = CondaDependencies.create(pip_packages=['azureml-sdk[automl]', dprep_dependency], conda_packages=['numpy'])\n",
|
||||||
|
"conda_run_config.environment.python.conda_dependencies = cd"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Load Data\n",
|
||||||
|
"\n",
|
||||||
|
"Here create the script to be run in azure compute for loading the data, load the hardware dataset into the X and y variables. Next split the data using train_test_split and return X_train and y_train for training the model."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"data = \"https://automlsamplenotebookdata.blob.core.windows.net/automl-sample-notebook-data/machineData.csv\"\n",
|
||||||
|
"dflow = dprep.read_csv(data, infer_column_types=True)\n",
|
||||||
|
"dflow.get_profile()\n",
|
||||||
|
"X = dflow.drop_columns(columns=['ERP'])\n",
|
||||||
|
"y = dflow.keep_columns(columns=['ERP'], validate_column_exists=True)\n",
|
||||||
|
"X_train, X_test = X.random_split(percentage=0.8, seed=223)\n",
|
||||||
|
"y_train, y_test = y.random_split(percentage=0.8, seed=223) \n",
|
||||||
|
"dflow.head()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"\n",
|
||||||
|
"## 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",
|
||||||
|
"|**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",
|
||||||
|
"\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": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"##### If you would like to see even better results increase \"iteration_time_out minutes\" to 10+ mins and increase \"iterations\" to a minimum of 30"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"automl_settings = {\n",
|
||||||
|
" \"iteration_timeout_minutes\": 5,\n",
|
||||||
|
" \"iterations\": 10,\n",
|
||||||
|
" \"n_cross_validations\": 5,\n",
|
||||||
|
" \"primary_metric\": 'spearman_correlation',\n",
|
||||||
|
" \"preprocess\": True,\n",
|
||||||
|
" \"max_concurrent_iterations\": 5,\n",
|
||||||
|
" \"verbosity\": logging.INFO,\n",
|
||||||
|
"}\n",
|
||||||
|
"\n",
|
||||||
|
"automl_config = AutoMLConfig(task = 'regression',\n",
|
||||||
|
" debug_log = 'automl_errors_20190417.log',\n",
|
||||||
|
" path = project_folder,\n",
|
||||||
|
" run_configuration=conda_run_config,\n",
|
||||||
|
" X = X_train,\n",
|
||||||
|
" y = y_train,\n",
|
||||||
|
" **automl_settings\n",
|
||||||
|
" )"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"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"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"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": "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": [
|
||||||
|
"## 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,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"children = list(remote_run.get_children())\n",
|
||||||
|
"metricslist = {}\n",
|
||||||
|
"for run in children:\n",
|
||||||
|
" properties = run.get_properties()\n",
|
||||||
|
" metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)}\n",
|
||||||
|
" metricslist[int(properties['iteration'])] = metrics\n",
|
||||||
|
"\n",
|
||||||
|
"rundata = pd.DataFrame(metricslist).sort_index(1)\n",
|
||||||
|
"rundata"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Retrieve the Best Model\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,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"best_run, fitted_model = remote_run.get_output()\n",
|
||||||
|
"print(best_run)\n",
|
||||||
|
"print(fitted_model)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Best Model Based on Any Other Metric\n",
|
||||||
|
"Show the run and the model that has the smallest `root_mean_squared_error` value (which turned out to be the same as the one with largest `spearman_correlation` value):"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"lookup_metric = \"root_mean_squared_error\"\n",
|
||||||
|
"best_run, fitted_model = remote_run.get_output(metric = lookup_metric)\n",
|
||||||
|
"print(best_run)\n",
|
||||||
|
"print(fitted_model)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"iteration = 3\n",
|
||||||
|
"third_run, third_model = remote_run.get_output(iteration = iteration)\n",
|
||||||
|
"print(third_run)\n",
|
||||||
|
"print(third_model)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Register the 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": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"description = 'AutoML Model'\n",
|
||||||
|
"tags = None\n",
|
||||||
|
"model = remote_run.register_model(description = description, tags = tags)\n",
|
||||||
|
"\n",
|
||||||
|
"print(remote_run.model_id) # This will be written to the script file later in the notebook."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Create Scoring Script\n",
|
||||||
|
"The scoring script is required to generate the image for deployment. It contains the code to do the predictions on input data."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"%%writefile score.py\n",
|
||||||
|
"import pickle\n",
|
||||||
|
"import json\n",
|
||||||
|
"import numpy\n",
|
||||||
|
"import azureml.train.automl\n",
|
||||||
|
"from sklearn.externals import joblib\n",
|
||||||
|
"from azureml.core.model import Model\n",
|
||||||
|
"\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",
|
||||||
|
" # deserialize the model file back into a sklearn model\n",
|
||||||
|
" model = joblib.load(model_path)\n",
|
||||||
|
"\n",
|
||||||
|
"def run(rawdata):\n",
|
||||||
|
" try:\n",
|
||||||
|
" data = json.loads(rawdata)['data']\n",
|
||||||
|
" data = numpy.array(data)\n",
|
||||||
|
" result = model.predict(data)\n",
|
||||||
|
" except Exception as e:\n",
|
||||||
|
" result = str(e)\n",
|
||||||
|
" return json.dumps({\"error\": result})\n",
|
||||||
|
" return json.dumps({\"result\":result.tolist()})"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Create a YAML File for the Environment"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"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. Details about retrieving the versions can be found in notebook [12.auto-ml-retrieve-the-training-sdk-versions](12.auto-ml-retrieve-the-training-sdk-versions.ipynb)."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"dependencies = remote_run.get_run_sdk_dependencies(iteration = 1)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"for p in ['azureml-train-automl', 'azureml-sdk', 'azureml-core']:\n",
|
||||||
|
" print('{}\\t{}'.format(p, dependencies[p]))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"myenv = CondaDependencies.create(conda_packages=['numpy','scikit-learn'], pip_packages=['azureml-sdk[automl]'])\n",
|
||||||
|
"\n",
|
||||||
|
"conda_env_file_name = 'myenv.yml'\n",
|
||||||
|
"myenv.save_to_file('.', conda_env_file_name)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"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",
|
||||||
|
"# However, we include this in case this code is used on an experiment from a previous SDK version.\n",
|
||||||
|
"\n",
|
||||||
|
"with open(conda_env_file_name, 'r') as cefr:\n",
|
||||||
|
" content = cefr.read()\n",
|
||||||
|
"\n",
|
||||||
|
"with open(conda_env_file_name, 'w') as cefw:\n",
|
||||||
|
" cefw.write(content.replace(azureml.core.VERSION, dependencies['azureml-sdk']))\n",
|
||||||
|
"\n",
|
||||||
|
"# Substitute the actual model id in the script file.\n",
|
||||||
|
"\n",
|
||||||
|
"script_file_name = 'score.py'\n",
|
||||||
|
"\n",
|
||||||
|
"with open(script_file_name, 'r') as cefr:\n",
|
||||||
|
" content = cefr.read()\n",
|
||||||
|
"\n",
|
||||||
|
"with open(script_file_name, 'w') as cefw:\n",
|
||||||
|
" cefw.write(content.replace('<<modelid>>', remote_run.model_id))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Create a Container Image\n",
|
||||||
|
"\n",
|
||||||
|
"Next use Azure Container Instances for deploying models as a web service for quickly deploying and validating your model\n",
|
||||||
|
"or when testing a model that is under development."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core.image import Image, ContainerImage\n",
|
||||||
|
"\n",
|
||||||
|
"image_config = ContainerImage.image_configuration(runtime= \"python\",\n",
|
||||||
|
" execution_script = script_file_name,\n",
|
||||||
|
" conda_file = conda_env_file_name,\n",
|
||||||
|
" tags = {'area': \"digits\", 'type': \"automl_regression\"},\n",
|
||||||
|
" description = \"Image for automl regression sample\")\n",
|
||||||
|
"\n",
|
||||||
|
"image = Image.create(name = \"automlsampleimage\",\n",
|
||||||
|
" # this is the model object \n",
|
||||||
|
" models = [model],\n",
|
||||||
|
" image_config = image_config, \n",
|
||||||
|
" workspace = ws)\n",
|
||||||
|
"\n",
|
||||||
|
"image.wait_for_creation(show_output = True)\n",
|
||||||
|
"\n",
|
||||||
|
"if image.creation_state == 'Failed':\n",
|
||||||
|
" print(\"Image build log at: \" + image.image_build_log_uri)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Deploy the Image as a Web Service on Azure Container Instance\n",
|
||||||
|
"\n",
|
||||||
|
"Deploy an image that contains the model and other assets needed by the service."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core.webservice import AciWebservice\n",
|
||||||
|
"\n",
|
||||||
|
"aciconfig = AciWebservice.deploy_configuration(cpu_cores = 1, \n",
|
||||||
|
" memory_gb = 1, \n",
|
||||||
|
" tags = {'area': \"digits\", 'type': \"automl_regression\"}, \n",
|
||||||
|
" description = 'sample service for Automl Regression')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core.webservice import Webservice\n",
|
||||||
|
"\n",
|
||||||
|
"aci_service_name = 'automl-sample-hardware'\n",
|
||||||
|
"print(aci_service_name)\n",
|
||||||
|
"aci_service = Webservice.deploy_from_image(deployment_config = aciconfig,\n",
|
||||||
|
" image = image,\n",
|
||||||
|
" name = aci_service_name,\n",
|
||||||
|
" workspace = ws)\n",
|
||||||
|
"aci_service.wait_for_deployment(True)\n",
|
||||||
|
"print(aci_service.state)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Delete a Web Service\n",
|
||||||
|
"\n",
|
||||||
|
"Deletes the specified web service."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"#aci_service.delete()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Get Logs from a Deployed Web Service\n",
|
||||||
|
"\n",
|
||||||
|
"Gets logs from a deployed web service."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"#aci_service.get_logs()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Test\n",
|
||||||
|
"\n",
|
||||||
|
"Now that the model is trained, split the data in the same way the data was split for training (The difference here is the data is being split locally) and then run the test data through the trained model to get the predicted values."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"X_test = X_test.to_pandas_dataframe()\n",
|
||||||
|
"y_test = y_test.to_pandas_dataframe()\n",
|
||||||
|
"y_test = np.array(y_test)\n",
|
||||||
|
"y_test = y_test[:,0]\n",
|
||||||
|
"X_train = X_train.to_pandas_dataframe()\n",
|
||||||
|
"y_train = y_train.to_pandas_dataframe()\n",
|
||||||
|
"y_train = np.array(y_train)\n",
|
||||||
|
"y_train = y_train[:,0]"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"##### Predict on training and test set, and calculate residual values."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"y_pred_train = fitted_model.predict(X_train)\n",
|
||||||
|
"y_residual_train = y_train - y_pred_train\n",
|
||||||
|
"\n",
|
||||||
|
"y_pred_test = fitted_model.predict(X_test)\n",
|
||||||
|
"y_residual_test = y_test - y_pred_test"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Calculate metrics for the prediction\n",
|
||||||
|
"\n",
|
||||||
|
"Now visualize the data on a scatter plot to show what our truth (actual) values are compared to the predicted values \n",
|
||||||
|
"from the trained model that was returned."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"%matplotlib inline\n",
|
||||||
|
"from sklearn.metrics import mean_squared_error, r2_score\n",
|
||||||
|
"\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",
|
||||||
|
"f.suptitle('Regression Residual Values', fontsize = 18)\n",
|
||||||
|
"f.set_figheight(6)\n",
|
||||||
|
"f.set_figwidth(16)\n",
|
||||||
|
"\n",
|
||||||
|
"# Plot residual values of training set.\n",
|
||||||
|
"a0.axis([0, 360, -200, 200])\n",
|
||||||
|
"a0.plot(y_residual_train, 'bo', alpha = 0.5)\n",
|
||||||
|
"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",
|
||||||
|
"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",
|
||||||
|
"\n",
|
||||||
|
"# Plot residual values of test set.\n",
|
||||||
|
"a1.axis([0, 90, -200, 200])\n",
|
||||||
|
"a1.plot(y_residual_test, 'bo', alpha = 0.5)\n",
|
||||||
|
"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",
|
||||||
|
"a1.text(5,140,'R2 score = {0:.2f}'.format(r2_score(y_test, y_pred_test)),fontsize = 12)\n",
|
||||||
|
"a1.set_xlabel('Test samples', fontsize = 12)\n",
|
||||||
|
"a1.set_yticklabels([])\n",
|
||||||
|
"\n",
|
||||||
|
"plt.show()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"%matplotlib notebook\n",
|
||||||
|
"test_pred = plt.scatter(y_test, y_pred_test, color='')\n",
|
||||||
|
"test_test = plt.scatter(y_test, y_test, color='g')\n",
|
||||||
|
"plt.legend((test_pred, test_test), ('prediction', 'truth'), loc='upper left', fontsize=8)\n",
|
||||||
|
"plt.show()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Acknowledgements\n",
|
||||||
|
"This Predicting Hardware Performance Dataset is made available under the CC0 1.0 Universal (CC0 1.0) Public Domain Dedication License: https://creativecommons.org/publicdomain/zero/1.0/. Any rights in individual contents of the database are licensed under the CC0 1.0 Universal (CC0 1.0) Public Domain Dedication License: https://creativecommons.org/publicdomain/zero/1.0/ . The dataset itself can be found here: https://www.kaggle.com/faizunnabi/comp-hardware-performance and https://archive.ics.uci.edu/ml/datasets/Computer+Hardware\n",
|
||||||
|
"\n",
|
||||||
|
"_**Citation Found Here**_\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"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.7.1"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 2
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
name: auto-ml-regression-hardware-performance
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
|
- azureml-train-automl
|
||||||
|
- azureml-widgets
|
||||||
|
- matplotlib
|
||||||
|
- pandas_ml
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
name: auto-ml-regression
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
|
- azureml-train-automl
|
||||||
|
- azureml-widgets
|
||||||
|
- matplotlib
|
||||||
|
- pandas_ml
|
||||||
|
- paramiko<2.5.0
|
||||||
@@ -9,6 +9,13 @@
|
|||||||
"Licensed under the MIT License."
|
"Licensed under the MIT License."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
""
|
||||||
|
]
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
@@ -21,8 +28,7 @@
|
|||||||
"1. [Setup](#Setup)\n",
|
"1. [Setup](#Setup)\n",
|
||||||
"1. [Data](#Data)\n",
|
"1. [Data](#Data)\n",
|
||||||
"1. [Train](#Train)\n",
|
"1. [Train](#Train)\n",
|
||||||
"1. [Results](#Results)\n",
|
"1. [Results](#Results)\n"
|
||||||
"1. [Test](#Test)"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -30,7 +36,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Introduction\n",
|
"## 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 AutoML for a simple classification problem.\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",
|
"\n",
|
||||||
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
|
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -38,9 +44,9 @@
|
|||||||
"1. Create an `Experiment` in an existing `Workspace`.\n",
|
"1. Create an `Experiment` in an existing `Workspace`.\n",
|
||||||
"2. Create or Attach existing AmlCompute to a workspace.\n",
|
"2. Create or Attach existing AmlCompute to a workspace.\n",
|
||||||
"3. Configure AutoML using `AutoMLConfig`.\n",
|
"3. Configure AutoML using `AutoMLConfig`.\n",
|
||||||
"4. Train the model using AmlCompute\n",
|
"4. Train the model using AmlCompute with ONNX compatible config on.\n",
|
||||||
"5. Explore the results.\n",
|
"5. Explore the results and save the ONNX model.\n",
|
||||||
"6. Test the best fitted model.\n",
|
"6. Inference with the ONNX model.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"In addition this notebook showcases the following features\n",
|
"In addition this notebook showcases the following features\n",
|
||||||
"- **Parallel** executions for iterations\n",
|
"- **Parallel** executions for iterations\n",
|
||||||
@@ -73,11 +79,13 @@
|
|||||||
"import numpy as np\n",
|
"import numpy as np\n",
|
||||||
"import pandas as pd\n",
|
"import pandas as pd\n",
|
||||||
"from sklearn import datasets\n",
|
"from sklearn import datasets\n",
|
||||||
|
"from sklearn.model_selection import train_test_split\n",
|
||||||
"\n",
|
"\n",
|
||||||
"import azureml.core\n",
|
"import azureml.core\n",
|
||||||
"from azureml.core.experiment import Experiment\n",
|
"from azureml.core.experiment import Experiment\n",
|
||||||
"from azureml.core.workspace import Workspace\n",
|
"from azureml.core.workspace import Workspace\n",
|
||||||
"from azureml.train.automl import AutoMLConfig"
|
"from azureml.train.automl import AutoMLConfig\n",
|
||||||
|
"import azureml.dataprep as dprep"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -89,7 +97,7 @@
|
|||||||
"ws = Workspace.from_config()\n",
|
"ws = Workspace.from_config()\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# Choose a name for the run history container in the workspace.\n",
|
"# Choose a name for the run history container in the workspace.\n",
|
||||||
"experiment_name = 'automl-remote-amlcompute'\n",
|
"experiment_name = 'automl-remote-amlcompute-with-onnx'\n",
|
||||||
"project_folder = './project'\n",
|
"project_folder = './project'\n",
|
||||||
"\n",
|
"\n",
|
||||||
"experiment = Experiment(ws, experiment_name)\n",
|
"experiment = Experiment(ws, experiment_name)\n",
|
||||||
@@ -129,7 +137,7 @@
|
|||||||
"from azureml.core.compute import ComputeTarget\n",
|
"from azureml.core.compute import ComputeTarget\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# Choose a name for your cluster.\n",
|
"# Choose a name for your cluster.\n",
|
||||||
"amlcompute_cluster_name = \"automlcl\"\n",
|
"amlcompute_cluster_name = \"cpu-cluster\"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"found = False\n",
|
"found = False\n",
|
||||||
"# Check if this compute target already exists in the workspace.\n",
|
"# Check if this compute target already exists in the workspace.\n",
|
||||||
@@ -138,30 +146,23 @@
|
|||||||
" found = True\n",
|
" found = True\n",
|
||||||
" print('Found existing compute target.')\n",
|
" print('Found existing compute target.')\n",
|
||||||
" compute_target = cts[amlcompute_cluster_name]\n",
|
" compute_target = cts[amlcompute_cluster_name]\n",
|
||||||
" \n",
|
"\n",
|
||||||
"if not found:\n",
|
"if not found:\n",
|
||||||
" print('Creating a new compute target...')\n",
|
" print('Creating a new compute target...')\n",
|
||||||
" provisioning_config = AmlCompute.provisioning_configuration(vm_size = \"STANDARD_D2_V2\", # for GPU, use \"STANDARD_NC6\"\n",
|
" provisioning_config = AmlCompute.provisioning_configuration(vm_size = \"STANDARD_D2_V2\", # for GPU, use \"STANDARD_NC6\"\n",
|
||||||
" #vm_priority = 'lowpriority', # optional\n",
|
" #vm_priority = 'lowpriority', # optional\n",
|
||||||
" max_nodes = 6)\n",
|
" max_nodes = 6)\n",
|
||||||
"\n",
|
"\n",
|
||||||
" # Create the cluster.\n",
|
" # Create the cluster.\\n\",\n",
|
||||||
" compute_target = ComputeTarget.create(ws, amlcompute_cluster_name, provisioning_config)\n",
|
" compute_target = ComputeTarget.create(ws, amlcompute_cluster_name, provisioning_config)\n",
|
||||||
" \n",
|
"\n",
|
||||||
" # Can poll for a minimum number of nodes and for a specific timeout.\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",
|
" # 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",
|
" compute_target.wait_for_completion(show_output = True, min_node_count = None, timeout_in_minutes = 20)\n",
|
||||||
" \n",
|
"\n",
|
||||||
" # For a more detailed view of current AmlCompute status, use get_status()."
|
" # For a more detailed view of current AmlCompute status, use get_status()."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": []
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
@@ -169,7 +170,7 @@
|
|||||||
"## Data\n",
|
"## Data\n",
|
||||||
"For remote executions, you need to make the data accessible from the remote compute.\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",
|
"This can be done by uploading the data to DataStore.\n",
|
||||||
"In this example, we upload scikit-learn's [load_digits](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html) data."
|
"In this example, we upload scikit-learn's [load_iris](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_iris.html) data."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -178,26 +179,45 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"data_train = datasets.load_digits()\n",
|
"iris = datasets.load_iris()\n",
|
||||||
"\n",
|
"\n",
|
||||||
"if not os.path.isdir('data'):\n",
|
"if not os.path.isdir('data'):\n",
|
||||||
" os.mkdir('data')\n",
|
" os.mkdir('data')\n",
|
||||||
" \n",
|
"\n",
|
||||||
"if not os.path.exists(project_folder):\n",
|
"if not os.path.exists(project_folder):\n",
|
||||||
" os.makedirs(project_folder)\n",
|
" os.makedirs(project_folder)\n",
|
||||||
" \n",
|
"\n",
|
||||||
"pd.DataFrame(data_train.data).to_csv(\"data/X_train.tsv\", index=False, header=False, quoting=csv.QUOTE_ALL, sep=\"\\t\")\n",
|
"X_train, X_test, y_train, y_test = train_test_split(iris.data, \n",
|
||||||
"pd.DataFrame(data_train.target).to_csv(\"data/y_train.tsv\", index=False, header=False, sep=\"\\t\")\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",
|
||||||
|
"X_train.to_csv(\"data/X_train.csv\", index=False)\n",
|
||||||
|
"y_train.to_csv(\"data/y_train.csv\", index=False)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"ds = ws.get_default_datastore()\n",
|
"ds = ws.get_default_datastore()\n",
|
||||||
"ds.upload(src_dir='./data', target_path='bai_data', overwrite=True, show_progress=True)\n",
|
"ds.upload(src_dir='./data', target_path='irisdata', overwrite=True, show_progress=True)"
|
||||||
"\n",
|
|
||||||
"from azureml.core.runconfig import DataReferenceConfiguration\n",
|
|
||||||
"dr = DataReferenceConfiguration(datastore_name=ds.name, \n",
|
|
||||||
" path_on_datastore='bai_data', \n",
|
|
||||||
" path_on_compute='/tmp/azureml_runs',\n",
|
|
||||||
" mode='download', # download files from datastore to compute target\n",
|
|
||||||
" overwrite=False)"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -208,6 +228,7 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"from azureml.core.runconfig import RunConfiguration\n",
|
"from azureml.core.runconfig import RunConfiguration\n",
|
||||||
"from azureml.core.conda_dependencies import CondaDependencies\n",
|
"from azureml.core.conda_dependencies import CondaDependencies\n",
|
||||||
|
"import pkg_resources\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# create a new RunConfig object\n",
|
"# create a new RunConfig object\n",
|
||||||
"conda_run_config = RunConfiguration(framework=\"python\")\n",
|
"conda_run_config = RunConfiguration(framework=\"python\")\n",
|
||||||
@@ -217,28 +238,29 @@
|
|||||||
"conda_run_config.environment.docker.enabled = True\n",
|
"conda_run_config.environment.docker.enabled = True\n",
|
||||||
"conda_run_config.environment.docker.base_image = azureml.core.runconfig.DEFAULT_CPU_IMAGE\n",
|
"conda_run_config.environment.docker.base_image = azureml.core.runconfig.DEFAULT_CPU_IMAGE\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# set the data reference of the run coonfiguration\n",
|
"dprep_dependency = 'azureml-dataprep==' + pkg_resources.get_distribution(\"azureml-dataprep\").version\n",
|
||||||
"conda_run_config.data_references = {ds.name: dr}\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
"cd = CondaDependencies.create(pip_packages=['azureml-sdk[automl]'], conda_packages=['numpy'])\n",
|
"cd = CondaDependencies.create(pip_packages=['azureml-sdk[automl]', dprep_dependency], conda_packages=['numpy','py-xgboost<=0.80'])\n",
|
||||||
"conda_run_config.environment.python.conda_dependencies = cd"
|
"conda_run_config.environment.python.conda_dependencies = cd"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Dprep reference\n",
|
||||||
|
"\n",
|
||||||
|
"Defined X and y as dprep references, which are passed to automated machine learning in the AutoMLConfig."
|
||||||
|
]
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"%%writefile $project_folder/get_data.py\n",
|
"X = dprep.read_csv(path=ds.path('irisdata/X_train.csv'), infer_column_types=True)\n",
|
||||||
"\n",
|
"y = dprep.read_csv(path=ds.path('irisdata/y_train.csv'), infer_column_types=True)"
|
||||||
"import pandas as pd\n",
|
|
||||||
"\n",
|
|
||||||
"def get_data():\n",
|
|
||||||
" X_train = pd.read_csv(\"/tmp/azureml_runs/bai_data/X_train.tsv\", delimiter=\"\\t\", header=None, quotechar='\"')\n",
|
|
||||||
" y_train = pd.read_csv(\"/tmp/azureml_runs/bai_data/y_train.tsv\", delimiter=\"\\t\", header=None, quotechar='\"')\n",
|
|
||||||
"\n",
|
|
||||||
" return { \"X\" : X_train.values, \"y\" : y_train[0].values }\n"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -249,6 +271,8 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"You can specify `automl_settings` as `**kwargs` as well. Also note that you can use a `get_data()` function for local excutions too.\n",
|
"You can specify `automl_settings` as `**kwargs` as well. Also note that you can use a `get_data()` function for local excutions too.\n",
|
||||||
"\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",
|
"**Note:** When using AmlCompute, you can't pass Numpy arrays directly to the fit method.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"|Property|Description|\n",
|
"|Property|Description|\n",
|
||||||
@@ -257,7 +281,15 @@
|
|||||||
"|**iteration_timeout_minutes**|Time limit in minutes for each iteration.|\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",
|
"|**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",
|
"|**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 cores on the DSVM.|"
|
"|**max_concurrent_iterations**|Maximum number of iterations that would be executed in parallel. This should be less than the number of cores on the DSVM.|\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."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -267,11 +299,11 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"automl_settings = {\n",
|
"automl_settings = {\n",
|
||||||
" \"iteration_timeout_minutes\": 2,\n",
|
" \"iteration_timeout_minutes\": 10,\n",
|
||||||
" \"iterations\": 20,\n",
|
" \"iterations\": 10,\n",
|
||||||
" \"n_cross_validations\": 5,\n",
|
" \"n_cross_validations\": 5,\n",
|
||||||
" \"primary_metric\": 'AUC_weighted',\n",
|
" \"primary_metric\": 'AUC_weighted',\n",
|
||||||
" \"preprocess\": False,\n",
|
" \"preprocess\": True,\n",
|
||||||
" \"max_concurrent_iterations\": 5,\n",
|
" \"max_concurrent_iterations\": 5,\n",
|
||||||
" \"verbosity\": logging.INFO\n",
|
" \"verbosity\": logging.INFO\n",
|
||||||
"}\n",
|
"}\n",
|
||||||
@@ -280,9 +312,11 @@
|
|||||||
" debug_log = 'automl_errors.log',\n",
|
" debug_log = 'automl_errors.log',\n",
|
||||||
" path = project_folder,\n",
|
" path = project_folder,\n",
|
||||||
" run_configuration=conda_run_config,\n",
|
" run_configuration=conda_run_config,\n",
|
||||||
" data_script = project_folder + \"/get_data.py\",\n",
|
" X = X,\n",
|
||||||
|
" y = y,\n",
|
||||||
|
" enable_onnx_compatible_models=True, # This will generate ONNX compatible models.\n",
|
||||||
" **automl_settings\n",
|
" **automl_settings\n",
|
||||||
" )\n"
|
" )"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -370,32 +404,6 @@
|
|||||||
"remote_run.wait_for_completion(show_output = True)"
|
"remote_run.wait_for_completion(show_output = True)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"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,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"children = list(remote_run.get_children())\n",
|
|
||||||
"metricslist = {}\n",
|
|
||||||
"for run in children:\n",
|
|
||||||
" properties = run.get_properties()\n",
|
|
||||||
" metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)}\n",
|
|
||||||
" metricslist[int(properties['iteration'])] = metrics\n",
|
|
||||||
"\n",
|
|
||||||
"rundata = pd.DataFrame(metricslist).sort_index(1)\n",
|
|
||||||
"rundata"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
@@ -422,69 +430,11 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"### Retrieve the Best Model\n",
|
"### Retrieve the Best ONNX Model\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Below we select the best pipeline from our iterations. The `get_output` method returns the best run and the fitted model. 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*."
|
"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",
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"best_run, fitted_model = remote_run.get_output()\n",
|
|
||||||
"print(best_run)\n",
|
|
||||||
"print(fitted_model)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Best Model Based on Any Other Metric\n",
|
|
||||||
"Show the run and the model which has the smallest `log_loss` value:"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"lookup_metric = \"log_loss\"\n",
|
|
||||||
"best_run, fitted_model = remote_run.get_output(metric = lookup_metric)\n",
|
|
||||||
"print(best_run)\n",
|
|
||||||
"print(fitted_model)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Model from a Specific Iteration\n",
|
|
||||||
"Show the run and the model from the third iteration:"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"iteration = 3\n",
|
|
||||||
"third_run, third_model = remote_run.get_output(iteration=iteration)\n",
|
|
||||||
"print(third_run)\n",
|
|
||||||
"print(third_model)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Test\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
"#### Load Test Data"
|
"Set the parameter return_onnx_model=True to retrieve the best ONNX model, instead of the Python model."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -493,17 +443,14 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"digits = datasets.load_digits()\n",
|
"best_run, onnx_mdl = remote_run.get_output(return_onnx_model=True)"
|
||||||
"X_test = digits.data[:10, :]\n",
|
|
||||||
"y_test = digits.target[:10]\n",
|
|
||||||
"images = digits.images[:10]"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"#### Testing Our Best Fitted Model"
|
"### Save the best ONNX model"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -512,18 +459,70 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"# Randomly select digits and test.\n",
|
"from azureml.automl.core.onnx_convert import OnnxConverter\n",
|
||||||
"for index in np.random.choice(len(y_test), 2, replace = False):\n",
|
"onnx_fl_path = \"./best_model.onnx\"\n",
|
||||||
" print(index)\n",
|
"OnnxConverter.save_onnx_model(onnx_mdl, onnx_fl_path)"
|
||||||
" predicted = fitted_model.predict(X_test[index:index + 1])[0]\n",
|
|
||||||
" label = y_test[index]\n",
|
|
||||||
" title = \"Label value = %d Predicted value = %d \" % (label, predicted)\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": "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",
|
||||||
|
" onnx_res = json.load(f)\n",
|
||||||
|
" return onnx_res\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": {
|
"metadata": {
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
name: auto-ml-remote-amlcompute-with-onnx
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
|
- azureml-train-automl
|
||||||
|
- azureml-widgets
|
||||||
|
- matplotlib
|
||||||
|
- pandas_ml
|
||||||
|
- onnxruntime
|
||||||
@@ -84,7 +84,8 @@
|
|||||||
"import azureml.core\n",
|
"import azureml.core\n",
|
||||||
"from azureml.core.experiment import Experiment\n",
|
"from azureml.core.experiment import Experiment\n",
|
||||||
"from azureml.core.workspace import Workspace\n",
|
"from azureml.core.workspace import Workspace\n",
|
||||||
"from azureml.train.automl import AutoMLConfig"
|
"from azureml.train.automl import AutoMLConfig\n",
|
||||||
|
"import azureml.dataprep as dprep"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -119,7 +120,9 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"### Create or Attach existing AmlCompute\n",
|
"### Create or Attach existing AmlCompute\n",
|
||||||
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for your AutoML run. In this tutorial, you create an AmlCompute as your training compute resource.\n",
|
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for your AutoML run. In this tutorial, you create `AmlCompute` as your training compute resource.\n",
|
||||||
|
"\n",
|
||||||
|
"**Creation of AmlCompute takes approximately 5 minutes.** If the AmlCompute with that name is already in your workspace this code will skip the creation process.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
|
||||||
]
|
]
|
||||||
@@ -134,12 +137,10 @@
|
|||||||
"from azureml.core.compute import ComputeTarget\n",
|
"from azureml.core.compute import ComputeTarget\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# Choose a name for your cluster.\n",
|
"# Choose a name for your cluster.\n",
|
||||||
"amlcompute_cluster_name = \"cpucluster\"\n",
|
"amlcompute_cluster_name = \"cpu-cluster\"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"found = False\n",
|
"found = False\n",
|
||||||
"\n",
|
|
||||||
"# Check if this compute target already exists in the workspace.\n",
|
"# Check if this compute target already exists in the workspace.\n",
|
||||||
"\n",
|
|
||||||
"cts = ws.compute_targets\n",
|
"cts = ws.compute_targets\n",
|
||||||
"if amlcompute_cluster_name in cts and cts[amlcompute_cluster_name].type == 'AmlCompute':\n",
|
"if amlcompute_cluster_name in cts and cts[amlcompute_cluster_name].type == 'AmlCompute':\n",
|
||||||
" found = True\n",
|
" found = True\n",
|
||||||
@@ -186,18 +187,11 @@
|
|||||||
"if not os.path.exists(project_folder):\n",
|
"if not os.path.exists(project_folder):\n",
|
||||||
" os.makedirs(project_folder)\n",
|
" os.makedirs(project_folder)\n",
|
||||||
" \n",
|
" \n",
|
||||||
"pd.DataFrame(data_train.data).to_csv(\"data/X_train.tsv\", index=False, header=False, quoting=csv.QUOTE_ALL, sep=\"\\t\")\n",
|
"pd.DataFrame(data_train.data[100:,:]).to_csv(\"data/X_train.csv\", index=False)\n",
|
||||||
"pd.DataFrame(data_train.target).to_csv(\"data/y_train.tsv\", index=False, header=False, sep=\"\\t\")\n",
|
"pd.DataFrame(data_train.target[100:]).to_csv(\"data/y_train.csv\", index=False)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"ds = ws.get_default_datastore()\n",
|
"ds = ws.get_default_datastore()\n",
|
||||||
"ds.upload(src_dir='./data', target_path='bai_data', overwrite=True, show_progress=True)\n",
|
"ds.upload(src_dir='./data', target_path='digitsdata', overwrite=True, show_progress=True)"
|
||||||
"\n",
|
|
||||||
"from azureml.core.runconfig import DataReferenceConfiguration\n",
|
|
||||||
"dr = DataReferenceConfiguration(datastore_name=ds.name, \n",
|
|
||||||
" path_on_datastore='bai_data', \n",
|
|
||||||
" path_on_compute='/tmp/azureml_runs',\n",
|
|
||||||
" mode='download', # download files from datastore to compute target\n",
|
|
||||||
" overwrite=False)"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -208,6 +202,7 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"from azureml.core.runconfig import RunConfiguration\n",
|
"from azureml.core.runconfig import RunConfiguration\n",
|
||||||
"from azureml.core.conda_dependencies import CondaDependencies\n",
|
"from azureml.core.conda_dependencies import CondaDependencies\n",
|
||||||
|
"import pkg_resources\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# create a new RunConfig object\n",
|
"# create a new RunConfig object\n",
|
||||||
"conda_run_config = RunConfiguration(framework=\"python\")\n",
|
"conda_run_config = RunConfiguration(framework=\"python\")\n",
|
||||||
@@ -217,28 +212,29 @@
|
|||||||
"conda_run_config.environment.docker.enabled = True\n",
|
"conda_run_config.environment.docker.enabled = True\n",
|
||||||
"conda_run_config.environment.docker.base_image = azureml.core.runconfig.DEFAULT_CPU_IMAGE\n",
|
"conda_run_config.environment.docker.base_image = azureml.core.runconfig.DEFAULT_CPU_IMAGE\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# set the data reference of the run coonfiguration\n",
|
"dprep_dependency = 'azureml-dataprep==' + pkg_resources.get_distribution(\"azureml-dataprep\").version\n",
|
||||||
"conda_run_config.data_references = {ds.name: dr}\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
"cd = CondaDependencies.create(pip_packages=['azureml-sdk[automl]'], conda_packages=['numpy','py-xgboost<=0.80'])\n",
|
"cd = CondaDependencies.create(pip_packages=['azureml-sdk[automl]', dprep_dependency], conda_packages=['numpy','py-xgboost<=0.80'])\n",
|
||||||
"conda_run_config.environment.python.conda_dependencies = cd"
|
"conda_run_config.environment.python.conda_dependencies = cd"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Dprep reference\n",
|
||||||
|
"\n",
|
||||||
|
"Defined X and y as dprep references, which are passed to automated machine learning in the AutoMLConfig."
|
||||||
|
]
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"%%writefile $project_folder/get_data.py\n",
|
"X = dprep.read_csv(path=ds.path('digitsdata/X_train.csv'), infer_column_types=True)\n",
|
||||||
"\n",
|
"y = dprep.read_csv(path=ds.path('digitsdata/y_train.csv'), infer_column_types=True)"
|
||||||
"import pandas as pd\n",
|
|
||||||
"\n",
|
|
||||||
"def get_data():\n",
|
|
||||||
" X_train = pd.read_csv(\"/tmp/azureml_runs/bai_data/X_train.tsv\", delimiter=\"\\t\", header=None, quotechar='\"')\n",
|
|
||||||
" y_train = pd.read_csv(\"/tmp/azureml_runs/bai_data/y_train.tsv\", delimiter=\"\\t\", header=None, quotechar='\"')\n",
|
|
||||||
"\n",
|
|
||||||
" return { \"X\" : X_train.values, \"y\" : y_train[0].values }\n"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -280,7 +276,8 @@
|
|||||||
" debug_log = 'automl_errors.log',\n",
|
" debug_log = 'automl_errors.log',\n",
|
||||||
" path = project_folder,\n",
|
" path = project_folder,\n",
|
||||||
" run_configuration=conda_run_config,\n",
|
" run_configuration=conda_run_config,\n",
|
||||||
" data_script = project_folder + \"/get_data.py\",\n",
|
" X = X,\n",
|
||||||
|
" y = y,\n",
|
||||||
" **automl_settings\n",
|
" **automl_settings\n",
|
||||||
" )\n"
|
" )\n"
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
name: auto-ml-remote-amlcompute
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
|
- azureml-train-automl
|
||||||
|
- azureml-widgets
|
||||||
|
- matplotlib
|
||||||
|
- pandas_ml
|
||||||
@@ -1,565 +0,0 @@
|
|||||||
{
|
|
||||||
"cells": [
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
|
||||||
"\n",
|
|
||||||
"Licensed under the MIT License."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
""
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"# Automated Machine Learning\n",
|
|
||||||
"_**Remote Execution using attach**_\n",
|
|
||||||
"\n",
|
|
||||||
"## Contents\n",
|
|
||||||
"1. [Introduction](#Introduction)\n",
|
|
||||||
"1. [Setup](#Setup)\n",
|
|
||||||
"1. [Data](#Data)\n",
|
|
||||||
"1. [Train](#Train)\n",
|
|
||||||
"1. [Results](#Results)\n",
|
|
||||||
"1. [Test](#Test)\n"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"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 to handle text data with remote attach.\n",
|
|
||||||
"\n",
|
|
||||||
"Make sure you have executed the [configuration](../../../configuration.ipynb) before running this notebook.\n",
|
|
||||||
"\n",
|
|
||||||
"In this notebook you will learn how to:\n",
|
|
||||||
"1. Create an `Experiment` in an existing `Workspace`.\n",
|
|
||||||
"2. Attach an existing DSVM to a workspace.\n",
|
|
||||||
"3. Configure AutoML using `AutoMLConfig`.\n",
|
|
||||||
"4. Train the model using the DSVM.\n",
|
|
||||||
"5. Explore the results.\n",
|
|
||||||
"6. Viewing the engineered names for featurized data and featurization summary for all raw features.\n",
|
|
||||||
"7. Test the best fitted 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`\n",
|
|
||||||
"- Handling **text** data using the `preprocess` flag"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"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 os\n",
|
|
||||||
"\n",
|
|
||||||
"import numpy as np\n",
|
|
||||||
"import pandas as pd\n",
|
|
||||||
"\n",
|
|
||||||
"import azureml.core\n",
|
|
||||||
"from azureml.core.experiment import Experiment\n",
|
|
||||||
"from azureml.core.workspace import Workspace\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 the run history container in the workspace.\n",
|
|
||||||
"experiment_name = 'automl-remote-attach'\n",
|
|
||||||
"project_folder = './sample_projects/automl-remote-attach'\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['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",
|
|
||||||
"outputDf.T"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Attach a Remote Linux DSVM\n",
|
|
||||||
"To use a remote Docker compute target:\n",
|
|
||||||
"1. Create a Linux DSVM in Azure, following these [instructions](https://docs.microsoft.com/en-us/azure/machine-learning/data-science-virtual-machine/dsvm-ubuntu-intro). Make sure you use the Ubuntu flavor (not CentOS). Make sure that disk space is available under `/tmp` because AutoML creates files under `/tmp/azureml_run`s. The DSVM should have more cores than the number of parallel runs that you plan to enable. It should also have at least 4GB per core.\n",
|
|
||||||
"2. Enter the IP address, user name and password below.\n",
|
|
||||||
"\n",
|
|
||||||
"**Note:** By default, SSH runs on port 22 and you don't need to change the port number below. If you've configured SSH to use a different port, change `dsvm_ssh_port` accordinglyaddress. [Read more](https://docs.microsoft.com/en-us/azure/virtual-machines/troubleshooting/detailed-troubleshoot-ssh-connection) on changing SSH ports for security reasons."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.core.compute import ComputeTarget, RemoteCompute\n",
|
|
||||||
"import time\n",
|
|
||||||
"\n",
|
|
||||||
"# Add your VM information below\n",
|
|
||||||
"# If a compute with the specified compute_name already exists, it will be used and the dsvm_ip_addr, dsvm_ssh_port, \n",
|
|
||||||
"# dsvm_username and dsvm_password will be ignored.\n",
|
|
||||||
"compute_name = 'mydsvmb'\n",
|
|
||||||
"dsvm_ip_addr = '<<ip_addr>>'\n",
|
|
||||||
"dsvm_ssh_port = 22\n",
|
|
||||||
"dsvm_username = '<<username>>'\n",
|
|
||||||
"dsvm_password = '<<password>>'\n",
|
|
||||||
"\n",
|
|
||||||
"if compute_name in ws.compute_targets:\n",
|
|
||||||
" print('Using existing compute.')\n",
|
|
||||||
" dsvm_compute = ws.compute_targets[compute_name]\n",
|
|
||||||
"else:\n",
|
|
||||||
" attach_config = RemoteCompute.attach_configuration(address=dsvm_ip_addr, username=dsvm_username, password=dsvm_password, ssh_port=dsvm_ssh_port)\n",
|
|
||||||
" ComputeTarget.attach(workspace=ws, name=compute_name, attach_configuration=attach_config)\n",
|
|
||||||
"\n",
|
|
||||||
" while ws.compute_targets[compute_name].provisioning_state == 'Creating':\n",
|
|
||||||
" time.sleep(1)\n",
|
|
||||||
"\n",
|
|
||||||
" dsvm_compute = ws.compute_targets[compute_name]\n",
|
|
||||||
" \n",
|
|
||||||
" if dsvm_compute.provisioning_state == 'Failed':\n",
|
|
||||||
" print('Attached failed.')\n",
|
|
||||||
" print(dsvm_compute.provisioning_errors)\n",
|
|
||||||
" dsvm_compute.detach()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"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 the Linux DSVM\n",
|
|
||||||
"conda_run_config.target = dsvm_compute\n",
|
|
||||||
"\n",
|
|
||||||
"pandas_dependency = 'pandas==' + pkg_resources.get_distribution(\"pandas\").version\n",
|
|
||||||
"\n",
|
|
||||||
"cd = CondaDependencies.create(pip_packages=['azureml-sdk[automl]'], conda_packages=['numpy','py-xgboost<=0.80',pandas_dependency])\n",
|
|
||||||
"conda_run_config.environment.python.conda_dependencies = cd"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Data\n",
|
|
||||||
"For remote executions you should author a `get_data.py` file containing a `get_data()` function. This file should be in the root directory of the project. You can encapsulate code to read data either from a blob storage or local disk in this file.\n",
|
|
||||||
"In this example, the `get_data()` function returns a [dictionary](README.md#getdata)."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"if not os.path.exists(project_folder):\n",
|
|
||||||
" os.makedirs(project_folder)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"%%writefile $project_folder/get_data.py\n",
|
|
||||||
"\n",
|
|
||||||
"import numpy as np\n",
|
|
||||||
"from sklearn.datasets import fetch_20newsgroups\n",
|
|
||||||
"\n",
|
|
||||||
"def get_data():\n",
|
|
||||||
" remove = ('headers', 'footers', 'quotes')\n",
|
|
||||||
" categories = [\n",
|
|
||||||
" 'alt.atheism',\n",
|
|
||||||
" 'talk.religion.misc',\n",
|
|
||||||
" 'comp.graphics',\n",
|
|
||||||
" 'sci.space',\n",
|
|
||||||
" ]\n",
|
|
||||||
" data_train = fetch_20newsgroups(subset = 'train', categories = categories,\n",
|
|
||||||
" shuffle = True, random_state = 42,\n",
|
|
||||||
" remove = remove)\n",
|
|
||||||
" \n",
|
|
||||||
" X_train = np.array(data_train.data).reshape((len(data_train.data),1))\n",
|
|
||||||
" y_train = np.array(data_train.target)\n",
|
|
||||||
" \n",
|
|
||||||
" return { \"X\" : X_train, \"y\" : y_train }"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Train\n",
|
|
||||||
"\n",
|
|
||||||
"You can specify `automl_settings` as `**kwargs` as well. Also note that you can use a `get_data()` function for local excutions too.\n",
|
|
||||||
"\n",
|
|
||||||
"**Note:** When using Remote DSVM, 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 cores on the DSVM.|\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",
|
|
||||||
"|**enable_cache**|Setting this to *True* enables preprocess done once and reuse the same preprocessed data for all the iterations. Default value is True.\n",
|
|
||||||
"|**max_cores_per_iteration**|Indicates how many cores on the compute target would be used to train a single pipeline.<br>Default is *1*; you can set it to *-1* to use all cores.|"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"automl_settings = {\n",
|
|
||||||
" \"iteration_timeout_minutes\": 60,\n",
|
|
||||||
" \"iterations\": 4,\n",
|
|
||||||
" \"n_cross_validations\": 5,\n",
|
|
||||||
" \"primary_metric\": 'AUC_weighted',\n",
|
|
||||||
" \"preprocess\": True,\n",
|
|
||||||
" \"max_cores_per_iteration\": 2\n",
|
|
||||||
"}\n",
|
|
||||||
"\n",
|
|
||||||
"automl_config = AutoMLConfig(task = 'classification',\n",
|
|
||||||
" path = project_folder,\n",
|
|
||||||
" run_configuration=conda_run_config,\n",
|
|
||||||
" data_script = project_folder + \"/get_data.py\",\n",
|
|
||||||
" **automl_settings\n",
|
|
||||||
" )\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."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"remote_run = experiment.submit(automl_config)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"remote_run"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Results\n",
|
|
||||||
"#### 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": [
|
|
||||||
"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": [
|
|
||||||
"### Pre-process cache cleanup\n",
|
|
||||||
"The preprocess data gets cache at user default file store. When the run is completed the cache can be cleaned by running below cell"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"remote_run.clean_preprocessor_cache()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"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,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"children = list(remote_run.get_children())\n",
|
|
||||||
"metricslist = {}\n",
|
|
||||||
"for run in children:\n",
|
|
||||||
" properties = run.get_properties()\n",
|
|
||||||
" metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)}\n",
|
|
||||||
" metricslist[int(properties['iteration'])] = metrics\n",
|
|
||||||
"\n",
|
|
||||||
"rundata = pd.DataFrame(metricslist).sort_index(1)\n",
|
|
||||||
"rundata"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Cancelling Runs\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 Model\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*."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"best_run, fitted_model = remote_run.get_output()\n",
|
|
||||||
"print(best_run)\n",
|
|
||||||
"print(fitted_model)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### View the engineered names for featurized data\n",
|
|
||||||
"Below we display the engineered feature names generated for the featurized data using the preprocessing featurization."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"fitted_model.named_steps['datatransformer'].get_engineered_feature_names()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### View the featurization summary\n",
|
|
||||||
"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",
|
|
||||||
"- Raw feature name\n",
|
|
||||||
"- Number of engineered features formed out of this raw feature\n",
|
|
||||||
"- Type detected\n",
|
|
||||||
"- If feature was dropped\n",
|
|
||||||
"- List of feature transformations for the raw feature"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"fitted_model.named_steps['datatransformer'].get_featurization_summary()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Best Model Based on Any Other Metric\n",
|
|
||||||
"Show the run and the model which has the smallest `accuracy` value:"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# lookup_metric = \"accuracy\"\n",
|
|
||||||
"# best_run, fitted_model = remote_run.get_output(metric = lookup_metric)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Model from a Specific Iteration"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"iteration = 0\n",
|
|
||||||
"zero_run, zero_model = remote_run.get_output(iteration = iteration)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Test"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# Load test data.\n",
|
|
||||||
"from pandas_ml import ConfusionMatrix\n",
|
|
||||||
"from sklearn.datasets import fetch_20newsgroups\n",
|
|
||||||
"\n",
|
|
||||||
"remove = ('headers', 'footers', 'quotes')\n",
|
|
||||||
"categories = [\n",
|
|
||||||
" 'alt.atheism',\n",
|
|
||||||
" 'talk.religion.misc',\n",
|
|
||||||
" 'comp.graphics',\n",
|
|
||||||
" 'sci.space',\n",
|
|
||||||
" ]\n",
|
|
||||||
"\n",
|
|
||||||
"data_test = fetch_20newsgroups(subset = 'test', categories = categories,\n",
|
|
||||||
" shuffle = True, random_state = 42,\n",
|
|
||||||
" remove = remove)\n",
|
|
||||||
"\n",
|
|
||||||
"X_test = np.array(data_test.data).reshape((len(data_test.data),1))\n",
|
|
||||||
"y_test = data_test.target\n",
|
|
||||||
"\n",
|
|
||||||
"# Test our best pipeline.\n",
|
|
||||||
"\n",
|
|
||||||
"y_pred = fitted_model.predict(X_test)\n",
|
|
||||||
"y_pred_strings = [data_test.target_names[i] for i in y_pred]\n",
|
|
||||||
"y_test_strings = [data_test.target_names[i] for i in y_test]\n",
|
|
||||||
"\n",
|
|
||||||
"cm = ConfusionMatrix(y_test_strings, y_pred_strings)\n",
|
|
||||||
"print(cm)\n",
|
|
||||||
"cm.plot()"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"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
|
|
||||||
}
|
|
||||||
@@ -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": [
|
|
||||||
""
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"# Automated Machine Learning\n",
|
|
||||||
"_**Remote Execution with DataStore**_\n",
|
|
||||||
"\n",
|
|
||||||
"## Contents\n",
|
|
||||||
"1. [Introduction](#Introduction)\n",
|
|
||||||
"1. [Setup](#Setup)\n",
|
|
||||||
"1. [Data](#Data)\n",
|
|
||||||
"1. [Train](#Train)\n",
|
|
||||||
"1. [Results](#Results)\n",
|
|
||||||
"1. [Test](#Test)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Introduction\n",
|
|
||||||
"This sample accesses a data file on a remote DSVM through DataStore. Advantages of using data store are:\n",
|
|
||||||
"1. DataStore secures the access details.\n",
|
|
||||||
"2. DataStore supports read, write to blob and file store\n",
|
|
||||||
"3. AutoML natively supports copying data from DataStore to DSVM\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. Storing data in DataStore.\n",
|
|
||||||
"2. get_data returning data from DataStore."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## 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."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"import logging\n",
|
|
||||||
"import os\n",
|
|
||||||
"import time\n",
|
|
||||||
"\n",
|
|
||||||
"import numpy as np\n",
|
|
||||||
"import pandas as pd\n",
|
|
||||||
"\n",
|
|
||||||
"import azureml.core\n",
|
|
||||||
"from azureml.core.compute import DsvmCompute\n",
|
|
||||||
"from azureml.core.experiment import Experiment\n",
|
|
||||||
"from azureml.core.workspace import Workspace\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-remote-datastore-file'\n",
|
|
||||||
"# project folder\n",
|
|
||||||
"project_folder = './sample_projects/automl-remote-datastore-file'\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['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",
|
|
||||||
"outputDf.T"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Create a Remote Linux DSVM\n",
|
|
||||||
"Note: If creation fails with a message about Marketplace purchase eligibilty, go to portal.azure.com, start creating DSVM there, and select \"Want to create programmatically\" to enable programmatic creation. Once you've enabled it, you can exit without actually creating VM.\n",
|
|
||||||
"\n",
|
|
||||||
"**Note**: By default SSH runs on port 22 and you don't need to specify it. But if for security reasons you can switch to a different port (such as 5022), you can append the port number to the address. [Read more](https://docs.microsoft.com/en-us/azure/virtual-machines/troubleshooting/detailed-troubleshoot-ssh-connection) on this."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"compute_target_name = 'mydsvmc'\n",
|
|
||||||
"\n",
|
|
||||||
"try:\n",
|
|
||||||
" while ws.compute_targets[compute_target_name].provisioning_state == 'Creating':\n",
|
|
||||||
" time.sleep(1)\n",
|
|
||||||
" \n",
|
|
||||||
" dsvm_compute = DsvmCompute(workspace=ws, name=compute_target_name)\n",
|
|
||||||
" print('found existing:', dsvm_compute.name)\n",
|
|
||||||
"except:\n",
|
|
||||||
" dsvm_config = DsvmCompute.provisioning_configuration(vm_size=\"Standard_D2_v2\")\n",
|
|
||||||
" dsvm_compute = DsvmCompute.create(ws, name=compute_target_name, provisioning_configuration=dsvm_config)\n",
|
|
||||||
" dsvm_compute.wait_for_completion(show_output=True)\n",
|
|
||||||
" print(\"Waiting one minute for ssh to be accessible\")\n",
|
|
||||||
" time.sleep(90) # Wait for ssh to be accessible"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Data\n",
|
|
||||||
"\n",
|
|
||||||
"### Copy data file to local\n",
|
|
||||||
"\n",
|
|
||||||
"Download the data file.\n"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"if not os.path.isdir('data'):\n",
|
|
||||||
" os.mkdir('data') "
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from sklearn.datasets import fetch_20newsgroups\n",
|
|
||||||
"import csv\n",
|
|
||||||
"\n",
|
|
||||||
"remove = ('headers', 'footers', 'quotes')\n",
|
|
||||||
"categories = [\n",
|
|
||||||
" 'alt.atheism',\n",
|
|
||||||
" 'talk.religion.misc',\n",
|
|
||||||
" 'comp.graphics',\n",
|
|
||||||
" 'sci.space',\n",
|
|
||||||
" ]\n",
|
|
||||||
"data_train = fetch_20newsgroups(subset = 'train', categories = categories,\n",
|
|
||||||
" shuffle = True, random_state = 42,\n",
|
|
||||||
" remove = remove)\n",
|
|
||||||
" \n",
|
|
||||||
"pd.DataFrame(data_train.data).to_csv(\"data/X_train.tsv\", index=False, header=False, quoting=csv.QUOTE_ALL, sep=\"\\t\")\n",
|
|
||||||
"pd.DataFrame(data_train.target).to_csv(\"data/y_train.tsv\", index=False, header=False, sep=\"\\t\")"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Upload data to the cloud"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Now make the data accessible remotely by uploading that data from your local machine into Azure so it can be accessed for remote training. The datastore is a convenient construct associated with your workspace for you to upload/download data, and interact with it from your remote compute targets. It is backed by Azure blob storage account.\n",
|
|
||||||
"\n",
|
|
||||||
"The data.tsv files are uploaded into a directory named data at the root of the datastore."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"#blob_datastore = Datastore(ws, blob_datastore_name)\n",
|
|
||||||
"ds = ws.get_default_datastore()\n",
|
|
||||||
"print(ds.datastore_type, ds.account_name, ds.container_name)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# ds.upload_files(\"data.tsv\")\n",
|
|
||||||
"ds.upload(src_dir='./data', target_path='data', overwrite=True, show_progress=True)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Configure & Run\n",
|
|
||||||
"\n",
|
|
||||||
"First let's create a DataReferenceConfigruation object to inform the system what data folder to download to the compute target.\n",
|
|
||||||
"The path_on_compute should be an absolute path to ensure that the data files are downloaded only once. The get_data method should use this same path to access the data files."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.core.runconfig import DataReferenceConfiguration\n",
|
|
||||||
"dr = DataReferenceConfiguration(datastore_name=ds.name, \n",
|
|
||||||
" path_on_datastore='data', \n",
|
|
||||||
" path_on_compute='/tmp/azureml_runs',\n",
|
|
||||||
" mode='download', # download files from datastore to compute target\n",
|
|
||||||
" overwrite=False)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"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 the Linux DSVM\n",
|
|
||||||
"conda_run_config.target = dsvm_compute\n",
|
|
||||||
"# set the data reference of the run coonfiguration\n",
|
|
||||||
"conda_run_config.data_references = {ds.name: dr}\n",
|
|
||||||
"\n",
|
|
||||||
"pandas_dependency = 'pandas==' + pkg_resources.get_distribution(\"pandas\").version\n",
|
|
||||||
"\n",
|
|
||||||
"cd = CondaDependencies.create(pip_packages=['azureml-sdk[automl]'], conda_packages=['numpy','py-xgboost<=0.80',pandas_dependency])\n",
|
|
||||||
"conda_run_config.environment.python.conda_dependencies = cd"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Create Get Data File\n",
|
|
||||||
"For remote executions you should author a get_data.py file containing a get_data() function. This file should be in the root directory of the project. You can encapsulate code to read data either from a blob storage or local disk in this file.\n",
|
|
||||||
"\n",
|
|
||||||
"The *get_data()* function returns a [dictionary](README.md#getdata).\n",
|
|
||||||
"\n",
|
|
||||||
"The read_csv uses the path_on_compute value specified in the DataReferenceConfiguration call plus the path_on_datastore folder and then the actual file name."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"if not os.path.exists(project_folder):\n",
|
|
||||||
" os.makedirs(project_folder)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"%%writefile $project_folder/get_data.py\n",
|
|
||||||
"\n",
|
|
||||||
"import pandas as pd\n",
|
|
||||||
"\n",
|
|
||||||
"def get_data():\n",
|
|
||||||
" X_train = pd.read_csv(\"/tmp/azureml_runs/data/X_train.tsv\", delimiter=\"\\t\", header=None, quotechar='\"')\n",
|
|
||||||
" y_train = pd.read_csv(\"/tmp/azureml_runs/data/y_train.tsv\", delimiter=\"\\t\", header=None, quotechar='\"')\n",
|
|
||||||
"\n",
|
|
||||||
" return { \"X\" : X_train.values, \"y\" : y_train[0].values }"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Train\n",
|
|
||||||
"\n",
|
|
||||||
"You can specify automl_settings as **kwargs** as well. Also note that you can use the get_data() symantic for local excutions too. \n",
|
|
||||||
"\n",
|
|
||||||
"<i>Note: For Remote DSVM and Batch AI you cannot pass Numpy arrays directly to AutoMLConfig.</i>\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 Auto ML trains a specific pipeline with the data|\n",
|
|
||||||
"|**n_cross_validations**|Number of cross validation splits|\n",
|
|
||||||
"|**max_concurrent_iterations**|Max number of iterations that would be executed in parallel. This should be less than the number of cores on the DSVM\n",
|
|
||||||
"|**preprocess**| *True/False* <br>Setting this to *True* enables Auto ML to perform preprocessing <br>on the input to handle *missing data*, and perform some common *feature extraction*|\n",
|
|
||||||
"|**enable_cache**|Setting this to *True* enables preprocess done once and reuse the same preprocessed data for all the iterations. Default value is True.|\n",
|
|
||||||
"|**max_cores_per_iteration**| Indicates how many cores on the compute target would be used to train a single pipeline.<br> Default is *1*, you can set it to *-1* to use all cores|"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"automl_settings = {\n",
|
|
||||||
" \"iteration_timeout_minutes\": 60,\n",
|
|
||||||
" \"iterations\": 4,\n",
|
|
||||||
" \"n_cross_validations\": 5,\n",
|
|
||||||
" \"primary_metric\": 'AUC_weighted',\n",
|
|
||||||
" \"preprocess\": True,\n",
|
|
||||||
" \"max_cores_per_iteration\": 1,\n",
|
|
||||||
" \"verbosity\": logging.INFO\n",
|
|
||||||
"}\n",
|
|
||||||
"automl_config = AutoMLConfig(task = 'classification',\n",
|
|
||||||
" debug_log = 'automl_errors.log',\n",
|
|
||||||
" path=project_folder,\n",
|
|
||||||
" run_configuration=conda_run_config,\n",
|
|
||||||
" #compute_target = dsvm_compute,\n",
|
|
||||||
" data_script = project_folder + \"/get_data.py\",\n",
|
|
||||||
" **automl_settings\n",
|
|
||||||
" )"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"For remote runs the execution is asynchronous, so you will see the iterations get populated as they complete. You can interact with the widgets/models even when the experiment is running to retreive the best model up to that point. Once you are satisfied with the model you can cancel a particular iteration or the whole run."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"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",
|
|
||||||
"#### Widget for monitoring runs\n",
|
|
||||||
"\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",
|
|
||||||
"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. This links to a web-ui 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": "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": [
|
|
||||||
"\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,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"children = list(remote_run.get_children())\n",
|
|
||||||
"metricslist = {}\n",
|
|
||||||
"for run in children:\n",
|
|
||||||
" properties = run.get_properties()\n",
|
|
||||||
" metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)} \n",
|
|
||||||
" metricslist[int(properties['iteration'])] = metrics\n",
|
|
||||||
"\n",
|
|
||||||
"rundata = pd.DataFrame(metricslist).sort_index(1)\n",
|
|
||||||
"rundata"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Canceling Runs\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": [
|
|
||||||
"### Pre-process cache cleanup\n",
|
|
||||||
"The preprocess data gets cache at user default file store. When the run is completed the cache can be cleaned by running below cell"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"remote_run.clean_preprocessor_cache()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"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. 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": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"best_run, fitted_model = remote_run.get_output()"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Best Model based on any other metric"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# lookup_metric = \"accuracy\"\n",
|
|
||||||
"# best_run, fitted_model = remote_run.get_output(metric=lookup_metric)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Model from a specific iteration"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# iteration = 1\n",
|
|
||||||
"# best_run, fitted_model = remote_run.get_output(iteration=iteration)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Test\n"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# Load test data.\n",
|
|
||||||
"from pandas_ml import ConfusionMatrix\n",
|
|
||||||
"\n",
|
|
||||||
"data_test = fetch_20newsgroups(subset = 'test', categories = categories,\n",
|
|
||||||
" shuffle = True, random_state = 42,\n",
|
|
||||||
" remove = remove)\n",
|
|
||||||
"\n",
|
|
||||||
"X_test = np.array(data_test.data).reshape((len(data_test.data),1))\n",
|
|
||||||
"y_test = data_test.target\n",
|
|
||||||
"\n",
|
|
||||||
"# Test our best pipeline.\n",
|
|
||||||
"\n",
|
|
||||||
"y_pred = fitted_model.predict(X_test)\n",
|
|
||||||
"y_pred_strings = [data_test.target_names[i] for i in y_pred]\n",
|
|
||||||
"y_test_strings = [data_test.target_names[i] for i in y_test]\n",
|
|
||||||
"\n",
|
|
||||||
"cm = ConfusionMatrix(y_test_strings, y_pred_strings)\n",
|
|
||||||
"print(cm)\n",
|
|
||||||
"cm.plot()"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"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
|
|
||||||
}
|
|
||||||
@@ -1,534 +0,0 @@
|
|||||||
{
|
|
||||||
"cells": [
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
|
||||||
"\n",
|
|
||||||
"Licensed under the MIT License."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
""
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"# Automated Machine Learning\n",
|
|
||||||
"_**Remote Execution using DSVM (Ubuntu)**_\n",
|
|
||||||
"\n",
|
|
||||||
"## Contents\n",
|
|
||||||
"1. [Introduction](#Introduction)\n",
|
|
||||||
"1. [Setup](#Setup)\n",
|
|
||||||
"1. [Data](#Data)\n",
|
|
||||||
"1. [Train](#Train)\n",
|
|
||||||
"1. [Results](#Results)\n",
|
|
||||||
"1. [Test](#Test)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"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 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 wiil learn how to:\n",
|
|
||||||
"1. Create an `Experiment` in an existing `Workspace`.\n",
|
|
||||||
"2. Attach an existing DSVM to a workspace.\n",
|
|
||||||
"3. Configure AutoML using `AutoMLConfig`.\n",
|
|
||||||
"4. Train the model using the DSVM.\n",
|
|
||||||
"5. Explore the results.\n",
|
|
||||||
"6. Test the best fitted 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",
|
|
||||||
"import time\n",
|
|
||||||
"import csv\n",
|
|
||||||
"\n",
|
|
||||||
"from matplotlib import pyplot as plt\n",
|
|
||||||
"import numpy as np\n",
|
|
||||||
"import pandas as pd\n",
|
|
||||||
"from sklearn import datasets\n",
|
|
||||||
"\n",
|
|
||||||
"import azureml.core\n",
|
|
||||||
"from azureml.core.experiment import Experiment\n",
|
|
||||||
"from azureml.core.workspace import Workspace\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 the run history container in the workspace.\n",
|
|
||||||
"experiment_name = 'automl-remote-dsvm'\n",
|
|
||||||
"project_folder = './project'\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['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",
|
|
||||||
"outputDf.T"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"### Create a Remote Linux DSVM\n",
|
|
||||||
"**Note:** If creation fails with a message about Marketplace purchase eligibilty, start creation of a DSVM through the [Azure portal](https://portal.azure.com), and select \"Want to create programmatically\" to enable programmatic creation. Once you've enabled this setting, you can exit the portal without actually creating the DSVM, and creation of the DSVM through the notebook should work.\n"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.core.compute import DsvmCompute\n",
|
|
||||||
"\n",
|
|
||||||
"dsvm_name = 'mydsvma'\n",
|
|
||||||
"try:\n",
|
|
||||||
" dsvm_compute = DsvmCompute(ws, dsvm_name)\n",
|
|
||||||
" print('Found an existing DSVM.')\n",
|
|
||||||
"except:\n",
|
|
||||||
" print('Creating a new DSVM.')\n",
|
|
||||||
" dsvm_config = DsvmCompute.provisioning_configuration(vm_size = \"Standard_D2_v2\")\n",
|
|
||||||
" dsvm_compute = DsvmCompute.create(ws, name = dsvm_name, provisioning_configuration = dsvm_config)\n",
|
|
||||||
" dsvm_compute.wait_for_completion(show_output = True)\n",
|
|
||||||
" print(\"Waiting one minute for ssh to be accessible\")\n",
|
|
||||||
" time.sleep(90) # Wait for ssh to be accessible"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"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_digits](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html) data."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"data_train = datasets.load_digits()\n",
|
|
||||||
"\n",
|
|
||||||
"if not os.path.isdir('data'):\n",
|
|
||||||
" os.mkdir('data')\n",
|
|
||||||
" \n",
|
|
||||||
"if not os.path.exists(project_folder):\n",
|
|
||||||
" os.makedirs(project_folder)\n",
|
|
||||||
" \n",
|
|
||||||
"pd.DataFrame(data_train.data).to_csv(\"data/X_train.tsv\", index=False, header=False, quoting=csv.QUOTE_ALL, sep=\"\\t\")\n",
|
|
||||||
"pd.DataFrame(data_train.target).to_csv(\"data/y_train.tsv\", index=False, header=False, sep=\"\\t\")\n",
|
|
||||||
"\n",
|
|
||||||
"ds = ws.get_default_datastore()\n",
|
|
||||||
"ds.upload(src_dir='./data', target_path='re_data', overwrite=True, show_progress=True)\n",
|
|
||||||
"\n",
|
|
||||||
"from azureml.core.runconfig import DataReferenceConfiguration\n",
|
|
||||||
"dr = DataReferenceConfiguration(datastore_name=ds.name, \n",
|
|
||||||
" path_on_datastore='re_data', \n",
|
|
||||||
" path_on_compute='/tmp/azureml_runs',\n",
|
|
||||||
" mode='download', # download files from datastore to compute target\n",
|
|
||||||
" overwrite=False)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"from azureml.core.runconfig import RunConfiguration\n",
|
|
||||||
"from azureml.core.conda_dependencies import CondaDependencies\n",
|
|
||||||
"\n",
|
|
||||||
"# create a new RunConfig object\n",
|
|
||||||
"conda_run_config = RunConfiguration(framework=\"python\")\n",
|
|
||||||
"\n",
|
|
||||||
"# Set compute target to the Linux DSVM\n",
|
|
||||||
"conda_run_config.target = dsvm_compute\n",
|
|
||||||
"\n",
|
|
||||||
"# set the data reference of the run coonfiguration\n",
|
|
||||||
"conda_run_config.data_references = {ds.name: dr}\n",
|
|
||||||
"\n",
|
|
||||||
"cd = CondaDependencies.create(pip_packages=['azureml-sdk[automl]'], conda_packages=['numpy','py-xgboost<=0.80'])\n",
|
|
||||||
"conda_run_config.environment.python.conda_dependencies = cd"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"%%writefile $project_folder/get_data.py\n",
|
|
||||||
"\n",
|
|
||||||
"import pandas as pd\n",
|
|
||||||
"\n",
|
|
||||||
"def get_data():\n",
|
|
||||||
" X_train = pd.read_csv(\"/tmp/azureml_runs/re_data/X_train.tsv\", delimiter=\"\\t\", header=None, quotechar='\"')\n",
|
|
||||||
" y_train = pd.read_csv(\"/tmp/azureml_runs/re_data/y_train.tsv\", delimiter=\"\\t\", header=None, quotechar='\"')\n",
|
|
||||||
"\n",
|
|
||||||
" return { \"X\" : X_train.values, \"y\" : y_train[0].values }\n"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Train\n",
|
|
||||||
"\n",
|
|
||||||
"You can specify `automl_settings` as `**kwargs` as well. Also note that you can use a `get_data()` function for local excutions too.\n",
|
|
||||||
"\n",
|
|
||||||
"**Note:** When using Remote DSVM, 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 to execute in parallel. This should be less than the number of cores on the DSVM.|"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"automl_settings = {\n",
|
|
||||||
" \"iteration_timeout_minutes\": 10,\n",
|
|
||||||
" \"iterations\": 20,\n",
|
|
||||||
" \"n_cross_validations\": 5,\n",
|
|
||||||
" \"primary_metric\": 'AUC_weighted',\n",
|
|
||||||
" \"preprocess\": False,\n",
|
|
||||||
" \"max_concurrent_iterations\": 2,\n",
|
|
||||||
" \"verbosity\": logging.INFO\n",
|
|
||||||
"}\n",
|
|
||||||
"\n",
|
|
||||||
"automl_config = AutoMLConfig(task = 'classification',\n",
|
|
||||||
" debug_log = 'automl_errors.log',\n",
|
|
||||||
" path = project_folder, \n",
|
|
||||||
" run_configuration=conda_run_config,\n",
|
|
||||||
" data_script = project_folder + \"/get_data.py\",\n",
|
|
||||||
" **automl_settings\n",
|
|
||||||
" )\n"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"**Note:** The first run on a new DSVM may take several minutes to prepare the environment."
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"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",
|
|
||||||
"\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_480d3ed6-fc94-44aa-8f4e-0b945db9d3ef')"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"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": [
|
|
||||||
"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": [
|
|
||||||
"\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,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"children = list(remote_run.get_children())\n",
|
|
||||||
"metricslist = {}\n",
|
|
||||||
"for run in children:\n",
|
|
||||||
" properties = run.get_properties()\n",
|
|
||||||
" metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)} \n",
|
|
||||||
" metricslist[int(properties['iteration'])] = metrics\n",
|
|
||||||
"\n",
|
|
||||||
"rundata = pd.DataFrame(metricslist).sort_index(1)\n",
|
|
||||||
"rundata"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"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 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,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"best_run, fitted_model = remote_run.get_output()\n",
|
|
||||||
"print(best_run)\n",
|
|
||||||
"print(fitted_model)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Best Model Based on Any Other Metric\n",
|
|
||||||
"Show the run and the model which has the smallest `log_loss` value:"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"lookup_metric = \"log_loss\"\n",
|
|
||||||
"best_run, fitted_model = remote_run.get_output(metric = lookup_metric)\n",
|
|
||||||
"print(best_run)\n",
|
|
||||||
"print(fitted_model)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Model from a Specific Iteration\n",
|
|
||||||
"Show the run and the model from the third iteration:"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"iteration = 3\n",
|
|
||||||
"third_run, third_model = remote_run.get_output(iteration = iteration)\n",
|
|
||||||
"print(third_run)\n",
|
|
||||||
"print(third_model)"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Test\n",
|
|
||||||
"\n",
|
|
||||||
"#### Load Test Data"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"digits = datasets.load_digits()\n",
|
|
||||||
"X_test = digits.data[:10, :]\n",
|
|
||||||
"y_test = digits.target[:10]\n",
|
|
||||||
"images = digits.images[:10]"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"#### Test Our Best Fitted Model"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "code",
|
|
||||||
"execution_count": null,
|
|
||||||
"metadata": {},
|
|
||||||
"outputs": [],
|
|
||||||
"source": [
|
|
||||||
"# Randomly select digits and test.\n",
|
|
||||||
"for index in np.random.choice(len(y_test), 2, replace = False):\n",
|
|
||||||
" print(index)\n",
|
|
||||||
" predicted = fitted_model.predict(X_test[index:index + 1])[0]\n",
|
|
||||||
" label = y_test[index]\n",
|
|
||||||
" title = \"Label value = %d Predicted value = %d \" % (label, predicted)\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()"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"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
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
name: auto-ml-sample-weight
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
|
- azureml-train-automl
|
||||||
|
- azureml-widgets
|
||||||
|
- matplotlib
|
||||||
|
- pandas_ml
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
name: auto-ml-sparse-data-train-test-split
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
|
- azureml-train-automl
|
||||||
|
- azureml-widgets
|
||||||
|
- matplotlib
|
||||||
|
- pandas_ml
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
# Table of Contents
|
||||||
|
1. [Introduction](#introduction)
|
||||||
|
1. [Setup using Azure Data Studio](#azuredatastudiosetup)
|
||||||
|
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 2019 on Linux](#ssms2019)
|
||||||
|
1. [Energy demand example using SQL Server Management Studio](#ssmsenergydemand)
|
||||||
|
|
||||||
|
|
||||||
|
<a name="introduction"></a>
|
||||||
|
# Introduction
|
||||||
|
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.
|
||||||
|
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.
|
||||||
|
|
||||||
|
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.
|
||||||
|
These instructions show using it from Azure Data Studio or SQL Server Managment Studio.
|
||||||
|
|
||||||
|
<a name="azuredatastudiosetup"></a>
|
||||||
|
## Setup 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. 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. 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.
|
||||||
|
|
||||||
|
<a name="azuredatastudioenergydemand"></a>
|
||||||
|
## 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.
|
||||||
|
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>
|
||||||
|
## Setup using SQL Server Management Studio 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)
|
||||||
|
2. Enable external scripts with the following commands:
|
||||||
|
```sh
|
||||||
|
sp_configure 'external scripts enabled',1
|
||||||
|
reconfigure with override
|
||||||
|
```
|
||||||
|
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)
|
||||||
|
```sh
|
||||||
|
cd "C:\Program Files\Microsoft SQL Server"
|
||||||
|
cd "MSSQL14.MSSQLSERVER\PYTHON_SERVICES"
|
||||||
|
python.exe -m pip install azureml-sdk[automl]
|
||||||
|
python.exe -m pip install --upgrade numpy
|
||||||
|
python.exe -m pip install --upgrade sklearn
|
||||||
|
```
|
||||||
|
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".
|
||||||
|
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)
|
||||||
|
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:
|
||||||
|
```sh
|
||||||
|
az login
|
||||||
|
az account set --subscription subscriptionid
|
||||||
|
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”.
|
||||||
|
|
||||||
|
<a name="ssms2019"></a>
|
||||||
|
## 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)
|
||||||
|
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)
|
||||||
|
4. Enable external scripts with the following commands:
|
||||||
|
```sh
|
||||||
|
sp_configure 'external scripts enabled',1
|
||||||
|
reconfigure with override
|
||||||
|
```
|
||||||
|
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):
|
||||||
|
```sh
|
||||||
|
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 sklearn
|
||||||
|
```
|
||||||
|
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.
|
||||||
|
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)
|
||||||
|
11. Create an Azure service principal. You can do this with the commands:
|
||||||
|
```sh
|
||||||
|
az login
|
||||||
|
az account set --subscription subscriptionid
|
||||||
|
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”.
|
||||||
|
|
||||||
|
<a name="ssmsenergydemand"></a>
|
||||||
|
## Energy demand example using SQL Server Management Studio
|
||||||
|
|
||||||
|
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.
|
||||||
|
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. When you get to the column definition page, allow nulls for all columns.
|
||||||
|
|
||||||
|
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.
|
||||||
|
* ForecastEnergyDemand.sql forecasts based on the most recent training run.
|
||||||
|
* GetMetrics.sql returns all the metrics for each model in the most recent training run.
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
-- 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
|
||||||
|
WHERE ExperimentName = 'automl-sql-forecast'
|
||||||
|
ORDER BY CreatedDate DESC)
|
||||||
|
|
||||||
|
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 @TestDataQuery NVARCHAR(MAX) = '
|
||||||
|
SELECT CAST(timeStamp AS NVARCHAR(30)) AS timeStamp,
|
||||||
|
demand,
|
||||||
|
precip,
|
||||||
|
temp
|
||||||
|
FROM nyc_energy
|
||||||
|
WHERE demand IS NOT NULL AND precip IS NOT NULL AND temp IS NOT NULL
|
||||||
|
AND timeStamp > ''' + @split_time + ''''
|
||||||
|
|
||||||
|
EXEC dbo.AutoMLForecast @input_query=@TestDataQuery,
|
||||||
|
@label_column='demand',
|
||||||
|
@time_column_name='timeStamp',
|
||||||
|
@model=@model
|
||||||
|
WITH RESULT SETS ((timeStamp DATETIME, grain NVARCHAR(255), predicted_demand FLOAT, precip FLOAT, temp FLOAT, actual_demand FLOAT))
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
-- This lists all the metrics for all iterations for the most recent run.
|
||||||
|
|
||||||
|
DECLARE @RunId NVARCHAR(43)
|
||||||
|
DECLARE @ExperimentName NVARCHAR(255)
|
||||||
|
|
||||||
|
SELECT TOP 1 @ExperimentName=ExperimentName, @RunId=SUBSTRING(RunId, 1, 43)
|
||||||
|
FROM aml_model
|
||||||
|
ORDER BY CreatedDate DESC
|
||||||
|
|
||||||
|
EXEC dbo.AutoMLGetMetrics @RunId, @ExperimentName
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
-- This shows using the AutoMLPredict 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
|
||||||
|
WHERE ExperimentName = 'automl-sql-forecast'
|
||||||
|
ORDER BY CreatedDate DESC)
|
||||||
|
|
||||||
|
EXEC dbo.AutoMLPredict @input_query='
|
||||||
|
SELECT CAST(timeStamp AS NVARCHAR(30)) AS timeStamp,
|
||||||
|
demand,
|
||||||
|
precip,
|
||||||
|
temp
|
||||||
|
FROM nyc_energy
|
||||||
|
WHERE demand IS NOT NULL AND precip IS NOT NULL AND temp IS NOT NULL
|
||||||
|
AND timeStamp >= ''2017-02-01''',
|
||||||
|
@label_column='demand',
|
||||||
|
@model=@model
|
||||||
|
WITH RESULT SETS ((timeStamp NVARCHAR(30), actual_demand FLOAT, precip FLOAT, temp FLOAT, predicted_demand FLOAT))
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
-- This shows using the AutoMLTrain stored procedure to create a forecasting model for the nyc_energy dataset.
|
||||||
|
|
||||||
|
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 @TrainDataQuery NVARCHAR(MAX) = '
|
||||||
|
SELECT CAST(timeStamp as NVARCHAR(30)) as timeStamp,
|
||||||
|
demand,
|
||||||
|
precip,
|
||||||
|
temp
|
||||||
|
FROM nyc_energy
|
||||||
|
WHERE demand IS NOT NULL AND precip IS NOT NULL AND temp IS NOT NULL
|
||||||
|
and timeStamp < ''' + @split_time + ''''
|
||||||
|
|
||||||
|
INSERT INTO dbo.aml_model(RunId, ExperimentName, Model, LogFileText, WorkspaceName)
|
||||||
|
EXEC dbo.AutoMLTrain @input_query= @TrainDataQuery,
|
||||||
|
@label_column='demand',
|
||||||
|
@task='forecasting',
|
||||||
|
@iterations=10,
|
||||||
|
@iteration_timeout_minutes=5,
|
||||||
|
@time_column_name='timeStamp',
|
||||||
|
@max_horizon=@max_horizon,
|
||||||
|
@experiment_name='automl-sql-forecast',
|
||||||
|
@primary_metric='normalized_root_mean_squared_error'
|
||||||
|
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# 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": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
""
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Set the default database"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"USE [automl]\r\n",
|
||||||
|
"GO"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Use the AutoMLTrain stored procedure to create a forecasting model for the nyc_energy dataset."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"INSERT INTO dbo.aml_model(RunId, ExperimentName, Model, LogFileText, WorkspaceName)\r\n",
|
||||||
|
"EXEC dbo.AutoMLTrain @input_query='\r\n",
|
||||||
|
"SELECT CAST(timeStamp as NVARCHAR(30)) as timeStamp,\r\n",
|
||||||
|
" demand,\r\n",
|
||||||
|
"\t precip,\r\n",
|
||||||
|
"\t temp,\r\n",
|
||||||
|
"\t CASE WHEN timeStamp < ''2017-01-01'' THEN 0 ELSE 1 END AS is_validate_column\r\n",
|
||||||
|
"FROM nyc_energy\r\n",
|
||||||
|
"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",
|
||||||
|
"@iterations=10,\r\n",
|
||||||
|
"@iteration_timeout_minutes=5,\r\n",
|
||||||
|
"@time_column_name='timeStamp',\r\n",
|
||||||
|
"@is_validate_column='is_validate_column',\r\n",
|
||||||
|
"@experiment_name='automl-sql-forecast',\r\n",
|
||||||
|
"@primary_metric='normalized_root_mean_squared_error'"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Use the AutoMLPredict stored procedure to predict using the forecasting model for the nyc_energy dataset."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"DECLARE @Model NVARCHAR(MAX) = (SELECT TOP 1 Model FROM dbo.aml_model\r\n",
|
||||||
|
" WHERE ExperimentName = 'automl-sql-forecast'\r\n",
|
||||||
|
"\t\t\t\t\t\t\t\tORDER BY CreatedDate DESC)\r\n",
|
||||||
|
"\r\n",
|
||||||
|
"EXEC dbo.AutoMLPredict @input_query='\r\n",
|
||||||
|
"SELECT CAST(timeStamp AS NVARCHAR(30)) AS timeStamp,\r\n",
|
||||||
|
" demand,\r\n",
|
||||||
|
"\t precip,\r\n",
|
||||||
|
"\t temp\r\n",
|
||||||
|
"FROM nyc_energy\r\n",
|
||||||
|
"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",
|
||||||
|
"@model=@model\r\n",
|
||||||
|
"WITH RESULT SETS ((timeStamp NVARCHAR(30), actual_demand FLOAT, precip FLOAT, temp FLOAT, predicted_demand FLOAT))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## List all the metrics for all iterations for the most recent training run."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"DECLARE @RunId NVARCHAR(43)\r\n",
|
||||||
|
"DECLARE @ExperimentName NVARCHAR(255)\r\n",
|
||||||
|
"\r\n",
|
||||||
|
"SELECT TOP 1 @ExperimentName=ExperimentName, @RunId=SUBSTRING(RunId, 1, 43)\r\n",
|
||||||
|
"FROM aml_model\r\n",
|
||||||
|
"ORDER BY CreatedDate DESC\r\n",
|
||||||
|
"\r\n",
|
||||||
|
"EXEC dbo.AutoMLGetMetrics @RunId, @ExperimentName"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"authors": [
|
||||||
|
{
|
||||||
|
"name": "jeffshep"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 3.6",
|
||||||
|
"language": "sql",
|
||||||
|
"name": "python36"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"name": "sql",
|
||||||
|
"version": ""
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 2
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
-- This procedure forecast values based on a forecasting model returned by AutoMLTrain.
|
||||||
|
-- It returns a dataset with the forecasted values.
|
||||||
|
SET ANSI_NULLS ON
|
||||||
|
GO
|
||||||
|
SET QUOTED_IDENTIFIER ON
|
||||||
|
GO
|
||||||
|
CREATE OR ALTER PROCEDURE [dbo].[AutoMLForecast]
|
||||||
|
(
|
||||||
|
@input_query NVARCHAR(MAX), -- A SQL query returning data to predict on.
|
||||||
|
@model NVARCHAR(MAX), -- A model returned from AutoMLTrain.
|
||||||
|
@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
|
||||||
|
@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)
|
||||||
|
-- and contain Nan for future times.
|
||||||
|
@forecast_column_name NVARCHAR(255) = 'predicted'
|
||||||
|
-- The name of the output column containing the forecast value.
|
||||||
|
) AS
|
||||||
|
BEGIN
|
||||||
|
|
||||||
|
EXEC sp_execute_external_script @language = N'Python', @script = N'import pandas as pd
|
||||||
|
import azureml.core
|
||||||
|
import numpy as np
|
||||||
|
from azureml.train.automl import AutoMLConfig
|
||||||
|
import pickle
|
||||||
|
import codecs
|
||||||
|
|
||||||
|
model_obj = pickle.loads(codecs.decode(model.encode(), "base64"))
|
||||||
|
|
||||||
|
test_data = input_data.copy()
|
||||||
|
|
||||||
|
if label_column != "" and label_column is not None:
|
||||||
|
y_test = test_data.pop(label_column).values
|
||||||
|
else:
|
||||||
|
y_test = None
|
||||||
|
|
||||||
|
if y_query_column != "" and y_query_column is not None:
|
||||||
|
y_query = test_data.pop(y_query_column).values
|
||||||
|
else:
|
||||||
|
y_query = np.repeat(np.nan, len(test_data))
|
||||||
|
|
||||||
|
X_test = test_data
|
||||||
|
|
||||||
|
if time_column_name != "" and time_column_name is not None:
|
||||||
|
X_test[time_column_name] = pd.to_datetime(X_test[time_column_name])
|
||||||
|
|
||||||
|
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):
|
||||||
|
# Demonstrates how to get the output aligned to the inputs
|
||||||
|
# using pandas indexes. Helps understand what happened if
|
||||||
|
# the output shape differs from the input shape, or if
|
||||||
|
# the data got re-sorted by time and grain during forecasting.
|
||||||
|
|
||||||
|
# Typical causes of misalignment are:
|
||||||
|
# * we predicted some periods that were missing in actuals -> drop from eval
|
||||||
|
# * model was asked to predict past max_horizon -> increase max horizon
|
||||||
|
# * data at start of X_test was needed for lags -> provide previous periods
|
||||||
|
|
||||||
|
df_fcst = pd.DataFrame({forecast_column_name : y_forecast})
|
||||||
|
# y and X outputs are aligned by forecast() function contract
|
||||||
|
df_fcst.index = X_trans.index
|
||||||
|
|
||||||
|
# align original X_test to y_test
|
||||||
|
X_test_full = X_test.copy()
|
||||||
|
if y_test is not None:
|
||||||
|
X_test_full[label_column] = y_test
|
||||||
|
|
||||||
|
# X_test_full does not include origin, so reset for merge
|
||||||
|
df_fcst.reset_index(inplace=True)
|
||||||
|
X_test_full = X_test_full.reset_index().drop(columns=''index'')
|
||||||
|
together = df_fcst.merge(X_test_full, how=''right'')
|
||||||
|
|
||||||
|
# drop rows where prediction or actuals are nan
|
||||||
|
# happens because of missing actuals
|
||||||
|
# or at edges of time due to lags/rolling windows
|
||||||
|
clean = together[together[[label_column, forecast_column_name]].notnull().all(axis=1)]
|
||||||
|
return(clean)
|
||||||
|
|
||||||
|
combined_output = align_outputs(y_fcst, X_trans, X_test, y_test, forecast_column_name)
|
||||||
|
|
||||||
|
'
|
||||||
|
, @input_data_1 = @input_query
|
||||||
|
, @input_data_1_name = N'input_data'
|
||||||
|
, @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)'
|
||||||
|
, @model = @model
|
||||||
|
, @time_column_name = @time_column_name
|
||||||
|
, @label_column = @label_column
|
||||||
|
, @y_query_column = @y_query_column
|
||||||
|
, @forecast_column_name = @forecast_column_name
|
||||||
|
END
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
-- This procedure returns a list of metrics for each iteration of a run.
|
||||||
|
SET ANSI_NULLS ON
|
||||||
|
GO
|
||||||
|
SET QUOTED_IDENTIFIER ON
|
||||||
|
GO
|
||||||
|
CREATE OR ALTER PROCEDURE [dbo].[AutoMLGetMetrics]
|
||||||
|
(
|
||||||
|
@run_id NVARCHAR(250), -- The RunId
|
||||||
|
@experiment_name NVARCHAR(32)='automl-sql-test', -- This can be used to find the experiment in the Azure Portal.
|
||||||
|
@connection_name NVARCHAR(255)='default' -- The AML connection to use.
|
||||||
|
) AS
|
||||||
|
BEGIN
|
||||||
|
DECLARE @tenantid NVARCHAR(255)
|
||||||
|
DECLARE @appid NVARCHAR(255)
|
||||||
|
DECLARE @password NVARCHAR(255)
|
||||||
|
DECLARE @config_file NVARCHAR(255)
|
||||||
|
|
||||||
|
SELECT @tenantid=TenantId, @appid=AppId, @password=Password, @config_file=ConfigFile
|
||||||
|
FROM aml_connection
|
||||||
|
WHERE ConnectionName = @connection_name;
|
||||||
|
|
||||||
|
EXEC sp_execute_external_script @language = N'Python', @script = N'import pandas as pd
|
||||||
|
import logging
|
||||||
|
import azureml.core
|
||||||
|
import numpy as np
|
||||||
|
from azureml.core.experiment import Experiment
|
||||||
|
from azureml.train.automl.run import AutoMLRun
|
||||||
|
from azureml.core.authentication import ServicePrincipalAuthentication
|
||||||
|
from azureml.core.workspace import Workspace
|
||||||
|
|
||||||
|
auth = ServicePrincipalAuthentication(tenantid, appid, password)
|
||||||
|
|
||||||
|
ws = Workspace.from_config(path=config_file, auth=auth)
|
||||||
|
|
||||||
|
experiment = Experiment(ws, experiment_name)
|
||||||
|
|
||||||
|
ml_run = AutoMLRun(experiment = experiment, run_id = run_id)
|
||||||
|
|
||||||
|
children = list(ml_run.get_children())
|
||||||
|
iterationlist = []
|
||||||
|
metricnamelist = []
|
||||||
|
metricvaluelist = []
|
||||||
|
|
||||||
|
for run in children:
|
||||||
|
properties = run.get_properties()
|
||||||
|
if "iteration" in properties:
|
||||||
|
iteration = int(properties["iteration"])
|
||||||
|
for metric_name, metric_value in run.get_metrics().items():
|
||||||
|
if isinstance(metric_value, float):
|
||||||
|
iterationlist.append(iteration)
|
||||||
|
metricnamelist.append(metric_name)
|
||||||
|
metricvaluelist.append(metric_value)
|
||||||
|
|
||||||
|
metrics = pd.DataFrame({"iteration": iterationlist, "metric_name": metricnamelist, "metric_value": metricvaluelist})
|
||||||
|
'
|
||||||
|
, @output_data_1_name = N'metrics'
|
||||||
|
, @params = N'@run_id NVARCHAR(250),
|
||||||
|
@experiment_name NVARCHAR(32),
|
||||||
|
@tenantid NVARCHAR(255),
|
||||||
|
@appid NVARCHAR(255),
|
||||||
|
@password NVARCHAR(255),
|
||||||
|
@config_file NVARCHAR(255)'
|
||||||
|
, @run_id = @run_id
|
||||||
|
, @experiment_name = @experiment_name
|
||||||
|
, @tenantid = @tenantid
|
||||||
|
, @appid = @appid
|
||||||
|
, @password = @password
|
||||||
|
, @config_file = @config_file
|
||||||
|
WITH RESULT SETS ((iteration INT, metric_name NVARCHAR(100), metric_value FLOAT))
|
||||||
|
END
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
-- 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.
|
||||||
|
SET ANSI_NULLS ON
|
||||||
|
GO
|
||||||
|
SET QUOTED_IDENTIFIER ON
|
||||||
|
GO
|
||||||
|
CREATE OR ALTER PROCEDURE [dbo].[AutoMLPredict]
|
||||||
|
(
|
||||||
|
@input_query NVARCHAR(MAX), -- A SQL query returning data to predict on.
|
||||||
|
@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
|
||||||
|
) AS
|
||||||
|
BEGIN
|
||||||
|
|
||||||
|
EXEC sp_execute_external_script @language = N'Python', @script = N'import pandas as pd
|
||||||
|
import azureml.core
|
||||||
|
import numpy as np
|
||||||
|
from azureml.train.automl import AutoMLConfig
|
||||||
|
import pickle
|
||||||
|
import codecs
|
||||||
|
|
||||||
|
model_obj = pickle.loads(codecs.decode(model.encode(), "base64"))
|
||||||
|
|
||||||
|
test_data = input_data.copy()
|
||||||
|
|
||||||
|
if label_column != "" and label_column is not None:
|
||||||
|
y_test = test_data.pop(label_column).values
|
||||||
|
X_test = test_data
|
||||||
|
|
||||||
|
predicted = model_obj.predict(X_test)
|
||||||
|
|
||||||
|
combined_output = input_data.assign(predicted=predicted)
|
||||||
|
|
||||||
|
'
|
||||||
|
, @input_data_1 = @input_query
|
||||||
|
, @input_data_1_name = N'input_data'
|
||||||
|
, @output_data_1_name = N'combined_output'
|
||||||
|
, @params = N'@model NVARCHAR(MAX), @label_column NVARCHAR(255)'
|
||||||
|
, @model = @model
|
||||||
|
, @label_column = @label_column
|
||||||
|
END
|
||||||
@@ -0,0 +1,240 @@
|
|||||||
|
-- This stored procedure uses automated machine learning to train several models
|
||||||
|
-- and returns the best model.
|
||||||
|
--
|
||||||
|
-- The result set has several columns:
|
||||||
|
-- best_run - iteration ID for the best model
|
||||||
|
-- experiment_name - experiment name pass in with the @experiment_name parameter
|
||||||
|
-- fitted_model - best model found
|
||||||
|
-- log_file_text - AutoML debug_log contents
|
||||||
|
-- workspace - name of the Azure ML workspace where run history is stored
|
||||||
|
--
|
||||||
|
-- An example call for a classification problem is:
|
||||||
|
-- insert into dbo.aml_model(RunId, ExperimentName, Model, LogFileText, WorkspaceName)
|
||||||
|
-- exec dbo.AutoMLTrain @input_query='
|
||||||
|
-- SELECT top 100000
|
||||||
|
-- CAST([pickup_datetime] AS NVARCHAR(30)) AS pickup_datetime
|
||||||
|
-- ,CAST([dropoff_datetime] AS NVARCHAR(30)) AS dropoff_datetime
|
||||||
|
-- ,[passenger_count]
|
||||||
|
-- ,[trip_time_in_secs]
|
||||||
|
-- ,[trip_distance]
|
||||||
|
-- ,[payment_type]
|
||||||
|
-- ,[tip_class]
|
||||||
|
-- FROM [dbo].[nyctaxi_sample] order by [hack_license] ',
|
||||||
|
-- @label_column = 'tip_class',
|
||||||
|
-- @iterations=10
|
||||||
|
--
|
||||||
|
-- An example call for forecasting is:
|
||||||
|
-- insert into dbo.aml_model(RunId, ExperimentName, Model, LogFileText, WorkspaceName)
|
||||||
|
-- exec dbo.AutoMLTrain @input_query='
|
||||||
|
-- select cast(timeStamp as nvarchar(30)) as timeStamp,
|
||||||
|
-- demand,
|
||||||
|
-- precip,
|
||||||
|
-- temp,
|
||||||
|
-- case when timeStamp < ''2017-01-01'' then 0 else 1 end as is_validate_column
|
||||||
|
-- from nyc_energy
|
||||||
|
-- where demand is not null and precip is not null and temp is not null
|
||||||
|
-- and timeStamp < ''2017-02-01''',
|
||||||
|
-- @label_column='demand',
|
||||||
|
-- @task='forecasting',
|
||||||
|
-- @iterations=10,
|
||||||
|
-- @iteration_timeout_minutes=5,
|
||||||
|
-- @time_column_name='timeStamp',
|
||||||
|
-- @is_validate_column='is_validate_column',
|
||||||
|
-- @experiment_name='automl-sql-forecast',
|
||||||
|
-- @primary_metric='normalized_root_mean_squared_error'
|
||||||
|
|
||||||
|
SET ANSI_NULLS ON
|
||||||
|
GO
|
||||||
|
SET QUOTED_IDENTIFIER ON
|
||||||
|
GO
|
||||||
|
CREATE OR ALTER PROCEDURE [dbo].[AutoMLTrain]
|
||||||
|
(
|
||||||
|
@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.
|
||||||
|
@primary_metric NVARCHAR(40)='AUC_weighted', -- The metric to optimize.
|
||||||
|
@iterations INT=100, -- The maximum number of pipelines to train.
|
||||||
|
@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.
|
||||||
|
@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.
|
||||||
|
@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.
|
||||||
|
-- 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
|
||||||
|
@whitelist_models NVARCHAR(MAX) = '', -- A comma separated list of algos that can be used.
|
||||||
|
-- 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
|
||||||
|
@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.
|
||||||
|
@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.
|
||||||
|
@time_column_name NVARCHAR(255)='', -- The name of the timestamp column for forecasting.
|
||||||
|
@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)
|
||||||
|
-- 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.
|
||||||
|
) AS
|
||||||
|
BEGIN
|
||||||
|
|
||||||
|
DECLARE @tenantid NVARCHAR(255)
|
||||||
|
DECLARE @appid NVARCHAR(255)
|
||||||
|
DECLARE @password NVARCHAR(255)
|
||||||
|
DECLARE @config_file NVARCHAR(255)
|
||||||
|
|
||||||
|
SELECT @tenantid=TenantId, @appid=AppId, @password=Password, @config_file=ConfigFile
|
||||||
|
FROM aml_connection
|
||||||
|
WHERE ConnectionName = @connection_name;
|
||||||
|
|
||||||
|
EXEC sp_execute_external_script @language = N'Python', @script = N'import pandas as pd
|
||||||
|
import logging
|
||||||
|
import azureml.core
|
||||||
|
import pandas as pd
|
||||||
|
import numpy as np
|
||||||
|
from azureml.core.experiment import Experiment
|
||||||
|
from azureml.train.automl import AutoMLConfig
|
||||||
|
from sklearn import datasets
|
||||||
|
import pickle
|
||||||
|
import codecs
|
||||||
|
from azureml.core.authentication import ServicePrincipalAuthentication
|
||||||
|
from azureml.core.workspace import Workspace
|
||||||
|
|
||||||
|
if __name__.startswith("sqlindb"):
|
||||||
|
auth = ServicePrincipalAuthentication(tenantid, appid, password)
|
||||||
|
|
||||||
|
ws = Workspace.from_config(path=config_file, auth=auth)
|
||||||
|
|
||||||
|
project_folder = "./sample_projects/" + experiment_name
|
||||||
|
|
||||||
|
experiment = Experiment(ws, experiment_name)
|
||||||
|
|
||||||
|
data_train = input_data
|
||||||
|
X_valid = None
|
||||||
|
y_valid = None
|
||||||
|
sample_weight_valid = None
|
||||||
|
|
||||||
|
if is_validate_column != "" and is_validate_column is not None:
|
||||||
|
data_train = 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_valid.pop(is_validate_column)
|
||||||
|
y_valid = data_valid.pop(label_column).values
|
||||||
|
if sample_weight_column != "" and sample_weight_column is not None:
|
||||||
|
sample_weight_valid = data_valid.pop(sample_weight_column).values
|
||||||
|
X_valid = data_valid
|
||||||
|
n_cross_validations = None
|
||||||
|
|
||||||
|
y_train = data_train.pop(label_column).values
|
||||||
|
|
||||||
|
sample_weight = None
|
||||||
|
if sample_weight_column != "" and sample_weight_column is not None:
|
||||||
|
sample_weight = data_train.pop(sample_weight_column).values
|
||||||
|
|
||||||
|
X_train = data_train
|
||||||
|
|
||||||
|
if experiment_timeout_minutes == 0:
|
||||||
|
experiment_timeout_minutes = None
|
||||||
|
|
||||||
|
if experiment_exit_score == 0:
|
||||||
|
experiment_exit_score = None
|
||||||
|
|
||||||
|
if blacklist_models == "":
|
||||||
|
blacklist_models = None
|
||||||
|
|
||||||
|
if blacklist_models is not None:
|
||||||
|
blacklist_models = blacklist_models.replace(" ", "").split(",")
|
||||||
|
|
||||||
|
if whitelist_models == "":
|
||||||
|
whitelist_models = None
|
||||||
|
|
||||||
|
if whitelist_models is not None:
|
||||||
|
whitelist_models = whitelist_models.replace(" ", "").split(",")
|
||||||
|
|
||||||
|
automl_settings = {}
|
||||||
|
preprocess = True
|
||||||
|
if time_column_name != "" and time_column_name is not None:
|
||||||
|
automl_settings = { "time_column_name": time_column_name }
|
||||||
|
preprocess = False
|
||||||
|
if max_horizon > 0:
|
||||||
|
automl_settings["max_horizon"] = max_horizon
|
||||||
|
|
||||||
|
log_file_name = "automl_sqlindb_errors.log"
|
||||||
|
|
||||||
|
automl_config = AutoMLConfig(task = task,
|
||||||
|
debug_log = log_file_name,
|
||||||
|
primary_metric = primary_metric,
|
||||||
|
iteration_timeout_minutes = iteration_timeout_minutes,
|
||||||
|
experiment_timeout_minutes = experiment_timeout_minutes,
|
||||||
|
iterations = iterations,
|
||||||
|
n_cross_validations = n_cross_validations,
|
||||||
|
preprocess = preprocess,
|
||||||
|
verbosity = logging.INFO,
|
||||||
|
X = X_train,
|
||||||
|
y = y_train,
|
||||||
|
path = project_folder,
|
||||||
|
blacklist_models = blacklist_models,
|
||||||
|
whitelist_models = whitelist_models,
|
||||||
|
experiment_exit_score = experiment_exit_score,
|
||||||
|
sample_weight = sample_weight,
|
||||||
|
X_valid = X_valid,
|
||||||
|
y_valid = y_valid,
|
||||||
|
sample_weight_valid = sample_weight_valid,
|
||||||
|
**automl_settings)
|
||||||
|
|
||||||
|
local_run = experiment.submit(automl_config, show_output = True)
|
||||||
|
|
||||||
|
best_run, fitted_model = local_run.get_output()
|
||||||
|
|
||||||
|
pickled_model = codecs.encode(pickle.dumps(fitted_model), "base64").decode()
|
||||||
|
|
||||||
|
log_file_text = ""
|
||||||
|
|
||||||
|
try:
|
||||||
|
with open(log_file_name, "r") as log_file:
|
||||||
|
log_file_text = log_file.read()
|
||||||
|
except:
|
||||||
|
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))
|
||||||
|
'
|
||||||
|
, @input_data_1 = @input_query
|
||||||
|
, @input_data_1_name = N'input_data'
|
||||||
|
, @output_data_1_name = N'returned_model'
|
||||||
|
, @params = N'@label_column NVARCHAR(255),
|
||||||
|
@primary_metric NVARCHAR(40),
|
||||||
|
@iterations INT, @task NVARCHAR(40),
|
||||||
|
@experiment_name NVARCHAR(32),
|
||||||
|
@iteration_timeout_minutes INT,
|
||||||
|
@experiment_timeout_minutes INT,
|
||||||
|
@n_cross_validations INT,
|
||||||
|
@blacklist_models NVARCHAR(MAX),
|
||||||
|
@whitelist_models NVARCHAR(MAX),
|
||||||
|
@experiment_exit_score FLOAT,
|
||||||
|
@sample_weight_column NVARCHAR(255),
|
||||||
|
@is_validate_column NVARCHAR(255),
|
||||||
|
@time_column_name NVARCHAR(255),
|
||||||
|
@tenantid NVARCHAR(255),
|
||||||
|
@appid NVARCHAR(255),
|
||||||
|
@password NVARCHAR(255),
|
||||||
|
@config_file NVARCHAR(255),
|
||||||
|
@max_horizon INT'
|
||||||
|
, @label_column = @label_column
|
||||||
|
, @primary_metric = @primary_metric
|
||||||
|
, @iterations = @iterations
|
||||||
|
, @task = @task
|
||||||
|
, @experiment_name = @experiment_name
|
||||||
|
, @iteration_timeout_minutes = @iteration_timeout_minutes
|
||||||
|
, @experiment_timeout_minutes = @experiment_timeout_minutes
|
||||||
|
, @n_cross_validations = @n_cross_validations
|
||||||
|
, @blacklist_models = @blacklist_models
|
||||||
|
, @whitelist_models = @whitelist_models
|
||||||
|
, @experiment_exit_score = @experiment_exit_score
|
||||||
|
, @sample_weight_column = @sample_weight_column
|
||||||
|
, @is_validate_column = @is_validate_column
|
||||||
|
, @time_column_name = @time_column_name
|
||||||
|
, @tenantid = @tenantid
|
||||||
|
, @appid = @appid
|
||||||
|
, @password = @password
|
||||||
|
, @config_file = @config_file
|
||||||
|
, @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)))
|
||||||
|
END
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
-- This is a table to store the Azure ML connection information.
|
||||||
|
SET ANSI_NULLS ON
|
||||||
|
GO
|
||||||
|
|
||||||
|
SET QUOTED_IDENTIFIER ON
|
||||||
|
GO
|
||||||
|
|
||||||
|
CREATE TABLE [dbo].[aml_connection](
|
||||||
|
[Id] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
|
||||||
|
[ConnectionName] [nvarchar](255) NULL,
|
||||||
|
[TenantId] [nvarchar](255) NULL,
|
||||||
|
[AppId] [nvarchar](255) NULL,
|
||||||
|
[Password] [nvarchar](255) NULL,
|
||||||
|
[ConfigFile] [nvarchar](255) NULL
|
||||||
|
) ON [PRIMARY]
|
||||||
|
GO
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
-- This is a table to hold the results from the AutoMLTrain procedure.
|
||||||
|
SET ANSI_NULLS ON
|
||||||
|
GO
|
||||||
|
|
||||||
|
SET QUOTED_IDENTIFIER ON
|
||||||
|
GO
|
||||||
|
|
||||||
|
CREATE TABLE [dbo].[aml_model](
|
||||||
|
[Id] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
|
||||||
|
[Model] [varchar](max) NOT NULL, -- The model, which can be passed to AutoMLPredict for testing or prediction.
|
||||||
|
[RunId] [nvarchar](250) NULL, -- The RunId, which can be used to view the model in the Azure Portal.
|
||||||
|
[CreatedDate] [datetime] NULL,
|
||||||
|
[ExperimentName] [nvarchar](100) NULL, -- Azure ML Experiment Name
|
||||||
|
[WorkspaceName] [nvarchar](100) NULL, -- Azure ML Workspace Name
|
||||||
|
[LogFileText] [nvarchar](max) NULL
|
||||||
|
)
|
||||||
|
GO
|
||||||
|
|
||||||
|
ALTER TABLE [dbo].[aml_model] ADD DEFAULT (getutcdate()) FOR [CreatedDate]
|
||||||
|
GO
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,562 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Set up Azure ML Automated Machine Learning on SQL Server 2019 CTP 2.4 big data cluster\r\n",
|
||||||
|
"\r\n",
|
||||||
|
"\\# Prerequisites: \r\n",
|
||||||
|
"\\# - An Azure subscription and resource group \r\n",
|
||||||
|
"\\# - An Azure Machine Learning workspace \r\n",
|
||||||
|
"\\# - A SQL Server 2019 CTP 2.4 big data cluster with Internet access and a database named 'automl' \r\n",
|
||||||
|
"\\# - Azure CLI \r\n",
|
||||||
|
"\\# - kubectl command \r\n",
|
||||||
|
"\\# - The https://github.com/Azure/MachineLearningNotebooks repository downloaded (cloned) to your local machine\r\n",
|
||||||
|
"\r\n",
|
||||||
|
"\\# In the 'automl' database, create a table named 'dbo.nyc_energy' as follows: \r\n",
|
||||||
|
"\\# - In SQL Server Management Studio, right-click the 'automl' database, select Tasks, then Import Flat File. \r\n",
|
||||||
|
"\\# - Select the file AzureMlCli\\notebooks\\how-to-use-azureml\\automated-machine-learning\\forecasting-energy-demand\\nyc_energy.csv. \r\n",
|
||||||
|
"\\# - Using the \"Modify Columns\" page, allow nulls for all columns. \r\n",
|
||||||
|
"\r\n",
|
||||||
|
"\\# Create an Azure Machine Learning Workspace using the instructions at https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-workspace \r\n",
|
||||||
|
"\r\n",
|
||||||
|
"\\# Create an Azure service principal. You can do this with the following commands: \r\n",
|
||||||
|
"\r\n",
|
||||||
|
"az login \r\n",
|
||||||
|
"az account set --subscription *subscriptionid* \r\n",
|
||||||
|
"\r\n",
|
||||||
|
"\\# The following command prints out the **appId** and **tenant**, \r\n",
|
||||||
|
"\\# which you insert into the indicated cell later in this notebook \r\n",
|
||||||
|
"\\# to allow AutoML to authenticate with Azure: \r\n",
|
||||||
|
"\r\n",
|
||||||
|
"az ad sp create-for-rbac --name *principlename* --password *password*\r\n",
|
||||||
|
"\r\n",
|
||||||
|
"\\# Log into the master instance of SQL Server 2019 CTP 2.4: \r\n",
|
||||||
|
"kubectl exec -it mssql-master-pool-0 -n *clustername* -c mssql-server -- /bin/bash\r\n",
|
||||||
|
"\r\n",
|
||||||
|
"mkdir /tmp/aml\r\n",
|
||||||
|
"\r\n",
|
||||||
|
"cd /tmp/aml\r\n",
|
||||||
|
"\r\n",
|
||||||
|
"\\# **Modify** the following with your subscription_id, resource_group, and workspace_name: \r\n",
|
||||||
|
"cat > config.json << EOF \r\n",
|
||||||
|
"{ \r\n",
|
||||||
|
" \"subscription_id\": \"123456ab-78cd-0123-45ef-abcd12345678\", \r\n",
|
||||||
|
" \"resource_group\": \"myrg1\", \r\n",
|
||||||
|
" \"workspace_name\": \"myws1\" \r\n",
|
||||||
|
"} \r\n",
|
||||||
|
"EOF\r\n",
|
||||||
|
"\r\n",
|
||||||
|
"\\# The directory referenced below is appropriate for the master instance of SQL Server 2019 CTP 2.4.\r\n",
|
||||||
|
"\r\n",
|
||||||
|
"cd /opt/mssql/mlservices/runtime/python/bin\r\n",
|
||||||
|
"\r\n",
|
||||||
|
"./python -m pip install azureml-sdk[automl]\r\n",
|
||||||
|
"\r\n",
|
||||||
|
"./python -m pip install --upgrade numpy \r\n",
|
||||||
|
"\r\n",
|
||||||
|
"./python -m pip install --upgrade sklearn\r\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
""
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"-- Enable external scripts to allow invoking Python\r\n",
|
||||||
|
"sp_configure 'external scripts enabled',1 \r\n",
|
||||||
|
"reconfigure with override \r\n",
|
||||||
|
"GO\r\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"-- Use database 'automl'\r\n",
|
||||||
|
"USE [automl]\r\n",
|
||||||
|
"GO"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"-- This is a table to hold the Azure ML connection information.\r\n",
|
||||||
|
"SET ANSI_NULLS ON\r\n",
|
||||||
|
"GO\r\n",
|
||||||
|
"\r\n",
|
||||||
|
"SET QUOTED_IDENTIFIER ON\r\n",
|
||||||
|
"GO\r\n",
|
||||||
|
"\r\n",
|
||||||
|
"CREATE TABLE [dbo].[aml_connection](\r\n",
|
||||||
|
" [Id] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,\r\n",
|
||||||
|
"\t[ConnectionName] [nvarchar](255) NULL,\r\n",
|
||||||
|
"\t[TenantId] [nvarchar](255) NULL,\r\n",
|
||||||
|
"\t[AppId] [nvarchar](255) NULL,\r\n",
|
||||||
|
"\t[Password] [nvarchar](255) NULL,\r\n",
|
||||||
|
"\t[ConfigFile] [nvarchar](255) NULL\r\n",
|
||||||
|
") ON [PRIMARY]\r\n",
|
||||||
|
"GO"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Copy the values from create-for-rbac above into the cell below"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"-- Use the following values:\r\n",
|
||||||
|
"-- Leave the name as 'Default'\r\n",
|
||||||
|
"-- Insert <tenant> returned by create-for-rbac above\r\n",
|
||||||
|
"-- Insert <AppId> returned by create-for-rbac above\r\n",
|
||||||
|
"-- Insert <password> used in create-for-rbac above\r\n",
|
||||||
|
"-- Leave <path> as '/tmp/aml/config.json'\r\n",
|
||||||
|
"INSERT INTO [dbo].[aml_connection] \r\n",
|
||||||
|
"VALUES (\r\n",
|
||||||
|
" N'Default', -- Name\r\n",
|
||||||
|
" N'11111111-2222-3333-4444-555555555555', -- Tenant\r\n",
|
||||||
|
" N'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee', -- AppId\r\n",
|
||||||
|
" N'insertpasswordhere', -- Password\r\n",
|
||||||
|
" N'/tmp/aml/config.json' -- Path\r\n",
|
||||||
|
" );\r\n",
|
||||||
|
"GO"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"-- This is a table to hold the results from the AutoMLTrain procedure.\r\n",
|
||||||
|
"SET ANSI_NULLS ON\r\n",
|
||||||
|
"GO\r\n",
|
||||||
|
"\r\n",
|
||||||
|
"SET QUOTED_IDENTIFIER ON\r\n",
|
||||||
|
"GO\r\n",
|
||||||
|
"\r\n",
|
||||||
|
"CREATE TABLE [dbo].[aml_model](\r\n",
|
||||||
|
" [Id] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,\r\n",
|
||||||
|
" [Model] [varchar](max) NOT NULL, -- The model, which can be passed to AutoMLPredict for testing or prediction.\r\n",
|
||||||
|
" [RunId] [nvarchar](250) NULL, -- The RunId, which can be used to view the model in the Azure Portal.\r\n",
|
||||||
|
" [CreatedDate] [datetime] NULL,\r\n",
|
||||||
|
" [ExperimentName] [nvarchar](100) NULL, -- Azure ML Experiment Name\r\n",
|
||||||
|
" [WorkspaceName] [nvarchar](100) NULL, -- Azure ML Workspace Name\r\n",
|
||||||
|
"\t[LogFileText] [nvarchar](max) NULL\r\n",
|
||||||
|
") \r\n",
|
||||||
|
"GO\r\n",
|
||||||
|
"\r\n",
|
||||||
|
"ALTER TABLE [dbo].[aml_model] ADD DEFAULT (getutcdate()) FOR [CreatedDate]\r\n",
|
||||||
|
"GO\r\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"-- This stored procedure uses automated machine learning to train several models\r\n",
|
||||||
|
"-- and return the best model.\r\n",
|
||||||
|
"--\r\n",
|
||||||
|
"-- The result set has several columns:\r\n",
|
||||||
|
"-- best_run - ID of the best model found\r\n",
|
||||||
|
"-- experiment_name - training run name\r\n",
|
||||||
|
"-- fitted_model - best model found\r\n",
|
||||||
|
"-- log_file_text - console output\r\n",
|
||||||
|
"-- workspace - name of the Azure ML workspace where run history is stored\r\n",
|
||||||
|
"--\r\n",
|
||||||
|
"-- An example call for a classification problem is:\r\n",
|
||||||
|
"-- insert into dbo.aml_model(RunId, ExperimentName, Model, LogFileText, WorkspaceName)\r\n",
|
||||||
|
"-- exec dbo.AutoMLTrain @input_query='\r\n",
|
||||||
|
"-- SELECT top 100000 \r\n",
|
||||||
|
"-- CAST([pickup_datetime] AS NVARCHAR(30)) AS pickup_datetime\r\n",
|
||||||
|
"-- ,CAST([dropoff_datetime] AS NVARCHAR(30)) AS dropoff_datetime\r\n",
|
||||||
|
"-- ,[passenger_count]\r\n",
|
||||||
|
"-- ,[trip_time_in_secs]\r\n",
|
||||||
|
"-- ,[trip_distance]\r\n",
|
||||||
|
"-- ,[payment_type]\r\n",
|
||||||
|
"-- ,[tip_class]\r\n",
|
||||||
|
"-- FROM [dbo].[nyctaxi_sample] order by [hack_license] ',\r\n",
|
||||||
|
"-- @label_column = 'tip_class',\r\n",
|
||||||
|
"-- @iterations=10\r\n",
|
||||||
|
"-- \r\n",
|
||||||
|
"-- An example call for forecasting is:\r\n",
|
||||||
|
"-- insert into dbo.aml_model(RunId, ExperimentName, Model, LogFileText, WorkspaceName)\r\n",
|
||||||
|
"-- exec dbo.AutoMLTrain @input_query='\r\n",
|
||||||
|
"-- select cast(timeStamp as nvarchar(30)) as timeStamp,\r\n",
|
||||||
|
"-- demand,\r\n",
|
||||||
|
"-- \t precip,\r\n",
|
||||||
|
"-- \t temp,\r\n",
|
||||||
|
"-- case when timeStamp < ''2017-01-01'' then 0 else 1 end as is_validate_column\r\n",
|
||||||
|
"-- from nyc_energy\r\n",
|
||||||
|
"-- 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",
|
||||||
|
"-- @iterations=10,\r\n",
|
||||||
|
"-- @iteration_timeout_minutes=5,\r\n",
|
||||||
|
"-- @time_column_name='timeStamp',\r\n",
|
||||||
|
"-- @is_validate_column='is_validate_column',\r\n",
|
||||||
|
"-- @experiment_name='automl-sql-forecast',\r\n",
|
||||||
|
"-- @primary_metric='normalized_root_mean_squared_error'\r\n",
|
||||||
|
"\r\n",
|
||||||
|
"SET ANSI_NULLS ON\r\n",
|
||||||
|
"GO\r\n",
|
||||||
|
"SET QUOTED_IDENTIFIER ON\r\n",
|
||||||
|
"GO\r\n",
|
||||||
|
"CREATE OR ALTER PROCEDURE [dbo].[AutoMLTrain]\r\n",
|
||||||
|
" (\r\n",
|
||||||
|
" @input_query NVARCHAR(MAX), -- The SQL Query that will return the data to train and validate the model.\r\n",
|
||||||
|
" @label_column NVARCHAR(255)='Label', -- The name of the column in the result of @input_query that is the label.\r\n",
|
||||||
|
" @primary_metric NVARCHAR(40)='AUC_weighted', -- The metric to optimize.\r\n",
|
||||||
|
" @iterations INT=100, -- The maximum number of pipelines to train.\r\n",
|
||||||
|
" @task NVARCHAR(40)='classification', -- The type of task. Can be classification, regression or forecasting.\r\n",
|
||||||
|
" @experiment_name NVARCHAR(32)='automl-sql-test', -- This can be used to find the experiment in the Azure Portal.\r\n",
|
||||||
|
" @iteration_timeout_minutes INT = 15, -- The maximum time in minutes for training a single pipeline. \r\n",
|
||||||
|
" @experiment_timeout_minutes INT = 60, -- The maximum time in minutes for training all pipelines.\r\n",
|
||||||
|
" @n_cross_validations INT = 3, -- The number of cross validations.\r\n",
|
||||||
|
" @blacklist_models NVARCHAR(MAX) = '', -- A comma separated list of algos that will not be used.\r\n",
|
||||||
|
" -- The list of possible models can be found at:\r\n",
|
||||||
|
" -- https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-configure-auto-train#configure-your-experiment-settings\r\n",
|
||||||
|
" @whitelist_models NVARCHAR(MAX) = '', -- A comma separated list of algos that can be used.\r\n",
|
||||||
|
" -- The list of possible models can be found at:\r\n",
|
||||||
|
" -- https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-configure-auto-train#configure-your-experiment-settings\r\n",
|
||||||
|
" @experiment_exit_score FLOAT = 0, -- Stop the experiment if this score is acheived.\r\n",
|
||||||
|
" @sample_weight_column NVARCHAR(255)='', -- The name of the column in the result of @input_query that gives a sample weight.\r\n",
|
||||||
|
" @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.\r\n",
|
||||||
|
"\t -- In the values of the column, 0 means for training and 1 means for validation.\r\n",
|
||||||
|
" @time_column_name NVARCHAR(255)='', -- The name of the timestamp column for forecasting.\r\n",
|
||||||
|
"\t@connection_name NVARCHAR(255)='default' -- The AML connection to use.\r\n",
|
||||||
|
" ) AS\r\n",
|
||||||
|
"BEGIN\r\n",
|
||||||
|
"\r\n",
|
||||||
|
" DECLARE @tenantid NVARCHAR(255)\r\n",
|
||||||
|
" DECLARE @appid NVARCHAR(255)\r\n",
|
||||||
|
" DECLARE @password NVARCHAR(255)\r\n",
|
||||||
|
" DECLARE @config_file NVARCHAR(255)\r\n",
|
||||||
|
"\r\n",
|
||||||
|
"\tSELECT @tenantid=TenantId, @appid=AppId, @password=Password, @config_file=ConfigFile\r\n",
|
||||||
|
"\tFROM aml_connection\r\n",
|
||||||
|
"\tWHERE ConnectionName = @connection_name;\r\n",
|
||||||
|
"\r\n",
|
||||||
|
"\tEXEC sp_execute_external_script @language = N'Python', @script = N'import pandas as pd\r\n",
|
||||||
|
"import logging \r\n",
|
||||||
|
"import azureml.core \r\n",
|
||||||
|
"import pandas as pd\r\n",
|
||||||
|
"import numpy as np\r\n",
|
||||||
|
"from azureml.core.experiment import Experiment \r\n",
|
||||||
|
"from azureml.train.automl import AutoMLConfig \r\n",
|
||||||
|
"from sklearn import datasets \r\n",
|
||||||
|
"import pickle\r\n",
|
||||||
|
"import codecs\r\n",
|
||||||
|
"from azureml.core.authentication import ServicePrincipalAuthentication \r\n",
|
||||||
|
"from azureml.core.workspace import Workspace \r\n",
|
||||||
|
"\r\n",
|
||||||
|
"if __name__.startswith(\"sqlindb\"):\r\n",
|
||||||
|
" auth = ServicePrincipalAuthentication(tenantid, appid, password) \r\n",
|
||||||
|
" \r\n",
|
||||||
|
" ws = Workspace.from_config(path=config_file, auth=auth) \r\n",
|
||||||
|
" \r\n",
|
||||||
|
" project_folder = \"./sample_projects/\" + experiment_name\r\n",
|
||||||
|
" \r\n",
|
||||||
|
" experiment = Experiment(ws, experiment_name) \r\n",
|
||||||
|
"\r\n",
|
||||||
|
" data_train = input_data\r\n",
|
||||||
|
" X_valid = None\r\n",
|
||||||
|
" y_valid = None\r\n",
|
||||||
|
" sample_weight_valid = None\r\n",
|
||||||
|
"\r\n",
|
||||||
|
" if is_validate_column != \"\" and is_validate_column is not None:\r\n",
|
||||||
|
" data_train = input_data[input_data[is_validate_column] <= 0]\r\n",
|
||||||
|
" data_valid = input_data[input_data[is_validate_column] > 0]\r\n",
|
||||||
|
" data_train.pop(is_validate_column)\r\n",
|
||||||
|
" data_valid.pop(is_validate_column)\r\n",
|
||||||
|
" y_valid = data_valid.pop(label_column).values\r\n",
|
||||||
|
" if sample_weight_column != \"\" and sample_weight_column is not None:\r\n",
|
||||||
|
" sample_weight_valid = data_valid.pop(sample_weight_column).values\r\n",
|
||||||
|
" X_valid = data_valid\r\n",
|
||||||
|
" n_cross_validations = None\r\n",
|
||||||
|
"\r\n",
|
||||||
|
" y_train = data_train.pop(label_column).values\r\n",
|
||||||
|
"\r\n",
|
||||||
|
" sample_weight = None\r\n",
|
||||||
|
" if sample_weight_column != \"\" and sample_weight_column is not None:\r\n",
|
||||||
|
" sample_weight = data_train.pop(sample_weight_column).values\r\n",
|
||||||
|
"\r\n",
|
||||||
|
" X_train = data_train\r\n",
|
||||||
|
"\r\n",
|
||||||
|
" if experiment_timeout_minutes == 0:\r\n",
|
||||||
|
" experiment_timeout_minutes = None\r\n",
|
||||||
|
"\r\n",
|
||||||
|
" if experiment_exit_score == 0:\r\n",
|
||||||
|
" experiment_exit_score = None\r\n",
|
||||||
|
"\r\n",
|
||||||
|
" if blacklist_models == \"\":\r\n",
|
||||||
|
" blacklist_models = None\r\n",
|
||||||
|
"\r\n",
|
||||||
|
" if blacklist_models is not None:\r\n",
|
||||||
|
" blacklist_models = blacklist_models.replace(\" \", \"\").split(\",\")\r\n",
|
||||||
|
"\r\n",
|
||||||
|
" if whitelist_models == \"\":\r\n",
|
||||||
|
" whitelist_models = None\r\n",
|
||||||
|
"\r\n",
|
||||||
|
" if whitelist_models is not None:\r\n",
|
||||||
|
" whitelist_models = whitelist_models.replace(\" \", \"\").split(\",\")\r\n",
|
||||||
|
"\r\n",
|
||||||
|
" automl_settings = {}\r\n",
|
||||||
|
" preprocess = True\r\n",
|
||||||
|
" if time_column_name != \"\" and time_column_name is not None:\r\n",
|
||||||
|
" automl_settings = { \"time_column_name\": time_column_name }\r\n",
|
||||||
|
" preprocess = False\r\n",
|
||||||
|
"\r\n",
|
||||||
|
" log_file_name = \"automl_errors.log\"\r\n",
|
||||||
|
"\t \r\n",
|
||||||
|
" automl_config = AutoMLConfig(task = task, \r\n",
|
||||||
|
" debug_log = log_file_name, \r\n",
|
||||||
|
" primary_metric = primary_metric, \r\n",
|
||||||
|
" iteration_timeout_minutes = iteration_timeout_minutes, \r\n",
|
||||||
|
" experiment_timeout_minutes = experiment_timeout_minutes,\r\n",
|
||||||
|
" iterations = iterations, \r\n",
|
||||||
|
" n_cross_validations = n_cross_validations, \r\n",
|
||||||
|
" preprocess = preprocess,\r\n",
|
||||||
|
" verbosity = logging.INFO, \r\n",
|
||||||
|
" enable_ensembling = False,\r\n",
|
||||||
|
" X = X_train, \r\n",
|
||||||
|
" y = y_train, \r\n",
|
||||||
|
" path = project_folder,\r\n",
|
||||||
|
" blacklist_models = blacklist_models,\r\n",
|
||||||
|
" whitelist_models = whitelist_models,\r\n",
|
||||||
|
" experiment_exit_score = experiment_exit_score,\r\n",
|
||||||
|
" sample_weight = sample_weight,\r\n",
|
||||||
|
" X_valid = X_valid,\r\n",
|
||||||
|
" y_valid = y_valid,\r\n",
|
||||||
|
" sample_weight_valid = sample_weight_valid,\r\n",
|
||||||
|
" **automl_settings) \r\n",
|
||||||
|
" \r\n",
|
||||||
|
" local_run = experiment.submit(automl_config, show_output = True) \r\n",
|
||||||
|
"\r\n",
|
||||||
|
" best_run, fitted_model = local_run.get_output()\r\n",
|
||||||
|
"\r\n",
|
||||||
|
" pickled_model = codecs.encode(pickle.dumps(fitted_model), \"base64\").decode()\r\n",
|
||||||
|
"\r\n",
|
||||||
|
" log_file_text = \"\"\r\n",
|
||||||
|
"\r\n",
|
||||||
|
" try:\r\n",
|
||||||
|
" with open(log_file_name, \"r\") as log_file:\r\n",
|
||||||
|
" log_file_text = log_file.read()\r\n",
|
||||||
|
" except:\r\n",
|
||||||
|
" log_file_text = \"Log file not found\"\r\n",
|
||||||
|
"\r\n",
|
||||||
|
" 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))\r\n",
|
||||||
|
"'\r\n",
|
||||||
|
"\t, @input_data_1 = @input_query\r\n",
|
||||||
|
"\t, @input_data_1_name = N'input_data'\r\n",
|
||||||
|
"\t, @output_data_1_name = N'returned_model'\r\n",
|
||||||
|
"\t, @params = N'@label_column NVARCHAR(255), \r\n",
|
||||||
|
"\t @primary_metric NVARCHAR(40),\r\n",
|
||||||
|
"\t\t\t\t @iterations INT, @task NVARCHAR(40),\r\n",
|
||||||
|
"\t\t\t\t @experiment_name NVARCHAR(32),\r\n",
|
||||||
|
"\t\t\t\t @iteration_timeout_minutes INT,\r\n",
|
||||||
|
"\t\t\t\t @experiment_timeout_minutes INT,\r\n",
|
||||||
|
"\t\t\t\t @n_cross_validations INT,\r\n",
|
||||||
|
"\t\t\t\t @blacklist_models NVARCHAR(MAX),\r\n",
|
||||||
|
"\t\t\t\t @whitelist_models NVARCHAR(MAX),\r\n",
|
||||||
|
"\t\t\t\t @experiment_exit_score FLOAT,\r\n",
|
||||||
|
"\t\t\t\t @sample_weight_column NVARCHAR(255),\r\n",
|
||||||
|
"\t\t\t\t @is_validate_column NVARCHAR(255),\r\n",
|
||||||
|
"\t\t\t\t @time_column_name NVARCHAR(255),\r\n",
|
||||||
|
"\t\t\t\t @tenantid NVARCHAR(255),\r\n",
|
||||||
|
"\t\t\t\t @appid NVARCHAR(255),\r\n",
|
||||||
|
"\t\t\t\t @password NVARCHAR(255),\r\n",
|
||||||
|
"\t\t\t\t @config_file NVARCHAR(255)'\r\n",
|
||||||
|
"\t, @label_column = @label_column\r\n",
|
||||||
|
"\t, @primary_metric = @primary_metric\r\n",
|
||||||
|
"\t, @iterations = @iterations\r\n",
|
||||||
|
"\t, @task = @task\r\n",
|
||||||
|
"\t, @experiment_name = @experiment_name\r\n",
|
||||||
|
"\t, @iteration_timeout_minutes = @iteration_timeout_minutes\r\n",
|
||||||
|
"\t, @experiment_timeout_minutes = @experiment_timeout_minutes\r\n",
|
||||||
|
"\t, @n_cross_validations = @n_cross_validations\r\n",
|
||||||
|
"\t, @blacklist_models = @blacklist_models\r\n",
|
||||||
|
"\t, @whitelist_models = @whitelist_models\r\n",
|
||||||
|
"\t, @experiment_exit_score = @experiment_exit_score\r\n",
|
||||||
|
"\t, @sample_weight_column = @sample_weight_column\r\n",
|
||||||
|
"\t, @is_validate_column = @is_validate_column\r\n",
|
||||||
|
"\t, @time_column_name = @time_column_name\r\n",
|
||||||
|
"\t, @tenantid = @tenantid\r\n",
|
||||||
|
"\t, @appid = @appid\r\n",
|
||||||
|
"\t, @password = @password\r\n",
|
||||||
|
"\t, @config_file = @config_file\r\n",
|
||||||
|
"WITH RESULT SETS ((best_run NVARCHAR(250), experiment_name NVARCHAR(100), fitted_model VARCHAR(MAX), log_file_text NVARCHAR(MAX), workspace NVARCHAR(100)))\r\n",
|
||||||
|
"END"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"-- This procedure returns a list of metrics for each iteration of a training run.\r\n",
|
||||||
|
"SET ANSI_NULLS ON\r\n",
|
||||||
|
"GO\r\n",
|
||||||
|
"SET QUOTED_IDENTIFIER ON\r\n",
|
||||||
|
"GO\r\n",
|
||||||
|
"CREATE OR ALTER PROCEDURE [dbo].[AutoMLGetMetrics]\r\n",
|
||||||
|
" (\r\n",
|
||||||
|
"\t@run_id NVARCHAR(250), -- The RunId\r\n",
|
||||||
|
" @experiment_name NVARCHAR(32)='automl-sql-test', -- This can be used to find the experiment in the Azure Portal.\r\n",
|
||||||
|
" @connection_name NVARCHAR(255)='default' -- The AML connection to use.\r\n",
|
||||||
|
" ) AS\r\n",
|
||||||
|
"BEGIN\r\n",
|
||||||
|
" DECLARE @tenantid NVARCHAR(255)\r\n",
|
||||||
|
" DECLARE @appid NVARCHAR(255)\r\n",
|
||||||
|
" DECLARE @password NVARCHAR(255)\r\n",
|
||||||
|
" DECLARE @config_file NVARCHAR(255)\r\n",
|
||||||
|
"\r\n",
|
||||||
|
"\tSELECT @tenantid=TenantId, @appid=AppId, @password=Password, @config_file=ConfigFile\r\n",
|
||||||
|
"\tFROM aml_connection\r\n",
|
||||||
|
"\tWHERE ConnectionName = @connection_name;\r\n",
|
||||||
|
"\r\n",
|
||||||
|
" EXEC sp_execute_external_script @language = N'Python', @script = N'import pandas as pd\r\n",
|
||||||
|
"import logging \r\n",
|
||||||
|
"import azureml.core \r\n",
|
||||||
|
"import numpy as np\r\n",
|
||||||
|
"from azureml.core.experiment import Experiment \r\n",
|
||||||
|
"from azureml.train.automl.run import AutoMLRun\r\n",
|
||||||
|
"from azureml.core.authentication import ServicePrincipalAuthentication \r\n",
|
||||||
|
"from azureml.core.workspace import Workspace \r\n",
|
||||||
|
"\r\n",
|
||||||
|
"auth = ServicePrincipalAuthentication(tenantid, appid, password) \r\n",
|
||||||
|
" \r\n",
|
||||||
|
"ws = Workspace.from_config(path=config_file, auth=auth) \r\n",
|
||||||
|
" \r\n",
|
||||||
|
"experiment = Experiment(ws, experiment_name) \r\n",
|
||||||
|
"\r\n",
|
||||||
|
"ml_run = AutoMLRun(experiment = experiment, run_id = run_id)\r\n",
|
||||||
|
"\r\n",
|
||||||
|
"children = list(ml_run.get_children())\r\n",
|
||||||
|
"iterationlist = []\r\n",
|
||||||
|
"metricnamelist = []\r\n",
|
||||||
|
"metricvaluelist = []\r\n",
|
||||||
|
"\r\n",
|
||||||
|
"for run in children:\r\n",
|
||||||
|
" properties = run.get_properties()\r\n",
|
||||||
|
" if \"iteration\" in properties:\r\n",
|
||||||
|
" iteration = int(properties[\"iteration\"])\r\n",
|
||||||
|
" for metric_name, metric_value in run.get_metrics().items():\r\n",
|
||||||
|
" if isinstance(metric_value, float):\r\n",
|
||||||
|
" iterationlist.append(iteration)\r\n",
|
||||||
|
" metricnamelist.append(metric_name)\r\n",
|
||||||
|
" metricvaluelist.append(metric_value)\r\n",
|
||||||
|
" \r\n",
|
||||||
|
"metrics = pd.DataFrame({\"iteration\": iterationlist, \"metric_name\": metricnamelist, \"metric_value\": metricvaluelist})\r\n",
|
||||||
|
"'\r\n",
|
||||||
|
" , @output_data_1_name = N'metrics'\r\n",
|
||||||
|
"\t, @params = N'@run_id NVARCHAR(250), \r\n",
|
||||||
|
"\t\t\t\t @experiment_name NVARCHAR(32),\r\n",
|
||||||
|
" \t\t\t\t @tenantid NVARCHAR(255),\r\n",
|
||||||
|
"\t\t\t\t @appid NVARCHAR(255),\r\n",
|
||||||
|
"\t\t\t\t @password NVARCHAR(255),\r\n",
|
||||||
|
"\t\t\t\t @config_file NVARCHAR(255)'\r\n",
|
||||||
|
" , @run_id = @run_id\r\n",
|
||||||
|
"\t, @experiment_name = @experiment_name\r\n",
|
||||||
|
"\t, @tenantid = @tenantid\r\n",
|
||||||
|
"\t, @appid = @appid\r\n",
|
||||||
|
"\t, @password = @password\r\n",
|
||||||
|
"\t, @config_file = @config_file\r\n",
|
||||||
|
"WITH RESULT SETS ((iteration INT, metric_name NVARCHAR(100), metric_value FLOAT))\r\n",
|
||||||
|
"END"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"-- This procedure predicts values based on a model returned by AutoMLTrain and a dataset.\r\n",
|
||||||
|
"-- It returns the dataset with a new column added, which is the predicted value.\r\n",
|
||||||
|
"SET ANSI_NULLS ON\r\n",
|
||||||
|
"GO\r\n",
|
||||||
|
"SET QUOTED_IDENTIFIER ON\r\n",
|
||||||
|
"GO\r\n",
|
||||||
|
"CREATE OR ALTER PROCEDURE [dbo].[AutoMLPredict]\r\n",
|
||||||
|
" (\r\n",
|
||||||
|
" @input_query NVARCHAR(MAX), -- A SQL query returning data to predict on.\r\n",
|
||||||
|
" @model NVARCHAR(MAX), -- A model returned from AutoMLTrain.\r\n",
|
||||||
|
" @label_column NVARCHAR(255)='' -- Optional name of the column from input_query, which should be ignored when predicting\r\n",
|
||||||
|
" ) AS \r\n",
|
||||||
|
"BEGIN \r\n",
|
||||||
|
" \r\n",
|
||||||
|
" EXEC sp_execute_external_script @language = N'Python', @script = N'import pandas as pd \r\n",
|
||||||
|
"import azureml.core \r\n",
|
||||||
|
"import numpy as np \r\n",
|
||||||
|
"from azureml.train.automl import AutoMLConfig \r\n",
|
||||||
|
"import pickle \r\n",
|
||||||
|
"import codecs \r\n",
|
||||||
|
" \r\n",
|
||||||
|
"model_obj = pickle.loads(codecs.decode(model.encode(), \"base64\")) \r\n",
|
||||||
|
" \r\n",
|
||||||
|
"test_data = input_data.copy() \r\n",
|
||||||
|
"\r\n",
|
||||||
|
"if label_column != \"\" and label_column is not None:\r\n",
|
||||||
|
" y_test = test_data.pop(label_column).values \r\n",
|
||||||
|
"X_test = test_data \r\n",
|
||||||
|
" \r\n",
|
||||||
|
"predicted = model_obj.predict(X_test) \r\n",
|
||||||
|
" \r\n",
|
||||||
|
"combined_output = input_data.assign(predicted=predicted)\r\n",
|
||||||
|
" \r\n",
|
||||||
|
"' \r\n",
|
||||||
|
" , @input_data_1 = @input_query \r\n",
|
||||||
|
" , @input_data_1_name = N'input_data' \r\n",
|
||||||
|
" , @output_data_1_name = N'combined_output' \r\n",
|
||||||
|
" , @params = N'@model NVARCHAR(MAX), @label_column NVARCHAR(255)' \r\n",
|
||||||
|
" , @model = @model \r\n",
|
||||||
|
"\t, @label_column = @label_column\r\n",
|
||||||
|
"END"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"authors": [
|
||||||
|
{
|
||||||
|
"name": "jeffshep"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 3.6",
|
||||||
|
"language": "sql",
|
||||||
|
"name": "python36"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"name": "sql",
|
||||||
|
"version": ""
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 2
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
name: auto-ml-subsampling-local
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
|
- azureml-train-automl
|
||||||
|
- azureml-widgets
|
||||||
|
- matplotlib
|
||||||
|
- pandas_ml
|
||||||
@@ -593,7 +593,10 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"fitted_model.named_steps['datatransformer'].get_featurization_summary()"
|
"# 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",
|
||||||
|
"pd.DataFrame.from_records(featurization_summary)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -13,7 +13,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"# Using Databricks as a Compute Target from Azure Machine Learning Pipeline\n",
|
"# Using Databricks as a Compute Target from Azure Machine Learning Pipeline\n",
|
||||||
"To use Databricks as a compute target from [Azure Machine Learning Pipeline](https://docs.microsoft.com/en-us/azure/machine-learning/service/concept-ml-pipelines), a [DatabricksStep](https://docs.microsoft.com/en-us/python/api/azureml-pipeline-steps/azureml.pipeline.steps.databricks_step.databricksstep?view=azure-ml-py) is used. This notebook demonstrates the use of DatabricksStep in Azure Machine Learning Pipeline.\n",
|
"To use Databricks as a compute target from [Azure Machine Learning Pipeline](https://aka.ms/pl-concept), a [DatabricksStep](https://docs.microsoft.com/en-us/python/api/azureml-pipeline-steps/azureml.pipeline.steps.databricks_step.databricksstep?view=azure-ml-py) is used. This notebook demonstrates the use of DatabricksStep in Azure Machine Learning Pipeline.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"The notebook will show:\n",
|
"The notebook will show:\n",
|
||||||
"1. Running an arbitrary Databricks notebook that the customer has in Databricks workspace\n",
|
"1. Running an arbitrary Databricks notebook that the customer has in Databricks workspace\n",
|
||||||
@@ -675,7 +675,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"# Next: ADLA as a Compute Target\n",
|
"# Next: ADLA as a Compute Target\n",
|
||||||
"To use ADLA as a compute target from Azure Machine Learning Pipeline, a AdlaStep is used. This [notebook](./aml-pipelines-use-adla-as-compute-target.ipynb) demonstrates the use of AdlaStep in Azure Machine Learning Pipeline."
|
"To use ADLA as a compute target from Azure Machine Learning Pipeline, a AdlaStep is used. This [notebook](https://aka.ms/pl-adla) demonstrates the use of AdlaStep in Azure Machine Learning Pipeline."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -77,7 +77,7 @@
|
|||||||
"from azureml.core import Workspace\n",
|
"from azureml.core import Workspace\n",
|
||||||
"\n",
|
"\n",
|
||||||
"ws = Workspace.from_config()\n",
|
"ws = Workspace.from_config()\n",
|
||||||
"print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep = '\\n')"
|
"print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep='\\n')"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -108,11 +108,11 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"from azureml.core.model import Model\n",
|
"from azureml.core.model import Model\n",
|
||||||
"\n",
|
"\n",
|
||||||
"model = Model.register(model_path = \"sklearn_regression_model.pkl\",\n",
|
"model = Model.register(model_path=\"sklearn_regression_model.pkl\",\n",
|
||||||
" model_name = \"sklearn_regression_model.pkl\",\n",
|
" model_name=\"sklearn_regression_model.pkl\",\n",
|
||||||
" tags = {'area': \"diabetes\", 'type': \"regression\"},\n",
|
" tags={'area': \"diabetes\", 'type': \"regression\"},\n",
|
||||||
" description = \"Ridge regression model to predict diabetes\",\n",
|
" description=\"Ridge regression model to predict diabetes\",\n",
|
||||||
" workspace = ws)"
|
" workspace=ws)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -177,7 +177,7 @@
|
|||||||
"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",
|
||||||
@@ -215,7 +215,7 @@
|
|||||||
" [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)"
|
||||||
]
|
]
|
||||||
@@ -247,15 +247,38 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"### Model Profiling\n",
|
"### Model Profiling\n",
|
||||||
"\n",
|
"\n",
|
||||||
"you can also take advantage of profiling feature for model\n",
|
"You can also take advantage of the profiling feature to estimate CPU and memory requirements for models.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"```python\n",
|
"```python\n",
|
||||||
"\n",
|
"profile = Model.profile(ws, \"profilename\", [model], inference_config, test_sample)\n",
|
||||||
"profile = model.profile(ws, \"profilename\", [model], inference_config, test_sample)\n",
|
|
||||||
"profile.wait_for_profiling(True)\n",
|
"profile.wait_for_profiling(True)\n",
|
||||||
"profiling_results = profile.get_results()\n",
|
"profiling_results = profile.get_results()\n",
|
||||||
"print(profiling_results)\n",
|
"print(profiling_results)\n",
|
||||||
|
"```"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Model Packaging\n",
|
||||||
"\n",
|
"\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",
|
||||||
"```"
|
"```"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,4 @@
|
|||||||
|
name: model-register-and-deploy
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
@@ -72,7 +72,7 @@
|
|||||||
"from azureml.core import Workspace\n",
|
"from azureml.core import Workspace\n",
|
||||||
"\n",
|
"\n",
|
||||||
"ws = Workspace.from_config()\n",
|
"ws = Workspace.from_config()\n",
|
||||||
"print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep = '\\n')"
|
"print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep='\\n')"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -103,11 +103,11 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"from azureml.core.model import Model\n",
|
"from azureml.core.model import Model\n",
|
||||||
"\n",
|
"\n",
|
||||||
"model = Model.register(model_path = \"sklearn_regression_model.pkl\",\n",
|
"model = Model.register(model_path=\"sklearn_regression_model.pkl\",\n",
|
||||||
" model_name = \"sklearn_regression_model.pkl\",\n",
|
" model_name=\"sklearn_regression_model.pkl\",\n",
|
||||||
" tags = {'area': \"diabetes\", 'type': \"regression\"},\n",
|
" tags={'area': \"diabetes\", 'type': \"regression\"},\n",
|
||||||
" description = \"Ridge regression model to predict diabetes\",\n",
|
" description=\"Ridge regression model to predict diabetes\",\n",
|
||||||
" workspace = ws)"
|
" workspace=ws)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -127,10 +127,10 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"source_directory = \"C:/abc\"\n",
|
"source_directory = \"C:/abc\"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"os.makedirs(source_directory, exist_ok = True)\n",
|
"os.makedirs(source_directory, exist_ok=True)\n",
|
||||||
"os.makedirs(\"C:/abc/x/y\", exist_ok = True)\n",
|
"os.makedirs(\"C:/abc/x/y\", exist_ok=True)\n",
|
||||||
"os.makedirs(\"C:/abc/env\", exist_ok = True)\n",
|
"os.makedirs(\"C:/abc/env\", exist_ok=True)\n",
|
||||||
"os.makedirs(\"C:/abc/dockerstep\", exist_ok = True)"
|
"os.makedirs(\"C:/abc/dockerstep\", exist_ok=True)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -253,7 +253,7 @@
|
|||||||
"from azureml.core.model import InferenceConfig\n",
|
"from azureml.core.model import InferenceConfig\n",
|
||||||
"\n",
|
"\n",
|
||||||
"inference_config = InferenceConfig(source_directory=\"C:/abc\",\n",
|
"inference_config = InferenceConfig(source_directory=\"C:/abc\",\n",
|
||||||
" runtime= \"python\", \n",
|
" runtime=\"python\", \n",
|
||||||
" entry_script=\"x/y/score.py\",\n",
|
" entry_script=\"x/y/score.py\",\n",
|
||||||
" conda_file=\"env/myenv.yml\", \n",
|
" conda_file=\"env/myenv.yml\", \n",
|
||||||
" extra_docker_file_steps=\"dockerstep/customDockerStep.txt\")"
|
" extra_docker_file_steps=\"dockerstep/customDockerStep.txt\")"
|
||||||
@@ -271,15 +271,10 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"NOTE:\n",
|
"NOTE:\n",
|
||||||
"\n",
|
"\n",
|
||||||
"we require docker running with linux container. If you are running Docker for Windows, you need to ensure the Linux Engine is running\n",
|
"The Docker image runs as a Linux container. If you are running Docker for Windows, you need to ensure the Linux Engine is running:\n",
|
||||||
"\n",
|
"\n",
|
||||||
" powershell command to switch to linux engine\n",
|
" # PowerShell command to switch to Linux engine\n",
|
||||||
" & 'C:\\Program Files\\Docker\\Docker\\DockerCli.exe' -SwitchLinuxEngine\n",
|
" & 'C:\\Program Files\\Docker\\Docker\\DockerCli.exe' -SwitchLinuxEngine"
|
||||||
"\n",
|
|
||||||
"and c drive is shared https://docs.docker.com/docker-for-windows/#shared-drives\n",
|
|
||||||
"sometimes you have to reshare c drive as docker \n",
|
|
||||||
"\n",
|
|
||||||
"<img src=\"./dockerSharedDrive.JPG\" align=\"left\"/>"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -295,7 +290,7 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"from azureml.core.webservice import LocalWebservice\n",
|
"from azureml.core.webservice import LocalWebservice\n",
|
||||||
"\n",
|
"\n",
|
||||||
"#this is optional, if not provided we choose random port\n",
|
"# This is optional, if not provided Docker will choose a random unused port.\n",
|
||||||
"deployment_config = LocalWebservice.deploy_configuration(port=6789)\n",
|
"deployment_config = LocalWebservice.deploy_configuration(port=6789)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"local_service = Model.deploy(ws, \"test\", [model], inference_config, deployment_config)\n",
|
"local_service = Model.deploy(ws, \"test\", [model], inference_config, deployment_config)\n",
|
||||||
@@ -427,9 +422,8 @@
|
|||||||
"local_service.reload()\n",
|
"local_service.reload()\n",
|
||||||
"print(\"--------------------------------------------------------------\")\n",
|
"print(\"--------------------------------------------------------------\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# after reload now if you call run this will return updated return message\n",
|
"# After calling reload(), run() will return the updated message.\n",
|
||||||
"\n",
|
"local_service.run(input_data=sample_input)"
|
||||||
"print(local_service.run(input_data=sample_input))"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -442,9 +436,9 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"```python\n",
|
"```python\n",
|
||||||
"\n",
|
"\n",
|
||||||
"local_service.update(models = [SomeOtherModelObject],\n",
|
"local_service.update(models=[SomeOtherModelObject],\n",
|
||||||
" deployment_config = local_config,\n",
|
" deployment_config=local_config,\n",
|
||||||
" inference_config = inference_config)\n",
|
" inference_config=inference_config)\n",
|
||||||
"```"
|
"```"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -468,7 +462,7 @@
|
|||||||
"metadata": {
|
"metadata": {
|
||||||
"authors": [
|
"authors": [
|
||||||
{
|
{
|
||||||
"name": "raymondl"
|
"name": "keriehm"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"kernelspec": {
|
"kernelspec": {
|
||||||
|
|||||||
@@ -68,7 +68,7 @@
|
|||||||
"from azureml.core import Workspace\n",
|
"from azureml.core import Workspace\n",
|
||||||
"\n",
|
"\n",
|
||||||
"ws = Workspace.from_config()\n",
|
"ws = Workspace.from_config()\n",
|
||||||
"print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep = '\\n')"
|
"print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep='\\n')"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -99,11 +99,31 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"from azureml.core.model import Model\n",
|
"from azureml.core.model import Model\n",
|
||||||
"\n",
|
"\n",
|
||||||
"model = Model.register(model_path = \"sklearn_regression_model.pkl\",\n",
|
"model = Model.register(model_path=\"sklearn_regression_model.pkl\",\n",
|
||||||
" model_name = \"sklearn_regression_model.pkl\",\n",
|
" model_name=\"sklearn_regression_model.pkl\",\n",
|
||||||
" tags = {'area': \"diabetes\", 'type': \"regression\"},\n",
|
" tags={'area': \"diabetes\", 'type': \"regression\"},\n",
|
||||||
" description = \"Ridge regression model to predict diabetes\",\n",
|
" description=\"Ridge regression model to predict diabetes\",\n",
|
||||||
" workspace = ws)"
|
" workspace=ws)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Create Environment"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.core.conda_dependencies import CondaDependencies\n",
|
||||||
|
"from azureml.core.environment import Environment\n",
|
||||||
|
"\n",
|
||||||
|
"environment = Environment(\"LocalDeploy\")\n",
|
||||||
|
"environment.python.conda_dependencies = CondaDependencies(\"myenv.yml\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -121,9 +141,8 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"from azureml.core.model import InferenceConfig\n",
|
"from azureml.core.model import InferenceConfig\n",
|
||||||
"\n",
|
"\n",
|
||||||
"inference_config = InferenceConfig(runtime= \"python\", \n",
|
"inference_config = InferenceConfig(entry_script=\"score.py\",\n",
|
||||||
" entry_script=\"score.py\",\n",
|
" environment=environment)"
|
||||||
" conda_file=\"myenv.yml\")"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -138,15 +157,10 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"NOTE:\n",
|
"NOTE:\n",
|
||||||
"\n",
|
"\n",
|
||||||
"we require docker running with linux container. If you are running Docker for Windows, you need to ensure the Linux Engine is running\n",
|
"The Docker image runs as a Linux container. If you are running Docker for Windows, you need to ensure the Linux Engine is running:\n",
|
||||||
"\n",
|
"\n",
|
||||||
" powershell command to switch to linux engine\n",
|
" # PowerShell command to switch to Linux engine\n",
|
||||||
" & 'C:\\Program Files\\Docker\\Docker\\DockerCli.exe' -SwitchLinuxEngine\n",
|
" & 'C:\\Program Files\\Docker\\Docker\\DockerCli.exe' -SwitchLinuxEngine"
|
||||||
"\n",
|
|
||||||
"and c drive is shared https://docs.docker.com/docker-for-windows/#shared-drives\n",
|
|
||||||
"sometimes you have to reshare c drive as docker \n",
|
|
||||||
"\n",
|
|
||||||
"<img src=\"./dockerSharedDrive.JPG\" align=\"left\"/>"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -157,7 +171,7 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"from azureml.core.webservice import LocalWebservice\n",
|
"from azureml.core.webservice import LocalWebservice\n",
|
||||||
"\n",
|
"\n",
|
||||||
"#this is optional, if not provided we choose random port\n",
|
"# This is optional, if not provided Docker will choose a random unused port.\n",
|
||||||
"deployment_config = LocalWebservice.deploy_configuration(port=6789)\n",
|
"deployment_config = LocalWebservice.deploy_configuration(port=6789)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"local_service = Model.deploy(ws, \"test\", [model], inference_config, deployment_config)\n",
|
"local_service = Model.deploy(ws, \"test\", [model], inference_config, deployment_config)\n",
|
||||||
@@ -221,7 +235,7 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"sample_input = bytes(sample_input, encoding='utf-8')\n",
|
"sample_input = bytes(sample_input, encoding='utf-8')\n",
|
||||||
"\n",
|
"\n",
|
||||||
"print(local_service.run(input_data=sample_input))"
|
"local_service.run(input_data=sample_input)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -282,9 +296,8 @@
|
|||||||
"local_service.reload()\n",
|
"local_service.reload()\n",
|
||||||
"print(\"--------------------------------------------------------------\")\n",
|
"print(\"--------------------------------------------------------------\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# after reload now if you call run this will return updated return message\n",
|
"# After calling reload(), run() will return the updated message.\n",
|
||||||
"\n",
|
"local_service.run(input_data=sample_input)"
|
||||||
"print(local_service.run(input_data=sample_input))"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -296,10 +309,9 @@
|
|||||||
"If you want to change your model(s), Conda dependencies, or deployment configuration, call `update()` to rebuild the Docker image.\n",
|
"If you want to change your model(s), Conda dependencies, or deployment configuration, call `update()` to rebuild the Docker image.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"```python\n",
|
"```python\n",
|
||||||
"\n",
|
"local_service.update(models=[SomeOtherModelObject],\n",
|
||||||
"local_service.update(models = [SomeOtherModelObject],\n",
|
" inference_config=inference_config,\n",
|
||||||
" deployment_config = local_config,\n",
|
" deployment_config=local_config)\n",
|
||||||
" inference_config = inference_config)\n",
|
|
||||||
"```"
|
"```"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -323,7 +335,7 @@
|
|||||||
"metadata": {
|
"metadata": {
|
||||||
"authors": [
|
"authors": [
|
||||||
{
|
{
|
||||||
"name": "raymondl"
|
"name": "keriehm"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"kernelspec": {
|
"kernelspec": {
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ Easily create and train a model using various deep neural networks (DNNs) as a f
|
|||||||
To learn more about the azureml-accel-model classes, see the section [Model Classes](#model-classes) below or the [Azure ML Accel Models SDK documentation](https://docs.microsoft.com/en-us/python/api/azureml-accel-models/azureml.accel?view=azure-ml-py).
|
To learn more about the azureml-accel-model classes, see the section [Model Classes](#model-classes) below or the [Azure ML Accel Models SDK documentation](https://docs.microsoft.com/en-us/python/api/azureml-accel-models/azureml.accel?view=azure-ml-py).
|
||||||
|
|
||||||
### Step 1: Create an Azure ML workspace
|
### Step 1: Create an Azure ML workspace
|
||||||
Follow [these instructions](https://docs.microsoft.com/en-us/azure/machine-learning/service/quickstart-create-workspace-with-python) to install the Azure ML SDK on your local machine, create an Azure ML workspace, and set up your notebook environment, which is required for the next step.
|
Follow [these instructions](https://docs.microsoft.com/en-us/azure/machine-learning/service/setup-create-workspace) to install the Azure ML SDK on your local machine, create an Azure ML workspace, and set up your notebook environment, which is required for the next step.
|
||||||
|
|
||||||
### Step 2: Check your FPGA quota
|
### Step 2: Check your FPGA quota
|
||||||
Use the Azure CLI to check whether you have quota.
|
Use the Azure CLI to check whether you have quota.
|
||||||
|
|||||||
@@ -1,492 +1,497 @@
|
|||||||
{
|
{
|
||||||
"cells": [
|
"cells": [
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
""
|
||||||
"\n",
|
]
|
||||||
"Licensed under the MIT License."
|
},
|
||||||
]
|
{
|
||||||
},
|
"cell_type": "markdown",
|
||||||
{
|
"metadata": {},
|
||||||
"cell_type": "markdown",
|
"source": [
|
||||||
"metadata": {},
|
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
||||||
"source": [
|
"\n",
|
||||||
"# Azure ML Hardware Accelerated Object Detection"
|
"Licensed under the MIT License."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"This tutorial will show you how to deploy an object detection service based on the SSD-VGG model in just a few minutes using the Azure Machine Learning Accelerated AI service.\n",
|
"# Azure ML Hardware Accelerated Object Detection"
|
||||||
"\n",
|
]
|
||||||
"We will use the SSD-VGG model accelerated on an FPGA. Our Accelerated Models Service handles translating deep neural networks (DNN) into an FPGA program.\n",
|
},
|
||||||
"\n",
|
{
|
||||||
"The steps in this notebook are: \n",
|
"cell_type": "markdown",
|
||||||
"1. [Setup Environment](#set-up-environment)\n",
|
"metadata": {},
|
||||||
"* [Construct Model](#construct-model)\n",
|
"source": [
|
||||||
" * Image Preprocessing\n",
|
"This tutorial will show you how to deploy an object detection service based on the SSD-VGG model in just a few minutes using the Azure Machine Learning Accelerated AI service.\n",
|
||||||
" * Featurizer\n",
|
"\n",
|
||||||
" * Save Model\n",
|
"We will use the SSD-VGG model accelerated on an FPGA. Our Accelerated Models Service handles translating deep neural networks (DNN) into an FPGA program.\n",
|
||||||
" * Save input and output tensor names\n",
|
"\n",
|
||||||
"* [Create Image](#create-image)\n",
|
"The steps in this notebook are: \n",
|
||||||
"* [Deploy Image](#deploy-image)\n",
|
"1. [Setup Environment](#set-up-environment)\n",
|
||||||
"* [Test the Service](#test-service)\n",
|
"* [Construct Model](#construct-model)\n",
|
||||||
" * Create Client\n",
|
" * Image Preprocessing\n",
|
||||||
" * Serve the model\n",
|
" * Featurizer\n",
|
||||||
"* [Cleanup](#cleanup)"
|
" * Save Model\n",
|
||||||
]
|
" * Save input and output tensor names\n",
|
||||||
},
|
"* [Create Image](#create-image)\n",
|
||||||
{
|
"* [Deploy Image](#deploy-image)\n",
|
||||||
"cell_type": "markdown",
|
"* [Test the Service](#test-service)\n",
|
||||||
"metadata": {},
|
" * Create Client\n",
|
||||||
"source": [
|
" * Serve the model\n",
|
||||||
"<a id=\"set-up-environment\"></a>\n",
|
"* [Cleanup](#cleanup)"
|
||||||
"## 1. Set up Environment\n",
|
]
|
||||||
"### 1.a. Imports"
|
},
|
||||||
]
|
{
|
||||||
},
|
"cell_type": "markdown",
|
||||||
{
|
"metadata": {},
|
||||||
"cell_type": "code",
|
"source": [
|
||||||
"execution_count": null,
|
"<a id=\"set-up-environment\"></a>\n",
|
||||||
"metadata": {},
|
"## 1. Set up Environment\n",
|
||||||
"outputs": [],
|
"### 1.a. Imports"
|
||||||
"source": [
|
]
|
||||||
"import os\n",
|
},
|
||||||
"import tensorflow as tf"
|
{
|
||||||
]
|
"cell_type": "code",
|
||||||
},
|
"execution_count": null,
|
||||||
{
|
"metadata": {},
|
||||||
"cell_type": "markdown",
|
"outputs": [],
|
||||||
"metadata": {},
|
"source": [
|
||||||
"source": [
|
"import os\n",
|
||||||
"### 1.b. Retrieve Workspace\n",
|
"import tensorflow as tf"
|
||||||
"If you haven't created a Workspace, please follow [this notebook](\"../../../configuration.ipynb\") to do so. If you have, run the codeblock below to retrieve it. "
|
]
|
||||||
]
|
},
|
||||||
},
|
{
|
||||||
{
|
"cell_type": "markdown",
|
||||||
"cell_type": "code",
|
"metadata": {},
|
||||||
"execution_count": null,
|
"source": [
|
||||||
"metadata": {},
|
"### 1.b. Retrieve Workspace\n",
|
||||||
"outputs": [],
|
"If you haven't created a Workspace, please follow [this notebook](\"../../../configuration.ipynb\") to do so. If you have, run the codeblock below to retrieve it. "
|
||||||
"source": [
|
]
|
||||||
"from azureml.core import Workspace\n",
|
},
|
||||||
"\n",
|
{
|
||||||
"ws = Workspace.from_config()\n",
|
"cell_type": "code",
|
||||||
"print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep = '\\n')"
|
"execution_count": null,
|
||||||
]
|
"metadata": {},
|
||||||
},
|
"outputs": [],
|
||||||
{
|
"source": [
|
||||||
"cell_type": "markdown",
|
"from azureml.core import Workspace\n",
|
||||||
"metadata": {},
|
"\n",
|
||||||
"source": [
|
"ws = Workspace.from_config()\n",
|
||||||
"<a id=\"construct-model\"></a>\n",
|
"print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep = '\\n')"
|
||||||
"## 2. Construct model\n",
|
]
|
||||||
"### 2.a. Image preprocessing\n",
|
},
|
||||||
"We'd like our service to accept JPEG images as input. However the input to SSD-VGG is a float tensor of shape \\[1, 300, 300, 3\\]. The first dimension is batch, then height, width, and channels (i.e. NHWC). To bridge this gap, we need code that decodes JPEG images and resizes them appropriately for input to SSD-VGG. The Accelerated AI service can execute TensorFlow graphs as part of the service and we'll use that ability to do the image preprocessing. This code defines a TensorFlow graph that preprocesses an array of JPEG images (as TensorFlow strings) and produces a tensor that is ready to be featurized by SSD-VGG.\n",
|
{
|
||||||
"\n",
|
"cell_type": "markdown",
|
||||||
"**Note:** Expect to see TF deprecation warnings until we port our SDK over to use Tensorflow 2.0."
|
"metadata": {},
|
||||||
]
|
"source": [
|
||||||
},
|
"<a id=\"construct-model\"></a>\n",
|
||||||
{
|
"## 2. Construct model\n",
|
||||||
"cell_type": "code",
|
"### 2.a. Image preprocessing\n",
|
||||||
"execution_count": null,
|
"We'd like our service to accept JPEG images as input. However the input to SSD-VGG is a float tensor of shape \\[1, 300, 300, 3\\]. The first dimension is batch, then height, width, and channels (i.e. NHWC). To bridge this gap, we need code that decodes JPEG images and resizes them appropriately for input to SSD-VGG. The Accelerated AI service can execute TensorFlow graphs as part of the service and we'll use that ability to do the image preprocessing. This code defines a TensorFlow graph that preprocesses an array of JPEG images (as TensorFlow strings) and produces a tensor that is ready to be featurized by SSD-VGG.\n",
|
||||||
"metadata": {},
|
"\n",
|
||||||
"outputs": [],
|
"**Note:** Expect to see TF deprecation warnings until we port our SDK over to use Tensorflow 2.0."
|
||||||
"source": [
|
]
|
||||||
"# Input images as a two-dimensional tensor containing an arbitrary number of images represented a strings\n",
|
},
|
||||||
"import azureml.accel.models.utils as utils\n",
|
{
|
||||||
"tf.reset_default_graph()\n",
|
"cell_type": "code",
|
||||||
"\n",
|
"execution_count": null,
|
||||||
"in_images = tf.placeholder(tf.string)\n",
|
"metadata": {},
|
||||||
"image_tensors = utils.preprocess_array(in_images, output_width=300, output_height=300, preserve_aspect_ratio=False)\n",
|
"outputs": [],
|
||||||
"print(image_tensors.shape)"
|
"source": [
|
||||||
]
|
"# Input images as a two-dimensional tensor containing an arbitrary number of images represented a strings\n",
|
||||||
},
|
"import azureml.accel.models.utils as utils\n",
|
||||||
{
|
"tf.reset_default_graph()\n",
|
||||||
"cell_type": "markdown",
|
"\n",
|
||||||
"metadata": {},
|
"in_images = tf.placeholder(tf.string)\n",
|
||||||
"source": [
|
"image_tensors = utils.preprocess_array(in_images, output_width=300, output_height=300, preserve_aspect_ratio=False)\n",
|
||||||
"### 2.b. Featurizer\n",
|
"print(image_tensors.shape)"
|
||||||
"The SSD-VGG model is different from our other models in that it generates 12 tensor outputs. These corresponds to x,y displacements of the anchor boxes and the detection confidence (for 21 classes). Because these outputs are not convenient to work with, we will later use a pre-defined post-processing utility to transform the outputs into a simplified list of bounding boxes with their respective class and confidence.\n",
|
]
|
||||||
"\n",
|
},
|
||||||
"For more information about the output tensors, take this example: the output tensor 'ssd_300_vgg/block4_box/Reshape_1:0' has a shape of [None, 37, 37, 4, 21]. This gives the pre-softmax confidence for 4 anchor boxes situated at each site of a 37 x 37 grid imposed on the image, one confidence score for each of the 21 classes. The first dimension is the batch dimension. Likewise, 'ssd_300_vgg/block4_box/Reshape:0' has shape [None, 37, 37, 4, 4] and encodes the (cx, cy) center shift and rescaling (sw, sh) relative to each anchor box. Refer to the [SSD-VGG paper](https://arxiv.org/abs/1512.02325) to understand how these are computed. The other 10 tensors are defined similarly."
|
{
|
||||||
]
|
"cell_type": "markdown",
|
||||||
},
|
"metadata": {},
|
||||||
{
|
"source": [
|
||||||
"cell_type": "code",
|
"### 2.b. Featurizer\n",
|
||||||
"execution_count": null,
|
"The SSD-VGG model is different from our other models in that it generates 12 tensor outputs. These corresponds to x,y displacements of the anchor boxes and the detection confidence (for 21 classes). Because these outputs are not convenient to work with, we will later use a pre-defined post-processing utility to transform the outputs into a simplified list of bounding boxes with their respective class and confidence.\n",
|
||||||
"metadata": {},
|
"\n",
|
||||||
"outputs": [],
|
"For more information about the output tensors, take this example: the output tensor 'ssd_300_vgg/block4_box/Reshape_1:0' has a shape of [None, 37, 37, 4, 21]. This gives the pre-softmax confidence for 4 anchor boxes situated at each site of a 37 x 37 grid imposed on the image, one confidence score for each of the 21 classes. The first dimension is the batch dimension. Likewise, 'ssd_300_vgg/block4_box/Reshape:0' has shape [None, 37, 37, 4, 4] and encodes the (cx, cy) center shift and rescaling (sw, sh) relative to each anchor box. Refer to the [SSD-VGG paper](https://arxiv.org/abs/1512.02325) to understand how these are computed. The other 10 tensors are defined similarly."
|
||||||
"source": [
|
]
|
||||||
"from azureml.accel.models import SsdVgg\n",
|
},
|
||||||
"\n",
|
{
|
||||||
"saved_model_dir = os.path.join(os.path.expanduser('~'), 'models')\n",
|
"cell_type": "code",
|
||||||
"model_graph = SsdVgg(saved_model_dir, is_frozen = True)\n",
|
"execution_count": null,
|
||||||
"\n",
|
"metadata": {},
|
||||||
"print('SSD-VGG Input Tensors:')\n",
|
"outputs": [],
|
||||||
"for idx, input_name in enumerate(model_graph.input_tensor_list):\n",
|
"source": [
|
||||||
" print('{}, {}'.format(input_name, model_graph.get_input_dims(idx)))\n",
|
"from azureml.accel.models import SsdVgg\n",
|
||||||
" \n",
|
"\n",
|
||||||
"print('SSD-VGG Output Tensors:')\n",
|
"saved_model_dir = os.path.join(os.path.expanduser('~'), 'models')\n",
|
||||||
"for idx, output_name in enumerate(model_graph.output_tensor_list):\n",
|
"model_graph = SsdVgg(saved_model_dir, is_frozen = True)\n",
|
||||||
" print('{}, {}'.format(output_name, model_graph.get_output_dims(idx)))\n",
|
"\n",
|
||||||
"\n",
|
"print('SSD-VGG Input Tensors:')\n",
|
||||||
"ssd_outputs = model_graph.import_graph_def(image_tensors, is_training=False)"
|
"for idx, input_name in enumerate(model_graph.input_tensor_list):\n",
|
||||||
]
|
" print('{}, {}'.format(input_name, model_graph.get_input_dims(idx)))\n",
|
||||||
},
|
" \n",
|
||||||
{
|
"print('SSD-VGG Output Tensors:')\n",
|
||||||
"cell_type": "markdown",
|
"for idx, output_name in enumerate(model_graph.output_tensor_list):\n",
|
||||||
"metadata": {},
|
" print('{}, {}'.format(output_name, model_graph.get_output_dims(idx)))\n",
|
||||||
"source": [
|
"\n",
|
||||||
"### 2.c. Save Model\n",
|
"ssd_outputs = model_graph.import_graph_def(image_tensors, is_training=False)"
|
||||||
"Now that we loaded both parts of the tensorflow graph (preprocessor and SSD-VGG featurizer), we can save the graph and associated variables to a directory which we can register as an Azure ML Model."
|
]
|
||||||
]
|
},
|
||||||
},
|
{
|
||||||
{
|
"cell_type": "markdown",
|
||||||
"cell_type": "code",
|
"metadata": {},
|
||||||
"execution_count": null,
|
"source": [
|
||||||
"metadata": {},
|
"### 2.c. Save Model\n",
|
||||||
"outputs": [],
|
"Now that we loaded both parts of the tensorflow graph (preprocessor and SSD-VGG featurizer), we can save the graph and associated variables to a directory which we can register as an Azure ML Model."
|
||||||
"source": [
|
]
|
||||||
"model_name = \"ssdvgg\"\n",
|
},
|
||||||
"model_save_path = os.path.join(saved_model_dir, model_name, \"saved_model\")\n",
|
{
|
||||||
"print(\"Saving model in {}\".format(model_save_path))\n",
|
"cell_type": "code",
|
||||||
"\n",
|
"execution_count": null,
|
||||||
"output_map = {}\n",
|
"metadata": {},
|
||||||
"for i, output in enumerate(ssd_outputs):\n",
|
"outputs": [],
|
||||||
" output_map['out_{}'.format(i)] = output\n",
|
"source": [
|
||||||
"\n",
|
"model_name = \"ssdvgg\"\n",
|
||||||
"with tf.Session() as sess:\n",
|
"model_save_path = os.path.join(saved_model_dir, model_name, \"saved_model\")\n",
|
||||||
" model_graph.restore_weights(sess)\n",
|
"print(\"Saving model in {}\".format(model_save_path))\n",
|
||||||
" tf.saved_model.simple_save(sess, \n",
|
"\n",
|
||||||
" model_save_path, \n",
|
"output_map = {}\n",
|
||||||
" inputs={'images': in_images}, \n",
|
"for i, output in enumerate(ssd_outputs):\n",
|
||||||
" outputs=output_map)"
|
" output_map['out_{}'.format(i)] = output\n",
|
||||||
]
|
"\n",
|
||||||
},
|
"with tf.Session() as sess:\n",
|
||||||
{
|
" model_graph.restore_weights(sess)\n",
|
||||||
"cell_type": "markdown",
|
" tf.saved_model.simple_save(sess, \n",
|
||||||
"metadata": {},
|
" model_save_path, \n",
|
||||||
"source": [
|
" inputs={'images': in_images}, \n",
|
||||||
"### 2.d. Important! Save names of input and output tensors\n",
|
" outputs=output_map)"
|
||||||
"\n",
|
]
|
||||||
"These input and output tensors that were created during the preprocessing and classifier steps are also going to be used when **converting the model** to an Accelerated Model that can run on FPGA's and for **making an inferencing request**. It is very important to save this information!"
|
},
|
||||||
]
|
{
|
||||||
},
|
"cell_type": "markdown",
|
||||||
{
|
"metadata": {},
|
||||||
"cell_type": "code",
|
"source": [
|
||||||
"execution_count": null,
|
"### 2.d. Important! Save names of input and output tensors\n",
|
||||||
"metadata": {
|
"\n",
|
||||||
"tags": [
|
"These input and output tensors that were created during the preprocessing and classifier steps are also going to be used when **converting the model** to an Accelerated Model that can run on FPGA's and for **making an inferencing request**. It is very important to save this information!"
|
||||||
"register model from file"
|
]
|
||||||
]
|
},
|
||||||
},
|
{
|
||||||
"outputs": [],
|
"cell_type": "code",
|
||||||
"source": [
|
"execution_count": null,
|
||||||
"input_tensors = in_images.name\n",
|
"metadata": {
|
||||||
"# We will use the list of output tensors during inferencing\n",
|
"tags": [
|
||||||
"output_tensors = [output.name for output in ssd_outputs]\n",
|
"register model from file"
|
||||||
"# However, for multiple output tensors, our AccelOnnxConverter will \n",
|
]
|
||||||
"# accept comma-delimited strings (lists will cause error)\n",
|
},
|
||||||
"output_tensors_str = \",\".join(output_tensors)\n",
|
"outputs": [],
|
||||||
"\n",
|
"source": [
|
||||||
"print(input_tensors)\n",
|
"input_tensors = in_images.name\n",
|
||||||
"print(output_tensors)"
|
"# We will use the list of output tensors during inferencing\n",
|
||||||
]
|
"output_tensors = [output.name for output in ssd_outputs]\n",
|
||||||
},
|
"# However, for multiple output tensors, our AccelOnnxConverter will \n",
|
||||||
{
|
"# accept comma-delimited strings (lists will cause error)\n",
|
||||||
"cell_type": "markdown",
|
"output_tensors_str = \",\".join(output_tensors)\n",
|
||||||
"metadata": {},
|
"\n",
|
||||||
"source": [
|
"print(input_tensors)\n",
|
||||||
"<a id=\"create-image\"></a>\n",
|
"print(output_tensors)"
|
||||||
"## 3. Create AccelContainerImage\n",
|
]
|
||||||
"Below we will execute all the same steps as in the [Quickstart](./accelerated-models-quickstart.ipynb#create-image) to package the model we have saved locally into an accelerated Docker image saved in our workspace. To complete all the steps, it may take a few minutes. For more details on each step, check out the [Quickstart section on model registration](./accelerated-models-quickstart.ipynb#register-model)."
|
},
|
||||||
]
|
{
|
||||||
},
|
"cell_type": "markdown",
|
||||||
{
|
"metadata": {},
|
||||||
"cell_type": "code",
|
"source": [
|
||||||
"execution_count": null,
|
"<a id=\"create-image\"></a>\n",
|
||||||
"metadata": {},
|
"## 3. Create AccelContainerImage\n",
|
||||||
"outputs": [],
|
"Below we will execute all the same steps as in the [Quickstart](./accelerated-models-quickstart.ipynb#create-image) to package the model we have saved locally into an accelerated Docker image saved in our workspace. To complete all the steps, it may take a few minutes. For more details on each step, check out the [Quickstart section on model registration](./accelerated-models-quickstart.ipynb#register-model)."
|
||||||
"source": [
|
]
|
||||||
"from azureml.core import Workspace\n",
|
},
|
||||||
"from azureml.core.model import Model\n",
|
{
|
||||||
"from azureml.core.image import Image\n",
|
"cell_type": "code",
|
||||||
"from azureml.accel import AccelOnnxConverter\n",
|
"execution_count": null,
|
||||||
"from azureml.accel import AccelContainerImage\n",
|
"metadata": {},
|
||||||
"\n",
|
"outputs": [],
|
||||||
"# Retrieve workspace\n",
|
"source": [
|
||||||
"ws = Workspace.from_config()\n",
|
"from azureml.core import Workspace\n",
|
||||||
"print(\"Successfully retrieved workspace:\", ws.name, ws.resource_group, ws.location, ws.subscription_id, '\\n')\n",
|
"from azureml.core.model import Model\n",
|
||||||
"\n",
|
"from azureml.core.image import Image\n",
|
||||||
"# Register model\n",
|
"from azureml.accel import AccelOnnxConverter\n",
|
||||||
"registered_model = Model.register(workspace = ws,\n",
|
"from azureml.accel import AccelContainerImage\n",
|
||||||
" model_path = model_save_path,\n",
|
"\n",
|
||||||
" model_name = model_name)\n",
|
"# Retrieve workspace\n",
|
||||||
"print(\"Successfully registered: \", registered_model.name, registered_model.description, registered_model.version, '\\n', sep = '\\t')\n",
|
"ws = Workspace.from_config()\n",
|
||||||
"\n",
|
"print(\"Successfully retrieved workspace:\", ws.name, ws.resource_group, ws.location, ws.subscription_id, '\\n')\n",
|
||||||
"# Convert model\n",
|
"\n",
|
||||||
"convert_request = AccelOnnxConverter.convert_tf_model(ws, registered_model, input_tensors, output_tensors_str)\n",
|
"# Register model\n",
|
||||||
"# If it fails, you can run wait_for_completion again with show_output=True.\n",
|
"registered_model = Model.register(workspace = ws,\n",
|
||||||
"convert_request.wait_for_completion(show_output=False)\n",
|
" model_path = model_save_path,\n",
|
||||||
"converted_model = convert_request.result\n",
|
" model_name = model_name)\n",
|
||||||
"print(\"\\nSuccessfully converted: \", converted_model.name, converted_model.url, converted_model.version, \n",
|
"print(\"Successfully registered: \", registered_model.name, registered_model.description, registered_model.version, '\\n', sep = '\\t')\n",
|
||||||
" converted_model.id, converted_model.created_time, '\\n')\n",
|
"\n",
|
||||||
"\n",
|
"# Convert model\n",
|
||||||
"# Package into AccelContainerImage\n",
|
"convert_request = AccelOnnxConverter.convert_tf_model(ws, registered_model, input_tensors, output_tensors_str)\n",
|
||||||
"image_config = AccelContainerImage.image_configuration()\n",
|
"if convert_request.wait_for_completion(show_output = False):\n",
|
||||||
"# Image name must be lowercase\n",
|
" # If the above call succeeded, get the converted model\n",
|
||||||
"image_name = \"{}-image\".format(model_name)\n",
|
" converted_model = convert_request.result\n",
|
||||||
"image = Image.create(name = image_name,\n",
|
" print(\"\\nSuccessfully converted: \", converted_model.name, converted_model.url, converted_model.version, \n",
|
||||||
" models = [converted_model],\n",
|
" converted_model.id, converted_model.created_time, '\\n')\n",
|
||||||
" image_config = image_config, \n",
|
"else:\n",
|
||||||
" workspace = ws)\n",
|
" print(\"Model conversion failed. Showing output.\")\n",
|
||||||
"image.wait_for_creation()\n",
|
" convert_request.wait_for_completion(show_output = True)\n",
|
||||||
"print(\"Created AccelContainerImage: {} {} {}\\n\".format(image.name, image.creation_state, image.image_location))"
|
"\n",
|
||||||
]
|
"# Package into AccelContainerImage\n",
|
||||||
},
|
"image_config = AccelContainerImage.image_configuration()\n",
|
||||||
{
|
"# Image name must be lowercase\n",
|
||||||
"cell_type": "markdown",
|
"image_name = \"{}-image\".format(model_name)\n",
|
||||||
"metadata": {},
|
"image = Image.create(name = image_name,\n",
|
||||||
"source": [
|
" models = [converted_model],\n",
|
||||||
"<a id=\"deploy-image\"></a>\n",
|
" image_config = image_config, \n",
|
||||||
"## 4. Deploy image\n",
|
" workspace = ws)\n",
|
||||||
"Once you have an Azure ML Accelerated Image in your Workspace, you can deploy it to two destinations, to a Databox Edge machine or to an AKS cluster. \n",
|
"image.wait_for_creation()\n",
|
||||||
"\n",
|
"print(\"Created AccelContainerImage: {} {} {}\\n\".format(image.name, image.creation_state, image.image_location))"
|
||||||
"### 4.a. Deploy to Databox Edge Machine using IoT Hub\n",
|
]
|
||||||
"See the sample [here](https://github.com/Azure-Samples/aml-real-time-ai/) for using the Azure IoT CLI extension for deploying your Docker image to your Databox Edge Machine.\n",
|
},
|
||||||
"\n",
|
{
|
||||||
"### 4.b. Deploy to AKS Cluster\n",
|
"cell_type": "markdown",
|
||||||
"Same as in the [Quickstart section on image deployment](./accelerated-models-quickstart.ipynb#deploy-image), we are going to create an AKS cluster with FPGA-enabled machines, then deploy our service to it.\n",
|
"metadata": {},
|
||||||
"#### Create AKS ComputeTarget"
|
"source": [
|
||||||
]
|
"<a id=\"deploy-image\"></a>\n",
|
||||||
},
|
"## 4. Deploy image\n",
|
||||||
{
|
"Once you have an Azure ML Accelerated Image in your Workspace, you can deploy it to two destinations, to a Databox Edge machine or to an AKS cluster. \n",
|
||||||
"cell_type": "code",
|
"\n",
|
||||||
"execution_count": null,
|
"### 4.a. Deploy to Databox Edge Machine using IoT Hub\n",
|
||||||
"metadata": {},
|
"See the sample [here](https://github.com/Azure-Samples/aml-real-time-ai/) for using the Azure IoT CLI extension for deploying your Docker image to your Databox Edge Machine.\n",
|
||||||
"outputs": [],
|
"\n",
|
||||||
"source": [
|
"### 4.b. Deploy to AKS Cluster\n",
|
||||||
"from azureml.core.compute import AksCompute, ComputeTarget\n",
|
"Same as in the [Quickstart section on image deployment](./accelerated-models-quickstart.ipynb#deploy-image), we are going to create an AKS cluster with FPGA-enabled machines, then deploy our service to it.\n",
|
||||||
"\n",
|
"#### Create AKS ComputeTarget"
|
||||||
"# Uses the specific FPGA enabled VM (sku: Standard_PB6s)\n",
|
]
|
||||||
"# Standard_PB6s are available in: eastus, westus2, westeurope, southeastasia\n",
|
},
|
||||||
"prov_config = AksCompute.provisioning_configuration(vm_size = \"Standard_PB6s\",\n",
|
{
|
||||||
" agent_count = 1, \n",
|
"cell_type": "code",
|
||||||
" location = \"eastus\")\n",
|
"execution_count": null,
|
||||||
"\n",
|
"metadata": {},
|
||||||
"aks_name = 'aks-pb6-obj'\n",
|
"outputs": [],
|
||||||
"# Create the cluster\n",
|
"source": [
|
||||||
"aks_target = ComputeTarget.create(workspace = ws, \n",
|
"from azureml.core.compute import AksCompute, ComputeTarget\n",
|
||||||
" name = aks_name, \n",
|
"\n",
|
||||||
" provisioning_configuration = prov_config)"
|
"# Uses the specific FPGA enabled VM (sku: Standard_PB6s)\n",
|
||||||
]
|
"# Standard_PB6s are available in: eastus, westus2, westeurope, southeastasia\n",
|
||||||
},
|
"prov_config = AksCompute.provisioning_configuration(vm_size = \"Standard_PB6s\",\n",
|
||||||
{
|
" agent_count = 1, \n",
|
||||||
"cell_type": "markdown",
|
" location = \"eastus\")\n",
|
||||||
"metadata": {},
|
"\n",
|
||||||
"source": [
|
"aks_name = 'aks-pb6-obj'\n",
|
||||||
"Provisioning an AKS cluster might take awhile (15 or so minutes), and we want to wait until it's successfully provisioned before we can deploy a service to it. If you interrupt this cell, provisioning of the cluster will continue. You can re-run it or check the status in your Workspace under Compute."
|
"# Create the cluster\n",
|
||||||
]
|
"aks_target = ComputeTarget.create(workspace = ws, \n",
|
||||||
},
|
" name = aks_name, \n",
|
||||||
{
|
" provisioning_configuration = prov_config)"
|
||||||
"cell_type": "code",
|
]
|
||||||
"execution_count": null,
|
},
|
||||||
"metadata": {},
|
{
|
||||||
"outputs": [],
|
"cell_type": "markdown",
|
||||||
"source": [
|
"metadata": {},
|
||||||
"aks_target.wait_for_completion(show_output = True)\n",
|
"source": [
|
||||||
"print(aks_target.provisioning_state)\n",
|
"Provisioning an AKS cluster might take awhile (15 or so minutes), and we want to wait until it's successfully provisioned before we can deploy a service to it. If you interrupt this cell, provisioning of the cluster will continue. You can re-run it or check the status in your Workspace under Compute."
|
||||||
"print(aks_target.provisioning_errors)"
|
]
|
||||||
]
|
},
|
||||||
},
|
{
|
||||||
{
|
"cell_type": "code",
|
||||||
"cell_type": "markdown",
|
"execution_count": null,
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"outputs": [],
|
||||||
"#### Deploy AccelContainerImage to AKS ComputeTarget"
|
"source": [
|
||||||
]
|
"%%time\n",
|
||||||
},
|
"aks_target.wait_for_completion(show_output = True)\n",
|
||||||
{
|
"print(aks_target.provisioning_state)\n",
|
||||||
"cell_type": "code",
|
"print(aks_target.provisioning_errors)"
|
||||||
"execution_count": null,
|
]
|
||||||
"metadata": {},
|
},
|
||||||
"outputs": [],
|
{
|
||||||
"source": [
|
"cell_type": "markdown",
|
||||||
"from azureml.core.webservice import Webservice, AksWebservice\n",
|
"metadata": {},
|
||||||
"\n",
|
"source": [
|
||||||
"# Set the web service configuration (for creating a test service, we don't want autoscale enabled)\n",
|
"#### Deploy AccelContainerImage to AKS ComputeTarget"
|
||||||
"# Authentication is enabled by default, but for testing we specify False\n",
|
]
|
||||||
"aks_config = AksWebservice.deploy_configuration(autoscale_enabled=False,\n",
|
},
|
||||||
" num_replicas=1,\n",
|
{
|
||||||
" auth_enabled = False)\n",
|
"cell_type": "code",
|
||||||
"\n",
|
"execution_count": null,
|
||||||
"aks_service_name ='my-aks-service'\n",
|
"metadata": {},
|
||||||
"\n",
|
"outputs": [],
|
||||||
"aks_service = Webservice.deploy_from_image(workspace = ws,\n",
|
"source": [
|
||||||
" name = aks_service_name,\n",
|
"%%time\n",
|
||||||
" image = image,\n",
|
"from azureml.core.webservice import Webservice, AksWebservice\n",
|
||||||
" deployment_config = aks_config,\n",
|
"\n",
|
||||||
" deployment_target = aks_target)\n",
|
"# Set the web service configuration (for creating a test service, we don't want autoscale enabled)\n",
|
||||||
"aks_service.wait_for_deployment(show_output = True)"
|
"# Authentication is enabled by default, but for testing we specify False\n",
|
||||||
]
|
"aks_config = AksWebservice.deploy_configuration(autoscale_enabled=False,\n",
|
||||||
},
|
" num_replicas=1,\n",
|
||||||
{
|
" auth_enabled = False)\n",
|
||||||
"cell_type": "markdown",
|
"\n",
|
||||||
"metadata": {},
|
"aks_service_name ='my-aks-service'\n",
|
||||||
"source": [
|
"\n",
|
||||||
"<a id=\"test-service\"></a>\n",
|
"aks_service = Webservice.deploy_from_image(workspace = ws,\n",
|
||||||
"## 5. Test the service\n",
|
" name = aks_service_name,\n",
|
||||||
"<a id=\"create-client\"></a>\n",
|
" image = image,\n",
|
||||||
"### 5.a. Create Client\n",
|
" deployment_config = aks_config,\n",
|
||||||
"The image supports gRPC and the TensorFlow Serving \"predict\" API. We have a client that can call into the docker image to get predictions. \n",
|
" deployment_target = aks_target)\n",
|
||||||
"\n",
|
"aks_service.wait_for_deployment(show_output = True)"
|
||||||
"**Note:** If you chose to use auth_enabled=True when creating your AksWebservice.deploy_configuration(), see documentation [here](https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.webservice(class)?view=azure-ml-py#get-keys--) on how to retrieve your keys and use either key as an argument to PredictionClient(...,access_token=key)."
|
]
|
||||||
]
|
},
|
||||||
},
|
{
|
||||||
{
|
"cell_type": "markdown",
|
||||||
"cell_type": "code",
|
"metadata": {},
|
||||||
"execution_count": null,
|
"source": [
|
||||||
"metadata": {},
|
"<a id=\"test-service\"></a>\n",
|
||||||
"outputs": [],
|
"## 5. Test the service\n",
|
||||||
"source": [
|
"<a id=\"create-client\"></a>\n",
|
||||||
"# Using the grpc client in AzureML Accelerated Models SDK\n",
|
"### 5.a. Create Client\n",
|
||||||
"from azureml.accel.client import PredictionClient\n",
|
"The image supports gRPC and the TensorFlow Serving \"predict\" API. We will create a PredictionClient from the Webservice object that can call into the docker image to get predictions. If you do not have the Webservice object, you can also create [PredictionClient](https://docs.microsoft.com/en-us/python/api/azureml-accel-models/azureml.accel.predictionclient?view=azure-ml-py) directly.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"address = aks_service.scoring_uri\n",
|
"**Note:** If you chose to use auth_enabled=True when creating your AksWebservice.deploy_configuration(), see documentation [here](https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.webservice(class)?view=azure-ml-py#get-keys--) on how to retrieve your keys and use either key as an argument to PredictionClient(...,access_token=key).\n",
|
||||||
"ssl_enabled = address.startswith(\"https\")\n",
|
"**WARNING:** If you are running on Azure Notebooks free compute, you will not be able to make outgoing calls to your service. Try locating your client on a different machine to consume it."
|
||||||
"address = address[address.find('/')+2:].strip('/')\n",
|
]
|
||||||
"port = 443 if ssl_enabled else 80\n",
|
},
|
||||||
"\n",
|
{
|
||||||
"# Initialize AzureML Accelerated Models client\n",
|
"cell_type": "code",
|
||||||
"client = PredictionClient(address=address,\n",
|
"execution_count": null,
|
||||||
" port=port,\n",
|
"metadata": {},
|
||||||
" use_ssl=ssl_enabled,\n",
|
"outputs": [],
|
||||||
" service_name=aks_service.name)"
|
"source": [
|
||||||
]
|
"# Using the grpc client in AzureML Accelerated Models SDK\n",
|
||||||
},
|
"from azureml.accel import client_from_service\n",
|
||||||
{
|
"\n",
|
||||||
"cell_type": "markdown",
|
"# Initialize AzureML Accelerated Models client\n",
|
||||||
"metadata": {},
|
"client = client_from_service(aks_service)"
|
||||||
"source": [
|
]
|
||||||
"You can adapt the client [code](https://github.com/Azure/aml-real-time-ai/blob/master/pythonlib/amlrealtimeai/client.py) to meet your needs. There is also an example C# [client](https://github.com/Azure/aml-real-time-ai/blob/master/sample-clients/csharp).\n",
|
},
|
||||||
"\n",
|
{
|
||||||
"The service provides an API that is compatible with TensorFlow Serving. There are instructions to download a sample client [here](https://www.tensorflow.org/serving/setup)."
|
"cell_type": "markdown",
|
||||||
]
|
"metadata": {},
|
||||||
},
|
"source": [
|
||||||
{
|
"You can adapt the client [code](https://github.com/Azure/aml-real-time-ai/blob/master/pythonlib/amlrealtimeai/client.py) to meet your needs. There is also an example C# [client](https://github.com/Azure/aml-real-time-ai/blob/master/sample-clients/csharp).\n",
|
||||||
"cell_type": "markdown",
|
"\n",
|
||||||
"metadata": {},
|
"The service provides an API that is compatible with TensorFlow Serving. There are instructions to download a sample client [here](https://www.tensorflow.org/serving/setup)."
|
||||||
"source": [
|
]
|
||||||
"<a id=\"serve-model\"></a>\n",
|
},
|
||||||
"### 5.b. Serve the model\n",
|
{
|
||||||
"The SSD-VGG model returns the confidence and bounding boxes for all possible anchor boxes. As mentioned earlier, we will use a post-processing routine to transform this into a list of bounding boxes (y1, x1, y2, x2) where x, y are fractional coordinates measured from left and top respectively. A respective list of classes and scores is also returned to tag each bounding box. Below we make use of this information to draw the bounding boxes on top the original image. Note that in the post-processing routine we select a confidence threshold of 0.5."
|
"cell_type": "markdown",
|
||||||
]
|
"metadata": {},
|
||||||
},
|
"source": [
|
||||||
{
|
"<a id=\"serve-model\"></a>\n",
|
||||||
"cell_type": "code",
|
"### 5.b. Serve the model\n",
|
||||||
"execution_count": null,
|
"The SSD-VGG model returns the confidence and bounding boxes for all possible anchor boxes. As mentioned earlier, we will use a post-processing routine to transform this into a list of bounding boxes (y1, x1, y2, x2) where x, y are fractional coordinates measured from left and top respectively. A respective list of classes and scores is also returned to tag each bounding box. Below we make use of this information to draw the bounding boxes on top the original image. Note that in the post-processing routine we select a confidence threshold of 0.5."
|
||||||
"metadata": {},
|
]
|
||||||
"outputs": [],
|
},
|
||||||
"source": [
|
{
|
||||||
"import cv2\n",
|
"cell_type": "code",
|
||||||
"from matplotlib import pyplot as plt\n",
|
"execution_count": null,
|
||||||
"\n",
|
"metadata": {},
|
||||||
"colors_tableau = [(255, 255, 255), (31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120),\n",
|
"outputs": [],
|
||||||
" (44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150),\n",
|
"source": [
|
||||||
" (148, 103, 189), (197, 176, 213), (140, 86, 75), (196, 156, 148),\n",
|
"import cv2\n",
|
||||||
" (227, 119, 194), (247, 182, 210), (127, 127, 127), (199, 199, 199),\n",
|
"from matplotlib import pyplot as plt\n",
|
||||||
" (188, 189, 34), (219, 219, 141), (23, 190, 207), (158, 218, 229)]\n",
|
"\n",
|
||||||
"\n",
|
"colors_tableau = [(255, 255, 255), (31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120),\n",
|
||||||
"\n",
|
" (44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150),\n",
|
||||||
"def draw_boxes_on_img(img, classes, scores, bboxes, thickness=2):\n",
|
" (148, 103, 189), (197, 176, 213), (140, 86, 75), (196, 156, 148),\n",
|
||||||
" shape = img.shape\n",
|
" (227, 119, 194), (247, 182, 210), (127, 127, 127), (199, 199, 199),\n",
|
||||||
" for i in range(bboxes.shape[0]):\n",
|
" (188, 189, 34), (219, 219, 141), (23, 190, 207), (158, 218, 229)]\n",
|
||||||
" bbox = bboxes[i]\n",
|
"\n",
|
||||||
" color = colors_tableau[classes[i]]\n",
|
"\n",
|
||||||
" # Draw bounding box...\n",
|
"def draw_boxes_on_img(img, classes, scores, bboxes, thickness=2):\n",
|
||||||
" p1 = (int(bbox[0] * shape[0]), int(bbox[1] * shape[1]))\n",
|
" shape = img.shape\n",
|
||||||
" p2 = (int(bbox[2] * shape[0]), int(bbox[3] * shape[1]))\n",
|
" for i in range(bboxes.shape[0]):\n",
|
||||||
" cv2.rectangle(img, p1[::-1], p2[::-1], color, thickness)\n",
|
" bbox = bboxes[i]\n",
|
||||||
" # Draw text...\n",
|
" color = colors_tableau[classes[i]]\n",
|
||||||
" s = '%s/%.3f' % (classes[i], scores[i])\n",
|
" # Draw bounding box...\n",
|
||||||
" p1 = (p1[0]-5, p1[1])\n",
|
" p1 = (int(bbox[0] * shape[0]), int(bbox[1] * shape[1]))\n",
|
||||||
" cv2.putText(img, s, p1[::-1], cv2.FONT_HERSHEY_DUPLEX, 0.4, color, 1)"
|
" p2 = (int(bbox[2] * shape[0]), int(bbox[3] * shape[1]))\n",
|
||||||
]
|
" cv2.rectangle(img, p1[::-1], p2[::-1], color, thickness)\n",
|
||||||
},
|
" # Draw text...\n",
|
||||||
{
|
" s = '%s/%.3f' % (classes[i], scores[i])\n",
|
||||||
"cell_type": "code",
|
" p1 = (p1[0]-5, p1[1])\n",
|
||||||
"execution_count": null,
|
" cv2.putText(img, s, p1[::-1], cv2.FONT_HERSHEY_DUPLEX, 0.4, color, 1)"
|
||||||
"metadata": {},
|
]
|
||||||
"outputs": [],
|
},
|
||||||
"source": [
|
{
|
||||||
"import azureml.accel._external.ssdvgg_utils as ssdvgg_utils\n",
|
"cell_type": "code",
|
||||||
"\n",
|
"execution_count": null,
|
||||||
"result = client.score_file(path=\"meeting.jpg\", input_name=input_tensors, outputs=output_tensors)\n",
|
"metadata": {},
|
||||||
"classes, scores, bboxes = ssdvgg_utils.postprocess(result, select_threshold=0.5)\n",
|
"outputs": [],
|
||||||
"\n",
|
"source": [
|
||||||
"img = cv2.imread('meeting.jpg', 1)\n",
|
"import azureml.accel._external.ssdvgg_utils as ssdvgg_utils\n",
|
||||||
"img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n",
|
"\n",
|
||||||
"draw_boxes_on_img(img, classes, scores, bboxes)\n",
|
"result = client.score_file(path=\"meeting.jpg\", input_name=input_tensors, outputs=output_tensors)\n",
|
||||||
"plt.imshow(img)"
|
"classes, scores, bboxes = ssdvgg_utils.postprocess(result, select_threshold=0.5)\n",
|
||||||
]
|
"\n",
|
||||||
},
|
"img = cv2.imread('meeting.jpg', 1)\n",
|
||||||
{
|
"img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n",
|
||||||
"cell_type": "markdown",
|
"draw_boxes_on_img(img, classes, scores, bboxes)\n",
|
||||||
"metadata": {},
|
"plt.imshow(img)"
|
||||||
"source": [
|
]
|
||||||
"<a id=\"cleanup\"></a>\n",
|
},
|
||||||
"## 6. Cleanup\n",
|
{
|
||||||
"It's important to clean up your resources, so that you won't incur unnecessary costs. In the [next notebook](./accelerated-models-training.ipynb) you will learn how to train a classfier on a new dataset using transfer learning."
|
"cell_type": "markdown",
|
||||||
]
|
"metadata": {},
|
||||||
},
|
"source": [
|
||||||
{
|
"<a id=\"cleanup\"></a>\n",
|
||||||
"cell_type": "code",
|
"## 6. Cleanup\n",
|
||||||
"execution_count": null,
|
"It's important to clean up your resources, so that you won't incur unnecessary costs. In the [next notebook](./accelerated-models-training.ipynb) you will learn how to train a classfier on a new dataset using transfer learning."
|
||||||
"metadata": {},
|
]
|
||||||
"outputs": [],
|
},
|
||||||
"source": [
|
{
|
||||||
"aks_service.delete()\n",
|
"cell_type": "code",
|
||||||
"aks_target.delete()\n",
|
"execution_count": null,
|
||||||
"image.delete()\n",
|
"metadata": {},
|
||||||
"registered_model.delete()\n",
|
"outputs": [],
|
||||||
"converted_model.delete()"
|
"source": [
|
||||||
]
|
"aks_service.delete()\n",
|
||||||
}
|
"aks_target.delete()\n",
|
||||||
],
|
"image.delete()\n",
|
||||||
"metadata": {
|
"registered_model.delete()\n",
|
||||||
"authors": [
|
"converted_model.delete()"
|
||||||
{
|
]
|
||||||
"name": "coverste"
|
}
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "paledger"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "sukha"
|
|
||||||
}
|
|
||||||
],
|
],
|
||||||
"kernelspec": {
|
"metadata": {
|
||||||
"display_name": "Python 3.6",
|
"authors": [
|
||||||
"language": "python",
|
{
|
||||||
"name": "python36"
|
"name": "coverste"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "paledger"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "sukha"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"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.5.6"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"language_info": {
|
"nbformat": 4,
|
||||||
"codemirror_mode": {
|
"nbformat_minor": 2
|
||||||
"name": "ipython",
|
}
|
||||||
"version": 3
|
|
||||||
},
|
|
||||||
"file_extension": ".py",
|
|
||||||
"mimetype": "text/x-python",
|
|
||||||
"name": "python",
|
|
||||||
"nbconvert_exporter": "python",
|
|
||||||
"pygments_lexer": "ipython3",
|
|
||||||
"version": "3.6.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"nbformat": 4,
|
|
||||||
"nbformat_minor": 2
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
name: accelerated-models-object-detection
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
|
- azureml-accel-models
|
||||||
|
- tensorflow
|
||||||
|
- opencv-python
|
||||||
|
- matplotlib
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,6 @@
|
|||||||
|
name: accelerated-models-quickstart
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
|
- azureml-accel-models
|
||||||
|
- tensorflow
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,9 @@
|
|||||||
|
name: accelerated-models-training
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
|
- azureml-accel-models
|
||||||
|
- tensorflow
|
||||||
|
- keras
|
||||||
|
- tqdm
|
||||||
|
- sklearn
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
name: enable-app-insights-in-production-service
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
name: enable-data-collection-for-models-in-aks
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
name: onnx-convert-aml-deploy-tinyyolo
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
|
- git+https://github.com/apple/coremltools
|
||||||
|
- onnxmltools==1.3.1
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
name: onnx-inference-facial-expression-recognition-deploy
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
|
- azureml-widgets
|
||||||
|
- matplotlib
|
||||||
|
- numpy
|
||||||
|
- onnx
|
||||||
|
- opencv-python
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
name: onnx-inference-mnist-deploy
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
|
- azureml-widgets
|
||||||
|
- matplotlib
|
||||||
|
- numpy
|
||||||
|
- onnx
|
||||||
|
- opencv-python
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
name: onnx-modelzoo-aml-deploy-resnet50
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
@@ -98,7 +98,7 @@
|
|||||||
"from azureml.core.compute_target import ComputeTargetException\n",
|
"from azureml.core.compute_target import ComputeTargetException\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# choose a name for your cluster\n",
|
"# choose a name for your cluster\n",
|
||||||
"cluster_name = \"gpucluster\"\n",
|
"cluster_name = \"gpu-cluster\"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"try:\n",
|
"try:\n",
|
||||||
" compute_target = ComputeTarget(workspace=ws, name=cluster_name)\n",
|
" compute_target = ComputeTarget(workspace=ws, name=cluster_name)\n",
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
name: onnx-train-pytorch-aml-deploy-mnist
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
|
- azureml-widgets
|
||||||
@@ -1,407 +1,407 @@
|
|||||||
{
|
{
|
||||||
"cells": [
|
"cells": [
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Licensed under the MIT License."
|
"Licensed under the MIT License."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"# Deploying a web service to Azure Kubernetes Service (AKS)\n",
|
"# Deploying a web service to Azure Kubernetes Service (AKS)\n",
|
||||||
"This notebook shows the steps for deploying a service: registering a model, creating an image, provisioning a cluster (one time action), and deploying a service to it. \n",
|
"This notebook shows the steps for deploying a service: registering a model, creating an image, provisioning a cluster (one time action), and deploying a service to it. \n",
|
||||||
"We then test and delete the service, image and model."
|
"We then test and delete the service, image and model."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from azureml.core import Workspace\n",
|
"from azureml.core import Workspace\n",
|
||||||
"from azureml.core.compute import AksCompute, ComputeTarget\n",
|
"from azureml.core.compute import AksCompute, ComputeTarget\n",
|
||||||
"from azureml.core.webservice import Webservice, AksWebservice\n",
|
"from azureml.core.webservice import Webservice, AksWebservice\n",
|
||||||
"from azureml.core.image import Image\n",
|
"from azureml.core.image import Image\n",
|
||||||
"from azureml.core.model import Model"
|
"from azureml.core.model import Model"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"import azureml.core\n",
|
"import azureml.core\n",
|
||||||
"print(azureml.core.VERSION)"
|
"print(azureml.core.VERSION)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"# Get workspace\n",
|
"# Get workspace\n",
|
||||||
"Load existing workspace from the config file info."
|
"Load existing workspace from the config file info."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from azureml.core.workspace import Workspace\n",
|
"from azureml.core.workspace import Workspace\n",
|
||||||
"\n",
|
"\n",
|
||||||
"ws = Workspace.from_config()\n",
|
"ws = Workspace.from_config()\n",
|
||||||
"print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep = '\\n')"
|
"print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep = '\\n')"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"# Register the model\n",
|
"# Register the model\n",
|
||||||
"Register an existing trained model, add descirption and tags. Prior to registering the model, you should have a TensorFlow [Saved Model](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md) in the `resnet50` directory. You can download a [pretrained resnet50](https://github.com/tensorflow/models/tree/master/official/resnet#pre-trained-model) and unpack it to that directory."
|
"Register an existing trained model, add descirption and tags. Prior to registering the model, you should have a TensorFlow [Saved Model](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md) in the `resnet50` directory. You can download a [pretrained resnet50](https://github.com/tensorflow/models/tree/master/official/resnet#pre-trained-model) and unpack it to that directory."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"#Register the model\n",
|
"#Register the model\n",
|
||||||
"from azureml.core.model import Model\n",
|
"from azureml.core.model import Model\n",
|
||||||
"model = Model.register(model_path = \"resnet50\", # this points to a local file\n",
|
"model = Model.register(model_path = \"resnet50\", # this points to a local file\n",
|
||||||
" model_name = \"resnet50\", # this is the name the model is registered as\n",
|
" model_name = \"resnet50\", # this is the name the model is registered as\n",
|
||||||
" tags = {'area': \"Image classification\", 'type': \"classification\"},\n",
|
" tags = {'area': \"Image classification\", 'type': \"classification\"},\n",
|
||||||
" description = \"Image classification trained on Imagenet Dataset\",\n",
|
" description = \"Image classification trained on Imagenet Dataset\",\n",
|
||||||
" workspace = ws)\n",
|
" workspace = ws)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"print(model.name, model.description, model.version)"
|
"print(model.name, model.description, model.version)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"# Create an image\n",
|
"# Create an image\n",
|
||||||
"Create an image using the registered model the script that will load and run the model."
|
"Create an image using the registered model the script that will load and run the model."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"%%writefile score.py\n",
|
"%%writefile score.py\n",
|
||||||
"import tensorflow as tf\n",
|
"import tensorflow as tf\n",
|
||||||
"import numpy as np\n",
|
"import numpy as np\n",
|
||||||
"import ujson\n",
|
"import ujson\n",
|
||||||
"from azureml.core.model import Model\n",
|
"from azureml.core.model import Model\n",
|
||||||
"from azureml.contrib.services.aml_request import AMLRequest, rawhttp\n",
|
"from azureml.contrib.services.aml_request import AMLRequest, rawhttp\n",
|
||||||
"from azureml.contrib.services.aml_response import AMLResponse\n",
|
"from azureml.contrib.services.aml_response import AMLResponse\n",
|
||||||
"\n",
|
"\n",
|
||||||
"def init():\n",
|
"def init():\n",
|
||||||
" global session\n",
|
" global session\n",
|
||||||
" global input_name\n",
|
" global input_name\n",
|
||||||
" global output_name\n",
|
" global output_name\n",
|
||||||
" \n",
|
" \n",
|
||||||
" session = tf.Session()\n",
|
" session = tf.Session()\n",
|
||||||
"\n",
|
"\n",
|
||||||
" model_path = Model.get_model_path('resnet50')\n",
|
" model_path = Model.get_model_path('resnet50')\n",
|
||||||
" model = tf.saved_model.loader.load(session, ['serve'], model_path)\n",
|
" model = tf.saved_model.loader.load(session, ['serve'], model_path)\n",
|
||||||
" if len(model.signature_def['serving_default'].inputs) > 1:\n",
|
" if len(model.signature_def['serving_default'].inputs) > 1:\n",
|
||||||
" raise ValueError(\"This score.py only supports one input\")\n",
|
" raise ValueError(\"This score.py only supports one input\")\n",
|
||||||
" if len(model.signature_def['serving_default'].outputs) > 1:\n",
|
" if len(model.signature_def['serving_default'].outputs) > 1:\n",
|
||||||
" raise ValueError(\"This score.py only supports one input\")\n",
|
" raise ValueError(\"This score.py only supports one input\")\n",
|
||||||
" input_name = [tensor.name for tensor in model.signature_def['serving_default'].inputs.values()][0]\n",
|
" input_name = [tensor.name for tensor in model.signature_def['serving_default'].inputs.values()][0]\n",
|
||||||
" output_name = [tensor.name for tensor in model.signature_def['serving_default'].outputs.values()][0]\n",
|
" output_name = [tensor.name for tensor in model.signature_def['serving_default'].outputs.values()][0]\n",
|
||||||
" \n",
|
" \n",
|
||||||
"\n",
|
"\n",
|
||||||
"@rawhttp\n",
|
"@rawhttp\n",
|
||||||
"def run(request):\n",
|
"def run(request):\n",
|
||||||
" if request.method == 'POST':\n",
|
" if request.method == 'POST':\n",
|
||||||
" reqBody = request.get_data(False)\n",
|
" reqBody = request.get_data(False)\n",
|
||||||
" resp = score(reqBody)\n",
|
" resp = score(reqBody)\n",
|
||||||
" return AMLResponse(resp, 200)\n",
|
" return AMLResponse(resp, 200)\n",
|
||||||
" if request.method == 'GET':\n",
|
" if request.method == 'GET':\n",
|
||||||
" respBody = str.encode(\"GET is not supported\")\n",
|
" respBody = str.encode(\"GET is not supported\")\n",
|
||||||
" return AMLResponse(respBody, 405)\n",
|
" return AMLResponse(respBody, 405)\n",
|
||||||
" return AMLResponse(\"bad request\", 500)\n",
|
" return AMLResponse(\"bad request\", 500)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"def score(data):\n",
|
"def score(data):\n",
|
||||||
" result = session.run(output_name, {input_name: [data]})\n",
|
" result = session.run(output_name, {input_name: [data]})\n",
|
||||||
" return ujson.dumps(result[0])\n",
|
" return ujson.dumps(result[0])\n",
|
||||||
"\n",
|
"\n",
|
||||||
"if __name__ == \"__main__\":\n",
|
"if __name__ == \"__main__\":\n",
|
||||||
" init()\n",
|
" init()\n",
|
||||||
" with open(\"test_image.jpg\", 'rb') as f:\n",
|
" with open(\"test_image.jpg\", 'rb') as f:\n",
|
||||||
" content = f.read()\n",
|
" content = f.read()\n",
|
||||||
" print(score(content))"
|
" print(score(content))"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from azureml.core.conda_dependencies import CondaDependencies \n",
|
"from azureml.core.conda_dependencies import CondaDependencies \n",
|
||||||
"\n",
|
"\n",
|
||||||
"myenv = CondaDependencies.create(conda_packages=['tensorflow-gpu==1.12.0','numpy','ujson','azureml-contrib-services'])\n",
|
"myenv = CondaDependencies.create(conda_packages=['tensorflow-gpu==1.12.0','numpy','ujson','azureml-contrib-services'])\n",
|
||||||
"\n",
|
"\n",
|
||||||
"with open(\"myenv.yml\",\"w\") as f:\n",
|
"with open(\"myenv.yml\",\"w\") as f:\n",
|
||||||
" f.write(myenv.serialize_to_string())"
|
" f.write(myenv.serialize_to_string())"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from azureml.core.image import ContainerImage\n",
|
"from azureml.core.image import ContainerImage\n",
|
||||||
"\n",
|
"\n",
|
||||||
"image_config = ContainerImage.image_configuration(execution_script = \"score.py\",\n",
|
"image_config = ContainerImage.image_configuration(execution_script = \"score.py\",\n",
|
||||||
" runtime = \"python\",\n",
|
" runtime = \"python\",\n",
|
||||||
" conda_file = \"myenv.yml\",\n",
|
" conda_file = \"myenv.yml\",\n",
|
||||||
" gpu_enabled = True\n",
|
" gpu_enabled = True\n",
|
||||||
" )\n",
|
" )\n",
|
||||||
"\n",
|
"\n",
|
||||||
"image = ContainerImage.create(name = \"GpuImage\",\n",
|
"image = ContainerImage.create(name = \"GpuImage\",\n",
|
||||||
" # this is the model object\n",
|
" # this is the model object\n",
|
||||||
" models = [model],\n",
|
" models = [model],\n",
|
||||||
" image_config = image_config,\n",
|
" image_config = image_config,\n",
|
||||||
" workspace = ws)\n",
|
" workspace = ws)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"image.wait_for_creation(show_output = True)"
|
"image.wait_for_creation(show_output = True)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"# Provision the AKS Cluster\n",
|
"# Provision the AKS Cluster\n",
|
||||||
"This is a one time setup. You can reuse this cluster for multiple deployments after it has been created. If you delete the cluster or the resource group that contains it, then you would have to recreate it."
|
"This is a one time setup. You can reuse this cluster for multiple deployments after it has been created. If you delete the cluster or the resource group that contains it, then you would have to recreate it."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"# Use the default configuration (can also provide parameters to customize)\n",
|
"# Use the default configuration (can also provide parameters to customize)\n",
|
||||||
"prov_config = AksCompute.provisioning_configuration(vm_size=\"Standard_NC6\")\n",
|
"prov_config = AksCompute.provisioning_configuration(vm_size=\"Standard_NC6\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"aks_name = 'my-aks-9' \n",
|
"aks_name = 'my-aks-9' \n",
|
||||||
"# Create the cluster\n",
|
"# Create the cluster\n",
|
||||||
"aks_target = ComputeTarget.create(workspace = ws, \n",
|
"aks_target = ComputeTarget.create(workspace = ws, \n",
|
||||||
" name = aks_name, \n",
|
" name = aks_name, \n",
|
||||||
" provisioning_configuration = prov_config)"
|
" provisioning_configuration = prov_config)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"# Create AKS Cluster in an existing virtual network (optional)\n",
|
"# Create AKS Cluster in an existing virtual network (optional)\n",
|
||||||
"See code snippet below. Check the documentation [here](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-enable-virtual-network#use-azure-kubernetes-service) for more details."
|
"See code snippet below. Check the documentation [here](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-enable-virtual-network#use-azure-kubernetes-service) for more details."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"'''\n",
|
"'''\n",
|
||||||
"from azureml.core.compute import ComputeTarget, AksCompute\n",
|
"from azureml.core.compute import ComputeTarget, AksCompute\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# Create the compute configuration and set virtual network information\n",
|
"# Create the compute configuration and set virtual network information\n",
|
||||||
"config = AksCompute.provisioning_configuration(vm_size=\"Standard_NC6\", location=\"eastus2\")\n",
|
"config = AksCompute.provisioning_configuration(vm_size=\"Standard_NC6\", location=\"eastus2\")\n",
|
||||||
"config.vnet_resourcegroup_name = \"mygroup\"\n",
|
"config.vnet_resourcegroup_name = \"mygroup\"\n",
|
||||||
"config.vnet_name = \"mynetwork\"\n",
|
"config.vnet_name = \"mynetwork\"\n",
|
||||||
"config.subnet_name = \"default\"\n",
|
"config.subnet_name = \"default\"\n",
|
||||||
"config.service_cidr = \"10.0.0.0/16\"\n",
|
"config.service_cidr = \"10.0.0.0/16\"\n",
|
||||||
"config.dns_service_ip = \"10.0.0.10\"\n",
|
"config.dns_service_ip = \"10.0.0.10\"\n",
|
||||||
"config.docker_bridge_cidr = \"172.17.0.1/16\"\n",
|
"config.docker_bridge_cidr = \"172.17.0.1/16\"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# Create the compute target\n",
|
"# Create the compute target\n",
|
||||||
"aks_target = ComputeTarget.create(workspace = ws,\n",
|
"aks_target = ComputeTarget.create(workspace = ws,\n",
|
||||||
" name = \"myaks\",\n",
|
" name = \"myaks\",\n",
|
||||||
" provisioning_configuration = config)\n",
|
" provisioning_configuration = config)\n",
|
||||||
"'''"
|
"'''"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"# Enable SSL on the AKS Cluster (optional)\n",
|
"# Enable SSL on the AKS Cluster (optional)\n",
|
||||||
"See code snippet below. Check the documentation [here](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-secure-web-service) for more details"
|
"See code snippet below. Check the documentation [here](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-secure-web-service) for more details"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"# provisioning_config = AksCompute.provisioning_configuration(ssl_cert_pem_file=\"cert.pem\", ssl_key_pem_file=\"key.pem\", ssl_cname=\"www.contoso.com\")"
|
"# provisioning_config = AksCompute.provisioning_configuration(ssl_cert_pem_file=\"cert.pem\", ssl_key_pem_file=\"key.pem\", ssl_cname=\"www.contoso.com\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"%%time\n",
|
"%%time\n",
|
||||||
"aks_target.wait_for_completion(show_output = True)\n",
|
"aks_target.wait_for_completion(show_output = True)\n",
|
||||||
"print(aks_target.provisioning_state)\n",
|
"print(aks_target.provisioning_state)\n",
|
||||||
"print(aks_target.provisioning_errors)"
|
"print(aks_target.provisioning_errors)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Optional step: Attach existing AKS cluster\n",
|
"## Optional step: Attach existing AKS cluster\n",
|
||||||
"\n",
|
"\n",
|
||||||
"If you have existing AKS cluster in your Azure subscription, you can attach it to the Workspace."
|
"If you have existing AKS cluster in your Azure subscription, you can attach it to the Workspace."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"'''\n",
|
"'''\n",
|
||||||
"# Use the default configuration (can also provide parameters to customize)\n",
|
"# Use the default configuration (can also provide parameters to customize)\n",
|
||||||
"resource_id = '/subscriptions/92c76a2f-0e1c-4216-b65e-abf7a3f34c1e/resourcegroups/raymondsdk0604/providers/Microsoft.ContainerService/managedClusters/my-aks-0605d37425356b7d01'\n",
|
"resource_id = '/subscriptions/92c76a2f-0e1c-4216-b65e-abf7a3f34c1e/resourcegroups/raymondsdk0604/providers/Microsoft.ContainerService/managedClusters/my-aks-0605d37425356b7d01'\n",
|
||||||
"\n",
|
"\n",
|
||||||
"create_name='my-existing-aks' \n",
|
"create_name='my-existing-aks' \n",
|
||||||
"# Create the cluster\n",
|
"# Create the cluster\n",
|
||||||
"attach_config = AksCompute.attach_configuration(resource_id=resource_id)\n",
|
"attach_config = AksCompute.attach_configuration(resource_id=resource_id)\n",
|
||||||
"aks_target = ComputeTarget.attach(workspace=ws, name=create_name, attach_configuration=attach_config)\n",
|
"aks_target = ComputeTarget.attach(workspace=ws, name=create_name, attach_configuration=attach_config)\n",
|
||||||
"# Wait for the operation to complete\n",
|
"# Wait for the operation to complete\n",
|
||||||
"aks_target.wait_for_completion(True)\n",
|
"aks_target.wait_for_completion(True)\n",
|
||||||
"'''"
|
"'''"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"# Deploy web service to AKS"
|
"# Deploy web service to AKS"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"#Set the web service configuration (using default here)\n",
|
"#Set the web service configuration (using default here)\n",
|
||||||
"aks_config = AksWebservice.deploy_configuration()"
|
"aks_config = AksWebservice.deploy_configuration()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"%%time\n",
|
"%%time\n",
|
||||||
"aks_service_name ='aks-service-1'\n",
|
"aks_service_name ='aks-service-1'\n",
|
||||||
"\n",
|
"\n",
|
||||||
"aks_service = Webservice.deploy_from_image(workspace = ws, \n",
|
"aks_service = Webservice.deploy_from_image(workspace = ws, \n",
|
||||||
" name = aks_service_name,\n",
|
" name = aks_service_name,\n",
|
||||||
" image = image,\n",
|
" image = image,\n",
|
||||||
" deployment_config = aks_config,\n",
|
" deployment_config = aks_config,\n",
|
||||||
" deployment_target = aks_target)\n",
|
" deployment_target = aks_target)\n",
|
||||||
"aks_service.wait_for_deployment(show_output = True)\n",
|
"aks_service.wait_for_deployment(show_output = True)\n",
|
||||||
"print(aks_service.state)"
|
"print(aks_service.state)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"# Test the web service\n",
|
"# Test the web service\n",
|
||||||
"We test the web sevice by passing the test images content."
|
"We test the web sevice by passing the test images content."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"%%time\n",
|
"%%time\n",
|
||||||
"import requests\n",
|
"import requests\n",
|
||||||
"key1, key2 = aks_service.get_keys()\n",
|
"key1, key2 = aks_service.get_keys()\n",
|
||||||
"\n",
|
"\n",
|
||||||
"headers = {'Content-Type':'application/json', 'Authorization': 'Bearer ' + key1}\n",
|
"headers = {'Content-Type':'application/json', 'Authorization': 'Bearer ' + key1}\n",
|
||||||
"test_sampe = open('test_image.jpg', 'rb').read()\n",
|
"test_sampe = open('test_image.jpg', 'rb').read()\n",
|
||||||
"resp = requests.post(aks_service.scoring_uri, test_sample, headers=headers)"
|
"resp = requests.post(aks_service.scoring_uri, test_sample, headers=headers)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"# Clean up\n",
|
"# Clean up\n",
|
||||||
"Delete the service, image, model and compute target"
|
"Delete the service, image, model and compute target"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"%%time\n",
|
"%%time\n",
|
||||||
"aks_service.delete()\n",
|
"aks_service.delete()\n",
|
||||||
"image.delete()\n",
|
"image.delete()\n",
|
||||||
"model.delete()\n",
|
"model.delete()\n",
|
||||||
"aks_target.delete()"
|
"aks_target.delete()"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
],
|
|
||||||
"metadata": {
|
|
||||||
"authors": [
|
|
||||||
{
|
|
||||||
"name": "aashishb"
|
|
||||||
}
|
|
||||||
],
|
],
|
||||||
"kernelspec": {
|
"metadata": {
|
||||||
"display_name": "Python 3",
|
"authors": [
|
||||||
"language": "python",
|
{
|
||||||
"name": "python3"
|
"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"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"language_info": {
|
"nbformat": 4,
|
||||||
"codemirror_mode": {
|
"nbformat_minor": 2
|
||||||
"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
|
|
||||||
}
|
|
||||||
@@ -470,7 +470,27 @@
|
|||||||
"nbconvert_exporter": "python",
|
"nbconvert_exporter": "python",
|
||||||
"pygments_lexer": "ipython3",
|
"pygments_lexer": "ipython3",
|
||||||
"version": "3.6.6"
|
"version": "3.6.6"
|
||||||
}
|
},
|
||||||
|
"friendly_name": "Prepare data for regression modeling",
|
||||||
|
"exclude_from_index": false,
|
||||||
|
"order_index": 1,
|
||||||
|
"category": "deployment",
|
||||||
|
"tags": [
|
||||||
|
"featured"
|
||||||
|
],
|
||||||
|
"task": "Regression",
|
||||||
|
"datasets": [
|
||||||
|
"test"
|
||||||
|
],
|
||||||
|
"compute": [
|
||||||
|
"localtest"
|
||||||
|
],
|
||||||
|
"deployment": [
|
||||||
|
"AKS"
|
||||||
|
],
|
||||||
|
"framework": [
|
||||||
|
"test1"
|
||||||
|
]
|
||||||
},
|
},
|
||||||
"nbformat": 4,
|
"nbformat": 4,
|
||||||
"nbformat_minor": 2
|
"nbformat_minor": 2
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
name: production-deploy-to-aks
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
|
- matplotlib
|
||||||
|
- tqdm
|
||||||
|
- scipy
|
||||||
|
- sklearn
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
name: register-model-create-image-deploy-service
|
||||||
|
dependencies:
|
||||||
|
- pip:
|
||||||
|
- azureml-sdk
|
||||||
|
- matplotlib
|
||||||
|
- tqdm
|
||||||
|
- scipy
|
||||||
|
- sklearn
|
||||||
@@ -1,8 +1,11 @@
|
|||||||
## Using explain model APIs
|
## Using explain model APIs
|
||||||
|
|
||||||
|
<a name="samples"></a>
|
||||||
|
# Explain Model SDK Sample Notebooks
|
||||||
|
|
||||||
Follow these sample notebooks to learn:
|
Follow these sample notebooks to learn:
|
||||||
|
|
||||||
1. [Explain tabular data locally](explain-tabular-data-local): Basic example of explaining model trained on tabular data.
|
1. [Explain tabular data locally](tabular-data): Basic examples of explaining model trained on tabular data.
|
||||||
4. [Explain on remote AMLCompute](explain-on-amlcompute): Explain a model on a remote AMLCompute target.
|
2. [Explain on remote AMLCompute](azure-integration/remote-explanation): Explain a model on a remote AMLCompute target.
|
||||||
5. [Explain tabular data with Run History](explain-tabular-data-run-history): Explain a model with Run History.
|
3. [Explain tabular data with Run History](azure-integration/run-history): Explain a model with Run History.
|
||||||
7. [Explain raw features](explain-tabular-data-raw-features): Explain the raw features of a trained model.
|
4. [Operationalize model explanation](azure-integration/scoring-time): Operationalize model explanation as a web service.
|
||||||
|
|||||||
@@ -0,0 +1,645 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
|
||||||
|
"\n",
|
||||||
|
"Licensed under the MIT License."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
""
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Save and retrieve explanations via Azure Machine Learning Run History\n",
|
||||||
|
"\n",
|
||||||
|
"_**This notebook showcases how to use the Azure Machine Learning Interpretability SDK to save and retrieve classification model explanations to/from Azure Machine Learning Run History.**_\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"## Table of Contents\n",
|
||||||
|
"\n",
|
||||||
|
"1. [Introduction](#Introduction)\n",
|
||||||
|
"1. [Setup](#Setup)\n",
|
||||||
|
"1. [Run model explainer locally at training time](#Explain)\n",
|
||||||
|
" 1. Apply feature transformations\n",
|
||||||
|
" 1. Train a binary classification model\n",
|
||||||
|
" 1. Explain the model on raw features\n",
|
||||||
|
" 1. Generate global explanations\n",
|
||||||
|
" 1. Generate local explanations\n",
|
||||||
|
"1. [Upload model explanations to Azure Machine Learning Run History](#Upload)\n",
|
||||||
|
"1. [Download model explanations from Azure Machine Learning Run History](#Download)\n",
|
||||||
|
"1. [Visualize explanations](#Visualize)\n",
|
||||||
|
"1. [Next steps](#Next)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Introduction\n",
|
||||||
|
"\n",
|
||||||
|
"This notebook showcases how to explain a classification model predictions locally at training time, upload explanations to the Azure Machine Learning's run history, and download previously-uploaded explanations from the Run History.\n",
|
||||||
|
"It demonstrates the API calls that you need to make to upload/download the global and local explanations and a visualization dashboard that provides an interactive way of discovering patterns in data and downloaded explanations.\n",
|
||||||
|
"\n",
|
||||||
|
"We will showcase three tabular data explainers: TabularExplainer (SHAP), MimicExplainer (global surrogate), and PFIExplainer.\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"Problem: IBM employee attrition classification with scikit-learn (run model explainer locally and upload explanation to the Azure Machine Learning Run History)\n",
|
||||||
|
"\n",
|
||||||
|
"1. Train a SVM classification model using Scikit-learn\n",
|
||||||
|
"2. Run 'explain_model' with AML Run History, which leverages run history service to store and manage the explanation data\n",
|
||||||
|
"---\n",
|
||||||
|
"\n",
|
||||||
|
"## Setup\n",
|
||||||
|
"\n",
|
||||||
|
"You will need to have extensions enabled prior to jupyter kernel starting to see the visualization dashboard.\n",
|
||||||
|
"```\n",
|
||||||
|
"(myenv) $ jupyter nbextension install --py --sys-prefix azureml.contrib.explain.model.visualize\n",
|
||||||
|
"(myenv) $ jupyter nbextension enable --py --sys-prefix azureml.contrib.explain.model.visualize\n",
|
||||||
|
"```\n",
|
||||||
|
"Or\n",
|
||||||
|
"\n",
|
||||||
|
"```\n",
|
||||||
|
"(myenv) $ jupyter nbextension install azureml.contrib.explain.model.visualize --user --py\n",
|
||||||
|
"(myenv) $ jupyter nbextension enable azureml.contrib.explain.model.visualize --user --py\n",
|
||||||
|
"```\n",
|
||||||
|
"\n",
|
||||||
|
"If you are using Jupyter Labs run the following commands instead:\n",
|
||||||
|
"```\n",
|
||||||
|
"(myenv) $ jupyter labextension install @jupyter-widgets/jupyterlab-manager\n",
|
||||||
|
"(myenv) $ jupyter labextension install microsoft-mli-widget\n",
|
||||||
|
"```"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Explain\n",
|
||||||
|
"\n",
|
||||||
|
"### Run model explainer locally at training time"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from sklearn.pipeline import Pipeline\n",
|
||||||
|
"from sklearn.impute import SimpleImputer\n",
|
||||||
|
"from sklearn.preprocessing import StandardScaler, OneHotEncoder\n",
|
||||||
|
"from sklearn.svm import SVC\n",
|
||||||
|
"import pandas as pd\n",
|
||||||
|
"import numpy as np\n",
|
||||||
|
"\n",
|
||||||
|
"# Explainers:\n",
|
||||||
|
"# 1. SHAP Tabular Explainer\n",
|
||||||
|
"from azureml.explain.model.tabular_explainer import TabularExplainer\n",
|
||||||
|
"\n",
|
||||||
|
"# OR\n",
|
||||||
|
"\n",
|
||||||
|
"# 2. Mimic Explainer\n",
|
||||||
|
"from azureml.explain.model.mimic.mimic_explainer import MimicExplainer\n",
|
||||||
|
"# You can use one of the following four interpretable models as a global surrogate to the black box model\n",
|
||||||
|
"from azureml.explain.model.mimic.models.lightgbm_model import LGBMExplainableModel\n",
|
||||||
|
"from azureml.explain.model.mimic.models.linear_model import LinearExplainableModel\n",
|
||||||
|
"from azureml.explain.model.mimic.models.linear_model import SGDExplainableModel\n",
|
||||||
|
"from azureml.explain.model.mimic.models.tree_model import DecisionTreeExplainableModel\n",
|
||||||
|
"\n",
|
||||||
|
"# OR\n",
|
||||||
|
"\n",
|
||||||
|
"# 3. PFI Explainer\n",
|
||||||
|
"from azureml.explain.model.permutation.permutation_importance import PFIExplainer "
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Load the IBM employee attrition data"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# get the IBM employee attrition dataset\n",
|
||||||
|
"outdirname = 'dataset.6.21.19'\n",
|
||||||
|
"try:\n",
|
||||||
|
" from urllib import urlretrieve\n",
|
||||||
|
"except ImportError:\n",
|
||||||
|
" from urllib.request import urlretrieve\n",
|
||||||
|
"import zipfile\n",
|
||||||
|
"zipfilename = outdirname + '.zip'\n",
|
||||||
|
"urlretrieve('https://publictestdatasets.blob.core.windows.net/data/' + zipfilename, zipfilename)\n",
|
||||||
|
"with zipfile.ZipFile(zipfilename, 'r') as unzip:\n",
|
||||||
|
" unzip.extractall('.')\n",
|
||||||
|
"attritionData = pd.read_csv('./WA_Fn-UseC_-HR-Employee-Attrition.csv')\n",
|
||||||
|
"\n",
|
||||||
|
"# Dropping Employee count as all values are 1 and hence attrition is independent of this feature\n",
|
||||||
|
"attritionData = attritionData.drop(['EmployeeCount'], axis=1)\n",
|
||||||
|
"# Dropping Employee Number since it is merely an identifier\n",
|
||||||
|
"attritionData = attritionData.drop(['EmployeeNumber'], axis=1)\n",
|
||||||
|
"\n",
|
||||||
|
"attritionData = attritionData.drop(['Over18'], axis=1)\n",
|
||||||
|
"\n",
|
||||||
|
"# Since all values are 80\n",
|
||||||
|
"attritionData = attritionData.drop(['StandardHours'], axis=1)\n",
|
||||||
|
"\n",
|
||||||
|
"# Converting target variables from string to numerical values\n",
|
||||||
|
"target_map = {'Yes': 1, 'No': 0}\n",
|
||||||
|
"attritionData[\"Attrition_numerical\"] = attritionData[\"Attrition\"].apply(lambda x: target_map[x])\n",
|
||||||
|
"target = attritionData[\"Attrition_numerical\"]\n",
|
||||||
|
"\n",
|
||||||
|
"attritionXData = attritionData.drop(['Attrition_numerical', 'Attrition'], axis=1)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Split data into train and test\n",
|
||||||
|
"from sklearn.model_selection import train_test_split\n",
|
||||||
|
"x_train, x_test, y_train, y_test = train_test_split(attritionXData, \n",
|
||||||
|
" target, \n",
|
||||||
|
" test_size = 0.2,\n",
|
||||||
|
" random_state=0,\n",
|
||||||
|
" stratify=target)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Creating dummy columns for each categorical feature\n",
|
||||||
|
"categorical = []\n",
|
||||||
|
"for col, value in attritionXData.iteritems():\n",
|
||||||
|
" if value.dtype == 'object':\n",
|
||||||
|
" categorical.append(col)\n",
|
||||||
|
" \n",
|
||||||
|
"# Store the numerical columns in a list numerical\n",
|
||||||
|
"numerical = attritionXData.columns.difference(categorical) "
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Transform raw features"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"We can explain raw features by either using a `sklearn.compose.ColumnTransformer` or a list of fitted transformer tuples. The cell below uses `sklearn.compose.ColumnTransformer`. In case you want to run the example with the list of fitted transformer tuples, comment the cell below and uncomment the cell that follows after. "
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from sklearn.compose import ColumnTransformer\n",
|
||||||
|
"\n",
|
||||||
|
"# We create the preprocessing pipelines for both numeric and categorical data.\n",
|
||||||
|
"numeric_transformer = Pipeline(steps=[\n",
|
||||||
|
" ('imputer', SimpleImputer(strategy='median')),\n",
|
||||||
|
" ('scaler', StandardScaler())])\n",
|
||||||
|
"\n",
|
||||||
|
"categorical_transformer = Pipeline(steps=[\n",
|
||||||
|
" ('imputer', SimpleImputer(strategy='constant', fill_value='missing')),\n",
|
||||||
|
" ('onehot', OneHotEncoder(handle_unknown='ignore'))])\n",
|
||||||
|
"\n",
|
||||||
|
"transformations = ColumnTransformer(\n",
|
||||||
|
" transformers=[\n",
|
||||||
|
" ('num', numeric_transformer, numerical),\n",
|
||||||
|
" ('cat', categorical_transformer, categorical)])\n",
|
||||||
|
"\n",
|
||||||
|
"# Append classifier to preprocessing pipeline.\n",
|
||||||
|
"# Now we have a full prediction pipeline.\n",
|
||||||
|
"clf = Pipeline(steps=[('preprocessor', transformations),\n",
|
||||||
|
" ('classifier', SVC(kernel='linear', C = 1.0, probability=True))])"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"'''\n",
|
||||||
|
"# Uncomment below if sklearn-pandas is not installed\n",
|
||||||
|
"#!pip install sklearn-pandas\n",
|
||||||
|
"from sklearn_pandas import DataFrameMapper\n",
|
||||||
|
"\n",
|
||||||
|
"# Impute, standardize the numeric features and one-hot encode the categorical features. \n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"numeric_transformations = [([f], Pipeline(steps=[('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler())])) for f in numerical]\n",
|
||||||
|
"\n",
|
||||||
|
"categorical_transformations = [([f], OneHotEncoder(handle_unknown='ignore', sparse=False)) for f in categorical]\n",
|
||||||
|
"\n",
|
||||||
|
"transformations = numeric_transformations + categorical_transformations\n",
|
||||||
|
"\n",
|
||||||
|
"# Append classifier to preprocessing pipeline.\n",
|
||||||
|
"# Now we have a full prediction pipeline.\n",
|
||||||
|
"clf = Pipeline(steps=[('preprocessor', transformations),\n",
|
||||||
|
" ('classifier', SVC(kernel='linear', C = 1.0, probability=True))]) \n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"'''"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Train a SVM classification model, which you want to explain"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"model = clf.fit(x_train, y_train)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Explain predictions on your local machine"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# 1. Using SHAP TabularExplainer\n",
|
||||||
|
"# clf.steps[-1][1] returns the trained classification model\n",
|
||||||
|
"explainer = TabularExplainer(clf.steps[-1][1], \n",
|
||||||
|
" initialization_examples=x_train, \n",
|
||||||
|
" features=attritionXData.columns, \n",
|
||||||
|
" classes=[\"Not leaving\", \"leaving\"], \n",
|
||||||
|
" transformations=transformations)\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"# 2. Using MimicExplainer\n",
|
||||||
|
"# augment_data is optional and if true, oversamples the initialization examples to improve surrogate model accuracy to fit original model. Useful for high-dimensional data where the number of rows is less than the number of columns. \n",
|
||||||
|
"# max_num_of_augmentations is optional and defines max number of times we can increase the input data size.\n",
|
||||||
|
"# LGBMExplainableModel can be replaced with LinearExplainableModel, SGDExplainableModel, or DecisionTreeExplainableModel\n",
|
||||||
|
"# explainer = MimicExplainer(clf.steps[-1][1], \n",
|
||||||
|
"# x_train, \n",
|
||||||
|
"# LGBMExplainableModel, \n",
|
||||||
|
"# augment_data=True, \n",
|
||||||
|
"# max_num_of_augmentations=10, \n",
|
||||||
|
"# features=attritionXData.columns, \n",
|
||||||
|
"# classes=[\"Not leaving\", \"leaving\"], \n",
|
||||||
|
"# transformations=transformations)\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"# 3. Using PFIExplainer\n",
|
||||||
|
"\n",
|
||||||
|
"# Use the parameter \"metric\" to pass a metric name or function to evaluate the permutation. \n",
|
||||||
|
"# Note that if a metric function is provided a higher value must be better.\n",
|
||||||
|
"# Otherwise, take the negative of the function or set the parameter \"is_error_metric\" to True.\n",
|
||||||
|
"# Default metrics: \n",
|
||||||
|
"# F1 Score for binary classification, F1 Score with micro average for multiclass classification and\n",
|
||||||
|
"# Mean absolute error for regression\n",
|
||||||
|
"\n",
|
||||||
|
"# explainer = PFIExplainer(clf.steps[-1][1], \n",
|
||||||
|
"# features=x_train.columns, \n",
|
||||||
|
"# transformations=transformations,\n",
|
||||||
|
"# classes=[\"Not leaving\", \"leaving\"])"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Generate global explanations\n",
|
||||||
|
"Explain overall model predictions (global explanation)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Passing in test dataset for evaluation examples - note it must be a representative sample of the original data\n",
|
||||||
|
"# x_train can be passed as well, but with more examples explanations will take longer although they may be more accurate\n",
|
||||||
|
"global_explanation = explainer.explain_global(x_test)\n",
|
||||||
|
"\n",
|
||||||
|
"# Note: if you used the PFIExplainer in the previous step, use the next line of code instead\n",
|
||||||
|
"# global_explanation = explainer.explain_global(x_test, true_labels=y_test)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Sorted SHAP values\n",
|
||||||
|
"print('ranked global importance values: {}'.format(global_explanation.get_ranked_global_values()))\n",
|
||||||
|
"# Corresponding feature names\n",
|
||||||
|
"print('ranked global importance names: {}'.format(global_explanation.get_ranked_global_names()))\n",
|
||||||
|
"# Feature ranks (based on original order of features)\n",
|
||||||
|
"print('global importance rank: {}'.format(global_explanation.global_importance_rank))\n",
|
||||||
|
"\n",
|
||||||
|
"# Note: PFIExplainer does not support per class explanations\n",
|
||||||
|
"# Per class feature names\n",
|
||||||
|
"print('ranked per class feature names: {}'.format(global_explanation.get_ranked_per_class_names()))\n",
|
||||||
|
"# Per class feature importance values\n",
|
||||||
|
"print('ranked per class feature values: {}'.format(global_explanation.get_ranked_per_class_values()))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Print out a dictionary that holds the sorted feature importance names and values\n",
|
||||||
|
"print('global importance rank: {}'.format(global_explanation.get_feature_importance_dict()))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Explain overall model predictions as a collection of local (instance-level) explanations"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# feature shap values for all features and all data points in the training data\n",
|
||||||
|
"print('local importance values: {}'.format(global_explanation.local_importance_values))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Generate local explanations\n",
|
||||||
|
"Explain local data points (individual instances)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Note: PFIExplainer does not support local explanations\n",
|
||||||
|
"# You can pass a specific data point or a group of data points to the explain_local function\n",
|
||||||
|
"\n",
|
||||||
|
"# E.g., Explain the first data point in the test set\n",
|
||||||
|
"instance_num = 1\n",
|
||||||
|
"local_explanation = explainer.explain_local(x_test[:instance_num])"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Get the prediction for the first member of the test set and explain why model made that prediction\n",
|
||||||
|
"prediction_value = clf.predict(x_test)[instance_num]\n",
|
||||||
|
"\n",
|
||||||
|
"sorted_local_importance_values = local_explanation.get_ranked_local_values()[prediction_value]\n",
|
||||||
|
"sorted_local_importance_names = local_explanation.get_ranked_local_names()[prediction_value]\n",
|
||||||
|
"\n",
|
||||||
|
"print('local importance values: {}'.format(sorted_local_importance_values))\n",
|
||||||
|
"print('local importance names: {}'.format(sorted_local_importance_names))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Upload\n",
|
||||||
|
"Upload explanations to Azure Machine Learning Run History"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"import azureml.core\n",
|
||||||
|
"from azureml.core import Workspace, Experiment, Run\n",
|
||||||
|
"from azureml.explain.model.tabular_explainer import TabularExplainer\n",
|
||||||
|
"from azureml.contrib.explain.model.explanation.explanation_client import ExplanationClient\n",
|
||||||
|
"# Check core SDK version number\n",
|
||||||
|
"print(\"SDK version:\", azureml.core.VERSION)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"ws = Workspace.from_config()\n",
|
||||||
|
"print('Workspace name: ' + ws.name, \n",
|
||||||
|
" 'Azure region: ' + ws.location, \n",
|
||||||
|
" 'Subscription id: ' + ws.subscription_id, \n",
|
||||||
|
" 'Resource group: ' + ws.resource_group, sep = '\\n')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"experiment_name = 'explain_model'\n",
|
||||||
|
"experiment = Experiment(ws, experiment_name)\n",
|
||||||
|
"run = experiment.start_logging()\n",
|
||||||
|
"client = ExplanationClient.from_run(run)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Uploading model explanation data for storage or visualization in webUX\n",
|
||||||
|
"# The explanation can then be downloaded on any compute\n",
|
||||||
|
"# Multiple explanations can be uploaded\n",
|
||||||
|
"client.upload_model_explanation(global_explanation, comment='global explanation: all features')\n",
|
||||||
|
"# Or you can only upload the explanation object with the top k feature info\n",
|
||||||
|
"#client.upload_model_explanation(global_explanation, top_k=2, comment='global explanation: Only top 2 features')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Uploading model explanation data for storage or visualization in webUX\n",
|
||||||
|
"# The explanation can then be downloaded on any compute\n",
|
||||||
|
"# Multiple explanations can be uploaded\n",
|
||||||
|
"client.upload_model_explanation(local_explanation, comment='local explanation for test point 1: all features')\n",
|
||||||
|
"\n",
|
||||||
|
"# Alterntively, you can only upload the local explanation object with the top k feature info\n",
|
||||||
|
"#client.upload_model_explanation(local_explanation, top_k=2, comment='local explanation: top 2 features')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Download\n",
|
||||||
|
"Download explanations from Azure Machine Learning Run History"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# List uploaded explanations\n",
|
||||||
|
"client.list_model_explanations()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"for explanation in client.list_model_explanations():\n",
|
||||||
|
" \n",
|
||||||
|
" if explanation['comment'] == 'local explanation for test point 1: all features':\n",
|
||||||
|
" downloaded_local_explanation = client.download_model_explanation(explanation_id=explanation['id'])\n",
|
||||||
|
" # You can pass a k value to only download the top k feature importance values\n",
|
||||||
|
" downloaded_local_explanation_top2 = client.download_model_explanation(top_k=2, explanation_id=explanation['id'])\n",
|
||||||
|
" \n",
|
||||||
|
" \n",
|
||||||
|
" elif explanation['comment'] == 'global explanation: all features':\n",
|
||||||
|
" downloaded_global_explanation = client.download_model_explanation(explanation_id=explanation['id'])\n",
|
||||||
|
" # You can pass a k value to only download the top k feature importance values\n",
|
||||||
|
" downloaded_global_explanation_top2 = client.download_model_explanation(top_k=2, explanation_id=explanation['id'])\n",
|
||||||
|
" "
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Visualize\n",
|
||||||
|
"Load the visualization dashboard"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from azureml.contrib.explain.model.visualize import ExplanationDashboard"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"ExplanationDashboard(downloaded_global_explanation, model, x_test)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Next\n",
|
||||||
|
"Learn about other use cases of the explain package on a:\n",
|
||||||
|
"1. [Training time: regression problem](../../tabular-data/explain-binary-classification-local.ipynb) \n",
|
||||||
|
"1. [Training time: binary classification problem](../../tabular-data/explain-binary-classification-local.ipynb)\n",
|
||||||
|
"1. [Training time: multiclass classification problem](../../tabular-data/explain-multiclass-classification-local.ipynb)\n",
|
||||||
|
"1. Explain models with engineered features:\n",
|
||||||
|
" 1. [Simple feature transformations](../../tabular-data/simple-feature-transformations-explain-local.ipynb)\n",
|
||||||
|
" 1. [Advanced feature transformations](../../tabular-data/advanced-feature-transformations-explain-local.ipynb)\n",
|
||||||
|
"1. [Run explainers remotely on Azure Machine Learning Compute (AMLCompute)](../remote-explanation/explain-model-on-amlcompute.ipynb)\n",
|
||||||
|
"1. Inferencing time: deploy a classification model and explainer:\n",
|
||||||
|
" 1. [Deploy a locally-trained model and explainer](../scoring-time/train-explain-model-locally-and-deploy.ipynb)\n",
|
||||||
|
" 1. [Deploy a remotely-trained model and explainer](../scoring-time/train-explain-model-on-amlcompute-and-deploy.ipynb)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"authors": [
|
||||||
|
{
|
||||||
|
"name": "mesameki"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 3.6",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python36"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"codemirror_mode": {
|
||||||
|
"name": "ipython",
|
||||||
|
"version": 3
|
||||||
|
},
|
||||||
|
"file_extension": ".py",
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython3",
|
||||||
|
"version": "3.6.8"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 2
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user