update samples from Release-66 as a part of SDK release

This commit is contained in:
amlrelsa-ms
2020-09-21 23:02:01 +00:00
parent bb1c7db690
commit 824d844cd7
92 changed files with 10892 additions and 3303 deletions

View File

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

View File

@@ -24,5 +24,5 @@ dependencies:
- pytorch-transformers==1.0.0 - pytorch-transformers==1.0.0
- spacy==2.1.8 - spacy==2.1.8
- https://aka.ms/automl-resources/packages/en_core_web_sm-2.1.0.tar.gz - https://aka.ms/automl-resources/packages/en_core_web_sm-2.1.0.tar.gz
- -r https://automlcesdkdataresources.blob.core.windows.net/validated-requirements/1.13.0/validated_win32_requirements.txt [--no-deps] - -r https://automlcesdkdataresources.blob.core.windows.net/validated-requirements/1.14.0/validated_win32_requirements.txt [--no-deps]

View File

@@ -24,5 +24,5 @@ dependencies:
- pytorch-transformers==1.0.0 - pytorch-transformers==1.0.0
- spacy==2.1.8 - spacy==2.1.8
- https://aka.ms/automl-resources/packages/en_core_web_sm-2.1.0.tar.gz - https://aka.ms/automl-resources/packages/en_core_web_sm-2.1.0.tar.gz
- -r https://automlcesdkdataresources.blob.core.windows.net/validated-requirements/1.13.0/validated_linux_requirements.txt [--no-deps] - -r https://automlcesdkdataresources.blob.core.windows.net/validated-requirements/1.14.0/validated_linux_requirements.txt [--no-deps]

View File

@@ -25,4 +25,4 @@ dependencies:
- pytorch-transformers==1.0.0 - pytorch-transformers==1.0.0
- spacy==2.1.8 - spacy==2.1.8
- https://aka.ms/automl-resources/packages/en_core_web_sm-2.1.0.tar.gz - https://aka.ms/automl-resources/packages/en_core_web_sm-2.1.0.tar.gz
- -r https://automlcesdkdataresources.blob.core.windows.net/validated-requirements/1.13.0/validated_darwin_requirements.txt [--no-deps] - -r https://automlcesdkdataresources.blob.core.windows.net/validated-requirements/1.14.0/validated_darwin_requirements.txt [--no-deps]

View File

