Compare commits

...

6 Commits

Author SHA1 Message Date
Shivani Santosh Sambare
0ce37dd18f updating spark notebook 2021-07-26 15:51:54 -07:00
Cody
d835b183a5 update README.md (#1552) 2021-07-15 10:43:22 -07:00
Cody
d3cafebff9 add code of conduct (#1551) 2021-07-15 08:08:44 -07:00
Harneet Virk
354b194a25 Merge pull request #1543 from Azure/release_update/Release-106
update samples from Release-106 as a part of  SDK release
2021-07-06 11:05:55 -07:00
amlrelsa-ms
a52d67bb84 update samples from Release-106 as a part of SDK release 2021-07-06 17:17:27 +00:00
Harneet Virk
421ea3d920 Merge pull request #1530 from Azure/release_update/Release-105
update samples from Release-105 as a part of  SDK release
2021-06-25 09:58:05 -07:00
43 changed files with 815 additions and 346 deletions

9
CODE_OF_CONDUCT.md Normal file
View File

@@ -0,0 +1,9 @@
# Microsoft Open Source Code of Conduct
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
Resources:
- [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/)
- [Microsoft Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/)
- Contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with questions or concerns

View File

@@ -1,77 +1,43 @@
# Azure Machine Learning service example notebooks
# Azure Machine Learning Python SDK notebooks
> a community-driven repository of examples using mlflow for tracking can be found at https://github.com/Azure/azureml-examples
This repository contains example notebooks demonstrating the [Azure Machine Learning](https://azure.microsoft.com/services/machine-learning-service/) Python SDK which allows you to build, train, deploy and manage machine learning solutions using Azure. The AML SDK allows you the choice of using local or cloud compute resources, while managing and maintaining the complete data science workflow from the cloud.
Welcome to the Azure Machine Learning Python SDK notebooks repository!
![Azure ML Workflow](https://raw.githubusercontent.com/MicrosoftDocs/azure-docs/master/articles/machine-learning/media/concept-azure-machine-learning-architecture/workflow.png)
## Getting started
These notebooks are recommended for use in an Azure Machine Learning [Compute Instance](https://docs.microsoft.com/azure/machine-learning/concept-compute-instance), where you can run them without any additional set up.
## Quick installation
```sh
pip install azureml-sdk
```
Read more detailed instructions on [how to set up your environment](./NBSETUP.md) using Azure Notebook service, your own Jupyter notebook server, or Docker.
However, the notebooks can be run in any development environment with the correct `azureml` packages installed.
## How to navigate and use the example notebooks?
If you are using an Azure Machine Learning Notebook VM, you are all set. Otherwise, you should always run the [Configuration](./configuration.ipynb) notebook first when setting up a notebook library on a new machine or in a new environment. It configures your notebook library to connect to an Azure Machine Learning workspace, and sets up your workspace and compute to be used by many of the other examples.
This [index](./index.md) should assist in navigating the Azure Machine Learning notebook samples and encourage efficient retrieval of topics and content.
If you want to...
* ...try out and explore Azure ML, start with image classification tutorials: [Part 1 (Training)](./tutorials/image-classification-mnist-data/img-classification-part1-training.ipynb) and [Part 2 (Deployment)](./tutorials/image-classification-mnist-data/img-classification-part2-deploy.ipynb).
* ...learn about experimentation and tracking run history: [track and monitor experiments](./how-to-use-azureml/track-and-monitor-experiments).
* ...train deep learning models at scale, first learn about [Machine Learning Compute](./how-to-use-azureml/training/train-on-amlcompute/train-on-amlcompute.ipynb), and then try [distributed hyperparameter tuning](./how-to-use-azureml/ml-frameworks/pytorch/train-hyperparameter-tune-deploy-with-pytorch/train-hyperparameter-tune-deploy-with-pytorch.ipynb) and [distributed training](./how-to-use-azureml/ml-frameworks/pytorch/distributed-pytorch-with-horovod/distributed-pytorch-with-horovod.ipynb).
* ...deploy models as a realtime scoring service, first learn the basics by [deploying to Azure Container Instance](./how-to-use-azureml/deployment/deploy-to-cloud/model-register-and-deploy.ipynb), then learn how to [production deploy models on Azure Kubernetes Cluster](./how-to-use-azureml/deployment/production-deploy-to-aks/production-deploy-to-aks.ipynb).
* ...deploy models as a batch scoring service: [create Machine Learning Compute for scoring compute](./how-to-use-azureml/training/train-on-amlcompute/train-on-amlcompute.ipynb) and [use Machine Learning Pipelines to deploy your model](https://aka.ms/pl-batch-scoring).
* ...monitor your deployed models, learn about using [App Insights](./how-to-use-azureml/deployment/enable-app-insights-in-production-service/enable-app-insights-in-production-service.ipynb).
## Tutorials
The [Tutorials](./tutorials) folder contains notebooks for the tutorials described in the [Azure Machine Learning documentation](https://aka.ms/aml-docs).
## How to use Azure ML
The [How to use Azure ML](./how-to-use-azureml) folder contains specific examples demonstrating the features of the Azure Machine Learning SDK
- [Training](./how-to-use-azureml/training) - Examples of how to build models using Azure ML's logging and execution capabilities on local and remote compute targets
- [Training with ML and DL frameworks](./how-to-use-azureml/ml-frameworks) - Examples demonstrating how to build and train machine learning models at scale on Azure ML and perform hyperparameter tuning.
- [Manage Azure ML Service](./how-to-use-azureml/manage-azureml-service) - Examples how to perform tasks, such as authenticate against Azure ML service in different ways.
- [Automated Machine Learning](./how-to-use-azureml/automated-machine-learning) - Examples using Automated Machine Learning to automatically generate optimal machine learning pipelines and models
- [Machine Learning Pipelines](./how-to-use-azureml/machine-learning-pipelines) - Examples showing how to create and use reusable pipelines for training and batch scoring
- [Deployment](./how-to-use-azureml/deployment) - Examples showing how to deploy and manage machine learning models and solutions
- [Azure Databricks](./how-to-use-azureml/azure-databricks) - Examples showing how to use Azure ML with Azure Databricks
- [Reinforcement Learning](./how-to-use-azureml/reinforcement-learning) - Examples showing how to train reinforcement learning agents
---
## Documentation
* Quickstarts, end-to-end tutorials, and how-tos on the [official documentation site for Azure Machine Learning service](https://docs.microsoft.com/en-us/azure/machine-learning/service/).
* [Python SDK reference](https://docs.microsoft.com/en-us/python/api/overview/azure/ml/intro?view=azure-ml-py)
* Azure ML Data Prep SDK [overview](https://aka.ms/data-prep-sdk), [Python SDK reference](https://aka.ms/aml-data-prep-apiref), and [tutorials and how-tos](https://aka.ms/aml-data-prep-notebooks).
---
## Community Repository
Visit this [community repository](https://github.com/microsoft/MLOps/tree/master/examples) to find useful end-to-end sample notebooks. Also, please follow these [contribution guidelines](https://github.com/microsoft/MLOps/blob/master/contributing.md) when contributing to this repository.
## Projects using Azure Machine Learning
Visit following repos to see projects contributed by Azure ML users:
- [Learn about Natural Language Processing best practices using Azure Machine Learning service](https://github.com/microsoft/nlp)
- [Pre-Train BERT models using Azure Machine Learning service](https://github.com/Microsoft/AzureML-BERT)
- [Fashion MNIST with Azure ML SDK](https://github.com/amynic/azureml-sdk-fashion)
- [UMass Amherst Student Samples](https://github.com/katiehouse3/microsoft-azure-ml-notebooks) - A number of end-to-end machine learning notebooks, including machine translation, image classification, and customer churn, created by students in the 696DS course at UMass Amherst.
## Data/Telemetry
This repository collects usage data and sends it to Microsoft to help improve our products and services. Read Microsoft's [privacy statement to learn more](https://privacy.microsoft.com/en-US/privacystatement)
To opt out of tracking, please go to the raw markdown or .ipynb files and remove the following line of code:
Install the `azureml.core` Python package:
```sh
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/README.png)"
pip install azureml-core
```
This URL will be slightly different depending on the file.
![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/README.png)
Install additional packages as needed:
```sh
pip install azureml-mlflow
pip install azureml-dataset-runtime
pip install azureml-automl-runtime
pip install azureml-pipeline
pip install azureml-pipeline-steps
...
```
We recommend starting with one of the [quickstarts](tutorials/compute-instance-quickstarts).
## Contributing
This repository is a push-only mirror. Pull requests are ignored.
## Code of Conduct
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). Please see the [code of conduct](CODE_OF_CONDUCT.md) for details.
## Reference
- [Documentation](https://docs.microsoft.com/azure/machine-learning)

View File

@@ -103,7 +103,7 @@
"source": [
"import azureml.core\n",
"\n",
"print(\"This notebook was created using version 1.31.0 of the Azure ML SDK\")\n",
"print(\"This notebook was created using version 1.32.0 of the Azure ML SDK\")\n",
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
]
},

View File

@@ -49,7 +49,7 @@
"* `fairlearn>=0.6.2` (pre-v0.5.0 will work with minor modifications)\n",
"* `joblib`\n",
"* `liac-arff`\n",
"* `raiwidgets==0.4.0`\n",
"* `raiwidgets~=0.7.0`\n",
"\n",
"Fairlearn relies on features introduced in v0.22.1 of `scikit-learn`. If you have an older version already installed, please uncomment and run the following cell:"
]

View File

@@ -6,4 +6,4 @@ dependencies:
- fairlearn>=0.6.2
- joblib
- liac-arff
- raiwidgets==0.4.0
- raiwidgets~=0.7.0

View File

@@ -51,7 +51,7 @@
"* `fairlearn>=0.6.2` (also works for pre-v0.5.0 with slight modifications)\n",
"* `joblib`\n",
"* `liac-arff`\n",
"* `raiwidgets==0.4.0`\n",
"* `raiwidgets~=0.7.0`\n",
"\n",
"Fairlearn relies on features introduced in v0.22.1 of `scikit-learn`. If you have an older version already installed, please uncomment and run the following cell:"
]

View File

@@ -6,4 +6,4 @@ dependencies:
- fairlearn>=0.6.2
- joblib
- liac-arff
- raiwidgets==0.4.0
- raiwidgets~=0.7.0

View File

@@ -2,7 +2,7 @@ name: azure_automl
dependencies:
# The python interpreter version.
# Currently Azure ML only supports 3.5.2 and later.
- pip==20.2.4
- pip==21.1.2
- python>=3.5.2,<3.8
- nb_conda
- boto3==1.15.18
@@ -21,8 +21,8 @@ dependencies:
- pip:
# Required packages for AzureML execution, history, and data preparation.
- azureml-widgets~=1.31.0
- azureml-widgets~=1.32.0
- pytorch-transformers==1.0.0
- spacy==2.1.8
- https://aka.ms/automl-resources/packages/en_core_web_sm-2.1.0.tar.gz
- -r https://automlresources-prod.azureedge.net/validated-requirements/1.31.0/validated_win32_requirements.txt [--no-deps]
- -r https://automlresources-prod.azureedge.net/validated-requirements/1.32.0/validated_win32_requirements.txt [--no-deps]

View File

@@ -2,7 +2,7 @@ name: azure_automl
dependencies:
# The python interpreter version.
# Currently Azure ML only supports 3.5.2 and later.
- pip==20.2.4
- pip==21.1.2
- python>=3.5.2,<3.8
- nb_conda
- boto3==1.15.18
@@ -21,8 +21,8 @@ dependencies:
- pip:
# Required packages for AzureML execution, history, and data preparation.
- azureml-widgets~=1.31.0
- azureml-widgets~=1.32.0
- pytorch-transformers==1.0.0
- spacy==2.1.8
- https://aka.ms/automl-resources/packages/en_core_web_sm-2.1.0.tar.gz
- -r https://automlresources-prod.azureedge.net/validated-requirements/1.31.0/validated_linux_requirements.txt [--no-deps]
- -r https://automlresources-prod.azureedge.net/validated-requirements/1.32.0/validated_linux_requirements.txt [--no-deps]

View File

@@ -2,7 +2,7 @@ name: azure_automl
dependencies:
# The python interpreter version.
# Currently Azure ML only supports 3.5.2 and later.
- pip==20.2.4
- pip==21.1.2
- nomkl
- python>=3.5.2,<3.8
- nb_conda
@@ -22,8 +22,8 @@ dependencies:
- pip:
# Required packages for AzureML execution, history, and data preparation.
- azureml-widgets~=1.31.0
- azureml-widgets~=1.32.0
- pytorch-transformers==1.0.0
- spacy==2.1.8
- https://aka.ms/automl-resources/packages/en_core_web_sm-2.1.0.tar.gz
- -r https://automlresources-prod.azureedge.net/validated-requirements/1.31.0/validated_darwin_requirements.txt [--no-deps]
- -r https://automlresources-prod.azureedge.net/validated-requirements/1.32.0/validated_darwin_requirements.txt [--no-deps]

View File

@@ -105,7 +105,7 @@
"metadata": {},
"outputs": [],
"source": [
"print(\"This notebook was created using version 1.31.0 of the Azure ML SDK\")\n",
"print(\"This notebook was created using version 1.32.0 of the Azure ML SDK\")\n",
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
]
},
@@ -190,7 +190,7 @@
" compute_target = ComputeTarget(workspace=ws, name=cpu_cluster_name)\n",
" print('Found existing cluster, use it.')\n",
"except ComputeTargetException:\n",
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_D2_V2',\n",
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_DS12_V2',\n",
" max_nodes=6)\n",
" compute_target = ComputeTarget.create(ws, cpu_cluster_name, compute_config)\n",
"\n",

View File

@@ -93,7 +93,7 @@
"metadata": {},
"outputs": [],
"source": [
"print(\"This notebook was created using version 1.31.0 of the Azure ML SDK\")\n",
"print(\"This notebook was created using version 1.32.0 of the Azure ML SDK\")\n",
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
]
},

View File

@@ -96,7 +96,7 @@
"metadata": {},
"outputs": [],
"source": [
"print(\"This notebook was created using version 1.31.0 of the Azure ML SDK\")\n",
"print(\"This notebook was created using version 1.32.0 of the Azure ML SDK\")\n",
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
]
},
@@ -162,7 +162,7 @@
" compute_target = ComputeTarget(workspace=ws, name=amlcompute_cluster_name)\n",
" print('Found existing cluster, use it.')\n",
"except ComputeTargetException:\n",
" compute_config = AmlCompute.provisioning_configuration(vm_size = \"STANDARD_NC6\", # CPU for BiLSTM, such as \"STANDARD_D2_V2\" \n",
" compute_config = AmlCompute.provisioning_configuration(vm_size = \"STANDARD_NC6\", # CPU for BiLSTM, such as \"STANDARD_DS12_V2\" \n",
" # To use BERT (this is recommended for best performance), select a GPU such as \"STANDARD_NC6\" \n",
" # or similar GPU option\n",
" # available in your workspace\n",

View File

@@ -81,7 +81,7 @@
"metadata": {},
"outputs": [],
"source": [
"print(\"This notebook was created using version 1.31.0 of the Azure ML SDK\")\n",
"print(\"This notebook was created using version 1.32.0 of the Azure ML SDK\")\n",
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
]
},
@@ -166,7 +166,7 @@
" compute_target = ComputeTarget(workspace=ws, name=amlcompute_cluster_name)\n",
" print('Found existing cluster, use it.')\n",
"except ComputeTargetException:\n",
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_D2_V2',\n",
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_DS12_V2',\n",
" max_nodes=4)\n",
" compute_target = ComputeTarget.create(ws, amlcompute_cluster_name, compute_config)\n",
"\n",

View File

@@ -92,7 +92,7 @@
"metadata": {},
"outputs": [],
"source": [
"print(\"This notebook was created using version 1.31.0 of the Azure ML SDK\")\n",
"print(\"This notebook was created using version 1.32.0 of the Azure ML SDK\")\n",
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
]
},

View File

@@ -91,7 +91,7 @@
"metadata": {},
"outputs": [],
"source": [
"print(\"This notebook was created using version 1.31.0 of the Azure ML SDK\")\n",
"print(\"This notebook was created using version 1.32.0 of the Azure ML SDK\")\n",
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
]
},
@@ -143,7 +143,7 @@
" compute_target = ComputeTarget(workspace=ws, name=cpu_cluster_name)\n",
" print('Found existing cluster, use it.')\n",
"except ComputeTargetException:\n",
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_D2_V2',\n",
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_DS12_V2',\n",
" max_nodes=4)\n",
" compute_target = ComputeTarget.create(ws, cpu_cluster_name, compute_config)\n",
"\n",

View File

@@ -113,7 +113,7 @@
"metadata": {},
"outputs": [],
"source": [
"print(\"This notebook was created using version 1.31.0 of the Azure ML SDK\")\n",
"print(\"This notebook was created using version 1.32.0 of the Azure ML SDK\")\n",
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
]
},
@@ -187,7 +187,7 @@
" compute_target = ComputeTarget(workspace=ws, name=cpu_cluster_name)\n",
" print('Found existing cluster, use it.')\n",
"except ComputeTargetException:\n",
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_D2_V2',\n",
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_DS12_V2',\n",
" max_nodes=4)\n",
" compute_target = ComputeTarget.create(ws, cpu_cluster_name, compute_config)\n",
"\n",
@@ -662,7 +662,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.7"
"version": "3.6.9"
}
},
"nbformat": 4,

View File

@@ -87,7 +87,7 @@
"metadata": {},
"outputs": [],
"source": [
"print(\"This notebook was created using version 1.31.0 of the Azure ML SDK\")\n",
"print(\"This notebook was created using version 1.32.0 of the Azure ML SDK\")\n",
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
]
},
@@ -154,7 +154,7 @@
" compute_target = ComputeTarget(workspace=ws, name=amlcompute_cluster_name)\n",
" print('Found existing cluster, use it.')\n",
"except ComputeTargetException:\n",
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_D2_V2',\n",
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_DS12_V2',\n",
" max_nodes=4)\n",
" compute_target = ComputeTarget.create(ws, amlcompute_cluster_name, compute_config)\n",
"\n",

View File

@@ -24,10 +24,11 @@
"_**Forecasting using the Energy Demand Dataset**_\n",
"\n",
"## Contents\n",
"1. [Introduction](#Introduction)\n",
"1. [Setup](#Setup)\n",
"1. [Data and Forecasting Configurations](#Data)\n",
"1. [Train](#Train)\n",
"1. [Introduction](#introduction)\n",
"1. [Setup](#setup)\n",
"1. [Data and Forecasting Configurations](#data)\n",
"1. [Train](#train)\n",
"1. [Generate and Evaluate the Forecast](#forecast)\n",
"\n",
"Advanced Forecasting\n",
"1. [Advanced Training](#advanced_training)\n",
@@ -38,7 +39,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"## Introduction\n",
"# Introduction<a id=\"introduction\"></a>\n",
"\n",
"In this example we use the associated New York City energy demand dataset to showcase how you can use AutoML for a simple forecasting problem and explore the results. The goal is predict the energy demand for the next 48 hours based on historic time-series data.\n",
"\n",
@@ -49,15 +50,16 @@
"1. Configure AutoML using 'AutoMLConfig'\n",
"1. Train the model using AmlCompute\n",
"1. Explore the engineered features and results\n",
"1. Generate the forecast and compute the out-of-sample accuracy metrics\n",
"1. Configuration and remote run of AutoML for a time-series model with lag and rolling window features\n",
"1. Run and explore the forecast"
"1. Run and explore the forecast with lagging features"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Setup"
"# Setup<a id=\"setup\"></a>"
]
},
{
@@ -97,7 +99,7 @@
"metadata": {},
"outputs": [],
"source": [
"print(\"This notebook was created using version 1.31.0 of the Azure ML SDK\")\n",
"print(\"This notebook was created using version 1.32.0 of the Azure ML SDK\")\n",
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
]
},
@@ -177,7 +179,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"# Data\n",
"# Data<a id=\"data\"></a>\n",
"\n",
"We will use energy consumption [data from New York City](http://mis.nyiso.com/public/P-58Blist.htm) for model training. The data is stored in a tabular format and includes energy demand and basic weather data at an hourly frequency. \n",
"\n",
@@ -309,7 +311,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"## Train\n",
"# Train<a id=\"train\"></a>\n",
"\n",
"Instantiate an AutoMLConfig object. This config defines the settings and data used to run the experiment. We can provide extra configurations within 'automl_settings', for this forecasting task we add the forecasting parameters to hold all the additional forecasting parameters.\n",
"\n",
@@ -451,9 +453,11 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"## Forecasting\n",
"# Forecasting<a id=\"forecast\"></a>\n",
"\n",
"Now that we have retrieved the best pipeline/model, it can be used to make predictions on test data. First, we remove the target values from the test set:"
"Now that we have retrieved the best pipeline/model, it can be used to make predictions on test data. We will do batch scoring on the test dataset which should have the same schema as training dataset.\n",
"\n",
"The inference will run on a remote compute. In this example, it will re-use the training compute."
]
},
{
@@ -462,16 +466,15 @@
"metadata": {},
"outputs": [],
"source": [
"X_test = test.to_pandas_dataframe().reset_index(drop=True)\n",
"y_test = X_test.pop(target_column_name).values"
"test_experiment = Experiment(ws, experiment_name + \"_inference\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Forecast Function\n",
"For forecasting, we will use the forecast function instead of the predict function. Using the predict method would result in getting predictions for EVERY horizon the forecaster can predict at. This is useful when training and evaluating the performance of the forecaster at various horizons, but the level of detail is excessive for normal use. Forecast function also can handle more complicated scenarios, see the [forecast function notebook](../forecasting-forecast-function/auto-ml-forecasting-function.ipynb)."
"### Retreiving forecasts from the model\n",
"We have created a function called `run_forecast` that submits the test data to the best model determined during the training run and retrieves forecasts. This function uses a helper script `forecasting_script` which is uploaded and expecuted on the remote compute."
]
},
{
@@ -480,10 +483,16 @@
"metadata": {},
"outputs": [],
"source": [
"# The featurized data, aligned to y, will also be returned.\n",
"# This contains the assumptions that were made in the forecast\n",
"# and helps align the forecast to the original data\n",
"y_predictions, X_trans = fitted_model.forecast(X_test)"
"from run_forecast import run_remote_inference\n",
"remote_run_infer = run_remote_inference(test_experiment=test_experiment,\n",
" compute_target=compute_target,\n",
" train_run=best_run,\n",
" test_dataset=test,\n",
" target_column_name=target_column_name)\n",
"remote_run_infer.wait_for_completion(show_output=False)\n",
"\n",
"# download the inference output file to the local machine\n",
"remote_run_infer.download_file('outputs/predictions.csv', 'predictions.csv')"
]
},
{
@@ -491,9 +500,7 @@
"metadata": {},
"source": [
"### Evaluate\n",
"To evaluate the accuracy of the forecast, we'll compare against the actual sales quantities for some select metrics, included the mean absolute percentage error (MAPE). For more metrics that can be used for evaluation after training, please see [supported metrics](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-understand-automated-ml#regressionforecasting-metrics), and [how to calculate residuals](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-understand-automated-ml#residuals).\n",
"\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."
"To evaluate the accuracy of the forecast, we'll compare against the actual sales quantities for some select metrics, included the mean absolute percentage error (MAPE). For more metrics that can be used for evaluation after training, please see [supported metrics](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-understand-automated-ml#regressionforecasting-metrics), and [how to calculate residuals](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-understand-automated-ml#residuals)."
]
},
{
@@ -502,9 +509,9 @@
"metadata": {},
"outputs": [],
"source": [
"from forecasting_helper import align_outputs\n",
"\n",
"df_all = align_outputs(y_predictions, X_trans, X_test, y_test, target_column_name)"
"# load forecast data frame\n",
"fcst_df = pd.read_csv('predictions.csv', parse_dates=[time_column_name])\n",
"fcst_df.head()"
]
},
{
@@ -519,8 +526,8 @@
"\n",
"# use automl metrics module\n",
"scores = scoring.score_regression(\n",
" y_test=df_all[target_column_name],\n",
" y_pred=df_all['predicted'],\n",
" y_test=fcst_df[target_column_name],\n",
" y_pred=fcst_df['predicted'],\n",
" metrics=list(constants.Metric.SCALAR_REGRESSION_SET))\n",
"\n",
"print(\"[Test data scores]\\n\")\n",
@@ -529,8 +536,8 @@
" \n",
"# Plot outputs\n",
"%matplotlib inline\n",
"test_pred = plt.scatter(df_all[target_column_name], df_all['predicted'], color='b')\n",
"test_test = plt.scatter(df_all[target_column_name], df_all[target_column_name], color='g')\n",
"test_pred = plt.scatter(fcst_df[target_column_name], fcst_df['predicted'], color='b')\n",
"test_test = plt.scatter(fcst_df[target_column_name], fcst_df[target_column_name], color='g')\n",
"plt.legend((test_pred, test_test), ('prediction', 'truth'), loc='upper left', fontsize=8)\n",
"plt.show()"
]
@@ -539,23 +546,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"Looking at `X_trans` is also useful to see what featurization happened to the data."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"X_trans"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Advanced Training <a id=\"advanced_training\"></a>\n",
"# Advanced Training <a id=\"advanced_training\"></a>\n",
"We did not use lags in the previous model specification. In effect, the prediction was the result of a simple regression on date, time series identifier columns and any additional features. This is often a very good prediction as common time series patterns like seasonality and trends can be captured in this manner. Such simple regression is horizon-less: it doesn't matter how far into the future we are predicting, because we are not using past data. In the previous example, the horizon was only used to split the data for cross-validation."
]
},
@@ -638,7 +629,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"## Advanced Results<a id=\"advanced_results\"></a>\n",
"# Advanced Results<a id=\"advanced_results\"></a>\n",
"We did not use lags in the previous model specification. In effect, the prediction was the result of a simple regression on date, time series identifier columns and any additional features. This is often a very good prediction as common time series patterns like seasonality and trends can be captured in this manner. Such simple regression is horizon-less: it doesn't matter how far into the future we are predicting, because we are not using past data. In the previous example, the horizon was only used to split the data for cross-validation."
]
},
@@ -648,10 +639,17 @@
"metadata": {},
"outputs": [],
"source": [
"# The featurized data, aligned to y, will also be returned.\n",
"# This contains the assumptions that were made in the forecast\n",
"# and helps align the forecast to the original data\n",
"y_predictions, X_trans = fitted_model_lags.forecast(X_test)"
"test_experiment_advanced = Experiment(ws, experiment_name + \"_inference_advanced\")\n",
"advanced_remote_run_infer = run_remote_inference(test_experiment=test_experiment_advanced,\n",
" compute_target=compute_target,\n",
" train_run=best_run_lags,\n",
" test_dataset=test,\n",
" target_column_name=target_column_name,\n",
" inference_folder='./forecast_advanced')\n",
"advanced_remote_run_infer.wait_for_completion(show_output=False)\n",
"\n",
"# download the inference output file to the local machine\n",
"advanced_remote_run_infer.download_file('outputs/predictions.csv', 'predictions_advanced.csv')"
]
},
{
@@ -660,9 +658,8 @@
"metadata": {},
"outputs": [],
"source": [
"from forecasting_helper import align_outputs\n",
"\n",
"df_all = align_outputs(y_predictions, X_trans, X_test, y_test, target_column_name)"
"fcst_adv_df = pd.read_csv('predictions_advanced.csv', parse_dates=[time_column_name])\n",
"fcst_adv_df.head()"
]
},
{
@@ -677,8 +674,8 @@
"\n",
"# use automl metrics module\n",
"scores = scoring.score_regression(\n",
" y_test=df_all[target_column_name],\n",
" y_pred=df_all['predicted'],\n",
" y_test=fcst_adv_df[target_column_name],\n",
" y_pred=fcst_adv_df['predicted'],\n",
" metrics=list(constants.Metric.SCALAR_REGRESSION_SET))\n",
"\n",
"print(\"[Test data scores]\\n\")\n",
@@ -687,8 +684,8 @@
" \n",
"# Plot outputs\n",
"%matplotlib inline\n",
"test_pred = plt.scatter(df_all[target_column_name], df_all['predicted'], color='b')\n",
"test_test = plt.scatter(df_all[target_column_name], df_all[target_column_name], color='g')\n",
"test_pred = plt.scatter(fcst_adv_df[target_column_name], fcst_adv_df['predicted'], color='b')\n",
"test_test = plt.scatter(fcst_adv_df[target_column_name], fcst_adv_df[target_column_name], color='g')\n",
"plt.legend((test_pred, test_test), ('prediction', 'truth'), loc='upper left', fontsize=8)\n",
"plt.show()"
]
@@ -719,7 +716,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.8"
"version": "3.6.9"
}
},
"nbformat": 4,

