{ "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": [ "We support installing AML SDK as library from GUI. When attaching a library follow this https://docs.databricks.com/user-guide/libraries.html and add the below string as your PyPi package. You can select the option to attach the library to all clusters or just one cluster.\n", "\n", "**install azureml-sdk with Automated ML**\n", "* Source: Upload Python Egg or PyPi\n", "* PyPi Name: `azureml-sdk[automl_databricks]`\n", "* Select Install Library" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# AutoML : Classification with Local Compute on Azure DataBricks with deployment to ACI\n", "\n", "In this example we use the scikit-learn's [digit dataset](http://scikit-learn.org/stable/datasets/index.html#optical-recognition-of-handwritten-digits-dataset) to showcase how you can use AutoML for a simple classification problem.\n", "\n", "In this notebook you will learn how to:\n", "1. Create Azure Machine Learning Workspace object and initialize your notebook directory to easily reload this object from a configuration file.\n", "2. Create an `Experiment` in an existing `Workspace`.\n", "3. Configure AutoML using `AutoMLConfig`.\n", "4. Train the model using AzureDataBricks.\n", "5. Explore the results.\n", "6. Register the model.\n", "7. Deploy the model.\n", "8. Test the best fitted model.\n", "\n", "Prerequisites:\n", "Before running this notebook, please follow the readme for installing necessary libraries to your cluster." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Register Machine Learning Services Resource Provider\n", "Microsoft.MachineLearningServices only needs to be registed once in the subscription. To register it:\n", "Start the Azure portal.\n", "Select your All services and then Subscription.\n", "Select the subscription that you want to use.\n", "Click on Resource providers\n", "Click the Register link next to Microsoft.MachineLearningServices" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Check the Azure ML Core SDK Version to Validate Your Installation" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import azureml.core\n", "\n", "print(\"SDK Version:\", azureml.core.VERSION)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Initialize an Azure ML Workspace\n", "### What is an Azure ML Workspace and Why Do I Need One?\n", "\n", "An Azure ML workspace is an Azure resource that organizes and coordinates the actions of many other Azure resources to assist in executing and sharing machine learning workflows. In particular, an Azure ML workspace coordinates storage, databases, and compute resources providing added functionality for machine learning experimentation, operationalization, and the monitoring of operationalized models.\n", "\n", "\n", "### What do I Need?\n", "\n", "To create or access an Azure ML workspace, you will need to import the Azure ML library and specify following information:\n", "* A name for your workspace. You can choose one.\n", "* Your subscription id. Use the `id` value from the `az account show` command output above.\n", "* The resource group name. The resource group organizes Azure resources and provides a default region for the resources in the group. The resource group will be created if it doesn't exist. Resource groups can be created and viewed in the [Azure portal](https://portal.azure.com)\n", "* Supported regions include `eastus2`, `eastus`,`westcentralus`, `southeastasia`, `westeurope`, `australiaeast`, `westus2`, `southcentralus`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "subscription_id = \"\"\n", "resource_group = \"\"\n", "workspace_name = \"\"\n", "workspace_region = \"\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Creating a Workspace\n", "If you already have access to an Azure ML workspace you want to use, you can skip this cell. Otherwise, this cell will create an Azure ML workspace for you in the specified subscription, provided you have the correct permissions for the given `subscription_id`.\n", "\n", "This will fail when:\n", "1. The workspace already exists.\n", "2. You do not have permission to create a workspace in the resource group.\n", "3. You are not a subscription owner or contributor and no Azure ML workspaces have ever been created in this subscription.\n", "\n", "If workspace creation fails for any reason other than already existing, please work with your IT administrator to provide you with the appropriate permissions or to provision the required resources.\n", "\n", "**Note:** Creation of a new workspace can take several minutes." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Import the Workspace class and check the Azure ML SDK version.\n", "from azureml.core import Workspace\n", "\n", "ws = Workspace.create(name = workspace_name,\n", " subscription_id = subscription_id,\n", " resource_group = resource_group, \n", " location = workspace_region,\n", " exist_ok=True)\n", "ws.get_details()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Configuring Your Local Environment\n", "You can validate that you have access to the specified workspace and write a configuration file to the default configuration location, `./aml_config/config.json`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from azureml.core import Workspace\n", "\n", "ws = Workspace(workspace_name = workspace_name,\n", " subscription_id = subscription_id,\n", " resource_group = resource_group)\n", "\n", "# Persist the subscription id, resource group name, and workspace name in aml_config/config.json.\n", "ws.write_config()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Create a Folder to Host Sample Projects\n", "Finally, create a folder where all the sample projects will be hosted." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import os\n", "\n", "sample_projects_folder = './sample_projects'\n", "\n", "if not os.path.isdir(sample_projects_folder):\n", " os.mkdir(sample_projects_folder)\n", " \n", "print('Sample projects will be created in {}.'.format(sample_projects_folder))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Create an Experiment\n", "\n", "As part of the setup you have already created an Azure ML `Workspace` object. For AutoML you will need to create an `Experiment` object, which is a named object in a `Workspace` used to run experiments." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import logging\n", "import os\n", "import random\n", "import time\n", "\n", "from matplotlib import pyplot as plt\n", "from matplotlib.pyplot import imshow\n", "import numpy as np\n", "import pandas as pd\n", "\n", "import azureml.core\n", "from azureml.core.experiment import Experiment\n", "from azureml.core.workspace import Workspace\n", "from azureml.train.automl import AutoMLConfig\n", "from azureml.train.automl.run import AutoMLRun" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Choose a name for the experiment and specify the project folder.\n", "experiment_name = 'automl-local-classification'\n", "project_folder = './sample_projects/automl-local-classification'\n", "\n", "experiment = Experiment(ws, experiment_name)\n", "\n", "output = {}\n", "output['SDK version'] = azureml.core.VERSION\n", "output['Subscription ID'] = ws.subscription_id\n", "output['Workspace Name'] = ws.name\n", "output['Resource Group'] = ws.resource_group\n", "output['Location'] = ws.location\n", "output['Project Directory'] = project_folder\n", "output['Experiment Name'] = experiment.name\n", "pd.set_option('display.max_colwidth', -1)\n", "pd.DataFrame(data = output, index = ['']).T" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Diagnostics\n", "\n", "Opt-in diagnostics for better experience, quality, and security of future releases." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from azureml.telemetry import set_diagnostics_collection\n", "set_diagnostics_collection(send_diagnostics = True)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Load Training Data Using DataPrep" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import azureml.dataprep as dprep\n", "# You can use `auto_read_file` which intelligently figures out delimiters and datatypes of a file.\n", "# The data referenced here was pulled from `sklearn.datasets.load_digits()`.\n", "simple_example_data_root = 'https://dprepdata.blob.core.windows.net/automl-notebook-data/'\n", "X_train = dprep.auto_read_file(simple_example_data_root + 'X.csv').skip(1) # Remove the header row.\n", "\n", "# You can also use `read_csv` and `to_*` transformations to read (with overridable delimiter)\n", "# and convert column types manually.\n", "# Here we read a comma delimited file and convert all columns to integers.\n", "y_train = dprep.read_csv(simple_example_data_root + 'y.csv').to_long(dprep.ColumnSelector(term='.*', use_regex = True))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Review the Data Preparation Result\n", "You can peek the result of a Dataflow at any range using skip(i) and head(j). Doing so evaluates only j records for all the steps in the Dataflow, which makes it fast even against large datasets." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "X_train.skip(1).head(5)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Configure AutoML\n", "\n", "Instantiate an `AutoMLConfig` object to specify the settings and data used to run the experiment.\n", "\n", "|Property|Description|\n", "|-|-|\n", "|**task**|classification or regression|\n", "|**primary_metric**|This is the metric that you want to optimize. Classification supports the following primary metrics:
accuracy
AUC_weighted
average_precision_score_weighted
norm_macro_recall
precision_score_weighted|\n", "|**primary_metric**|This is the metric that you want to optimize. Regression supports the following primary metrics:
spearman_correlation
normalized_root_mean_squared_error
r2_score
normalized_mean_absolute_error|\n", "|**iteration_timeout_minutes**|Time limit in minutes for each iteration.|\n", "|**iterations**|Number of iterations. In each iteration AutoML trains a specific pipeline with the data.|\n", "|**n_cross_validations**|Number of cross validation splits.|\n", "|**spark_context**|Spark Context object. for Databricks, use spark_context=sc|\n", "|**max_concurrent_iterations**|Maximum number of iterations to execute in parallel. This should be <= number of worker nodes in your Azure Databricks cluster.|\n", "|**X**|(sparse) array-like, shape = [n_samples, n_features]|\n", "|**y**|(sparse) array-like, shape = [n_samples, ], [n_samples, n_classes]
Multi-class targets. An indicator matrix turns on multilabel classification. This should be an array of integers.|\n", "|**path**|Relative path to the project folder. AutoML stores configuration files for the experiment under this folder. You can specify a new empty folder.|\n", "|**preprocess**|set this to True to enable pre-processing of data eg. string to numeric using one-hot encoding|\n", "|**exit_score**|Target score for experiment. It is associated with the metric. eg. exit_score=0.995 will exit experiment after that|" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "automl_config = AutoMLConfig(task = 'classification',\n", " debug_log = 'automl_errors.log',\n", " primary_metric = 'AUC_weighted',\n", " iteration_timeout_minutes = 10,\n", " iterations = 5,\n", " n_cross_validations = 2,\n", " max_concurrent_iterations = 4, #change it based on number of worker nodes\n", " verbosity = logging.INFO,\n", " spark_context=sc, #databricks/spark related\n", " X = X_train, \n", " y = y_train,\n", " enable_cache=False,\n", " path = project_folder)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Train the Models\n", "\n", "Call the `submit` method on the experiment object and pass the run configuration. Execution of local runs is synchronous. Depending on the data and the number of iterations this can run for a while.\n", "In this example, we specify `show_output = True` to print currently running iterations to the console." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "local_run = experiment.submit(automl_config, show_output = True) # for higher runs please use show_output=False and use the below" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Explore the Results" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Portal URL for Monitoring Runs\n", "\n", "The following will provide a link to the web interface to explore individual run details and status. In the future we might support output displayed in the notebook." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "displayHTML(\"Azure Portal: {}\".format(local_run.get_portal_url(), local_run.id))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The following will show the child runs and waits for the parent run to complete." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Retrieve All Child Runs after the experiment is completed (in portal)\n", "You can also use SDK methods to fetch all the child runs and see individual metrics that we log." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "children = list(local_run.get_children())\n", "metricslist = {}\n", "for run in children:\n", " properties = run.get_properties()\n", " metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)} \n", " metricslist[int(properties['iteration'])] = metrics\n", "\n", "rundata = pd.DataFrame(metricslist).sort_index(1)\n", "rundata" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Retrieve the Best Model after the above run is complete \n", "\n", "Below we select the best pipeline from our iterations. The `get_output` method returns the best run and the fitted model. The Model includes the pipeline and any pre-processing. Overloads on `get_output` allow you to retrieve the best run and fitted model for *any* logged metric or for a particular *iteration*." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "best_run, fitted_model = local_run.get_output()\n", "print(best_run)\n", "print(fitted_model)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Best Model Based on Any Other Metric after the above run is complete based on the child run\n", "Show the run and the model that has the smallest `log_loss` value:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "lookup_metric = \"log_loss\"\n", "best_run, fitted_model = local_run.get_output(metric = lookup_metric)\n", "print(best_run)\n", "print(fitted_model)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Register the Fitted Model for Deployment\n", "If neither metric nor iteration are specified in the register_model call, the iteration with the best primary metric is registered." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "description = 'AutoML Model'\n", "tags = None\n", "model = local_run.register_model(description = description, tags = tags)\n", "local_run.model_id # This will be written to the scoring script file later in the notebook." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Create Scoring Script\n", "Replace model_id with name of model from output of above register cell" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%%writefile score.py\n", "import pickle\n", "import json\n", "import numpy\n", "import azureml.train.automl\n", "from sklearn.externals import joblib\n", "from azureml.core.model import Model\n", "\n", "\n", "def init():\n", " global model\n", " model_path = Model.get_model_path(model_name = '<>') # this name is model.id of model that we want to deploy\n", " # deserialize the model file back into a sklearn model\n", " model = joblib.load(model_path)\n", "\n", "def run(rawdata):\n", " try:\n", " data = json.loads(rawdata)['data']\n", " data = numpy.array(data)\n", " result = model.predict(data)\n", " except Exception as e:\n", " result = str(e)\n", " return json.dumps({\"error\": result})\n", " return json.dumps({\"result\":result.tolist()})" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Create a YAML File for the Environment" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from azureml.core.conda_dependencies import CondaDependencies\n", "\n", "myenv = CondaDependencies.create(conda_packages=['numpy','scikit-learn'], pip_packages=['azureml-sdk[automl]'])\n", "\n", "conda_env_file_name = 'mydeployenv.yml'\n", "myenv.save_to_file('.', conda_env_file_name)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Create ACI config" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#deploy to ACI\n", "from azureml.core.webservice import AciWebservice, Webservice\n", "\n", "myaci_config = AciWebservice.deploy_configuration(\n", " cpu_cores = 2, \n", " memory_gb = 2, \n", " tags = {'name':'Databricks Azure ML ACI'}, \n", " description = 'This is for ADB and AutoML example.')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Deploy the Image as a Web Service on Azure Container Instance\n", "Replace servicename with any meaningful name of service" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\n", "# this will take 10-15 minutes to finish\n", "\n", "service_name = \"<>\"\n", "runtime = \"spark-py\" \n", "driver_file = \"score.py\"\n", "my_conda_file = \"mydeployenv.yml\"\n", "\n", "# image creation\n", "from azureml.core.image import ContainerImage\n", "myimage_config = ContainerImage.image_configuration(execution_script = driver_file, \n", " runtime = runtime, \n", " conda_file = 'mydeployenv.yml')\n", "\n", "# Webservice creation\n", "myservice = Webservice.deploy_from_model(\n", " workspace=ws, \n", " name=service_name,\n", " deployment_config = myaci_config,\n", " models = [model],\n", " image_config = myimage_config\n", " )\n", "\n", "myservice.wait_for_deployment(show_output=True)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#for using the Web HTTP API \n", "print(myservice.scoring_uri)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Test the Best Fitted Model\n", "\n", "#### Load Test Data - you can split the dataset beforehand & pass Train dataset to AutoML and use Test dataset to evaluate the best model." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from sklearn import datasets\n", "digits = datasets.load_digits()\n", "X_test = digits.data[:10, :]\n", "y_test = digits.target[:10]\n", "images = digits.images[:10]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Testing Our Best Fitted Model\n", "We will try to predict digits and see how our model works. This is just an example to show you." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Randomly select digits and test.\n", "for index in np.random.choice(len(y_test), 2, replace = False):\n", " print(index)\n", " predicted = fitted_model.predict(X_test[index:index + 1])[0]\n", " label = y_test[index]\n", " title = \"Label value = %d Predicted value = %d \" % (label, predicted)\n", " fig = plt.figure(1, figsize = (3,3))\n", " ax1 = fig.add_axes((0,0,.8,.8))\n", " ax1.set_title(title)\n", " plt.imshow(images[index], cmap = plt.cm.gray_r, interpolation = 'nearest')\n", " display(fig)" ] } ], "metadata": { "authors": [ { "name": "savitam" }, { "name": "wamartin" } ], "kernelspec": { "display_name": "Python 3.6", "language": "python", "name": "python36" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.0" }, "name": "auto-ml-classification-local-adb", "notebookId": 3888835968049288 }, "nbformat": 4, "nbformat_minor": 0 }