@@ -105,7 +105,7 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"print(\"This notebook was created using version 1.13.0 of the Azure ML SDK\")\n", "print(\"This notebook was created using version 1.14.0 of the Azure ML SDK\")\n",
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")" "print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
] ]
}, },
@@ -500,9 +500,8 @@
"source": [ "source": [
"# Wait for the best model explanation run to complete\n", "# Wait for the best model explanation run to complete\n",
"from azureml.core.run import Run\n", "from azureml.core.run import Run\n",
"model_explainability_run_id = remote_run.get_properties().get('ModelExplainRunId')\n", "model_explainability_run_id = remote_run.id + \"_\" + \"ModelExplain\"\n",
"print(model_explainability_run_id)\n", "print(model_explainability_run_id)\n",
"if model_explainability_run_id is not None:\n",
"model_explainability_run = Run(experiment=experiment, run_id=model_explainability_run_id)\n", "model_explainability_run = Run(experiment=experiment, run_id=model_explainability_run_id)\n",
"model_explainability_run.wait_for_completion()\n", "model_explainability_run.wait_for_completion()\n",
"\n", "\n",

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,36 +0,0 @@
## Examples to get started with Azure Machine Learning SDK for R
Learn how to use Azure Machine Learning SDK for R for experimentation and model management.
As a pre-requisite, go through the [Installation](vignettes/installation.Rmd) and [Configuration](vignettes/configuration.Rmd) vignettes to first install the package and set up your Azure Machine Learning Workspace unless you are running these examples on an Azure Machine Learning compute instance. Azure Machine Learning compute instances have the Azure Machine Learning SDK pre-installed and your workspace details pre-configured.
Samples
* Deployment
* [deploy-to-aci](./samples/deployment/deploy-to-aci): Deploy a model as a web service to Azure Container Instances (ACI).
* [deploy-to-local](./samples/deployment/deploy-to-local): Deploy a model as a web service locally.
* Training
* [train-on-amlcompute](./samples/training/train-on-amlcompute): Train a model on a remote AmlCompute cluster.
* [train-on-local](./samples/training/train-on-local): Train a model locally with Docker.
Vignettes
* [deploy-to-aks](./vignettes/deploy-to-aks): Production deploy a model as a web service to Azure Kubernetes Service (AKS).
* [hyperparameter-tune-with-keras](./vignettes/hyperparameter-tune-with-keras): Hyperparameter tune a Keras model using HyperDrive, Azure ML's hyperparameter tuning functionality.
* [train-and-deploy-to-aci](./vignettes/train-and-deploy-to-aci): Train a caret model and deploy as a web service to Azure Container Instances (ACI).
* [train-with-tensorflow](./vignettes/train-with-tensorflow): Train a deep learning TensorFlow model with Azure ML.
Find more information on the [official documentation site for Azure Machine Learning SDK for R](https://azure.github.io/azureml-sdk-for-r/).
### Troubleshooting
- If the following error occurs when submitting an experiment using RStudio:
```R
Error in py_call_impl(callable, dots$args, dots$keywords) :
PermissionError: [Errno 13] Permission denied
```
Move the files for your project into a subdirectory and reset the working directory to that directory before re-submitting.
In order to submit an experiment, the Azure ML SDK must create a .zip file of the project directory to send to the service. However,
the SDK does not have permission to write into the .Rproj.user subdirectory that is automatically created during an RStudio
session. For this reason, the recommended best practice is to isolate project files into their own directory.

View File

@@ -1,11 +0,0 @@
## Azure Machine Learning samples
These samples are short code examples for using Azure Machine Learning SDK for R. If you are new to the R SDK, we recommend that you first take a look at the more detailed end-to-end [vignettes](../vignettes).
Before running a sample in RStudio, set the working directory to the folder that contains the sample script in RStudio using `setwd(dirname)` or Session -> Set Working Directory -> To Source File Location. Each vignette assumes that the data and scripts are in the current working directory.
1. [train-on-amlcompute](training/train-on-amlcompute): Train a model on a remote AmlCompute cluster.
2. [train-on-local](training/train-on-local): Train a model locally with Docker.
2. [deploy-to-aci](deployment/deploy-to-aci): Deploy a model as a web service to Azure Container Instances (ACI).
3. [deploy-to-local](deployment/deploy-to-local): Deploy a model as a web service locally.
> Before you run these samples, make sure you have an Azure Machine Learning workspace. You can follow the [configuration vignette](../vignettes/configuration.Rmd) to set up a workspace. (You do not need to do this if you are running these examples on an Azure Machine Learning compute instance).

View File

@@ -1,59 +0,0 @@
# Copyright(c) Microsoft Corporation.
# Licensed under the MIT license.
library(azuremlsdk)
library(jsonlite)
ws <- load_workspace_from_config()
# Register the model
model <- register_model(ws, model_path = "project_files/model.rds",
model_name = "model.rds")
# Create environment
r_env <- r_environment(name = "r_env")
# Create inference config
inference_config <- inference_config(
entry_script = "score.R",
source_directory = "project_files",
environment = r_env)
# Create ACI deployment config
deployment_config <- aci_webservice_deployment_config(cpu_cores = 1,
memory_gb = 1)
# Deploy the web service
service <- deploy_model(ws,
'rservice',
list(model),
inference_config,
deployment_config)
wait_for_deployment(service, show_output = TRUE)
# If you encounter any issue in deploying the webservice, please visit
# https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-troubleshoot-deployment
# Inferencing
# versicolor
plant <- data.frame(Sepal.Length = 6.4,
Sepal.Width = 2.8,
Petal.Length = 4.6,
Petal.Width = 1.8)
# setosa
plant <- data.frame(Sepal.Length = 5.1,
Sepal.Width = 3.5,
Petal.Length = 1.4,
Petal.Width = 0.2)
# virginica
plant <- data.frame(Sepal.Length = 6.7,
Sepal.Width = 3.3,
Petal.Length = 5.2,
Petal.Width = 2.3)
# Test the web service
predicted_val <- invoke_webservice(service, toJSON(plant))
predicted_val
# Delete the web service
delete_webservice(service)

View File

@@ -1,17 +0,0 @@
# Copyright(c) Microsoft Corporation.
# Licensed under the MIT license.
library(jsonlite)
init <- function() {
model_path <- Sys.getenv("AZUREML_MODEL_DIR")
model <- readRDS(file.path(model_path, "model.rds"))
message("model is loaded")
function(data) {
plant <- as.data.frame(fromJSON(data))
prediction <- predict(model, plant)
result <- as.character(prediction)
toJSON(result)
}
}

View File

@@ -1,112 +0,0 @@
# Copyright(c) Microsoft Corporation.
# Licensed under the MIT license.
# Register model and deploy locally
# This example shows how to deploy a web service in step-by-step fashion:
#
# 1) Register model
# 2) Deploy the model as a web service in a local Docker container.
# 3) Invoke web service with SDK or call web service with raw HTTP call.
# 4) Quickly test changes to your entry script by reloading the local service.
# 5) Optionally, you can also make changes to model and update the local service.
library(azuremlsdk)
library(jsonlite)
ws <- load_workspace_from_config()
# Register the model
model <- register_model(ws, model_path = "project_files/model.rds",
model_name = "model.rds")
# Create environment
r_env <- r_environment(name = "r_env")
# Create inference config
inference_config <- inference_config(
entry_script = "score.R",
source_directory = "project_files",
environment = r_env)
# Create local deployment config
local_deployment_config <- local_webservice_deployment_config()
# Deploy the web service
# NOTE:
# The Docker image runs as a Linux container. If you are running Docker for Windows, you need to ensure the Linux Engine is running:
# # PowerShell command to switch to Linux engine
# & 'C:\Program Files\Docker\Docker\DockerCli.exe' -SwitchLinuxEngine
service <- deploy_model(ws,
'rservice-local',
list(model),
inference_config,
local_deployment_config)
# Wait for deployment
wait_for_deployment(service, show_output = TRUE)
# Show the port of local service
message(service$port)
# If you encounter any issue in deploying the webservice, please visit
# https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-troubleshoot-deployment
# Inferencing
# versicolor
# plant <- data.frame(Sepal.Length = 6.4,
# Sepal.Width = 2.8,
# Petal.Length = 4.6,
# Petal.Width = 1.8)
# setosa
plant <- data.frame(Sepal.Length = 5.1,
Sepal.Width = 3.5,
Petal.Length = 1.4,
Petal.Width = 0.2)
# # virginica
# plant <- data.frame(Sepal.Length = 6.7,
# Sepal.Width = 3.3,
# Petal.Length = 5.2,
# Petal.Width = 2.3)
#Test the web service
invoke_webservice(service, toJSON(plant))
## The last few lines of the logs should have the correct prediction and should display -> R[write to console]: "setosa"
cat(gsub(pattern = "\n", replacement = " \n", x = get_webservice_logs(service)))
## Test the web service with a HTTP Raw request
#
# NOTE:
# To test the service locally use the https://localhost:<local_service$port> URL
# Import the request library
library(httr)
# Get the service scoring URL from the service object, its URL is for testing locally
local_service_url <- service$scoring_uri #Same as https://localhost:<local_service$port>
#POST request to web service
resp <- POST(local_service_url, body = plant, encode = "json", verbose())
## The last few lines of the logs should have the correct prediction and should display -> R[write to console]: "setosa"
cat(gsub(pattern = "\n", replacement = " \n", x = get_webservice_logs(service)))
# Optional, use a new scoring script
inference_config <- inference_config(
entry_script = "score_new.R",
source_directory = "project_files",
environment = r_env)
## Then reload the service to see the changes made
reload_local_webservice_assets(service)
## Check reloaded service, you will see the last line will say "this is a new scoring script! I was reloaded"
invoke_webservice(service, toJSON(plant))
cat(gsub(pattern = "\n", replacement = " \n", x = get_webservice_logs(service)))
# Update service
# If you want to change your model(s), environment, or deployment configuration, call update() to rebuild the Docker image.
# update_local_webservice(service, models = [NewModelObject], deployment_config = deployment_config, wait = FALSE, inference_config = inference_config)
# Delete service
delete_local_webservice(service)

View File

@@ -1,18 +0,0 @@
# Copyright(c) Microsoft Corporation.
# Licensed under the MIT license.
library(jsonlite)
init <- function() {
model_path <- Sys.getenv("AZUREML_MODEL_DIR")
model <- readRDS(file.path(model_path, "model.rds"))
message("model is loaded")
function(data) {
plant <- as.data.frame(fromJSON(data))
prediction <- predict(model, plant)
result <- as.character(prediction)
message(result)
toJSON(result)
}
}

View File

@@ -1,19 +0,0 @@
# Copyright(c) Microsoft Corporation.
# Licensed under the MIT license.
library(jsonlite)
init <- function() {
model_path <- Sys.getenv("AZUREML_MODEL_DIR")
model <- readRDS(file.path(model_path, "model.rds"))
message("model is loaded")
function(data) {
plant <- as.data.frame(fromJSON(data))
prediction <- predict(model, plant)
result <- as.character(prediction)
message(result)
message("this is a new scoring script! I was reloaded")
toJSON(result)
}
}

View File

@@ -1,34 +0,0 @@
# This script loads a dataset of which the last column is supposed to be the
# class and logs the accuracy
library(azuremlsdk)
library(caret)
library(optparse)
library(datasets)
iris_data <- data(iris)
summary(iris_data)
in_train <- createDataPartition(y = iris_data$Species, p = .8, list = FALSE)
train_data <- iris_data[in_train,]
test_data <- iris_data[-in_train,]
# Run algorithms using 10-fold cross validation
control <- trainControl(method = "cv", number = 10)
metric <- "Accuracy"
set.seed(7)
model <- train(Species ~ .,
data = train_data,
method = "lda",
metric = metric,
trControl = control)
predictions <- predict(model, test_data)
conf_matrix <- confusionMatrix(predictions, test_data$Species)
message(conf_matrix)
log_metric_to_run(metric, conf_matrix$overall["Accuracy"])
saveRDS(model, file = "./outputs/model.rds")
message("Model saved")

View File

@@ -1,41 +0,0 @@
# Copyright(c) Microsoft Corporation.
# Licensed under the MIT license.
# Reminder: set working directory to current file location prior to running this script
library(azuremlsdk)
ws <- load_workspace_from_config()
# Create AmlCompute cluster
cluster_name <- "r-cluster"
compute_target <- get_compute(ws, cluster_name = cluster_name)
if (is.null(compute_target)) {
vm_size <- "STANDARD_D2_V2"
compute_target <- create_aml_compute(workspace = ws,
cluster_name = cluster_name,
vm_size = vm_size,
max_nodes = 1)
wait_for_provisioning_completion(compute_target, show_output = TRUE)
}
# Define estimator
est <- estimator(source_directory = "scripts",
entry_script = "train.R",
compute_target = compute_target)
experiment_name <- "train-r-script-on-amlcompute"
exp <- experiment(ws, experiment_name)
# Submit job and display the run details
run <- submit_experiment(exp, est)
view_run_details(run)
wait_for_run_completion(run, show_output = TRUE)
# Get the run metrics
metrics <- get_run_metrics(run)
metrics
# Delete cluster
delete_compute(compute_target)

View File

@@ -1,28 +0,0 @@
# This script loads a dataset of which the last column is supposed to be the
# class and logs the accuracy
library(azuremlsdk)
library(caret)
library(datasets)
iris_data <- data(iris)
summary(iris_data)
in_train <- createDataPartition(y = iris_data$Species, p = .8, list = FALSE)
train_data <- iris_data[in_train,]
test_data <- iris_data[-in_train,]
# Run algorithms using 10-fold cross validation
control <- trainControl(method = "cv", number = 10)
metric <- "Accuracy"
set.seed(7)
model <- train(Species ~ .,
data = train_data,
method = "lda",
metric = metric,
trControl = control)
predictions <- predict(model, test_data)
conf_matrix <- confusionMatrix(predictions, test_data$Species)
message(conf_matrix)
log_metric_to_run(metric, conf_matrix$overall["Accuracy"])

View File

@@ -1,26 +0,0 @@
# Copyright(c) Microsoft Corporation.
# Licensed under the MIT license.
# Reminder: set working directory to current file location prior to running this script
library(azuremlsdk)
ws <- load_workspace_from_config()
# Define estimator
est <- estimator(source_directory = "scripts",
entry_script = "train.R",
compute_target = "local")
# Initialize experiment
experiment_name <- "train-r-script-on-local"
exp <- experiment(ws, experiment_name)
# Submit job and display the run details
run <- submit_experiment(exp, est)
view_run_details(run)
wait_for_run_completion(run, show_output = TRUE)
# Get the run metrics
metrics <- get_run_metrics(run)
metrics

View File

@@ -1,17 +0,0 @@
## Azure Machine Learning vignettes
These vignettes are end-to-end tutorials for using Azure Machine Learning SDK for R.
Before running a vignette in RStudio, set the working directory to the folder that contains the vignette file (.Rmd file) in RStudio using `setwd(dirname)` or Session -> Set Working Directory -> To Source File Location. Each vignette assumes that the data and scripts are in the current working directory.
The following vignettes are included:
1. [installation](installation.Rmd): Install the Azure ML SDK for R.
2. [configuration](configuration.Rmd): Set up an Azure ML workspace.
3. [train-and-deploy-to-aci](train-and-deploy-to-aci): Train a caret model and deploy as a web service to Azure Container Instances (ACI).
4. [train-with-tensorflow](train-with-tensorflow/): Train a deep learning TensorFlow model with Azure ML.
5. [hyperparameter-tune-with-keras](hyperparameter-tune-with-keras/): Hyperparameter tune a Keras model using HyperDrive, Azure ML's hyperparameter tuning functionality.
6. [deploy-to-aks](deploy-to-aks/): Production deploy a model as a web service to Azure Kubernetes Service (AKS).
> Before you run these samples, make sure you have an Azure Machine Learning workspace. You can follow the [configuration vignette](../vignettes/configuration.Rmd) to set up a workspace. (You do not need to do this if you are running these examples on an Azure Machine Learning compute instance).
For additional examples on using the R SDK, see the [samples](../samples) folder.

View File

@@ -1,108 +0,0 @@
---
title: "Set up an Azure ML workspace"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Set up an Azure ML workspace}
%\VignetteEngine{knitr::rmarkdown}
\use_package{UTF-8}
---
This tutorial gets you started with the Azure Machine Learning service by walking through the requirements and instructions for setting up a workspace, the top-level resource for Azure ML.
You do not need run this if you are working on an Azure Machine Learning Compute Instance, as the compute instance is already associated with an existing workspace.
## What is an Azure ML workspace?
The workspace is the top-level resource for Azure ML, providing a centralized place to work with all the artifacts you create when you use Azure ML. The workspace keeps a history of all training runs, including logs, metrics, output, and a snapshot of your scripts.
When you create a new workspace, it automatically creates several Azure resources that are used by the workspace:
* Azure Container Registry: Registers docker containers that you use during training and when you deploy a model. To minimize costs, ACR is lazy-loaded until deployment images are created.
* Azure Storage account: Used as the default datastore for the workspace.
* Azure Application Insights: Stores monitoring information about your models.
* Azure Key Vault: Stores secrets that are used by compute targets and other sensitive information that's needed by the workspace.
## Setup
This section describes the steps required before you can access any Azure ML service functionality.
### Azure subscription
In order to create an Azure ML workspace, first you need access to an Azure subscription. An Azure subscription allows you to manage storage, compute, and other assets in the Azure cloud. You can [create a new subscription](https://azure.microsoft.com/en-us/free/) or access existing subscription information from the [Azure portal](https://portal.azure.com/). Later in this tutorial you will need information such as your subscription ID in order to create and access workspaces.
### Azure ML SDK installation
Follow the [installation guide](https://azure.github.io/azureml-sdk-for-r/articles/installation.html) to install **azuremlsdk** on your machine.
## Configure your workspace
### Workspace parameters
To use an Azure ML workspace, you will need to supply the following information:
* Your subscription ID
* A resource group name
* (Optional) The region that will host your workspace
* A name for your workspace
You can get your subscription ID from the [Azure portal](https://portal.azure.com/).
You will also need access to a [resource group](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-overview#resource-groups), which organizes Azure resources and provides a default region for the resources in a group. You can see what resource groups to which you have access, or create a new one in the Azure portal. If you don't have a resource group, the `create_workspace()` method will create one for you using the name you provide.
The region to host your workspace will be used if you are creating a new workspace. You do not need to specify this if you are using an existing workspace. You can find the list of supported regions [here](https://azure.microsoft.com/en-us/global-infrastructure/services/?products=machine-learning-service). You should pick a region that is close to your location or that contains your data.
The name for your workspace is unique within the subscription and should be descriptive enough to discern among other workspaces. The subscription may be used only by you, or it may be used by your department or your entire enterprise, so choose a name that makes sense for your situation.
The following code chunk allows you to specify your workspace parameters. It uses `Sys.getenv` to read values from environment variables, which is useful for automation. If no environment variable exists, the parameters will be set to the specified default values. Replace the default values in the code below with your default parameter values.
``` {r configure_parameters, eval=FALSE}
subscription_id <- Sys.getenv("SUBSCRIPTION_ID", unset = "<my-subscription-id>")
resource_group <- Sys.getenv("RESOURCE_GROUP", default="<my-resource-group>")
workspace_name <- Sys.getenv("WORKSPACE_NAME", default="<my-workspace-name>")
workspace_region <- Sys.getenv("WORKSPACE_REGION", default="eastus2")
```
### Create a new workspace
If you don't have an existing workspace and are the owner of the subscription or resource group, you can create a new workspace. If you don't have a resource group, `create_workspace()` will create one for you using the name you provide. If you don't want it to do so, set the `create_resource_group = FALSE` parameter.
Note: As with other Azure services, there are limits on certain resources (e.g. AmlCompute quota) associated with the Azure ML service. Please read this [article](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota.
This cell will create an Azure ML workspace for you in a subscription, provided you have the correct permissions.
This will fail if:
* You do not have permission to create a workspace in the resource group.
* You do not have permission to create a resource group if it does not exist.
* You are not a subscription owner or contributor and no Azure ML workspaces have ever been created in this subscription.
If workspace creation fails, please work with your IT admin to provide you with the appropriate permissions or to provision the required resources.
There are additional parameters that are not shown below that can be configured when creating a workspace. Please see [`create_workspace()`](https://azure.github.io/azureml-sdk-for-r/reference/create_workspace.html) for more details.
``` {r create_workspace, eval=FALSE}
library(azuremlsdk)
ws <- create_workspace(name = workspace_name,
subscription_id = subscription_id,
resource_group = resource_group,
location = workspace_region,
exist_ok = TRUE)
```
You can out write out the workspace ARM properties to a config file with [`write_workspace_config()`](https://azure.github.io/azureml-sdk-for-r/reference/write_workspace_config.html). The method provides a simple way of reusing the same workspace across multiple files or projects. Users can save the workspace details with `write_workspace_config()`, and use [`load_workspace_from_config()`](https://azure.github.io/azureml-sdk-for-r/reference/load_workspace_from_config.html) to load the same workspace in different files or projects without retyping the workspace ARM properties. The method defaults to writing out the config file to the current working directory with "config.json" as the file name. To specify a different path or file name, set the `path` and `file_name` parameters.
``` {r write_config, eval=FALSE}
write_workspace_config(ws)
```
### Access an existing workspace
You can access an existing workspace in a couple of ways. If your workspace properties were previously saved to a config file, you can load the workspace as follows:
``` {r load_config, eval=FALSE}
ws <- load_workspace_from_config()
```
If Azure ML cannot find the config file, specify the path to the config file with the `path` parameter. The method defaults to starting the search in the current directory.
You can also initialize a workspace using the [`get_workspace()`](https://azure.github.io/azureml-sdk-for-r/reference/get_workspace.html) method.
``` {r get_workspace, eval=FALSE}
ws <- get_workspace(name = workspace_name,
subscription_id = subscription_id,
resource_group = resource_group)
```

View File

@@ -1,188 +0,0 @@
---
title: "Deploy a web service to Azure Kubernetes Service"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Deploy a web service to Azure Kubernetes Service}
%\VignetteEngine{knitr::rmarkdown}
\use_package{UTF-8}
---
This tutorial demonstrates how to deploy a model as a web service on [Azure Kubernetes Service](https://azure.microsoft.com/en-us/services/kubernetes-service/) (AKS). AKS is good for high-scale production deployments; use it if you need one or more of the following capabilities:
* Fast response time
* Autoscaling of the deployed service
* Hardware acceleration options such as GPU
You will learn to:
* Set up your testing environment
* Register a model
* Provision an AKS cluster
* Deploy the model to AKS
* Test the deployed service
## Prerequisites
If you don<6F>t have access to an Azure ML workspace, follow the [setup tutorial](https://azure.github.io/azureml-sdk-for-r/articles/configuration.html) to configure and create a workspace.
## Set up your testing environment
Start by setting up your environment. This includes importing the **azuremlsdk** package and connecting to your workspace.
### Import package
```{r import_package, eval=FALSE}
library(azuremlsdk)
```
### Load your workspace
Instantiate a workspace object from your existing workspace. The following code will load the workspace details from a **config.json** file if you previously wrote one out with `write_workspace_config()`.
```{r load_workspace, eval=FALSE}
ws <- load_workspace_from_config()
```
Or, you can retrieve a workspace by directly specifying your workspace details:
```{r get_workspace, eval=FALSE}
ws <- get_workspace("<your workspace name>", "<your subscription ID>", "<your resource group>")
```
## Register the model
In this tutorial we will deploy a model that was trained in one of the [samples](https://github.com/Azure/azureml-sdk-for-r/blob/master/samples/training/train-on-amlcompute/train-on-amlcompute.R). The model was trained with the Iris dataset and can be used to determine if a flower is one of three Iris flower species (setosa, versicolor, virginica). We have provided the model file (`model.rds`) for the tutorial; it is located in the "project_files" directory of this vignette.
First, register the model to your workspace with [`register_model()`](https://azure.github.io/azureml-sdk-for-r/reference/register_model.html). A registered model can be any collection of files, but in this case the R model file is sufficient. Azure ML will use the registered model for deployment.
```{r register_model, eval=FALSE}
model <- register_model(ws,
model_path = "project_files/model.rds",
model_name = "iris_model",
description = "Predict an Iris flower type")
```
## Provision an AKS cluster
When deploying a web service to AKS, you deploy to an AKS cluster that is connected to your workspace. There are two ways to connect an AKS cluster to your workspace:
* Create the AKS cluster. The process automatically connects the cluster to the workspace.
* Attach an existing AKS cluster to your workspace. You can attach a cluster with the [`attach_aks_compute()`](https://azure.github.io/azureml-sdk-for-r/reference/attach_aks_compute.html) method.
Creating or attaching an AKS cluster is a one-time process for your workspace. You can reuse this cluster for multiple deployments. If you delete the cluster or the resource group that contains it, you must create a new cluster the next time you need to deploy.
In this tutorial, we will go with the first method of provisioning a new cluster. See the [`create_aks_compute()`](https://azure.github.io/azureml-sdk-for-r/reference/create_aks_compute.html) reference for the full set of configurable parameters. If you pick custom values for the `agent_count` and `vm_size` parameters, you need to make sure `agent_count` multiplied by `vm_size` is greater than or equal to `12` virtual CPUs.
``` {r provision_cluster, eval=FALSE}
aks_target <- create_aks_compute(ws, cluster_name = 'myakscluster')
wait_for_provisioning_completion(aks_target, show_output = TRUE)
```
The Azure ML SDK does not provide support for scaling an AKS cluster. To scale the nodes in the cluster, use the UI for your AKS cluster in the Azure portal. You can only change the node count, not the VM size of the cluster.
## Deploy as a web service
### Define the inference dependencies
To deploy a model, you need an **inference configuration**, which describes the environment needed to host the model and web service. To create an inference config, you will first need a scoring script and an Azure ML environment.
The scoring script (`entry_script`) is an R script that will take as input variable values (in JSON format) and output a prediction from your model. For this tutorial, use the provided scoring file `score.R`. The scoring script must contain an `init()` method that loads your model and returns a function that uses the model to make a prediction based on the input data. See the [documentation](https://azure.github.io/azureml-sdk-for-r/reference/inference_config.html#details) for more details.
Next, define an Azure ML **environment** for your script<70>s package dependencies. With an environment, you specify R packages (from CRAN or elsewhere) that are needed for your script to run. You can also provide the values of environment variables that your script can reference to modify its behavior.
By default Azure ML will build a default Docker image that includes R, the Azure ML SDK, and additional required dependencies for deployment. See the documentation here for the full list of dependencies that will be installed in the default container. You can also specify additional packages to be installed at runtime, or even a custom Docker image to be used instead of the base image that will be built, using the other available parameters to [`r_environment()`](https://azure.github.io/azureml-sdk-for-r/reference/r_environment.html).
```{r create_env, eval=FALSE}
r_env <- r_environment(name = "deploy_env")
```
Now you have everything you need to create an inference config for encapsulating your scoring script and environment dependencies.
``` {r create_inference_config, eval=FALSE}
inference_config <- inference_config(
entry_script = "score.R",
source_directory = "project_files",
environment = r_env)
```
### Deploy to AKS
Now, define the deployment configuration that describes the compute resources needed, for example, the number of cores and memory. See the [`aks_webservice_deployment_config()`](https://azure.github.io/azureml-sdk-for-r/reference/aks_webservice_deployment_config.html) for the full set of configurable parameters.
``` {r deploy_config, eval=FALSE}
aks_config <- aks_webservice_deployment_config(cpu_cores = 1, memory_gb = 1)
```
Now, deploy your model as a web service to the AKS cluster you created earlier.
```{r deploy_service, eval=FALSE}
aks_service <- deploy_model(ws,
'my-new-aksservice',
models = list(model),
inference_config = inference_config,
deployment_config = aks_config,
deployment_target = aks_target)
wait_for_deployment(aks_service, show_output = TRUE)
```
To inspect the logs from the deployment:
```{r get_logs, eval=FALSE}
get_webservice_logs(aks_service)
```
If you encounter any issue in deploying the web service, please visit the [troubleshooting guide](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-troubleshoot-deployment).
## Test the deployed service
Now that your model is deployed as a service, you can test the service from R using [`invoke_webservice()`](https://azure.github.io/azureml-sdk-for-r/reference/invoke_webservice.html). Provide a new set of data to predict from, convert it to JSON, and send it to the service.
``` {r test_service, eval=FALSE}
library(jsonlite)
# versicolor
plant <- data.frame(Sepal.Length = 6.4,
Sepal.Width = 2.8,
Petal.Length = 4.6,
Petal.Width = 1.8)
# setosa
# plant <- data.frame(Sepal.Length = 5.1,
# Sepal.Width = 3.5,
# Petal.Length = 1.4,
# Petal.Width = 0.2)
# virginica
# plant <- data.frame(Sepal.Length = 6.7,
# Sepal.Width = 3.3,
# Petal.Length = 5.2,
# Petal.Width = 2.3)
predicted_val <- invoke_webservice(aks_service, toJSON(plant))
message(predicted_val)
```
You can also get the web service<63>s HTTP endpoint, which accepts REST client calls. You can share this endpoint with anyone who wants to test the web service or integrate it into an application.
``` {r eval=FALSE}
aks_service$scoring_uri
```
## Web service authentication
When deploying to AKS, key-based authentication is enabled by default. You can also enable token-based authentication. Token-based authentication requires clients to use an Azure Active Directory account to request an authentication token, which is used to make requests to the deployed service.
To disable key-based auth, set the `auth_enabled = FALSE` parameter when creating the deployment configuration with [`aks_webservice_deployment_config()`](https://azure.github.io/azureml-sdk-for-r/reference/aks_webservice_deployment_config.html).
To enable token-based auth, set `token_auth_enabled = TRUE` when creating the deployment config.
### Key-based authentication
If key authentication is enabled, you can use the [`get_webservice_keys()`](https://azure.github.io/azureml-sdk-for-r/reference/get_webservice_keys.html) method to retrieve a primary and secondary authentication key. To generate a new key, use [`generate_new_webservice_key()`](https://azure.github.io/azureml-sdk-for-r/reference/generate_new_webservice_key.html).
### Token-based authentication
If token authentication is enabled, you can use the [`get_webservice_token()`](https://azure.github.io/azureml-sdk-for-r/reference/get_webservice_token.html) method to retrieve a JWT token and that token's expiration time. Make sure to request a new token after the token's expiration time.
## Clean up resources
Delete the resources once you no longer need them. Do not delete any resource you plan on still using.
Delete the web service:
```{r delete_service, eval=FALSE}
delete_webservice(aks_service)
```
Delete the registered model:
```{r delete_model, eval=FALSE}
delete_model(model)
```
Delete the AKS cluster:
```{r delete_cluster, eval=FALSE}
delete_compute(aks_target)
```

View File

@@ -1,17 +0,0 @@
#' Copyright(c) Microsoft Corporation.
#' Licensed under the MIT license.
library(jsonlite)
init <- function() {
model_path <- Sys.getenv("AZUREML_MODEL_DIR")
model <- readRDS(file.path(model_path, "model.rds"))
message("model is loaded")
function(data) {
plant <- as.data.frame(fromJSON(data))
prediction <- predict(model, plant)
result <- as.character(prediction)
toJSON(result)
}
}

View File

@@ -1,242 +0,0 @@
---
title: "Hyperparameter tune a Keras model"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Hyperparameter tune a Keras model}
%\VignetteEngine{knitr::rmarkdown}
\use_package{UTF-8}
---
This tutorial demonstrates how you can efficiently tune hyperparameters for a model using HyperDrive, Azure ML's hyperparameter tuning functionality. You will train a Keras model on the CIFAR10 dataset, automate hyperparameter exploration, launch parallel jobs, log your results, and find the best run.
### What are hyperparameters?
Hyperparameters are variable parameters chosen to train a model. Learning rate, number of epochs, and batch size are all examples of hyperparameters.
Using brute-force methods to find the optimal values for parameters can be time-consuming, and poor-performing runs can result in wasted money. To avoid this, HyperDrive automates hyperparameter exploration in a time-saving and cost-effective manner by launching several parallel runs with different configurations and finding the configuration that results in best performance on your primary metric.
Let's get started with the example to see how it works!
## Prerequisites
If you don<6F>t have access to an Azure ML workspace, follow the [setup tutorial](https://azure.github.io/azureml-sdk-for-r/articles/configuration.html) to configure and create a workspace.
## Set up development environment
The setup for your development work in this tutorial includes the following actions:
* Import required packages
* Connect to a workspace
* Create an experiment to track your runs
* Create a remote compute target to use for training
### Import **azuremlsdk** package
```{r eval=FALSE}
library(azuremlsdk)
```
### Load your workspace
Instantiate a workspace object from your existing workspace. The following code will load the workspace details from a **config.json** file if you previously wrote one out with [`write_workspace_config()`](https://azure.github.io/azureml-sdk-for-r/reference/write_workspace_config.html).
```{r load_workpace, eval=FALSE}
ws <- load_workspace_from_config()
```
Or, you can retrieve a workspace by directly specifying your workspace details:
```{r get_workpace, eval=FALSE}
ws <- get_workspace("<your workspace name>", "<your subscription ID>", "<your resource group>")
```
### Create an experiment
An Azure ML **experiment** tracks a grouping of runs, typically from the same training script. Create an experiment to track hyperparameter tuning runs for the Keras model.
```{r create_experiment, eval=FALSE}
exp <- experiment(workspace = ws, name = 'hyperdrive-cifar10')
```
If you would like to track your runs in an existing experiment, simply specify that experiment's name to the `name` parameter of `experiment()`.
### Create a compute target
By using Azure Machine Learning Compute (AmlCompute), a managed service, data scientists can train machine learning models on clusters of Azure virtual machines. In this tutorial, you create a GPU-enabled cluster as your training environment. The code below creates the compute cluster for you if it doesn't already exist in your workspace.
You may need to wait a few minutes for your compute cluster to be provisioned if it doesn't already exist.
```{r create_cluster, eval=FALSE}
cluster_name <- "gpucluster"
compute_target <- get_compute(ws, cluster_name = cluster_name)
if (is.null(compute_target))
{
vm_size <- "STANDARD_NC6"
compute_target <- create_aml_compute(workspace = ws,
cluster_name = cluster_name,
vm_size = vm_size,
max_nodes = 4)
wait_for_provisioning_completion(compute_target, show_output = TRUE)
}
```
## Prepare the training script
A training script called `cifar10_cnn.R` has been provided for you in the "project_files" directory of this tutorial.
In order to leverage HyperDrive, the training script for your model must log the relevant metrics during model training. When you configure the hyperparameter tuning run, you specify the primary metric to use for evaluating run performance. You must log this metric so it is available to the hyperparameter tuning process.
In order to log the required metrics, you need to do the following **inside the training script**:
* Import the **azuremlsdk** package
```
library(azuremlsdk)
```
* Take the hyperparameters as command-line arguments to the script. This is necessary so that when HyperDrive carries out the hyperparameter sweep, it can run the training script with different values to the hyperparameters as defined by the search space.
* Use the [`log_metric_to_run()`](https://azure.github.io/azureml-sdk-for-r/reference/log_metric_to_run.html) function to log the hyperparameters and the primary metric.
```
log_metric_to_run("batch_size", batch_size)
...
log_metric_to_run("epochs", epochs)
...
log_metric_to_run("lr", lr)
...
log_metric_to_run("decay", decay)
...
log_metric_to_run("Loss", results[[1]])
```
## Create an estimator
An Azure ML **estimator** encapsulates the run configuration information needed for executing a training script on the compute target. Azure ML runs are run as containerized jobs on the specified compute target. By default, the Docker image built for your training job will include R, the Azure ML SDK, and a set of commonly used R packages. See the full list of default packages included [here](https://azure.github.io/azureml-sdk-for-r/reference/r_environment.html). The estimator is used to define the configuration for each of the child runs that the parent HyperDrive run will kick off.
To create the estimator, define the following:
* The directory that contains your scripts needed for training (`source_directory`). All the files in this directory are uploaded to the cluster node(s) for execution. The directory must contain your training script and any additional scripts required.
* The training script that will be executed (`entry_script`).
* The compute target (`compute_target`), in this case the AmlCompute cluster you created earlier.
* Any environment dependencies required for training. Since the training script requires the Keras package, which is not included in the image by default, pass the package name to the `cran_packages` parameter to have it installed in the Docker container where the job will run. See the [`estimator()`](https://azure.github.io/azureml-sdk-for-r/reference/estimator.html) reference for the full set of configurable options.
* Set the `use_gpu = TRUE` flag so the default base GPU Docker image will be built, since the job will be run on a GPU cluster.
```{r create_estimator, eval=FALSE}
est <- estimator(source_directory = "project_files",
entry_script = "cifar10_cnn.R",
compute_target = compute_target,
cran_packages = c("keras"),
use_gpu = TRUE)
```
## Configure the HyperDrive run
To kick off hyperparameter tuning in Azure ML, you will need to configure a HyperDrive run, which will in turn launch individual children runs of the training scripts with the corresponding hyperparameter values.
### Define search space
In this experiment, we will use four hyperparameters: batch size, number of epochs, learning rate, and decay. In order to begin tuning, we must define the range of values we would like to explore from and how they will be distributed. This is called a parameter space definition and can be created with discrete or continuous ranges.
__Discrete hyperparameters__ are specified as a choice among discrete values represented as a list.
Advanced discrete hyperparameters can also be specified using a distribution. The following distributions are supported:
* `quniform(low, high, q)`
* `qloguniform(low, high, q)`
* `qnormal(mu, sigma, q)`
* `qlognormal(mu, sigma, q)`
__Continuous hyperparameters__ are specified as a distribution over a continuous range of values. The following distributions are supported:
* `uniform(low, high)`
* `loguniform(low, high)`
* `normal(mu, sigma)`
* `lognormal(mu, sigma)`
Here, we will use the [`random_parameter_sampling()`](https://azure.github.io/azureml-sdk-for-r/reference/random_parameter_sampling.html) function to define the search space for each hyperparameter. `batch_size` and `epochs` will be chosen from discrete sets while `lr` and `decay` will be drawn from continuous distributions.
Other available sampling function options are:
* [`grid_parameter_sampling()`](https://azure.github.io/azureml-sdk-for-r/reference/grid_parameter_sampling.html)
* [`bayesian_parameter_sampling()`](https://azure.github.io/azureml-sdk-for-r/reference/bayesian_parameter_sampling.html)
```{r search_space, eval=FALSE}
sampling <- random_parameter_sampling(list(batch_size = choice(c(16, 32, 64)),
epochs = choice(c(200, 350, 500)),
lr = normal(0.0001, 0.005),
decay = uniform(1e-6, 3e-6)))
```
### Define termination policy
To prevent resource waste, Azure ML can detect and terminate poorly performing runs. HyperDrive will do this automatically if you specify an early termination policy.
Here, you will use the [`bandit_policy()`](https://azure.github.io/azureml-sdk-for-r/reference/bandit_policy.html), which terminates any runs where the primary metric is not within the specified slack factor with respect to the best performing training run.
```{r termination_policy, eval=FALSE}
policy <- bandit_policy(slack_factor = 0.15)
```
Other termination policy options are:
* [`median_stopping_policy()`](https://azure.github.io/azureml-sdk-for-r/reference/median_stopping_policy.html)
* [`truncation_selection_policy()`](https://azure.github.io/azureml-sdk-for-r/reference/truncation_selection_policy.html)
If no policy is provided, all runs will continue to completion regardless of performance.
### Finalize configuration
Now, you can create a `HyperDriveConfig` object to define your HyperDrive run. Along with the sampling and policy definitions, you need to specify the name of the primary metric that you want to track and whether we want to maximize it or minimize it. The `primary_metric_name` must correspond with the name of the primary metric you logged in your training script. `max_total_runs` specifies the total number of child runs to launch. See the [hyperdrive_config()](https://azure.github.io/azureml-sdk-for-r/reference/hyperdrive_config.html) reference for the full set of configurable parameters.
```{r create_config, eval=FALSE}
hyperdrive_config <- hyperdrive_config(hyperparameter_sampling = sampling,
primary_metric_goal("MINIMIZE"),
primary_metric_name = "Loss",
max_total_runs = 4,
policy = policy,
estimator = est)
```
## Submit the HyperDrive run
Finally submit the experiment to run on your cluster. The parent HyperDrive run will launch the individual child runs. `submit_experiment()` will return a `HyperDriveRun` object that you will use to interface with the run. In this tutorial, since the cluster we created scales to a max of `4` nodes, all 4 child runs will be launched in parallel.
```{r submit_run, eval=FALSE}
hyperdrive_run <- submit_experiment(exp, hyperdrive_config)
```
You can view the HyperDrive run<75>s details as a table. Clicking the <20>Web View<65> link provided will bring you to Azure Machine Learning studio, where you can monitor the run in the UI.
```{r eval=FALSE}
view_run_details(hyperdrive_run)
```
Wait until hyperparameter tuning is complete before you run more code.
```{r eval=FALSE}
wait_for_run_completion(hyperdrive_run, show_output = TRUE)
```
## Analyse runs by performance
Finally, you can view and compare the metrics collected during all of the child runs!
```{r analyse_runs, eval=FALSE}
# Get the metrics of all the child runs
child_run_metrics <- get_child_run_metrics(hyperdrive_run)
child_run_metrics
# Get the child run objects sorted in descending order by the best primary metric
child_runs <- get_child_runs_sorted_by_primary_metric(hyperdrive_run)
child_runs
# Directly get the run object of the best performing run
best_run <- get_best_run_by_primary_metric(hyperdrive_run)
# Get the metrics of the best performing run
metrics <- get_run_metrics(best_run)
metrics
```
The `metrics` variable will include the values of the hyperparameters that resulted in the best performing run.
## Clean up resources
Delete the resources once you no longer need them. Don't delete any resource you plan to still use.
Delete the compute cluster:
```{r delete_compute, eval=FALSE}
delete_compute(compute_target)
```

View File

@@ -1,124 +0,0 @@
#' Modified from: "https://github.com/rstudio/keras/blob/master/vignettes/
#' examples/cifar10_cnn.R"
#'
#' Train a simple deep CNN on the CIFAR10 small images dataset.
#'
#' It gets down to 0.65 test logloss in 25 epochs, and down to 0.55 after 50
#' epochs, though it is still underfitting at that point.
library(keras)
install_keras()
library(azuremlsdk)
# Parameters --------------------------------------------------------------
args <- commandArgs(trailingOnly = TRUE)
batch_size <- as.numeric(args[2])
log_metric_to_run("batch_size", batch_size)
epochs <- as.numeric(args[4])
log_metric_to_run("epochs", epochs)
lr <- as.numeric(args[6])
log_metric_to_run("lr", lr)
decay <- as.numeric(args[8])
log_metric_to_run("decay", decay)
data_augmentation <- TRUE
# Data Preparation --------------------------------------------------------
# See ?dataset_cifar10 for more info
cifar10 <- dataset_cifar10()
# Feature scale RGB values in test and train inputs
x_train <- cifar10$train$x / 255
x_test <- cifar10$test$x / 255
y_train <- to_categorical(cifar10$train$y, num_classes = 10)
y_test <- to_categorical(cifar10$test$y, num_classes = 10)
# Defining Model ----------------------------------------------------------
# Initialize sequential model
model <- keras_model_sequential()
model %>%
# Start with hidden 2D convolutional layer being fed 32x32 pixel images
layer_conv_2d(
filter = 32, kernel_size = c(3, 3), padding = "same",
input_shape = c(32, 32, 3)
) %>%
layer_activation("relu") %>%
# Second hidden layer
layer_conv_2d(filter = 32, kernel_size = c(3, 3)) %>%
layer_activation("relu") %>%
# Use max pooling
layer_max_pooling_2d(pool_size = c(2, 2)) %>%
layer_dropout(0.25) %>%
# 2 additional hidden 2D convolutional layers
layer_conv_2d(filter = 32, kernel_size = c(3, 3), padding = "same") %>%
layer_activation("relu") %>%
layer_conv_2d(filter = 32, kernel_size = c(3, 3)) %>%
layer_activation("relu") %>%
# Use max pooling once more
layer_max_pooling_2d(pool_size = c(2, 2)) %>%
layer_dropout(0.25) %>%
# Flatten max filtered output into feature vector
# and feed into dense layer
layer_flatten() %>%
layer_dense(512) %>%
layer_activation("relu") %>%
layer_dropout(0.5) %>%
# Outputs from dense layer are projected onto 10 unit output layer
layer_dense(10) %>%
layer_activation("softmax")
opt <- optimizer_rmsprop(lr, decay)
model %>%
compile(loss = "categorical_crossentropy",
optimizer = opt,
metrics = "accuracy"
)
# Training ----------------------------------------------------------------
if (!data_augmentation) {
model %>%
fit(x_train,
y_train,
batch_size = batch_size,
epochs = epochs,
validation_data = list(x_test, y_test),
shuffle = TRUE
)
} else {
datagen <- image_data_generator(rotation_range = 20,
width_shift_range = 0.2,
height_shift_range = 0.2,
horizontal_flip = TRUE
)
datagen %>% fit_image_data_generator(x_train)
results <- evaluate(model, x_train, y_train, batch_size)
log_metric_to_run("Loss", results[[1]])
cat("Loss: ", results[[1]], "\n")
cat("Accuracy: ", results[[2]], "\n")
}

View File

@@ -1,100 +0,0 @@
---
title: "Install the Azure ML SDK for R"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Install the Azure ML SDK for R}
%\VignetteEngine{knitr::rmarkdown}
\use_package{UTF-8}
---
This article covers the step-by-step instructions for installing the Azure ML SDK for R.
You do not need run this if you are working on an Azure Machine Learning Compute Instance, as the compute instance already has the Azure ML SDK preinstalled.
## Install Conda
If you do not have Conda already installed on your machine, you will first need to install it, since the Azure ML R SDK uses **reticulate** to bind to the Python SDK. We recommend installing [Miniconda](https://docs.conda.io/en/latest/miniconda.html), which is a smaller, lightweight version of Anaconda. Choose the 64-bit binary for Python 3.5 or later.
## Install the **azuremlsdk** R package
You will need **remotes** to install **azuremlsdk** from the GitHub repo.
``` {r install_remotes, eval=FALSE}
install.packages('remotes')
```
Then, you can use the `install_github` function to install the package.
``` {r install_azuremlsdk, eval=FALSE}
remotes::install_cran('azuremlsdk', repos = 'https://cloud.r-project.org/')
```
If you are using R installed from CRAN, which comes with 32-bit and 64-bit binaries, you may need to specify the parameter `INSTALL_opts=c("--no-multiarch")` to only build for the current 64-bit architecture.
``` {r eval=FALSE}
remotes::install_cran('azuremlsdk', repos = 'https://cloud.r-project.org/', INSTALL_opts=c("--no-multiarch"))
```
## Install the Azure ML Python SDK
Lastly, use the **azuremlsdk** R library to install the Python SDK. By default, `azuremlsdk::install_azureml()` will install the [latest version of the Python SDK](https://pypi.org/project/azureml-sdk/) in a conda environment called `r-azureml` if reticulate < 1.14 or `r-reticulate` if reticulate ≥ 1.14.
``` {r install_pythonsdk, eval=FALSE}
azuremlsdk::install_azureml()
```
If you would like to override the default version, environment name, or Python version, you can pass in those arguments. If you would like to restart the R session after installation or delete the conda environment if it already exists and create a new environment, you can also do so:
``` {r eval=FALSE}
azuremlsdk::install_azureml(version = NULL,
custom_envname = "<your conda environment name>",
conda_python_version = "<desired python version>",
restart_session = TRUE,
remove_existing_env = TRUE)
```
## Test installation
You can confirm your installation worked by loading the library and successfully retrieving a run.
``` {r test_installation, eval=FALSE}
library(azuremlsdk)
get_current_run()
```
## Troubleshooting
- In step 3 of the installation, if you get ssl errors on windows, it is due to an
outdated openssl binary. Install the latest openssl binaries from
[here](https://wiki.openssl.org/index.php/Binaries).
- If installation fails due to this error:
```R
Error in strptime(xx, f, tz = tz) :
(converted from warning) unable to identify current timezone 'C':
please set environment variable 'TZ'
In R CMD INSTALL
Error in i.p(...) :
(converted from warning) installation of package C:/.../azureml_0.4.0.tar.gz had non-zero exit
status
```
You will need to set your time zone environment variable to GMT and restart the installation process.
```R
Sys.setenv(TZ='GMT')
```
- If the following permission error occurs while installing in RStudio,
change your RStudio session to administrator mode, and re-run the installation command.
```R
Downloading GitHub repo Azure/azureml-sdk-for-r@master
Skipping 2 packages ahead of CRAN: reticulate, rlang
Running `R CMD build`...
Error: (converted from warning) invalid package
'C:/.../file2b441bf23631'
In R CMD INSTALL
Error in i.p(...) :
(converted from warning) installation of package
C:/.../file2b441bf23631 had non-zero exit status
In addition: Warning messages:
1: In file(con, "r") :
cannot open file 'C:...\file2b44144a540f': Permission denied
2: In file(con, "r") :
cannot open file 'C:...\file2b4463c21577': Permission denied
```

View File

@@ -1,16 +0,0 @@
#' Copyright(c) Microsoft Corporation.
#' Licensed under the MIT license.
library(jsonlite)
init <- function() {
model_path <- Sys.getenv("AZUREML_MODEL_DIR")
model <- readRDS(file.path(model_path, "model.rds"))
message("logistic regression model loaded")
function(data) {
vars <- as.data.frame(fromJSON(data))
prediction <- as.numeric(predict(model, vars, type = "response") * 100)
toJSON(prediction)
}
}

View File

@@ -1,33 +0,0 @@
#' Copyright(c) Microsoft Corporation.
#' Licensed under the MIT license.
library(azuremlsdk)
library(optparse)
library(caret)
options <- list(
make_option(c("-d", "--data_folder"))
)
opt_parser <- OptionParser(option_list = options)
opt <- parse_args(opt_parser)
paste(opt$data_folder)
accidents <- readRDS(file.path(opt$data_folder, "accidents.Rd"))
summary(accidents)
mod <- glm(dead ~ dvcat + seatbelt + frontal + sex + ageOFocc + yearVeh + airbag + occRole, family = binomial, data = accidents)
summary(mod)
predictions <- factor(ifelse(predict(mod) > 0.1, "dead", "alive"))
conf_matrix <- confusionMatrix(predictions, accidents$dead)
message(conf_matrix)
log_metric_to_run("Accuracy", conf_matrix$overall["Accuracy"])
output_dir = "outputs"
if (!dir.exists(output_dir)) {
dir.create(output_dir)
}
saveRDS(mod, file = "./outputs/model.rds")
message("Model saved")

View File

@@ -1,326 +0,0 @@
---
title: "Train and deploy your first model with Azure ML"
author: "David Smith"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Train and deploy your first model with Azure ML}
%\VignetteEngine{knitr::rmarkdown}
\use_package{UTF-8}
---
In this tutorial, you learn the foundational design patterns in Azure Machine Learning. You'll train and deploy a **caret** model to predict the likelihood of a fatality in an automobile accident. After completing this tutorial, you'll have the practical knowledge of the R SDK to scale up to developing more-complex experiments and workflows.
In this tutorial, you learn the following tasks:
* Connect your workspace
* Load data and prepare for training
* Upload data to the datastore so it is available for remote training
* Create a compute resource
* Train a caret model to predict probability of fatality
* Deploy a prediction endpoint
* Test the model from R
## Prerequisites
If you don't have access to an Azure ML workspace, follow the [setup tutorial](https://azure.github.io/azureml-sdk-for-r/articles/configuration.html) to configure and create a workspace.
## Set up your development environment
The setup for your development work in this tutorial includes the following actions:
* Install required packages
* Connect to a workspace, so that your local computer can communicate with remote resources
* Create an experiment to track your runs
* Create a remote compute target to use for training
### Install required packages
This tutorial assumes you already have the Azure ML SDK installed. Go ahead and import the **azuremlsdk** package.
```{r eval=FALSE}
library(azuremlsdk)
```
The tutorial uses data from the [**DAAG** package](https://cran.r-project.org/package=DAAG). Install the package if you don't have it.
```{r eval=FALSE}
install.packages("DAAG")
```
The training and scoring scripts (`accidents.R` and `accident_predict.R`) have some additional dependencies. If you plan on running those scripts locally, make sure you have those required packages as well.
### Load your workspace
Instantiate a workspace object from your existing workspace. The following code will load the workspace details from the **config.json** file. You can also retrieve a workspace using [`get_workspace()`](https://azure.github.io/azureml-sdk-for-r/reference/get_workspace.html).
```{r load_workpace, eval=FALSE}
ws <- load_workspace_from_config()
```
### Create an experiment
An Azure ML experiment tracks a grouping of runs, typically from the same training script. Create an experiment to track the runs for training the caret model on the accidents data.
```{r create_experiment, eval=FALSE}
experiment_name <- "accident-logreg"
exp <- experiment(ws, experiment_name)
```
### Create a compute target
By using Azure Machine Learning Compute (AmlCompute), a managed service, data scientists can train machine learning models on clusters of Azure virtual machines. Examples include VMs with GPU support. In this tutorial, you create a single-node AmlCompute cluster as your training environment. The code below creates the compute cluster for you if it doesn't already exist in your workspace.
You may need to wait a few minutes for your compute cluster to be provisioned if it doesn't already exist.
```{r create_cluster, eval=FALSE}
cluster_name <- "rcluster"
compute_target <- get_compute(ws, cluster_name = cluster_name)
if (is.null(compute_target)) {
vm_size <- "STANDARD_D2_V2"
compute_target <- create_aml_compute(workspace = ws,
cluster_name = cluster_name,
vm_size = vm_size,
max_nodes = 1)
wait_for_provisioning_completion(compute_target, show_output = TRUE)
}
```
## Prepare data for training
This tutorial uses data from the **DAAG** package. This dataset includes data from over 25,000 car crashes in the US, with variables you can use to predict the likelihood of a fatality. First, import the data into R and transform it into a new dataframe `accidents` for analysis, and export it to an `Rdata` file.
```{r load_data, eval=FALSE}
library(DAAG)
data(nassCDS)
accidents <- na.omit(nassCDS[,c("dead","dvcat","seatbelt","frontal","sex","ageOFocc","yearVeh","airbag","occRole")])
accidents$frontal <- factor(accidents$frontal, labels=c("notfrontal","frontal"))
accidents$occRole <- factor(accidents$occRole)
saveRDS(accidents, file="accidents.Rd")
```
### Upload data to the datastore
Upload data to the cloud so that it can be access by your remote training environment. Each Azure ML workspace comes with a default datastore that stores the connection information to the Azure blob container that is provisioned in the storage account attached to the workspace. The following code will upload the accidents data you created above to that datastore.
```{r upload_data, eval=FALSE}
ds <- get_default_datastore(ws)
target_path <- "accidentdata"
upload_files_to_datastore(ds,
list("./project_files/accidents.Rd"),
target_path = target_path,
overwrite = TRUE)
```
## Train a model
For this tutorial, fit a logistic regression model on your uploaded data using your remote compute cluster. To submit a job, you need to:
* Prepare the training script
* Create an estimator
* Submit the job
### Prepare the training script
A training script called `accidents.R` has been provided for you in the "project_files" directory of this tutorial. Notice the following details **inside the training script** that have been done to leverage the Azure ML service for training:
* The training script takes an argument `-d` to find the directory that contains the training data. When you define and submit your job later, you point to the datastore for this argument. Azure ML will mount the storage folder to the remote cluster for the training job.
* The training script logs the final accuracy as a metric to the run record in Azure ML using `log_metric_to_run()`. The Azure ML SDK provides a set of logging APIs for logging various metrics during training runs. These metrics are recorded and persisted in the experiment run record. The metrics can then be accessed at any time or viewed in the run details page in [Azure Machine Learning studio](http://ml.azure.com). See the [reference](https://azure.github.io/azureml-sdk-for-r/reference/index.html#section-training-experimentation) for the full set of logging methods `log_*()`.
* The training script saves your model into a directory named **outputs**. The `./outputs` folder receives special treatment by Azure ML. During training, files written to `./outputs` are automatically uploaded to your run record by Azure ML and persisted as artifacts. By saving the trained model to `./outputs`, you'll be able to access and retrieve your model file even after the run is over and you no longer have access to your remote training environment.
### Create an estimator
An Azure ML estimator encapsulates the run configuration information needed for executing a training script on the compute target. Azure ML runs are run as containerized jobs on the specified compute target. By default, the Docker image built for your training job will include R, the Azure ML SDK, and a set of commonly used R packages. See the full list of default packages included [here](https://azure.github.io/azureml-sdk-for-r/reference/r_environment.html).
To create the estimator, define:
* The directory that contains your scripts needed for training (`source_directory`). All the files in this directory are uploaded to the cluster node(s) for execution. The directory must contain your training script and any additional scripts required.
* The training script that will be executed (`entry_script`).
* The compute target (`compute_target`), in this case the AmlCompute cluster you created earlier.
* The parameters required from the training script (`script_params`). Azure ML will run your training script as a command-line script with `Rscript`. In this tutorial you specify one argument to the script, the data directory mounting point, which you can access with `ds$path(target_path)`.
* Any environment dependencies required for training. The default Docker image built for training already contains the three packages (`caret`, `e1071`, and `optparse`) needed in the training script. So you don't need to specify additional information. If you are using R packages that are not included by default, use the estimator's `cran_packages` parameter to add additional CRAN packages. See the [`estimator()`](https://azure.github.io/azureml-sdk-for-r/reference/estimator.html) reference for the full set of configurable options.
```{r create_estimator, eval=FALSE}
est <- estimator(source_directory = "project_files",
entry_script = "accidents.R",
script_params = list("--data_folder" = ds$path(target_path)),
compute_target = compute_target
)
```
### Submit the job on the remote cluster
Finally submit the job to run on your cluster. `submit_experiment()` returns a Run object that you then use to interface with the run. In total, the first run takes **about 10 minutes**. But for later runs, the same Docker image is reused as long as the script dependencies don't change. In this case, the image is cached and the container startup time is much faster.
```{r submit_job, eval=FALSE}
run <- submit_experiment(exp, est)
```
You can view a table of the run's details. Clicking the "Web View" link provided will bring you to Azure Machine Learning studio, where you can monitor the run in the UI.
```{r view_run, eval=FALSE}
view_run_details(run)
```
Model training happens in the background. Wait until the model has finished training before you run more code.
```{r wait_run, eval=FALSE}
wait_for_run_completion(run, show_output = TRUE)
```
You -- and colleagues with access to the workspace -- can submit multiple experiments in parallel, and Azure ML will take of scheduling the tasks on the compute cluster. You can even configure the cluster to automatically scale up to multiple nodes, and scale back when there are no more compute tasks in the queue. This configuration is a cost-effective way for teams to share compute resources.
## Retrieve training results
Once your model has finished training, you can access the artifacts of your job that were persisted to the run record, including any metrics logged and the final trained model.
### Get the logged metrics
In the training script `accidents.R`, you logged a metric from your model: the accuracy of the predictions in the training data. You can see metrics in the [studio](https://ml.azure.com), or extract them to the local session as an R list as follows:
```{r metrics, eval=FALSE}
metrics <- get_run_metrics(run)
metrics
```
If you've run multiple experiments (say, using differing variables, algorithms, or hyperparamers), you can use the metrics from each run to compare and choose the model you'll use in production.
### Get the trained model
You can retrieve the trained model and look at the results in your local R session. The following code will download the contents of the `./outputs` directory, which includes the model file.
```{r retrieve_model, eval=FALSE}
download_files_from_run(run, prefix="outputs/")
accident_model <- readRDS("project_files/outputs/model.rds")
summary(accident_model)
```
You see some factors that contribute to an increase in the estimated probability of death:
* higher impact speed
* male driver
* older occupant
* passenger
You see lower probabilities of death with:
* presence of airbags
* presence seatbelts
* frontal collision
The vehicle year of manufacture does not have a significant effect.
You can use this model to make new predictions:
```{r manual_predict, eval=FALSE}
newdata <- data.frame( # valid values shown below
dvcat="10-24", # "1-9km/h" "10-24" "25-39" "40-54" "55+"
seatbelt="none", # "none" "belted"
frontal="frontal", # "notfrontal" "frontal"
sex="f", # "f" "m"
ageOFocc=16, # age in years, 16-97
yearVeh=2002, # year of vehicle, 1955-2003
airbag="none", # "none" "airbag"
occRole="pass" # "driver" "pass"
)
## predicted probability of death for these variables, as a percentage
as.numeric(predict(accident_model,newdata, type="response")*100)
```
## Deploy as a web service
With your model, you can predict the danger of death from a collision. Use Azure ML to deploy your model as a prediction service. In this tutorial, you will deploy the web service in [Azure Container Instances](https://docs.microsoft.com/en-us/azure/container-instances/) (ACI).
### Register the model
First, register the model you downloaded to your workspace with [`register_model()`](https://azure.github.io/azureml-sdk-for-r/reference/register_model.html). A registered model can be any collection of files, but in this case the R model object is sufficient. Azure ML will use the registered model for deployment.
```{r register_model, eval=FALSE}
model <- register_model(ws,
model_path = "project_files/outputs/model.rds",
model_name = "accidents_model",
description = "Predict probablity of auto accident")
```
### Define the inference dependencies
To create a web service for your model, you first need to create a scoring script (`entry_script`), an R script that will take as input variable values (in JSON format) and output a prediction from your model. For this tutorial, use the provided scoring file `accident_predict.R`. The scoring script must contain an `init()` method that loads your model and returns a function that uses the model to make a prediction based on the input data. See the [documentation](https://azure.github.io/azureml-sdk-for-r/reference/inference_config.html#details) for more details.
Next, define an Azure ML **environment** for your script's package dependencies. With an environment, you specify R packages (from CRAN or elsewhere) that are needed for your script to run. You can also provide the values of environment variables that your script can reference to modify its behavior. By default, Azure ML will build the same default Docker image used with the estimator for training. Since the tutorial has no special requirements, create an environment with no special attributes.
```{r create_environment, eval=FALSE}
r_env <- r_environment(name = "basic_env")
```
If you want to use your own Docker image for deployment instead, specify the `custom_docker_image` parameter. See the [`r_environment()`](https://azure.github.io/azureml-sdk-for-r/reference/r_environment.html) reference for the full set of configurable options for defining an environment.
Now you have everything you need to create an **inference config** for encapsulating your scoring script and environment dependencies.
``` {r create_inference_config, eval=FALSE}
inference_config <- inference_config(
entry_script = "accident_predict.R",
source_directory = "project_files",
environment = r_env)
```
### Deploy to ACI
In this tutorial, you will deploy your service to ACI. This code provisions a single container to respond to inbound requests, which is suitable for testing and light loads. See [`aci_webservice_deployment_config()`](https://azure.github.io/azureml-sdk-for-r/reference/aci_webservice_deployment_config.html) for additional configurable options. (For production-scale deployments, you can also [deploy to Azure Kubernetes Service](https://azure.github.io/azureml-sdk-for-r/articles/deploy-to-aks/deploy-to-aks.html).)
``` {r create_aci_config, eval=FALSE}
aci_config <- aci_webservice_deployment_config(cpu_cores = 1, memory_gb = 0.5)
```
Now you deploy your model as a web service. Deployment **can take several minutes**.
```{r deploy_service, eval=FALSE}
aci_service <- deploy_model(ws,
'accident-pred',
list(model),
inference_config,
aci_config)
wait_for_deployment(aci_service, show_output = TRUE)
```
If you encounter any issue in deploying the web service, please visit the [troubleshooting guide](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-troubleshoot-deployment).
## Test the deployed service
Now that your model is deployed as a service, you can test the service from R using [`invoke_webservice()`](https://azure.github.io/azureml-sdk-for-r/reference/invoke_webservice.html). Provide a new set of data to predict from, convert it to JSON, and send it to the service.
```{r test_deployment, eval=FALSE}
library(jsonlite)
newdata <- data.frame( # valid values shown below
dvcat="10-24", # "1-9km/h" "10-24" "25-39" "40-54" "55+"
seatbelt="none", # "none" "belted"
frontal="frontal", # "notfrontal" "frontal"
sex="f", # "f" "m"
ageOFocc=22, # age in years, 16-97
yearVeh=2002, # year of vehicle, 1955-2003
airbag="none", # "none" "airbag"
occRole="pass" # "driver" "pass"
)
prob <- invoke_webservice(aci_service, toJSON(newdata))
prob
```
You can also get the web service's HTTP endpoint, which accepts REST client calls. You can share this endpoint with anyone who wants to test the web service or integrate it into an application.
```{r get_endpoint, eval=FALSE}
aci_service$scoring_uri
```
## Clean up resources
Delete the resources once you no longer need them. Don't delete any resource you plan to still use.
Delete the web service:
```{r delete_service, eval=FALSE}
delete_webservice(aci_service)
```
Delete the registered model:
```{r delete_model, eval=FALSE}
delete_model(model)
```
Delete the compute cluster:
```{r delete_compute, eval=FALSE}
delete_compute(compute_target)
```

View File

@@ -1,62 +0,0 @@
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
# Copyright 2016 RStudio, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
library(tensorflow)
install_tensorflow(version = "1.13.2-gpu")
library(azuremlsdk)
# Create the model
x <- tf$placeholder(tf$float32, shape(NULL, 784L))
W <- tf$Variable(tf$zeros(shape(784L, 10L)))
b <- tf$Variable(tf$zeros(shape(10L)))
y <- tf$nn$softmax(tf$matmul(x, W) + b)
# Define loss and optimizer
y_ <- tf$placeholder(tf$float32, shape(NULL, 10L))
cross_entropy <- tf$reduce_mean(-tf$reduce_sum(y_ * log(y),
reduction_indices = 1L))
train_step <- tf$train$GradientDescentOptimizer(0.5)$minimize(cross_entropy)
# Create session and initialize variables
sess <- tf$Session()
sess$run(tf$global_variables_initializer())
# Load mnist data )
datasets <- tf$contrib$learn$datasets
mnist <- datasets$mnist$read_data_sets("MNIST-data", one_hot = TRUE)
# Train
for (i in 1:1000) {
batches <- mnist$train$next_batch(100L)
batch_xs <- batches[[1]]
batch_ys <- batches[[2]]
sess$run(train_step,
feed_dict = dict(x = batch_xs, y_ = batch_ys))
}
# Test trained model
correct_prediction <- tf$equal(tf$argmax(y, 1L), tf$argmax(y_, 1L))
accuracy <- tf$reduce_mean(tf$cast(correct_prediction, tf$float32))
cat("Accuracy: ", sess$run(accuracy,
feed_dict = dict(x = mnist$test$images,
y_ = mnist$test$labels)))
log_metric_to_run("accuracy",
sess$run(accuracy, feed_dict = dict(x = mnist$test$images,
y_ = mnist$test$labels)))

View File

@@ -1,143 +0,0 @@
---
title: "Train a TensorFlow model"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Train a TensorFlow model}
%\VignetteEngine{knitr::rmarkdown}
\use_package{UTF-8}
---
This tutorial demonstrates how run a TensorFlow job at scale using Azure ML. You will train a TensorFlow model to classify handwritten digits (MNIST) using a deep neural network (DNN) and log your results to the Azure ML service.
## Prerequisites
If you don<6F>t have access to an Azure ML workspace, follow the [setup tutorial](https://azure.github.io/azureml-sdk-for-r/articles/configuration.html) to configure and create a workspace.
## Set up development environment
The setup for your development work in this tutorial includes the following actions:
* Import required packages
* Connect to a workspace
* Create an experiment to track your runs
* Create a remote compute target to use for training
### Import **azuremlsdk** package
```{r eval=FALSE}
library(azuremlsdk)
```
### Load your workspace
Instantiate a workspace object from your existing workspace. The following code will load the workspace details from a **config.json** file if you previously wrote one out with [`write_workspace_config()`](https://azure.github.io/azureml-sdk-for-r/reference/write_workspace_config.html).
```{r load_workpace, eval=FALSE}
ws <- load_workspace_from_config()
```
Or, you can retrieve a workspace by directly specifying your workspace details:
```{r get_workpace, eval=FALSE}
ws <- get_workspace("<your workspace name>", "<your subscription ID>", "<your resource group>")
```
### Create an experiment
An Azure ML **experiment** tracks a grouping of runs, typically from the same training script. Create an experiment to track the runs for training the TensorFlow model on the MNIST data.
```{r create_experiment, eval=FALSE}
exp <- experiment(workspace = ws, name = "tf-mnist")
```
If you would like to track your runs in an existing experiment, simply specify that experiment's name to the `name` parameter of `experiment()`.
### Create a compute target
By using Azure Machine Learning Compute (AmlCompute), a managed service, data scientists can train machine learning models on clusters of Azure virtual machines. In this tutorial, you create a GPU-enabled cluster as your training environment. The code below creates the compute cluster for you if it doesn't already exist in your workspace.
You may need to wait a few minutes for your compute cluster to be provisioned if it doesn't already exist.
```{r create_cluster, eval=FALSE}
cluster_name <- "gpucluster"
compute_target <- get_compute(ws, cluster_name = cluster_name)
if (is.null(compute_target))
{
vm_size <- "STANDARD_NC6"
compute_target <- create_aml_compute(workspace = ws,
cluster_name = cluster_name,
vm_size = vm_size,
max_nodes = 4)
wait_for_provisioning_completion(compute_target, show_output = TRUE)
}
```
## Prepare the training script
A training script called `tf_mnist.R` has been provided for you in the "project_files" directory of this tutorial. The Azure ML SDK provides a set of logging APIs for logging various metrics during training runs. These metrics are recorded and persisted in the experiment run record, and can be be accessed at any time or viewed in the run details page in [Azure Machine Learning studio](http://ml.azure.com/).
In order to collect and upload run metrics, you need to do the following **inside the training script**:
* Import the **azuremlsdk** package
```
library(azuremlsdk)
```
* Add the [`log_metric_to_run()`](https://azure.github.io/azureml-sdk-for-r/reference/log_metric_to_run.html) function to track our primary metric, "accuracy", for this experiment. If you have your own training script with several important metrics, simply create a logging call for each one within the script.
```
log_metric_to_run("accuracy",
sess$run(accuracy,
feed_dict = dict(x = mnist$test$images, y_ = mnist$test$labels)))
```
See the [reference](https://azure.github.io/azureml-sdk-for-r/reference/index.html#section-training-experimentation) for the full set of logging methods `log_*()` available from the R SDK.
## Create an estimator
An Azure ML **estimator** encapsulates the run configuration information needed for executing a training script on the compute target. Azure ML runs are run as containerized jobs on the specified compute target. By default, the Docker image built for your training job will include R, the Azure ML SDK, and a set of commonly used R packages. See the full list of default packages included [here](https://azure.github.io/azureml-sdk-for-r/reference/r_environment.html).
To create the estimator, define the following:
* The directory that contains your scripts needed for training (`source_directory`). All the files in this directory are uploaded to the cluster node(s) for execution. The directory must contain your training script and any additional scripts required.
* The training script that will be executed (`entry_script`).
* The compute target (`compute_target`), in this case the AmlCompute cluster you created earlier.
* Any environment dependencies required for training. Since the training script requires the TensorFlow package, which is not included in the image by default, pass the package name to the `cran_packages` parameter to have it installed in the Docker container where the job will run. See the [`estimator()`](https://azure.github.io/azureml-sdk-for-r/reference/estimator.html) reference for the full set of configurable options.
* Set the `use_gpu = TRUE` flag so the default base GPU Docker image will be built, since the job will be run on a GPU cluster.
```{r create_estimator, eval=FALSE}
est <- estimator(source_directory = "project_files",
entry_script = "tf_mnist.R",
compute_target = compute_target,
cran_packages = c("tensorflow"),
use_gpu = TRUE)
```
## Submit the job
Finally submit the job to run on your cluster. [`submit_experiment()`](https://azure.github.io/azureml-sdk-for-r/reference/submit_experiment.html) returns a `Run` object that you can then use to interface with the run.
```{r submit_job, eval=FALSE}
run <- submit_experiment(exp, est)
```
You can view the run<75>s details as a table. Clicking the <20>Web View<65> link provided will bring you to Azure Machine Learning studio, where you can monitor the run in the UI.
```{r eval=FALSE}
view_run_details(run)
```
Model training happens in the background. Wait until the model has finished training before you run more code.
```{r eval=FALSE}
wait_for_run_completion(run, show_output = TRUE)
```
## View run metrics
Once your job has finished, you can view the metrics collected during your TensorFlow run.
```{r get_metrics, eval=FALSE}
metrics <- get_run_metrics(run)
metrics
```
## Clean up resources
Delete the resources once you no longer need them. Don't delete any resource you plan to still use.
Delete the compute cluster:
```{r delete_compute, eval=FALSE}
delete_compute(compute_target)
```

View File

@@ -6,6 +6,6 @@ dependencies:
- interpret-community[visualization] - interpret-community[visualization]
- matplotlib - matplotlib
- azureml-contrib-interpret - azureml-contrib-interpret
- sklearn-pandas - sklearn-pandas<2.0.0
- azureml-dataset-runtime - azureml-dataset-runtime
- ipywidgets - ipywidgets

View File

@@ -6,5 +6,5 @@ dependencies:
- interpret-community[visualization] - interpret-community[visualization]
- matplotlib - matplotlib
- azureml-contrib-interpret - azureml-contrib-interpret
- sklearn-pandas - sklearn-pandas<2.0.0
- ipywidgets - ipywidgets

View File

@@ -6,7 +6,7 @@ dependencies:
- interpret-community[visualization] - interpret-community[visualization]
- matplotlib - matplotlib
- azureml-contrib-interpret - azureml-contrib-interpret
- sklearn-pandas - sklearn-pandas<2.0.0
- azureml-dataset-runtime - azureml-dataset-runtime
- azureml-core - azureml-core
- ipywidgets - ipywidgets

View File

@@ -34,7 +34,7 @@
"| Azure Data Lake Storage Gen 1 | Yes | Yes |\n", "| Azure Data Lake Storage Gen 1 | Yes | Yes |\n",
"| Azure Data Lake Storage Gen 2 | Yes | Yes |\n", "| Azure Data Lake Storage Gen 2 | Yes | Yes |\n",
"| Azure SQL Database | Yes | Yes |\n", "| Azure SQL Database | Yes | Yes |\n",
"| Azure Database for PostgreSQL | Yes | Yes |", "| Azure Database for PostgreSQL | Yes | Yes |\n",
"| Azure Database for MySQL | Yes | Yes |" "| Azure Database for MySQL | Yes | Yes |"
] ]
}, },
@@ -558,7 +558,7 @@
"metadata": { "metadata": {
"authors": [ "authors": [
{ {
"name": "sanpil" "name": "shbijlan"
} }
], ],
"category": "tutorial", "category": "tutorial",

View File

@@ -100,7 +100,7 @@
"from azureml.core.compute_target import ComputeTargetException\n", "from azureml.core.compute_target import ComputeTargetException\n",
"\n", "\n",
"# choose a name for your cluster\n", "# choose a name for your cluster\n",
"cluster_name = \"cpu-cluster\"\n", "cluster_name = \"amlcomp\"\n",
"\n", "\n",
"try:\n", "try:\n",
" cpu_cluster = ComputeTarget(workspace=ws, name=cluster_name)\n", " cpu_cluster = ComputeTarget(workspace=ws, name=cluster_name)\n",
@@ -147,10 +147,8 @@
" 'script_params' accepts a dictionary. However 'estimator_entry_script_arguments' parameter expects arguments as\n", " 'script_params' accepts a dictionary. However 'estimator_entry_script_arguments' parameter expects arguments as\n",
" a list.\n", " a list.\n",
"\n", "\n",
"> Estimator object initialization involves specifying a list of DataReference objects in its 'inputs' parameter.\n", "> Estimator object initialization involves specifying a list of data input and output.\n",
" In Pipelines, a step can take another step's output or DataReferences as input. So when creating an EstimatorStep,\n", " In Pipelines, a step can take another step's output as input. So when creating an EstimatorStep.\n",
" the parameters 'inputs' and 'outputs' need to be set explicitly and that will override 'inputs' parameter\n",
" specified in the Estimator object.\n",
" \n", " \n",
"> The best practice is to use separate folders for scripts and its dependent files for each step and specify that folder as the `source_directory` for the step. This helps reduce the size of the snapshot created for the step (only the specific folder is snapshotted). Since changes in any files in the `source_directory` would trigger a re-upload of the snapshot, this helps keep the reuse of the step when there are no changes in the `source_directory` of the step." "> The best practice is to use separate folders for scripts and its dependent files for each step and specify that folder as the `source_directory` for the step. This helps reduce the size of the snapshot created for the step (only the specific folder is snapshotted). Since changes in any files in the `source_directory` would trigger a re-upload of the snapshot, this helps keep the reuse of the step when there are no changes in the `source_directory` of the step."
] ]
@@ -166,17 +164,27 @@
"outputs": [], "outputs": [],
"source": [ "source": [
"from azureml.core import Datastore\n", "from azureml.core import Datastore\n",
"from azureml.data.data_reference import DataReference\n",
"from azureml.pipeline.core import PipelineData\n",
"\n", "\n",
"def_blob_store = Datastore(ws, \"workspaceblobstore\")\n", "def_blob_store = Datastore(ws, \"workspaceblobstore\")\n",
"\n", "\n",
"input_data = DataReference(\n", "#upload input data to workspaceblobstore\n",
" datastore=def_blob_store,\n", "def_blob_store.upload_files(files=['20news.pkl'], target_path='20newsgroups')"
" data_reference_name=\"input_data\",\n", ]
" path_on_datastore=\"20newsgroups/20news.pkl\")\n", },
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.core import Dataset\n",
"from azureml.data import OutputFileDatasetConfig\n",
"\n", "\n",
"output = PipelineData(\"output\", datastore=def_blob_store)\n", "# create dataset to be used as the input to estimator step\n",
"input_data = Dataset.File.from_files(def_blob_store.path('20newsgroups/20news.pkl'))\n",
"\n",
"# OutputFileDatasetConfig by default write output to the default workspaceblobstore\n",
"output = OutputFileDatasetConfig()\n",
"\n", "\n",
"source_directory = 'estimator_train'" "source_directory = 'estimator_train'"
] ]
@@ -204,10 +212,8 @@
"\n", "\n",
"- **name:** Name of the step\n", "- **name:** Name of the step\n",
"- **estimator:** Estimator object\n", "- **estimator:** Estimator object\n",
"- **estimator_entry_script_arguments:** \n", "- **estimator_entry_script_arguments:** A list of command-line arguments\n",
"- **runconfig_pipeline_params:** Override runconfig properties at runtime using key-value pairs each with name of the runconfig property and PipelineParameter for that property\n", "- **runconfig_pipeline_params:** Override runconfig properties at runtime using key-value pairs each with name of the runconfig property and PipelineParameter for that property\n",
"- **inputs:** Inputs\n",
"- **outputs:** Output is list of PipelineData\n",
"- **compute_target:** Compute target to use \n", "- **compute_target:** Compute target to use \n",
"- **allow_reuse:** Whether the step should reuse previous results when run with the same settings/inputs. If this is false, a new run will always be generated for this step during pipeline execution.\n", "- **allow_reuse:** Whether the step should reuse previous results when run with the same settings/inputs. If this is false, a new run will always be generated for this step during pipeline execution.\n",
"- **version:** Optional version tag to denote a change in functionality for the step" "- **version:** Optional version tag to denote a change in functionality for the step"
@@ -227,10 +233,8 @@
"\n", "\n",
"est_step = EstimatorStep(name=\"Estimator_Train\", \n", "est_step = EstimatorStep(name=\"Estimator_Train\", \n",
" estimator=est, \n", " estimator=est, \n",
" estimator_entry_script_arguments=[\"--datadir\", input_data, \"--output\", output],\n", " estimator_entry_script_arguments=[\"--datadir\", input_data.as_mount(), \"--output\", output],\n",
" runconfig_pipeline_params=None, \n", " runconfig_pipeline_params=None, \n",
" inputs=[input_data], \n",
" outputs=[output], \n",
" compute_target=cpu_cluster)" " compute_target=cpu_cluster)"
] ]
}, },

View File

@@ -42,11 +42,9 @@
"outputs": [], "outputs": [],
"source": [ "source": [
"import azureml.core\n", "import azureml.core\n",
"from azureml.core import Workspace, Experiment\n", "from azureml.core import Workspace, Experiment, Datastore, Dataset\n",
"from azureml.core.datastore import Datastore\n",
"from azureml.core.compute import ComputeTarget, AmlCompute\n", "from azureml.core.compute import ComputeTarget, AmlCompute\n",
"from azureml.exceptions import ComputeTargetException\n", "from azureml.exceptions import ComputeTargetException\n",
"from azureml.data.data_reference import DataReference\n",
"from azureml.pipeline.steps import HyperDriveStep, HyperDriveStepRun\n", "from azureml.pipeline.steps import HyperDriveStep, HyperDriveStepRun\n",
"from azureml.pipeline.core import Pipeline, PipelineData\n", "from azureml.pipeline.core import Pipeline, PipelineData\n",
"from azureml.train.dnn import TensorFlow\n", "from azureml.train.dnn import TensorFlow\n",
@@ -179,8 +177,25 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"ds = ws.get_default_datastore()\n", "datastore = ws.get_default_datastore()\n",
"ds.upload(src_dir='./data/mnist', target_path='mnist', overwrite=True, show_progress=True)" "datastore.upload(src_dir='./data/mnist', target_path='mnist', overwrite=True, show_progress=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Create Azure Machine Learning datasets\n",
"By creating a dataset, you create a reference to the data source location. If you applied any subsetting transformations to the dataset, they will be stored in the dataset as well. The data remains in its existing location, so no extra storage cost is incurred."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"dataset = Dataset.File.from_files(datastore.path('mnist'))"
] ]
}, },
{ {
@@ -204,7 +219,7 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"cluster_name = \"gpu-cluster\"\n", "cluster_name = \"amlcomp\"\n",
"\n", "\n",
"try:\n", "try:\n",
" compute_target = ComputeTarget(workspace=ws, name=cluster_name)\n", " compute_target = ComputeTarget(workspace=ws, name=cluster_name)\n",
@@ -264,7 +279,8 @@
" compute_target=compute_target,\n", " compute_target=compute_target,\n",
" entry_script='tf_mnist.py', \n", " entry_script='tf_mnist.py', \n",
" use_gpu=True,\n", " use_gpu=True,\n",
" framework_version='1.13')" " framework_version='2.0',\n",
" pip_packages=['azureml-dataset-runtime[pandas,fuse]'])"
] ]
}, },
{ {
@@ -344,7 +360,7 @@
"## Add HyperDrive as a step of pipeline\n", "## Add HyperDrive as a step of pipeline\n",
"\n", "\n",
"### Setup an input for the hypderdrive step\n", "### Setup an input for the hypderdrive step\n",
"Let's setup a data reference for inputs of hyperdrive step." "You can mount dataset to remote compute."
] ]
}, },
{ {
@@ -353,9 +369,7 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"data_folder = DataReference(\n", "data_folder = dataset.as_mount()"
" datastore=ds,\n",
" data_reference_name=\"mnist_data\")"
] ]
}, },
{ {
@@ -386,7 +400,7 @@
"source": [ "source": [
"metrics_output_name = 'metrics_output'\n", "metrics_output_name = 'metrics_output'\n",
"metrics_data = PipelineData(name='metrics_data',\n", "metrics_data = PipelineData(name='metrics_data',\n",
" datastore=ds,\n", " datastore=datastore,\n",
" pipeline_output_name=metrics_output_name)\n", " pipeline_output_name=metrics_output_name)\n",
"\n", "\n",
"hd_step_name='hd_step01'\n", "hd_step_name='hd_step01'\n",
@@ -577,7 +591,7 @@
"name": "python", "name": "python",
"nbconvert_exporter": "python", "nbconvert_exporter": "python",
"pygments_lexer": "ipython3", "pygments_lexer": "ipython3",
"version": "3.6.7" "version": "3.6.9"
}, },
"order_index": 8, "order_index": 8,
"star_tag": [ "star_tag": [

View File

@@ -6,3 +6,4 @@ dependencies:
- matplotlib - matplotlib
- numpy - numpy
- pandas_ml - pandas_ml
- azureml-dataset-runtime[pandas,fuse]

View File

@@ -87,7 +87,7 @@
"source": [ "source": [
"## Create an Azure ML experiment\n", "## Create an Azure ML experiment\n",
"\n", "\n",
"Let's create an experiment named \"automl-classification\" and a folder to hold the training scripts. The script runs will be recorded under the experiment in Azure." "Let's create an experiment named \"showcasing-datapath\" and a folder to hold the training scripts. The script runs will be recorded under the experiment in Azure."
] ]
}, },
{ {
@@ -479,7 +479,7 @@
"metadata": { "metadata": {
"authors": [ "authors": [
{ {
"name": "sanpil" "name": "shbijlan"
} }
], ],
"category": "tutorial", "category": "tutorial",

View File

@@ -4,34 +4,103 @@
import numpy as np import numpy as np
import argparse import argparse
import os import os
import re
import tensorflow as tf import tensorflow as tf
import time
import glob
from azureml.core import Run from azureml.core import Run
from utils import load_data from utils import load_data
from tensorflow.keras import Model, layers
print("TensorFlow version:", tf.VERSION)
# 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 = argparse.ArgumentParser()
parser.add_argument('--data-folder', type=str, dest='data_folder', help='data folder mounting point') 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=50, help='mini batch size for training') 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=100, parser.add_argument('--first-layer-neurons', type=int, dest='n_hidden_1', default=128,
help='# of neurons in the first layer') 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') 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('--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() args = parser.parse_args()
data_folder = os.path.join(args.data_folder, 'mnist') 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))
print('training dataset is stored here:', data_folder) 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(os.path.join(data_folder, 'train-images.gz'), False) / 255.0 X_train = load_data(os.path.join(data_folder, 'train-images.gz'), False) / 255.0
X_test = load_data(os.path.join(data_folder, 'test-images.gz'), False) / 255.0 X_test = load_data(os.path.join(data_folder, 'test-images.gz'), False) / 255.0
y_train = load_data(os.path.join(data_folder, 'train-labels.gz'), True).reshape(-1) y_train = load_data(os.path.join(data_folder, 'train-labels.gz'), True).reshape(-1)
y_test = load_data(os.path.join(data_folder, 'test-labels.gz'), True).reshape(-1) y_test = load_data(os.path.join(data_folder, 'test-labels.gz'), True).reshape(-1)
print(X_train.shape, y_train.shape, X_test.shape, y_test.shape, sep='\n') print(X_train.shape, y_train.shape, X_test.shape, y_test.shape, sep='\n')
training_set_size = X_train.shape[0] training_set_size = X_train.shape[0]
n_inputs = 28 * 28 n_inputs = 28 * 28
@@ -39,36 +108,31 @@ n_h1 = args.n_hidden_1
n_h2 = args.n_hidden_2 n_h2 = args.n_hidden_2
n_outputs = 10 n_outputs = 10
learning_rate = args.learning_rate learning_rate = args.learning_rate
n_epochs = 50 n_epochs = 20
batch_size = args.batch_size batch_size = args.batch_size
with tf.name_scope('network'): # Build neural network model.
# construct the DNN neural_net = NeuralNet()
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')
with tf.name_scope('train'): # Stochastic gradient descent optimizer.
cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y, logits=output) optimizer = tf.optimizers.SGD(learning_rate)
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()
# start an Azure ML run # start an Azure ML run
run = Run.get_context() run = Run.get_context()
with tf.Session() as sess: if previous_model_location:
init.run() # Restore variables from latest checkpoint.
for epoch in range(n_epochs): 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_time = time.perf_counter()
for epoch in range(0, n_epochs):
# randomly shuffle training set # randomly shuffle training set
indices = np.random.permutation(training_set_size) indices = np.random.permutation(training_set_size)
@@ -87,20 +151,36 @@ with tf.Session() as sess:
b_end = min(b_start + batch_size, training_set_size) b_end = min(b_start + batch_size, training_set_size)
# train # train
sess.run(train_op, feed_dict={X: X_batch, y: y_batch}) run_optimization(X_batch, y_batch)
# evaluate training set # evaluate training set
acc_train = acc_op.eval(feed_dict={X: X_batch, y: y_batch}) pred = neural_net(X_batch, is_training=False)
acc_train = accuracy(pred, y_batch)
# evaluate validation set # evaluate validation set
acc_val = acc_op.eval(feed_dict={X: X_test, y: y_test}) pred = neural_net(X_test, is_training=False)
acc_val = accuracy(pred, y_test)
# log accuracies # log accuracies
run.log('training_acc', np.float(acc_train)) run.log('training_acc', np.float(acc_train))
run.log('validation_acc', np.float(acc_val)) run.log('validation_acc', np.float(acc_val))
print(epoch, '-- Training accuracy:', acc_train, '\b Validation accuracy:', 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)
# 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)) run.log('final_acc', np.float(acc_val))
os.makedirs('./outputs/model', exist_ok=True) os.makedirs('./outputs/model', exist_ok=True)
# files saved in the "./outputs" folder are automatically uploaded into run history # files saved in the "./outputs" folder are automatically uploaded into run history
saver.save(sess, './outputs/model/mnist-tf.model') # 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)))

View File

@@ -13,7 +13,7 @@
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {}, "metadata": {},
"source": [ "source": [
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/using-mlflow/train-and-deploy-keras-auto-logging/train-and-deploy-keras-auto-logging.png)" "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/ml-frameworks/using-mlflow/train-and-deploy-keras-auto-logging/train-and-deploy-keras-auto-logging.png)"
] ]
}, },
{ {

View File

@@ -13,7 +13,7 @@
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {}, "metadata": {},
"source": [ "source": [
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/using-mlflow/train-and-deploy-pytorch/train-and-deploy-pytorch.png)" "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/ml-frameworks/using-mlflow/train-and-deploy-pytorch/train-and-deploy-pytorch.png)"
] ]
}, },
{ {

View File

@@ -539,7 +539,7 @@
" except StopIteration:\n", " except StopIteration:\n",
" time.sleep(1)\n", " time.sleep(1)\n",
"\n", "\n",
"tb = Tensorboard([head_run])\n", "tb = Tensorboard([head_run], port=6007)\n",
"tb.start()" "tb.start()"
] ]
}, },

View File

@@ -12,8 +12,8 @@
Try out the sample notebooks: Try out the sample notebooks:
1. [Use MLflow with Azure Machine Learning for Local Training Run](./using-mlflow/train-local/train-local.ipynb) 1. [Use MLflow with Azure Machine Learning for Local Training Run](./using-mlflow/train-local/train-local.ipynb)
1. [Use MLflow with Azure Machine Learning for Remote Training Run](./using-mlflow/train-remote/train-remote.ipynb) 1. [Use MLflow with Azure Machine Learning for Remote Training Run](./using-mlflow/train-remote/train-remote.ipynb)
1. [Train and Deploy PyTorch Image Classifier](./using-mlflow/train-and-deploy-pytorch/train-and-deploy-pytorch.ipynb) 1. [Use MLflow with Azure Machine Learning to submit runs locally with MLflow projects](./using-mlflow/train-projects-local/train-projects-local.ipynb)
1. [Train and Deploy Keras Image Classifier with MLflow auto logging](./using-mlflow/train-and-deploy-keras-auto-logging/train-and-deploy-keras-auto-logging.ipynb) 1. [Use MLflow with Azure Machine Learning to submit runs on AzureML compute with MLflow projects](./using-mlflow/train-projects-remote/train-projects-remote.ipynb)
![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/track-and-monitor-experiments/README.png) ![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/track-and-monitor-experiments/README.png)

View File

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

View File

@@ -161,7 +161,7 @@
"\n", "\n",
"We'll start by running this locally. While it might not initially seem that useful to use this for a local run - why not just run TB against the files generated locally? - even in this case there is some value to using this feature. Your local run will be registered in the run history, and your Tensorboard logs will be uploaded to the artifact store associated with this run. Later, you'll be able to restore the logs from any run, regardless of where it happened.\n", "We'll start by running this locally. While it might not initially seem that useful to use this for a local run - why not just run TB against the files generated locally? - even in this case there is some value to using this feature. Your local run will be registered in the run history, and your Tensorboard logs will be uploaded to the artifact store associated with this run. Later, you'll be able to restore the logs from any run, regardless of where it happened.\n",
"\n", "\n",
"Note that for this run, you will need to install Tensorflow on your local machine by yourself. Further, the Tensorboard module (that is, the one included with Tensorflow) must be accessible to this notebook's kernel, as the local machine is what runs Tensorboard." "Note that for this run, you will need to install Tensorflow on your local machine by yourself. Further, the Tensorboard module (that is, the one included with Tensorflow) must be accessible to this notebook's kernel, as the local machine is what runs Tensorboard. In addition, you will also need to have the `azureml-tensorboard` package installed."
] ]
}, },
{ {
@@ -170,14 +170,13 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"from azureml.core.runconfig import RunConfiguration\n", "from azureml.core import Environment\n",
"\n", "\n",
"# Create a run configuration.\n", "myenv = Environment(\"myenv\")\n",
"run_config = RunConfiguration()\n", "myenv.python.user_managed_dependencies = True\n",
"run_config.environment.python.user_managed_dependencies = True\n",
"\n", "\n",
"# You can choose a specific Python environment by pointing to a Python path \n", "# You can choose a specific Python environment by pointing to a Python path \n",
"#run_config.environment.python.interpreter_path = '/home/ninghai/miniconda3/envs/sdk2/bin/python'" "#myenv.python.interpreter_path = '/home/ninghai/miniconda3/envs/sdk2/bin/python'"
] ]
}, },
{ {
@@ -199,20 +198,20 @@
"\n", "\n",
"# Writing logs to ./logs results in their being uploaded to Artifact Service,\n", "# Writing logs to ./logs results in their being uploaded to Artifact Service,\n",
"# and thus, made accessible to our Tensorboard instance.\n", "# and thus, made accessible to our Tensorboard instance.\n",
"arguments_list = [\"--log_dir\", logs_dir]\n", "arguments = [\"--log_dir\", logs_dir]\n",
"\n", "\n",
"# Create an experiment\n", "# Create an experiment\n",
"exp = Experiment(ws, experiment_name)\n", "exp = Experiment(ws, experiment_name)\n",
"\n", "\n",
"# If you would like the run to go for longer, add --max_steps 5000 to the arguments list:\n", "# If you would like the run to go for longer, add --max_steps 5000 to the arguments list:\n",
"# arguments_list += [\"--max_steps\", \"5000\"]\n", "# arguments += [\"--max_steps\", \"5000\"]\n",
"\n", "\n",
"script = ScriptRunConfig(exp_dir,\n", "src = ScriptRunConfig(exp_dir,\n",
" script=\"mnist_with_summaries.py\",\n", " script=\"mnist_with_summaries.py\",\n",
" run_config=run_config,\n", " arguments=arguments,\n",
" arguments=arguments_list)\n", " environment=myenv)\n",
"\n", "\n",
"run = exp.submit(script)\n", "run = exp.submit(src)\n",
"# You can also wait for the run to complete\n", "# You can also wait for the run to complete\n",
"# run.wait_for_completion(show_output=True)\n", "# run.wait_for_completion(show_output=True)\n",
"runs.append(run)" "runs.append(run)"
@@ -578,7 +577,7 @@
"name": "python", "name": "python",
"nbconvert_exporter": "python", "nbconvert_exporter": "python",
"pygments_lexer": "ipython3", "pygments_lexer": "ipython3",
"version": "3.6.6" "version": "3.7.7"
}, },
"tags": [ "tags": [
"None" "None"

View File

@@ -0,0 +1,10 @@
name: mlflow-example
conda_env: conda.yaml
entry_points:
main:
parameters:
alpha: float
l1_ratio: {type: float, default: 0.1}
command: "python train.py {alpha} {l1_ratio}"

View File

@@ -0,0 +1,3 @@
{
"USE_CONDA": "False"
}

View File

@@ -0,0 +1,13 @@
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license.
name: mlflow-example
channels:
- defaults
dependencies:
- numpy>=1.14.3
- pandas>=1.0.0
- scikit-learn=0.19.1
- pip
- pip:
- mlflow
- azureml-mlflow

View File

@@ -0,0 +1,304 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/track-and-monitor-experiments/using-mlflow/train-projects-local/train-projects-local.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
"\n",
"Licensed under the MIT License."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Train with MLflow Projects on local compute\n",
"\n",
"Train MLflow Projects on your machine with local compute and AzureML tracking. In this notebook you will:\n",
"\n",
"1. Set up MLflow tracking URI to track experiments and metrics in AzureML\n",
"2. Create experiment\n",
"3. Set up an MLflow project to run on AzureML compute\n",
"4. Submit an MLflow project run and view it in an AzureML workspace "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Prerequisites \n",
"\n",
"If you are using a Notebook VM, you're all set. Otherwise, go through the [Configuration](../../../../configuration.ipnyb) notebook to set up your Azure Machine Learning workspace and ensure other common prerequisites are met.\n",
"\n",
"Install azureml-mlflow package before running this notebook. Note that mlflow itself gets installed as dependency if you haven't installed it yet.\n",
"\n",
"```\n",
"pip install azureml-mlflow\n",
"```\n",
"\n",
"This example also uses scikit-learn. Install them using the following:\n",
"```\n",
"pip install scikit-learn matplotlib\n",
"```\n",
"\n",
"Make sure you have the following before starting the notebook: \n",
"- Connected to an AzureML Workspace \n",
"- Your local conda environment has the necessary packages needed to run this project\n",
"\n",
"\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Set-up\n",
"\n",
"Configure your workspace and check package versions"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"import sys, os\n",
"import mlflow\n",
"import mlflow.azureml\n",
"\n",
"import azureml.core\n",
"from azureml.core import Workspace\n",
"\n",
"ws = Workspace.from_config()\n",
"\n",
"print(\"SDK version:\", azureml.core.VERSION)\n",
"print(\"MLflow version:\", mlflow.version.VERSION)\n",
"print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep = '\\n')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Initialize Tracking Store and Experiment\n",
"\n",
"### Set the Tracking Store\n",
"Set the MLflow tracking URI to point to your Azure ML Workspace. The subsequent logging calls from MLflow APIs will go to Azure ML services and will be tracked under your Workspace."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"mlflow.set_tracking_uri(ws.get_mlflow_tracking_uri())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Create Experiment\n",
"Create an Mlflow Experiment to organize your runs. It can be set either by passing the name as a parameter in the mlflow.projects.run call or by the following,"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"experiment_name = \"train-project-local\"\n",
"mlflow.set_experiment(experiment_name)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Create the Backend Configuration Object\n",
"\n",
"The backend configuration object will store necesary information for the integration such as the compute target and whether to use your local managed environment or a system managed environment. \n",
"\n",
"The integration will accept \"COMPUTE\" and \"USE_CONDA\" as parameters where \"COMPUTE\" is set to the name of a remote target (not applicable for this training example) and \"USE_CONDA\" which creates a new environment for the project from the environment configuration file. You must set this to \"False\" and include it in the backend configuration object if you want to use your local environment for the project run. Mlflow accepts a dictionary object or a JSON file."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# dictionary\n",
"backend_config = {\"USE_CONDA\": False}\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Add the Integration to your Environment Configuration\n",
"\n",
"Add the azureml-mlflow package as a pip dependency to your environment configuration file (conda.yaml). The project can run without this addition, but key artifacts and metrics will not be logged to your Workspace. An example conda.yaml file is included in this notebook folder. Adding it to to the file will look like this,\n",
"\n",
"```\n",
"name: mlflow-example\n",
"channels:\n",
" - defaults\n",
" - anaconda\n",
" - conda-forge\n",
"dependencies:\n",
" - python=3.6\n",
" - scikit-learn=0.19.1\n",
" - pip\n",
" - pip:\n",
" - mlflow\n",
" - azureml-mlflow\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## User Managed environment\n",
"For using your local conda environment, set `use_conda = False` in the backend_config object. Ensure your local environment has all the necessary packages for running the project and you are specifying the **backend parameter** in any run call to be **\"azureml\"**."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"local_env_run = mlflow.projects.run(uri=\".\", \n",
" parameters={\"alpha\":0.3},\n",
" backend = \"azureml\",\n",
" use_conda=False,\n",
" backend_config = backend_config)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"local_env_run"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note: All these calculations were run on your local machine, in the conda environment you defined above. You can find the results in:\n",
"- Your AzureML Experiments (a link to the run will be provided in the console)\n",
"- ~/.azureml/envs/azureml_xxxx for the conda environment you just created\n",
"- ~/AppData/Local/Temp/azureml_runs/train-on-local_xxxx for the machine learning models you trained (this path may differ depending on the platform you use). This folder also contains\n",
" - Logs (under azureml_logs/)\n",
" - Output pickled files (under outputs/)\n",
" - The configuration files (credentials, local and docker image setups)\n",
" - The train.py and mylib.py scripts\n",
" - The current notebook"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## System Mananged Environment\n",
"\n",
"Now, instead of managing the setup of the environment yourself, you can ask the system to build a new conda environment for you using the environment configuration file in this project. If a backend configuration object is not provided in the call, the integration will default to creating a new conda environment. The environment is built once, and will be reused in subsequent executions as long as the conda dependencies remain unchanged.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"backend_config = {\"USE_CONDA\": True}\n",
"local_mlproject_run = mlflow.projects.run(uri=\".\", \n",
" parameters={\"alpha\":0.3},\n",
" backend = \"azureml\",\n",
" backend_config = backend_config)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Next Steps \n",
"\n",
"Try out these notebooks to learn more about MLflow-Azure Machine Learning integration:\n",
"\n",
" * [Train a model using remote compute on Azure Cloud](../train-on-remote/train-on-remote.ipynb)\n",
" * [Deploy the model as a web service](../deploy-model/deploy-model.ipynb)\n",
" * [Train a model using Pytorch and MLflow](../../ml-frameworks/using-mlflow/train-and-deploy-pytorch)\n",
"\n"
]
}
],
"metadata": {
"authors": [
{
"name": "shipatel"
}
],
"category": "tutorial",
"celltoolbar": "Edit Metadata",
"compute": [
"Local"
],
"exclude_from_index": false,
"framework": [
"ScikitLearn"
],
"friendly_name": "Use MLflow projects with Azure Machine Learning to train a model with local compute",
"kernelspec": {
"display_name": "Python 3.6",
"language": "python",
"name": "python36"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.5-final"
},
"tags": [
"mlflow",
"scikit"
],
"task": "Use MLflow projects with Azure Machine Learning to train a model using local compute"
},
"nbformat": 4,
"nbformat_minor": 2
}

View File

@@ -0,0 +1,7 @@
name: train-projects-local
dependencies:
- scikit-learn
- pip:
- azureml-sdk
- scikit-learn
- azureml-mlflow

View File

@@ -0,0 +1,64 @@
# The data set used in this example is from http://archive.ics.uci.edu/ml/datasets/Wine+Quality
# P. Cortez, A. Cerdeira, F. Almeida, T. Matos and J. Reis.
# Modeling wine preferences by data mining from physicochemical properties.
# In Decision Support Systems, Elsevier, 47(4):547-553, 2009.
import os
import warnings
import sys
import pandas as pd
import numpy as np
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
from sklearn.model_selection import train_test_split
from sklearn.linear_model import ElasticNet
import mlflow
import mlflow.sklearn
def eval_metrics(actual, pred):
rmse = np.sqrt(mean_squared_error(actual, pred))
mae = mean_absolute_error(actual, pred)
r2 = r2_score(actual, pred)
return rmse, mae, r2
if __name__ == "__main__":
warnings.filterwarnings("ignore")
np.random.seed(40)
# Read the wine-quality csv file (make sure you're running this from the root of MLflow!)
wine_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "wine-quality.csv")
data = pd.read_csv(wine_path)
# Split the data into training and test sets. (0.75, 0.25) split.
train, test = train_test_split(data)
# The predicted column is "quality" which is a scalar from [3, 9]
train_x = train.drop(["quality"], axis=1)
test_x = test.drop(["quality"], axis=1)
train_y = train[["quality"]]
test_y = test[["quality"]]
alpha = float(sys.argv[1]) if len(sys.argv) > 1 else 0.5
l1_ratio = float(sys.argv[2]) if len(sys.argv) > 2 else 0.5
with mlflow.start_run():
lr = ElasticNet(alpha=alpha, l1_ratio=l1_ratio, random_state=42)
lr.fit(train_x, train_y)
predicted_qualities = lr.predict(test_x)
(rmse, mae, r2) = eval_metrics(test_y, predicted_qualities)
print("Elasticnet model (alpha=%f, l1_ratio=%f):" % (alpha, l1_ratio))
print(" RMSE: %s" % rmse)
print(" MAE: %s" % mae)
print(" R2: %s" % r2)
mlflow.log_param("alpha", alpha)
mlflow.log_param("l1_ratio", l1_ratio)
mlflow.log_metric("rmse", rmse)
mlflow.log_metric("r2", r2)
mlflow.log_metric("mae", mae)
mlflow.sklearn.log_model(lr, "model")

View File

@@ -0,0 +1,10 @@
name: tutorial
conda_env: conda.yaml
entry_points:
main:
parameters:
alpha: float
l1_ratio: {type: float, default: 0.1}
command: "python train.py {alpha} {l1_ratio}"

View File

@@ -0,0 +1,4 @@
{
"COMPUTE": "cpu-cluster",
"USE_CONDA": "True"
}

View File

@@ -0,0 +1,13 @@
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license.
name: tutorial
channels:
- defaults
dependencies:
- numpy>=1.14.3
- pandas>=1.0.0
- scikit-learn=0.19.1
- pip
- pip:
- mlflow
- azureml-mlflow

View File

@@ -0,0 +1,276 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/track-and-monitor-experiments/using-mlflow/train-projects-remote/train-projects-remote.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
"\n",
"Licensed under the MIT License."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Train with MLflow Projects on AML Compute\n",
"\n",
"Train MLflow Projects on Azure Machine Learning Compute.\n",
"\n",
"Train MLflow Projects on your machine with AzureML compute and tracking. In this notebook you will:\n",
"\n",
"1. Set up MLflow tracking URI to track experiments and metrics in AzureML\n",
"2. Create experiment\n",
"3. Set up an MLflow project to run on AzureML compute\n",
"4. Submit an MLflow project run and view it in an AzureML workspace \n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Prerequisites \n",
"\n",
"If you are using a Notebook VM, you are all set. Otherwise, go through the [Configuration](../../../../configuration.ipnyb) notebook to set up your Azure Machine Learning workspace and ensure other common prerequisites are met.\n",
"\n",
"Make sure you have the following before staring the notebook: \n",
"- Connected to an AML Workspace \n",
"- Have an existing [Azure ML Compute cluster](https://docs.microsoft.com/azure/machine-learning/how-to-create-attach-compute-sdk#amlcompute) in that Workspace \n",
"- Have an MLproject file with a modified environment specification \n",
"\n",
"Add the azureml-mlflow package as a pip dependency to your environment configuration file (conda.yaml). The project can run without this addition, but key artifacts and metrics will not be logged to your Workspace. An example conda.yaml is included in this tutorial folder with the necessary packages. \n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Set-up \n",
"\n",
"Check the Azure ML and MLflow SDK version installed on your computer and connect to your workspace"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"import sys, os\n",
"import mlflow\n",
"import mlflow.azureml\n",
"\n",
"import azureml.core\n",
"from azureml.core import Workspace\n",
"\n",
"ws = Workspace.from_config()\n",
"\n",
"print(\"SDK version:\", azureml.core.VERSION)\n",
"print(\"MLflow version:\", mlflow.version.VERSION)\n",
"print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep = '\\n')\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Initialize Tracking Store and Experiment\n",
"\n",
"### Set Tracking URI \n",
"\n",
"Set the MLflow tracking URI to point to your Azure ML Workspace. The subsequent logging calls from MLflow APIs will go to Azure ML services and will be tracked under your Workspace."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"mlflow.set_tracking_uri(ws.get_mlflow_tracking_uri())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Create Experiment\n",
"\n",
"Create an Mlflow Experiment to organize your runs. It can be set either by passing the name as a **parameter** in the mlflow.projects.run call or by the following,"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"experiment_name = \"train-project-amlcompute\"\n",
"mlflow.set_experiment(experiment_name)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Create the Backend Configuration Object\n",
"\n",
"The backend configuration object will store necesary information for the integration such as the compute target and whether to use your local managed environment or a system managed environment. \n",
"\n",
"The integration will accept \"COMPUTE\" and \"USE_CONDA\" as parameters where \"COMPUTE\" is set to the name of your remote compute cluster and \"USE_CONDA\" which creates a new environment for the project from the environment configuration file. If \"COMPUTE\" is present in the object, the project will be automatically submitted to the remote compute and ignore \"USE_CONDA\". MLflow accepts a dictionary object or a JSON file."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# dictionary\n",
"backend_config = {\"COMPUTE\": \"cpu-cluster\", \"USE_CONDA\": False}\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Modify your Environment specification\n",
"\n",
"Add the azureml-mlflow package as a pip dependency to your environment configuration file (conda.yaml). The project can run without this addition, but key artifacts and metrics will not be logged to your Workspace. An example conda.yaml is included in the notebook folder. Adding it to to the file will look like this,\n",
"\n",
"```\n",
"name: mlflow-example\n",
"channels:\n",
" - defaults\n",
" - anaconda\n",
" - conda-forge\n",
"dependencies:\n",
" - python=3.6\n",
" - scikit-learn=0.19.1\n",
" - pip\n",
" - pip:\n",
" - mlflow\n",
" - azureml-mlflow\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Submit Run \n",
"\n",
"Submit the mlflow project run using aml compute and ensure the **backened** parameter is set to azureml.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"remote_mlflow_run = mlflow.projects.run(uri=\".\", \n",
" parameters={\"alpha\":0.3},\n",
" backend = \"azureml\",\n",
" backend_config = backend_config,\n",
" synchronous=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### View run \n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"remote_mlflow_run"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Next Steps\n",
"\n",
"Try out these notebooks to learn more about MLflow-Azure Machine Learning integration:\n",
"\n",
" * [Train a model using remote compute on Azure Cloud](../train-on-remote/train-on-remote.ipynb)\n",
" * [Deploy the model as a web service](../deploy-model/deploy-model.ipynb)\n",
" * [Train a model using Pytorch and MLflow](../../ml-frameworks/using-mlflow/train-and-deploy-pytorch)\n",
"\n"
]
}
],
"metadata": {
"authors": [
{
"name": "shipatel"
}
],
"category": "tutorial",
"celltoolbar": "Edit Metadata",
"compute": [
"AML Compute"
],
"exclude_from_index": false,
"framework": [
"Scikit"
],
"friendly_name": "Use MLflow projects with Azure Machine Learning to train a model",
"kernelspec": {
"display_name": "Python 3.6",
"language": "python",
"name": "python36"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.5-final"
},
"tags": [
"mlflow",
"scikit"
],
"task": "Use MLflow projects with Azure Machine Learning to train a model using azureml compute"
},
"nbformat": 4,
"nbformat_minor": 2
}

View File

@@ -0,0 +1,7 @@
name: train-projects-remote
dependencies:
- scikit-learn
- pip:
- azureml-sdk
- scikit-learn
- azureml-mlflow

View File

@@ -0,0 +1,66 @@
# The data set used in this example is from http://archive.ics.uci.edu/ml/datasets/Wine+Quality
# P. Cortez, A. Cerdeira, F. Almeida, T. Matos and J. Reis.
# Modeling wine preferences by data mining from physicochemical properties.
# In Decision Support Systems, Elsevier, 47(4):547-553, 2009.
import os
import warnings
import sys
import pandas as pd
import numpy as np
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
from sklearn.model_selection import train_test_split
from sklearn.linear_model import ElasticNet
import mlflow
import mlflow.sklearn
def eval_metrics(actual, pred):
rmse = np.sqrt(mean_squared_error(actual, pred))
mae = mean_absolute_error(actual, pred)
r2 = r2_score(actual, pred)
return rmse, mae, r2
if __name__ == "__main__":
warnings.filterwarnings("ignore")
np.random.seed(40)
# Read the wine-quality csv file (make sure you're running this from the root of MLflow!)
wine_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "wine-quality.csv")
data = pd.read_csv(wine_path)
# Split the data into training and test sets. (0.75, 0.25) split.
train, test = train_test_split(data)
# The predicted column is "quality" which is a scalar from [3, 9]
train_x = train.drop(["quality"], axis=1)
test_x = test.drop(["quality"], axis=1)
train_y = train[["quality"]]
test_y = test[["quality"]]
alpha = float(sys.argv[1]) if len(sys.argv) > 1 else 0.5
l1_ratio = float(sys.argv[2]) if len(sys.argv) > 2 else 0.5
with mlflow.start_run():
lr = ElasticNet(alpha=alpha, l1_ratio=l1_ratio, random_state=42)
lr.fit(train_x, train_y)
predicted_qualities = lr.predict(test_x)
(rmse, mae, r2) = eval_metrics(test_y, predicted_qualities)
print("Elasticnet model (alpha=%f, l1_ratio=%f):" % (alpha, l1_ratio))
print(" RMSE: %s" % rmse)
print(" MAE: %s" % mae)
print(" R2: %s" % r2)
mlflow.log_param("alpha", alpha)
mlflow.log_param("l1_ratio", l1_ratio)
mlflow.log_metric("rmse", rmse)
mlflow.log_metric("r2", r2)
mlflow.log_metric("mae", mae)
mlflow.sklearn.log_model(lr, "model")

View File

@@ -80,11 +80,11 @@
"from azureml.core.compute_target import ComputeTargetException\n", "from azureml.core.compute_target import ComputeTargetException\n",
"\n", "\n",
"# Choose a name for your CPU cluster\n", "# Choose a name for your CPU cluster\n",
"cpu_cluster_name = \"cpu-cluster\"\n", "cluster_name = \"cpu-cluster\"\n",
"\n", "\n",
"# Verify that cluster does not exist already\n", "# Verify that cluster does not exist already\n",
"try:\n", "try:\n",
" cpu_cluster = ComputeTarget(workspace=ws, name=cpu_cluster_name)\n", " cpu_cluster = ComputeTarget(workspace=ws, name=cluster_name)\n",
" print(\"Found existing cpu-cluster\")\n", " print(\"Found existing cpu-cluster\")\n",
"except ComputeTargetException:\n", "except ComputeTargetException:\n",
" print(\"Creating new cpu-cluster\")\n", " print(\"Creating new cpu-cluster\")\n",
@@ -95,7 +95,7 @@
" max_nodes=2)\n", " max_nodes=2)\n",
"\n", "\n",
" # Create the cluster with the specified name and configuration\n", " # Create the cluster with the specified name and configuration\n",
" cpu_cluster = ComputeTarget.create(ws, cpu_cluster_name, compute_config)\n", " cpu_cluster = ComputeTarget.create(ws, cluster_name, compute_config)\n",
" \n", " \n",
" # Wait for the cluster to complete, show the output log\n", " # Wait for the cluster to complete, show the output log\n",
" cpu_cluster.wait_for_completion(show_output=True)" " cpu_cluster.wait_for_completion(show_output=True)"
@@ -208,9 +208,10 @@
"source": [ "source": [
"from azureml.core import ScriptRunConfig\n", "from azureml.core import ScriptRunConfig\n",
"\n", "\n",
"src = ScriptRunConfig(source_directory=\".\", script=training_script)\n", "src = ScriptRunConfig(source_directory=\".\",\n",
"src.run_config.environment = env\n", " script=training_script,\n",
"src.run_config.target = cpu_cluster.name" " compute_target=cpu_cluster,\n",
" environment=env)"
] ]
}, },
{ {
@@ -268,7 +269,7 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"ws.get_details()" "run.get_details()"
] ]
}, },
{ {
@@ -326,7 +327,7 @@
"name": "python", "name": "python",
"nbconvert_exporter": "python", "nbconvert_exporter": "python",
"pygments_lexer": "ipython3", "pygments_lexer": "ipython3",
"version": "3.6.4" "version": "3.7.7"
}, },
"tags": [ "tags": [
"None" "None"

View File

@@ -2,13 +2,7 @@
These examples show you: These examples show you:
1. [How to use the Estimator pattern in Azure ML](how-to-use-estimator) 1. [Train using Keras and tune hyperparameters using Hyperdrive](train-hyperparameter-tune-deploy-with-keras)
2. [Train using Keras and tune hyperparameters using Hyperdrive](train-hyperparameter-tune-deploy-with-keras) 2. [Export run history records to Tensorboard](export-run-history-to-tensorboard)
3. [Distributed training using CNTK and custom Docker image](distributed-cntk-with-custom-docker)
4. [Export run history records to Tensorboard](export-run-history-to-tensorboard)
5. [Use TensorBoard to monitor training execution](tensorboard)
Learn more about how to use `Estimator` class to [train deep neural networks with Azure Machine Learning](https://docs.microsoft.com/azure/machine-learning/service/how-to-train-ml-models).
![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/training-with-deep-learning/README.png) ![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/training-with-deep-learning/README.png)

View File

@@ -1,117 +0,0 @@
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license.
# Adapted from:
# https://github.com/Microsoft/CNTK/blob/master/Examples/Image/Classification/ConvNet/Python/ConvNet_MNIST.py
# ====================================================================
"""Train a CNN model on the MNIST dataset via distributed training."""
from __future__ import print_function
import numpy as np
import os
import cntk as C
import argparse
from cntk.train.training_session import CheckpointConfig, TestConfig
def create_reader(path, is_training, input_dim, label_dim, total_number_of_samples):
"""Define the reader for both training and evaluation action."""
return C.io.MinibatchSource(C.io.CTFDeserializer(path, C.io.StreamDefs(
features=C.io.StreamDef(field='features', shape=input_dim),
labels=C.io.StreamDef(field='labels', shape=label_dim)
)), randomize=is_training, max_samples=total_number_of_samples)
def convnet_mnist(max_epochs, output_dir, data_dir, debug_output=False, epoch_size=60000, minibatch_size=64):
"""Creates and trains a feedforward classification model for MNIST images."""
image_height = 28
image_width = 28
num_channels = 1
input_dim = image_height * image_width * num_channels
num_output_classes = 10
# Input variables denoting the features and label data
input_var = C.ops.input_variable((num_channels, image_height, image_width), np.float32)
label_var = C.ops.input_variable(num_output_classes, np.float32)
# Instantiate the feedforward classification model
scaled_input = C.ops.element_times(C.ops.constant(0.00390625), input_var)
with C.layers.default_options(activation=C.ops.relu, pad=False):
conv1 = C.layers.Convolution2D((5, 5), 32, pad=True)(scaled_input)
pool1 = C.layers.MaxPooling((3, 3), (2, 2))(conv1)
conv2 = C.layers.Convolution2D((3, 3), 48)(pool1)
pool2 = C.layers.MaxPooling((3, 3), (2, 2))(conv2)
conv3 = C.layers.Convolution2D((3, 3), 64)(pool2)
f4 = C.layers.Dense(96)(conv3)
drop4 = C.layers.Dropout(0.5)(f4)
z = C.layers.Dense(num_output_classes, activation=None)(drop4)
ce = C.losses.cross_entropy_with_softmax(z, label_var)
pe = C.metrics.classification_error(z, label_var)
# Load train data
reader_train = create_reader(os.path.join(data_dir, 'Train-28x28_cntk_text.txt'), True,
input_dim, num_output_classes, max_epochs * epoch_size)
# Load test data
reader_test = create_reader(os.path.join(data_dir, 'Test-28x28_cntk_text.txt'), False,
input_dim, num_output_classes, C.io.FULL_DATA_SWEEP)
# Set learning parameters
lr_per_sample = [0.001] * 10 + [0.0005] * 10 + [0.0001]
lr_schedule = C.learning_parameter_schedule_per_sample(lr_per_sample, epoch_size=epoch_size)
mms = [0] * 5 + [0.9990239141819757]
mm_schedule = C.learners.momentum_schedule_per_sample(mms, epoch_size=epoch_size)
# Instantiate the trainer object to drive the model training
local_learner = C.learners.momentum_sgd(z.parameters, lr_schedule, mm_schedule)
progress_printer = C.logging.ProgressPrinter(
tag='Training',
rank=C.train.distributed.Communicator.rank(),
num_epochs=max_epochs,
)
learner = C.train.distributed.data_parallel_distributed_learner(local_learner)
trainer = C.Trainer(z, (ce, pe), learner, progress_printer)
# define mapping from reader streams to network inputs
input_map_train = {
input_var: reader_train.streams.features,
label_var: reader_train.streams.labels
}
input_map_test = {
input_var: reader_test.streams.features,
label_var: reader_test.streams.labels
}
C.logging.log_number_of_parameters(z)
print()
C.train.training_session(
trainer=trainer,
mb_source=reader_train,
model_inputs_to_streams=input_map_train,
mb_size=minibatch_size,
progress_frequency=epoch_size,
checkpoint_config=CheckpointConfig(frequency=epoch_size,
filename=os.path.join(output_dir, "ConvNet_MNIST")),
test_config=TestConfig(reader_test, minibatch_size=minibatch_size,
model_inputs_to_streams=input_map_test)
).train()
return
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--num_epochs', help='Total number of epochs to train', type=int, default='40')
parser.add_argument('--output_dir', help='Output directory', required=False, default='outputs')
parser.add_argument('--data_dir', help='Directory with training data')
args = parser.parse_args()
os.makedirs(args.output_dir, exist_ok=True)
convnet_mnist(args.num_epochs, args.output_dir, args.data_dir)
# Must call MPI finalize when process exit without exceptions
C.train.distributed.Communicator.finalize()

View File

@@ -1,405 +0,0 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
"\n",
"Licensed under the MIT License."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/training-with-deep-learning/distributed-cntk-with-custom-docker/distributed-cntk-with-custom-docker.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Distributed CNTK using custom docker images\n",
"In this tutorial, you will train a CNTK model on the [MNIST](http://yann.lecun.com/exdb/mnist/) dataset using a custom docker image and distributed training."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Prerequisites\n",
"* Understand the [architecture and terms](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture) introduced by Azure Machine Learning\n",
"* If you are using an Azure Machine Learning Notebook VM, you are all set. Otherwise, go through the [configuration notebook](../../../configuration.ipynb) to:\n",
" * install the AML SDK\n",
" * create a workspace and its configuration file (`config.json`)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Check core SDK version number\n",
"import azureml.core\n",
"\n",
"print(\"SDK version:\", azureml.core.VERSION)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Diagnostics\n",
"Opt-in diagnostics for better experience, quality, and security of future releases."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": [
"Diagnostics"
]
},
"outputs": [],
"source": [
"from azureml.telemetry import set_diagnostics_collection\n",
"\n",
"set_diagnostics_collection(send_diagnostics=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Initialize workspace\n",
"\n",
"Initialize a [Workspace](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#workspace) object from the existing workspace you created in the Prerequisites step. `Workspace.from_config()` creates a workspace object from the details stored in `config.json`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.core.workspace import Workspace\n",
"\n",
"ws = Workspace.from_config()\n",
"print('Workspace name: ' + ws.name,\n",
" 'Azure region: ' + ws.location, \n",
" 'Subscription id: ' + ws.subscription_id, \n",
" 'Resource group: ' + ws.resource_group, sep='\\n')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Create or Attach existing AmlCompute\n",
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for training your model. In this tutorial, you create `AmlCompute` as your training compute resource.\n",
"\n",
"**Creation of AmlCompute takes approximately 5 minutes.** If the AmlCompute with that name is already in your workspace this code will skip the creation process.\n",
"\n",
"As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.core.compute import ComputeTarget, AmlCompute\n",
"from azureml.core.compute_target import ComputeTargetException\n",
"\n",
"# choose a name for your cluster\n",
"cluster_name = \"gpu-cluster\"\n",
"\n",
"try:\n",
" compute_target = ComputeTarget(workspace=ws, name=cluster_name)\n",
" print('Found existing compute target.')\n",
"except ComputeTargetException:\n",
" print('Creating a new compute target...')\n",
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_NC6',\n",
" max_nodes=4)\n",
"\n",
" # create the cluster\n",
" compute_target = ComputeTarget.create(ws, cluster_name, compute_config)\n",
"\n",
" compute_target.wait_for_completion(show_output=True)\n",
"\n",
"# use get_status() to get a detailed status for the current AmlCompute\n",
"print(compute_target.get_status().serialize())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Upload training data\n",
"For this tutorial, we will be using the MNIST dataset.\n",
"\n",
"First, let's download the dataset. We've included the `install_mnist.py` script to download the data and convert it to a CNTK-supported format. Our data files will get written to a directory named `'mnist'`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import install_mnist\n",
"\n",
"install_mnist.main('mnist')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To make the data accessible for remote training, you will need to upload the data from your local machine to the cloud. AML provides a convenient way to do so via a [Datastore](https://docs.microsoft.com/azure/machine-learning/service/how-to-access-data). The datastore provides a mechanism for you to upload/download data, and interact with it from your remote compute targets. \n",
"\n",
"Each workspace is associated with a default datastore. In this tutorial, we will upload the training data to this default datastore, which we will then mount on the remote compute for training in the next section."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"ds = ws.get_default_datastore()\n",
"print(ds.datastore_type, ds.account_name, ds.container_name)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The following code will upload the training data to the path `./mnist` on the default datastore."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"ds.upload(src_dir='./mnist', target_path='./mnist')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now let's get a reference to the path on the datastore with the training data. We can do so using the `path` method. In the next section, we can then pass this reference to our training script's `--data_dir` argument. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"path_on_datastore = 'mnist'\n",
"ds_data = ds.path(path_on_datastore)\n",
"print(ds_data)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Train model on the remote compute\n",
"Now that we have the cluster ready to go, let's run our distributed training job."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Create a project directory\n",
"Create a directory that will contain all the necessary code from your local machine that you will need access to on the remote resource. This includes the training script, and any additional files your training script depends on."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"\n",
"project_folder = './cntk-distr'\n",
"os.makedirs(project_folder, exist_ok=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Copy the training script `cntk_distr_mnist.py` into this project directory."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import shutil\n",
"\n",
"shutil.copy('cntk_distr_mnist.py', project_folder)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Create an experiment\n",
"Create an [experiment](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#experiment) to track all the runs in your workspace for this distributed CNTK tutorial. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.core import Experiment\n",
"\n",
"experiment_name = 'cntk-distr'\n",
"experiment = Experiment(ws, name=experiment_name)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Create an Estimator\n",
"The AML SDK's base Estimator enables you to easily submit custom scripts for both single-node and distributed runs. You should this generic estimator for training code using frameworks such as sklearn or CNTK that don't have corresponding custom estimators. For more information on using the generic estimator, refer [here](https://docs.microsoft.com/azure/machine-learning/service/how-to-train-ml-models)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": [
"estimator-remarks-sample"
]
},
"outputs": [],
"source": [
"from azureml.train.estimator import Estimator\n",
"\n",
"script_params = {\n",
" '--num_epochs': 20,\n",
" '--data_dir': ds_data.as_mount(),\n",
" '--output_dir': './outputs'\n",
"}\n",
"\n",
"estimator = Estimator(source_directory=project_folder,\n",
" compute_target=compute_target,\n",
" entry_script='cntk_distr_mnist.py',\n",
" script_params=script_params,\n",
" node_count=2,\n",
" process_count_per_node=1,\n",
" distributed_backend='mpi',\n",
" pip_packages=['cntk-gpu==2.6'],\n",
" custom_docker_image='microsoft/mmlspark:gpu-0.12',\n",
" use_gpu=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We would like to train our model using a [pre-built Docker container](https://hub.docker.com/r/microsoft/mmlspark/). To do so, specify the name of the docker image to the argument `custom_docker_image`. Finally, we provide the `cntk` package to `pip_packages` to install CNTK 2.6 on our custom image.\n",
"\n",
"The above code specifies that we will run our training script on `2` nodes, with one worker per node. In order to run distributed CNTK, which uses MPI, you must provide the argument `distributed_backend='mpi'`."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Submit job\n",
"Run your experiment by submitting your estimator object. Note that this call is asynchronous."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"run = experiment.submit(estimator)\n",
"print(run)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Monitor your run\n",
"You can monitor the progress of the run with a Jupyter widget. Like the run submission, the widget is asynchronous and provides live updates every 10-15 seconds until the job completes."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.widgets import RunDetails\n",
"\n",
"RunDetails(run).show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Alternatively, you can block until the script has completed training before running more code."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"run.wait_for_completion(show_output=True)"
]
}
],
"metadata": {
"authors": [
{
"name": "ninhu"
}
],
"kernelspec": {
"display_name": "Python 3.6",
"language": "python",
"name": "python36"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.6"
}
},
"nbformat": 4,
"nbformat_minor": 2
}

View File

@@ -1,6 +0,0 @@
name: distributed-cntk-with-custom-docker
dependencies:
- pip:
- azureml-sdk
- azureml-widgets
- numpy

View File

@@ -1,96 +0,0 @@
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license.
# Script from:
# https://github.com/Microsoft/CNTK/blob/master/Examples/Image/DataSets/MNIST/install_mnist.py
from __future__ import print_function
try:
from urllib.request import urlretrieve
except ImportError:
from urllib import urlretrieve
import gzip
import os
import struct
import numpy as np
def loadData(src, cimg):
print('Downloading ' + src)
gzfname, h = urlretrieve(src, './delete.me')
print('Done.')
try:
with gzip.open(gzfname) as gz:
n = struct.unpack('I', gz.read(4))
# Read magic number.
if n[0] != 0x3080000:
raise Exception('Invalid file: unexpected magic number.')
# Read number of entries.
n = struct.unpack('>I', gz.read(4))[0]
if n != cimg:
raise Exception('Invalid file: expected {0} entries.'.format(cimg))
crow = struct.unpack('>I', gz.read(4))[0]
ccol = struct.unpack('>I', gz.read(4))[0]
if crow != 28 or ccol != 28:
raise Exception('Invalid file: expected 28 rows/cols per image.')
# Read data.
res = np.fromstring(gz.read(cimg * crow * ccol), dtype=np.uint8)
finally:
os.remove(gzfname)
return res.reshape((cimg, crow * ccol))
def loadLabels(src, cimg):
print('Downloading ' + src)
gzfname, h = urlretrieve(src, './delete.me')
print('Done.')
try:
with gzip.open(gzfname) as gz:
n = struct.unpack('I', gz.read(4))
# Read magic number.
if n[0] != 0x1080000:
raise Exception('Invalid file: unexpected magic number.')
# Read number of entries.
n = struct.unpack('>I', gz.read(4))
if n[0] != cimg:
raise Exception('Invalid file: expected {0} rows.'.format(cimg))
# Read labels.
res = np.fromstring(gz.read(cimg), dtype=np.uint8)
finally:
os.remove(gzfname)
return res.reshape((cimg, 1))
def load(dataSrc, labelsSrc, cimg):
data = loadData(dataSrc, cimg)
labels = loadLabels(labelsSrc, cimg)
return np.hstack((data, labels))
def savetxt(filename, ndarray):
with open(filename, 'w') as f:
labels = list(map(' '.join, np.eye(10, dtype=np.uint).astype(str)))
for row in ndarray:
row_str = row.astype(str)
label_str = labels[row[-1]]
feature_str = ' '.join(row_str[:-1])
f.write('|labels {} |features {}\n'.format(label_str, feature_str))
def main(data_dir):
os.makedirs(data_dir, exist_ok=True)
train = load('http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz',
'http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz', 60000)
print('Writing train text file...')
train_txt = os.path.join(data_dir, 'Train-28x28_cntk_text.txt')
savetxt(train_txt, train)
print('Done.')
test = load('http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz',
'http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz', 10000)
print('Writing test text file...')
test_txt = os.path.join(data_dir, 'Test-28x28_cntk_text.txt')
savetxt(test_txt, test)
print('Done.')
if __name__ == "__main__":
main('mnist')

View File

@@ -1,42 +0,0 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import argparse
print("*********************************************************")
print("Hello Azure ML!")
parser = argparse.ArgumentParser()
parser.add_argument('--numbers-in-sequence', type=int, dest='num_in_sequence', default=10,
help='number of fibonacci numbers in sequence')
# This is how you can use a bool argument in Python. If you want the 'my_bool_var' to be True, just pass it
# in Estimator's script_param as script+params:{'my_bool_var': ''}.
# And, if you want to use it as False, then do not pass it in the Estimator's script_params.
# You can reverse the behavior by setting action='store_false' in the next line.
parser.add_argument("--my_bool_var", action='store_true')
args = parser.parse_args()
num = args.num_in_sequence
my_bool_var = args.my_bool_var
def fibo(n):
if n < 2:
return n
else:
return fibo(n - 1) + fibo(n - 2)
try:
from azureml.core import Run
run = Run.get_context()
print("The value of boolean parameter 'my_bool_var' is {}".format(my_bool_var))
print("Log Fibonacci numbers.")
for i in range(0, num - 1):
run.log('Fibonacci numbers', fibo(i))
run.complete()
except:
print("Warning: you need to install Azure ML SDK in order to log metrics.")
print("*********************************************************")

View File

@@ -1,561 +0,0 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
"\n",
"Licensed under the MIT License."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/training-with-deep-learning/how-to-use-estimator/how-to-use-estimator.png)"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "bf74d2e9-2708-49b1-934b-e0ede342f475"
}
},
"source": [
"# How to use Estimator in Azure ML\n",
"\n",
"## Introduction\n",
"This tutorial shows how to use the Estimator pattern in Azure Machine Learning SDK. Estimator is a convenient object in Azure Machine Learning that wraps run configuration information to help simplify the tasks of specifying how a script is executed.\n",
"\n",
"\n",
"## Prerequisite:\n",
"* Understand the [architecture and terms](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture) introduced by Azure Machine Learning\n",
"* If you are using an Azure Machine Learning Notebook VM, you are all set. Otherwise, go through the [configuration notebook](../../../configuration.ipynb) to:\n",
" * install the AML SDK\n",
" * create a workspace and its configuration file (`config.json`)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's get started. First let's import some Python libraries."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "edaa7f2f-2439-4148-b57a-8c794c0945ec"
}
},
"outputs": [],
"source": [
"import azureml.core\n",
"from azureml.core import Workspace\n",
"\n",
"# check core SDK version number\n",
"print(\"Azure ML SDK Version: \", azureml.core.VERSION)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Initialize workspace\n",
"Initialize a [Workspace](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#workspace) object from the existing workspace you created in the Prerequisites step. `Workspace.from_config()` creates a workspace object from the details stored in `config.json`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"ws = Workspace.from_config()\n",
"print('Workspace name: ' + ws.name, \n",
" 'Azure region: ' + ws.location, \n",
" 'Subscription id: ' + ws.subscription_id, \n",
" 'Resource group: ' + ws.resource_group, sep = '\\n')"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "59f52294-4a25-4c92-bab8-3b07f0f44d15"
}
},
"source": [
"## Create an Azure ML experiment\n",
"Let's create an experiment named \"estimator-test\". The script runs will be recorded under this experiment in Azure."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "bc70f780-c240-4779-96f3-bc5ef9a37d59"
}
},
"outputs": [],
"source": [
"from azureml.core import Experiment\n",
"\n",
"exp = Experiment(workspace=ws, name='estimator-test')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Create or Attach existing AmlCompute\n",
"You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for training your model. In this tutorial, you create `AmlCompute` as your training compute resource."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If we could not find the cluster with the given name, then we will create a new cluster here. We will create an `AmlCompute` cluster of `STANDARD_NC6` GPU VMs. This process is broken down into 3 steps:\n",
"1. create the configuration (this step is local and only takes a second)\n",
"2. create the cluster (this step will take about **20 seconds**)\n",
"3. provision the VMs to bring the cluster to the initial size (of 1 in this case). This step will take about **3-5 minutes** and is providing only sparse output in the process. Please make sure to wait until the call returns before moving to the next cell"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.core.compute import ComputeTarget, AmlCompute\n",
"from azureml.core.compute_target import ComputeTargetException\n",
"\n",
"# choose a name for your cluster\n",
"cluster_name = \"cpu-cluster\"\n",
"\n",
"try:\n",
" cpu_cluster = ComputeTarget(workspace=ws, name=cluster_name)\n",
" print('Found existing compute target')\n",
"except ComputeTargetException:\n",
" print('Creating a new compute target...')\n",
" compute_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_D2_V2', max_nodes=4)\n",
"\n",
" # create the cluster\n",
" cpu_cluster = ComputeTarget.create(ws, cluster_name, compute_config)\n",
"\n",
" # can poll for a minimum number of nodes and for a specific timeout. \n",
" # if no min node count is provided it uses the scale settings for the cluster\n",
" cpu_cluster.wait_for_completion(show_output=True, min_node_count=None, timeout_in_minutes=20)\n",
"\n",
"# use get_status() to get a detailed status for the current cluster. \n",
"print(cpu_cluster.get_status().serialize())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now that you have retrieved the compute target, let's see what the workspace's `compute_targets` property returns."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"compute_targets = ws.compute_targets\n",
"for name, ct in compute_targets.items():\n",
" print(name, ct.type, ct.provisioning_state)"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "2039d2d5-aca6-4f25-a12f-df9ae6529cae"
}
},
"source": [
"## Use a simple script\n",
"We have already created a simple \"hello world\" script. This is the script that we will submit through the estimator pattern. It prints a hello-world message, and if Azure ML SDK is installed, it will also logs an array of values ([Fibonacci numbers](https://en.wikipedia.org/wiki/Fibonacci_number)). The script takes as input the number of Fibonacci numbers in the sequence to log."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"with open('./dummy_train.py', 'r') as f:\n",
" print(f.read())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Create A Generic Estimator"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"First we import the Estimator class and also a widget to visualize a run."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.train.estimator import Estimator\n",
"from azureml.widgets import RunDetails"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The simplest estimator is to submit the current folder to the local computer. Estimator by default will attempt to use Docker-based execution. Let's turn that off for now. It then builds a conda environment locally, installs Azure ML SDK in it, and runs your script."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# use a conda environment, don't use Docker, on local computer\n",
"# Let's see how you can pass bool arguments in the script_params. Passing `'--my_bool_var': ''` will set my_bool_var as True and\n",
"# if you want it to be False, just do not pass it in the script_params.\n",
"script_params = {\n",
" '--numbers-in-sequence': 10,\n",
" '--my_bool_var': ''\n",
"}\n",
"est = Estimator(source_directory='.', script_params=script_params, compute_target='local', entry_script='dummy_train.py', use_docker=False)\n",
"run = exp.submit(est)\n",
"RunDetails(run).show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can also enable Docker and let estimator pick the default CPU image supplied by Azure ML for execution. You can target an AmlCompute cluster (or any other supported compute target types)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# use a conda environment on default Docker image in an AmlCompute cluster\n",
"script_params = {\n",
" '--numbers-in-sequence': 10\n",
"}\n",
"est = Estimator(source_directory='.', script_params=script_params, compute_target=cpu_cluster, entry_script='dummy_train.py', use_docker=True)\n",
"run = exp.submit(est)\n",
"RunDetails(run).show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can customize the conda environment by adding conda and/or pip packages."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# add a conda package\n",
"script_params = {\n",
" '--numbers-in-sequence': 10\n",
"}\n",
"est = Estimator(source_directory='.', \n",
" script_params=script_params, \n",
" compute_target='local', \n",
" entry_script='dummy_train.py', \n",
" use_docker=False, \n",
" conda_packages=['scikit-learn'])\n",
"run = exp.submit(est)\n",
"RunDetails(run).show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can also specify a custom Docker image for execution. In this case, you probably want to tell the system not to build a new conda environment for you. Instead, you can specify the path to an existing Python environment in the custom Docker image. If custom Docker image information is not specified, Azure ML uses the default Docker image to run your training. For more information about Docker containers used in Azure ML training, please see [Azure ML Containers repository](https://github.com/Azure/AzureML-Containers).\n",
"\n",
"**Note**: since the below example points to the preinstalled Python environment in the miniconda3 image maintained by continuum.io on Docker Hub where Azure ML SDK is not present, the logging metric code is not triggered. But a run history record is still recorded. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# use a custom Docker image\n",
"from azureml.core.container_registry import ContainerRegistry\n",
"\n",
"# this is an image available in Docker Hub\n",
"image_name = 'continuumio/miniconda3'\n",
"\n",
"# you can also point to an image in a private ACR\n",
"image_registry_details = ContainerRegistry()\n",
"image_registry_details.address = \"myregistry.azurecr.io\"\n",
"image_registry_details.username = \"username\"\n",
"image_registry_details.password = \"password\"\n",
"\n",
"# don't let the system build a new conda environment\n",
"user_managed_dependencies = True\n",
"\n",
"# submit to a local Docker container. if you don't have Docker engine running locally, you can set compute_target to cpu_cluster.\n",
"script_params = {\n",
" '--numbers-in-sequence': 10\n",
"}\n",
"est = Estimator(source_directory='.', \n",
" script_params=script_params, \n",
" compute_target='local', \n",
" entry_script='dummy_train.py',\n",
" custom_docker_image=image_name,\n",
" # uncomment below line to use your private ACR\n",
" #image_registry_details=image_registry_details,\n",
" user_managed=user_managed_dependencies\n",
" )\n",
"\n",
"run = exp.submit(est)\n",
"RunDetails(run).show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In addition to passing in a python file, you can also pass in a Jupyter notebook as the `entry_script`. [notebook_example.ipynb](notebook_example.ipynb) uses pm.record() to log key-value pairs which will appear in Azure Portal and shown in below widget.\n",
"\n",
"In order to run below, make sure `azureml-contrib-notebook` package is installed in current environment with `pip intall azureml-contrib-notebook`.\n",
"\n",
"This code snippet specifies the following parameters to the `Estimator` constructor. For more information on `Estimator`, please see [tutorial](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-train-ml-models) or [API doc](https://docs.microsoft.com/en-us/python/api/azureml-train-core/azureml.train.estimator.estimator?view=azure-ml-py).\n",
"\n",
"| Parameter | Description |\n",
"| ------------- | ------------- |\n",
"| source_directory | (str) Local directory that contains all of your code needed for the training job. This folder gets copied from your local machine to the remote compute |\n",
"| compute_target | ([AbstractComputeTarget](https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.compute_target.abstractcomputetarget?view=azure-ml-py) or str) Remote compute target that your training script will run on, in this case a previously created persistent compute cluster (cpu_cluster) |\n",
"| entry_script | (str) Filepath (relative to the source_directory) of the training script/notebook to be run on the remote compute. This file, and any additional files it depends on, should be located in this folder |\n",
"| script_params | (dict) A dictionary containing parameters to the `entry_script`. This is useful for passing datastore reference, for example, see [train-hyperparameter-tune-deploy-with-tensorflow.ipynb](../train-hyperparameter-tune-deploy-with-tensorflow/train-hyperparameter-tune-deploy-with-tensorflow.ipynb) |"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"est = Estimator(source_directory='.', compute_target=cpu_cluster, entry_script='notebook_example.ipynb', pip_packages=['nteract-scrapbook', 'azureml-contrib-notebook'])\n",
"run = exp.submit(est)\n",
"RunDetails(run).show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note: if you need to cancel a run, you can follow [these instructions](https://aka.ms/aml-docs-cancel-run)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Intelligent hyperparameter tuning\n",
"\n",
"The simple \"hello world\" script above lets the user fix the value of a parameter for the number of Fibonacci numbers in the sequence to log. Similarly, when training models, you can fix values of parameters of the training algorithm itself. E.g. the learning rate, the number of layers, the number of nodes in each layer in a neural network, etc. These adjustable parameters that govern the training process are referred to as the hyperparameters of the model. The goal of hyperparameter tuning is to search across various hyperparameter configurations and find the configuration that results in the best performance.\n",
"\n",
"\n",
"To demonstrate how Azure Machine Learning can help you automate the process of hyperarameter tuning, we will launch multiple runs with different values for numbers in the sequence. First let's define the parameter space using random sampling."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.train.hyperdrive import RandomParameterSampling, BanditPolicy, HyperDriveConfig, PrimaryMetricGoal\n",
"from azureml.train.hyperdrive import choice\n",
"\n",
"ps = RandomParameterSampling(\n",
" {\n",
" '--numbers-in-sequence': choice(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20)\n",
" }\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Next, we will create a new estimator without the above numbers-in-sequence parameter since that will be passed in later. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"est = Estimator(source_directory='.', script_params={}, compute_target=cpu_cluster, entry_script='dummy_train.py', use_docker=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Next, we will look at training metrics and early termination policies. When training a model, users are interested in logging and optimizing certain metrics of the model e.g. maximize the accuracy of the model, or minimize loss. This metric is logged by the training script for each run. In our simple script above, we are logging Fibonacci numbers in a sequence. But a training script could just as easily log other metrics like accuracy or loss, which can be used to evaluate the performance of a given training run.\n",
"\n",
"The intelligent hyperparameter tuning capability in Azure Machine Learning automatically terminates poorly performing runs using an early termination policy. Early termination reduces wastage of compute resources and instead uses these resources for exploring other hyperparameter configurations. In this example, we use the BanditPolicy. This basically states to check the job every 2 iterations. If the primary metric (defined later) falls outside of the top 10% range, Azure ML will terminate the training run. This saves us from continuing to explore hyperparameters that don't show promise of helping reach our target metric."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"policy = BanditPolicy(evaluation_interval=2, slack_factor=0.1)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we are ready to configure a run configuration object for hyperparameter tuning. We need to call out the primary metric that we want the experiment to optimize. The name of the primary metric needs to exactly match the name of the metric logged by the training script and we specify that we are looking to maximize this value. Next, we control the resource budget for the experiment by setting the maximum total number of training runs to 10. We also set the maximum number of training runs to run concurrently at 4, which is the same as the number of nodes in our computer cluster."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"hdc = HyperDriveConfig(estimator=est, \n",
" hyperparameter_sampling=ps, \n",
" policy=policy, \n",
" primary_metric_name='Fibonacci numbers', \n",
" primary_metric_goal=PrimaryMetricGoal.MAXIMIZE, \n",
" max_total_runs=10,\n",
" max_concurrent_runs=4)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Finally, let's launch the hyperparameter tuning job."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"hdr = exp.submit(config=hdc)\n",
"RunDetails(hdr).show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"When all the runs complete, we can find the run with the best performance."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"best_run = hdr.get_best_run_by_primary_metric()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can register the model from the best run and use it to deploy a web service that can be used for Inferencing. Details on how how you can do this can be found in the sample folders for the ohter types of estimators.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Next Steps\n",
"Now you can proceed to explore the other types of estimators, such as TensorFlow estimator, PyTorch estimator, etc. in the sample folder."
]
}
],
"metadata": {
"authors": [
{
"name": "ninhu"
}
],
"kernelspec": {
"display_name": "Python 3.6",
"language": "python",
"name": "python36"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.8"
},
"friendly_name": "Estimators in AML with hyperparameter tuning",
"exclude_from_index": false,
"index_order": 1,
"category": "starter",
"task": "Use the Estimator pattern in Azure Machine Learning SDK",
"datasets": [
"None"
],
"compute": [
"AML Compute"
],
"deployment": [
"None"
],
"framework": [
"None"
],
"tags": [
"None"
]
},
"nbformat": 4,
"nbformat_minor": 2
}

View File

@@ -1,6 +0,0 @@
name: how-to-use-estimator
dependencies:
- pip:
- azureml-sdk
- azureml-widgets
- azureml-contrib-notebook

View File

@@ -1,57 +0,0 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
"\n",
"Licensed under the MIT License."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import scrapbook as sb\n",
"sb.glue('Fibonacci numbers', [0, 1, 1, 2, 3, 5, 8, 13, 21, 34])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"authors": [
{
"name": "jingywa"
}
],
"kernelspec": {
"display_name": "Python 3.6",
"language": "python",
"name": "python36"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.8"
},
"msauthor": "jingywa"
},
"nbformat": 4,
"nbformat_minor": 2
}