View File

@@ -1,5 +1,15 @@
"""
This is the script that is executed on the compute instance. It relies
on the model.pkl file which is uploaded along with this script to the
compute instance.
"""
import argparse
import pandas as pd
import numpy as np
from azureml.core import Dataset, Run
from azureml.automl.core.shared.constants import TimeSeriesInternal
from sklearn.externals import joblib
from pandas.tseries.frequencies import to_offset
@@ -42,3 +52,38 @@ def align_outputs(y_predicted, X_trans, X_test, y_test, target_column_name,
clean = together[together[[target_column_name,
predicted_column_name]].notnull().all(axis=1)]
return(clean)
parser = argparse.ArgumentParser()
parser.add_argument(
'--target_column_name', type=str, dest='target_column_name',
help='Target Column Name')
parser.add_argument(
'--test_dataset', type=str, dest='test_dataset',
help='Test Dataset')
args = parser.parse_args()
target_column_name = args.target_column_name
test_dataset_id = args.test_dataset
run = Run.get_context()
ws = run.experiment.workspace
# get the input dataset by id
test_dataset = Dataset.get_by_id(ws, id=test_dataset_id)
X_test = test_dataset.to_pandas_dataframe().reset_index(drop=True)
y_test = X_test.pop(target_column_name).values
# generate forecast
fitted_model = joblib.load('model.pkl')
y_predictions, X_trans = fitted_model.forecast(X_test)
# align output
df_all = align_outputs(y_predictions, X_trans, X_test, y_test, target_column_name)
file_name = 'outputs/predictions.csv'
export_csv = df_all.to_csv(file_name, header=True, index=False) # added Index
# Upload the predictions into artifacts
run.upload_file(name=file_name, path_or_stream=file_name)

View File

@@ -1,22 +0,0 @@
import pandas as pd
import numpy as np
def APE(actual, pred):
"""
Calculate absolute percentage error.
Returns a vector of APE values with same length as actual/pred.
"""
return 100 * np.abs((actual - pred) / actual)
def MAPE(actual, pred):
"""
Calculate mean absolute percentage error.
Remove NA and values where actual is close to zero
"""
not_na = ~(np.isnan(actual) | np.isnan(pred))
not_zero = ~np.isclose(actual, 0.0)
actual_safe = actual[not_na & not_zero]
pred_safe = pred[not_na & not_zero]
return np.mean(APE(actual_safe, pred_safe))

View File

@@ -0,0 +1,38 @@
import os
import shutil
from azureml.core import ScriptRunConfig
def run_remote_inference(test_experiment, compute_target, train_run,
test_dataset, target_column_name, inference_folder='./forecast'):
# Create local directory to copy the model.pkl and forecsting_script.py files into.
# These files will be uploaded to and executed on the compute instance.
os.makedirs(inference_folder, exist_ok=True)
shutil.copy('forecasting_script.py', inference_folder)
train_run.download_file('outputs/model.pkl',
os.path.join(inference_folder, 'model.pkl'))
inference_env = train_run.get_environment()
config = ScriptRunConfig(source_directory=inference_folder,
script='forecasting_script.py',
arguments=['--target_column_name',
target_column_name,
'--test_dataset',
test_dataset.as_named_input(test_dataset.name)],
compute_target=compute_target,
environment=inference_env)
run = test_experiment.submit(config,
tags={'training_run_id':
train_run.id,
'run_algorithm':
train_run.properties['run_algorithm'],
'valid_score':
train_run.properties['score'],
'primary_metric':
train_run.properties['primary_metric']})
run.log("run_algorithm", run.tags['run_algorithm'])
return run

View File

@@ -94,7 +94,7 @@
"metadata": {},
"outputs": [],
"source": [
"print(\"This notebook was created using version 1.31.0 of the Azure ML SDK\")\n",
"print(\"This notebook was created using version 1.32.0 of the Azure ML SDK\")\n",
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
]
},
@@ -285,7 +285,7 @@
" compute_target = ComputeTarget(workspace=ws, name=amlcompute_cluster_name)\n",
" print('Found existing cluster, use it.')\n",
"except ComputeTargetException:\n",
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_D2_V2',\n",
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_DS12_V2',\n",
" max_nodes=6)\n",
" compute_target = ComputeTarget.create(ws, amlcompute_cluster_name, compute_config)\n",
"\n",

