mirror of
https://github.com/Azure/MachineLearningNotebooks.git
synced 2025-12-22 10:35:12 -05:00
Compare commits
6 Commits
azureml-sd
...
azureml-sd
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
59fcb54998 | ||
|
|
e0ea99a6bb | ||
|
|
b06f5ce269 | ||
|
|
ed0ce9e895 | ||
|
|
71053d705b | ||
|
|
77f98bf75f |
@@ -103,7 +103,7 @@
|
||||
"source": [
|
||||
"import azureml.core\n",
|
||||
"\n",
|
||||
"print(\"This notebook was created using version 1.1.5rc0 of the Azure ML SDK\")\n",
|
||||
"print(\"This notebook was created using version 1.1.5 of the Azure ML SDK\")\n",
|
||||
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
||||
]
|
||||
},
|
||||
|
||||
@@ -4,6 +4,7 @@ dependencies:
|
||||
- py-xgboost<=0.80
|
||||
- pip:
|
||||
- azureml-sdk
|
||||
- numpy==1.16.2
|
||||
- azureml-train-automl
|
||||
- azureml-widgets
|
||||
- matplotlib
|
||||
|
||||
@@ -4,6 +4,7 @@ dependencies:
|
||||
- py-xgboost<=0.80
|
||||
- pip:
|
||||
- azureml-sdk
|
||||
- numpy==1.16.2
|
||||
- azureml-train-automl
|
||||
- azureml-widgets
|
||||
- matplotlib
|
||||
|
||||
@@ -2,6 +2,7 @@ name: auto-ml-forecasting-energy-demand
|
||||
dependencies:
|
||||
- pip:
|
||||
- azureml-sdk
|
||||
- numpy==1.16.2
|
||||
- azureml-train-automl
|
||||
- azureml-widgets
|
||||
- matplotlib
|
||||
|
||||
@@ -701,7 +701,7 @@
|
||||
"metadata": {
|
||||
"authors": [
|
||||
{
|
||||
"name": "erwright, nirovins"
|
||||
"name": "erwright"
|
||||
}
|
||||
],
|
||||
"category": "tutorial",
|
||||
|
||||
@@ -4,6 +4,7 @@ dependencies:
|
||||
- py-xgboost<=0.80
|
||||
- pip:
|
||||
- azureml-sdk
|
||||
- numpy==1.16.2
|
||||
- azureml-train-automl
|
||||
- azureml-widgets
|
||||
- matplotlib
|
||||
|
||||
@@ -4,6 +4,7 @@ dependencies:
|
||||
- py-xgboost<=0.80
|
||||
- pip:
|
||||
- azureml-sdk
|
||||
- numpy==1.16.2
|
||||
- pandas==0.23.4
|
||||
- azureml-train-automl
|
||||
- azureml-widgets
|
||||
|
||||
@@ -100,7 +100,7 @@
|
||||
"\n",
|
||||
"# Check core SDK version number\n",
|
||||
"\n",
|
||||
"print(\"This notebook was created using SDK version 1.1.5rc0, you are currently running version\", azureml.core.VERSION)"
|
||||
"print(\"This notebook was created using SDK version 1.1.5, you are currently running version\", azureml.core.VERSION)"
|
||||
]
|
||||
},
|
||||
{
|
||||
|
||||
@@ -149,6 +149,20 @@
|
||||
" ssh_port=22, \n",
|
||||
" username=os.environ.get('hdiusername', '<ssh_username>'), \n",
|
||||
" password=os.environ.get('hdipassword', '<my_password>'))\n",
|
||||
"\n",
|
||||
"# The following Azure regions do not support attaching a HDI Cluster using the public IP address of the HDI Cluster.\n",
|
||||
"# Instead, use the Azure Resource Manager ID of the HDI Cluster with the resource_id parameter:\n",
|
||||
"# US East\n",
|
||||
"# US West 2\n",
|
||||
"# US South Central\n",
|
||||
"# The resource ID of the HDI Cluster can be constructed using the\n",
|
||||
"# subscription ID, resource group name, and cluster name using the following string format:\n",
|
||||
"# /subscriptions/<subscription_id>/resourceGroups/<resource_group>/providers/Microsoft.HDInsight/clusters/<cluster_name>. \n",
|
||||
"# If in US East, US West 2, or US South Central, use the following instead:\n",
|
||||
"# attach_config = HDInsightCompute.attach_configuration(resource_id='<resource_id>',\n",
|
||||
"# ssh_port=22,\n",
|
||||
"# username=os.environ.get('hdiusername', '<ssh_username>'),\n",
|
||||
"# password=os.environ.get('hdipassword', '<my_password>'))\n",
|
||||
" hdi_compute = ComputeTarget.attach(workspace=ws, \n",
|
||||
" name='myhdi', \n",
|
||||
" attach_configuration=attach_config)\n",
|
||||
|
||||
@@ -266,7 +266,23 @@
|
||||
" ssh_port=22,\n",
|
||||
" username=username,\n",
|
||||
" private_key_file='./.ssh/id_rsa')\n",
|
||||
" attached_dsvm_compute = ComputeTarget.attach(workspace=ws,\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# The following Azure regions do not support attaching a virtual machine using the public IP address of the VM.\n",
|
||||
"# Instead, use the Azure Resource Manager ID of the VM with the resource_id parameter:\n",
|
||||
"# US East\n",
|
||||
"# US West 2\n",
|
||||
"# US South Central\n",
|
||||
"# The resource ID of the VM can be constructed using the\n",
|
||||
"# subscription ID, resource group name, and VM name using the following string format:\n",
|
||||
"# /subscriptions/<subscription_id>/resourceGroups/<resource_group>/providers/Microsoft.Compute/virtualMachines/<vm_name>. \n",
|
||||
"# If in US East, US West 2, or US South Central, use the following instead:\n",
|
||||
"# attach_config = RemoteCompute.attach_configuration(resource_id='<resource_id>',\n",
|
||||
"# ssh_port=22,\n",
|
||||
"# username='username',\n",
|
||||
"# private_key_file='./.ssh/id_rsa')\n",
|
||||
"\n",
|
||||
" attached_dsvm_compute = ComputeTarget.attach(workspace=ws,\n",
|
||||
" name=compute_target_name,\n",
|
||||
" attach_configuration=attach_config)\n",
|
||||
" attached_dsvm_compute.wait_for_completion(show_output=True)"
|
||||
|
||||
@@ -102,7 +102,7 @@
|
||||
"source": [
|
||||
"import azureml.core\n",
|
||||
"\n",
|
||||
"print(\"This notebook was created using version 1.1.5rc0 of the Azure ML SDK\")\n",
|
||||
"print(\"This notebook was created using version 1.1.5 of the Azure ML SDK\")\n",
|
||||
"print(\"You are currently using version\", azureml.core.VERSION, \"of the Azure ML SDK\")"
|
||||
]
|
||||
},
|
||||
|
||||
@@ -30,7 +30,9 @@
|
||||
"\n",
|
||||
"## Prerequisites\n",
|
||||
"\n",
|
||||
"See prerequisites in the [Azure Machine Learning documentation](https://docs.microsoft.com/azure/machine-learning/service/tutorial-train-models-with-aml#prerequisites)."
|
||||
"See prerequisites in the [Azure Machine Learning documentation](https://docs.microsoft.com/azure/machine-learning/service/tutorial-train-models-with-aml#prerequisites).\n",
|
||||
"\n",
|
||||
"On the computer running this notebook, conda install matplotlib, numpy, scikit-learn=0.22.1"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -309,7 +311,7 @@
|
||||
"import glob\n",
|
||||
"\n",
|
||||
"from sklearn.linear_model import LogisticRegression\n",
|
||||
"from sklearn.externals import joblib\n",
|
||||
"import joblib\n",
|
||||
"\n",
|
||||
"from azureml.core import Run\n",
|
||||
"from utils import load_data\n",
|
||||
@@ -397,15 +399,20 @@
|
||||
"source": [
|
||||
"### Create an estimator\n",
|
||||
"\n",
|
||||
"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 SKLearn estimator for scikit-learn model, by specifying\n",
|
||||
"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 an 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 compute target. In this case you will use the AmlCompute you created\n",
|
||||
"* The training script name, train.py\n",
|
||||
"* Parameters required from the training script \n",
|
||||
"* An environment that contains the libraries needed to run the script\n",
|
||||
"* Parameters required from the training script. \n",
|
||||
"\n",
|
||||
"In this tutorial, the target is AmlCompute. All files in the script folder are uploaded into the cluster nodes for execution. The data_folder is set to use the dataset."
|
||||
"In this tutorial, the target is AmlCompute. All files in the script folder are uploaded into the cluster nodes for execution. The data_folder is set to use the dataset.\n",
|
||||
"\n",
|
||||
"First, create the environment that contains: the scikit-learn library, azureml-dataprep required for accessing the dataset, and azureml-defaults which contains the dependencies for logging metrics. The azureml-defaults also contains the dependencies required for deploying the model as a web service later in the part 2 of the tutorial.\n",
|
||||
"\n",
|
||||
"Once the environment is defined, register it with the Workspace to re-use it in part 2 of the tutorial."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -418,10 +425,20 @@
|
||||
"from azureml.core.conda_dependencies import CondaDependencies\n",
|
||||
"\n",
|
||||
"# to install required packages\n",
|
||||
"env = Environment('my_env')\n",
|
||||
"cd = CondaDependencies.create(pip_packages=['azureml-sdk','scikit-learn==0.22.1','azureml-dataprep[pandas,fuse]>=1.1.14'])\n",
|
||||
"env = Environment('tutorial-env')\n",
|
||||
"cd = CondaDependencies.create(pip_packages=['azureml-dataprep[pandas,fuse]>=1.1.14', 'azureml-defaults'], conda_packages = ['scikit-learn==0.22.1'])\n",
|
||||
"\n",
|
||||
"env.python.conda_dependencies = cd"
|
||||
"env.python.conda_dependencies = cd\n",
|
||||
"\n",
|
||||
"# Register environment to re-use later\n",
|
||||
"env.register(workspace = ws)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Then, create the estimator by specifying the training script, compute target and environment."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -434,7 +451,7 @@
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from azureml.train.sklearn import SKLearn\n",
|
||||
"from azureml.train.estimator import Estimator\n",
|
||||
"\n",
|
||||
"script_params = {\n",
|
||||
" # to mount files referenced by mnist dataset\n",
|
||||
@@ -442,7 +459,7 @@
|
||||
" '--regularization': 0.5\n",
|
||||
"}\n",
|
||||
"\n",
|
||||
"est = SKLearn(source_directory=script_folder,\n",
|
||||
"est = Estimator(source_directory=script_folder,\n",
|
||||
" script_params=script_params,\n",
|
||||
" compute_target=compute_target,\n",
|
||||
" environment_definition=env,\n",
|
||||
@@ -667,7 +684,7 @@
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.6.9"
|
||||
"version": "3.7.6"
|
||||
},
|
||||
"msauthor": "roastala"
|
||||
},
|
||||
|
||||
@@ -39,11 +39,7 @@
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"tags": [
|
||||
"register model from file"
|
||||
]
|
||||
},
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# If you did NOT complete the tutorial, you can instead run this cell \n",
|
||||
@@ -62,7 +58,19 @@
|
||||
" model_name=model_name,\n",
|
||||
" tags={\"data\": \"mnist\", \"model\": \"classification\"},\n",
|
||||
" description=\"Mnist handwriting recognition\",\n",
|
||||
" workspace=ws)"
|
||||
" workspace=ws)\n",
|
||||
"\n",
|
||||
"from azureml.core.environment import Environment\n",
|
||||
"from azureml.core.conda_dependencies import CondaDependencies\n",
|
||||
"\n",
|
||||
"# to install required packages\n",
|
||||
"env = Environment('tutorial-env')\n",
|
||||
"cd = CondaDependencies.create(pip_packages=['azureml-dataprep[pandas,fuse]>=1.1.14', 'azureml-defaults'], conda_packages = ['scikit-learn==0.22.1'])\n",
|
||||
"\n",
|
||||
"env.python.conda_dependencies = cd\n",
|
||||
"\n",
|
||||
"# Register environment to re-use later\n",
|
||||
"env.register(workspace = ws)"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -102,9 +110,61 @@
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Retrieve the model\n",
|
||||
"## Deploy as web service\n",
|
||||
"\n",
|
||||
"You registered a model in your workspace in the previous tutorial. Now, load this workspace and download the model to your local directory."
|
||||
"Deploy the model as a web service hosted in ACI. \n",
|
||||
"\n",
|
||||
"To build the correct environment for ACI, provide the following:\n",
|
||||
"* A scoring script to show how to use the model\n",
|
||||
"* A configuration file to build the ACI\n",
|
||||
"* The model you trained before\n",
|
||||
"\n",
|
||||
"### Create scoring script\n",
|
||||
"\n",
|
||||
"Create the scoring script, called score.py, used by the web service call to show how to use the model.\n",
|
||||
"\n",
|
||||
"You must include two required functions into the scoring script:\n",
|
||||
"* The `init()` function, which typically loads the model into a global object. This function is run only once when the Docker container is started. \n",
|
||||
"\n",
|
||||
"* The `run(input_data)` function uses the model to predict a value based on the input data. Inputs and outputs to the run typically use JSON for serialization and de-serialization, but other formats are supported.\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"%%writefile score.py\n",
|
||||
"import json\n",
|
||||
"import numpy as np\n",
|
||||
"import os\n",
|
||||
"import pickle\n",
|
||||
"import joblib\n",
|
||||
"\n",
|
||||
"def init():\n",
|
||||
" global model\n",
|
||||
" # AZUREML_MODEL_DIR is an environment variable created during deployment.\n",
|
||||
" # It is the path to the model folder (./azureml-models/$MODEL_NAME/$VERSION)\n",
|
||||
" # For multiple models, it points to the folder containing all deployed models (./azureml-models)\n",
|
||||
" model_path = os.path.join(os.getenv('AZUREML_MODEL_DIR'), 'sklearn_mnist_model.pkl')\n",
|
||||
" model = joblib.load(model_path)\n",
|
||||
"\n",
|
||||
"def run(raw_data):\n",
|
||||
" data = np.array(json.loads(raw_data)['data'])\n",
|
||||
" # make prediction\n",
|
||||
" y_hat = model.predict(data)\n",
|
||||
" # you can return any data type as long as it is JSON-serializable\n",
|
||||
" return y_hat.tolist()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Create configuration file\n",
|
||||
"\n",
|
||||
"Create a deployment configuration file and specify the number of CPUs and gigabyte of RAM needed for your ACI container. While it depends on your model, the default of 1 core and 1 gigabyte of RAM is usually sufficient for many models. If you feel you need more later, you would have to recreate the image and redeploy the service."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -112,37 +172,98 @@
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"tags": [
|
||||
"load workspace",
|
||||
"download model"
|
||||
"configure web service",
|
||||
"aci"
|
||||
]
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from azureml.core import Workspace\n",
|
||||
"from azureml.core.model import Model\n",
|
||||
"import os \n",
|
||||
"ws = Workspace.from_config()\n",
|
||||
"model=Model(ws, 'sklearn_mnist')\n",
|
||||
"from azureml.core.webservice import AciWebservice\n",
|
||||
"\n",
|
||||
"model.download(target_dir=os.getcwd(), exist_ok=True)\n",
|
||||
"\n",
|
||||
"# verify the downloaded model file\n",
|
||||
"file_path = os.path.join(os.getcwd(), \"sklearn_mnist_model.pkl\")\n",
|
||||
"\n",
|
||||
"os.stat(file_path)"
|
||||
"aciconfig = AciWebservice.deploy_configuration(cpu_cores=1, \n",
|
||||
" memory_gb=1, \n",
|
||||
" tags={\"data\": \"MNIST\", \"method\" : \"sklearn\"}, \n",
|
||||
" description='Predict MNIST with sklearn')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Test model locally\n",
|
||||
"### Deploy in ACI\n",
|
||||
"Estimated time to complete: **about 2-5 minutes**\n",
|
||||
"\n",
|
||||
"Before deploying, make sure your model is working locally by:\n",
|
||||
"* Downloading the test data if you haven't already\n",
|
||||
"* Loading test data\n",
|
||||
"* Predicting test data\n",
|
||||
"* Examining the confusion matrix"
|
||||
"Configure the image and deploy. The following code goes through these steps:\n",
|
||||
"\n",
|
||||
"1. Create environment object containing dependencies needed by the model using the environment file (`myenv.yml`)\n",
|
||||
"1. Create inference configuration necessary to deploy the model as a web service using:\n",
|
||||
" * The scoring file (`score.py`)\n",
|
||||
" * envrionment object created in previous step\n",
|
||||
"1. Deploy the model to the ACI container.\n",
|
||||
"1. Get the web service HTTP endpoint."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"tags": [
|
||||
"configure image",
|
||||
"create image",
|
||||
"deploy web service",
|
||||
"aci"
|
||||
]
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"%%time\n",
|
||||
"from azureml.core.webservice import Webservice\n",
|
||||
"from azureml.core.model import InferenceConfig\n",
|
||||
"from azureml.core.environment import Environment\n",
|
||||
"from azureml.core import Workspace\n",
|
||||
"from azureml.core.model import Model\n",
|
||||
"\n",
|
||||
"ws = Workspace.from_config()\n",
|
||||
"model = Model(ws, 'sklearn_mnist')\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"myenv = Environment.get(workspace=ws, name=\"tutorial-env\", version=\"1\")\n",
|
||||
"inference_config = InferenceConfig(entry_script=\"score.py\", environment=myenv)\n",
|
||||
"\n",
|
||||
"service = Model.deploy(workspace=ws, \n",
|
||||
" name='sklearn-mnist-svc', \n",
|
||||
" models=[model], \n",
|
||||
" inference_config=inference_config, \n",
|
||||
" deployment_config=aciconfig)\n",
|
||||
"\n",
|
||||
"service.wait_for_deployment(show_output=True)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Get the scoring web service's HTTP endpoint, which accepts REST client calls. This endpoint can be shared with anyone who wants to test the web service or integrate it into an application."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"tags": [
|
||||
"get scoring uri"
|
||||
]
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"print(service.scoring_uri)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Test the model\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -150,7 +271,7 @@
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Download test data\n",
|
||||
"If you haven't already, download the test data to the **./data/** directory"
|
||||
"Download the test data to the **./data/** directory"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -159,16 +280,15 @@
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# download test data\n",
|
||||
"import os\n",
|
||||
"import urllib.request\n",
|
||||
"from azureml.core import Dataset\n",
|
||||
"from azureml.opendatasets import MNIST\n",
|
||||
"\n",
|
||||
"data_folder = os.path.join(os.getcwd(), 'data')\n",
|
||||
"os.makedirs(data_folder, exist_ok = True)\n",
|
||||
"os.makedirs(data_folder, exist_ok=True)\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"urllib.request.urlretrieve('http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz', filename=os.path.join(data_folder, 'test-images.gz'))\n",
|
||||
"urllib.request.urlretrieve('http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz', filename=os.path.join(data_folder, 'test-labels.gz'))"
|
||||
"mnist_file_dataset = MNIST.get_file_dataset()\n",
|
||||
"mnist_file_dataset.download(data_folder, overwrite=True)"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -191,8 +311,8 @@
|
||||
"\n",
|
||||
"data_folder = os.path.join(os.getcwd(), 'data')\n",
|
||||
"# note we also shrink the intensity values (X) from 0-255 to 0-1. This helps the neural network converge faster\n",
|
||||
"X_test = load_data(os.path.join(data_folder, 'test-images.gz'), False) / 255.0\n",
|
||||
"y_test = load_data(os.path.join(data_folder, 'test-labels.gz'), True).reshape(-1)"
|
||||
"X_test = load_data(os.path.join(data_folder, 't10k-images-idx3-ubyte.gz'), False) / 255.0\n",
|
||||
"y_test = load_data(os.path.join(data_folder, 't10k-labels-idx1-ubyte.gz'), True).reshape(-1)"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -201,7 +321,13 @@
|
||||
"source": [
|
||||
"### Predict test data\n",
|
||||
"\n",
|
||||
"Feed the test dataset to the model to get predictions."
|
||||
"Feed the test dataset to the model to get predictions.\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"The following code goes through these steps:\n",
|
||||
"1. Send the data as a JSON array to the web service hosted in ACI. \n",
|
||||
"\n",
|
||||
"1. Use the SDK's `run` API to invoke the service. You can also make raw calls using any HTTP tool such as curl."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -210,12 +336,10 @@
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import pickle\n",
|
||||
"import joblib\n",
|
||||
"\n",
|
||||
"clf = joblib.load( os.path.join(os.getcwd(), 'sklearn_mnist_model.pkl'))\n",
|
||||
"y_hat = clf.predict(X_test)\n",
|
||||
"print(y_hat)"
|
||||
"import json\n",
|
||||
"test = json.dumps({\"data\": X_test.tolist()})\n",
|
||||
"test = bytes(test, encoding='utf8')\n",
|
||||
"y_hat = service.run(input_data=test)"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -277,209 +401,10 @@
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Deploy as web service\n",
|
||||
"## Show predictions\n",
|
||||
"\n",
|
||||
"Once you've tested the model and are satisfied with the results, deploy the model as a web service hosted in ACI. \n",
|
||||
"Test the deployed model with a random sample of 30 images from the test data. \n",
|
||||
"\n",
|
||||
"To build the correct environment for ACI, provide the following:\n",
|
||||
"* A scoring script to show how to use the model\n",
|
||||
"* An environment file to show what packages need to be installed\n",
|
||||
"* A configuration file to build the ACI\n",
|
||||
"* The model you trained before\n",
|
||||
"\n",
|
||||
"### Create scoring script\n",
|
||||
"\n",
|
||||
"Create the scoring script, called score.py, used by the web service call to show how to use the model.\n",
|
||||
"\n",
|
||||
"You must include two required functions into the scoring script:\n",
|
||||
"* The `init()` function, which typically loads the model into a global object. This function is run only once when the Docker container is started. \n",
|
||||
"\n",
|
||||
"* The `run(input_data)` function uses the model to predict a value based on the input data. Inputs and outputs to the run typically use JSON for serialization and de-serialization, but other formats are supported.\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"%%writefile score.py\n",
|
||||
"import json\n",
|
||||
"import numpy as np\n",
|
||||
"import os\n",
|
||||
"import pickle\n",
|
||||
"import joblib\n",
|
||||
"\n",
|
||||
"def init():\n",
|
||||
" global model\n",
|
||||
" # AZUREML_MODEL_DIR is an environment variable created during deployment.\n",
|
||||
" # It is the path to the model folder (./azureml-models/$MODEL_NAME/$VERSION)\n",
|
||||
" # For multiple models, it points to the folder containing all deployed models (./azureml-models)\n",
|
||||
" model_path = os.path.join(os.getenv('AZUREML_MODEL_DIR'), 'sklearn_mnist_model.pkl')\n",
|
||||
" model = joblib.load(model_path)\n",
|
||||
"\n",
|
||||
"def run(raw_data):\n",
|
||||
" data = np.array(json.loads(raw_data)['data'])\n",
|
||||
" # make prediction\n",
|
||||
" y_hat = model.predict(data)\n",
|
||||
" # you can return any data type as long as it is JSON-serializable\n",
|
||||
" return y_hat.tolist()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Create environment file\n",
|
||||
"\n",
|
||||
"Next, create an environment file, called myenv.yml, that specifies all of the script's package dependencies. This file is used to ensure that all of those dependencies are installed in the Docker image. This model needs `scikit-learn` and `azureml-sdk`."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"tags": [
|
||||
"set conda dependencies"
|
||||
]
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from azureml.core.conda_dependencies import CondaDependencies \n",
|
||||
"\n",
|
||||
"myenv = CondaDependencies()\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",
|
||||
" f.write(myenv.serialize_to_string())"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Review the content of the `myenv.yml` file."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"with open(\"myenv.yml\",\"r\") as f:\n",
|
||||
" print(f.read())"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Create configuration file\n",
|
||||
"\n",
|
||||
"Create a deployment configuration file and specify the number of CPUs and gigabyte of RAM needed for your ACI container. While it depends on your model, the default of 1 core and 1 gigabyte of RAM is usually sufficient for many models. If you feel you need more later, you would have to recreate the image and redeploy the service."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"tags": [
|
||||
"configure web service",
|
||||
"aci"
|
||||
]
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from azureml.core.webservice import AciWebservice\n",
|
||||
"\n",
|
||||
"aciconfig = AciWebservice.deploy_configuration(cpu_cores=1, \n",
|
||||
" memory_gb=1, \n",
|
||||
" tags={\"data\": \"MNIST\", \"method\" : \"sklearn\"}, \n",
|
||||
" description='Predict MNIST with sklearn')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Deploy in ACI\n",
|
||||
"Estimated time to complete: **about 7-8 minutes**\n",
|
||||
"\n",
|
||||
"Configure the image and deploy. The following code goes through these steps:\n",
|
||||
"\n",
|
||||
"1. Create environment object containing dependencies needed by the model using the environment file (`myenv.yml`)\n",
|
||||
"1. Create inference configuration necessary to deploy the model as a web service using:\n",
|
||||
" * The scoring file (`score.py`)\n",
|
||||
" * envrionment object created in previous step\n",
|
||||
"1. Deploy the model to the ACI container.\n",
|
||||
"1. Get the web service HTTP endpoint."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"tags": [
|
||||
"configure image",
|
||||
"create image",
|
||||
"deploy web service",
|
||||
"aci"
|
||||
]
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"%%time\n",
|
||||
"from azureml.core.webservice import Webservice\n",
|
||||
"from azureml.core.model import InferenceConfig\n",
|
||||
"from azureml.core.environment import Environment\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"myenv = Environment.from_conda_specification(name=\"myenv\", file_path=\"myenv.yml\")\n",
|
||||
"inference_config = InferenceConfig(entry_script=\"score.py\", environment=myenv)\n",
|
||||
"\n",
|
||||
"service = Model.deploy(workspace=ws, \n",
|
||||
" name='sklearn-mnist-svc', \n",
|
||||
" models=[model], \n",
|
||||
" inference_config=inference_config, \n",
|
||||
" deployment_config=aciconfig)\n",
|
||||
"\n",
|
||||
"service.wait_for_deployment(show_output=True)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Get the scoring web service's HTTP endpoint, which accepts REST client calls. This endpoint can be shared with anyone who wants to test the web service or integrate it into an application."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"tags": [
|
||||
"get scoring uri"
|
||||
]
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"print(service.scoring_uri)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Test deployed service\n",
|
||||
"\n",
|
||||
"Earlier you scored all the test data with the local version of the model. Now, you can test the deployed model with a random sample of 30 images from the test data. \n",
|
||||
"\n",
|
||||
"The following code goes through these steps:\n",
|
||||
"1. Send the data as a JSON array to the web service hosted in ACI. \n",
|
||||
"\n",
|
||||
"1. Use the SDK's `run` API to invoke the service. You can also make raw calls using any HTTP tool such as curl.\n",
|
||||
"\n",
|
||||
"1. Print the returned predictions and plot them along with the input images. Red font and inverse image (white on black) is used to highlight the misclassified samples. \n",
|
||||
"\n",
|
||||
|
||||
Reference in New Issue
Block a user