View File

@@ -125,7 +125,7 @@
"\n", "\n",
"First lets check which VM families are available in your region. Azure is a regional service and some specialized SKUs (especially GPUs) are only available in certain regions. Since AmlCompute is created in the region of your workspace, we will use the supported_vms () function to see if the VM family we want to use ('STANDARD_D2_V2') is supported.\n", "First lets check which VM families are available in your region. Azure is a regional service and some specialized SKUs (especially GPUs) are only available in certain regions. Since AmlCompute is created in the region of your workspace, we will use the supported_vms () function to see if the VM family we want to use ('STANDARD_D2_V2') is supported.\n",
"\n", "\n",
"You can also pass a different region to check availability and then re-create your workspace in that region through the [configuration notebook](../../../configuration.ipynb)" "You can also pass a different region to check availability and then re-create your workspace in that region through the [configuration notebook](../../../configuration.ipynb)."
] ]
}, },
{ {
@@ -241,15 +241,11 @@
"outputs": [], "outputs": [],
"source": [ "source": [
"from azureml.core import ScriptRunConfig\n", "from azureml.core import ScriptRunConfig\n",
"from azureml.core.runconfig import DEFAULT_CPU_IMAGE\n",
"\n", "\n",
"src = ScriptRunConfig(source_directory=project_folder, script='train.py')\n", "src = ScriptRunConfig(source_directory=project_folder, \n",
"\n", " script='train.py', \n",
"# Set compute target to the one created in previous step\n", " compute_target=cpu_cluster, \n",
"src.run_config.target = cpu_cluster.name\n", " environment=myenv)\n",
"\n",
"# Set environment\n",
"src.run_config.environment = myenv\n",
" \n", " \n",
"run = experiment.submit(config=src)\n", "run = experiment.submit(config=src)\n",
"run" "run"
@@ -355,7 +351,7 @@
"outputs": [], "outputs": [],
"source": [ "source": [
"# Set compute target to the one created in previous step\n", "# Set compute target to the one created in previous step\n",
"src.run_config.target = cpu_cluster.name\n", "src.run_config.target = cpu_cluster\n",
" \n", " \n",
"run = experiment.submit(config=src)\n", "run = experiment.submit(config=src)\n",
"run" "run"
@@ -397,7 +393,7 @@
"outputs": [], "outputs": [],
"source": [ "source": [
"#get_status () gets the latest status of the AmlCompute target\n", "#get_status () gets the latest status of the AmlCompute target\n",
"cpu_cluster.get_status().serialize()\n" "cpu_cluster.get_status().serialize()"
] ]
}, },
{ {
@@ -407,7 +403,7 @@
"outputs": [], "outputs": [],
"source": [ "source": [
"#list_nodes () gets the list of nodes on the cluster with status, IP and associated run\n", "#list_nodes () gets the list of nodes on the cluster with status, IP and associated run\n",
"cpu_cluster.list_nodes()\n" "cpu_cluster.list_nodes()"
] ]
}, },
{ {
@@ -481,7 +477,7 @@
"name": "python", "name": "python",
"nbconvert_exporter": "python", "nbconvert_exporter": "python",
"pygments_lexer": "ipython3", "pygments_lexer": "ipython3",
"version": "3.6.6" "version": "3.7.7"
}, },
"tags": [ "tags": [
"None" "None"

View File

@@ -168,8 +168,8 @@
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {
"name": "user_managed_env", "msdoc": "how-to-track-experiments.md",
"msdoc": "how-to-track-experiments.md" "name": "user_managed_env"
}, },
"outputs": [], "outputs": [],
"source": [ "source": [
@@ -196,23 +196,22 @@
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {
"name": "src", "msdoc": "how-to-track-experiments.md",
"msdoc": "how-to-track-experiments.md" "name": "src"
}, },
"outputs": [], "outputs": [],
"source": [ "source": [
"from azureml.core import ScriptRunConfig\n", "from azureml.core import ScriptRunConfig\n",
"\n", "\n",
"src = ScriptRunConfig(source_directory='./', script='train.py')\n", "src = ScriptRunConfig(source_directory='./', script='train.py', environment=user_managed_env)"
"src.run_config.environment = user_managed_env"
] ]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": { "metadata": {
"name": "run", "msdoc": "how-to-track-experiments.md",
"msdoc": "how-to-track-experiments.md" "name": "run"
}, },
"outputs": [], "outputs": [],
"source": [ "source": [
@@ -491,20 +490,24 @@
"#### 6.C.d Use a custom Docker image\n", "#### 6.C.d Use a custom Docker image\n",
"\n", "\n",
"You can also specify a custom Docker image, if you don't want to use the default image provided by Azure ML.\n", "You can also specify a custom Docker image, if you don't want to use the default image provided by Azure ML.\n",
"```python\n",
"custom_docker_env = Environment(\"custom-docker-env\")\n",
"custom_docker_env.docker.enabled = True\n",
"```\n",
"\n", "\n",
"You can either pull an image directly from Anaconda:\n", "You can either pull an image directly from Anaconda:\n",
"```python\n", "```python\n",
"# Use an image available in Docker Hub without authentication\n", "# Use an image available in Docker Hub without authentication\n",
"run_config_docker.environment.docker.base_image = \"continuumio/miniconda3\"\n", "custom_docker_env.docker.base_image = \"continuumio/miniconda3\"\n",
"```\n", "```\n",
"\n", "\n",
"Or one of the images you may already have created:\n", "Or one of the images you may already have created:\n",
"```python\n", "```python\n",
"# or, use an image available in your private Azure Container Registry\n", "# or, use an image available in your private Azure Container Registry\n",
"run_config_docker.environment.docker.base_image = \"mycustomimage:1.0\"\n", "custom_docker_env.docker.base_image = \"mycustomimage:1.0\"\n",
"run_config_docker.environment.docker.base_image_registry.address = \"myregistry.azurecr.io\"\n", "custom_docker_env.docker.base_image_registry.address = \"myregistry.azurecr.io\"\n",
"run_config_docker.environment.docker.base_image_registry.username = \"username\"\n", "custom_docker_env.docker.base_image_registry.username = \"username\"\n",
"run_config_docker.environment.docker.base_image_registry.password = \"password\"\n", "custom_docker_env.docker.base_image_registry.password = \"password\"\n",
"```\n", "```\n",
"\n", "\n",
"##### Where to find my Docker image name and registry credentials\n", "##### Where to find my Docker image name and registry credentials\n",
@@ -527,9 +530,14 @@
"\n", "\n",
"When you are using your custom Docker image, you might already have your Python environment properly set up. In that case, you can skip specifying conda dependencies, and just use the `user_managed_dependencies` option instead:\n", "When you are using your custom Docker image, you might already have your Python environment properly set up. In that case, you can skip specifying conda dependencies, and just use the `user_managed_dependencies` option instead:\n",
"```python\n", "```python\n",
"run_config_docker.environment.python.user_managed_dependencies = True\n", "custom_docker_env.python.user_managed_dependencies = True\n",
"# path to the Python environment in the custom Docker image\n", "# path to the Python environment in the custom Docker image\n",
"run_config.environment.python.interpreter_path = '/opt/conda/bin/python'\n", "custom_docker_env.python.interpreter_path = '/opt/conda/bin/python'\n",
"```\n",
"\n",
"Once you are done defining your environment, set that environment on your run configuration:\n",
"```python\n",
"src.run_config.environment = custom_docker_env\n",
"```" "```"
] ]
}, },
@@ -691,7 +699,7 @@
"name": "python", "name": "python",
"nbconvert_exporter": "python", "nbconvert_exporter": "python",
"pygments_lexer": "ipython3", "pygments_lexer": "ipython3",
"version": "3.6.5" "version": "3.7.7"
}, },
"tags": [ "tags": [
"None" "None"

View File

@@ -227,7 +227,7 @@
"source": [ "source": [
"## Create and Attach a DSVM as a compute target\n", "## Create and Attach a DSVM as a compute target\n",
"\n", "\n",
"**Note**: To streamline the compute that Azure Machine Learning creates, we are making updates to support creating only single to multi-node `AmlCompute`. The DSVM can be created using the below single line command and then attached(like any VM) using the sample code below. Also note, that we only support Linux VMs for remote execution from AML and the commands below will spin a Linux VM only.\n", "The DSVM can be created using the below single line command and then attached(like any VM) using the sample code below. Also note, that we only support Linux VMs for remote execution from AML and the commands below will spin a Linux VM only.\n",
"\n", "\n",
"```shell\n", "```shell\n",
"# create a DSVM in your resource group\n", "# create a DSVM in your resource group\n",
@@ -325,12 +325,9 @@
"src = ScriptRunConfig(source_directory=script_folder, \n", "src = ScriptRunConfig(source_directory=script_folder, \n",
" script='train.py', \n", " script='train.py', \n",
" # pass the dataset as a parameter to the training script\n", " # pass the dataset as a parameter to the training script\n",
" arguments=script_arguments\n", " arguments=script_arguments,\n",
" ) \n", " compute_target = attached_dsvm_compute,\n",
"\n", " environment = conda_env) "
"src.run_config.framework = \"python\"\n",
"src.run_config.environment = conda_env\n",
"src.run_config.target = attached_dsvm_compute.name"
] ]
}, },
{ {
@@ -429,8 +426,10 @@
"with open(os.path.join(script_folder, './train2.py'), 'r') as training_script:\n", "with open(os.path.join(script_folder, './train2.py'), 'r') as training_script:\n",
" print(training_script.read())\n", " print(training_script.read())\n",
"\n", "\n",
"src.script = \"train2.py\"\n", "src = ScriptRunConfig(source_directory=script_folder, \n",
"src.arguments = None" " script='train2.py', \n",
" compute_target = attached_dsvm_compute,\n",
" environment = conda_env) "
] ]
}, },
{ {
@@ -501,8 +500,11 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"src.script = \"train.py\"\n", "src = ScriptRunConfig(source_directory=script_folder, \n",
"src.arguments = script_arguments\n", " script='train.py', \n",
" arguments=script_arguments,\n",
" compute_target = attached_dsvm_compute,\n",
" environment = conda_env) \n",
"\n", "\n",
"run = exp.submit(config=src)\n", "run = exp.submit(config=src)\n",
"\n", "\n",
@@ -650,7 +652,7 @@
"name": "python", "name": "python",
"nbconvert_exporter": "python", "nbconvert_exporter": "python",
"pygments_lexer": "ipython3", "pygments_lexer": "ipython3",
"version": "3.7.4" "version": "3.7.7"
}, },
"tags": [ "tags": [
"None" "None"

View File

@@ -237,10 +237,12 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"runconfig = ScriptRunConfig(source_directory=\".\", script=\"example.py\")\n", "src = ScriptRunConfig(source_directory=\".\",\n",
"runconfig.run_config.target = \"local\"\n", " script=\"example.py\",\n",
"runconfig.run_config.environment = myenv\n", " compute_target=\"local\",\n",
"run = myexp.submit(config=runconfig)\n", " environment=myenv)\n",
"\n",
"run = myexp.submit(config=src)\n",
"\n", "\n",
"run.wait_for_completion(show_output=True)" "run.wait_for_completion(show_output=True)"
] ]
@@ -249,7 +251,7 @@
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {}, "metadata": {},
"source": [ "source": [
"To audit the environment used by for a run, you can use ```get_environement```." "To audit the environment used by for a run, you can use ```get_environment```."
] ]
}, },
{ {
@@ -332,29 +334,6 @@
"```\n" "```\n"
] ]
}, },
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Estimators and environments\n",
"\n",
"[Estimators](https://docs.microsoft.com/azure/machine-learning/service/how-to-train-ml-models) are backed by environments that define the base images, Python packages and other settings for the training environment. \n",
"\n",
"For example, to see the environment behind PyTorch Estimator, you can create a dummy instance of the Estimator, and look at the ```run_config.environment``` property."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.train.dnn import PyTorch\n",
"\n",
"pt = PyTorch(source_directory=\".\", compute_target=\"local\")\n",
"pt.run_config.environment"
]
},
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {}, "metadata": {},
@@ -447,9 +426,9 @@
"\n", "\n",
"Learn more about remote runs on different compute targets:\n", "Learn more about remote runs on different compute targets:\n",
"\n", "\n",
"* [Train on ML Compute](../../train-on-amlcompute)\n", "* [Train on ML Compute](../../training/train-on-amlcompute/train-on-amlcompute.ipynb)\n",
"\n", "\n",
"* [Train on remote VM](../../train-on-remote-vm)\n", "* [Train on remote VM](../../training/train-on-remote-vm/train-on-remote-vm.ipynb)\n",
"\n", "\n",
"Learn more about registering and deploying a model:\n", "Learn more about registering and deploying a model:\n",
"\n", "\n",
@@ -501,7 +480,7 @@
"name": "python", "name": "python",
"nbconvert_exporter": "python", "nbconvert_exporter": "python",
"pygments_lexer": "ipython3", "pygments_lexer": "ipython3",
"version": "3.6.5" "version": "3.7.7"
}, },
"tags": [ "tags": [
"None" "None"

View File

@@ -1,6 +1,6 @@
# Azure Machine Learning datasets (preview) # Azure Machine Learning datasets
Azure Machine Learning datasets (preview) let data scientists and machine learning engineers apply data for ML with confidence. By creating a dataset, you create a reference to the data source location, along with a copy of its metadata. The data remains in its existing location, so no extra storage cost is incurred. Azure Machine Learning datasets let data scientists and machine learning engineers apply data for ML with confidence. By creating a dataset, you create a reference to the data source location, along with a copy of its metadata. The data remains in its existing location, so no extra storage cost is incurred.
With Azure Machine Learning datasets, you can: With Azure Machine Learning datasets, you can:

View File

@@ -10,7 +10,6 @@ Machine Learning notebook samples and encourage efficient retrieval of topics an
|Title| Task | Dataset | Training Compute | Deployment Target | ML Framework | Tags | |Title| Task | Dataset | Training Compute | Deployment Target | ML Framework | Tags |
|:----|:-----|:-------:|:----------------:|:-----------------:|:------------:|:------------:| |:----|:-----|:-------:|:----------------:|:-----------------:|:------------:|:------------:|
| [Using Azure ML environments](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/training/using-environments/using-environments.ipynb) | Creating and registering environments | None | Local | None | None | None | | [Using Azure ML environments](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/training/using-environments/using-environments.ipynb) | Creating and registering environments | None | Local | None | None | None |
| [Estimators in AML with hyperparameter tuning](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/training-with-deep-learning/how-to-use-estimator/how-to-use-estimator.ipynb) | Use the Estimator pattern in Azure Machine Learning SDK | None | AML Compute | None | None | None |
## Tutorials ## Tutorials
@@ -45,8 +44,10 @@ Machine Learning notebook samples and encourage efficient retrieval of topics an
| :star:[How to use AutoMLStep with AML Pipelines](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-with-automated-machine-learning-step.ipynb) | Demonstrates the use of AutoMLStep | Custom | AML Compute | None | Automated Machine Learning | None | | :star:[How to use AutoMLStep with AML Pipelines](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-with-automated-machine-learning-step.ipynb) | Demonstrates the use of AutoMLStep | Custom | AML Compute | None | Automated Machine Learning | None |
| :star:[Azure Machine Learning Pipelines with Data Dependency](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-with-data-dependency-steps.ipynb) | Demonstrates how to construct a Pipeline with data dependency between steps | Custom | AML Compute | None | Azure ML | None | | :star:[Azure Machine Learning Pipelines with Data Dependency](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-with-data-dependency-steps.ipynb) | Demonstrates how to construct a Pipeline with data dependency between steps | Custom | AML Compute | None | Azure ML | None |
| [How to use run a notebook as a step in AML Pipelines](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-with-notebook-runner-step.ipynb) | Demonstrates the use of NotebookRunnerStep | Custom | AML Compute | None | Azure ML | None | | [How to use run a notebook as a step in AML Pipelines](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-with-notebook-runner-step.ipynb) | Demonstrates the use of NotebookRunnerStep | Custom | AML Compute | None | Azure ML | None |
| [Use MLflow with Azure Machine Learning to Train and Deploy Keras Image Classifier](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/track-and-monitor-experiments/using-mlflow/train-and-deploy-keras-auto-logging/train-and-deploy-keras-auto-logging.ipynb) | Use MLflow with Azure Machine Learning to Train and Deploy Keras Image Classifier, leveraging MLflow auto logging | MNIST | Local, AML Compute | Azure Container Instance | Keras | mlflow, keras | | [Use MLflow with Azure Machine Learning to Train and Deploy Keras Image Classifier](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/ml-frameworks/using-mlflow/train-and-deploy-keras-auto-logging/train-and-deploy-keras-auto-logging.ipynb) | Use MLflow with Azure Machine Learning to Train and Deploy Keras Image Classifier, leveraging MLflow auto logging | MNIST | Local, AML Compute | Azure Container Instance | Keras | mlflow, keras |
| [Use MLflow with Azure Machine Learning to Train and Deploy PyTorch Image Classifier](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/track-and-monitor-experiments/using-mlflow/train-and-deploy-pytorch/train-and-deploy-pytorch.ipynb) | Use MLflow with Azure Machine Learning to train and deploy PyTorch image classifier model | MNIST | Local, AML Compute | Azure Container Instance | PyTorch | mlflow, pytorch | | [Use MLflow with Azure Machine Learning to Train and Deploy PyTorch Image Classifier](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/ml-frameworks/using-mlflow/train-and-deploy-pytorch/train-and-deploy-pytorch.ipynb) | Use MLflow with Azure Machine Learning to train and deploy PyTorch image classifier model | MNIST | Local, AML Compute | Azure Container Instance | PyTorch | mlflow, pytorch |
| [Use MLflow projects with Azure Machine Learning to train a model with local compute](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/track-and-monitor-experiments/using-mlflow/train-projects-local/train-projects-local.ipynb) | Use MLflow projects with Azure Machine Learning to train a model using local compute | | Local | | ScikitLearn | mlflow, scikit |
| [Use MLflow projects with Azure Machine Learning to train a model](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/track-and-monitor-experiments/using-mlflow/train-projects-remote/train-projects-remote.ipynb) | Use MLflow projects with Azure Machine Learning to train a model using azureml compute | | AML Compute | | Scikit | mlflow, scikit |
| [How to use ScriptRun with data input and output](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/work-with-data/datasets-tutorial/scriptrun-with-data-input-output/how-to-use-scriptrun.ipynb) | Demonstrates the use of Scriptrun with datasets | Custom | AML Compute | None | Azure ML | Dataset, ScriptRun | | [How to use ScriptRun with data input and output](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/work-with-data/datasets-tutorial/scriptrun-with-data-input-output/how-to-use-scriptrun.ipynb) | Demonstrates the use of Scriptrun with datasets | Custom | AML Compute | None | Azure ML | Dataset, ScriptRun |
## Training ## Training
@@ -133,8 +134,6 @@ Machine Learning notebook samples and encourage efficient retrieval of topics an
| [particle](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/reinforcement-learning/multiagent-particle-envs/particle.ipynb) | | | | | | | | [particle](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/reinforcement-learning/multiagent-particle-envs/particle.ipynb) | | | | | | |
| [devenv_setup](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/reinforcement-learning/setup/devenv_setup.ipynb) | | | | | | | | [devenv_setup](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/reinforcement-learning/setup/devenv_setup.ipynb) | | | | | | |
| [Logging APIs](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/track-and-monitor-experiments/logging-api/logging-api.ipynb) | Logging APIs and analyzing results | None | None | None | None | None | | [Logging APIs](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/track-and-monitor-experiments/logging-api/logging-api.ipynb) | Logging APIs and analyzing results | None | None | None | None | None |
| [distributed-cntk-with-custom-docker](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/training-with-deep-learning/distributed-cntk-with-custom-docker/distributed-cntk-with-custom-docker.ipynb) | | | | | | |
| [notebook_example](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/training-with-deep-learning/how-to-use-estimator/notebook_example.ipynb) | | | | | | |
| [configuration](https://github.com/Azure/MachineLearningNotebooks/blob/master//setup-environment/configuration.ipynb) | | | | | | | | [configuration](https://github.com/Azure/MachineLearningNotebooks/blob/master//setup-environment/configuration.ipynb) | | | | | | |
| [tutorial-1st-experiment-sdk-train](https://github.com/Azure/MachineLearningNotebooks/blob/master//tutorials/create-first-ml-experiment/tutorial-1st-experiment-sdk-train.ipynb) | | | | | | | | [tutorial-1st-experiment-sdk-train](https://github.com/Azure/MachineLearningNotebooks/blob/master//tutorials/create-first-ml-experiment/tutorial-1st-experiment-sdk-train.ipynb) | | | | | | |
| [img-classification-part1-training](https://github.com/Azure/MachineLearningNotebooks/blob/master//tutorials/image-classification-mnist-data/img-classification-part1-training.ipynb) | | | | | | | | [img-classification-part1-training](https://github.com/Azure/MachineLearningNotebooks/blob/master//tutorials/image-classification-mnist-data/img-classification-part1-training.ipynb) | | | | | | |

View File

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

View File

@@ -57,7 +57,12 @@
"source": [ "source": [
"Import the `Workspace` class, and load your subscription information from the file `config.json` using the function `from_config().` This looks for the JSON file in the current directory by default, but you can also specify a path parameter to point to the file using `from_config(path=\"your/file/path\")`. If you are running this notebook in a cloud notebook server in your workspace, the file is automatically in the root directory.\n", "Import the `Workspace` class, and load your subscription information from the file `config.json` using the function `from_config().` This looks for the JSON file in the current directory by default, but you can also specify a path parameter to point to the file using `from_config(path=\"your/file/path\")`. If you are running this notebook in a cloud notebook server in your workspace, the file is automatically in the root directory.\n",
"\n", "\n",
"If the following code asks for additional authentication, simply paste the link in a browser and enter the authentication token." "If the following code asks for additional authentication, simply paste the link in a browser and enter the authentication token. In addition, if you have more than one tenant linked to your user, you will need to add the following lines:\n",
"```\n",
"from azureml.core.authentication import InteractiveLoginAuthentication\n",
"interactive_auth = InteractiveLoginAuthentication(tenant_id=\"your-tenant-id\")\n",
"Additional details on authentication can be found here: https://aka.ms/aml-notebook-auth \n",
"```\n"
] ]
}, },
{ {