View File

@@ -24,20 +24,20 @@
"_**Orange Juice Sales Forecasting**_\n",
"\n",
"## Contents\n",
"1. [Introduction](#Introduction)\n",
"1. [Setup](#Setup)\n",
"1. [Compute](#Compute)\n",
"1. [Data](#Data)\n",
"1. [Train](#Train)\n",
"1. [Predict](#Predict)\n",
"1. [Operationalize](#Operationalize)"
"1. [Introduction](#introduction)\n",
"1. [Setup](#setup)\n",
"1. [Compute](#compute)\n",
"1. [Data](#data)\n",
"1. [Train](#train)\n",
"1. [Forecast](#forecast)\n",
"1. [Operationalize](#operationalize)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Introduction\n",
"## Introduction<a id=\"introduction\"></a>\n",
"In this example, we use AutoML to train, select, and operationalize a time-series forecasting model for multiple time-series.\n",
"\n",
"Make sure you have executed the [configuration notebook](../../../configuration.ipynb) before running this notebook.\n",
@@ -49,7 +49,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"## Setup"
"## Setup<a id=\"setup\"></a>"
]
},
{
@@ -82,7 +82,7 @@
"metadata": {},
"outputs": [],
"source": [
"print(\"This notebook was created using version 1.31.0 of the Azure ML SDK\")\n",
"print(\"This notebook was created using version 1.32.0 of the Azure ML SDK\")\n",
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
]
},
@@ -122,7 +122,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"## Compute\n",
"## Compute<a id=\"compute\"></a>\n",
"You will need to create a [compute target](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-set-up-training-targets#amlcompute) for your AutoML run. In this tutorial, you create AmlCompute as your training compute resource.\n",
"\n",
"> Note that if you have an AzureML Data Scientist role, you will not have permission to create compute resources. Talk to your workspace or IT admin to create the compute targets described in this section, if they do not already exist.\n",
@@ -149,7 +149,7 @@
" compute_target = ComputeTarget(workspace=ws, name=amlcompute_cluster_name)\n",
" print('Found existing cluster, use it.')\n",
"except ComputeTargetException:\n",
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_D2_V2',\n",
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_D12_V2',\n",
" max_nodes=6)\n",
" compute_target = ComputeTarget.create(ws, amlcompute_cluster_name, compute_config)\n",
"\n",
@@ -160,7 +160,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"## Data\n",
"## Data<a id=\"data\"></a>\n",
"You are now ready to load the historical orange juice sales data. We will load the CSV file into a plain pandas DataFrame; the time column in the CSV is called _WeekStarting_, so it will be specially parsed into the datetime type."
]
},
@@ -287,7 +287,8 @@
"outputs": [],
"source": [
"from azureml.core.dataset import Dataset\n",
"train_dataset = Dataset.Tabular.from_delimited_files(path=datastore.path('dataset/dominicks_OJ_train.csv'))"
"train_dataset = Dataset.Tabular.from_delimited_files(path=datastore.path('dataset/dominicks_OJ_train.csv'))\n",
"test_dataset = Dataset.Tabular.from_delimited_files(path=datastore.path('dataset/dominicks_OJ_test.csv'))"
]
},
{
@@ -380,7 +381,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"## Train\n",
"## Train<a id=\"train\"></a>\n",
"\n",
"The [AutoMLConfig](https://docs.microsoft.com/en-us/python/api/azureml-train-automl-client/azureml.train.automl.automlconfig.automlconfig?view=azure-ml-py) object defines the settings and data for an AutoML training job. Here, we set necessary inputs like the task type, the number of AutoML iterations to try, the training data, and cross-validation parameters.\n",
"\n",
@@ -521,9 +522,11 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"# Forecasting\n",
"# Forecast<a id=\"forecast\"></a>\n",
"\n",
"Now that we have retrieved the best pipeline/model, it can be used to make predictions on test data. First, we remove the target values from the test set:"
"Now that we have retrieved the best pipeline/model, it can be used to make predictions on test data. We will do batch scoring on the test dataset which should have the same schema as training dataset.\n",
"\n",
"The inference will run on a remote compute. In this example, it will re-use the training compute."
]
},
{
@@ -532,17 +535,15 @@
"metadata": {},
"outputs": [],
"source": [
"X_test = test\n",
"y_test = X_test.pop(target_column_name).values"
"test_experiment = Experiment(ws, experiment_name + \"_inference\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"cell_type": "markdown",
"metadata": {},
"outputs": [],
"source": [
"X_test.head()"
"### Retreiving forecasts from the model\n",
"We have created a function called `run_forecast` that submits the test data to the best model determined during the training run and retrieves forecasts. This function uses a helper script `forecasting_script` which is uploaded and expecuted on the remote compute."
]
},
{
@@ -558,18 +559,16 @@
"metadata": {},
"outputs": [],
"source": [
"# forecast returns the predictions and the featurized data, aligned to X_test.\n",
"# This contains the assumptions that were made in the forecast\n",
"y_predictions, X_trans = fitted_model.forecast(X_test)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If you are used to scikit pipelines, perhaps you expected `predict(X_test)`. However, forecasting requires a more general interface that also supplies the past target `y` values. Please use `forecast(X,y)` as `predict(X)` is reserved for internal purposes on forecasting models.\n",
"from run_forecast import run_remote_inference\n",
"remote_run_infer = run_remote_inference(test_experiment=test_experiment, \n",
" compute_target=compute_target,\n",
" train_run=best_run,\n",
" test_dataset=test_dataset,\n",
" target_column_name=target_column_name)\n",
"remote_run_infer.wait_for_completion(show_output=False)\n",
"\n",
"The [forecast function notebook](../forecasting-forecast-function/auto-ml-forecasting-function.ipynb)."
"# download the forecast file to the local machine\n",
"remote_run_infer.download_file('outputs/predictions.csv', 'predictions.csv')"
]
},
{
@@ -589,8 +588,9 @@
"metadata": {},
"outputs": [],
"source": [
"assign_dict = {'predicted': y_predictions, target_column_name: y_test}\n",
"df_all = X_test.assign(**assign_dict)"
"# load forecast data frame\n",
"fcst_df = pd.read_csv('predictions.csv', parse_dates=[time_column_name])\n",
"fcst_df.head()"
]
},
{
@@ -605,8 +605,8 @@
"\n",
"# use automl scoring module\n",
"scores = scoring.score_regression(\n",
" y_test=df_all[target_column_name],\n",
" y_pred=df_all['predicted'],\n",
" y_test=fcst_df[target_column_name],\n",
" y_pred=fcst_df['predicted'],\n",
" metrics=list(constants.Metric.SCALAR_REGRESSION_SET))\n",
"\n",
"print(\"[Test data scores]\\n\")\n",
@@ -615,8 +615,8 @@
" \n",
"# Plot outputs\n",
"%matplotlib inline\n",
"test_pred = plt.scatter(df_all[target_column_name], df_all['predicted'], color='b')\n",
"test_test = plt.scatter(df_all[target_column_name], df_all[target_column_name], color='g')\n",
"test_pred = plt.scatter(fcst_df[target_column_name], fcst_df['predicted'], color='b')\n",
"test_test = plt.scatter(fcst_df[target_column_name], fcst_df[target_column_name], color='g')\n",
"plt.legend((test_pred, test_test), ('prediction', 'truth'), loc='upper left', fontsize=8)\n",
"plt.show()"
]
@@ -625,7 +625,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"# Operationalize"
"# Operationalize<a id=\"operationalize\"></a>"
]
},
{
@@ -723,7 +723,8 @@
"outputs": [],
"source": [
"import json\n",
"X_query = X_test.copy()\n",
"X_query = test.copy()\n",
"X_query.pop(target_column_name)\n",
"# We have to convert datetime to string, because Timestamps cannot be serialized to JSON.\n",
"X_query[time_column_name] = X_query[time_column_name].astype(str)\n",
"# The Service object accept the complex dictionary, which is internally converted to JSON string.\n",
@@ -805,7 +806,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.8"
"version": "3.6.9"
},
"tags": [
"None"

View File

@@ -0,0 +1,89 @@
"""
This is the script that is executed on the compute instance. It relies
on the model.pkl file which is uploaded along with this script to the
compute instance.
"""
import argparse
import pandas as pd
import numpy as np
from azureml.core import Dataset, Run
from azureml.automl.core.shared.constants import TimeSeriesInternal
from sklearn.externals import joblib
from pandas.tseries.frequencies import to_offset
def align_outputs(y_predicted, X_trans, X_test, y_test, target_column_name,
predicted_column_name='predicted',
horizon_colname='horizon_origin'):
"""
Demonstrates how to get the output aligned to the inputs
using pandas indexes. Helps understand what happened if
the output's shape differs from the input shape, or if
the data got re-sorted by time and grain during forecasting.
Typical causes of misalignment are:
* we predicted some periods that were missing in actuals -> drop from eval
* model was asked to predict past max_horizon -> increase max horizon
* data at start of X_test was needed for lags -> provide previous periods
"""
if (horizon_colname in X_trans):
df_fcst = pd.DataFrame({predicted_column_name: y_predicted,
horizon_colname: X_trans[horizon_colname]})
else:
df_fcst = pd.DataFrame({predicted_column_name: y_predicted})
# y and X outputs are aligned by forecast() function contract
df_fcst.index = X_trans.index
# align original X_test to y_test
X_test_full = X_test.copy()
X_test_full[target_column_name] = y_test
# X_test_full's index does not include origin, so reset for merge
df_fcst.reset_index(inplace=True)
X_test_full = X_test_full.reset_index().drop(columns='index')
together = df_fcst.merge(X_test_full, how='right')
# drop rows where prediction or actuals are nan
# happens because of missing actuals
# or at edges of time due to lags/rolling windows
clean = together[together[[target_column_name,
predicted_column_name]].notnull().all(axis=1)]
return(clean)
parser = argparse.ArgumentParser()
parser.add_argument(
'--target_column_name', type=str, dest='target_column_name',
help='Target Column Name')
parser.add_argument(
'--test_dataset', type=str, dest='test_dataset',
help='Test Dataset')
args = parser.parse_args()
target_column_name = args.target_column_name
test_dataset_id = args.test_dataset
run = Run.get_context()
ws = run.experiment.workspace
# get the input dataset by id
test_dataset = Dataset.get_by_id(ws, id=test_dataset_id)
X_test = test_dataset.to_pandas_dataframe().reset_index(drop=True)
y_test = X_test.pop(target_column_name).values
# generate forecast
fitted_model = joblib.load('model.pkl')
y_predictions, X_trans = fitted_model.forecast(X_test)
# align output
df_all = align_outputs(y_predictions, X_trans, X_test, y_test, target_column_name)
file_name = 'outputs/predictions.csv'
export_csv = df_all.to_csv(file_name, header=True, index=False) # added Index
# Upload the predictions into artifacts
run.upload_file(name=file_name, path_or_stream=file_name)

View File

@@ -0,0 +1,38 @@
import os
import shutil
from azureml.core import ScriptRunConfig
def run_remote_inference(test_experiment, compute_target, train_run,
test_dataset, target_column_name, inference_folder='./forecast'):
# Create local directory to copy the model.pkl and forecsting_script.py files into.
# These files will be uploaded to and executed on the compute instance.
os.makedirs(inference_folder, exist_ok=True)
shutil.copy('forecasting_script.py', inference_folder)
train_run.download_file('outputs/model.pkl',
os.path.join(inference_folder, 'model.pkl'))
inference_env = train_run.get_environment()
config = ScriptRunConfig(source_directory=inference_folder,
script='forecasting_script.py',
arguments=['--target_column_name',
target_column_name,
'--test_dataset',
test_dataset.as_named_input(test_dataset.name)],
compute_target=compute_target,
environment=inference_env)
run = test_experiment.submit(config,
tags={'training_run_id':
train_run.id,
'run_algorithm':
train_run.properties['run_algorithm'],
'valid_score':
train_run.properties['score'],
'primary_metric':
train_run.properties['primary_metric']})
run.log("run_algorithm", run.tags['run_algorithm'])
return run

View File

@@ -96,7 +96,7 @@
"metadata": {},
"outputs": [],
"source": [
"print(\"This notebook was created using version 1.31.0 of the Azure ML SDK\")\n",
"print(\"This notebook was created using version 1.32.0 of the Azure ML SDK\")\n",
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
]
},

View File

@@ -96,7 +96,7 @@
"metadata": {},
"outputs": [],
"source": [
"print(\"This notebook was created using version 1.31.0 of the Azure ML SDK\")\n",
"print(\"This notebook was created using version 1.32.0 of the Azure ML SDK\")\n",
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
]
},
@@ -154,7 +154,7 @@
" compute_target = ComputeTarget(workspace=ws, name=amlcompute_cluster_name)\n",
" print('Found existing cluster, use it.')\n",
"except ComputeTargetException:\n",
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_D2_V2',\n",
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_DS12_V2',\n",
" max_nodes=4)\n",
" compute_target = ComputeTarget.create(ws, amlcompute_cluster_name, compute_config)\n",
"\n",

