diff --git a/configuration.ipynb b/configuration.ipynb index 7a5ecc6ce..37c998142 100644 --- a/configuration.ipynb +++ b/configuration.ipynb @@ -103,7 +103,7 @@ "source": [ "import azureml.core\n", "\n", - "print(\"This notebook was created using version 1.1.0rc0 of the Azure ML SDK\")\n", + "print(\"This notebook was created using version 1.1.0rc1 of the Azure ML SDK\")\n", "print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")" ] }, diff --git a/how-to-use-azureml/automated-machine-learning/automl_env.yml b/how-to-use-azureml/automated-machine-learning/automl_env.yml index 4b77517fa..827999ee5 100644 --- a/how-to-use-azureml/automated-machine-learning/automl_env.yml +++ b/how-to-use-azureml/automated-machine-learning/automl_env.yml @@ -23,7 +23,6 @@ dependencies: - azureml-train-automl - azureml-train - azureml-widgets - - azureml-explain-model - azureml-pipeline - azureml-contrib-interpret - pytorch-transformers==1.0.0 @@ -34,4 +33,4 @@ dependencies: channels: - conda-forge -- pytorch +- pytorch \ No newline at end of file diff --git a/how-to-use-azureml/automated-machine-learning/automl_env_mac.yml b/how-to-use-azureml/automated-machine-learning/automl_env_mac.yml index 3a2226124..9cdae0b38 100644 --- a/how-to-use-azureml/automated-machine-learning/automl_env_mac.yml +++ b/how-to-use-azureml/automated-machine-learning/automl_env_mac.yml @@ -24,7 +24,6 @@ dependencies: - azureml-train-automl - azureml-train - azureml-widgets - - azureml-explain-model - azureml-pipeline - azureml-contrib-interpret - pytorch-transformers==1.0.0 @@ -35,4 +34,4 @@ dependencies: channels: - conda-forge -- pytorch +- pytorch \ No newline at end of file diff --git a/how-to-use-azureml/automated-machine-learning/classification-credit-card-fraud/auto-ml-classification-credit-card-fraud.ipynb b/how-to-use-azureml/automated-machine-learning/classification-credit-card-fraud/auto-ml-classification-credit-card-fraud.ipynb index e8daabfd9..46eade829 100644 --- a/how-to-use-azureml/automated-machine-learning/classification-credit-card-fraud/auto-ml-classification-credit-card-fraud.ipynb +++ b/how-to-use-azureml/automated-machine-learning/classification-credit-card-fraud/auto-ml-classification-credit-card-fraud.ipynb @@ -212,7 +212,7 @@ " \"primary_metric\": 'average_precision_score_weighted',\n", " \"enable_early_stopping\": True,\n", " \"max_concurrent_iterations\": 2, # This is a limit for testing purpose, please increase it as per cluster size\n", - " \"experiment_timeout_hours\": 0.2, # This is a time limit for testing purposes, remove it for real use cases, this will drastically limit ablity to find the best model possible\n", + " \"experiment_timeout_hours\": 0.25, # This is a time limit for testing purposes, remove it for real use cases, this will drastically limit ablity to find the best model possible\n", " \"verbosity\": logging.INFO,\n", "}\n", "\n", diff --git a/how-to-use-azureml/automated-machine-learning/classification-text-dnn/auto-ml-classification-text-dnn.ipynb b/how-to-use-azureml/automated-machine-learning/classification-text-dnn/auto-ml-classification-text-dnn.ipynb index 418f08ed6..34e6f1e0d 100644 --- a/how-to-use-azureml/automated-machine-learning/classification-text-dnn/auto-ml-classification-text-dnn.ipynb +++ b/how-to-use-azureml/automated-machine-learning/classification-text-dnn/auto-ml-classification-text-dnn.ipynb @@ -121,9 +121,9 @@ "metadata": {}, "source": [ "## Set up a compute cluster\n", - "This section uses a user-provided compute cluster (named \"cpu-cluster\" in this example). If a cluster with this name does not exist in the user's workspace, the below code will create a new cluster. You can choose the parameters of the cluster as mentioned in the comments.\n", + "This section uses a user-provided compute cluster (named \"dnntext-cluster\" in this example). If a cluster with this name does not exist in the user's workspace, the below code will create a new cluster. You can choose the parameters of the cluster as mentioned in the comments.\n", "\n", - "Whether you provide/select a CPU or GPU cluster, AutoML will choose the appropriate DNN for that setup - BiLSTM or BERT text featurizer will be included in the candidate featurizers on CPU and GPU respectively." + "Whether you provide/select a CPU or GPU cluster, AutoML will choose the appropriate DNN for that setup - BiLSTM or BERT text featurizer will be included in the candidate featurizers on CPU and GPU respectively. If your goal is to obtain the most accurate model, we recommend you use GPU clusters since BERT featurizers usually outperform BiLSTM featurizers." ] }, { @@ -133,7 +133,7 @@ "outputs": [], "source": [ "# Choose a name for your cluster.\n", - "amlcompute_cluster_name = \"cpu-dnntext\"\n", + "amlcompute_cluster_name = \"dnntext-cluster\"\n", "\n", "found = False\n", "# Check if this compute target already exists in the workspace.\n", @@ -145,11 +145,11 @@ "\n", "if not found:\n", " print('Creating a new compute target...')\n", - " provisioning_config = AmlCompute.provisioning_configuration(vm_size = \"STANDARD_D2_V2\", # CPU for BiLSTM\n", - " # To use BERT, select a GPU such as \"STANDARD_NC6\" \n", + " provisioning_config = AmlCompute.provisioning_configuration(vm_size = \"STANDARD_NC6\", # CPU for BiLSTM, such as \"STANDARD_D2_V2\" \n", + " # To use BERT (this is recommended for best performance), select a GPU such as \"STANDARD_NC6\" \n", " # or similar GPU option\n", " # available in your workspace\n", - " max_nodes = 6)\n", + " max_nodes = 1)\n", "\n", " # Create the cluster\n", " compute_target = ComputeTarget.create(ws, amlcompute_cluster_name, provisioning_config)\n", @@ -218,7 +218,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Featch data and upload to datastore for use in training" + "#### Fetch data and upload to datastore for use in training" ] }, { @@ -347,7 +347,26 @@ "metadata": {}, "outputs": [], "source": [ - "#best_run, fitted_model = automl_run.get_output()" + "best_run, fitted_model = automl_run.get_output()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You can now see what text transformations are used to convert text data to features for this dataset, including deep learning transformations based on BiLSTM or Transformer (BERT is one implementation of a Transformer) models." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "text_transformations_used = []\n", + "for column_group in fitted_model.named_steps['datatransformer'].get_featurization_summary():\n", + " text_transformations_used.extend(column_group['Transformations'])\n", + "text_transformations_used" ] }, { diff --git a/how-to-use-azureml/automated-machine-learning/classification-text-dnn/auto-ml-classification-text-dnn.yml b/how-to-use-azureml/automated-machine-learning/classification-text-dnn/auto-ml-classification-text-dnn.yml index 5ea6dc1c7..122a88495 100644 --- a/how-to-use-azureml/automated-machine-learning/classification-text-dnn/auto-ml-classification-text-dnn.yml +++ b/how-to-use-azureml/automated-machine-learning/classification-text-dnn/auto-ml-classification-text-dnn.yml @@ -6,3 +6,8 @@ dependencies: - azureml-widgets - matplotlib - azurmel-train + - https://download.pytorch.org/whl/cpu/torch-1.1.0-cp35-cp35m-win_amd64.whl + - sentencepiece==0.1.82 + - pytorch-transformers==1.0 + - spacy==2.1.8 + - https://aka.ms/automl-resources/packages/en_core_web_sm-2.1.0.tar.gz diff --git a/how-to-use-azureml/automated-machine-learning/continuous-retraining/auto-ml-continuous-retraining.ipynb b/how-to-use-azureml/automated-machine-learning/continuous-retraining/auto-ml-continuous-retraining.ipynb index 37065745c..1d66116e7 100644 --- a/how-to-use-azureml/automated-machine-learning/continuous-retraining/auto-ml-continuous-retraining.ipynb +++ b/how-to-use-azureml/automated-machine-learning/continuous-retraining/auto-ml-continuous-retraining.ipynb @@ -197,7 +197,7 @@ "conda_run_config.environment.docker.base_image = azureml.core.runconfig.DEFAULT_CPU_IMAGE\n", "\n", "cd = CondaDependencies.create(pip_packages=['azureml-sdk[automl]', 'applicationinsights', 'azureml-opendatasets'], \n", - " conda_packages=['numpy', 'py-xgboost'], \n", + " conda_packages=['numpy==1.16.2'], \n", " pin_sdk_version=False)\n", "#cd.add_pip_package('azureml-explain-model')\n", "conda_run_config.environment.python.conda_dependencies = cd\n", @@ -277,7 +277,7 @@ "metadata": {}, "outputs": [], "source": [ - "data_pipeline_run.wait_for_completion()" + "data_pipeline_run.wait_for_completion(show_output=False)" ] }, { @@ -347,7 +347,7 @@ "\n", "automl_settings = {\n", " \"iteration_timeout_minutes\": 10,\n", - " \"experiment_timeout_hours\": 0.2,\n", + " \"experiment_timeout_hours\": 0.25,\n", " \"n_cross_validations\": 3,\n", " \"primary_metric\": 'r2_score',\n", " \"max_concurrent_iterations\": 3,\n", diff --git a/how-to-use-azureml/automated-machine-learning/local-run-classification-credit-card-fraud/auto-ml-classification-credit-card-fraud-local.ipynb b/how-to-use-azureml/automated-machine-learning/local-run-classification-credit-card-fraud/auto-ml-classification-credit-card-fraud-local.ipynb index 8d1a1c0ab..16eebfae5 100644 --- a/how-to-use-azureml/automated-machine-learning/local-run-classification-credit-card-fraud/auto-ml-classification-credit-card-fraud-local.ipynb +++ b/how-to-use-azureml/automated-machine-learning/local-run-classification-credit-card-fraud/auto-ml-classification-credit-card-fraud-local.ipynb @@ -155,7 +155,7 @@ "automl_settings = {\n", " \"n_cross_validations\": 3,\n", " \"primary_metric\": 'average_precision_score_weighted',\n", - " \"experiment_timeout_hours\": 0.2, # This is a time limit for testing purposes, remove it for real use cases, this will drastically limit ability to find the best model possible\n", + " \"experiment_timeout_hours\": 0.25, # This is a time limit for testing purposes, remove it for real use cases, this will drastically limit ability to find the best model possible\n", " \"verbosity\": logging.INFO,\n", " \"enable_stack_ensemble\": False\n", "}\n", diff --git a/how-to-use-azureml/automated-machine-learning/regression-hardware-performance-explanation-and-featurization/auto-ml-regression-hardware-performance-explanation-and-featurization.ipynb b/how-to-use-azureml/automated-machine-learning/regression-hardware-performance-explanation-and-featurization/auto-ml-regression-hardware-performance-explanation-and-featurization.ipynb index ff93989c2..124d0ab11 100644 --- a/how-to-use-azureml/automated-machine-learning/regression-hardware-performance-explanation-and-featurization/auto-ml-regression-hardware-performance-explanation-and-featurization.ipynb +++ b/how-to-use-azureml/automated-machine-learning/regression-hardware-performance-explanation-and-featurization/auto-ml-regression-hardware-performance-explanation-and-featurization.ipynb @@ -262,7 +262,7 @@ "source": [ "automl_settings = {\n", " \"enable_early_stopping\": True, \n", - " \"experiment_timeout_hours\" : 0.2,\n", + " \"experiment_timeout_hours\" : 0.25,\n", " \"max_concurrent_iterations\": 4,\n", " \"max_cores_per_iteration\": -1,\n", " \"n_cross_validations\": 5,\n", diff --git a/how-to-use-azureml/azureml-sdk-for-r/README.md b/how-to-use-azureml/azureml-sdk-for-r/README.md new file mode 100644 index 000000000..bd2784b97 --- /dev/null +++ b/how-to-use-azureml/azureml-sdk-for-r/README.md @@ -0,0 +1,36 @@ +## 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. diff --git a/how-to-use-azureml/azureml-sdk-for-r/samples/README.md b/how-to-use-azureml/azureml-sdk-for-r/samples/README.md new file mode 100644 index 000000000..070fe71d6 --- /dev/null +++ b/how-to-use-azureml/azureml-sdk-for-r/samples/README.md @@ -0,0 +1,11 @@ +## 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). diff --git a/how-to-use-azureml/azureml-sdk-for-r/samples/deployment/deploy-to-aci/deploy-to-aci.R b/how-to-use-azureml/azureml-sdk-for-r/samples/deployment/deploy-to-aci/deploy-to-aci.R new file mode 100644 index 000000000..1c286023f --- /dev/null +++ b/how-to-use-azureml/azureml-sdk-for-r/samples/deployment/deploy-to-aci/deploy-to-aci.R @@ -0,0 +1,59 @@ +# 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) diff --git a/how-to-use-azureml/azureml-sdk-for-r/samples/deployment/deploy-to-aci/project_files/model.rds b/how-to-use-azureml/azureml-sdk-for-r/samples/deployment/deploy-to-aci/project_files/model.rds new file mode 100644 index 000000000..9e46c2fea Binary files /dev/null and b/how-to-use-azureml/azureml-sdk-for-r/samples/deployment/deploy-to-aci/project_files/model.rds differ diff --git a/how-to-use-azureml/azureml-sdk-for-r/samples/deployment/deploy-to-aci/project_files/score.R b/how-to-use-azureml/azureml-sdk-for-r/samples/deployment/deploy-to-aci/project_files/score.R new file mode 100644 index 000000000..be132918b --- /dev/null +++ b/how-to-use-azureml/azureml-sdk-for-r/samples/deployment/deploy-to-aci/project_files/score.R @@ -0,0 +1,17 @@ +# 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) + } +} \ No newline at end of file diff --git a/how-to-use-azureml/azureml-sdk-for-r/samples/deployment/deploy-to-local/deploy-to-local.R b/how-to-use-azureml/azureml-sdk-for-r/samples/deployment/deploy-to-local/deploy-to-local.R new file mode 100644 index 000000000..dad3ba692 --- /dev/null +++ b/how-to-use-azureml/azureml-sdk-for-r/samples/deployment/deploy-to-local/deploy-to-local.R @@ -0,0 +1,112 @@ +# 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: 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: + +#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) diff --git a/how-to-use-azureml/azureml-sdk-for-r/samples/deployment/deploy-to-local/project_files/model.rds b/how-to-use-azureml/azureml-sdk-for-r/samples/deployment/deploy-to-local/project_files/model.rds new file mode 100644 index 000000000..9e46c2fea Binary files /dev/null and b/how-to-use-azureml/azureml-sdk-for-r/samples/deployment/deploy-to-local/project_files/model.rds differ diff --git a/how-to-use-azureml/azureml-sdk-for-r/samples/deployment/deploy-to-local/project_files/score.R b/how-to-use-azureml/azureml-sdk-for-r/samples/deployment/deploy-to-local/project_files/score.R new file mode 100644 index 000000000..73bb16bab --- /dev/null +++ b/how-to-use-azureml/azureml-sdk-for-r/samples/deployment/deploy-to-local/project_files/score.R @@ -0,0 +1,18 @@ +# 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) + } +} \ No newline at end of file diff --git a/how-to-use-azureml/azureml-sdk-for-r/samples/deployment/deploy-to-local/project_files/score_new.R b/how-to-use-azureml/azureml-sdk-for-r/samples/deployment/deploy-to-local/project_files/score_new.R new file mode 100644 index 000000000..ebc57449e --- /dev/null +++ b/how-to-use-azureml/azureml-sdk-for-r/samples/deployment/deploy-to-local/project_files/score_new.R @@ -0,0 +1,19 @@ +# 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) + } +} \ No newline at end of file diff --git a/how-to-use-azureml/azureml-sdk-for-r/samples/training/train-on-amlcompute/scripts/train.R b/how-to-use-azureml/azureml-sdk-for-r/samples/training/train-on-amlcompute/scripts/train.R new file mode 100644 index 000000000..9825c2bae --- /dev/null +++ b/how-to-use-azureml/azureml-sdk-for-r/samples/training/train-on-amlcompute/scripts/train.R @@ -0,0 +1,34 @@ +# 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") diff --git a/how-to-use-azureml/azureml-sdk-for-r/samples/training/train-on-amlcompute/train-on-amlcompute.R b/how-to-use-azureml/azureml-sdk-for-r/samples/training/train-on-amlcompute/train-on-amlcompute.R new file mode 100644 index 000000000..e033db77c --- /dev/null +++ b/how-to-use-azureml/azureml-sdk-for-r/samples/training/train-on-amlcompute/train-on-amlcompute.R @@ -0,0 +1,41 @@ +# 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) diff --git a/how-to-use-azureml/azureml-sdk-for-r/samples/training/train-on-local/scripts/train.R b/how-to-use-azureml/azureml-sdk-for-r/samples/training/train-on-local/scripts/train.R new file mode 100644 index 000000000..720045870 --- /dev/null +++ b/how-to-use-azureml/azureml-sdk-for-r/samples/training/train-on-local/scripts/train.R @@ -0,0 +1,28 @@ +# 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"]) \ No newline at end of file diff --git a/how-to-use-azureml/azureml-sdk-for-r/samples/training/train-on-local/train-on-local.R b/how-to-use-azureml/azureml-sdk-for-r/samples/training/train-on-local/train-on-local.R new file mode 100644 index 000000000..ecb75cd01 --- /dev/null +++ b/how-to-use-azureml/azureml-sdk-for-r/samples/training/train-on-local/train-on-local.R @@ -0,0 +1,26 @@ +# 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 diff --git a/how-to-use-azureml/azureml-sdk-for-r/vignettes/README.md b/how-to-use-azureml/azureml-sdk-for-r/vignettes/README.md new file mode 100644 index 000000000..618714e81 --- /dev/null +++ b/how-to-use-azureml/azureml-sdk-for-r/vignettes/README.md @@ -0,0 +1,17 @@ +## 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. \ No newline at end of file diff --git a/how-to-use-azureml/azureml-sdk-for-r/vignettes/configuration.Rmd b/how-to-use-azureml/azureml-sdk-for-r/vignettes/configuration.Rmd new file mode 100644 index 000000000..2cde4d75e --- /dev/null +++ b/how-to-use-azureml/azureml-sdk-for-r/vignettes/configuration.Rmd @@ -0,0 +1,108 @@ +--- +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 = "") +resource_group <- Sys.getenv("RESOURCE_GROUP", default="") +workspace_name <- Sys.getenv("WORKSPACE_NAME", default="") +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) +``` \ No newline at end of file diff --git a/how-to-use-azureml/azureml-sdk-for-r/vignettes/deploy-to-aks/deploy-to-aks.Rmd b/how-to-use-azureml/azureml-sdk-for-r/vignettes/deploy-to-aks/deploy-to-aks.Rmd new file mode 100644 index 000000000..603af7525 --- /dev/null +++ b/how-to-use-azureml/azureml-sdk-for-r/vignettes/deploy-to-aks/deploy-to-aks.Rmd @@ -0,0 +1,188 @@ +--- +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’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("", "", "") +``` + +## 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’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’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) +``` \ No newline at end of file diff --git a/how-to-use-azureml/azureml-sdk-for-r/vignettes/deploy-to-aks/project_files/model.rds b/how-to-use-azureml/azureml-sdk-for-r/vignettes/deploy-to-aks/project_files/model.rds new file mode 100644 index 000000000..9e46c2fea Binary files /dev/null and b/how-to-use-azureml/azureml-sdk-for-r/vignettes/deploy-to-aks/project_files/model.rds differ diff --git a/how-to-use-azureml/azureml-sdk-for-r/vignettes/deploy-to-aks/project_files/score.R b/how-to-use-azureml/azureml-sdk-for-r/vignettes/deploy-to-aks/project_files/score.R new file mode 100644 index 000000000..53c47dac9 --- /dev/null +++ b/how-to-use-azureml/azureml-sdk-for-r/vignettes/deploy-to-aks/project_files/score.R @@ -0,0 +1,17 @@ +#' 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) + } +} diff --git a/how-to-use-azureml/azureml-sdk-for-r/vignettes/hyperparameter-tune-with-keras/hyperparameter-tune-with-keras.Rmd b/how-to-use-azureml/azureml-sdk-for-r/vignettes/hyperparameter-tune-with-keras/hyperparameter-tune-with-keras.Rmd new file mode 100644 index 000000000..200cac139 --- /dev/null +++ b/how-to-use-azureml/azureml-sdk-for-r/vignettes/hyperparameter-tune-with-keras/hyperparameter-tune-with-keras.Rmd @@ -0,0 +1,242 @@ +--- +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’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("", "", "") +``` + +### 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’s details as a table. Clicking the “Web View” 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) +``` \ No newline at end of file diff --git a/how-to-use-azureml/azureml-sdk-for-r/vignettes/hyperparameter-tune-with-keras/project_files/cifar10_cnn.R b/how-to-use-azureml/azureml-sdk-for-r/vignettes/hyperparameter-tune-with-keras/project_files/cifar10_cnn.R new file mode 100644 index 000000000..2d1f8ac9d --- /dev/null +++ b/how-to-use-azureml/azureml-sdk-for-r/vignettes/hyperparameter-tune-with-keras/project_files/cifar10_cnn.R @@ -0,0 +1,124 @@ +#' 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") +} \ No newline at end of file diff --git a/how-to-use-azureml/azureml-sdk-for-r/vignettes/installation.Rmd b/how-to-use-azureml/azureml-sdk-for-r/vignettes/installation.Rmd new file mode 100644 index 000000000..d072acabb --- /dev/null +++ b/how-to-use-azureml/azureml-sdk-for-r/vignettes/installation.Rmd @@ -0,0 +1,100 @@ +--- +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 = "", + conda_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 + ``` + \ No newline at end of file diff --git a/how-to-use-azureml/azureml-sdk-for-r/vignettes/train-and-deploy-to-aci/project_files/accident_predict.R b/how-to-use-azureml/azureml-sdk-for-r/vignettes/train-and-deploy-to-aci/project_files/accident_predict.R new file mode 100644 index 000000000..37e16795c --- /dev/null +++ b/how-to-use-azureml/azureml-sdk-for-r/vignettes/train-and-deploy-to-aci/project_files/accident_predict.R @@ -0,0 +1,16 @@ +#' 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) + } +} diff --git a/how-to-use-azureml/azureml-sdk-for-r/vignettes/train-and-deploy-to-aci/project_files/accidents.R b/how-to-use-azureml/azureml-sdk-for-r/vignettes/train-and-deploy-to-aci/project_files/accidents.R new file mode 100644 index 000000000..14dd52371 --- /dev/null +++ b/how-to-use-azureml/azureml-sdk-for-r/vignettes/train-and-deploy-to-aci/project_files/accidents.R @@ -0,0 +1,33 @@ +#' 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") diff --git a/how-to-use-azureml/azureml-sdk-for-r/vignettes/train-and-deploy-to-aci/train-and-deploy-to-aci.Rmd b/how-to-use-azureml/azureml-sdk-for-r/vignettes/train-and-deploy-to-aci/train-and-deploy-to-aci.Rmd new file mode 100644 index 000000000..a0b9f4c33 --- /dev/null +++ b/how-to-use-azureml/azureml-sdk-for-r/vignettes/train-and-deploy-to-aci/train-and-deploy-to-aci.Rmd @@ -0,0 +1,326 @@ +--- +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) +``` diff --git a/how-to-use-azureml/azureml-sdk-for-r/vignettes/train-with-tensorflow/project_files/tf_mnist.R b/how-to-use-azureml/azureml-sdk-for-r/vignettes/train-with-tensorflow/project_files/tf_mnist.R new file mode 100644 index 000000000..4eaff5db8 --- /dev/null +++ b/how-to-use-azureml/azureml-sdk-for-r/vignettes/train-with-tensorflow/project_files/tf_mnist.R @@ -0,0 +1,62 @@ +# 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))) diff --git a/how-to-use-azureml/azureml-sdk-for-r/vignettes/train-with-tensorflow/train-with-tensorflow.Rmd b/how-to-use-azureml/azureml-sdk-for-r/vignettes/train-with-tensorflow/train-with-tensorflow.Rmd new file mode 100644 index 000000000..1290c4b4b --- /dev/null +++ b/how-to-use-azureml/azureml-sdk-for-r/vignettes/train-with-tensorflow/train-with-tensorflow.Rmd @@ -0,0 +1,143 @@ +--- +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’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("", "", "") +``` + +### 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’s details as a table. Clicking the “Web View” 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) +``` \ No newline at end of file diff --git a/how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-setup-schedule-for-a-published-pipeline.ipynb b/how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-setup-schedule-for-a-published-pipeline.ipynb index 800258dc4..d16538747 100644 --- a/how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-setup-schedule-for-a-published-pipeline.ipynb +++ b/how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-setup-schedule-for-a-published-pipeline.ipynb @@ -378,7 +378,8 @@ "### Create a schedule for the pipeline using a Datastore\n", "This schedule will run when additions or modifications are made to Blobs in the Datastore.\n", "By default, the Datastore container is monitored for changes. Use the path_on_datastore parameter to instead specify a path on the Datastore to monitor for changes. Note: the path_on_datastore will be under the container for the datastore, so the actual path monitored will be container/path_on_datastore. Changes made to subfolders in the container/path will not trigger the schedule.\n", - "Note: Only Blob Datastores are supported." + "Note: Only Blob Datastores are supported.\n", + "Note: Not supported for CMK workspaces. Please review these [instructions](https://docs.microsoft.com/azure/machine-learning/how-to-trigger-published-pipeline) in order to setup a blob trigger submission schedule with CMK enabled. Also see those instructions to bring your own LogicApp to avoid the schedule triggers per month limit." ] }, { diff --git a/how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-with-automated-machine-learning-step.ipynb b/how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-with-automated-machine-learning-step.ipynb index cb049d7ba..7b1017c6a 100644 --- a/how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-with-automated-machine-learning-step.ipynb +++ b/how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-with-automated-machine-learning-step.ipynb @@ -76,7 +76,7 @@ "from azureml.core.runconfig import RunConfiguration\n", "from azureml.core.conda_dependencies import CondaDependencies\n", "\n", - "from azureml.train.automl.runtime import AutoMLStep\n", + "from azureml.pipeline.steps import AutoMLStep\n", "\n", "# Check core SDK version number\n", "print(\"SDK version:\", azureml.core.VERSION)" @@ -173,12 +173,7 @@ "source": [ "# create a new RunConfig object\n", "conda_run_config = RunConfiguration(framework=\"python\")\n", - "\n", - "conda_run_config.environment.docker.enabled = True\n", - "conda_run_config.environment.docker.base_image = azureml.core.runconfig.DEFAULT_CPU_IMAGE\n", - "\n", - "cd = CondaDependencies.create(pip_packages=['azureml-sdk[automl]'], \n", - " conda_packages=['numpy', 'py-xgboost<=0.80'])\n", + "cd = CondaDependencies.create(pip_packages=['azureml-sdk[automl]'])\n", "conda_run_config.environment.python.conda_dependencies = cd\n", "\n", "print('run config is ready')" diff --git a/how-to-use-azureml/machine-learning-pipelines/parallel-run/README.md b/how-to-use-azureml/machine-learning-pipelines/parallel-run/README.md index 83ab27301..b7274ae9f 100644 --- a/how-to-use-azureml/machine-learning-pipelines/parallel-run/README.md +++ b/how-to-use-azureml/machine-learning-pipelines/parallel-run/README.md @@ -71,7 +71,7 @@ base_image_registry.password = "password" - **models**: zero or more model names already registered in Azure Machine Learning model registry. - **parallel_run_config**: ParallelRunConfig as defined above. - **inputs**: one or more Dataset objects. - - **output**: this should be a PipelineData object encapsulating an Azure BLOB container path. + - **output**: this should be a PipelineData object encapsulating an Azure BLOB container path. - **arguments**: list of custom arguments passed to scoring script (optional) - **allow_reuse**: optional, default value is True. If the inputs remain the same as a previous run, it will make the previous run results immediately available (skips re-computing the step). @@ -121,7 +121,8 @@ pipeline_run.wait_for_completion(show_output=True) # Sample notebooks -- [file-dataset-image-inference-mnist.ipynb](./file-dataset-image-inference-mnist.ipynb) demonstrates how to run batch inference on an MNIST dataset. -- [tabular-dataset-inference-iris.ipynb](./tabular-dataset-inference-iris.ipynb) demonstrates how to run batch inference on an IRIS dataset. +- [file-dataset-image-inference-mnist.ipynb](./file-dataset-image-inference-mnist.ipynb) demonstrates how to run batch inference on an MNIST dataset using FileDataset. +- [tabular-dataset-inference-iris.ipynb](./tabular-dataset-inference-iris.ipynb) demonstrates how to run batch inference on an IRIS dataset using TabularDataset. +- [pipeline-style-transfer.ipynb](../pipeline-style-transfer/pipeline-style-transfer.ipynb) demonstrates using ParallelRunStep in multi-step pipeline and using output from one step as input to ParallelRunStep. ![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/machine-learning-pipelines/parallel-run/README.png) diff --git a/how-to-use-azureml/machine-learning-pipelines/parallel-run/file-dataset-image-inference-mnist.yml b/how-to-use-azureml/machine-learning-pipelines/parallel-run/file-dataset-image-inference-mnist.yml index e1727c0a6..cd4be0864 100644 --- a/how-to-use-azureml/machine-learning-pipelines/parallel-run/file-dataset-image-inference-mnist.yml +++ b/how-to-use-azureml/machine-learning-pipelines/parallel-run/file-dataset-image-inference-mnist.yml @@ -4,3 +4,4 @@ dependencies: - azureml-sdk - azureml-contrib-pipeline-steps - azureml-widgets + - pandas diff --git a/how-to-use-azureml/machine-learning-pipelines/parallel-run/tabular-dataset-inference-iris.yml b/how-to-use-azureml/machine-learning-pipelines/parallel-run/tabular-dataset-inference-iris.yml index 8bbf1c7ad..6d1c08a8b 100644 --- a/how-to-use-azureml/machine-learning-pipelines/parallel-run/tabular-dataset-inference-iris.yml +++ b/how-to-use-azureml/machine-learning-pipelines/parallel-run/tabular-dataset-inference-iris.yml @@ -4,3 +4,4 @@ dependencies: - azureml-sdk - azureml-contrib-pipeline-steps - azureml-widgets + - pandas diff --git a/how-to-use-azureml/ml-frameworks/pytorch/deployment/train-hyperparameter-tune-deploy-with-pytorch/train-hyperparameter-tune-deploy-with-pytorch.ipynb b/how-to-use-azureml/ml-frameworks/pytorch/deployment/train-hyperparameter-tune-deploy-with-pytorch/train-hyperparameter-tune-deploy-with-pytorch.ipynb index 2489ac1e5..4e621cfe4 100644 --- a/how-to-use-azureml/ml-frameworks/pytorch/deployment/train-hyperparameter-tune-deploy-with-pytorch/train-hyperparameter-tune-deploy-with-pytorch.ipynb +++ b/how-to-use-azureml/ml-frameworks/pytorch/deployment/train-hyperparameter-tune-deploy-with-pytorch/train-hyperparameter-tune-deploy-with-pytorch.ipynb @@ -535,7 +535,7 @@ "source": [ "from azureml.core.conda_dependencies import CondaDependencies \n", "\n", - "myenv = CondaDependencies.create(pip_packages=['azureml-defaults', 'torch', 'torchvision'])\n", + "myenv = CondaDependencies.create(pip_packages=['azureml-defaults', 'torch', 'torchvision>=0.5.0'])\n", "\n", "with open(\"myenv.yml\",\"w\") as f:\n", " f.write(myenv.serialize_to_string())\n", diff --git a/how-to-use-azureml/ml-frameworks/tensorflow/training/distributed-tensorflow-with-horovod/tf_horovod_word2vec.py b/how-to-use-azureml/ml-frameworks/tensorflow/training/distributed-tensorflow-with-horovod/tf_horovod_word2vec.py index e075d4e8e..483053302 100644 --- a/how-to-use-azureml/ml-frameworks/tensorflow/training/distributed-tensorflow-with-horovod/tf_horovod_word2vec.py +++ b/how-to-use-azureml/ml-frameworks/tensorflow/training/distributed-tensorflow-with-horovod/tf_horovod_word2vec.py @@ -37,7 +37,7 @@ print("the input data is at %s" % input_data) # Step 1: Read data. -filename = glob.glob(os.path.join(input_data, '**/text8.zip'), recursive=True)[0] +filename = input_data # Read the data into a list of strings. diff --git a/how-to-use-azureml/ml-frameworks/tensorflow/training/hyperparameter-tune-and-warm-start-with-tensorflow/hyperparameter-tune-and-warm-start-with-tensorflow.ipynb b/how-to-use-azureml/ml-frameworks/tensorflow/training/hyperparameter-tune-and-warm-start-with-tensorflow/hyperparameter-tune-and-warm-start-with-tensorflow.ipynb index 86fc3d9b0..4539c4362 100644 --- a/how-to-use-azureml/ml-frameworks/tensorflow/training/hyperparameter-tune-and-warm-start-with-tensorflow/hyperparameter-tune-and-warm-start-with-tensorflow.ipynb +++ b/how-to-use-azureml/ml-frameworks/tensorflow/training/hyperparameter-tune-and-warm-start-with-tensorflow/hyperparameter-tune-and-warm-start-with-tensorflow.ipynb @@ -149,7 +149,7 @@ "script_folder = './tf-mnist'\n", "os.makedirs(script_folder, exist_ok=True)\n", "\n", - "exp = Experiment(workspace=ws, name='tf-mnist')" + "exp = Experiment(workspace=ws, name='tf-mnist-2')" ] }, { diff --git a/how-to-use-azureml/monitor-models/data-drift/drift-on-aks.ipynb b/how-to-use-azureml/monitor-models/data-drift/drift-on-aks.ipynb index e0384ef69..9131ed12e 100644 --- a/how-to-use-azureml/monitor-models/data-drift/drift-on-aks.ipynb +++ b/how-to-use-azureml/monitor-models/data-drift/drift-on-aks.ipynb @@ -390,15 +390,6 @@ "run = monitor.run(target_date, services, feature_list=feature_list, compute_target='cpu-cluster')" ] }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "time.sleep(1200)" - ] - }, { "cell_type": "markdown", "metadata": {}, @@ -418,6 +409,24 @@ "# Here we retrieve the individual service run to get its output results and metrics. \n", "\n", "child_run = list(run.get_children())[0]\n", + "child_run" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "child_run.wait_for_completion(wait_post_processing=True)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ "results, metrics = monitor.get_output(run_id=child_run.id)" ] }, diff --git a/how-to-use-azureml/track-and-monitor-experiments/logging-api/logging-api.ipynb b/how-to-use-azureml/track-and-monitor-experiments/logging-api/logging-api.ipynb index 33a779e76..1253622b9 100644 --- a/how-to-use-azureml/track-and-monitor-experiments/logging-api/logging-api.ipynb +++ b/how-to-use-azureml/track-and-monitor-experiments/logging-api/logging-api.ipynb @@ -100,7 +100,7 @@ "\n", "# Check core SDK version number\n", "\n", - "print(\"This notebook was created using SDK version 1.1.0rc0, you are currently running version\", azureml.core.VERSION)" + "print(\"This notebook was created using SDK version 1.1.0rc1, you are currently running version\", azureml.core.VERSION)" ] }, { diff --git a/how-to-use-azureml/training-with-deep-learning/train-hyperparameter-tune-deploy-with-keras/train-hyperparameter-tune-deploy-with-keras.ipynb b/how-to-use-azureml/training-with-deep-learning/train-hyperparameter-tune-deploy-with-keras/train-hyperparameter-tune-deploy-with-keras.ipynb index 1f8ad67e1..508ec236e 100644 --- a/how-to-use-azureml/training-with-deep-learning/train-hyperparameter-tune-deploy-with-keras/train-hyperparameter-tune-deploy-with-keras.ipynb +++ b/how-to-use-azureml/training-with-deep-learning/train-hyperparameter-tune-deploy-with-keras/train-hyperparameter-tune-deploy-with-keras.ipynb @@ -1103,13 +1103,11 @@ "metadata": {}, "outputs": [], "source": [ - "models = ws.models\n", - "for name, model in models.items():\n", - " print(\"Model: {}, ID: {}\".format(name, model.id))\n", + "model = ws.models['keras-mlp-mnist']\n", + "print(\"Model: {}, ID: {}\".format('keras-mlp-mnist', model.id))\n", " \n", - "webservices = ws.webservices\n", - "for name, webservice in webservices.items():\n", - " print(\"Webservice: {}, scoring URI: {}\".format(name, webservice.scoring_uri))" + "webservice = ws.webservices['keras-mnist-svc']\n", + "print(\"Webservice: {}, scoring URI: {}\".format('keras-mnist-svc', webservice.scoring_uri))" ] }, { diff --git a/how-to-use-azureml/training/train-on-remote-vm/train-on-remote-vm.ipynb b/how-to-use-azureml/training/train-on-remote-vm/train-on-remote-vm.ipynb index 415fb061b..7d2b546ba 100644 --- a/how-to-use-azureml/training/train-on-remote-vm/train-on-remote-vm.ipynb +++ b/how-to-use-azureml/training/train-on-remote-vm/train-on-remote-vm.ipynb @@ -23,7 +23,7 @@ "# 04. Train in a remote Linux VM\n", "* Create Workspace\n", "* Create `train.py` file\n", - "* Create and Attach a Remote VM (eg. DSVM) as compute resource.\n", + "* Create and Attach a Remote VM (eg. DSVM) as compute resource\n", "* Upload data files into default datastore\n", "* Configure & execute a run in a few different ways\n", " - Use system-built conda\n", @@ -126,7 +126,7 @@ "metadata": {}, "outputs": [], "source": [ - "# get the default datastore\n", + "# Get the default datastore\n", "ds = ws.get_default_datastore()\n", "print(ds.name, ds.datastore_type, ds.account_name, ds.container_name)" ] @@ -313,11 +313,11 @@ "from azureml.core import ScriptRunConfig\n", "from uuid import uuid4\n", "\n", + "script_arguments = ['--data-folder', dataset.as_named_input('diabetes').as_mount('/tmp/{}'.format(uuid4()))]\n", "src = ScriptRunConfig(source_directory=script_folder, \n", " script='train.py', \n", " # pass the dataset as a parameter to the training script\n", - " arguments=['--data-folder', \n", - " dataset.as_named_input('diabetes').as_mount('/tmp/{}'.format(uuid4()))]\n", + " arguments=script_arguments\n", " ) \n", "\n", "src.run_config.framework = \"python\"\n", @@ -392,14 +392,14 @@ "metadata": {}, "outputs": [], "source": [ - "run = exp.submit(config=src)\n", + " run = exp.submit(config=src)\n", "\n", - "from azureml.exceptions import ActivityFailedException\n", + " from azureml.exceptions import ActivityFailedException\n", "\n", - "try:\n", - " run.wait_for_completion(show_output=True)\n", - "except ActivityFailedException as ex:\n", - " print(ex)" + " try:\n", + " run.wait_for_completion(show_output=True)\n", + " except ActivityFailedException as ex:\n", + " print(ex)" ] }, { @@ -421,7 +421,8 @@ "with open(os.path.join(script_folder, './train2.py'), 'r') as training_script:\n", " print(training_script.read())\n", " \n", - "src.script = \"train2.py\"" + "src.script = \"train2.py\"\n", + "src.arguments = None" ] }, { @@ -493,6 +494,7 @@ "outputs": [], "source": [ "src.script = \"train.py\"\n", + "src.arguments = script_arguments\n", "\n", "run = exp.submit(config=src)\n", "\n", diff --git a/how-to-use-azureml/training/train-on-remote-vm/train-on-remote-vm.yml b/how-to-use-azureml/training/train-on-remote-vm/train-on-remote-vm.yml deleted file mode 100644 index 930604bf7..000000000 --- a/how-to-use-azureml/training/train-on-remote-vm/train-on-remote-vm.yml +++ /dev/null @@ -1,10 +0,0 @@ -name: train-on-remote-vm -dependencies: -- matplotlib -- tqdm -- scikit-learn==0.22.1 -- numpy==1.18.1 -- pip: - - azureml-sdk - - azureml-widgets - - azureml-dataprep[fuse,pandas] diff --git a/how-to-use-azureml/work-with-data/datadrift-tutorial/datadrift-tutorial.ipynb b/how-to-use-azureml/work-with-data/datadrift-tutorial/datadrift-tutorial.ipynb index 599d88d66..8459192c7 100644 --- a/how-to-use-azureml/work-with-data/datadrift-tutorial/datadrift-tutorial.ipynb +++ b/how-to-use-azureml/work-with-data/datadrift-tutorial/datadrift-tutorial.ipynb @@ -300,28 +300,6 @@ "backfill" ] }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Enable the monitor's pipeline schedule\n", - "\n", - "Turn on a scheduled pipeline which will anlayze the target dataset for drift every `frequency`. Use the latency parameter to adjust the start time of the pipeline. For instance, if it takes 24 hours for my data processing pipelines for data to arrive in the target dataset, set latency to 24. " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# enable the pipeline schedule and recieve email alerts\n", - "monitor.enable_schedule()\n", - "\n", - "# disable the pipeline schedule \n", - "#monitor.disable_schedule()" - ] - }, { "cell_type": "markdown", "metadata": {}, @@ -338,8 +316,7 @@ "outputs": [], "source": [ "# make sure the backfill has completed\n", - "import time\n", - "time.sleep(1200)" + "backfill.wait_for_completion(wait_post_processing=True)" ] }, { @@ -366,9 +343,9 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## See results in Azure Machine Learning studio (Enterprise only)\n", + "## Enable the monitor's pipeline schedule\n", "\n", - "The below cell will print a link to the monitor in the Azure Machine Learning studio, where the results can be viewed. Alertnatively, use the `show` or `get_results` to get and plot data drift results in Python." + "Turn on a scheduled pipeline which will anlayze the target dataset for drift every `frequency`. Use the latency parameter to adjust the start time of the pipeline. For instance, if it takes 24 hours for my data processing pipelines for data to arrive in the target dataset, set latency to 24. " ] }, { @@ -377,8 +354,11 @@ "metadata": {}, "outputs": [], "source": [ - "link = 'https://ml.azure.com/data/monitor/{}?wsid=/subscriptions/{}/resourcegroups/{}/workspaces/{}&startDate={}&endDate={}'.format(monitor.name, ws.subscription_id, ws.resource_group, ws.name, backfill_start_date.strftime('%Y-%m-%d'), backfill_end_date .strftime('%Y-%m-%d'))\n", - "print(link)" + "# enable the pipeline schedule and recieve email alerts\n", + "monitor.enable_schedule()\n", + "\n", + "# disable the pipeline schedule \n", + "#monitor.disable_schedule()" ] }, { diff --git a/how-to-use-azureml/work-with-data/datasets-tutorial/labeled-datasets/labeled-datasets.ipynb b/how-to-use-azureml/work-with-data/datasets-tutorial/labeled-datasets/labeled-datasets.ipynb new file mode 100644 index 000000000..ed210f6ad --- /dev/null +++ b/how-to-use-azureml/work-with-data/datasets-tutorial/labeled-datasets/labeled-datasets.ipynb @@ -0,0 +1,403 @@ +{ + "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/work-with-data/datasets-tutorial/labeled-datasets/labeled-datasets.png)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Introduction to labeled datasets\n", + "\n", + "Labeled datasets are output from Azure Machine Learning [labeling projects](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-create-labeling-projects). It captures the reference to the data (e.g. image files) and its labels. \n", + "\n", + "This tutorial introduces the capabilities of labeled datasets and how to use it in training.\n", + "\n", + "Learn how-to:\n", + "\n", + "> * Set up your development environment\n", + "> * Explore labeled datasets\n", + "> * Train a simple deep learning neural network on a remote cluster\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", + "* Go through Azure Machine Learning [labeling projects](https://docs.microsoft.com/azure/machine-learning/service/how-to-create-labeling-projects) and export the labels as an Azure Machine Learning dataset\n", + "* Go through the [configuration notebook](../../../configuration.ipynb) to:\n", + " * install the latest version of azureml-sdk\n", + " * install the latest version of azureml-contrib-dataset\n", + " * install [PyTorch](https://pytorch.org/)\n", + " * create a workspace and its configuration file (`config.json`)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Set up your development environment\n", + "\n", + "All the setup for your development work can be accomplished in a Python notebook. Setup includes:\n", + "\n", + "* Importing Python packages\n", + "* Connecting to a workspace to enable communication between your local computer and remote resources\n", + "* Creating an experiment to track all your runs\n", + "* Creating a remote compute target to use for training\n", + "\n", + "### Import packages\n", + "\n", + "Import Python packages you need in this session. Also display the Azure Machine Learning SDK version." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import os\n", + "import azureml.core\n", + "import azureml.contrib.dataset\n", + "from azureml.core import Dataset, Workspace, Experiment\n", + "from azureml.contrib.dataset import FileHandlingOption\n", + "\n", + "# check core SDK version number\n", + "print(\"Azure ML SDK Version: \", azureml.core.VERSION)\n", + "print(\"Azure ML Contrib Version\", azureml.contrib.dataset.VERSION)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Connect to workspace\n", + "\n", + "Create a workspace object from the existing workspace. `Workspace.from_config()` reads the file **config.json** and loads the details into an object named `workspace`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# load workspace\n", + "workspace = Workspace.from_config()\n", + "print('Workspace name: ' + workspace.name, \n", + " 'Azure region: ' + workspace.location, \n", + " 'Subscription id: ' + workspace.subscription_id, \n", + " 'Resource group: ' + workspace.resource_group, sep='\\n')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Create experiment and a directory\n", + "\n", + "Create an experiment to track the runs in your workspace and a directory to deliver the necessary code from your computer to the remote resource." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# create an ML experiment\n", + "exp = Experiment(workspace=workspace, name='labeled-datasets')\n", + "\n", + "# create a directory\n", + "script_folder = './labeled-datasets'\n", + "os.makedirs(script_folder, exist_ok=True)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Create or Attach existing compute resource\n", + "By using Azure Machine Learning Compute, 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 will create Azure Machine Learning Compute as your training environment. The code below creates the compute clusters for you if they don't already exist in your workspace.\n", + "\n", + "**Creation of compute takes approximately 5 minutes.** If the AmlCompute with that name is already in your workspace the code will skip the creation process." + ] + }, + { + "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 = \"openhack\"\n", + "\n", + "try:\n", + " compute_target = ComputeTarget(workspace=workspace, 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(workspace, 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", + " compute_target.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(compute_target.get_status().serialize())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Explore labeled datasets\n", + "\n", + "**Note**: How to create labeled datasets is not covered in this tutorial. To create labeled datasets, you can go through [labeling projects](https://docs.microsoft.com/azure/machine-learning/service/how-to-create-labeling-projects) and export the output labels as Azure Machine Lerning datasets. \n", + "\n", + "`animal_labels` used in this tutorial section is the output from a labeling project, with the task type of \"Object Identification\"." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# get animal_labels dataset from the workspace\n", + "animal_labels = Dataset.get_by_name(workspace, 'animal_labels')\n", + "animal_labels" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You can load labeled datasets into pandas DataFrame. There are 3 file handling option that you can choose to load the data files referenced by the labeled datasets:\n", + "* Streaming: The default option to load data files.\n", + "* Download: Download your data files to a local path.\n", + "* Mount: Mount your data files to a mount point. Mount only works for Linux-based compute, including Azure Machine Learning notebook VM and Azure Machine Learning Compute." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "animal_pd = animal_labels.to_pandas_dataframe(file_handling_option=FileHandlingOption.DOWNLOAD, target_path='./download/', overwrite_download=True)\n", + "animal_pd" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n", + "import matplotlib.image as mpimg\n", + "\n", + "# read images from downloaded path\n", + "img = mpimg.imread(animal_pd.loc[0,'image_url'])\n", + "imgplot = plt.imshow(img)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You can also load labeled datasets into [torchvision datasets](https://pytorch.org/docs/stable/torchvision/datasets.html), so that you can leverage on the open source libraries provided by PyTorch for image transformation and training." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from torchvision.transforms import functional as F\n", + "\n", + "# load animal_labels dataset into torchvision dataset\n", + "pytorch_dataset = animal_labels.to_torchvision()\n", + "img = pytorch_dataset[0][0]\n", + "print(type(img))\n", + "\n", + "# use methods from torchvision to transform the img into grayscale\n", + "pil_image = F.to_pil_image(img)\n", + "gray_image = F.to_grayscale(pil_image, num_output_channels=3)\n", + "\n", + "imgplot = plt.imshow(gray_image)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Train an image classification model\n", + "\n", + " `crack_labels` dataset used in this tutorial section is the output from a labeling project, with the task type of \"Image Classification Multi-class\". We will use this dataset to train an image classification model that classify whether an image has cracks or not." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# get crack_labels dataset from the workspace\n", + "crack_labels = Dataset.get_by_name(workspace, 'crack_labels')\n", + "crack_labels" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Configure Estimator for training\n", + "\n", + "You can ask the system to build a conda environment based on your dependency specification. Once the environment is built, and if you don't change your dependencies, it will be reused in subsequent runs." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from azureml.core import Environment\n", + "from azureml.core.conda_dependencies import CondaDependencies\n", + "\n", + "conda_env = Environment('conda-env')\n", + "conda_env.python.conda_dependencies = CondaDependencies.create(pip_packages=['azureml-sdk',\n", + " 'azureml-contrib-dataset',\n", + " 'torch','torchvision',\n", + " 'azureml-dataprep[pandas]'])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "An estimator object is used to submit the run. Azure Machine Learning has pre-configured estimators for common machine learning frameworks, as well as generic Estimator. Create a generic estimator for by specifying\n", + "\n", + "* The name of the estimator object, `est`\n", + "* The directory that contains your scripts. All the files in this directory are uploaded into the cluster nodes for execution. \n", + "* The training script name, train.py\n", + "* The input dataset for training\n", + "* The compute target. In this case you will use the AmlCompute you created\n", + "* The environment definition for the experiment" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from azureml.train.estimator import Estimator\n", + "\n", + "est = Estimator(source_directory=script_folder, \n", + " entry_script='train.py',\n", + " inputs=[crack_labels.as_named_input('crack_labels')],\n", + " compute_target=compute_target,\n", + " environment_definition= conda_env)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Submit job to run\n", + "\n", + "Submit the estimator to the Azure ML experiment to kick off the execution." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run = exp.submit(est)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run.wait_for_completion(show_output=True)" + ] + } + ], + "metadata": { + "authors": [ + { + "name": "sihhu" + } + ], + "category": "tutorial", + "compute": [ + "Remote" + ], + "deployment": [ + "None" + ], + "exclude_from_index": false, + "framework": [ + "Azure ML" + ], + "friendly_name": "Introduction to labeled datasets", + "index_order": 1, + "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.9" + }, + "nteract": { + "version": "nteract-front-end@1.0.0" + }, + "star_tag": [ + "featured" + ], + "tags": [ + "Dataset", + "label", + "Estimator" + ], + "task": "Train" + }, + "nbformat": 4, + "nbformat_minor": 2 +} \ No newline at end of file diff --git a/how-to-use-azureml/work-with-data/datasets-tutorial/labeled-datasets/labeled-datasets.yml b/how-to-use-azureml/work-with-data/datasets-tutorial/labeled-datasets/labeled-datasets.yml new file mode 100644 index 000000000..26c3266a9 --- /dev/null +++ b/how-to-use-azureml/work-with-data/datasets-tutorial/labeled-datasets/labeled-datasets.yml @@ -0,0 +1,10 @@ +name: labeled-datasets +dependencies: +- pip: + - azureml-sdk + - azureml-dataprep + - pandas + - fuse + - azureml.contrib.dataset + - matplotlib + - torchvision diff --git a/how-to-use-azureml/work-with-data/datasets-tutorial/labeled-datasets/labeled-datasets/train.py b/how-to-use-azureml/work-with-data/datasets-tutorial/labeled-datasets/labeled-datasets/train.py new file mode 100644 index 000000000..a4bfc53e0 --- /dev/null +++ b/how-to-use-azureml/work-with-data/datasets-tutorial/labeled-datasets/labeled-datasets/train.py @@ -0,0 +1,106 @@ +import os +import torchvision +import torchvision.transforms as transforms +import torch +import torch.nn as nn +import torch.nn.functional as F +import torch.optim as optim + +from azureml.core import Dataset, Run +import azureml.contrib.dataset +from azureml.contrib.dataset import FileHandlingOption, LabeledDatasetTask + +run = Run.get_context() + +# get input dataset by name +labeled_dataset = run.input_datasets['crack_labels'] +pytorch_dataset = labeled_dataset.to_torchvision() + + +indices = torch.randperm(len(pytorch_dataset)).tolist() +dataset_train = torch.utils.data.Subset(pytorch_dataset, indices[:40]) +dataset_test = torch.utils.data.Subset(pytorch_dataset, indices[-10:]) + +trainloader = torch.utils.data.DataLoader(dataset_train, batch_size=4, + shuffle=True, num_workers=0) + +testloader = torch.utils.data.DataLoader(dataset_test, batch_size=4, + shuffle=True, num_workers=0) + + +class Net(nn.Module): + def __init__(self): + super(Net, self).__init__() + self.conv1 = nn.Conv2d(3, 6, 5) + self.pool = nn.MaxPool2d(2, 2) + self.conv2 = nn.Conv2d(6, 16, 5) + self.fc1 = nn.Linear(16 * 71 * 71, 120) + self.fc2 = nn.Linear(120, 84) + self.fc3 = nn.Linear(84, 10) + + def forward(self, x): + x = self.pool(F.relu(self.conv1(x))) + x = self.pool(F.relu(self.conv2(x))) + x = x.view(x.size(0), 16 * 71 * 71) + x = F.relu(self.fc1(x)) + x = F.relu(self.fc2(x)) + x = self.fc3(x) + return x + + +net = Net() + +criterion = nn.CrossEntropyLoss() +optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9) + + +for epoch in range(2): # loop over the dataset multiple times + + running_loss = 0.0 + for i, data in enumerate(trainloader, 0): + # get the inputs; data is a list of [inputs, labels] + inputs, labels = data + + # zero the parameter gradients + optimizer.zero_grad() + + # forward + backward + optimize + outputs = net(inputs) + loss = criterion(outputs, labels) + loss.backward() + optimizer.step() + + # print statistics + running_loss += loss.item() + if i % 5 == 4: # print every 5 mini-batches + print('[%d, %5d] loss: %.3f' % + (epoch + 1, i + 1, running_loss / 5)) + running_loss = 0.0 + +print('Finished Training') +classes = trainloader.dataset.dataset.labels +PATH = './cifar_net.pth' +torch.save(net.state_dict(), PATH) + +dataiter = iter(testloader) +images, labels = dataiter.next() + +net = Net() +net.load_state_dict(torch.load(PATH)) + +outputs = net(images) + +_, predicted = torch.max(outputs, 1) + +correct = 0 +total = 0 +with torch.no_grad(): + for data in testloader: + images, labels = data + outputs = net(images) + _, predicted = torch.max(outputs.data, 1) + total += labels.size(0) + correct += (predicted == labels).sum().item() + +print('Accuracy of the network on the 10 test images: %d %%' % (100 * correct / total)) +pass diff --git a/how-to-use-azureml/work-with-data/datasets-tutorial/pipeline-with-datasets/keras-mnist-fashion/prepare.py b/how-to-use-azureml/work-with-data/datasets-tutorial/pipeline-with-datasets/keras-mnist-fashion/prepare.py new file mode 100644 index 000000000..4e8c054a8 --- /dev/null +++ b/how-to-use-azureml/work-with-data/datasets-tutorial/pipeline-with-datasets/keras-mnist-fashion/prepare.py @@ -0,0 +1,35 @@ +import os + + +def convert(imgf, labelf, outf, n): + f = open(imgf, "rb") + l = open(labelf, "rb") + o = open(outf, "w") + + f.read(16) + l.read(8) + images = [] + + for i in range(n): + image = [ord(l.read(1))] + for j in range(28 * 28): + image.append(ord(f.read(1))) + images.append(image) + + for image in images: + o.write(",".join(str(pix) for pix in image) + "\n") + f.close() + o.close() + l.close() + + +mounted_input_path = os.environ['fashion_ds'] +mounted_output_path = os.environ['AZUREML_DATAREFERENCE_prepared_fashion_ds'] +os.makedirs(mounted_output_path, exist_ok=True) + +convert(os.path.join(mounted_input_path, 'train-images-idx3-ubyte'), + os.path.join(mounted_input_path, 'train-labels-idx1-ubyte'), + os.path.join(mounted_output_path, 'mnist_train.csv'), 60000) +convert(os.path.join(mounted_input_path, 't10k-images-idx3-ubyte'), + os.path.join(mounted_input_path, 't10k-labels-idx1-ubyte'), + os.path.join(mounted_output_path, 'mnist_test.csv'), 10000) diff --git a/how-to-use-azureml/work-with-data/datasets-tutorial/pipeline-with-datasets/keras-mnist-fashion/t10k-images-idx3-ubyte b/how-to-use-azureml/work-with-data/datasets-tutorial/pipeline-with-datasets/keras-mnist-fashion/t10k-images-idx3-ubyte new file mode 100644 index 000000000..37bac79bc Binary files /dev/null and b/how-to-use-azureml/work-with-data/datasets-tutorial/pipeline-with-datasets/keras-mnist-fashion/t10k-images-idx3-ubyte differ diff --git a/how-to-use-azureml/work-with-data/datasets-tutorial/pipeline-with-datasets/keras-mnist-fashion/t10k-labels-idx1-ubyte b/how-to-use-azureml/work-with-data/datasets-tutorial/pipeline-with-datasets/keras-mnist-fashion/t10k-labels-idx1-ubyte new file mode 100644 index 000000000..2195a4d09 Binary files /dev/null and b/how-to-use-azureml/work-with-data/datasets-tutorial/pipeline-with-datasets/keras-mnist-fashion/t10k-labels-idx1-ubyte differ diff --git a/how-to-use-azureml/work-with-data/datasets-tutorial/pipeline-with-datasets/keras-mnist-fashion/train-images-idx3-ubyte b/how-to-use-azureml/work-with-data/datasets-tutorial/pipeline-with-datasets/keras-mnist-fashion/train-images-idx3-ubyte new file mode 100644 index 000000000..ff2f5a963 Binary files /dev/null and b/how-to-use-azureml/work-with-data/datasets-tutorial/pipeline-with-datasets/keras-mnist-fashion/train-images-idx3-ubyte differ diff --git a/how-to-use-azureml/work-with-data/datasets-tutorial/pipeline-with-datasets/keras-mnist-fashion/train-labels-idx1-ubyte b/how-to-use-azureml/work-with-data/datasets-tutorial/pipeline-with-datasets/keras-mnist-fashion/train-labels-idx1-ubyte new file mode 100644 index 000000000..30424ca2e Binary files /dev/null and b/how-to-use-azureml/work-with-data/datasets-tutorial/pipeline-with-datasets/keras-mnist-fashion/train-labels-idx1-ubyte differ diff --git a/how-to-use-azureml/work-with-data/datasets-tutorial/pipeline-with-datasets/keras-mnist-fashion/train.py b/how-to-use-azureml/work-with-data/datasets-tutorial/pipeline-with-datasets/keras-mnist-fashion/train.py new file mode 100644 index 000000000..b0215ad1b --- /dev/null +++ b/how-to-use-azureml/work-with-data/datasets-tutorial/pipeline-with-datasets/keras-mnist-fashion/train.py @@ -0,0 +1,120 @@ +import keras +from keras.models import Sequential +from keras.layers import Dense, Dropout, Flatten +from keras.layers import Conv2D, MaxPooling2D +from keras.layers.normalization import BatchNormalization +from keras.utils import to_categorical +from keras.callbacks import Callback + +import numpy as np +import pandas as pd +import os +import matplotlib.pyplot as plt +from sklearn.model_selection import train_test_split +from azureml.core import Run + +# dataset object from the run +run = Run.get_context() +dataset = run.input_datasets['prepared_fashion_ds'] + +# split dataset into train and test set +(train_dataset, test_dataset) = dataset.random_split(percentage=0.8, seed=111) + +# load dataset into pandas dataframe +data_train = train_dataset.to_pandas_dataframe() +data_test = test_dataset.to_pandas_dataframe() + +img_rows, img_cols = 28, 28 +input_shape = (img_rows, img_cols, 1) + +X = np.array(data_train.iloc[:, 1:]) +y = to_categorical(np.array(data_train.iloc[:, 0])) + +# here we split validation data to optimiza classifier during training +X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=13) + +# test data +X_test = np.array(data_test.iloc[:, 1:]) +y_test = to_categorical(np.array(data_test.iloc[:, 0])) + + +X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, 1).astype('float32') / 255 +X_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, 1).astype('float32') / 255 +X_val = X_val.reshape(X_val.shape[0], img_rows, img_cols, 1).astype('float32') / 255 + +batch_size = 256 +num_classes = 10 +epochs = 10 + +# construct neuron network +model = Sequential() +model.add(Conv2D(32, kernel_size=(3, 3), + activation='relu', + kernel_initializer='he_normal', + input_shape=input_shape)) +model.add(MaxPooling2D((2, 2))) +model.add(Dropout(0.25)) +model.add(Conv2D(64, (3, 3), activation='relu')) +model.add(MaxPooling2D(pool_size=(2, 2))) +model.add(Dropout(0.25)) +model.add(Conv2D(128, (3, 3), activation='relu')) +model.add(Dropout(0.4)) +model.add(Flatten()) +model.add(Dense(128, activation='relu')) +model.add(Dropout(0.3)) +model.add(Dense(num_classes, activation='softmax')) + +model.compile(loss=keras.losses.categorical_crossentropy, + optimizer=keras.optimizers.Adam(), + metrics=['accuracy']) + +# start an Azure ML run +run = Run.get_context() + + +class LogRunMetrics(Callback): + # callback at the end of every epoch + def on_epoch_end(self, epoch, log): + # log a value repeated which creates a list + run.log('Loss', log['loss']) + run.log('Accuracy', log['accuracy']) + + +history = model.fit(X_train, y_train, + batch_size=batch_size, + epochs=epochs, + verbose=1, + validation_data=(X_val, y_val), + callbacks=[LogRunMetrics()]) + +score = model.evaluate(X_test, y_test, verbose=0) + +# log a single value +run.log("Final test loss", score[0]) +print('Test loss:', score[0]) + +run.log('Final test accuracy', score[1]) +print('Test accuracy:', score[1]) + +plt.figure(figsize=(6, 3)) +plt.title('Fashion MNIST with Keras ({} epochs)'.format(epochs), fontsize=14) +plt.plot(history.history['accuracy'], 'b-', label='Accuracy', lw=4, alpha=0.5) +plt.plot(history.history['loss'], 'r--', label='Loss', lw=4, alpha=0.5) +plt.legend(fontsize=12) +plt.grid(True) + +# log an image +run.log_image('Loss v.s. Accuracy', plot=plt) + +# create a ./outputs/model folder in the compute target +# files saved in the "./outputs" folder are automatically uploaded into run history +os.makedirs('./outputs/model', exist_ok=True) + +# serialize NN architecture to JSON +model_json = model.to_json() +# save model JSON +with open('./outputs/model/model.json', 'w') as f: + f.write(model_json) +# save model weights +model.save_weights('./outputs/model/model.h5') +print("model saved in ./outputs/model folder") diff --git a/how-to-use-azureml/work-with-data/datasets-tutorial/pipeline-with-datasets/pipeline-for-image-classification.ipynb b/how-to-use-azureml/work-with-data/datasets-tutorial/pipeline-with-datasets/pipeline-for-image-classification.ipynb new file mode 100644 index 000000000..eefd2b70e --- /dev/null +++ b/how-to-use-azureml/work-with-data/datasets-tutorial/pipeline-with-datasets/pipeline-for-image-classification.ipynb @@ -0,0 +1,488 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Copyright (c) Microsoft Corporation. All rights reserved.\n", + "\n", + "Licensed under the MIT License [2017] Zalando SE, https://tech.zalando.com" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/work-with-data/datasets-tutorial/pipeline-with-datasets/pipeline-for-image-classification.png)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Build a simple ML pipeline for image classification\n", + "\n", + "## Introduction\n", + "This tutorial shows how to train a simple deep neural network using the [Fashion MNIST](https://github.com/zalandoresearch/fashion-mnist) dataset and Keras on Azure Machine Learning. Fashion-MNIST is a dataset of Zalando's article images\u00e2\u20ac\u201dconsisting of a training set of 60,000 examples and a test set of 10,000 examples. Each example is a 28x28 grayscale image, associated with a label from 10 classes.\n", + "\n", + "Learn how to:\n", + "\n", + "> * Set up your development environment\n", + "> * Create the Fashion MNIST dataset\n", + "> * Create a machine learning pipeline to train a simple deep learning neural network on a remote cluster\n", + "> * Retrieve input datasets from the experiment and register the output model with datasets\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 latest version of AzureML SDK\n", + " * create a workspace and its configuration file (`config.json`)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Set up your development environment\n", + "\n", + "All the setup for your development work can be accomplished in a Python notebook. Setup includes:\n", + "\n", + "* Importing Python packages\n", + "* Connecting to a workspace to enable communication between your local computer and remote resources\n", + "* Creating an experiment to track all your runs\n", + "* Creating a remote compute target to use for training\n", + "\n", + "### Import packages\n", + "\n", + "Import Python packages you need in this session. Also display the Azure Machine Learning SDK version." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import os\n", + "import azureml.core\n", + "from azureml.core import Workspace, Dataset, Datastore, ComputeTarget, RunConfiguration, Experiment\n", + "from azureml.core.runconfig import CondaDependencies\n", + "from azureml.pipeline.steps import PythonScriptStep, EstimatorStep\n", + "from azureml.pipeline.core import Pipeline, PipelineData\n", + "from azureml.train.dnn import TensorFlow\n", + "\n", + "# check core SDK version number\n", + "print(\"Azure ML SDK Version: \", azureml.core.VERSION)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Connect to workspace\n", + "\n", + "Create a workspace object from the existing workspace. `Workspace.from_config()` reads the file **config.json** and loads the details into an object named `workspace`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# load workspace\n", + "workspace = Workspace.from_config()\n", + "print('Workspace name: ' + workspace.name, \n", + " 'Azure region: ' + workspace.location, \n", + " 'Subscription id: ' + workspace.subscription_id, \n", + " 'Resource group: ' + workspace.resource_group, sep='\\n')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Create experiment and a directory\n", + "\n", + "Create an experiment to track the runs in your workspace and a directory to deliver the necessary code from your computer to the remote resource." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# create an ML experiment\n", + "exp = Experiment(workspace=workspace, name='keras-mnist-fashion')\n", + "\n", + "# create a directory\n", + "script_folder = './keras-mnist-fashion'\n", + "os.makedirs(script_folder, exist_ok=True)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Create or Attach existing compute resource\n", + "By using Azure Machine Learning Compute, 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 Azure Machine Learning Compute as your training environment. The code below creates the compute clusters for you if they don't already exist in your workspace.\n", + "\n", + "**Creation of compute takes approximately 5 minutes.** If the AmlCompute with that name is already in your workspace the code will skip the creation process." + ] + }, + { + "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 = \"your-cluster-name\"\n", + "\n", + "try:\n", + " compute_target = ComputeTarget(workspace=workspace, 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(workspace, 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", + " compute_target.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(compute_target.get_status().serialize())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Create the Fashion MNIST dataset\n", + "\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. \n", + "\n", + "Every workspace comes with a default [datastore](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-access-data) (and you can register more) which is backed by the Azure blob storage account associated with the workspace. We can use it to transfer data from local to the cloud, and create a dataset from it. We will now upload the [Fashion MNIST](./keras-mnist-fashion) to the default datastore (blob) within your workspace." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "datastore = workspace.get_default_datastore()\n", + "datastore.upload_files(files = ['keras-mnist-fashion/t10k-images-idx3-ubyte', 'keras-mnist-fashion/t10k-labels-idx1-ubyte',\n", + " 'keras-mnist-fashion/train-images-idx3-ubyte','keras-mnist-fashion/train-labels-idx1-ubyte'],\n", + " target_path = 'mnist-fashion',\n", + " overwrite = True,\n", + " show_progress = True)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Then we will create an unregistered FileDataset pointing to the path in the datastore. You can also create a dataset from multiple paths. [Learn More](https://aka.ms/azureml/howto/createdatasets) " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "fashion_ds = Dataset.File.from_files([(datastore, 'mnist-fashion')])\n", + "\n", + "# list the files referenced by fashion_ds\n", + "fashion_ds.to_path()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Build 2-step ML pipeline\n", + "\n", + "The [Azure Machine Learning Pipeline](https://docs.microsoft.com/en-us/azure/machine-learning/service/concept-ml-pipelines) enables data scientists to create and manage multiple simple and complex workflows concurrently. A typical pipeline would have multiple tasks to prepare data, train, deploy and evaluate models. Individual steps in the pipeline can make use of diverse compute options (for example: CPU for data preparation and GPU for training) and languages. [Learn More](https://github.com/Azure/MachineLearningNotebooks/tree/master/how-to-use-azureml/machine-learning-pipelines)\n", + "\n", + "\n", + "### Step 1: data preparation\n", + "\n", + "In step one, we will load the image and labels from Fashion MNIST dataset into mnist_train.csv and mnist_test.csv\n", + "\n", + "Each image is 28 pixels in height and 28 pixels in width, for a total of 784 pixels in total. Each pixel has a single pixel-value associated with it, indicating the lightness or darkness of that pixel, with higher numbers meaning darker. This pixel-value is an integer between 0 and 255. Both mnist_train.csv and mnist_test.csv contain 785 columns. The first column consists of the class labels, which represent the article of clothing. The rest of the columns contain the pixel-values of the associated image." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# set up the compute environment to install required packages\n", + "conda = CondaDependencies.create(\n", + " pip_packages=['azureml-sdk','azureml-dataprep[fuse,pandas]'],\n", + " pin_sdk_version=False)\n", + "\n", + "conda.set_pip_option('--pre')\n", + "\n", + "run_config = RunConfiguration()\n", + "run_config.environment.python.conda_dependencies = conda" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Intermediate data (or output of a step) is represented by a `PipelineData` object. preprared_fashion_ds is produced as the output of step 1, and used as the input of step 2. PipelineData introduces a data dependency between steps, and creates an implicit execution order in the pipeline. You can register a `PipelineData` as a dataset and version the output data automatically. [Learn More](https://docs.microsoft.com/azure/machine-learning/service/how-to-version-track-datasets#version-a-pipeline-output-dataset) " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# define output data\n", + "prepared_fashion_ds = PipelineData('prepared_fashion_ds', datastore=datastore).as_dataset()\n", + "\n", + "# register output data as dataset\n", + "prepared_fashion_ds = prepared_fashion_ds.register(name='prepared_fashion_ds', create_new_version=True)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "A **PythonScriptStep** is a basic, built-in step to run a Python Script on a compute target. It takes a script name and optionally other parameters like arguments for the script, compute target, inputs and outputs. If no compute target is specified, default compute target for the workspace is used. You can also use a [**RunConfiguration**](https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.runconfiguration?view=azure-ml-py) to specify requirements for the PythonScriptStep, such as conda dependencies and docker image." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "prep_step = PythonScriptStep(name='prepare step',\n", + " script_name=\"prepare.py\",\n", + " # mount fashion_ds dataset to the compute_target\n", + " inputs=[fashion_ds.as_named_input('fashion_ds').as_mount()],\n", + " outputs=[prepared_fashion_ds],\n", + " source_directory=script_folder,\n", + " compute_target=compute_target,\n", + " runconfig=run_config)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Step 2: train CNN with Keras\n", + "\n", + "Next, we construct an `azureml.train.dnn.TensorFlow` estimator object. The TensorFlow estimator is providing a simple way of launching a TensorFlow training job on a compute target. It will automatically provide a docker image that has TensorFlow installed.\n", + "\n", + "[EstimatorStep](https://docs.microsoft.com/en-us/python/api/azureml-pipeline-steps/azureml.pipeline.steps.estimator_step.estimatorstep?view=azure-ml-py) adds a step to run Tensorflow Estimator in a Pipeline. It takes a dataset as the input." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# set up training step with Tensorflow estimator\n", + "est = TensorFlow(entry_script='train.py',\n", + " source_directory=script_folder, \n", + " pip_packages = ['azureml-sdk','keras','numpy','scikit-learn', 'matplotlib'],\n", + " compute_target=compute_target)\n", + "\n", + "est_step = EstimatorStep(name='train step',\n", + " estimator=est,\n", + " estimator_entry_script_arguments=[],\n", + " # parse prepared_fashion_ds into TabularDataset and use it as the input\n", + " inputs=[prepared_fashion_ds.parse_delimited_files()],\n", + " compute_target=compute_target)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Build the pipeline\n", + "Once we have the steps (or steps collection), we can build the [pipeline](https://docs.microsoft.com/python/api/azureml-pipeline-core/azureml.pipeline.core.pipeline.pipeline?view=azure-ml-py).\n", + "\n", + "A pipeline is created with a list of steps and a workspace. Submit a pipeline using [submit](https://docs.microsoft.com/python/api/azureml-core/azureml.core.experiment(class)?view=azure-ml-py#submit-config--tags-none----kwargs-). When submit is called, a [PipelineRun](https://docs.microsoft.com/python/api/azureml-pipeline-core/azureml.pipeline.core.pipelinerun?view=azure-ml-py) is created which in turn creates [StepRun](https://docs.microsoft.com/python/api/azureml-pipeline-core/azureml.pipeline.core.steprun?view=azure-ml-py) objects for each step in the workflow." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# build pipeline & run experiment\n", + "pipeline = Pipeline(workspace, steps=[prep_step, est_step])\n", + "run = exp.submit(pipeline)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Monitor the PipelineRun" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "inputHidden": false, + "outputHidden": false + }, + "outputs": [], + "source": [ + "run.wait_for_completion(show_output=True)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run.find_step_run('train step')[0].get_metrics()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Register the input dataset and the output model" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Azure Machine Learning dataset makes it easy to trace how your data is used in ML. [Learn More](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-version-track-datasets#track-datasets-in-experiments)
\n", + "For each Machine Learning experiment, you can easily trace the datasets used as the input through `Run` object." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# get input datasets\n", + "prep_step = run.find_step_run('prepare step')[0]\n", + "inputs = prep_step.get_details()['inputDatasets']\n", + "input_dataset = inputs[0]['dataset']\n", + "\n", + "# list the files referenced by input_dataset\n", + "input_dataset.to_path()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Register the input Fashion MNIST dataset with the workspace so that you can reuse it in other experiments or share it with your colleagues who have access to your workspace." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "fashion_ds = input_dataset.register(workspace = workspace,\n", + " name = 'fashion_ds',\n", + " description = 'image and label files from fashion mnist',\n", + " create_new_version = True)\n", + "fashion_ds" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Register the output model with dataset" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run.find_step_run('train step')[0].register_model(model_name = 'keras-model', model_path = 'outputs/model/', \n", + " datasets =[('train test data',fashion_ds)])" + ] + } + ], + "metadata": { + "authors": [ + { + "name": "sihhu" + } + ], + "category": "tutorial", + "compute": [ + "Remote" + ], + "datasets": [ + "Fashion MNIST" + ], + "deployment": [ + "None" + ], + "exclude_from_index": false, + "framework": [ + "Azure ML" + ], + "friendly_name": "Datasets with ML Pipeline", + "index_order": 1, + "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.9" + }, + "nteract": { + "version": "nteract-front-end@1.0.0" + }, + "star_tag": [ + "featured" + ], + "tags": [ + "Dataset", + "Pipeline", + "Estimator", + "ScriptRun" + ], + "task": "Train" + }, + "nbformat": 4, + "nbformat_minor": 2 +} \ No newline at end of file diff --git a/how-to-use-azureml/work-with-data/datasets-tutorial/pipeline-with-datasets/pipeline-for-image-classification.yml b/how-to-use-azureml/work-with-data/datasets-tutorial/pipeline-with-datasets/pipeline-for-image-classification.yml new file mode 100644 index 000000000..a73794455 --- /dev/null +++ b/how-to-use-azureml/work-with-data/datasets-tutorial/pipeline-with-datasets/pipeline-for-image-classification.yml @@ -0,0 +1,7 @@ +name: pipeline-for-image-classification +dependencies: +- pip: + - azureml-sdk + - azureml-dataprep + - pandas + - fuse diff --git a/how-to-use-azureml/work-with-data/datasets-tutorial/timeseries-datasets/tabular-timeseries-dataset-filtering.ipynb b/how-to-use-azureml/work-with-data/datasets-tutorial/timeseries-datasets/tabular-timeseries-dataset-filtering.ipynb new file mode 100644 index 000000000..7f909acdb --- /dev/null +++ b/how-to-use-azureml/work-with-data/datasets-tutorial/timeseries-datasets/tabular-timeseries-dataset-filtering.ipynb @@ -0,0 +1,594 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Tabular Time Series Related API Demo with NOAA Weather Data" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Copyright (c) Microsoft Corporation. All rights reserved.
\n", + "Licensed under the MIT License." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In this notebook, you will learn how to use the Tabular Time Series related API to filter the data by time windows for sample data uploaded to Azure blob storage. \n", + "\n", + "The detailed APIs to be demoed in this script are:\n", + "- Create Tabular Dataset instance\n", + "- Assign fine timestamp column and coarse timestamp column for Tabular Dataset to activate Time Series related APIs\n", + "- Clear fine timestamp column and coarse timestamp column\n", + "- Filter in data before a specific time\n", + "- Filter in data after a specific time\n", + "- Filter in data in a specific time range\n", + "- Filter in data for recent time range\n", + "\n", + "Besides above APIs, you'll also see:\n", + "- Create and load a Workspace\n", + "- Load weather data into Azure blob storage\n", + "- Create and register weather data as a Tabular dataset\n", + "- Re-load Tabular Dataset from your Workspace" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Import Dependencies\n", + "\n", + "If you are using an Azure Machine Learning Notebook VM, you are all set. Otherwise, run the cells below to install the Azure Machine Learning Python SDK and create an Azure ML Workspace that's required for this demo." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Prepare Environment" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Print out your version of the Azure ML Python SDK. Version 1.0.60 or above is required for TabularDataset with timeseries attribute. " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import azureml.core\n", + "azureml.data.__version__" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Import Packages" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# import packages\n", + "import os\n", + "\n", + "import pandas as pd\n", + "\n", + "from calendar import monthrange\n", + "from datetime import datetime, timedelta\n", + "\n", + "from azureml.core import Dataset, Datastore, Workspace, Run" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Set up Configuraton and Create Azure ML Workspace\n", + "\n", + "If you are using an Azure Machine Learning Notebook VM, you are all set. Otherwise, go through the [configuration notebook](https://github.com/Azure/MachineLearningNotebooks/blob/master/configuration.ipynb) first if you haven't already to establish your connection to the Azure ML Workspace." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "ws = Workspace.from_config()\n", + "dstore = ws.get_default_datastore()\n", + "\n", + "dset_name = 'weather-data-florida'\n", + "\n", + "print(ws.name, ws.resource_group, ws.location, ws.subscription_id, dstore.name, sep = '\\n')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Load Data to Blob Storage\n", + "\n", + "This demo uses 2019 weather data under within weather-data folder. You can replace this data with your own." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Upload data to blob storage so it can be used as a Dataset." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "dstore.upload('weather-data', dset_name, overwrite=True, show_progress=True)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Create & Register Tabular Dataset with time-series trait from Blob\n", + "\n", + "The API on Tabular datasets with time-series trait is specially designed to handle Tabular time-series data and time related operations more efficiently. By registering your time-series dataset, you are publishing your dataset to your workspace so that it is accessible to anyone with the same subscription id. " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Create Tabular Dataset instance from blob storage datapath.\n", + "\n", + "**TIP:** you can set virtual columns in the partition_format. I.e. if you partition the weather data by state and city, the path can be '/{STATE}/{CITY}/{coarse_time:yyy/MM}/data.parquet'. STATE and CITY would then appear as virtual columns in the dataset, allowing for efficient filtering by these grains. " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "datastore_path = [(dstore, dset_name + '/*/*/data.parquet')]\n", + "dataset = Dataset.Tabular.from_parquet_files(path=datastore_path, partition_format = dset_name + '/{coarse_time:yyyy/MM}/data.parquet')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Assign fine timestamp column for Tabular Dataset to activate Time Series related APIs. The column to be assigned should be a Date type, otherwise the assigning will fail." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# for this demo, leave out coarse_time so fine_grain_timestamp is used\n", + "tsd = dataset.with_timestamp_columns(fine_grain_timestamp='datetime') # coarse_grain_timestamp='coarse_time')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Register the dataset for easy access from anywhere in Azure ML and to keep track of versions, lineage. " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# register dataset to Workspace\n", + "registered_ds = tsd.register(ws, dset_name, create_new_version=True, description='Data for Tabular Dataset with time-series trait demo.', tags={ 'type': 'TabularDataset' })" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Reload the Dataset from Workspace" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# get dataset by dataset name\n", + "tsd = Dataset.get_by_name(ws, name=dset_name)\n", + "tsd.to_pandas_dataframe().head(5)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Filter Data by Time Windows\n", + "\n", + "Once your data has been loaded into the notebook, you can query by time using the time_before(), time_after(), time_between(), and time_recent() functions. You can also choose to drop or keep certain columns. " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Before Time Input" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# select data that occurs before a specified date\n", + "tsd2 = tsd.time_before(datetime(2019, 6, 12))\n", + "tsd2.to_pandas_dataframe().tail(5)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## After Time Input" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# select data that occurs after a specified date\n", + "tsd2 = tsd.time_after(datetime(2019, 5, 30))\n", + "tsd2.to_pandas_dataframe().head(5)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Before & After Time Inputs\n", + "\n", + "You can chain time functions together." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**NOTE:** You must set the coarse_grain_timestamp to None to filter on the fine_grain_timestamp. The below cell will fail unless the second line is uncommented " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# select data that occurs within a given time range\n", + "#tsd = tsd.with_timestamp_columns(fine_grain_timestamp='datetime', coarse_grain_timestamp=None)\n", + "tsd2 = tsd.time_after(datetime(2019, 1, 2)).time_before(datetime(2019, 1, 10))\n", + "tsd2.to_pandas_dataframe().head(5)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Time Range Input" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# another way to select data that occurs within a given time range\n", + "tsd2 = tsd.time_between(start_time=datetime(2019, 1, 31, 23, 59, 59), end_time=datetime(2019, 2, 7))\n", + "tsd2.to_pandas_dataframe().head(5)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Time Recent Input" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This function takes in a datetime.timedelta and returns a dataset containing the data from datetime.now()-timedelta() to datetime.now()." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "tsd2 = tsd.time_recent(timedelta(weeks=5, days=0))\n", + "tsd2.to_pandas_dataframe().head(5)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**NOTE:** This will return an empty dataframe there is no data within the last 2 days." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "tsd2 = tsd.time_recent(timedelta(days=2))\n", + "tsd2.to_pandas_dataframe().tail(5)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Drop Columns" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "If a timeseries column is dropped, the corresponding capabilities will be dropped for the returned dataset.
" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "scrolled": true + }, + "outputs": [], + "source": [ + "tsd2 = tsd.drop_columns(columns=['snowDepth', 'version', 'datetime'])\n", + "tsd2.take(5).to_pandas_dataframe()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The exception is expected because dataset loses timeseries capabilities to do time travel." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "try:\n", + " tsd2.time_before(datetime(2019, 6, 12)).to_pandas_dataframe().tail(5)\n", + "except Exception as e:\n", + " print('Expected exception : {}'.format(str(e)))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Drop will return dataset with timeseries capabilities if modify column list to exclude timestamp columns." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "tsd2 = tsd.drop_columns(columns=['snowDepth', 'version', 'upload_date'])\n", + "tsd2.take(5).to_pandas_dataframe()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "tsd2.time_before(datetime(2019, 6, 12)).to_pandas_dataframe().tail(5)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Keep Columns" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "If a timeseries column is not included, the timeseries capabilities will be dropped for the returned dataset.
" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "tsd2 = tsd.keep_columns(columns=['snowDepth'], validate=False)\n", + "tsd2.to_pandas_dataframe().tail()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The exception is expected because dataset loses timeseries capabilities to do time travel." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "try:\n", + " tsd2.time_before(datetime(2019, 6, 12)).to_pandas_dataframe().tail(5)\n", + "except Exception as e:\n", + " print('Expected exception : {}'.format(str(e)))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Keep will return dataset with timeseries capabilities if modify column list to include timestamp columns." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "tsd2 = tsd.keep_columns(columns=['snowDepth', 'datetime', 'coarse_time'], validate=False)\n", + "tsd2.to_pandas_dataframe().tail()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "tsd2.time_before(datetime(2019, 6, 12)).to_pandas_dataframe().tail(5)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Resetting Timestamp Columns" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Rules for reseting are:\n", + "- You cannot assign 'None' to fine_grain_timestamp while assign a valid column name to coarse_grain_timestamp because coarse_grain_timestamp is optional while fine_grain_timestamp is mandatory for Tabular time series data.\n", + "- If you assign 'None' to fine_grain_timestamp, then both fine_grain_timestamp and coarse_grain_timestamp will all be cleared.\n", + "- If you assign only 'None' to coarse_grain_timestamp, then only coarse_grain_timestamp will be cleared." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Illegal clearing, exception is expected.\n", + "try:\n", + " tsd2 = tsd.with_timestamp_columns(fine_grain_timestamp=None, coarse_grain_timestamp='coarse_time')\n", + "except Exception as e:\n", + " print('Cleaning not allowed because {}'.format(str(e)))\n", + "\n", + "# clear both\n", + "tsd2 = tsd.with_timestamp_columns(fine_grain_timestamp=None, coarse_grain_timestamp=None)\n", + "print('after clean both with None/None, timestamp columns are: {}'.format(tsd2.timestamp_columns))\n", + "\n", + "# clear coarse_grain_timestamp only and assign 'datetime' as fine timestamp column\n", + "tsd2 = tsd2.with_timestamp_columns(fine_grain_timestamp='datetime', coarse_grain_timestamp=None)\n", + "print('after clean coarse timestamp column, timestamp columns are: {}'.format(tsd2.timestamp_columns))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/work-with-data/datasets-tutorial/datasets-tutorial.png)" + ] + } + ], + "metadata": { + "authors": [ + { + "name": "ylxiong" + } + ], + "category": "tutorial", + "compute": [ + "Local" + ], + "datasets": [ + "NOAA" + ], + "deployment": [ + "None" + ], + "exclude_from_index": false, + "framework": [ + "Azure ML" + ], + "friendly_name": "Filtering data using Tabular Timeseiries Dataset related API", + "index_order": 1, + "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" + }, + "notice": "Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License.", + "star_tag": [ + "featured" + ], + "tags": [ + "Dataset", + "Tabular Timeseries" + ], + "task": "Filtering" + }, + "nbformat": 4, + "nbformat_minor": 2 +} \ No newline at end of file diff --git a/how-to-use-azureml/work-with-data/datasets-tutorial/timeseries-datasets/tabular-timeseries-dataset-filtering.yml b/how-to-use-azureml/work-with-data/datasets-tutorial/timeseries-datasets/tabular-timeseries-dataset-filtering.yml new file mode 100644 index 000000000..96daf4fbd --- /dev/null +++ b/how-to-use-azureml/work-with-data/datasets-tutorial/timeseries-datasets/tabular-timeseries-dataset-filtering.yml @@ -0,0 +1,6 @@ +name: tabular-timeseries-dataset-filtering +dependencies: +- pip: + - azureml-sdk + - azureml-dataprep + - pandas diff --git a/how-to-use-azureml/work-with-data/datasets-tutorial/timeseries-datasets/weather-data/2019/01/data.parquet b/how-to-use-azureml/work-with-data/datasets-tutorial/timeseries-datasets/weather-data/2019/01/data.parquet new file mode 100644 index 000000000..0f2e4be50 Binary files /dev/null and b/how-to-use-azureml/work-with-data/datasets-tutorial/timeseries-datasets/weather-data/2019/01/data.parquet differ diff --git a/how-to-use-azureml/work-with-data/datasets-tutorial/timeseries-datasets/weather-data/2019/02/data.parquet b/how-to-use-azureml/work-with-data/datasets-tutorial/timeseries-datasets/weather-data/2019/02/data.parquet new file mode 100644 index 000000000..ff6b97afd Binary files /dev/null and b/how-to-use-azureml/work-with-data/datasets-tutorial/timeseries-datasets/weather-data/2019/02/data.parquet differ diff --git a/how-to-use-azureml/work-with-data/datasets-tutorial/timeseries-datasets/weather-data/2019/03/data.parquet b/how-to-use-azureml/work-with-data/datasets-tutorial/timeseries-datasets/weather-data/2019/03/data.parquet new file mode 100644 index 000000000..b93cea1f7 Binary files /dev/null and b/how-to-use-azureml/work-with-data/datasets-tutorial/timeseries-datasets/weather-data/2019/03/data.parquet differ diff --git a/how-to-use-azureml/work-with-data/datasets-tutorial/timeseries-datasets/weather-data/2019/04/data.parquet b/how-to-use-azureml/work-with-data/datasets-tutorial/timeseries-datasets/weather-data/2019/04/data.parquet new file mode 100644 index 000000000..257eedc50 Binary files /dev/null and b/how-to-use-azureml/work-with-data/datasets-tutorial/timeseries-datasets/weather-data/2019/04/data.parquet differ diff --git a/how-to-use-azureml/work-with-data/datasets-tutorial/timeseries-datasets/weather-data/2019/05/data.parquet b/how-to-use-azureml/work-with-data/datasets-tutorial/timeseries-datasets/weather-data/2019/05/data.parquet new file mode 100644 index 000000000..9ea22a883 Binary files /dev/null and b/how-to-use-azureml/work-with-data/datasets-tutorial/timeseries-datasets/weather-data/2019/05/data.parquet differ diff --git a/how-to-use-azureml/work-with-data/datasets-tutorial/timeseries-datasets/weather-data/2019/06/data.parquet b/how-to-use-azureml/work-with-data/datasets-tutorial/timeseries-datasets/weather-data/2019/06/data.parquet new file mode 100644 index 000000000..aa4d8a923 Binary files /dev/null and b/how-to-use-azureml/work-with-data/datasets-tutorial/timeseries-datasets/weather-data/2019/06/data.parquet differ diff --git a/how-to-use-azureml/work-with-data/datasets-tutorial/timeseries-datasets/weather-data/2019/07/data.parquet b/how-to-use-azureml/work-with-data/datasets-tutorial/timeseries-datasets/weather-data/2019/07/data.parquet new file mode 100644 index 000000000..a92ccd0db Binary files /dev/null and b/how-to-use-azureml/work-with-data/datasets-tutorial/timeseries-datasets/weather-data/2019/07/data.parquet differ diff --git a/how-to-use-azureml/work-with-data/datasets-tutorial/timeseries-datasets/weather-data/2019/08/data.parquet b/how-to-use-azureml/work-with-data/datasets-tutorial/timeseries-datasets/weather-data/2019/08/data.parquet new file mode 100644 index 000000000..8328d0397 Binary files /dev/null and b/how-to-use-azureml/work-with-data/datasets-tutorial/timeseries-datasets/weather-data/2019/08/data.parquet differ diff --git a/how-to-use-azureml/work-with-data/datasets-tutorial/timeseries-datasets/weather-data/2019/09/data.parquet b/how-to-use-azureml/work-with-data/datasets-tutorial/timeseries-datasets/weather-data/2019/09/data.parquet new file mode 100644 index 000000000..9ee3faa07 Binary files /dev/null and b/how-to-use-azureml/work-with-data/datasets-tutorial/timeseries-datasets/weather-data/2019/09/data.parquet differ diff --git a/how-to-use-azureml/work-with-data/datasets-tutorial/timeseries-datasets/weather-data/2019/10/data.parquet b/how-to-use-azureml/work-with-data/datasets-tutorial/timeseries-datasets/weather-data/2019/10/data.parquet new file mode 100644 index 000000000..7635534c6 Binary files /dev/null and b/how-to-use-azureml/work-with-data/datasets-tutorial/timeseries-datasets/weather-data/2019/10/data.parquet differ diff --git a/how-to-use-azureml/work-with-data/datasets-tutorial/train-with-datasets/train-dataset/iris.csv b/how-to-use-azureml/work-with-data/datasets-tutorial/train-with-datasets/train-dataset/iris.csv new file mode 100644 index 000000000..21ae19637 --- /dev/null +++ b/how-to-use-azureml/work-with-data/datasets-tutorial/train-with-datasets/train-dataset/iris.csv @@ -0,0 +1,151 @@ +sepal_length,sepal_width,petal_length,petal_width,species +5.1,3.5,1.4,0.2,Iris-setosa +4.9,3,1.4,0.2,Iris-setosa +4.7,3.2,1.3,0.2,Iris-setosa +4.6,3.1,1.5,0.2,Iris-setosa +5,3.6,1.4,0.2,Iris-setosa +5.4,3.9,1.7,0.4,Iris-setosa +4.6,3.4,1.4,0.3,Iris-setosa +5,3.4,1.5,0.2,Iris-setosa +4.4,2.9,1.4,0.2,Iris-setosa +4.9,3.1,1.5,0.1,Iris-setosa +5.4,3.7,1.5,0.2,Iris-setosa +4.8,3.4,1.6,0.2,Iris-setosa +4.8,3,1.4,0.1,Iris-setosa +4.3,3,1.1,0.1,Iris-setosa +5.8,4,1.2,0.2,Iris-setosa +5.7,4.4,1.5,0.4,Iris-setosa +5.4,3.9,1.3,0.4,Iris-setosa +5.1,3.5,1.4,0.3,Iris-setosa +5.7,3.8,1.7,0.3,Iris-setosa +5.1,3.8,1.5,0.3,Iris-setosa +5.4,3.4,1.7,0.2,Iris-setosa +5.1,3.7,1.5,0.4,Iris-setosa +4.6,3.6,1,0.2,Iris-setosa +5.1,3.3,1.7,0.5,Iris-setosa +4.8,3.4,1.9,0.2,Iris-setosa +5,3,1.6,0.2,Iris-setosa +5,3.4,1.6,0.4,Iris-setosa +5.2,3.5,1.5,0.2,Iris-setosa +5.2,3.4,1.4,0.2,Iris-setosa +4.7,3.2,1.6,0.2,Iris-setosa +4.8,3.1,1.6,0.2,Iris-setosa +5.4,3.4,1.5,0.4,Iris-setosa +5.2,4.1,1.5,0.1,Iris-setosa +5.5,4.2,1.4,0.2,Iris-setosa +4.9,3.1,1.5,0.1,Iris-setosa +5,3.2,1.2,0.2,Iris-setosa +5.5,3.5,1.3,0.2,Iris-setosa +4.9,3.1,1.5,0.1,Iris-setosa +4.4,3,1.3,0.2,Iris-setosa +5.1,3.4,1.5,0.2,Iris-setosa +5,3.5,1.3,0.3,Iris-setosa +4.5,2.3,1.3,0.3,Iris-setosa +4.4,3.2,1.3,0.2,Iris-setosa +5,3.5,1.6,0.6,Iris-setosa +5.1,3.8,1.9,0.4,Iris-setosa +4.8,3,1.4,0.3,Iris-setosa +5.1,3.8,1.6,0.2,Iris-setosa +4.6,3.2,1.4,0.2,Iris-setosa +5.3,3.7,1.5,0.2,Iris-setosa +5,3.3,1.4,0.2,Iris-setosa +7,3.2,4.7,1.4,Iris-versicolor +6.4,3.2,4.5,1.5,Iris-versicolor +6.9,3.1,4.9,1.5,Iris-versicolor +5.5,2.3,4,1.3,Iris-versicolor +6.5,2.8,4.6,1.5,Iris-versicolor +5.7,2.8,4.5,1.3,Iris-versicolor +6.3,3.3,4.7,1.6,Iris-versicolor +4.9,2.4,3.3,1,Iris-versicolor +6.6,2.9,4.6,1.3,Iris-versicolor +5.2,2.7,3.9,1.4,Iris-versicolor +5,2,3.5,1,Iris-versicolor +5.9,3,4.2,1.5,Iris-versicolor +6,2.2,4,1,Iris-versicolor +6.1,2.9,4.7,1.4,Iris-versicolor +5.6,2.9,3.6,1.3,Iris-versicolor +6.7,3.1,4.4,1.4,Iris-versicolor +5.6,3,4.5,1.5,Iris-versicolor +5.8,2.7,4.1,1,Iris-versicolor +6.2,2.2,4.5,1.5,Iris-versicolor +5.6,2.5,3.9,1.1,Iris-versicolor +5.9,3.2,4.8,1.8,Iris-versicolor +6.1,2.8,4,1.3,Iris-versicolor +6.3,2.5,4.9,1.5,Iris-versicolor +6.1,2.8,4.7,1.2,Iris-versicolor +6.4,2.9,4.3,1.3,Iris-versicolor +6.6,3,4.4,1.4,Iris-versicolor +6.8,2.8,4.8,1.4,Iris-versicolor +6.7,3,5,1.7,Iris-versicolor +6,2.9,4.5,1.5,Iris-versicolor +5.7,2.6,3.5,1,Iris-versicolor +5.5,2.4,3.8,1.1,Iris-versicolor +5.5,2.4,3.7,1,Iris-versicolor +5.8,2.7,3.9,1.2,Iris-versicolor +6,2.7,5.1,1.6,Iris-versicolor +5.4,3,4.5,1.5,Iris-versicolor +6,3.4,4.5,1.6,Iris-versicolor +6.7,3.1,4.7,1.5,Iris-versicolor +6.3,2.3,4.4,1.3,Iris-versicolor +5.6,3,4.1,1.3,Iris-versicolor +5.5,2.5,4,1.3,Iris-versicolor +5.5,2.6,4.4,1.2,Iris-versicolor +6.1,3,4.6,1.4,Iris-versicolor +5.8,2.6,4,1.2,Iris-versicolor +5,2.3,3.3,1,Iris-versicolor +5.6,2.7,4.2,1.3,Iris-versicolor +5.7,3,4.2,1.2,Iris-versicolor +5.7,2.9,4.2,1.3,Iris-versicolor +6.2,2.9,4.3,1.3,Iris-versicolor +5.1,2.5,3,1.1,Iris-versicolor +5.7,2.8,4.1,1.3,Iris-versicolor +6.3,3.3,6,2.5,Iris-virginica +5.8,2.7,5.1,1.9,Iris-virginica +7.1,3,5.9,2.1,Iris-virginica +6.3,2.9,5.6,1.8,Iris-virginica +6.5,3,5.8,2.2,Iris-virginica +7.6,3,6.6,2.1,Iris-virginica +4.9,2.5,4.5,1.7,Iris-virginica +7.3,2.9,6.3,1.8,Iris-virginica +6.7,2.5,5.8,1.8,Iris-virginica +7.2,3.6,6.1,2.5,Iris-virginica +6.5,3.2,5.1,2,Iris-virginica +6.4,2.7,5.3,1.9,Iris-virginica +6.8,3,5.5,2.1,Iris-virginica +5.7,2.5,5,2,Iris-virginica +5.8,2.8,5.1,2.4,Iris-virginica +6.4,3.2,5.3,2.3,Iris-virginica +6.5,3,5.5,1.8,Iris-virginica +7.7,3.8,6.7,2.2,Iris-virginica +7.7,2.6,6.9,2.3,Iris-virginica +6,2.2,5,1.5,Iris-virginica +6.9,3.2,5.7,2.3,Iris-virginica +5.6,2.8,4.9,2,Iris-virginica +7.7,2.8,6.7,2,Iris-virginica +6.3,2.7,4.9,1.8,Iris-virginica +6.7,3.3,5.7,2.1,Iris-virginica +7.2,3.2,6,1.8,Iris-virginica +6.2,2.8,4.8,1.8,Iris-virginica +6.1,3,4.9,1.8,Iris-virginica +6.4,2.8,5.6,2.1,Iris-virginica +7.2,3,5.8,1.6,Iris-virginica +7.4,2.8,6.1,1.9,Iris-virginica +7.9,3.8,6.4,2,Iris-virginica +6.4,2.8,5.6,2.2,Iris-virginica +6.3,2.8,5.1,1.5,Iris-virginica +6.1,2.6,5.6,1.4,Iris-virginica +7.7,3,6.1,2.3,Iris-virginica +6.3,3.4,5.6,2.4,Iris-virginica +6.4,3.1,5.5,1.8,Iris-virginica +6,3,4.8,1.8,Iris-virginica +6.9,3.1,5.4,2.1,Iris-virginica +6.7,3.1,5.6,2.4,Iris-virginica +6.9,3.1,5.1,2.3,Iris-virginica +5.8,2.7,5.1,1.9,Iris-virginica +6.8,3.2,5.9,2.3,Iris-virginica +6.7,3.3,5.7,2.5,Iris-virginica +6.7,3,5.2,2.3,Iris-virginica +6.3,2.5,5,1.9,Iris-virginica +6.5,3,5.2,2,Iris-virginica +6.2,3.4,5.4,2.3,Iris-virginica +5.9,3,5.1,1.8,Iris-virginica diff --git a/how-to-use-azureml/work-with-data/datasets-tutorial/train-with-datasets/train-with-datasets.ipynb b/how-to-use-azureml/work-with-data/datasets-tutorial/train-with-datasets/train-with-datasets.ipynb new file mode 100644 index 000000000..5dfbff642 --- /dev/null +++ b/how-to-use-azureml/work-with-data/datasets-tutorial/train-with-datasets/train-with-datasets.ipynb @@ -0,0 +1,657 @@ +{ + "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/work-with-data/datasets-tutorial/train-with-datasets/train-with-datasets.png)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Train with Azure Machine Learning datasets\n", + "Datasets are categorized into TabularDataset and FileDataset based on how users consume them in training. \n", + "* A TabularDataset represents data in a tabular format by parsing the provided file or list of files. TabularDataset can be created from csv, tsv, parquet files, SQL query results etc. For the complete list, please visit our [documentation](https://aka.ms/tabulardataset-api-reference). It provides you with the ability to materialize the data into a pandas DataFrame.\n", + "* A FileDataset references single or multiple files in your datastores or public urls. This provides you with the ability to download or mount the files to your compute. The files can be of any format, which enables a wider range of machine learning scenarios including deep learning.\n", + "\n", + "In this tutorial, you will learn how to train with Azure Machine Learning datasets:\n", + "\n", + "☑ Use datasets directly in your training script\n", + "\n", + "☑ Use datasets to mount files to a remote compute" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Prerequisites\n", + "If you are using an Azure Machine Learning Notebook VM, you are all set. Otherwise, go through the [configuration notebook](../../../configuration.ipynb) first if you haven't already established your connection to the AzureML Workspace." + ] + }, + { + "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": [ + "## Initialize Workspace\n", + "\n", + "Initialize a workspace object from persisted configuration." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from azureml.core import Workspace\n", + "\n", + "ws = Workspace.from_config()\n", + "print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep='\\n')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Create Experiment\n", + "\n", + "**Experiment** is a logical container in an Azure ML Workspace. It hosts run records which can include run metrics and output artifacts from your experiments." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "experiment_name = 'train-with-datasets'\n", + "\n", + "from azureml.core import Experiment\n", + "exp = Experiment(workspace=ws, name=experiment_name)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Create or Attach existing compute resource\n", + "By using Azure Machine Learning Compute, 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 Azure Machine Learning Compute as your training environment. The code below creates the compute clusters for you if they don't already exist in your workspace.\n", + "\n", + "**Creation of compute takes approximately 5 minutes.** If the AmlCompute with that name is already in your workspace the code will skip the creation process." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from azureml.core.compute import AmlCompute\n", + "from azureml.core.compute import ComputeTarget\n", + "import os\n", + "\n", + "# choose a name for your cluster\n", + "compute_name = os.environ.get('AML_COMPUTE_CLUSTER_NAME', 'cpu-cluster')\n", + "compute_min_nodes = os.environ.get('AML_COMPUTE_CLUSTER_MIN_NODES', 0)\n", + "compute_max_nodes = os.environ.get('AML_COMPUTE_CLUSTER_MAX_NODES', 4)\n", + "\n", + "# This example uses CPU VM. For using GPU VM, set SKU to STANDARD_NC6\n", + "vm_size = os.environ.get('AML_COMPUTE_CLUSTER_SKU', 'STANDARD_D2_V2')\n", + "\n", + "\n", + "if compute_name in ws.compute_targets:\n", + " compute_target = ws.compute_targets[compute_name]\n", + " if compute_target and type(compute_target) is AmlCompute:\n", + " print('found compute target. just use it. ' + compute_name)\n", + "else:\n", + " print('creating a new compute target...')\n", + " provisioning_config = AmlCompute.provisioning_configuration(vm_size=vm_size,\n", + " min_nodes=compute_min_nodes, \n", + " max_nodes=compute_max_nodes)\n", + "\n", + " # create the cluster\n", + " compute_target = ComputeTarget.create(ws, compute_name, provisioning_config)\n", + " \n", + " # can poll for a minimum number of nodes and for a specific timeout. \n", + " # if no min node count is provided it will use the scale settings for the cluster\n", + " compute_target.wait_for_completion(show_output=True, min_node_count=None, timeout_in_minutes=20)\n", + " \n", + " # For a more detailed view of current AmlCompute status, use get_status()\n", + " print(compute_target.get_status().serialize())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You now have the necessary packages and compute resources to train a model in the cloud.\n", + "## Use datasets directly in training\n", + "\n", + "### Create a TabularDataset\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. \n", + "\n", + "Every workspace comes with a default [datastore](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-access-data) (and you can register more) which is backed by the Azure blob storage account associated with the workspace. We can use it to transfer data from local to the cloud, and create dataset from it. We will now upload the [Iris data](./train-dataset/Iris.csv) to the default datastore (blob) within your workspace." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "datastore = ws.get_default_datastore()\n", + "datastore.upload_files(files = ['./train-dataset/iris.csv'],\n", + " target_path = 'train-dataset/tabular/',\n", + " overwrite = True,\n", + " show_progress = True)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Then we will create an unregistered TabularDataset pointing to the path in the datastore. You can also create a dataset from multiple paths. [learn more](https://aka.ms/azureml/howto/createdatasets) \n", + "\n", + "[TabularDataset](https://docs.microsoft.com/python/api/azureml-core/azureml.data.tabulardataset?view=azure-ml-py) represents data in a tabular format by parsing the provided file or list of files. This provides you with the ability to materialize the data into a Pandas or Spark DataFrame. You can create a TabularDataset object from .csv, .tsv, and parquet files, and from SQL query results. For a complete list, see [TabularDatasetFactory](https://docs.microsoft.com/python/api/azureml-core/azureml.data.dataset_factory.tabulardatasetfactory?view=azure-ml-py) class." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "dataset-remarks-tabular-sample" + ] + }, + "outputs": [], + "source": [ + "from azureml.core import Dataset\n", + "dataset = Dataset.Tabular.from_delimited_files(path = [(datastore, 'train-dataset/tabular/iris.csv')])\n", + "\n", + "# preview the first 3 rows of the dataset\n", + "dataset.take(3).to_pandas_dataframe()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Create a training script\n", + "\n", + "To submit the job to the cluster, first create a training script. Run the following code to create the training script called `train_titanic.py` in the script_folder. " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "script_folder = os.path.join(os.getcwd(), 'train-dataset')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "%%writefile $script_folder/train_iris.py\n", + "\n", + "import os\n", + "\n", + "from azureml.core import Dataset, Run\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.externals import joblib\n", + "\n", + "run = Run.get_context()\n", + "# get input dataset by name\n", + "dataset = run.input_datasets['iris']\n", + "\n", + "df = dataset.to_pandas_dataframe()\n", + "\n", + "x_col = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width']\n", + "y_col = ['species']\n", + "x_df = df.loc[:, x_col]\n", + "y_df = df.loc[:, y_col]\n", + "\n", + "#dividing X,y into train and test data\n", + "x_train, x_test, y_train, y_test = train_test_split(x_df, y_df, test_size=0.2, random_state=223)\n", + "\n", + "data = {'train': {'X': x_train, 'y': y_train},\n", + "\n", + " 'test': {'X': x_test, 'y': y_test}}\n", + "\n", + "clf = DecisionTreeClassifier().fit(data['train']['X'], data['train']['y'])\n", + "model_file_name = 'decision_tree.pkl'\n", + "\n", + "print('Accuracy of Decision Tree classifier on training set: {:.2f}'.format(clf.score(x_train, y_train)))\n", + "print('Accuracy of Decision Tree classifier on test set: {:.2f}'.format(clf.score(x_test, y_test)))\n", + "\n", + "os.makedirs('./outputs', exist_ok=True)\n", + "with open(model_file_name, 'wb') as file:\n", + " joblib.dump(value=clf, filename='outputs/' + model_file_name)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Configure and use datasets as the input to Estimator" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "An estimator is a configuration object you submit to Azure Machine Learning to instruct how to set up the remote environment. Azure Machine Learning has pre-configured estimators for common machine learning frameworks, as well as generic Estimator. Create a SKLearn estimator by specifying:\n", + "\n", + "* The name of the estimator object, `est`\n", + "* The directory that contains your scripts. All the files in this directory are uploaded into the cluster nodes for execution. \n", + "* The training script name, train_titanic.py\n", + "* The input dataset for training. `as_named_input()` is required so that the input dataset can be referenced by the assigned name in your training script. \n", + "* The compute target. In this case you will use the AmlCompute you created\n", + "* The environment definition for the experiment" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from azureml.train.sklearn import SKLearn\n", + "\n", + "est = SKLearn(source_directory=script_folder, \n", + " entry_script='train_iris.py', \n", + " # pass dataset object as an input with name 'titanic'\n", + " inputs=[dataset.as_named_input('iris')],\n", + " pip_packages=['azureml-dataprep[fuse]'],\n", + " compute_target=compute_target) " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Submit job to run\n", + "Submit the estimator to the Azure ML experiment to kick off the execution." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run = exp.submit(est)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from azureml.widgets import RunDetails\n", + "\n", + "# monitor the run\n", + "RunDetails(run).show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Use datasets to mount files to a remote compute\n", + "\n", + "You can use the `Dataset` object to mount or download files referred by it. When you mount a file system, you attach that file system to a directory (mount point) and make it available to the system. Because mounting load files at the time of processing, it is usually faster than download.
\n", + "Note: mounting is only available for Linux-based compute (DSVM/VM, AMLCompute, HDInsights)." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Upload data files into datastore\n", + "We will first load diabetes data from `scikit-learn` to the train-dataset folder." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from sklearn.datasets import load_diabetes\n", + "import numpy as np\n", + "\n", + "training_data = load_diabetes()\n", + "np.save(file='train-dataset/features.npy', arr=training_data['data'])\n", + "np.save(file='train-dataset/labels.npy', arr=training_data['target'])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now let's upload the 2 files into the default datastore under a path named `diabetes`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "datastore.upload_files(['train-dataset/features.npy', 'train-dataset/labels.npy'], target_path='diabetes', overwrite=True)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Create a FileDataset\n", + "\n", + "[FileDataset](https://docs.microsoft.com/python/api/azureml-core/azureml.data.file_dataset.filedataset?view=azure-ml-py) references single or multiple files in your datastores or public URLs. Using this method, you can download or mount the files to your compute as a FileDataset object. The files can be in any format, which enables a wider range of machine learning scenarios, including deep learning." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from azureml.core import Dataset\n", + "\n", + "dataset = Dataset.File.from_files(path = [(datastore, 'diabetes/')])\n", + "\n", + "# see a list of files referenced by dataset\n", + "dataset.to_path()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Create a training script\n", + "\n", + "To submit the job to the cluster, first create a training script. Run the following code to create the training script called `train_diabetes.py` in the script_folder. " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "%%writefile $script_folder/train_diabetes.py\n", + "\n", + "import os\n", + "import glob\n", + "\n", + "from sklearn.linear_model import Ridge\n", + "from sklearn.metrics import mean_squared_error\n", + "from sklearn.model_selection import train_test_split\n", + "from azureml.core.run import Run\n", + "from sklearn.externals import joblib\n", + "\n", + "import numpy as np\n", + "\n", + "os.makedirs('./outputs', exist_ok=True)\n", + "\n", + "run = Run.get_context()\n", + "base_path = run.input_datasets['diabetes']\n", + "\n", + "X = np.load(glob.glob(os.path.join(base_path, '**/features.npy'), recursive=True)[0])\n", + "y = np.load(glob.glob(os.path.join(base_path, '**/labels.npy'), recursive=True)[0])\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(\n", + " X, y, test_size=0.2, random_state=0)\n", + "data = {'train': {'X': X_train, 'y': y_train},\n", + " 'test': {'X': X_test, 'y': y_test}}\n", + "\n", + "# list of numbers from 0.0 to 1.0 with a 0.05 interval\n", + "alphas = np.arange(0.0, 1.0, 0.05)\n", + "\n", + "for alpha in alphas:\n", + " # use Ridge algorithm to create a regression model\n", + " reg = Ridge(alpha=alpha)\n", + " reg.fit(data['train']['X'], data['train']['y'])\n", + "\n", + " preds = reg.predict(data['test']['X'])\n", + " mse = mean_squared_error(preds, data['test']['y'])\n", + " run.log('alpha', alpha)\n", + " run.log('mse', mse)\n", + "\n", + " model_file_name = 'ridge_{0:.2f}.pkl'.format(alpha)\n", + " with open(model_file_name, 'wb') as file:\n", + " joblib.dump(value=reg, filename='outputs/' + model_file_name)\n", + "\n", + " print('alpha is {0:.2f}, and mse is {1:0.2f}'.format(alpha, mse))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Configure & Run" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You can ask the system to build a conda environment based on your dependency specification. Once the environment is built, and if you don't change your dependencies, it will be reused in subsequent runs." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from azureml.core import Environment\n", + "from azureml.core.conda_dependencies import CondaDependencies\n", + "\n", + "conda_env = Environment('conda-env')\n", + "conda_env.python.conda_dependencies = CondaDependencies.create(pip_packages=['azureml-sdk',\n", + " 'azureml-dataprep[pandas,fuse]',\n", + " 'scikit-learn'])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from azureml.core import ScriptRunConfig\n", + "\n", + "src = ScriptRunConfig(source_directory=script_folder, \n", + " script='train_diabetes.py', \n", + " # to mount the dataset on the remote compute and pass the mounted path as an argument to the training script\n", + " arguments =[dataset.as_named_input('diabetes').as_mount()])\n", + "\n", + "src.run_config.framework = 'python'\n", + "src.run_config.environment = conda_env\n", + "src.run_config.target = compute_target.name" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "run = exp.submit(config=src)\n", + "\n", + "# monitor the run\n", + "RunDetails(run).show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Display run results\n", + "You now have a model trained on a remote cluster. Retrieve all the metrics logged during the run, including the accuracy of the model:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "print(run.get_metrics())\n", + "metrics = run.get_metrics()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Register datasets\n", + "Use the register() method to register datasets to your workspace so they can be shared with others, reused across various experiments, and referred to by name in your training script." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "dataset = dataset.register(workspace = ws,\n", + " name = 'diabetes dataset',\n", + " description='training dataset',\n", + " create_new_version=True)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Register models with datasets\n", + "The last step in the training script wrote the model files in a directory named `outputs` in the VM of the cluster where the job is executed. `outputs` is a special directory in that all content in this directory is automatically uploaded to your workspace. This content appears in the run record in the experiment under your workspace. Hence, the model file is now also available in your workspace.\n", + "\n", + "You can register models with datasets for reproducibility and auditing purpose." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# find the index where MSE is the smallest\n", + "indices = list(range(0, len(metrics['mse'])))\n", + "min_mse_index = min(indices, key=lambda x: metrics['mse'][x])\n", + "\n", + "print('When alpha is {1:0.2f}, we have min MSE {0:0.2f}.'.format(\n", + " metrics['mse'][min_mse_index], \n", + " metrics['alpha'][min_mse_index]\n", + "))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# find the best model\n", + "best_alpha = metrics['alpha'][min_mse_index]\n", + "model_file_name = 'ridge_{0:.2f}.pkl'.format(best_alpha)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# register the best model with the input dataset\n", + "model = run.register_model(model_name='sklearn_diabetes', model_path=os.path.join('outputs', model_file_name),\n", + " datasets =[('training data',dataset)])" + ] + } + ], + "metadata": { + "authors": [ + { + "name": "sihhu" + } + ], + "category": "tutorial", + "compute": [ + "Remote" + ], + "datasets": [ + "Iris", + "Diabetes" + ], + "deployment": [ + "None" + ], + "exclude_from_index": false, + "framework": [ + "Azure ML" + ], + "friendly_name": "Train with Datasets (Tabular and File)", + "index_order": 1, + "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.9" + }, + "star_tag": [ + "featured" + ], + "tags": [ + "Dataset", + "Estimator", + "ScriptRun" + ], + "task": "Train" + }, + "nbformat": 4, + "nbformat_minor": 2 +} \ No newline at end of file diff --git a/how-to-use-azureml/work-with-data/datasets-tutorial/train-with-datasets/train-with-datasets.yml b/how-to-use-azureml/work-with-data/datasets-tutorial/train-with-datasets/train-with-datasets.yml new file mode 100644 index 000000000..096a82b15 --- /dev/null +++ b/how-to-use-azureml/work-with-data/datasets-tutorial/train-with-datasets/train-with-datasets.yml @@ -0,0 +1,9 @@ +name: train-with-datasets +dependencies: +- pip: + - azureml-sdk + - azureml-widgets + - azureml-dataprep + - pandas + - fuse + - scikit-learn diff --git a/index.md b/index.md index 46b20a284..125111491 100644 --- a/index.md +++ b/index.md @@ -24,6 +24,10 @@ Machine Learning notebook samples and encourage efficient retrieval of topics an | :star:[Data drift on aks](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/monitor-models/data-drift/drift-on-aks.ipynb) | Filtering | NOAA | Remote | AKS | Azure ML | Dataset, Timeseries, Drift | | [Train and deploy a model using Python SDK](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/training/train-within-notebook/train-within-notebook.ipynb) | Training and deploying a model from a notebook | Diabetes | Local | Azure Container Instance | None | None | | :star:[Data drift quickdemo](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/work-with-data/datadrift-tutorial/datadrift-tutorial.ipynb) | Filtering | NOAA | Remote | None | Azure ML | Dataset, Timeseries, Drift | +| :star:[Introduction to labeled datasets](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/work-with-data/datasets-tutorial/labeled-datasets/labeled-datasets.ipynb) | Train | | Remote | None | Azure ML | Dataset, label, Estimator | +| :star:[Datasets with ML Pipeline](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/work-with-data/datasets-tutorial/pipeline-with-datasets/pipeline-for-image-classification.ipynb) | Train | Fashion MNIST | Remote | None | Azure ML | Dataset, Pipeline, Estimator, ScriptRun | +| :star:[Filtering data using Tabular Timeseiries Dataset related API](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/work-with-data/datasets-tutorial/timeseries-datasets/tabular-timeseries-dataset-filtering.ipynb) | Filtering | NOAA | Local | None | Azure ML | Dataset, Tabular Timeseries | +| :star:[Train with Datasets (Tabular and File)](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/work-with-data/datasets-tutorial/train-with-datasets/train-with-datasets.ipynb) | Train | Iris, Diabetes | Remote | None | Azure ML | Dataset, Estimator, ScriptRun | | [Forecasting away from training data](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/automated-machine-learning/forecasting-high-frequency/automl-forecasting-function.ipynb) | Forecasting | None | Remote | None | Azure ML AutoML | Forecasting, Confidence Intervals | | [Automated ML run with basic edition features.](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/automated-machine-learning/classification-bank-marketing-all-features/auto-ml-classification-bank-marketing-all-features.ipynb) | Classification | Bankmarketing | AML | ACI | None | featurization, explainability, remote_run, AutomatedML | | [Classification of credit card fraudulent transactions using Automated ML](https://github.com/Azure/MachineLearningNotebooks/blob/master//how-to-use-azureml/automated-machine-learning/classification-credit-card-fraud/auto-ml-classification-credit-card-fraud.ipynb) | Classification | Creditcard | AML Compute | None | None | remote_run, AutomatedML | diff --git a/setup-environment/configuration.ipynb b/setup-environment/configuration.ipynb index f16c4a8a8..9d441c61d 100644 --- a/setup-environment/configuration.ipynb +++ b/setup-environment/configuration.ipynb @@ -102,7 +102,7 @@ "source": [ "import azureml.core\n", "\n", - "print(\"This notebook was created using version 1.1.0rc0 of the Azure ML SDK\")\n", + "print(\"This notebook was created using version 1.1.0rc1 of the Azure ML SDK\")\n", "print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")" ] }, diff --git a/tutorials/image-classification-mnist-data/img-classification-part1-training.ipynb b/tutorials/image-classification-mnist-data/img-classification-part1-training.ipynb index db744bb42..65db573c6 100644 --- a/tutorials/image-classification-mnist-data/img-classification-part1-training.ipynb +++ b/tutorials/image-classification-mnist-data/img-classification-part1-training.ipynb @@ -418,7 +418,7 @@ "\n", "# to install required packages\n", "env = Environment('my_env')\n", - "cd = CondaDependencies.create(pip_packages=['azureml-sdk','scikit-learn','azureml-dataprep[pandas,fuse]>=1.1.14'])\n", + "cd = CondaDependencies.create(pip_packages=['azureml-sdk','scikit-learn==0.22.1','azureml-dataprep[pandas,fuse]>=1.1.14'])\n", "\n", "env.python.conda_dependencies = cd" ] diff --git a/tutorials/image-classification-mnist-data/img-classification-part2-deploy.ipynb b/tutorials/image-classification-mnist-data/img-classification-part2-deploy.ipynb index 7ad02ecd1..465174438 100644 --- a/tutorials/image-classification-mnist-data/img-classification-part2-deploy.ipynb +++ b/tutorials/image-classification-mnist-data/img-classification-part2-deploy.ipynb @@ -348,7 +348,7 @@ "from azureml.core.conda_dependencies import CondaDependencies \n", "\n", "myenv = CondaDependencies()\n", - "myenv.add_pip_package(\"scikit-learn\")\n", + "myenv.add_pip_package(\"scikit-learn==0.22.1\")\n", "myenv.add_pip_package(\"azureml-defaults\")\n", "\n", "with open(\"myenv.yml\",\"w\") as f:\n", diff --git a/tutorials/machine-learning-pipelines-advanced/tutorial-pipeline-batch-scoring-classification.ipynb b/tutorials/machine-learning-pipelines-advanced/tutorial-pipeline-batch-scoring-classification.ipynb index 06ca5b767..7d067225e 100644 --- a/tutorials/machine-learning-pipelines-advanced/tutorial-pipeline-batch-scoring-classification.ipynb +++ b/tutorials/machine-learning-pipelines-advanced/tutorial-pipeline-batch-scoring-classification.ipynb @@ -12,7 +12,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/machine-learning-pipelines/pipeline-batch-scoring/pipeline-batch-scoring.png)" + "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/tutorials/machine-learning-pipelines-advanced/tutorial-pipeline-batch-scoring-classification.png)" ] }, {