diff --git a/configuration.ipynb b/configuration.ipynb index cf0b00a1..9bc1c3b4 100644 --- a/configuration.ipynb +++ b/configuration.ipynb @@ -103,7 +103,7 @@ "source": [ "import azureml.core\n", "\n", - "print(\"This notebook was created using version 1.4.0 of the Azure ML SDK\")\n", + "print(\"This notebook was created using version 1.5.0 of the Azure ML SDK\")\n", "print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")" ] }, diff --git a/how-to-use-azureml/automated-machine-learning/README.md b/how-to-use-azureml/automated-machine-learning/README.md index ec5aa15a..ec88126b 100644 --- a/how-to-use-azureml/automated-machine-learning/README.md +++ b/how-to-use-azureml/automated-machine-learning/README.md @@ -1,8 +1,8 @@ # Table of Contents 1. [Automated ML Introduction](#introduction) -1. [Setup using Azure Notebooks](#jupyter) -1. [Setup using Azure Databricks](#databricks) +1. [Setup using Compute Instances](#jupyter) 1. [Setup using a Local Conda environment](#localconda) +1. [Setup using Azure Databricks](#databricks) 1. [Automated ML SDK Sample Notebooks](#samples) 1. [Documentation](#documentation) 1. [Running using python command](#pythoncommand) @@ -21,13 +21,13 @@ Below are the three execution environments supported by automated ML. -## Setup using Notebook VMs - Jupyter based notebooks from a Azure VM +## Setup using Compute Instances - Jupyter based notebooks from a Azure Virtual Machine 1. Open the [ML Azure portal](https://ml.azure.com) 1. Select Compute -1. Select Notebook VMs +1. Select Compute Instances 1. Click New -1. Type a name for the Vm and select a VM type +1. Type a Compute Name, select a Virtual Machine type and select a Virtual Machine size 1. Click Create diff --git a/how-to-use-azureml/automated-machine-learning/automl_env_mac.yml b/how-to-use-azureml/automated-machine-learning/automl_env_mac.yml index 5759576d..501763bb 100644 --- a/how-to-use-azureml/automated-machine-learning/automl_env_mac.yml +++ b/how-to-use-azureml/automated-machine-learning/automl_env_mac.yml @@ -5,19 +5,18 @@ dependencies: - pip<=19.3.1 - nomkl - python>=3.5.2,<3.6.8 -- wheel==0.30.0 - nb_conda - matplotlib==2.1.0 - numpy>=1.16.0,<=1.16.2 - cython - urllib3<1.24 -- scipy>=1.0.0,<=1.1.0 +- scipy==1.4.1 - scikit-learn>=0.19.0,<=0.20.3 - pandas>=0.22.0,<0.23.0 - py-xgboost<=0.80 -- fbprophet==0.5 -- pytorch=1.1.0 -- cudatoolkit=9.0 +- conda-forge::fbprophet==0.5 +- pytorch::pytorch=1.4.0 +- cudatoolkit=10.1.243 - pip: # Required packages for AzureML execution, history, and data preparation. @@ -30,8 +29,3 @@ dependencies: - pytorch-transformers==1.0.0 - spacy==2.1.8 - https://aka.ms/automl-resources/packages/en_core_web_sm-2.1.0.tar.gz - -channels: -- anaconda -- conda-forge -- pytorch diff --git a/how-to-use-azureml/automated-machine-learning/automl_env.yml b/how-to-use-azureml/automated-machine-learning/automl_env_master.yml similarity index 51% rename from how-to-use-azureml/automated-machine-learning/automl_env.yml rename to how-to-use-azureml/automated-machine-learning/automl_env_master.yml index fdddb9d2..7608ab9b 100644 --- a/how-to-use-azureml/automated-machine-learning/automl_env.yml +++ b/how-to-use-azureml/automated-machine-learning/automl_env_master.yml @@ -1,36 +1,33 @@ -name: azure_automl +name: automl_env_master dependencies: # The python interpreter version. # Currently Azure ML only supports 3.5.2 and later. - pip<=19.3.1 - python>=3.5.2,<3.6.8 -- wheel==0.30.0 - nb_conda - matplotlib==2.1.0 - numpy>=1.16.0,<=1.16.2 - cython - urllib3<1.24 -- scipy>=1.0.0,<=1.1.0 +- scipy==1.4.1 - scikit-learn>=0.19.0,<=0.20.3 - pandas>=0.22.0,<=0.23.4 +- testpath=0.3.1 - py-xgboost<=0.90 -- fbprophet==0.5 -- pytorch=1.1.0 -- cudatoolkit=9.0 +- conda-forge::fbprophet==0.5 +- pytorch::pytorch=1.4.0 +- cudatoolkit=10.1.243 - pip: # Required packages for AzureML execution, history, and data preparation. - - azureml-defaults + - --extra-index-url https://azuremlsdktestpypi.azureedge.net/sdk-release/master/588E708E0DF342C4A80BD954289657CF + - --extra-index-url https://dataprepdownloads.azureedge.net/pypi/weekly-rc-932B96D048E011E8B56608/latest/ + - azureml-defaults<0.1.50 - azureml-dataprep[pandas] - - azureml-train-automl - - azureml-train - - azureml-widgets - - azureml-pipeline + - azureml-train-automl<0.1.50 + - azureml-train<0.1.50 + - azureml-widgets<0.1.50 + - azureml-pipeline<0.1.50 - pytorch-transformers==1.0.0 - spacy==2.1.8 - https://aka.ms/automl-resources/packages/en_core_web_sm-2.1.0.tar.gz - -channels: -- anaconda -- conda-forge -- pytorch diff --git a/how-to-use-azureml/automated-machine-learning/classification-bank-marketing-all-features/auto-ml-classification-bank-marketing-all-features.ipynb b/how-to-use-azureml/automated-machine-learning/classification-bank-marketing-all-features/auto-ml-classification-bank-marketing-all-features.ipynb index fbf773bc..324cbffa 100644 --- a/how-to-use-azureml/automated-machine-learning/classification-bank-marketing-all-features/auto-ml-classification-bank-marketing-all-features.ipynb +++ b/how-to-use-azureml/automated-machine-learning/classification-bank-marketing-all-features/auto-ml-classification-bank-marketing-all-features.ipynb @@ -41,7 +41,7 @@ "\n", "In this example we use the UCI Bank Marketing dataset to showcase how you can use AutoML for a classification problem and deploy it to an Azure Container Instance (ACI). The classification goal is to predict if the client will subscribe to a term deposit with the bank.\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", + "If you are using an Azure Machine Learning Compute Instance, you are all set. Otherwise, go through the [configuration](../../../configuration.ipynb) notebook first if you haven't already to establish your connection to the AzureML Workspace. \n", "\n", "Please find the ONNX related documentations [here](https://github.com/onnx/onnx).\n", "\n", @@ -105,7 +105,7 @@ "metadata": {}, "outputs": [], "source": [ - "print(\"This notebook was created using version 1.4.0 of the Azure ML SDK\")\n", + "print(\"This notebook was created using version 1.5.0 of the Azure ML SDK\")\n", "print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")" ] }, @@ -643,7 +643,7 @@ "\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*." + "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*." ] }, { diff --git a/how-to-use-azureml/automated-machine-learning/classification-credit-card-fraud/auto-ml-classification-credit-card-fraud.ipynb b/how-to-use-azureml/automated-machine-learning/classification-credit-card-fraud/auto-ml-classification-credit-card-fraud.ipynb index d8d91819..96cb9a45 100644 --- a/how-to-use-azureml/automated-machine-learning/classification-credit-card-fraud/auto-ml-classification-credit-card-fraud.ipynb +++ b/how-to-use-azureml/automated-machine-learning/classification-credit-card-fraud/auto-ml-classification-credit-card-fraud.ipynb @@ -42,7 +42,7 @@ "\n", "This notebook is using remote compute to train the model.\n", "\n", - "If you are using an Azure Machine Learning [Notebook VM](https://docs.microsoft.com/en-us/azure/machine-learning/service/tutorial-1st-experiment-sdk-setup), 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", + "If you are using an Azure Machine Learning Compute Instance, you are all set. Otherwise, go through the [configuration](../../../configuration.ipynb) notebook first if you haven't already to establish your connection to the AzureML Workspace. \n", "\n", "In this notebook you will learn how to:\n", "1. Create an experiment using an existing workspace.\n", @@ -93,7 +93,7 @@ "metadata": {}, "outputs": [], "source": [ - "print(\"This notebook was created using version 1.4.0 of the Azure ML SDK\")\n", + "print(\"This notebook was created using version 1.5.0 of the Azure ML SDK\")\n", "print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")" ] }, @@ -322,7 +322,7 @@ "\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*." + "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*." ] }, { diff --git a/how-to-use-azureml/automated-machine-learning/classification-text-dnn/auto-ml-classification-text-dnn.ipynb b/how-to-use-azureml/automated-machine-learning/classification-text-dnn/auto-ml-classification-text-dnn.ipynb index 3bc63650..13dd8cad 100644 --- a/how-to-use-azureml/automated-machine-learning/classification-text-dnn/auto-ml-classification-text-dnn.ipynb +++ b/how-to-use-azureml/automated-machine-learning/classification-text-dnn/auto-ml-classification-text-dnn.ipynb @@ -97,7 +97,7 @@ "metadata": {}, "outputs": [], "source": [ - "print(\"This notebook was created using version 1.4.0 of the Azure ML SDK\")\n", + "print(\"This notebook was created using version 1.5.0 of the Azure ML SDK\")\n", "print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")" ] }, diff --git a/how-to-use-azureml/automated-machine-learning/classification-text-dnn/infer.py b/how-to-use-azureml/automated-machine-learning/classification-text-dnn/infer.py index e316ca06..9f0e2977 100644 --- a/how-to-use-azureml/automated-machine-learning/classification-text-dnn/infer.py +++ b/how-to-use-azureml/automated-machine-learning/classification-text-dnn/infer.py @@ -2,8 +2,7 @@ import numpy as np import argparse from azureml.core import Run from sklearn.externals import joblib -from azureml.automl.core._vendor.automl.client.core.common import metrics -from automl.client.core.common import constants +from azureml.automl.core.shared import constants, metrics from azureml.core.model import Model diff --git a/how-to-use-azureml/automated-machine-learning/continuous-retraining/auto-ml-continuous-retraining.ipynb b/how-to-use-azureml/automated-machine-learning/continuous-retraining/auto-ml-continuous-retraining.ipynb index 7bcfc6c0..222d3e88 100644 --- a/how-to-use-azureml/automated-machine-learning/continuous-retraining/auto-ml-continuous-retraining.ipynb +++ b/how-to-use-azureml/automated-machine-learning/continuous-retraining/auto-ml-continuous-retraining.ipynb @@ -88,7 +88,7 @@ "metadata": {}, "outputs": [], "source": [ - "print(\"This notebook was created using version 1.4.0 of the Azure ML SDK\")\n", + "print(\"This notebook was created using version 1.5.0 of the Azure ML SDK\")\n", "print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")" ] }, diff --git a/how-to-use-azureml/automated-machine-learning/forecasting-beer-remote/auto-ml-forecasting-beer-remote.ipynb b/how-to-use-azureml/automated-machine-learning/forecasting-beer-remote/auto-ml-forecasting-beer-remote.ipynb index 708dd4bc..7848165f 100644 --- a/how-to-use-azureml/automated-machine-learning/forecasting-beer-remote/auto-ml-forecasting-beer-remote.ipynb +++ b/how-to-use-azureml/automated-machine-learning/forecasting-beer-remote/auto-ml-forecasting-beer-remote.ipynb @@ -114,7 +114,7 @@ "metadata": {}, "outputs": [], "source": [ - "print(\"This notebook was created using version 1.4.0 of the Azure ML SDK\")\n", + "print(\"This notebook was created using version 1.5.0 of the Azure ML SDK\")\n", "print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")" ] }, diff --git a/how-to-use-azureml/automated-machine-learning/forecasting-beer-remote/infer.py b/how-to-use-azureml/automated-machine-learning/forecasting-beer-remote/infer.py index 9b3a3171..40c9b371 100644 --- a/how-to-use-azureml/automated-machine-learning/forecasting-beer-remote/infer.py +++ b/how-to-use-azureml/automated-machine-learning/forecasting-beer-remote/infer.py @@ -4,8 +4,7 @@ import argparse from azureml.core import Run from sklearn.externals import joblib from sklearn.metrics import mean_absolute_error, mean_squared_error -from azureml.automl.core._vendor.automl.client.core.common import metrics -from automl.client.core.common import constants +from azureml.automl.core.shared import constants, metrics from pandas.tseries.frequencies import to_offset diff --git a/how-to-use-azureml/automated-machine-learning/forecasting-bike-share/auto-ml-forecasting-bike-share.ipynb b/how-to-use-azureml/automated-machine-learning/forecasting-bike-share/auto-ml-forecasting-bike-share.ipynb index 57f7b0e8..e1fb4412 100644 --- a/how-to-use-azureml/automated-machine-learning/forecasting-bike-share/auto-ml-forecasting-bike-share.ipynb +++ b/how-to-use-azureml/automated-machine-learning/forecasting-bike-share/auto-ml-forecasting-bike-share.ipynb @@ -87,7 +87,7 @@ "metadata": {}, "outputs": [], "source": [ - "print(\"This notebook was created using version 1.4.0 of the Azure ML SDK\")\n", + "print(\"This notebook was created using version 1.5.0 of the Azure ML SDK\")\n", "print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")" ] }, @@ -510,10 +510,9 @@ "metadata": {}, "outputs": [], "source": [ - "from azureml.automl.core._vendor.automl.client.core.common import metrics\n", + "from azureml.automl.core.shared import constants, metrics\n", "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", "from matplotlib import pyplot as plt\n", - "from automl.client.core.common import constants\n", "\n", "# use automl metrics module\n", "scores = metrics.compute_metrics_regression(\n", diff --git a/how-to-use-azureml/automated-machine-learning/forecasting-bike-share/forecasting_script.py b/how-to-use-azureml/automated-machine-learning/forecasting-bike-share/forecasting_script.py index f3fb7b89..ca951597 100644 --- a/how-to-use-azureml/automated-machine-learning/forecasting-bike-share/forecasting_script.py +++ b/how-to-use-azureml/automated-machine-learning/forecasting-bike-share/forecasting_script.py @@ -1,6 +1,6 @@ import argparse import azureml.train.automl -from azureml.automl.runtime._vendor.automl.client.core.runtime import forecasting_models +from azureml.automl.runtime.shared import forecasting_models from azureml.core import Run from sklearn.externals import joblib import forecasting_helper diff --git a/how-to-use-azureml/automated-machine-learning/forecasting-energy-demand/auto-ml-forecasting-energy-demand.ipynb b/how-to-use-azureml/automated-machine-learning/forecasting-energy-demand/auto-ml-forecasting-energy-demand.ipynb index a554a904..f439d348 100644 --- a/how-to-use-azureml/automated-machine-learning/forecasting-energy-demand/auto-ml-forecasting-energy-demand.ipynb +++ b/how-to-use-azureml/automated-machine-learning/forecasting-energy-demand/auto-ml-forecasting-energy-demand.ipynb @@ -42,7 +42,7 @@ "\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", - "If you are using an Azure Machine Learning [Notebook VM](https://docs.microsoft.com/en-us/azure/machine-learning/service/tutorial-1st-experiment-sdk-setup), 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.\n", + "If you are using an Azure Machine Learning Compute Instance, 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.\n", "\n", "In this notebook you will learn how to:\n", "1. Creating an Experiment using an existing Workspace\n", @@ -97,7 +97,7 @@ "metadata": {}, "outputs": [], "source": [ - "print(\"This notebook was created using version 1.4.0 of the Azure ML SDK\")\n", + "print(\"This notebook was created using version 1.5.0 of the Azure ML SDK\")\n", "print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")" ] }, @@ -507,9 +507,8 @@ "metadata": {}, "outputs": [], "source": [ - "from azureml.automl.core._vendor.automl.client.core.common import metrics\n", + "from azureml.automl.core.shared import constants, metrics\n", "from matplotlib import pyplot as plt\n", - "from automl.client.core.common import constants\n", "\n", "# use automl metrics module\n", "scores = metrics.compute_metrics_regression(\n", @@ -668,9 +667,8 @@ "metadata": {}, "outputs": [], "source": [ - "from azureml.automl.core._vendor.automl.client.core.common import metrics\n", + "from azureml.automl.core.shared import constants, metrics\n", "from matplotlib import pyplot as plt\n", - "from automl.client.core.common import constants\n", "\n", "# use automl metrics module\n", "scores = metrics.compute_metrics_regression(\n", diff --git a/how-to-use-azureml/automated-machine-learning/forecasting-high-frequency/auto-ml-forecasting-function.ipynb b/how-to-use-azureml/automated-machine-learning/forecasting-high-frequency/auto-ml-forecasting-function.ipynb index 5df787be..1c0e43ff 100644 --- a/how-to-use-azureml/automated-machine-learning/forecasting-high-frequency/auto-ml-forecasting-function.ipynb +++ b/how-to-use-azureml/automated-machine-learning/forecasting-high-frequency/auto-ml-forecasting-function.ipynb @@ -95,7 +95,7 @@ "metadata": {}, "outputs": [], "source": [ - "print(\"This notebook was created using version 1.4.0 of the Azure ML SDK\")\n", + "print(\"This notebook was created using version 1.5.0 of the Azure ML SDK\")\n", "print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")" ] }, diff --git a/how-to-use-azureml/automated-machine-learning/forecasting-orange-juice-sales/auto-ml-forecasting-orange-juice-sales.ipynb b/how-to-use-azureml/automated-machine-learning/forecasting-orange-juice-sales/auto-ml-forecasting-orange-juice-sales.ipynb index 4ceae6ca..f4f73dd0 100644 --- a/how-to-use-azureml/automated-machine-learning/forecasting-orange-juice-sales/auto-ml-forecasting-orange-juice-sales.ipynb +++ b/how-to-use-azureml/automated-machine-learning/forecasting-orange-juice-sales/auto-ml-forecasting-orange-juice-sales.ipynb @@ -82,7 +82,7 @@ "metadata": {}, "outputs": [], "source": [ - "print(\"This notebook was created using version 1.4.0 of the Azure ML SDK\")\n", + "print(\"This notebook was created using version 1.5.0 of the Azure ML SDK\")\n", "print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")" ] }, @@ -355,11 +355,18 @@ "source": [ "## Train\n", "\n", - "The AutoMLConfig object defines the settings and data for an AutoML training job. Here, we set necessary inputs like the task type, the number of AutoML iterations to try, the training data, and cross-validation parameters. \n", + "The [AutoMLConfig](https://docs.microsoft.com/en-us/python/api/azureml-train-automl-client/azureml.train.automl.automlconfig.automlconfig?view=azure-ml-py) object defines the settings and data for an AutoML training job. Here, we set necessary inputs like the task type, the number of AutoML iterations to try, the training data, and cross-validation parameters.\n", "\n", - "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 grain columns are 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", + "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 application that estimates the next month of sales should set the horizon according to suitable planning time-scales. 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", + "We note here that AutoML can sweep over two types of time-series models:\n", + "* Models that are trained for each series such as ARIMA and Facebook's Prophet. Note that these models are only available for [Enterprise Edition Workspaces](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-manage-workspace#upgrade).\n", + "* Models trained across multiple time-series using a regression approach.\n", + "\n", + "In the first case, AutoML loops over all time-series in your dataset and trains one model (e.g. AutoArima or Prophet, as the case may be) for each series. This can result in long runtimes to train these models if there are a lot of series in the data. One way to mitigate this problem is to fit models for different series in parallel if you have multiple compute cores available. To enable this behavior, set the `max_cores_per_iteration` parameter in your AutoMLConfig as shown in the example in the next cell. \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. 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", "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 *validation_data* parameter of AutoMLConfig.\n", "\n", @@ -381,7 +388,8 @@ "|**time_column_name**|Name of the datetime column in the input data|\n", "|**grain_column_names**|Name(s) of the columns defining individual series in the input data|\n", "|**max_horizon**|Maximum desired forecast horizon in units of time-series frequency|\n", - "|**featurization**| 'auto' / 'off' / FeaturizationConfig Indicator for whether featurization step should be done automatically or not, or whether customized featurization should be used. Setting this enables AutoML to perform featurization on the input to handle *missing data*, and to perform some common *feature extraction*.|" + "|**featurization**| 'auto' / 'off' / FeaturizationConfig Indicator for whether featurization step should be done automatically or not, or whether customized featurization should be used. Setting this enables AutoML to perform featurization on the input to handle *missing data*, and to perform some common *feature extraction*.|\n", + "|**max_cores_per_iteration**|Maximum number of cores to utilize per iteration. A value of -1 indicates all available cores should be used.|" ] }, { @@ -407,6 +415,7 @@ " featurization=featurization_config,\n", " n_cross_validations=3,\n", " verbosity=logging.INFO,\n", + " max_cores_per_iteration=-1,\n", " **time_series_settings)" ] }, @@ -536,7 +545,7 @@ "source": [ "If you are used to scikit pipelines, perhaps you expected `predict(X_test)`. However, forecasting requires a more general interface that also supplies the past target `y` values. Please use `forecast(X,y)` as `predict(X)` is reserved for internal purposes on forecasting models.\n", "\n", - "The [energy demand forecasting notebook](https://github.com/Azure/MachineLearningNotebooks/tree/master/how-to-use-azureml/automated-machine-learning/forecasting-energy-demand) demonstrates the use of the forecast function in more detail in the context of using lags and rolling window features. " + "The [forecast function notebook](https://github.com/Azure/MachineLearningNotebooks/blob/master/how-to-use-azureml/automated-machine-learning/forecasting-high-frequency/auto-ml-forecasting-function.ipynb) demonstrates the use of the forecast function for a variety of use cases. Also, please see the [API documentation for the forecast function](https://docs.microsoft.com/en-us/python/api/azureml-automl-runtime/azureml.automl.runtime.shared.model_wrappers.forecastingpipelinewrapper?view=azure-ml-py#forecast-x-pred--typing-union-pandas-core-frame-dataframe--nonetype----none--y-pred--typing-union-pandas-core-frame-dataframe--numpy-ndarray--nonetype----none--forecast-destination--typing-union-pandas--libs-tslibs-timestamps-timestamp--nonetype----none--ignore-data-errors--bool---false-----typing-tuple-numpy-ndarray--pandas-core-frame-dataframe-)." ] }, { @@ -567,9 +576,8 @@ "metadata": {}, "outputs": [], "source": [ - "from azureml.automl.core._vendor.automl.client.core.common import metrics\n", + "from azureml.automl.core.shared import constants, metrics\n", "from matplotlib import pyplot as plt\n", - "from automl.client.core.common import constants\n", "\n", "# use automl metrics module\n", "scores = metrics.compute_metrics_regression(\n", diff --git a/how-to-use-azureml/automated-machine-learning/local-run-classification-credit-card-fraud/auto-ml-classification-credit-card-fraud-local.ipynb b/how-to-use-azureml/automated-machine-learning/local-run-classification-credit-card-fraud/auto-ml-classification-credit-card-fraud-local.ipynb index 55f69373..9750a559 100644 --- a/how-to-use-azureml/automated-machine-learning/local-run-classification-credit-card-fraud/auto-ml-classification-credit-card-fraud-local.ipynb +++ b/how-to-use-azureml/automated-machine-learning/local-run-classification-credit-card-fraud/auto-ml-classification-credit-card-fraud-local.ipynb @@ -42,7 +42,7 @@ "\n", "This notebook is using the local machine compute to train the model.\n", "\n", - "If you are using an Azure Machine Learning [Notebook VM](https://docs.microsoft.com/en-us/azure/machine-learning/service/tutorial-1st-experiment-sdk-setup), 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", + "If you are using an Azure Machine Learning Compute Instance, you are all set. Otherwise, go through the [configuration](../../../configuration.ipynb) notebook first if you haven't already to establish your connection to the AzureML Workspace. \n", "\n", "In this notebook you will learn how to:\n", "1. Create an experiment using an existing workspace.\n", @@ -95,7 +95,7 @@ "metadata": {}, "outputs": [], "source": [ - "print(\"This notebook was created using version 1.4.0 of the Azure ML SDK\")\n", + "print(\"This notebook was created using version 1.5.0 of the Azure ML SDK\")\n", "print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")" ] }, diff --git a/how-to-use-azureml/automated-machine-learning/regression-explanation-featurization/auto-ml-regression-explanation-featurization.ipynb b/how-to-use-azureml/automated-machine-learning/regression-explanation-featurization/auto-ml-regression-explanation-featurization.ipynb index 4951f4f8..099b7539 100644 --- a/how-to-use-azureml/automated-machine-learning/regression-explanation-featurization/auto-ml-regression-explanation-featurization.ipynb +++ b/how-to-use-azureml/automated-machine-learning/regression-explanation-featurization/auto-ml-regression-explanation-featurization.ipynb @@ -40,7 +40,7 @@ "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", "After training AutoML models for this regression data set, we show how you can compute model explanations on your remote compute using a sample explainer script.\n", "\n", - "If you are using an Azure Machine Learning Notebook VM, you are all set. Otherwise, go through the [configuration](../../../configuration.ipynb) notebook first if you haven't already to establish your connection to the AzureML Workspace. \n", + "If you are using an Azure Machine Learning Compute Instance, you are all set. Otherwise, go through the [configuration](../../../configuration.ipynb) notebook first if you haven't already to establish your connection to the AzureML Workspace. \n", "\n", "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/azure/machine-learning/service/concept-workspace#upgrade) \n", "\n", @@ -98,7 +98,7 @@ "metadata": {}, "outputs": [], "source": [ - "print(\"This notebook was created using version 1.4.0 of the Azure ML SDK\")\n", + "print(\"This notebook was created using version 1.5.0 of the Azure ML SDK\")\n", "print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")" ] }, diff --git a/how-to-use-azureml/automated-machine-learning/regression-explanation-featurization/train_explainer.py b/how-to-use-azureml/automated-machine-learning/regression-explanation-featurization/train_explainer.py index b27d76b2..86595e7d 100644 --- a/how-to-use-azureml/automated-machine-learning/regression-explanation-featurization/train_explainer.py +++ b/how-to-use-azureml/automated-machine-learning/regression-explanation-featurization/train_explainer.py @@ -10,7 +10,7 @@ from azureml.train.automl.runtime.automl_explain_utilities import AutoMLExplaine automl_setup_model_explanations, automl_check_model_if_explainable from azureml.explain.model.mimic.models.lightgbm_model import LGBMExplainableModel from azureml.explain.model.mimic_wrapper import MimicWrapper -from automl.client.core.common.constants import MODEL_PATH +from azureml.automl.core.shared.constants import MODEL_PATH from azureml.explain.model.scoring.scoring_explainer import TreeScoringExplainer, save diff --git a/how-to-use-azureml/automated-machine-learning/regression/auto-ml-regression.ipynb b/how-to-use-azureml/automated-machine-learning/regression/auto-ml-regression.ipynb index 1cbf6523..a8992a59 100644 --- a/how-to-use-azureml/automated-machine-learning/regression/auto-ml-regression.ipynb +++ b/how-to-use-azureml/automated-machine-learning/regression/auto-ml-regression.ipynb @@ -40,7 +40,7 @@ "## 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", + "If you are using an Azure Machine Learning Compute Instance, you are all set. Otherwise, go through the [configuration](../../../configuration.ipynb) notebook first if you haven't already to establish your connection to the AzureML Workspace. \n", "\n", "In this notebook you will learn how to:\n", "1. Create an `Experiment` in an existing `Workspace`.\n", @@ -92,7 +92,7 @@ "metadata": {}, "outputs": [], "source": [ - "print(\"This notebook was created using version 1.4.0 of the Azure ML SDK\")\n", + "print(\"This notebook was created using version 1.5.0 of the Azure ML SDK\")\n", "print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")" ] }, diff --git a/how-to-use-azureml/azure-databricks/automl/automl-databricks-local-with-deployment.ipynb b/how-to-use-azureml/azure-databricks/automl/automl-databricks-local-with-deployment.ipynb index 3ca93022..48aa5518 100644 --- a/how-to-use-azureml/azure-databricks/automl/automl-databricks-local-with-deployment.ipynb +++ b/how-to-use-azureml/azure-databricks/automl/automl-databricks-local-with-deployment.ipynb @@ -542,7 +542,7 @@ "metadata": {}, "outputs": [], "source": [ - "from automl.client.core.common import constants\n", + "from azureml.automl.core.shared import constants\n", "conda_env_file_name = 'conda_env.yml'\n", "best_run.download_file(name=\"outputs/conda_env_v_1_0_0.yml\", output_file_path=conda_env_file_name)\n", "with open(conda_env_file_name, \"r\") as conda_file:\n", @@ -564,7 +564,7 @@ "metadata": {}, "outputs": [], "source": [ - "from automl.client.core.common import constants\n", + "from azureml.automl.core.shared import constants\n", "script_file_name = 'scoring_file.py'\n", "best_run.download_file(name=\"outputs/scoring_file_v_1_0_0.py\", output_file_path=script_file_name)\n", "with open(script_file_name, \"r\") as scoring_file:\n", diff --git a/how-to-use-azureml/deployment/deploy-to-cloud/model-register-and-deploy.ipynb b/how-to-use-azureml/deployment/deploy-to-cloud/model-register-and-deploy.ipynb index 6c81ead9..f26620b6 100644 --- a/how-to-use-azureml/deployment/deploy-to-cloud/model-register-and-deploy.ipynb +++ b/how-to-use-azureml/deployment/deploy-to-cloud/model-register-and-deploy.ipynb @@ -383,6 +383,8 @@ "- an inference configuration\n", "- a single column tabular dataset, where each row contains a string representing sample request data sent to the service.\n", "\n", + "Please, note that profiling is a long running operation and can take up to 25 minutes depending on the size of the dataset.\n", + "\n", "At this point we only support profiling of services that expect their request data to be a string, for example: string serialized json, text, string serialized image, etc. The content of each row of the dataset (string) will be put into the body of the HTTP request and sent to the service encapsulating the model for scoring.\n", "\n", "Below is an example of how you can construct an input dataset to profile a service which expects its incoming requests to contain serialized json. In this case we created a dataset based one hundred instances of the same request data. In real world scenarios however, we suggest that you use larger datasets with various inputs, especially if your model resource usage/behavior is input dependent." @@ -483,6 +485,7 @@ " cpu=1.0,\n", " memory_in_gb=0.5)\n", "\n", + "# profiling is a long running operation and may take up to 25 min\n", "profile.wait_for_completion(True)\n", "details = profile.get_details()" ] diff --git a/how-to-use-azureml/deployment/deploy-to-local/register-model-deploy-local-advanced.ipynb b/how-to-use-azureml/deployment/deploy-to-local/register-model-deploy-local-advanced.ipynb index b0374f64..8fb8a77c 100644 --- a/how-to-use-azureml/deployment/deploy-to-local/register-model-deploy-local-advanced.ipynb +++ b/how-to-use-azureml/deployment/deploy-to-local/register-model-deploy-local-advanced.ipynb @@ -86,7 +86,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "You can add tags and descriptions to your models. we are using `sklearn_regression_model.pkl` file in the current directory as a model with the name `sklearn_regression_model_local_adv` in the workspace.\n", + "You can add tags and descriptions to your models. we are using `sklearn_regression_model.pkl` file in the current directory as a model with the name `sklearn_regression_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, framework, category, target customer etc. Note that tags must be alphanumeric." ] @@ -105,7 +105,7 @@ "from azureml.core.model import Model\n", "\n", "model = Model.register(model_path=\"sklearn_regression_model.pkl\",\n", - " model_name=\"sklearn_regression_model_local_adv\",\n", + " model_name=\"sklearn_regression_model\",\n", " tags={'area': \"diabetes\", 'type': \"regression\"},\n", " description=\"Ridge regression model to predict diabetes\",\n", " workspace=ws)" @@ -126,12 +126,12 @@ "source": [ "import os\n", "\n", - "source_directory = \"C:/abc\"\n", + "source_directory = \"source_directory\"\n", "\n", "os.makedirs(source_directory, 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/dockerstep\", exist_ok=True)" + "os.makedirs(os.path.join(source_directory, \"x/y\"), exist_ok=True)\n", + "os.makedirs(os.path.join(source_directory, \"env\"), exist_ok=True)\n", + "os.makedirs(os.path.join(source_directory, \"dockerstep\"), exist_ok=True)" ] }, { @@ -147,7 +147,7 @@ "metadata": {}, "outputs": [], "source": [ - "%%writefile C:/abc/x/y/score.py\n", + "%%writefile source_directory/x/y/score.py\n", "import os\n", "import pickle\n", "import json\n", @@ -170,7 +170,7 @@ " global name\n", " # note here, entire source directory on inference config gets added into image\n", " # bellow is the example how you can use any extra files in image\n", - " with open('./abc/extradata.json') as json_file: \n", + " with open('./source_directory/extradata.json') as json_file:\n", " data = json.load(json_file)\n", " name = data[\"people\"][0][\"name\"]\n", "\n", @@ -191,9 +191,7 @@ }, { "cell_type": "markdown", - "execution_count": null, "metadata": {}, - "outputs": [], "source": [ "Please note that you must indicate azureml-defaults with verion >= 1.0.45 as a pip dependency for your environemnt. This package contains the functionality needed to host the model as a web service." ] @@ -204,7 +202,7 @@ "metadata": {}, "outputs": [], "source": [ - "%%writefile C:/abc/env/myenv.yml\n", + "%%writefile source_directory/env/myenv.yml\n", "name: project_environment\n", "dependencies:\n", " - python=3.6.2\n", @@ -221,7 +219,7 @@ "metadata": {}, "outputs": [], "source": [ - "%%writefile C:/abc/extradata.json\n", + "%%writefile source_directory/extradata.json\n", "{\n", " \"people\": [\n", " {\n", @@ -255,13 +253,14 @@ "from azureml.core.model import InferenceConfig\n", "\n", "\n", - "myenv = Environment.from_conda_specification(name='myenv', file_path='env/myenv.yml')\n", + "myenv = Environment.from_conda_specification(name='myenv', file_path='myenv.yml')\n", "\n", "# explicitly set base_image to None when setting base_dockerfile\n", "myenv.docker.base_image = None\n", - "myenv.docker.base_dockerfile = \"RUN echo \\\"this is test\\\"\"\n", + "myenv.docker.base_dockerfile = \"FROM mcr.microsoft.com/azureml/base:intelmpi2018.3-ubuntu16.04\\nRUN echo \\\"this is test\\\"\"\n", + "myenv.inferencing_stack_version = \"latest\"\n", "\n", - "inference_config = InferenceConfig(source_directory=\"C:/abc\",\n", + "inference_config = InferenceConfig(source_directory=source_directory,\n", " entry_script=\"x/y/score.py\",\n", " environment=myenv)\n" ] @@ -379,7 +378,7 @@ "metadata": {}, "outputs": [], "source": [ - "%%writefile C:/abc/x/y/score.py\n", + "%%writefile source_directory/x/y/score.py\n", "import os\n", "import pickle\n", "import json\n", @@ -401,7 +400,7 @@ " global name, from_location\n", " # note here, entire source directory on inference config gets added into image\n", " # bellow is the example how you can use any extra files in image\n", - " with open('./abc/extradata.json') as json_file: \n", + " with open('source_directory/extradata.json') as json_file: \n", " data = json.load(json_file)\n", " name = data[\"people\"][0][\"name\"]\n", " from_location = data[\"people\"][0][\"from\"]\n", diff --git a/how-to-use-azureml/deployment/deploy-to-local/register-model-deploy-local.ipynb b/how-to-use-azureml/deployment/deploy-to-local/register-model-deploy-local.ipynb index 0b7660a2..fd6c888f 100644 --- a/how-to-use-azureml/deployment/deploy-to-local/register-model-deploy-local.ipynb +++ b/how-to-use-azureml/deployment/deploy-to-local/register-model-deploy-local.ipynb @@ -82,7 +82,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "You can add tags and descriptions to your models. we are using `sklearn_regression_model.pkl` file in the current directory as a model with the name `sklearn_regression_model_local` in the workspace.\n", + "You can add tags and descriptions to your models. we are using `sklearn_regression_model.pkl` file in the current directory as a model with the name `sklearn_regression_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, framework, category, target customer etc. Note that tags must be alphanumeric." ] @@ -100,7 +100,7 @@ "from azureml.core.model import Model\n", "\n", "model = Model.register(model_path=\"sklearn_regression_model.pkl\",\n", - " model_name=\"sklearn_regression_model_local\",\n", + " model_name=\"sklearn_regression_model\",\n", " tags={'area': \"diabetes\", 'type': \"regression\"},\n", " description=\"Ridge regression model to predict diabetes\",\n", " workspace=ws)" @@ -159,6 +159,8 @@ "- an inference configuration\n", "- a single column tabular dataset, where each row contains a string representing sample request data sent to the service.\n", "\n", + "Please, note that profiling is a long running operation and can take up to 25 minutes depending on the size of the dataset.\n", + "\n", "At this point we only support profiling of services that expect their request data to be a string, for example: string serialized json, text, string serialized image, etc. The content of each row of the dataset (string) will be put into the body of the HTTP request and sent to the service encapsulating the model for scoring.\n", "\n", "Below is an example of how you can construct an input dataset to profile a service which expects its incoming requests to contain serialized json. In this case we created a dataset based one hundred instances of the same request data. In real world scenarios however, we suggest that you use larger datasets with various inputs, especially if your model resource usage/behavior is input dependent." @@ -245,6 +247,7 @@ " cpu=1.0,\n", " memory_in_gb=0.5)\n", "\n", + "# profiling is a long running operation and may take up to 25 min\n", "profile.wait_for_completion(True)\n", "details = profile.get_details()" ] diff --git a/how-to-use-azureml/deployment/onnx/onnx-convert-aml-deploy-tinyyolo.yml b/how-to-use-azureml/deployment/onnx/onnx-convert-aml-deploy-tinyyolo.yml index 06c455f0..7ea284e5 100644 --- a/how-to-use-azureml/deployment/onnx/onnx-convert-aml-deploy-tinyyolo.yml +++ b/how-to-use-azureml/deployment/onnx/onnx-convert-aml-deploy-tinyyolo.yml @@ -4,4 +4,4 @@ dependencies: - azureml-sdk - numpy - git+https://github.com/apple/coremltools@v2.1 - - onnxmltools==1.3.1 + - onnxmltools diff --git a/how-to-use-azureml/deployment/onnx/onnx-inference-facial-expression-recognition-deploy.yml b/how-to-use-azureml/deployment/onnx/onnx-inference-facial-expression-recognition-deploy.yml index 7a41748d..8d9a9c4b 100644 --- a/how-to-use-azureml/deployment/onnx/onnx-inference-facial-expression-recognition-deploy.yml +++ b/how-to-use-azureml/deployment/onnx/onnx-inference-facial-expression-recognition-deploy.yml @@ -6,4 +6,4 @@ dependencies: - matplotlib - numpy - onnx - - opencv-python + - opencv-python-headless diff --git a/how-to-use-azureml/deployment/onnx/onnx-inference-mnist-deploy.yml b/how-to-use-azureml/deployment/onnx/onnx-inference-mnist-deploy.yml index 614209c5..0d73085a 100644 --- a/how-to-use-azureml/deployment/onnx/onnx-inference-mnist-deploy.yml +++ b/how-to-use-azureml/deployment/onnx/onnx-inference-mnist-deploy.yml @@ -6,4 +6,4 @@ dependencies: - matplotlib - numpy - onnx - - opencv-python + - opencv-python-headless diff --git a/how-to-use-azureml/deployment/production-deploy-to-aks-gpu/production-deploy-to-aks-gpu.ipynb b/how-to-use-azureml/deployment/production-deploy-to-aks-gpu/production-deploy-to-aks-gpu.ipynb index aed26009..d78603b2 100644 --- a/how-to-use-azureml/deployment/production-deploy-to-aks-gpu/production-deploy-to-aks-gpu.ipynb +++ b/how-to-use-azureml/deployment/production-deploy-to-aks-gpu/production-deploy-to-aks-gpu.ipynb @@ -59,8 +59,44 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "# 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](http://download.tensorflow.org/models/official/20181001_resnet/savedmodels/resnet_v1_fp32_savedmodel_NCHW_jpg.tar.gz) and unpack it to that directory." + "# Download the model\n", + "\n", + "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. This cell will download a [pretrained resnet50](http://download.tensorflow.org/models/official/20181001_resnet/savedmodels/resnet_v1_fp32_savedmodel_NCHW_jpg.tar.gz) and unpack it to that directory." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import os\n", + "import requests\n", + "import shutil\n", + "import tarfile\n", + "import tempfile\n", + "\n", + "from io import BytesIO\n", + "\n", + "model_url = \"http://download.tensorflow.org/models/official/20181001_resnet/savedmodels/resnet_v1_fp32_savedmodel_NCHW_jpg.tar.gz\"\n", + "\n", + "archive_prefix = \"./resnet_v1_fp32_savedmodel_NCHW_jpg/1538686758/\"\n", + "target_folder = \"resnet50\"\n", + "\n", + "if not os.path.exists(target_folder):\n", + " response = requests.get(model_url)\n", + " archive = tarfile.open(fileobj=BytesIO(response.content))\n", + " with tempfile.TemporaryDirectory() as temp_folder:\n", + " archive.extractall(temp_folder)\n", + " shutil.copytree(os.path.join(temp_folder, archive_prefix), target_folder)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Register the model\n", + "Register an existing trained model, add description and tags." ] }, { @@ -69,13 +105,13 @@ "metadata": {}, "outputs": [], "source": [ - "#Register the model\n", "from azureml.core.model import Model\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", - " tags = {'area': \"Image classification\", 'type': \"classification\"},\n", - " description = \"Image classification trained on Imagenet Dataset\",\n", - " workspace = ws)\n", + "\n", + "model = Model.register(model_path=\"resnet50\", # This points to the local directory to upload.\n", + " model_name=\"resnet50\", # This is the name the model is registered as.\n", + " tags={'area': \"Image classification\", 'type': \"classification\"},\n", + " description=\"Image classification trained on Imagenet Dataset\",\n", + " workspace=ws)\n", "\n", "print(model.name, model.description, model.version)" ] diff --git a/how-to-use-azureml/deployment/production-deploy-to-aks/production-deploy-to-aks.ipynb b/how-to-use-azureml/deployment/production-deploy-to-aks/production-deploy-to-aks.ipynb index 5ea43c86..b9d35d30 100644 --- a/how-to-use-azureml/deployment/production-deploy-to-aks/production-deploy-to-aks.ipynb +++ b/how-to-use-azureml/deployment/production-deploy-to-aks/production-deploy-to-aks.ipynb @@ -212,6 +212,8 @@ "- an inference configuration\n", "- a single column tabular dataset, where each row contains a string representing sample request data sent to the service.\n", "\n", + "Please, note that profiling is a long running operation and can take up to 25 minutes depending on the size of the dataset.\n", + "\n", "At this point we only support profiling of services that expect their request data to be a string, for example: string serialized json, text, string serialized image, etc. The content of each row of the dataset (string) will be put into the body of the HTTP request and sent to the service encapsulating the model for scoring.\n", "\n", "Below is an example of how you can construct an input dataset to profile a service which expects its incoming requests to contain serialized json. In this case we created a dataset based one hundred instances of the same request data. In real world scenarios however, we suggest that you use larger datasets with various inputs, especially if your model resource usage/behavior is input dependent." @@ -312,6 +314,7 @@ " cpu=1.0,\n", " memory_in_gb=0.5)\n", "\n", + "# profiling is a long running operation and may take up to 25 min\n", "profile.wait_for_completion(True)\n", "details = profile.get_details()" ] diff --git a/how-to-use-azureml/explain-model/azure-integration/remote-explanation/explain-model-on-amlcompute.ipynb b/how-to-use-azureml/explain-model/azure-integration/remote-explanation/explain-model-on-amlcompute.ipynb index 27506f1b..7f0702b3 100644 --- a/how-to-use-azureml/explain-model/azure-integration/remote-explanation/explain-model-on-amlcompute.ipynb +++ b/how-to-use-azureml/explain-model/azure-integration/remote-explanation/explain-model-on-amlcompute.ipynb @@ -243,8 +243,25 @@ " 'azureml-interpret', 'sklearn-pandas', 'azureml-dataprep'\n", "]\n", "\n", + "# Note: this is to pin the scikit-learn and pandas versions to be same as notebook.\n", + "# In production scenario user would choose their dependencies\n", + "import pkg_resources\n", + "available_packages = pkg_resources.working_set\n", + "sklearn_ver = None\n", + "pandas_ver = None\n", + "for dist in available_packages:\n", + " if dist.key == 'scikit-learn':\n", + " sklearn_ver = dist.version\n", + " elif dist.key == 'pandas':\n", + " pandas_ver = dist.version\n", + "sklearn_dep = 'scikit-learn'\n", + "pandas_dep = 'pandas'\n", + "if sklearn_ver:\n", + " sklearn_dep = 'scikit-learn=={}'.format(sklearn_ver)\n", + "if pandas_ver:\n", + " pandas_dep = 'pandas=={}'.format(pandas_ver)\n", "# specify CondaDependencies obj\n", - "run_config.environment.python.conda_dependencies = CondaDependencies.create(conda_packages=['scikit-learn'],\n", + "run_config.environment.python.conda_dependencies = CondaDependencies.create(conda_packages=[sklearn_dep, pandas_dep],\n", " pip_packages=azureml_pip_packages)\n", "\n", "# Now submit a run on AmlCompute\n", @@ -344,8 +361,25 @@ " 'azureml-interpret', 'azureml-dataprep'\n", "]\n", "\n", + "# Note: this is to pin the scikit-learn and pandas versions to be same as notebook.\n", + "# In production scenario user would choose their dependencies\n", + "import pkg_resources\n", + "available_packages = pkg_resources.working_set\n", + "sklearn_ver = None\n", + "pandas_ver = None\n", + "for dist in available_packages:\n", + " if dist.key == 'scikit-learn':\n", + " sklearn_ver = dist.version\n", + " elif dist.key == 'pandas':\n", + " pandas_ver = dist.version\n", + "sklearn_dep = 'scikit-learn'\n", + "pandas_dep = 'pandas'\n", + "if sklearn_ver:\n", + " sklearn_dep = 'scikit-learn=={}'.format(sklearn_ver)\n", + "if pandas_ver:\n", + " pandas_dep = 'pandas=={}'.format(pandas_ver)\n", "# specify CondaDependencies obj\n", - "run_config.environment.python.conda_dependencies = CondaDependencies.create(conda_packages=['scikit-learn'],\n", + "run_config.environment.python.conda_dependencies = CondaDependencies.create(conda_packages=[sklearn_dep, pandas_dep],\n", " pip_packages=azureml_pip_packages)\n", "\n", "from azureml.core import Run\n", @@ -457,8 +491,25 @@ "\n", "\n", "\n", + "# Note: this is to pin the scikit-learn and pandas versions to be same as notebook.\n", + "# In production scenario user would choose their dependencies\n", + "import pkg_resources\n", + "available_packages = pkg_resources.working_set\n", + "sklearn_ver = None\n", + "pandas_ver = None\n", + "for dist in available_packages:\n", + " if dist.key == 'scikit-learn':\n", + " sklearn_ver = dist.version\n", + " elif dist.key == 'pandas':\n", + " pandas_ver = dist.version\n", + "sklearn_dep = 'scikit-learn'\n", + "pandas_dep = 'pandas'\n", + "if sklearn_ver:\n", + " sklearn_dep = 'scikit-learn=={}'.format(sklearn_ver)\n", + "if pandas_ver:\n", + " pandas_dep = 'pandas=={}'.format(pandas_ver)\n", "# specify CondaDependencies obj\n", - "run_config.environment.python.conda_dependencies = CondaDependencies.create(conda_packages=['scikit-learn'],\n", + "run_config.environment.python.conda_dependencies = CondaDependencies.create(conda_packages=[sklearn_dep, pandas_dep],\n", " pip_packages=azureml_pip_packages)\n", "\n", "from azureml.core import Run\n", diff --git a/how-to-use-azureml/explain-model/azure-integration/scoring-time/train-explain-model-keras-locally-and-deploy.ipynb b/how-to-use-azureml/explain-model/azure-integration/scoring-time/train-explain-model-keras-locally-and-deploy.ipynb index c62d55bf..651b0256 100644 --- a/how-to-use-azureml/explain-model/azure-integration/scoring-time/train-explain-model-keras-locally-and-deploy.ipynb +++ b/how-to-use-azureml/explain-model/azure-integration/scoring-time/train-explain-model-keras-locally-and-deploy.ipynb @@ -431,8 +431,25 @@ " 'azureml-defaults', 'azureml-contrib-interpret', 'azureml-core', 'azureml-telemetry',\n", " 'azureml-interpret'\n", "]\n", + "# Note: this is to pin the scikit-learn and pandas versions to be same as notebook.\n", + "# In production scenario user would choose their dependencies\n", + "import pkg_resources\n", + "available_packages = pkg_resources.working_set\n", + "sklearn_ver = None\n", + "pandas_ver = None\n", + "for dist in available_packages:\n", + " if dist.key == 'scikit-learn':\n", + " sklearn_ver = dist.version\n", + " elif dist.key == 'pandas':\n", + " pandas_ver = dist.version\n", + "sklearn_dep = 'scikit-learn'\n", + "pandas_dep = 'pandas'\n", + "if sklearn_ver:\n", + " sklearn_dep = 'scikit-learn=={}'.format(sklearn_ver)\n", + "if pandas_ver:\n", + " pandas_dep = 'pandas=={}'.format(pandas_ver)\n", "# specify CondaDependencies obj\n", - "myenv = CondaDependencies.create(conda_packages=['scikit-learn', 'pandas'],\n", + "myenv = CondaDependencies.create(conda_packages=[sklearn_dep, pandas_dep],\n", " pip_packages=['sklearn-pandas', 'pyyaml', 'tensorflow<2.0', 'keras==2.3.1'] + azureml_pip_packages)\n", "\n", "with open(\"myenv.yml\",\"w\") as f:\n", @@ -476,7 +493,7 @@ "inference_config = InferenceConfig(entry_script=\"score_local_explain_keras.py\", environment=myenv)\n", "\n", "# Use configs and models generated above\n", - "service = Model.deploy(ws, 'model-scoring-deploy-local', [scoring_explainer_model, featurize_model, keras_model], inference_config, aciconfig)\n", + "service = Model.deploy(ws, 'model-scoring-keras-deploy-local', [scoring_explainer_model, featurize_model, keras_model], inference_config, aciconfig)\n", "service.wait_for_deployment(show_output=True)" ] }, diff --git a/how-to-use-azureml/explain-model/azure-integration/scoring-time/train-explain-model-locally-and-deploy.ipynb b/how-to-use-azureml/explain-model/azure-integration/scoring-time/train-explain-model-locally-and-deploy.ipynb index ed070d5d..fb3635fc 100644 --- a/how-to-use-azureml/explain-model/azure-integration/scoring-time/train-explain-model-locally-and-deploy.ipynb +++ b/how-to-use-azureml/explain-model/azure-integration/scoring-time/train-explain-model-locally-and-deploy.ipynb @@ -328,8 +328,25 @@ "]\n", " \n", "\n", + "# Note: this is to pin the scikit-learn and pandas versions to be same as notebook.\n", + "# In production scenario user would choose their dependencies\n", + "import pkg_resources\n", + "available_packages = pkg_resources.working_set\n", + "sklearn_ver = None\n", + "pandas_ver = None\n", + "for dist in available_packages:\n", + " if dist.key == 'scikit-learn':\n", + " sklearn_ver = dist.version\n", + " elif dist.key == 'pandas':\n", + " pandas_ver = dist.version\n", + "sklearn_dep = 'scikit-learn'\n", + "pandas_dep = 'pandas'\n", + "if sklearn_ver:\n", + " sklearn_dep = 'scikit-learn=={}'.format(sklearn_ver)\n", + "if pandas_ver:\n", + " pandas_dep = 'pandas=={}'.format(pandas_ver)\n", "# specify CondaDependencies obj\n", - "myenv = CondaDependencies.create(conda_packages=['scikit-learn', 'pandas'],\n", + "myenv = CondaDependencies.create(conda_packages=[sklearn_dep, pandas_dep],\n", " pip_packages=['sklearn-pandas', 'pyyaml'] + azureml_pip_packages,\n", " pin_sdk_version=False)\n", "\n", diff --git a/how-to-use-azureml/explain-model/azure-integration/scoring-time/train-explain-model-on-amlcompute-and-deploy.ipynb b/how-to-use-azureml/explain-model/azure-integration/scoring-time/train-explain-model-on-amlcompute-and-deploy.ipynb index acce1822..64b4e187 100644 --- a/how-to-use-azureml/explain-model/azure-integration/scoring-time/train-explain-model-on-amlcompute-and-deploy.ipynb +++ b/how-to-use-azureml/explain-model/azure-integration/scoring-time/train-explain-model-on-amlcompute-and-deploy.ipynb @@ -246,8 +246,25 @@ " \n", "\n", "\n", + "# Note: this is to pin the scikit-learn version to be same as notebook.\n", + "# In production scenario user would choose their dependencies\n", + "import pkg_resources\n", + "available_packages = pkg_resources.working_set\n", + "sklearn_ver = None\n", + "pandas_ver = None\n", + "for dist in available_packages:\n", + " if dist.key == 'scikit-learn':\n", + " sklearn_ver = dist.version\n", + " elif dist.key == 'pandas':\n", + " pandas_ver = dist.version\n", + "sklearn_dep = 'scikit-learn'\n", + "pandas_dep = 'pandas'\n", + "if sklearn_ver:\n", + " sklearn_dep = 'scikit-learn=={}'.format(sklearn_ver)\n", + "if pandas_ver:\n", + " pandas_dep = 'pandas=={}'.format(pandas_ver)\n", "# specify CondaDependencies obj\n", - "run_config.environment.python.conda_dependencies = CondaDependencies.create(conda_packages=['scikit-learn'],\n", + "run_config.environment.python.conda_dependencies = CondaDependencies.create(conda_packages=[sklearn_dep, pandas_dep],\n", " pip_packages=['sklearn_pandas', 'pyyaml'] + azureml_pip_packages,\n", " pin_sdk_version=False)\n", "# Now submit a run on AmlCompute\n", @@ -397,8 +414,25 @@ "]\n", " \n", "\n", + "# Note: this is to pin the scikit-learn and pandas versions to be same as notebook.\n", + "# In production scenario user would choose their dependencies\n", + "import pkg_resources\n", + "available_packages = pkg_resources.working_set\n", + "sklearn_ver = None\n", + "pandas_ver = None\n", + "for dist in available_packages:\n", + " if dist.key == 'scikit-learn':\n", + " sklearn_ver = dist.version\n", + " elif dist.key == 'pandas':\n", + " pandas_ver = dist.version\n", + "sklearn_dep = 'scikit-learn'\n", + "pandas_dep = 'pandas'\n", + "if sklearn_ver:\n", + " sklearn_dep = 'scikit-learn=={}'.format(sklearn_ver)\n", + "if pandas_ver:\n", + " pandas_dep = 'pandas=={}'.format(pandas_ver)\n", "# specify CondaDependencies obj\n", - "myenv = CondaDependencies.create(conda_packages=['scikit-learn', 'pandas'],\n", + "myenv = CondaDependencies.create(conda_packages=[sklearn_dep, pandas_dep],\n", " pip_packages=['sklearn-pandas', 'pyyaml'] + azureml_pip_packages,\n", " pin_sdk_version=False)\n", "\n", diff --git a/how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-parameter-tuning-with-hyperdrive.ipynb b/how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-parameter-tuning-with-hyperdrive.ipynb index 1193163c..83f1bba7 100644 --- a/how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-parameter-tuning-with-hyperdrive.ipynb +++ b/how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-parameter-tuning-with-hyperdrive.ipynb @@ -537,259 +537,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Deploy the model in ACI\n", - "Now we are ready to deploy the model as a web service running in Azure Container Instance [ACI](https://azure.microsoft.com/en-us/services/container-instances/). \n", - "### Create score.py\n", - "First, we will create a scoring script that will be invoked by the web service call. \n", - "\n", - "* Note that the scoring script must have two required functions, `init()` and `run(input_data)`. \n", - " * In `init()` function, you typically load the model into a global object. This function is executed only once when the Docker container is started. \n", - " * In `run(input_data)` function, the model is used to predict a value based on the input data. The input and output to `run` typically use JSON as serialization and de-serialization format but you are not limited to that." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "%%writefile score.py\n", - "import json\n", - "import numpy as np\n", - "import os\n", - "import tensorflow as tf\n", - "\n", - "def init():\n", - " global X, output, sess\n", - " tf.reset_default_graph()\n", - " # AZUREML_MODEL_DIR is an environment variable created during deployment.\n", - " # It is the path to the model folder (./azureml-models/$MODEL_NAME/$VERSION)\n", - " # For multiple models, it points to the folder containing all deployed models (./azureml-models)\n", - " model_root = os.path.join(os.getenv('AZUREML_MODEL_DIR'), 'model')\n", - " saver = tf.train.import_meta_graph(os.path.join(model_root, 'mnist-tf.model.meta'))\n", - " X = tf.get_default_graph().get_tensor_by_name(\"network/X:0\")\n", - " output = tf.get_default_graph().get_tensor_by_name(\"network/output/MatMul:0\")\n", - " \n", - " sess = tf.Session()\n", - " saver.restore(sess, os.path.join(model_root, 'mnist-tf.model'))\n", - "\n", - "def run(raw_data):\n", - " data = np.array(json.loads(raw_data)['data'])\n", - " # make prediction\n", - " out = output.eval(session=sess, feed_dict={X: data})\n", - " y_hat = np.argmax(out, axis=1)\n", - " return y_hat.tolist()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Create myenv.yml\n", - "We also need to create an environment file so that Azure Machine Learning can install the necessary packages in the Docker image which are required by your scoring script. In this case, we need to specify packages `numpy`, `tensorflow`." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "from azureml.core.runconfig import CondaDependencies\n", - "\n", - "cd = CondaDependencies.create()\n", - "cd.add_conda_package('numpy')\n", - "cd.add_tensorflow_conda_package()\n", - "cd.save_to_file(base_directory='./', conda_file_path='myenv.yml')\n", - "\n", - "print(cd.serialize_to_string())" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Deploy to ACI\n", - "Now we can deploy. **This cell will run for about 7-8 minutes**. Behind the scene, AzureML will build a Docker container image with the given configuration, if already not available. This image will be deployed to the ACI infrastructure and the scoring script and model will be mounted on the container. The model will then be available as a web service with an HTTP endpoint to accept REST client calls." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "%%time\n", - "from azureml.core.environment import Environment\n", - "from azureml.core.model import Model, InferenceConfig\n", - "from azureml.core.webservice import AciWebservice\n", - "\n", - "\n", - "myenv = Environment.from_conda_specification(name=\"env\", file_path=\"myenv.yml\")\n", - "inference_config = InferenceConfig(entry_script=\"score.py\", environment=myenv)\n", - "\n", - "aciconfig = AciWebservice.deploy_configuration(cpu_cores=1, \n", - " memory_gb=1, \n", - " tags={'name':'mnist', 'framework': 'TensorFlow DNN'},\n", - " description='Tensorflow DNN on MNIST')\n", - "\n", - "service = Model.deploy(ws, 'tf-mnist-svc', [model], inference_config, aciconfig)\n", - "service.wait_for_deployment(show_output=True)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "**Tip: If something goes wrong with the deployment, the first thing to look at is the logs from the service by running the following command:**" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "print(service.get_logs())" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This is the scoring web service endpoint:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "print(service.scoring_uri)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Test the deployed model\n", - "Let's test the deployed model. Pick 30 random samples from the test set, and send it to the web service hosted in ACI. Note here we are using the `run` API in the SDK to invoke the service. You can also make raw HTTP calls using any HTTP tool such as curl.\n", - "\n", - "After the invocation, we print the returned predictions and plot them along with the input images. Use red font color and inversed image (white on black) to highlight the misclassified samples. Note since the model accuracy is pretty high, you might have to run the below cell a few times before you can see a misclassified sample." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "import json\n", - "\n", - "# find 30 random samples from test set\n", - "n = 30\n", - "sample_indices = np.random.permutation(X_test.shape[0])[0:n]\n", - "\n", - "test_samples = json.dumps({\"data\": X_test[sample_indices].tolist()})\n", - "test_samples = bytes(test_samples, encoding='utf8')\n", - "\n", - "# predict using the deployed model\n", - "result = service.run(input_data=test_samples)\n", - "\n", - "# compare actual value vs. the predicted values:\n", - "i = 0\n", - "plt.figure(figsize = (20, 1))\n", - "\n", - "for s in sample_indices:\n", - " plt.subplot(1, n, i + 1)\n", - " plt.axhline('')\n", - " plt.axvline('')\n", - " \n", - " # use different color for misclassified sample\n", - " font_color = 'red' if y_test[s] != result[i] else 'black'\n", - " clr_map = plt.cm.gray if y_test[s] != result[i] else plt.cm.Greys\n", - " \n", - " plt.text(x=10, y=-10, s=y_hat[s], fontsize=18, color=font_color)\n", - " plt.imshow(X_test[s].reshape(28, 28), cmap=clr_map)\n", - " \n", - " i = i + 1\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can also send raw HTTP request to the service." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "import requests\n", - "\n", - "# send a random row from the test set to score\n", - "random_index = np.random.randint(0, len(X_test)-1)\n", - "input_data = \"{\\\"data\\\": [\" + str(list(X_test[random_index])) + \"]}\"\n", - "\n", - "headers = {'Content-Type':'application/json'}\n", - "\n", - "resp = requests.post(service.scoring_uri, input_data, headers=headers)\n", - "\n", - "print(\"POST to url\", service.scoring_uri)\n", - "print(\"input data:\", input_data)\n", - "print(\"label:\", y_test[random_index])\n", - "print(\"prediction:\", resp.text)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Let's look at the workspace after the web service was deployed. You should see \n", - "* a registered model named 'model' and with the id 'model:1'\n", - "* an image called 'tf-mnist' and with a docker image location pointing to your workspace's Azure Container Registry (ACR) \n", - "* a webservice called 'tf-mnist' with some scoring URL" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "models = ws.models\n", - "for name, model in models.items():\n", - " print(\"Model: {}, ID: {}\".format(name, model.id))\n", - " \n", - "images = ws.images\n", - "for name, image in images.items():\n", - " print(\"Image: {}, location: {}\".format(name, image.image_location))\n", - " \n", - "webservices = ws.webservices\n", - "for name, webservice in webservices.items():\n", - " print(\"Webservice: {}, scoring URI: {}\".format(name, webservice.scoring_uri))" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Clean up\n", - "You can delete the ACI deployment with a simple delete API call." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "service.delete()" + "For model deployment, please refer to [Training, hyperparameter tune, and deploy with TensorFlow](https://github.com/Azure/MachineLearningNotebooks/blob/master/how-to-use-azureml/ml-frameworks/tensorflow/deployment/train-hyperparameter-tune-deploy-with-tensorflow/train-hyperparameter-tune-deploy-with-tensorflow.ipynb)." ] } ], diff --git a/how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-with-automated-machine-learning-step.ipynb b/how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-with-automated-machine-learning-step.ipynb index be000d26..33c5dfc7 100644 --- a/how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-with-automated-machine-learning-step.ipynb +++ b/how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-with-automated-machine-learning-step.ipynb @@ -136,6 +136,7 @@ "source": [ "from azureml.core.compute import AmlCompute\n", "from azureml.core.compute import ComputeTarget\n", + "from azureml.core.compute_target import ComputeTargetException\n", "\n", "# Choose a name for your CPU cluster\n", "amlcompute_cluster_name = \"cpu-cluster\"\n", diff --git a/how-to-use-azureml/machine-learning-pipelines/parallel-run/file-dataset-image-inference-mnist.ipynb b/how-to-use-azureml/machine-learning-pipelines/parallel-run/file-dataset-image-inference-mnist.ipynb index 398a7f6f..ef0008d1 100644 --- a/how-to-use-azureml/machine-learning-pipelines/parallel-run/file-dataset-image-inference-mnist.ipynb +++ b/how-to-use-azureml/machine-learning-pipelines/parallel-run/file-dataset-image-inference-mnist.ipynb @@ -341,7 +341,7 @@ "from azureml.core import Environment\n", "from azureml.core.runconfig import CondaDependencies, DEFAULT_CPU_IMAGE\n", "\n", - "batch_conda_deps = CondaDependencies.create(pip_packages=[\"tensorflow==1.13.1\", \"pillow\"])\n", + "batch_conda_deps = CondaDependencies.create(pip_packages=[\"tensorflow==1.15.2\", \"pillow\"])\n", "\n", "batch_env = Environment(name=\"batch_environment\")\n", "batch_env.python.conda_dependencies = batch_conda_deps\n", diff --git a/how-to-use-azureml/ml-frameworks/pytorch/training/mask-rcnn-object-detection/pytorch-mask-rcnn.yml b/how-to-use-azureml/ml-frameworks/pytorch/training/mask-rcnn-object-detection/pytorch-mask-rcnn.yml index 4302c349..7a3343e6 100644 --- a/how-to-use-azureml/ml-frameworks/pytorch/training/mask-rcnn-object-detection/pytorch-mask-rcnn.yml +++ b/how-to-use-azureml/ml-frameworks/pytorch/training/mask-rcnn-object-detection/pytorch-mask-rcnn.yml @@ -1,7 +1,7 @@ name: pytorch-mask-rcnn dependencies: - cython -- pytorch -c pytorch +- pytorch==1.4.0 -c pytorch - torchvision -c pytorch - pip: - azureml-sdk diff --git a/how-to-use-azureml/ml-frameworks/tensorflow/deployment/train-hyperparameter-tune-deploy-with-tensorflow/tf_mnist.py b/how-to-use-azureml/ml-frameworks/tensorflow/deployment/train-hyperparameter-tune-deploy-with-tensorflow/tf_mnist.py index 32e0b8f2..87be1ab3 100644 --- a/how-to-use-azureml/ml-frameworks/tensorflow/deployment/train-hyperparameter-tune-deploy-with-tensorflow/tf_mnist.py +++ b/how-to-use-azureml/ml-frameworks/tensorflow/deployment/train-hyperparameter-tune-deploy-with-tensorflow/tf_mnist.py @@ -4,33 +4,100 @@ import numpy as np import argparse import os +import re import tensorflow as tf +import time import glob from azureml.core import Run from utils import load_data +from tensorflow.keras import Model, layers + + +# Create TF Model. +class NeuralNet(Model): + # Set layers. + def __init__(self): + super(NeuralNet, self).__init__() + # First hidden layer. + self.h1 = layers.Dense(n_h1, activation=tf.nn.relu) + # Second hidden layer. + self.h2 = layers.Dense(n_h2, activation=tf.nn.relu) + self.out = layers.Dense(n_outputs) + + # Set forward pass. + def call(self, x, is_training=False): + x = self.h1(x) + x = self.h2(x) + x = self.out(x) + if not is_training: + # Apply softmax when not training. + x = tf.nn.softmax(x) + return x + + +def cross_entropy_loss(y, logits): + # Convert labels to int 64 for tf cross-entropy function. + y = tf.cast(y, tf.int64) + # Apply softmax to logits and compute cross-entropy. + loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y, logits=logits) + # Average loss across the batch. + return tf.reduce_mean(loss) + + +# Accuracy metric. +def accuracy(y_pred, y_true): + # Predicted class is the index of highest score in prediction vector (i.e. argmax). + correct_prediction = tf.equal(tf.argmax(y_pred, 1), tf.cast(y_true, tf.int64)) + return tf.reduce_mean(tf.cast(correct_prediction, tf.float32), axis=-1) + + +# Optimization process. +def run_optimization(x, y): + # Wrap computation inside a GradientTape for automatic differentiation. + with tf.GradientTape() as g: + # Forward pass. + logits = neural_net(x, is_training=True) + # Compute loss. + loss = cross_entropy_loss(y, logits) + + # Variables to update, i.e. trainable variables. + trainable_variables = neural_net.trainable_variables + + # Compute gradients. + gradients = g.gradient(loss, trainable_variables) + + # Update W and b following gradients. + optimizer.apply_gradients(zip(gradients, trainable_variables)) + print("TensorFlow version:", tf.__version__) parser = argparse.ArgumentParser() -parser.add_argument('--data-folder', type=str, dest='data_folder', help='data folder mounting point') -parser.add_argument('--batch-size', type=int, dest='batch_size', default=50, help='mini batch size for training') -parser.add_argument('--first-layer-neurons', type=int, dest='n_hidden_1', default=100, +parser.add_argument('--data-folder', type=str, dest='data_folder', default='data', help='data folder mounting point') +parser.add_argument('--batch-size', type=int, dest='batch_size', default=128, help='mini batch size for training') +parser.add_argument('--first-layer-neurons', type=int, dest='n_hidden_1', default=128, help='# of neurons in the first layer') -parser.add_argument('--second-layer-neurons', type=int, dest='n_hidden_2', default=100, +parser.add_argument('--second-layer-neurons', type=int, dest='n_hidden_2', default=128, help='# of neurons in the second layer') parser.add_argument('--learning-rate', type=float, dest='learning_rate', default=0.01, help='learning rate') +parser.add_argument('--resume-from', type=str, default=None, + help='location of the model or checkpoint files from where to resume the training') args = parser.parse_args() +previous_model_location = args.resume_from +# You can also use environment variable to get the model/checkpoint files location +# previous_model_location = os.path.expandvars(os.getenv("AZUREML_DATAREFERENCE_MODEL_LOCATION", None)) + data_folder = args.data_folder print('Data folder:', data_folder) # load train and test set into numpy arrays # note we scale the pixel intensity values to 0-1 (by dividing it with 255.0) so the model can converge faster. X_train = load_data(glob.glob(os.path.join(data_folder, '**/train-images-idx3-ubyte.gz'), - recursive=True)[0], False) / 255.0 + recursive=True)[0], False) / np.float32(255.0) X_test = load_data(glob.glob(os.path.join(data_folder, '**/t10k-images-idx3-ubyte.gz'), - recursive=True)[0], False) / 255.0 + recursive=True)[0], False) / np.float32(255.0) y_train = load_data(glob.glob(os.path.join(data_folder, '**/train-labels-idx1-ubyte.gz'), recursive=True)[0], True).reshape(-1) y_test = load_data(glob.glob(os.path.join(data_folder, '**/t10k-labels-idx1-ubyte.gz'), @@ -48,65 +115,76 @@ learning_rate = args.learning_rate n_epochs = 20 batch_size = args.batch_size -with tf.name_scope('network'): - # construct the DNN - X = tf.placeholder(tf.float32, shape=(None, n_inputs), name='X') - y = tf.placeholder(tf.int64, shape=(None), name='y') - h1 = tf.layers.dense(X, n_h1, activation=tf.nn.relu, name='h1') - h2 = tf.layers.dense(h1, n_h2, activation=tf.nn.relu, name='h2') - output = tf.layers.dense(h2, n_outputs, name='output') +# Build neural network model. +neural_net = NeuralNet() -with tf.name_scope('train'): - cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y, logits=output) - loss = tf.reduce_mean(cross_entropy, name='loss') - optimizer = tf.train.GradientDescentOptimizer(learning_rate) - train_op = optimizer.minimize(loss) - -with tf.name_scope('eval'): - correct = tf.nn.in_top_k(output, y, 1) - acc_op = tf.reduce_mean(tf.cast(correct, tf.float32)) - -init = tf.global_variables_initializer() -saver = tf.train.Saver() +# Stochastic gradient descent optimizer. +optimizer = tf.optimizers.SGD(learning_rate) # start an Azure ML run run = Run.get_context() -with tf.Session() as sess: - init.run() - for epoch in range(n_epochs): +if previous_model_location: + # Restore variables from latest checkpoint. + checkpoint = tf.train.Checkpoint(model=neural_net, optimizer=optimizer) + checkpoint_file_path = tf.train.latest_checkpoint(previous_model_location) + checkpoint.restore(checkpoint_file_path) + checkpoint_filename = os.path.basename(checkpoint_file_path) + num_found = re.search(r'\d+', checkpoint_filename) + if num_found: + start_epoch = int(num_found.group(0)) + print("Resuming from epoch {}".format(str(start_epoch))) - # randomly shuffle training set - indices = np.random.permutation(training_set_size) - X_train = X_train[indices] - y_train = y_train[indices] +start_time = time.perf_counter() +for epoch in range(0, n_epochs): - # batch index - b_start = 0 - b_end = b_start + batch_size - for _ in range(training_set_size // batch_size): - # get a batch - X_batch, y_batch = X_train[b_start: b_end], y_train[b_start: b_end] + # randomly shuffle training set + indices = np.random.permutation(training_set_size) + X_train = X_train[indices] + y_train = y_train[indices] - # update batch index for the next batch - b_start = b_start + batch_size - b_end = min(b_start + batch_size, training_set_size) + # batch index + b_start = 0 + b_end = b_start + batch_size + for _ in range(training_set_size // batch_size): + # get a batch + X_batch, y_batch = X_train[b_start: b_end], y_train[b_start: b_end] - # train - sess.run(train_op, feed_dict={X: X_batch, y: y_batch}) - # evaluate training set - acc_train = acc_op.eval(feed_dict={X: X_batch, y: y_batch}) - # evaluate validation set - acc_val = acc_op.eval(feed_dict={X: X_test, y: y_test}) + # update batch index for the next batch + b_start = b_start + batch_size + b_end = min(b_start + batch_size, training_set_size) - # log accuracies - run.log('training_acc', np.float(acc_train)) - run.log('validation_acc', np.float(acc_val)) - print(epoch, '-- Training accuracy:', acc_train, '\b Validation accuracy:', acc_val) - y_hat = np.argmax(output.eval(feed_dict={X: X_test}), axis=1) + # train + run_optimization(X_batch, y_batch) - run.log('final_acc', np.float(acc_val)) + # evaluate training set + pred = neural_net(X_batch, is_training=False) + acc_train = accuracy(pred, y_batch) - os.makedirs('./outputs/model', exist_ok=True) - # files saved in the "./outputs" folder are automatically uploaded into run history - saver.save(sess, './outputs/model/mnist-tf.model') + # evaluate validation set + pred = neural_net(X_test, is_training=False) + acc_val = accuracy(pred, y_test) + + # log accuracies + run.log('training_acc', np.float(acc_train)) + run.log('validation_acc', np.float(acc_val)) + print(epoch, '-- Training accuracy:', acc_train, '\b Validation accuracy:', acc_val) + + # Save checkpoints in the "./outputs" folder so that they are automatically uploaded into run history. + checkpoint_dir = './outputs/' + checkpoint = tf.train.Checkpoint(model=neural_net, optimizer=optimizer) + + if epoch % 2 == 0: + checkpoint.save(checkpoint_dir) + +run.log('final_acc', np.float(acc_val)) +os.makedirs('./outputs/model', exist_ok=True) + +# files saved in the "./outputs" folder are automatically uploaded into run history +# this is workaround for https://github.com/tensorflow/tensorflow/issues/33913 and will be fixed once we move to >tf2.1 +neural_net._set_inputs(X_train) +tf.saved_model.save(neural_net, './outputs/model/') + +stop_time = time.perf_counter() +training_time = (stop_time - start_time) * 1000 +print("Total time in milliseconds for training: {}".format(str(training_time))) diff --git a/how-to-use-azureml/ml-frameworks/tensorflow/deployment/train-hyperparameter-tune-deploy-with-tensorflow/train-hyperparameter-tune-deploy-with-tensorflow.ipynb b/how-to-use-azureml/ml-frameworks/tensorflow/deployment/train-hyperparameter-tune-deploy-with-tensorflow/train-hyperparameter-tune-deploy-with-tensorflow.ipynb index 314161c1..5aadb46b 100644 --- a/how-to-use-azureml/ml-frameworks/tensorflow/deployment/train-hyperparameter-tune-deploy-with-tensorflow/train-hyperparameter-tune-deploy-with-tensorflow.ipynb +++ b/how-to-use-azureml/ml-frameworks/tensorflow/deployment/train-hyperparameter-tune-deploy-with-tensorflow/train-hyperparameter-tune-deploy-with-tensorflow.ipynb @@ -170,18 +170,19 @@ "metadata": {}, "outputs": [], "source": [ - "import urllib\n", - "data_folder = 'data'\n", + "import urllib.request\n", + "\n", + "data_folder = os.path.join(os.getcwd(), 'data')\n", "os.makedirs(data_folder, exist_ok=True)\n", "\n", "urllib.request.urlretrieve('https://azureopendatastorage.blob.core.windows.net/mnist/train-images-idx3-ubyte.gz',\n", - " filename=os.path.join(data_folder, 'train-images.gz'))\n", + " filename=os.path.join(data_folder, 'train-images-idx3-ubyte.gz'))\n", "urllib.request.urlretrieve('https://azureopendatastorage.blob.core.windows.net/mnist/train-labels-idx1-ubyte.gz',\n", - " filename=os.path.join(data_folder, 'train-labels.gz'))\n", + " filename=os.path.join(data_folder, 'train-labels-idx1-ubyte.gz'))\n", "urllib.request.urlretrieve('https://azureopendatastorage.blob.core.windows.net/mnist/t10k-images-idx3-ubyte.gz',\n", - " filename=os.path.join(data_folder, 'test-images.gz'))\n", + " filename=os.path.join(data_folder, 't10k-images-idx3-ubyte.gz'))\n", "urllib.request.urlretrieve('https://azureopendatastorage.blob.core.windows.net/mnist/t10k-labels-idx1-ubyte.gz',\n", - " filename=os.path.join(data_folder, 'test-labels.gz'))" + " filename=os.path.join(data_folder, 't10k-labels-idx1-ubyte.gz'))" ] }, { @@ -209,11 +210,10 @@ "from utils import load_data\n", "\n", "# note we also shrink the intensity values (X) from 0-255 to 0-1. This helps the neural network converge faster.\n", - "X_train = load_data(os.path.join(data_folder, 'train-images.gz'), False) / 255.0\n", - "y_train = load_data(os.path.join(data_folder, 'train-labels.gz'), True).reshape(-1)\n", - "\n", - "X_test = load_data(os.path.join(data_folder, 'test-images.gz'), False) / 255.0\n", - "y_test = load_data(os.path.join(data_folder, 'test-labels.gz'), True).reshape(-1)\n", + "X_train = load_data(os.path.join(data_folder, 'train-images-idx3-ubyte.gz'), False) / np.float32(255.0)\n", + "X_test = load_data(os.path.join(data_folder, 't10k-images-idx3-ubyte.gz'), False) / np.float32(255.0)\n", + "y_train = load_data(os.path.join(data_folder, 'train-labels-idx1-ubyte.gz'), True).reshape(-1)\n", + "y_test = load_data(os.path.join(data_folder, 't10k-labels-idx1-ubyte.gz'), True).reshape(-1)\n", "\n", "count = 0\n", "sample_size = 30\n", @@ -447,9 +447,9 @@ "\n", "script_params = {\n", " '--data-folder': dataset.as_named_input('mnist').as_mount(),\n", - " '--batch-size': 50,\n", - " '--first-layer-neurons': 300,\n", - " '--second-layer-neurons': 100,\n", + " '--batch-size': 64,\n", + " '--first-layer-neurons': 256,\n", + " '--second-layer-neurons': 128,\n", " '--learning-rate': 0.01\n", "}\n", "\n", @@ -458,6 +458,7 @@ " compute_target=compute_target,\n", " entry_script='tf_mnist.py',\n", " use_gpu=True,\n", + " framework_version='2.0',\n", " pip_packages=['azureml-dataprep[pandas,fuse]'])" ] }, @@ -622,14 +623,7 @@ "metadata": {}, "outputs": [], "source": [ - "# create a model folder in the current directory\n", - "os.makedirs('./model', exist_ok=True)\n", - "\n", - "for f in run.get_file_names():\n", - " if f.startswith('outputs/model'):\n", - " output_file_path = os.path.join('./model', f.split('/')[-1])\n", - " print('Downloading from {} to {} ...'.format(f, output_file_path))\n", - " run.download_file(name=f, output_file_path=output_file_path)" + "run.download_files(prefix='outputs/model', output_directory='./model', append_prefix=False)" ] }, { @@ -649,22 +643,7 @@ "outputs": [], "source": [ "import tensorflow as tf\n", - "\n", - "tf.reset_default_graph()\n", - "\n", - "saver = tf.train.import_meta_graph(\"./model/mnist-tf.model.meta\")\n", - "graph = tf.get_default_graph()\n", - "\n", - "for op in graph.get_operations():\n", - " if op.name.startswith('network'):\n", - " print(op.name)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Feed test dataset to the persisted model to get predictions." + "imported_model = tf.saved_model.load('./model')" ] }, { @@ -673,16 +652,8 @@ "metadata": {}, "outputs": [], "source": [ - "# input tensor. this is an array of 784 elements, each representing the intensity of a pixel in the digit image.\n", - "X = tf.get_default_graph().get_tensor_by_name(\"network/X:0\")\n", - "# output tensor. this is an array of 10 elements, each representing the probability of predicted value of the digit.\n", - "output = tf.get_default_graph().get_tensor_by_name(\"network/output/MatMul:0\")\n", - "\n", - "with tf.Session() as sess:\n", - " saver.restore(sess, './model/mnist-tf.model')\n", - " k = output.eval(feed_dict={X : X_test})\n", - "# get the prediction, which is the index of the element that has the largest probability value.\n", - "y_hat = np.argmax(k, axis=1)\n", + "pred =imported_model(X_test)\n", + "y_hat = np.argmax(pred, axis=1)\n", "\n", "# print the first 30 labels and predictions\n", "print('labels: \\t', y_test[:30])\n", @@ -690,10 +661,12 @@ ] }, { - "cell_type": "markdown", + "cell_type": "code", + "execution_count": null, "metadata": {}, + "outputs": [], "source": [ - "Calculate the overall accuracy by comparing the predicted value against the test set." + "print(\"Accuracy on the test set:\", np.average(y_hat == y_test))" ] }, { @@ -724,9 +697,9 @@ "\n", "ps = RandomParameterSampling(\n", " {\n", - " '--batch-size': choice(25, 50, 100),\n", - " '--first-layer-neurons': choice(10, 50, 200, 300, 500),\n", - " '--second-layer-neurons': choice(10, 50, 200, 500),\n", + " '--batch-size': choice(32, 64, 128),\n", + " '--first-layer-neurons': choice(16, 64, 128, 256, 512),\n", + " '--second-layer-neurons': choice(16, 64, 256, 512),\n", " '--learning-rate': loguniform(-6, -1)\n", " }\n", ")" @@ -748,7 +721,8 @@ "est = TensorFlow(source_directory=script_folder,\n", " script_params={'--data-folder': dataset.as_named_input('mnist').as_mount()},\n", " compute_target=compute_target,\n", - " entry_script='tf_mnist.py', \n", + " entry_script='tf_mnist.py',\n", + " framework_version='2.0',\n", " use_gpu=True,\n", " pip_packages=['azureml-dataprep[pandas,fuse]'])" ] @@ -928,24 +902,20 @@ "from azureml.core.model import Model\n", "\n", "def init():\n", - " global X, output, sess\n", - " tf.reset_default_graph()\n", + " global tf_model\n", " model_root = os.getenv('AZUREML_MODEL_DIR')\n", " # the name of the folder in which to look for tensorflow model files\n", " tf_model_folder = 'model'\n", - " saver = tf.train.import_meta_graph(\n", - " os.path.join(model_root, tf_model_folder, 'mnist-tf.model.meta'))\n", - " X = tf.get_default_graph().get_tensor_by_name(\"network/X:0\")\n", - " output = tf.get_default_graph().get_tensor_by_name(\"network/output/MatMul:0\")\n", - "\n", - " sess = tf.Session()\n", - " saver.restore(sess, os.path.join(model_root, tf_model_folder, 'mnist-tf.model'))\n", + " \n", + " tf_model = tf.saved_model.load(os.path.join(model_root, tf_model_folder))\n", "\n", "def run(raw_data):\n", - " data = np.array(json.loads(raw_data)['data'])\n", + " data = np.array(json.loads(raw_data)['data'], dtype=np.float32)\n", + " \n", " # make prediction\n", - " out = output.eval(session=sess, feed_dict={X: data})\n", + " out = tf_model(data)\n", " y_hat = np.argmax(out, axis=1)\n", + "\n", " return y_hat.tolist()" ] }, @@ -967,7 +937,7 @@ "\n", "cd = CondaDependencies.create()\n", "cd.add_conda_package('numpy')\n", - "cd.add_pip_package('tensorflow==1.13.1')\n", + "cd.add_pip_package('tensorflow==2.0.0')\n", "cd.add_pip_package(\"azureml-defaults\")\n", "cd.save_to_file(base_directory='./', conda_file_path='myenv.yml')\n", "\n", diff --git a/how-to-use-azureml/ml-frameworks/tensorflow/deployment/train-hyperparameter-tune-deploy-with-tensorflow/train-hyperparameter-tune-deploy-with-tensorflow.yml b/how-to-use-azureml/ml-frameworks/tensorflow/deployment/train-hyperparameter-tune-deploy-with-tensorflow/train-hyperparameter-tune-deploy-with-tensorflow.yml index 3f25441b..4629e907 100644 --- a/how-to-use-azureml/ml-frameworks/tensorflow/deployment/train-hyperparameter-tune-deploy-with-tensorflow/train-hyperparameter-tune-deploy-with-tensorflow.yml +++ b/how-to-use-azureml/ml-frameworks/tensorflow/deployment/train-hyperparameter-tune-deploy-with-tensorflow/train-hyperparameter-tune-deploy-with-tensorflow.yml @@ -1,13 +1,13 @@ name: train-hyperparameter-tune-deploy-with-tensorflow dependencies: - numpy -- tensorflow==1.10.0 - matplotlib - pip: - azureml-sdk - azureml-widgets - pandas - keras + - tensorflow==2.0.0 - matplotlib - azureml-dataprep - fuse diff --git a/how-to-use-azureml/ml-frameworks/tensorflow/training/hyperparameter-tune-and-warm-start-with-tensorflow/hyperparameter-tune-and-warm-start-with-tensorflow.ipynb b/how-to-use-azureml/ml-frameworks/tensorflow/training/hyperparameter-tune-and-warm-start-with-tensorflow/hyperparameter-tune-and-warm-start-with-tensorflow.ipynb index aabcacc5..30fe9e25 100644 --- a/how-to-use-azureml/ml-frameworks/tensorflow/training/hyperparameter-tune-and-warm-start-with-tensorflow/hyperparameter-tune-and-warm-start-with-tensorflow.ipynb +++ b/how-to-use-azureml/ml-frameworks/tensorflow/training/hyperparameter-tune-and-warm-start-with-tensorflow/hyperparameter-tune-and-warm-start-with-tensorflow.ipynb @@ -175,13 +175,13 @@ "os.makedirs(data_folder, exist_ok=True)\n", "\n", "urllib.request.urlretrieve('https://azureopendatastorage.blob.core.windows.net/mnist/train-images-idx3-ubyte.gz',\n", - " filename=os.path.join(data_folder, 'train-images.gz'))\n", + " filename=os.path.join(data_folder, 'train-images-idx3-ubyte.gz'))\n", "urllib.request.urlretrieve('https://azureopendatastorage.blob.core.windows.net/mnist/train-labels-idx1-ubyte.gz',\n", - " filename=os.path.join(data_folder, 'train-labels.gz'))\n", + " filename=os.path.join(data_folder, 'train-labels-idx1-ubyte.gz'))\n", "urllib.request.urlretrieve('https://azureopendatastorage.blob.core.windows.net/mnist/t10k-images-idx3-ubyte.gz',\n", - " filename=os.path.join(data_folder, 'test-images.gz'))\n", + " filename=os.path.join(data_folder, 't10k-images-idx3-ubyte.gz'))\n", "urllib.request.urlretrieve('https://azureopendatastorage.blob.core.windows.net/mnist/t10k-labels-idx1-ubyte.gz',\n", - " filename=os.path.join(data_folder, 'test-labels.gz'))" + " filename=os.path.join(data_folder, 't10k-labels-idx1-ubyte.gz'))" ] }, { @@ -209,10 +209,10 @@ "from utils import load_data\n", "\n", "# note we also shrink the intensity values (X) from 0-255 to 0-1. This helps the model converge faster.\n", - "X_train = load_data(os.path.join(data_folder, 'train-images.gz'), False) / 255.0\n", - "X_test = load_data(os.path.join(data_folder, 'test-images.gz'), False) / 255.0\n", - "y_train = load_data(os.path.join(data_folder, 'train-labels.gz'), True).reshape(-1)\n", - "y_test = load_data(os.path.join(data_folder, 'test-labels.gz'), True).reshape(-1)\n", + "X_train = load_data(os.path.join(data_folder, 'train-images-idx3-ubyte.gz'), False) / 255.0\n", + "X_test = load_data(os.path.join(data_folder, 't10k-images-idx3-ubyte.gz'), False) / 255.0\n", + "y_train = load_data(os.path.join(data_folder, 'train-labels-idx1-ubyte.gz'), True).reshape(-1)\n", + "y_test = load_data(os.path.join(data_folder, 't10k-labels-idx1-ubyte.gz'), True).reshape(-1)\n", "\n", "# now let's show some randomly chosen images from the training set.\n", "count = 0\n", @@ -243,10 +243,10 @@ "outputs": [], "source": [ "from azureml.core.dataset import Dataset\n", - "web_paths = ['http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz',\n", - " 'http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz',\n", - " 'http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz',\n", - " 'http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz'\n", + "web_paths = ['https://azureopendatastorage.blob.core.windows.net/mnist/train-images-idx3-ubyte.gz',\n", + " 'https://azureopendatastorage.blob.core.windows.net/mnist/train-labels-idx1-ubyte.gz',\n", + " 'https://azureopendatastorage.blob.core.windows.net/mnist/t10k-images-idx3-ubyte.gz',\n", + " 'https://azureopendatastorage.blob.core.windows.net/mnist/t10k-labels-idx1-ubyte.gz'\n", " ]\n", "dataset = Dataset.File.from_files(path = web_paths)" ] @@ -445,9 +445,9 @@ "# ensure latest azureml-dataprep and other required packages installed in the environment\n", "cd = CondaDependencies.create(pip_packages=['keras',\n", " 'azureml-sdk',\n", - " 'tensorflow==1.14.0',\n", + " 'tensorflow==2.0.0',\n", " 'matplotlib',\n", - " 'azureml-dataprep[pandas,fuse]>=1.1.14'])\n", + " 'azureml-dataprep[pandas,fuse]'])\n", "\n", "env.python.conda_dependencies = cd" ] @@ -466,9 +466,9 @@ "\n", "script_params = {\n", " '--data-folder': dataset.as_named_input('mnist').as_mount(),\n", - " '--batch-size': 50,\n", - " '--first-layer-neurons': 300,\n", - " '--second-layer-neurons': 100,\n", + " '--batch-size': 64,\n", + " '--first-layer-neurons': 256,\n", + " '--second-layer-neurons': 128,\n", " '--learning-rate': 0.01\n", "}\n", "\n", @@ -476,7 +476,7 @@ " script_params=script_params,\n", " compute_target=compute_target,\n", " entry_script='tf_mnist.py', \n", - " framework_version='1.13',\n", + " framework_version='2.0',\n", " environment_definition= env)" ] }, @@ -534,9 +534,9 @@ "\n", "ps = RandomParameterSampling(\n", " {\n", - " '--batch-size': choice(25, 50, 100),\n", - " '--first-layer-neurons': choice(10, 50, 200, 300, 500),\n", - " '--second-layer-neurons': choice(10, 50, 200, 500),\n", + " '--batch-size': choice(32, 64, 128),\n", + " '--first-layer-neurons': choice(16, 64, 128, 256, 512),\n", + " '--second-layer-neurons': choice(16, 64, 256, 512),\n", " '--learning-rate': loguniform(-6, -1)\n", " }\n", ")" @@ -558,7 +558,8 @@ "est = TensorFlow(source_directory=script_folder,\n", " script_params={'--data-folder': dataset.as_named_input('mnist').as_mount()},\n", " compute_target=compute_target,\n", - " entry_script='tf_mnist.py', \n", + " entry_script='tf_mnist.py',\n", + " framework_version='2.0',\n", " environment_definition = env)" ] }, @@ -566,7 +567,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Next we will define an early termnination policy. This will terminate poorly performing runs automatically, reducing wastage of resources and instead efficiently using these resources for exploring other parameter configurations. In this example, we will use the `TruncationSelectionPolicy`, truncating the bottom performing 10% runs. It states to check the job every 2 iterations. If the primary metric (defined later) falls in the bottom 25% range, Azure ML terminate the job. This saves us from continuing to explore hyperparameters that don't show promise of helping reach our target metric." + "Next we will define an early termnination policy. This will terminate poorly performing runs automatically, reducing wastage of resources and instead efficiently using these resources for exploring other parameter configurations. In this example, we will use the `TruncationSelectionPolicy`, truncating the bottom performing 25% runs. It states to check the job every 2 iterations. If the primary metric (defined later) falls in the bottom 25% range, Azure ML terminate the job. This saves us from continuing to explore hyperparameters that don't show promise of helping reach our target metric." ] }, { diff --git a/how-to-use-azureml/ml-frameworks/tensorflow/training/hyperparameter-tune-and-warm-start-with-tensorflow/hyperparameter-tune-and-warm-start-with-tensorflow.yml b/how-to-use-azureml/ml-frameworks/tensorflow/training/hyperparameter-tune-and-warm-start-with-tensorflow/hyperparameter-tune-and-warm-start-with-tensorflow.yml index 0c1fa94c..fa635e3b 100644 --- a/how-to-use-azureml/ml-frameworks/tensorflow/training/hyperparameter-tune-and-warm-start-with-tensorflow/hyperparameter-tune-and-warm-start-with-tensorflow.yml +++ b/how-to-use-azureml/ml-frameworks/tensorflow/training/hyperparameter-tune-and-warm-start-with-tensorflow/hyperparameter-tune-and-warm-start-with-tensorflow.yml @@ -7,7 +7,7 @@ dependencies: - azureml-widgets - pandas - keras - - tensorflow==1.14.0 + - tensorflow - matplotlib - azureml-dataprep - fuse diff --git a/how-to-use-azureml/ml-frameworks/tensorflow/training/hyperparameter-tune-and-warm-start-with-tensorflow/tf_mnist.py b/how-to-use-azureml/ml-frameworks/tensorflow/training/hyperparameter-tune-and-warm-start-with-tensorflow/tf_mnist.py index 3a08708f..d4ae3425 100644 --- a/how-to-use-azureml/ml-frameworks/tensorflow/training/hyperparameter-tune-and-warm-start-with-tensorflow/tf_mnist.py +++ b/how-to-use-azureml/ml-frameworks/tensorflow/training/hyperparameter-tune-and-warm-start-with-tensorflow/tf_mnist.py @@ -11,15 +11,74 @@ import glob from azureml.core import Run from utils import load_data +from tensorflow.keras import Model, layers + + +# Create TF Model. +class NeuralNet(Model): + # Set layers. + def __init__(self): + super(NeuralNet, self).__init__() + # First hidden layer. + self.h1 = layers.Dense(n_h1, activation=tf.nn.relu) + # Second hidden layer. + self.h2 = layers.Dense(n_h2, activation=tf.nn.relu) + self.out = layers.Dense(n_outputs) + + # Set forward pass. + def call(self, x, is_training=False): + x = self.h1(x) + x = self.h2(x) + x = self.out(x) + if not is_training: + # Apply softmax when not training. + x = tf.nn.softmax(x) + return x + + +def cross_entropy_loss(y, logits): + # Convert labels to int 64 for tf cross-entropy function. + y = tf.cast(y, tf.int64) + # Apply softmax to logits and compute cross-entropy. + loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y, logits=logits) + # Average loss across the batch. + return tf.reduce_mean(loss) + + +# Accuracy metric. +def accuracy(y_pred, y_true): + # Predicted class is the index of highest score in prediction vector (i.e. argmax). + correct_prediction = tf.equal(tf.argmax(y_pred, 1), tf.cast(y_true, tf.int64)) + return tf.reduce_mean(tf.cast(correct_prediction, tf.float32), axis=-1) + + +# Optimization process. +def run_optimization(x, y): + # Wrap computation inside a GradientTape for automatic differentiation. + with tf.GradientTape() as g: + # Forward pass. + logits = neural_net(x, is_training=True) + # Compute loss. + loss = cross_entropy_loss(y, logits) + + # Variables to update, i.e. trainable variables. + trainable_variables = neural_net.trainable_variables + + # Compute gradients. + gradients = g.gradient(loss, trainable_variables) + + # Update W and b following gradients. + optimizer.apply_gradients(zip(gradients, trainable_variables)) + print("TensorFlow version:", tf.__version__) parser = argparse.ArgumentParser() -parser.add_argument('--data-folder', type=str, dest='data_folder', help='data folder mounting point') -parser.add_argument('--batch-size', type=int, dest='batch_size', default=50, help='mini batch size for training') -parser.add_argument('--first-layer-neurons', type=int, dest='n_hidden_1', default=100, +parser.add_argument('--data-folder', type=str, dest='data_folder', default='data', help='data folder mounting point') +parser.add_argument('--batch-size', type=int, dest='batch_size', default=128, help='mini batch size for training') +parser.add_argument('--first-layer-neurons', type=int, dest='n_hidden_1', default=128, help='# of neurons in the first layer') -parser.add_argument('--second-layer-neurons', type=int, dest='n_hidden_2', default=100, +parser.add_argument('--second-layer-neurons', type=int, dest='n_hidden_2', default=128, help='# of neurons in the second layer') parser.add_argument('--learning-rate', type=float, dest='learning_rate', default=0.01, help='learning rate') parser.add_argument('--resume-from', type=str, default=None, @@ -36,9 +95,9 @@ print('Data folder:', data_folder) # load train and test set into numpy arrays # note we scale the pixel intensity values to 0-1 (by dividing it with 255.0) so the model can converge faster. X_train = load_data(glob.glob(os.path.join(data_folder, '**/train-images-idx3-ubyte.gz'), - recursive=True)[0], False) / 255.0 + recursive=True)[0], False) / np.float32(255.0) X_test = load_data(glob.glob(os.path.join(data_folder, '**/t10k-images-idx3-ubyte.gz'), - recursive=True)[0], False) / 255.0 + recursive=True)[0], False) / np.float32(255.0) y_train = load_data(glob.glob(os.path.join(data_folder, '**/train-labels-idx1-ubyte.gz'), recursive=True)[0], True).reshape(-1) y_test = load_data(glob.glob(os.path.join(data_folder, '**/t10k-labels-idx1-ubyte.gz'), @@ -56,88 +115,77 @@ learning_rate = args.learning_rate n_epochs = 20 batch_size = args.batch_size -with tf.name_scope('network'): - # construct the DNN - X = tf.placeholder(tf.float32, shape=(None, n_inputs), name='X') - y = tf.placeholder(tf.int64, shape=(None), name='y') - h1 = tf.layers.dense(X, n_h1, activation=tf.nn.relu, name='h1') - h2 = tf.layers.dense(h1, n_h2, activation=tf.nn.relu, name='h2') - output = tf.layers.dense(h2, n_outputs, name='output') +# Build neural network model. +neural_net = NeuralNet() -with tf.name_scope('train'): - cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y, logits=output) - loss = tf.reduce_mean(cross_entropy, name='loss') - optimizer = tf.train.GradientDescentOptimizer(learning_rate) - train_op = optimizer.minimize(loss) - -with tf.name_scope('eval'): - correct = tf.nn.in_top_k(output, y, 1) - acc_op = tf.reduce_mean(tf.cast(correct, tf.float32)) - -init = tf.global_variables_initializer() -saver = tf.train.Saver() +# Stochastic gradient descent optimizer. +optimizer = tf.optimizers.SGD(learning_rate) # start an Azure ML run run = Run.get_context() -with tf.Session() as sess: - start_time = time.perf_counter() +if previous_model_location: + # Restore variables from latest checkpoint. + checkpoint = tf.train.Checkpoint(model=neural_net, optimizer=optimizer) + checkpoint_file_path = tf.train.latest_checkpoint(previous_model_location) + checkpoint.restore(checkpoint_file_path) + checkpoint_filename = os.path.basename(checkpoint_file_path) + num_found = re.search(r'\d+', checkpoint_filename) + if num_found: + start_epoch = int(num_found.group(0)) + print("Resuming from epoch {}".format(str(start_epoch))) - start_epoch = 0 - if previous_model_location: - checkpoint_file_path = tf.train.latest_checkpoint(previous_model_location) - saver.restore(sess, checkpoint_file_path) - checkpoint_filename = os.path.basename(checkpoint_file_path) - num_found = re.search(r'\d+', checkpoint_filename) - if num_found: - start_epoch = int(num_found.group(0)) - print("Resuming from epoch {}".format(str(start_epoch))) - else: - init.run() +start_time = time.perf_counter() +for epoch in range(0, n_epochs): - for epoch in range(start_epoch, n_epochs): + # randomly shuffle training set + indices = np.random.permutation(training_set_size) + X_train = X_train[indices] + y_train = y_train[indices] - # randomly shuffle training set - indices = np.random.permutation(training_set_size) - X_train = X_train[indices] - y_train = y_train[indices] + # batch index + b_start = 0 + b_end = b_start + batch_size + for _ in range(training_set_size // batch_size): + # get a batch + X_batch, y_batch = X_train[b_start: b_end], y_train[b_start: b_end] - # batch index - b_start = 0 - b_end = b_start + batch_size - for _ in range(training_set_size // batch_size): - # get a batch - X_batch, y_batch = X_train[b_start: b_end], y_train[b_start: b_end] + # update batch index for the next batch + b_start = b_start + batch_size + b_end = min(b_start + batch_size, training_set_size) - # update batch index for the next batch - b_start = b_start + batch_size - b_end = min(b_start + batch_size, training_set_size) + # train + run_optimization(X_batch, y_batch) - # train - sess.run(train_op, feed_dict={X: X_batch, y: y_batch}) - # evaluate training set - acc_train = acc_op.eval(feed_dict={X: X_batch, y: y_batch}) - # evaluate validation set - acc_val = acc_op.eval(feed_dict={X: X_test, y: y_test}) + # evaluate training set + pred = neural_net(X_batch, is_training=False) + acc_train = accuracy(pred, y_batch) - time.sleep(10) + # evaluate validation set + pred = neural_net(X_test, is_training=False) + acc_val = accuracy(pred, y_test) - # log accuracies - run.log('training_acc', np.float(acc_train)) - run.log('validation_acc', np.float(acc_val)) - print(epoch, '-- Training accuracy:', acc_train, '\b Validation accuracy:', acc_val) - y_hat = np.argmax(output.eval(feed_dict={X: X_test}), axis=1) + # log accuracies + run.log('training_acc', np.float(acc_train)) + run.log('validation_acc', np.float(acc_val)) + print(epoch, '-- Training accuracy:', acc_train, '\b Validation accuracy:', acc_val) - # Save checkpoints in the "./outputs" folder so that they are automatically uploaded into run history. - if epoch % 2 == 0: - saver.save(sess, './outputs/', global_step=epoch) + # Save checkpoints in the "./outputs" folder so that they are automatically uploaded into run history. + checkpoint_dir = './outputs/' + checkpoint = tf.train.Checkpoint(model=neural_net, optimizer=optimizer) - run.log('final_acc', np.float(acc_val)) + if epoch % 2 == 0: + checkpoint.save(checkpoint_dir) + time.sleep(3) - os.makedirs('./outputs/model', exist_ok=True) - # files saved in the "./outputs" folder are automatically uploaded into run history - saver.save(sess, './outputs/model/mnist-tf.model') +run.log('final_acc', np.float(acc_val)) +os.makedirs('./outputs/model', exist_ok=True) - stop_time = time.perf_counter() - training_time = (stop_time - start_time) * 1000 - print("Total time in milliseconds for training: {}".format(str(training_time))) +# files saved in the "./outputs" folder are automatically uploaded into run history +# this is workaround for https://github.com/tensorflow/tensorflow/issues/33913 and will be fixed once we move to >tf2.1 +neural_net._set_inputs(X_train) +tf.saved_model.save(neural_net, './outputs/model/') + +stop_time = time.perf_counter() +training_time = (stop_time - start_time) * 1000 +print("Total time in milliseconds for training: {}".format(str(training_time))) diff --git a/how-to-use-azureml/monitor-models/data-drift/drift-on-aks.ipynb b/how-to-use-azureml/monitor-models/data-drift/drift-on-aks.ipynb index 9131ed12..3eed691c 100644 --- a/how-to-use-azureml/monitor-models/data-drift/drift-on-aks.ipynb +++ b/how-to-use-azureml/monitor-models/data-drift/drift-on-aks.ipynb @@ -184,11 +184,10 @@ "prov_config = AksCompute.provisioning_configuration()\n", "\n", "aks_name = 'drift-aks'\n", + "aks_target = ws.compute_targets.get(aks_name)\n", "\n", "# Create the cluster\n", - "try:\n", - " aks_target = ws.compute_targets[aks_name]\n", - "except KeyError:\n", + "if not aks_target:\n", " aks_target = ComputeTarget.create(workspace = ws,\n", " name = aks_name,\n", " provisioning_configuration = prov_config)\n", diff --git a/how-to-use-azureml/reinforcement-learning/README.md b/how-to-use-azureml/reinforcement-learning/README.md new file mode 100644 index 00000000..2a322a03 --- /dev/null +++ b/how-to-use-azureml/reinforcement-learning/README.md @@ -0,0 +1,118 @@ + +# Azure Machine Learning - Reinforcement Learning (Public Preview) + + + +This is an introduction to the [Azure Machine Learning](https://docs.microsoft.com/en-us/azure/machine-learning/service/) Reinforcement Learning (Public Preview) using the [Ray](https://github.com/ray-project/ray/) framework. + +Using these samples, you will be able to do the following. + +1. Use an Azure Machine Learning workspace, set up virtual network and create compute clusters for running Ray. +2. Run some experiments to train a reinforcement learning agent using Ray and RLlib. + +## Contents + +| File/folder | Description | +|-------------------|--------------------------------------------| +| [README.md](README.md) | This README file. | +| [devenv_setup.ipynb](setup/devenv_setup.ipynb) | Notebook to setup development environment for Azure ML RL | +| [cartpole_ci.ipynb](cartpole-on-compute-instance/cartpole_ci.ipynb) | Notebook to train a Cartpole playing agent on an Azure ML Compute Instance | +| [cartpole_cc.ipynb](cartpole-on-single-compute/cartpole_cc.ipynb) | Notebook to train a Cartpole playing agent on an Azure ML Compute Cluster (single node) | +| [pong_rllib.ipynb](atari-on-distributed-compute/pong_rllib.ipynb) | Notebook to train Pong agent using RLlib on multiple compute targets | + +## Prerequisites + +To make use of these samples, you need the following. + +* A Microsoft Azure subscription. +* A Microsoft Azure resource group. +* An Azure Machine Learning Workspace in the resource group. Please make sure that the VM sizes `STANDARD_NC6` and `STANDARD_D2_V2` are supported in the workspace's region. +* A virtual network set up in the resource group. + * A virtual network is needed for the examples training on multiple compute targets. + * The [devenv_setup.ipynb](setup/devenv_setup.ipynb) notebook shows you how to create a virtual network. You can alternatively use an existing virtual network, make sure it's in the same region as workspace is. + * Any network security group defined on the virtual network must allow network traffic on ports used by Azure infrastructure services. This is described in more detail in the [devenv_setup.ipynb](setup/devenv_setup.ipynb) notebook. + + +## Setup + +You can run these samples in the following ways. + +* On an Azure ML Compute Instance or Notebook VM. +* On a workstation with Python and the Azure ML Python SDK installed. + +### Azure ML Compute Instance or Notebook VM +#### Update packages + + +We recommend that you update the required Python packages before you proceed. The following commands are for entering in a Python interpreter such as a notebook. + +```shell +# We recommend updating pip to the latest version. +!pip install --upgrade pip +# Update matplotlib for plotting charts +!pip install --upgrade matplotlib +# Update Azure Machine Learning SDK to the latest version +!pip install --upgrade azureml-sdk +# For Jupyter notebook widget used in samples +!pip install --upgrade azureml-widgets +# For Tensorboard used in samples +!pip install --upgrade azureml-tensorboard +# Install Azure Machine Learning Reinforcement Learning SDK +!pip install --upgrade azureml-contrib-reinforcementlearning +``` + +### Your own workstation +#### Install/update packages + +For a local workstation, create a Python environment and install [Azure Machine Learning SDK](https://docs.microsoft.com/en-us/python/api/overview/azure/ml/install?view=azure-ml-py) and the RL SDK. We recommend Python 3.6 and higher. + +```shell +# Activate your environment first. +# e.g., +# conda activate amlrl +# We recommend updating pip to the latest version. +pip install --upgrade pip +# Install/upgrade matplotlib for plotting charts +pip install --upgrade matplotlib +# Install/upgrade tensorboard used in samples +pip install --upgrade tensorboard +# Install/upgrade Azure ML SDK to the latest version +pip install --upgrade azureml-sdk +# For Jupyter notebook widget used in samples +pip install --upgrade azureml-widgets +# For Tensorboard used in samples +pip install --upgrade azureml-tensorboard +# Install Azure Machine Learning Reinforcement Learning SDK +pip install --upgrade azureml-contrib-reinforcementlearning +# To use the notebook widget, you may need to register and enable the Azure ML extensions first. +jupyter nbextension install --py --user azureml.widgets +jupyter nbextension enable --py --user azureml.widgets +``` + +## Contributing + +This project welcomes contributions and suggestions. Most contributions require you to agree to a +Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us +the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com. + +When you submit a pull request, a CLA bot will automatically determine whether you need to provide +a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions +provided by the bot. You will only need to do this once across all repos using our CLA. + +This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). +For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or +contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. + +For more on SDK concepts, please refer to [notebooks](https://github.com/Azure/MachineLearningNotebooks). + +**Please let us know your feedback.** + + + + \ No newline at end of file diff --git a/how-to-use-azureml/reinforcement-learning/atari-on-distributed-compute/files/pong_rllib.py b/how-to-use-azureml/reinforcement-learning/atari-on-distributed-compute/files/pong_rllib.py new file mode 100644 index 00000000..c78a19c6 --- /dev/null +++ b/how-to-use-azureml/reinforcement-learning/atari-on-distributed-compute/files/pong_rllib.py @@ -0,0 +1,39 @@ +import ray +import ray.tune as tune +from ray.rllib import train + +import os +import sys + +from azureml.core import Run +from utils import callbacks + +DEFAULT_RAY_ADDRESS = 'localhost:6379' + +if __name__ == "__main__": + + # Parse arguments + train_parser = train.create_parser() + + args = train_parser.parse_args() + print("Algorithm config:", args.config) + + if args.ray_address is None: + args.ray_address = DEFAULT_RAY_ADDRESS + + ray.init(address=args.ray_address) + + tune.run(run_or_experiment=args.run, + config={ + "env": args.env, + "num_gpus": args.config["num_gpus"], + "num_workers": args.config["num_workers"], + "callbacks": {"on_train_result": callbacks.on_train_result}, + "sample_batch_size": 50, + "train_batch_size": 1000, + "num_sgd_iter": 2, + "num_data_loader_buffers": 2, + "model": {"dim": 42}, + }, + stop=args.stop, + local_dir='./logs') diff --git a/how-to-use-azureml/reinforcement-learning/atari-on-distributed-compute/files/utils/callbacks.py b/how-to-use-azureml/reinforcement-learning/atari-on-distributed-compute/files/utils/callbacks.py new file mode 100644 index 00000000..f34a4e8c --- /dev/null +++ b/how-to-use-azureml/reinforcement-learning/atari-on-distributed-compute/files/utils/callbacks.py @@ -0,0 +1,17 @@ +'''RLlib callbacks module: + Common callback methods to be passed to RLlib trainer. +''' + +from azureml.core import Run + + +def on_train_result(info): + '''Callback on train result to record metrics returned by trainer. + ''' + run = Run.get_context() + run.log( + name='episode_reward_mean', + value=info["result"]["episode_reward_mean"]) + run.log( + name='episodes_total', + value=info["result"]["episodes_total"]) diff --git a/how-to-use-azureml/reinforcement-learning/atari-on-distributed-compute/images/pong.gif b/how-to-use-azureml/reinforcement-learning/atari-on-distributed-compute/images/pong.gif new file mode 100644 index 00000000..c29cc4a3 Binary files /dev/null and b/how-to-use-azureml/reinforcement-learning/atari-on-distributed-compute/images/pong.gif differ diff --git a/how-to-use-azureml/reinforcement-learning/atari-on-distributed-compute/pong_rllib.ipynb b/how-to-use-azureml/reinforcement-learning/atari-on-distributed-compute/pong_rllib.ipynb new file mode 100644 index 00000000..0979479b --- /dev/null +++ b/how-to-use-azureml/reinforcement-learning/atari-on-distributed-compute/pong_rllib.ipynb @@ -0,0 +1,604 @@ +{ + "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": [ + "# Azure ML Reinforcement Learning Sample - Pong problem\n", + "Azure ML Reinforcement Learning (Azure ML RL) is a managed service for running distributed RL (reinforcement learning) simulation and training using the Ray framework.\n", + "This example uses Ray RLlib to train a Pong playing agent on a multi-node cluster.\n", + "\n", + "## Pong problem\n", + "[Pong](https://en.wikipedia.org/wiki/Pong) is a two-dimensional sports game that simulates table tennis. The player controls an in-game paddle by moving it vertically across the left or right side of the screen. They can compete against another player controlling a second paddle on the opposing side. Players use the paddles to hit a ball back and forth." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
![]() | \n",
+ "
|---|
| Fig 1. Pong game animation (from towardsdatascience.com). | \n", + "
\n",
+ " \n",
+ " | \n",
+ "
|---|
Fig 1. Cartpole problem schematic description (from towardsdatascience.com). | \n",
+ "
\n",
+ " \n",
+ " | \n",
+ "
|---|
Fig 1. Cartpole problem schematic description (from towardsdatascience.com). | \n",
+ "