View File

@@ -92,7 +92,7 @@
"metadata": {},
"outputs": [],
"source": [
"print(\"This notebook was created using version 1.31.0 of the Azure ML SDK\")\n",
"print(\"This notebook was created using version 1.32.0 of the Azure ML SDK\")\n",
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
]
},
@@ -145,7 +145,7 @@
" compute_target = ComputeTarget(workspace=ws, name=cpu_cluster_name)\n",
" print('Found existing cluster, use it.')\n",
"except ComputeTargetException:\n",
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_D2_V2',\n",
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_DS12_V2',\n",
" max_nodes=4)\n",
" compute_target = ComputeTarget.create(ws, cpu_cluster_name, compute_config)\n",
"\n",

View File

@@ -42,6 +42,31 @@
"## Leverage ScriptRunConfig to submit scala job to an attached synapse spark cluster"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Prepare data"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.core.datastore import Datastore\n",
"# Use the default blob storage\n",
"def_blob_store = Datastore(ws, \"workspaceblobstore\")\n",
"\n",
"# We are uploading a sample file in the local directory to be used as a datasource\n",
"file_name = \"shakespeare.txt\"\n",
"def_blob_store.upload_files(files=[\"./{}\".format(file_name)], overwrite=False)\n",
"\n",
"# Create file dataset\n",
"file_dataset = Dataset.File.from_files(path=[(def_blob_store, file_name)])"
]
},
{
"cell_type": "code",
"execution_count": null,
@@ -59,11 +84,11 @@
"run_config.spark.configuration[\"spark.executor.memory\"] = \"2g\"\n",
"run_config.spark.configuration[\"spark.executor.cores\"] = 1\n",
"run_config.spark.configuration[\"spark.executor.instances\"] = 1\n",
"\n",
"run_config.spark.configuration[\"spark.yarn.dist.jars\"]=\"wasbs://synapse@azuremlexamples.blob.core.windows.net/shared/wordcount.jar\" # this can be removed if you are using local jars in source folder\n",
"# This can be removed if you are using local jars in source folder\n",
"run_config.spark.configuration[\"spark.yarn.dist.jars\"]=\"wasbs://synapse@azuremlexamples.blob.core.windows.net/shared/wordcount.jar\"\n",
"\n",
"dir_name = \"wordcount-{}\".format(str(uuid.uuid4()))\n",
"input = \"wasbs://synapse@azuremlexamples.blob.core.windows.net/shared/shakespeare.txt\"\n",
"input = file_dataset.as_named_input(\"input\").as_hdfs()\n",
"output = HDFSOutputDatasetConfig(destination=(ws.get_default_datastore(), \"{}/result\".format(dir_name)))\n",
"\n",
"from azureml.core import ScriptRunConfig\n",
@@ -103,9 +128,10 @@
"from azureml.pipeline.steps import SynapseSparkStep\n",
"\n",
"configs = {}\n",
"configs[\"spark.yarn.dist.jars\"] = \"wasbs://synapse@azuremlexamples.blob.core.windows.net/shared/wordcount.jar\"\n",
"#configs[\"spark.yarn.dist.jars\"] = \"wasbs://synapse@azuremlexamples.blob.core.windows.net/shared/wordcount.jar\"\n",
"step_1 = SynapseSparkStep(name = 'synapse-spark',\n",
" file = 'start_script.py',\n",
" jars = \"wasbs://synapse@azuremlexamples.blob.core.windows.net/shared/wordcount.jar\",\n",
" source_directory=\".\",\n",
" arguments = args,\n",
" compute_target = 'link-pool',\n",

View File

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

View File

@@ -2,23 +2,22 @@
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
"\n",
"Licensed under the MIT License."
]
],
"metadata": {}
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/deployment/deploy-to-cloud/model-register-and-deploy.png)"
]
],
"metadata": {}
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Register Spark Model and deploy as Webservice\n",
"\n",
@@ -26,120 +25,128 @@
"\n",
" 1. Register Spark Model\n",
" 2. Deploy Spark Model as Webservice"
]
],
"metadata": {}
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Prerequisites\n",
"If you are using an Azure Machine Learning Notebook VM, you are all set. Otherwise, make sure you go through the [configuration](../../../configuration.ipynb) Notebook first if you haven't."
]
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Check core SDK version number\n",
"import azureml.core\n",
"\n",
"# Check core SDK version number\r\n",
"import azureml.core\r\n",
"\r\n",
"print(\"SDK version:\", azureml.core.VERSION)"
]
],
"outputs": [],
"metadata": {}
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Initialize Workspace\n",
"\n",
"Initialize a workspace object from persisted configuration."
]
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"from azureml.core import Workspace\r\n",
"\r\n",
"ws = Workspace.from_config()\r\n",
"print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep='\\n')"
],
"outputs": [],
"metadata": {
"tags": [
"create workspace"
]
},
"outputs": [],
"source": [
"from azureml.core import Workspace\n",
"\n",
"ws = Workspace.from_config()\n",
"print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep='\\n')"
]
}
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Register Model"
]
],
"metadata": {}
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can add tags and descriptions to your Models. Note you need to have a `iris.model` file in the current directory. This model file is generated using [train in spark](../training/train-in-spark/train-in-spark.ipynb) notebook. The below call registers that file as a Model with the same name `iris.model` in the workspace.\n",
"\n",
"Using tags, you can track useful information such as the name and version of the machine learning library used to train the model. Note that tags must be alphanumeric."
]
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"from azureml.core.model import Model\r\n",
"\r\n",
"model = Model.register(model_path=\"iris.model\",\r\n",
" model_name=\"iris.model\",\r\n",
" tags={'type': \"regression\"},\r\n",
" description=\"Logistic regression model to predict iris species\",\r\n",
" workspace=ws)"
],
"outputs": [],
"metadata": {
"tags": [
"register model from file"
]
},
"outputs": [],
"source": [
"from azureml.core.model import Model\n",
"\n",
"model = Model.register(model_path=\"iris.model\",\n",
" model_name=\"iris.model\",\n",
" tags={'type': \"regression\"},\n",
" description=\"Logistic regression model to predict iris species\",\n",
" workspace=ws)"
]
}
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Fetch Environment"
]
],
"metadata": {}
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can now create and/or use an Environment object when deploying a Webservice. The Environment can have been previously registered with your Workspace, or it will be registered with it as a part of the Webservice deployment.\n",
"\n",
"In this notebook, we will be using 'AzureML-PySpark-MmlSpark-0.15', a curated environment.\n",
"\n",
"More information can be found in our [using environments notebook](../training/using-environments/using-environments.ipynb)."
]
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.core import Environment\n",
"\n",
"env = Environment.get(ws, name='AzureML-PySpark-MmlSpark-0.15')\n"
]
"from azureml.core import Environment\r\n",
"from azureml.core.environment import SparkPackage\r\n",
"from azureml.core.conda_dependencies import CondaDependencies\r\n",
"\r\n",
"myenv = Environment('my-pyspark-environment')\r\n",
"myenv.docker.base_image = \"mcr.microsoft.com/mmlspark/release:0.15\"\r\n",
"myenv.inferencing_stack_version = \"latest\"\r\n",
"myenv.python.conda_dependencies = CondaDependencies.create(pip_packages=[\"azureml-core\",\"azureml-defaults\",\"azureml-telemetry\",\"azureml-train-restclients-hyperdrive\",\"azureml-train-core\"], python_version=\"3.6.2\")\r\n",
"myenv.python.conda_dependencies.add_channel(\"conda-forge\")\r\n",
"myenv.spark.packages = [SparkPackage(\"com.microsoft.ml.spark\", \"mmlspark_2.11\", \"0.15\"), SparkPackage(\"com.microsoft.azure\", \"azure-storage\", \"2.0.0\"), SparkPackage(\"org.apache.hadoop\", \"hadoop-azure\", \"2.7.0\")]\r\n",
"myenv.spark.repositories = [\"https://mmlspark.azureedge.net/maven\"]\r\n"
],
"outputs": [],
"metadata": {}
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Create Inference Configuration\n",
"\n",
@@ -157,109 +164,109 @@
" - source_directory = holds source path as string, this entire folder gets added in image so its really easy to access any files within this folder or subfolder\n",
" - entry_script = contains logic specific to initializing your model and running predictions\n",
" - environment = An environment object to use for the deployment. Doesn't have to be registered"
]
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"from azureml.core.model import InferenceConfig\r\n",
"\r\n",
"inference_config = InferenceConfig(entry_script=\"score.py\", environment=myenv)"
],
"outputs": [],
"metadata": {
"tags": [
"create image"
]
},
"outputs": [],
"source": [
"from azureml.core.model import InferenceConfig\n",
"\n",
"inference_config = InferenceConfig(entry_script=\"score.py\", environment=env)"
]
}
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Deploy Model as Webservice on Azure Container Instance\n",
"\n",
"Note that the service creation can take few minutes."
]
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"from azureml.core.webservice import AciWebservice, Webservice\r\n",
"from azureml.exceptions import WebserviceException\r\n",
"\r\n",
"deployment_config = AciWebservice.deploy_configuration(cpu_cores=1, memory_gb=1)\r\n",
"aci_service_name = 'aciservice1'\r\n",
"\r\n",
"try:\r\n",
" # if you want to get existing service below is the command\r\n",
" # since aci name needs to be unique in subscription deleting existing aci if any\r\n",
" # we use aci_service_name to create azure aci\r\n",
" service = Webservice(ws, name=aci_service_name)\r\n",
" if service:\r\n",
" service.delete()\r\n",
"except WebserviceException as e:\r\n",
" print()\r\n",
"\r\n",
"service = Model.deploy(ws, aci_service_name, [model], inference_config, deployment_config)\r\n",
"\r\n",
"service.wait_for_deployment(True)\r\n",
"print(service.state)"
],
"outputs": [],
"metadata": {
"tags": [
"azuremlexception-remarks-sample"
]
},
"outputs": [],
"source": [
"from azureml.core.webservice import AciWebservice, Webservice\n",
"from azureml.exceptions import WebserviceException\n",
"\n",
"deployment_config = AciWebservice.deploy_configuration(cpu_cores=1, memory_gb=1)\n",
"aci_service_name = 'aciservice1'\n",
"\n",
"try:\n",
" # if you want to get existing service below is the command\n",
" # since aci name needs to be unique in subscription deleting existing aci if any\n",
" # we use aci_service_name to create azure aci\n",
" service = Webservice(ws, name=aci_service_name)\n",
" if service:\n",
" service.delete()\n",
"except WebserviceException as e:\n",
" print()\n",
"\n",
"service = Model.deploy(ws, aci_service_name, [model], inference_config, deployment_config)\n",
"\n",
"service.wait_for_deployment(True)\n",
"print(service.state)"
]
}
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Test web service"
]
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import json\n",
"test_sample = json.dumps({'features':{'type':1,'values':[4.3,3.0,1.1,0.1]},'label':2.0})\n",
"\n",
"test_sample_encoded = bytes(test_sample, encoding='utf8')\n",
"prediction = service.run(input_data=test_sample_encoded)\n",
"import json\r\n",
"test_sample = json.dumps({'features':{'type':1,'values':[4.3,3.0,1.1,0.1]},'label':2.0})\r\n",
"\r\n",
"test_sample_encoded = bytes(test_sample, encoding='utf8')\r\n",
"prediction = service.run(input_data=test_sample_encoded)\r\n",
"print(prediction)"
]
],
"outputs": [],
"metadata": {}
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Delete ACI to clean up"
]
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"service.delete()"
],
"outputs": [],
"metadata": {
"tags": [
"deploy service",
"aci"
]
},
"outputs": [],
"source": [
"service.delete()"
]
}
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Model Profiling\n",
"\n",
@@ -271,11 +278,11 @@
"profiling_results = profile.get_results()\n",
"print(profiling_results)\n",
"```"
]
],
"metadata": {}
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Model Packaging\n",
"\n",
@@ -296,7 +303,8 @@
"package.wait_for_creation(show_output=True)\n",
"package.save(\"./local_context_dir\")\n",
"```"
]
],
"metadata": {}
}
],
"metadata": {

View File

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

View File

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

View File

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

View File

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

View File

@@ -148,7 +148,7 @@
" compute_target = ComputeTarget(workspace=ws, name=amlcompute_cluster_name)\n",
" print('Found existing cluster, use it.')\n",
"except ComputeTargetException:\n",
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_D2_V2',# for GPU, use \"STANDARD_NC6\"\n",
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_DS12_V2',# for GPU, use \"STANDARD_NC6\"\n",
" #vm_priority = 'lowpriority', # optional\n",
" max_nodes=4)\n",
" compute_target = ComputeTarget.create(ws, amlcompute_cluster_name, compute_config)\n",

View File

@@ -247,7 +247,7 @@
" aml_compute = ComputeTarget(workspace=ws, name=amlcompute_cluster_name)\n",
" print('Found existing cluster, use it.')\n",
"except ComputeTargetException:\n",
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_D2_V2',\n",
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_DS12_V2',\n",
" max_nodes=4)\n",
" aml_compute = ComputeTarget.create(ws, amlcompute_cluster_name, compute_config)\n",
"\n",

View File

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

View File

@@ -35,7 +35,7 @@
"source": [
"## Install required packages\n",
"\n",
"This notebook works with Fairlearn v0.6.1, but not with versions pre-v0.5.0. If needed, please uncomment and run the following cell:"
"This notebook works with Fairlearn v0.7.0, but not with versions pre-v0.5.0. If needed, please uncomment and run the following cell:"
]
},
{

View File

@@ -8,5 +8,5 @@ dependencies:
- matplotlib
- azureml-dataset-runtime
- ipywidgets
- raiwidgets==0.4.0
- raiwidgets~=0.7.0
- liac-arff

View File

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

View File

@@ -102,7 +102,7 @@
"source": [
"import azureml.core\n",
"\n",
"print(\"This notebook was created using version 1.31.0 of the Azure ML SDK\")\n",
"print(\"This notebook was created using version 1.32.0 of the Azure ML SDK\")\n",
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
]
},