{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "# Use scikit-learn to recognize hand-written digits with `ibm-watson-machine-learning`\n", "\n", "This notebook contains steps and code to demonstrate how to persist and deploy a locally trained scikit-learn model in the Watson Machine Learning Service. This notebook contains steps and code to work with the [ibm-watson-machine-learning](https://pypi.python.org/pypi/ibm-watson-machine-learning) library available in the PyPI repository. This notebook introduces commands for getting a model and training data, persisting the model, deploying it, scoring it, updating it, and redeploying it.\n", "\n", "Some familiarity with Python is helpful. This notebook uses Python 3.9 with the ibm-watson-machine-learning package." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Learning goals\n", "\n", "The learning goals of this notebook are:\n", "\n", "- Train an sklearn model\n", "- Persist the trained model in the Watson Machine Learning repository\n", "- Deploy the model for online scoring using the client library\n", "- Score sample records using the client library\n", "\n", "\n", "## Contents\n", "\n", "This notebook contains the following parts:\n", "\n", "1.\t[Setup](#setup)\n", "2.\t[Explore data and create a scikit-learn model](#train)\n", "3.\t[Persist the externally created scikit model](#upload)\n", "4.\t[Deploy and score](#deploy)\n", "5. [Batch scoring using connection_asset](#score)\n", "6. [Clean up](#cleanup)\n", "7.\t[Summary and next steps](#summary)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "## 1. Set up the environment\n", "\n", "Before you use the sample code in this notebook, contact your IBM Cloud Pak® for Data administrator and ask for your account credentials.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Connection to WML\n", "\n", "Authenticate the Watson Machine Learning service on IBM Cloud Pak® for Data. You need to provide platform `url`, your `username` and `api_key`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "username = 'PASTE YOUR USERNAME HERE'\n", "api_key = 'PASTE YOUR API_KEY HERE'\n", "url = 'PASTE THE PLATFORM URL HERE'" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "wml_credentials = {\n", " \"username\": username,\n", " \"apikey\": api_key,\n", " \"url\": url,\n", " \"instance_id\": 'openshift',\n", " \"version\": '4.0'\n", "}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Alternatively you can use `username` and `password` to authenticate WML services.\n", "\n", "```\n", "wml_credentials = {\n", " \"username\": ***,\n", " \"password\": ***,\n", " \"url\": ***,\n", " \"instance_id\": 'openshift',\n", " \"version\": '4.0'\n", "}\n", "\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Install and import the `ibm-watson-machine-learning` package\n", "**Note:** `ibm-watson-machine-learning` documentation can be found here." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "!pip install -U ibm-watson-machine-learning" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "from ibm_watson_machine_learning import APIClient\n", "\n", "client = APIClient(wml_credentials)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Working with spaces\n", "\n", "First of all, you need to create a space that will be used for your work. If you do not have a space, you can use `{PLATFORM_URL}/ml-runtime/spaces?context=icp4data` to create one.\n", "\n", "- Click New Deployment Space\n", "- Create an empty space\n", "- Go to space `Settings` tab\n", "- Copy `space_id` and paste it below\n", "\n", "**Tip**: You can also use SDK to prepare the space for your work. More information can be found [here](https://github.com/IBM/watson-machine-learning-samples/blob/master/cpd4.0/notebooks/python_sdk/instance-management/Space%20management.ipynb).\n", "\n", "**Action**: Assign space ID below" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "space_id = 'PASTE YOUR SPACE ID HERE'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can use the `list()` method to print all existing spaces." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "client.spaces.list(limit=10)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To be able to interact with all resources available in Watson Machine Learning, you need to set **space** which you will be using." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'SUCCESS'" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "client.set.default_space(space_id)" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" } }, "source": [ "\n", "## 2. Explore data and create an scikit-learn model\n", "In this section, you will prepare and train a handwritten digits model using the scikit-learn library." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2.1 Explore data" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As the first step, you will load the data from scikit-learn sample datasets and perform basic exploration." ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "pycharm": { "is_executing": false, "name": "#%%\n" } }, "outputs": [], "source": [ "import sklearn\n", "from sklearn import datasets\n", "\n", "digits = datasets.load_digits()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Loaded dataset consists of 8x8 pixels images of hand-written digits.\n", "\n", "Let's display first digit data and label using **data** and **target**." ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "pycharm": { "is_executing": false, "name": "#%%\n" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[ 0. 0. 5. 13. 9. 1. 0. 0.]\n", " [ 0. 0. 13. 15. 10. 15. 5. 0.]\n", " [ 0. 3. 15. 2. 0. 11. 8. 0.]\n", " [ 0. 4. 12. 0. 0. 8. 8. 0.]\n", " [ 0. 5. 8. 0. 0. 9. 8. 0.]\n", " [ 0. 4. 11. 0. 1. 12. 7. 0.]\n", " [ 0. 2. 14. 5. 10. 12. 0. 0.]\n", " [ 0. 0. 6. 13. 10. 0. 0. 0.]]\n" ] } ], "source": [ "print(digits.data[0].reshape((8, 8)))" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "digits.target[0]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the next step, you will count data examples." ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Number of samples: 1797\n" ] } ], "source": [ "samples_count = len(digits.images)\n", "print(\"Number of samples: \" + str(samples_count))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2.2. Create a scikit-learn model" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Prepare data**" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this step, you'll split your data into three datasets:\n", "- train\n", "- test\n", "- score" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Number of training records: 1257\n", "Number of testing records : 360\n", "Number of scoring records : 180\n" ] } ], "source": [ "train_data = digits.data[: int(0.7*samples_count)]\n", "train_labels = digits.target[: int(0.7*samples_count)]\n", "\n", "test_data = digits.data[int(0.7*samples_count): int(0.9*samples_count)]\n", "test_labels = digits.target[int(0.7*samples_count): int(0.9*samples_count)]\n", "\n", "score_data = digits.data[int(0.9*samples_count): ]\n", "\n", "print(\"Number of training records: \" + str(len(train_data)))\n", "print(\"Number of testing records : \" + str(len(test_data)))\n", "print(\"Number of scoring records : \" + str(len(score_data)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Create pipeline**" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Next, you'll create an scikit-learn pipeline." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this step, you will import the scikit-learn machine learning packages to be used in next cells." ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "from sklearn.pipeline import Pipeline\n", "from sklearn import preprocessing\n", "from sklearn import svm, metrics" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Standardize features by removing the mean and scaling to unit variance." ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [], "source": [ "scaler = preprocessing.StandardScaler()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Next, define estimators you want to use for classification. Support Vector Machines (SVM) with the radial basis function as kernel is used in the following example." ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [], "source": [ "clf = svm.SVC(kernel='rbf')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's build the pipeline now. This pipeline consists of a transformer and an estimator." ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [], "source": [ "pipeline = Pipeline([('scaler', scaler), ('svc', clf)])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Train model**" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, you can train your SVM model by using the previously defined **pipeline** and **train data**." ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [], "source": [ "model = pipeline.fit(train_data, train_labels)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Evaluate model**" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can check your **model quality** now. To evaluate the model, use **test data**." ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Evaluation report: \n", "\n", " precision recall f1-score support\n", "\n", " 0 1.00 0.97 0.99 37\n", " 1 0.97 0.97 0.97 34\n", " 2 1.00 0.97 0.99 36\n", " 3 1.00 0.94 0.97 35\n", " 4 0.78 0.97 0.87 37\n", " 5 0.97 0.97 0.97 38\n", " 6 0.97 0.86 0.91 36\n", " 7 0.92 0.97 0.94 35\n", " 8 0.91 0.89 0.90 35\n", " 9 0.97 0.92 0.94 37\n", "\n", " accuracy 0.94 360\n", " macro avg 0.95 0.94 0.95 360\n", "weighted avg 0.95 0.94 0.95 360\n", "\n" ] } ], "source": [ "predicted = model.predict(test_data)\n", "\n", "print(\"Evaluation report: \\n\\n%s\" % metrics.classification_report(test_labels, predicted))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can tune your model now to achieve better accuracy. For simplicity, tuning section is omitted." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "## 3. Persist the locally created scikit-learn model" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this section, you will learn how to store your model in the Watson Machine Learning repository by using the IBM Watson Machine Learning SDK." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 3.1: Publish model" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Publish the model in the Watson Machine Learning repository on Cloud." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Define model name, autor name and email." ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "pycharm": { "is_executing": false, "name": "#%%\n" } }, "outputs": [], "source": [ "sofware_spec_uid = client.software_specifications.get_id_by_name(\"runtime-22.1-py3.9\")" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "pycharm": { "is_executing": false, "name": "#%%\n" } }, "outputs": [], "source": [ "metadata = {\n", " client.repository.ModelMetaNames.NAME: 'Scikit model',\n", " client.repository.ModelMetaNames.TYPE: 'scikit-learn_1.0',\n", " client.repository.ModelMetaNames.SOFTWARE_SPEC_UID: sofware_spec_uid\n", "}\n", "\n", "published_model = client.repository.store_model(\n", " model=model,\n", " meta_props=metadata,\n", " training_data=train_data,\n", " training_target=train_labels)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 3.2: Get model details" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "pycharm": { "is_executing": false, "name": "#%%\n" } }, "outputs": [], "source": [ "import json\n", "\n", "published_model_uid = client.repository.get_model_id(published_model)\n", "model_details = client.repository.get_details(published_model_uid)\n", "print(json.dumps(model_details, indent=2))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 3.3 Get all models" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "pycharm": { "is_executing": false, "name": "#%%\n" } }, "outputs": [], "source": [ "models_details = client.repository.list_models()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "## 4. Deploy and score" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this section, you will learn how to create online scoring and to score a new data record by using the IBM Watson Machine Learning SDK." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 4.1: Create a model deployment" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Create an online deployment for the published model" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "pycharm": { "is_executing": false, "name": "#%%\n" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "#######################################################################################\n", "\n", "Synchronous deployment creation for uid: '5d11ad11-fcc3-49af-afa4-43f6ec139e46' started\n", "\n", "#######################################################################################\n", "\n", "\n", "initializing\n", "Note: online_url is deprecated and will be removed in a future release. Use serving_urls instead.\n", "\n", "ready\n", "\n", "\n", "------------------------------------------------------------------------------------------------\n", "Successfully finished deployment creation, deployment_uid='b857cbaf-7fb2-4d41-b5a7-d3842c13767a'\n", "------------------------------------------------------------------------------------------------\n", "\n", "\n" ] } ], "source": [ "metadata = {\n", " client.deployments.ConfigurationMetaNames.NAME: \"Deployment of scikit model\",\n", " client.deployments.ConfigurationMetaNames.ONLINE: {}\n", "}\n", "\n", "created_deployment = client.deployments.create(published_model_uid, meta_props=metadata)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Note**: Here we use the deployment url saved in the published_model object. In the next section, we show how to retrieve the deployment url from the Watson Machine Learning instance." ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [], "source": [ "deployment_uid = client.deployments.get_id(created_deployment)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now you can print an online scoring endpoint. " ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "pycharm": { "is_executing": false, "name": "#%%\n" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "https://cpd-wmlautoai-jun24.apps.ocp46wmlautoaai.cp.fyre.ibm.com/ml/v4/deployments/b857cbaf-7fb2-4d41-b5a7-d3842c13767a/predictions\n" ] } ], "source": [ "scoring_endpoint = client.deployments.get_scoring_href(created_deployment)\n", "print(scoring_endpoint)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can also list existing deployments." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "client.deployments.list()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 4.2: Get deployment details" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "pycharm": { "is_executing": false, "name": "#%%\n" } }, "outputs": [], "source": [ "client.deployments.get_details(deployment_uid)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 4.3: Score" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can use the following method to perform a test scoring request against the deployed model." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Action**: Prepare scoring payload with records to score." ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [], "source": [ "score_0 = list(score_data[0])\n", "score_1 = list(score_data[1])" ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "pycharm": { "is_executing": false, "name": "#%%\n" } }, "outputs": [], "source": [ "scoring_payload = {\"input_data\": [{\"values\": [score_0, score_1]}]}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Use ``client.deployments.score()`` method to run scoring." ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "pycharm": { "is_executing": false, "name": "#%%\n" } }, "outputs": [], "source": [ "predictions = client.deployments.score(deployment_uid, scoring_payload)" ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "pycharm": { "is_executing": false, "name": "#%%\n" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{\n", " \"predictions\": [\n", " {\n", " \"fields\": [\n", " \"prediction\"\n", " ],\n", " \"values\": [\n", " [\n", " 5\n", " ],\n", " [\n", " 4\n", " ]\n", " ]\n", " }\n", " ]\n", "}\n" ] } ], "source": [ "print(json.dumps(predictions, indent=2))" ] }, { "cell_type": "markdown", "metadata": { "id": "789bca8c-0fb2-4223-bbd7-1a854705f26a" }, "source": [ "\n", "## 5. Create a batch deployment and score using connection asset" ] }, { "cell_type": "markdown", "metadata": { "id": "eddf6718-2cf9-4886-b52c-0eb365ff3139" }, "source": [ "### 5.1: Create a batch deployment of the scikit‑learn model" ] }, { "cell_type": "markdown", "metadata": { "id": "f4539771-3125-4648-bc45-caeb26cce2ba" }, "source": [ "Use the cell below to create a batch deployment for the stored model." ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "id": "03ead939-2bd8-42cc-8186-b1d456938732" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "#######################################################################################\n", "\n", "Synchronous deployment creation for uid: '5d11ad11-fcc3-49af-afa4-43f6ec139e46' started\n", "\n", "#######################################################################################\n", "\n", "\n", "ready.\n", "\n", "\n", "------------------------------------------------------------------------------------------------\n", "Successfully finished deployment creation, deployment_uid='b2d346aa-1fe5-451a-9977-fe17887d96f0'\n", "------------------------------------------------------------------------------------------------\n", "\n", "\n" ] } ], "source": [ "deployment = client.deployments.create(\n", " artifact_uid=published_model_uid,\n", " meta_props={\n", " client.deployments.ConfigurationMetaNames.NAME: \"Batch deployment of scikit model\",\n", " client.deployments.ConfigurationMetaNames.BATCH: {},\n", " client.deployments.ConfigurationMetaNames.HARDWARE_SPEC: {\n", " \"name\": \"S\",\n", " \"num_nodes\": 1\n", " }\n", " }\n", ")\n", "\n", "deployment_uid = client.deployments.get_uid(deployment)" ] }, { "cell_type": "markdown", "metadata": { "id": "133614ea-b1f6-4173-9398-40993e719361" }, "source": [ "## 5.2 Create a connection to an external database" ] }, { "cell_type": "markdown", "metadata": { "id": "85d6c6e3-dd21-40e8-8549-59f94768279e" }, "source": [ "**Action**: Enter your COS credentials in the following cell. \n", "You can find these credentials in your COS instance dashboard under the **Service credentials** tab. \n", "**Note** the HMAC key, described in [set up the environment](#setup) is included in these credentials." ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [], "source": [ "db_name = 'bluemixcloudobjectstorage'\n", "file_name = 'mnist_scoring.csv'" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "bucket_name = 'PUT YOUR COS BUCKET NAME HERE'" ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "id": "4282f158-40ac-4e8d-85b5-d95b9e632244" }, "outputs": [], "source": [ "cos_credentials = {\n", " \"apikey\": \"***\",\n", " \"cos_hmac_keys\": {\n", " \"access_key_id\": \"***\",\n", " \"secret_access_key\": \"***\"\n", " },\n", " \"endpoints\": \"***\",\n", " \"iam_apikey_description\": \"***\",\n", " \"iam_apikey_name\": \"***\",\n", " \"iam_role_crn\": \"***\",\n", " \"iam_serviceid_crn\": \"***\",\n", " \"resource_instance_id\": \"***\"\n", "}" ] }, { "cell_type": "markdown", "metadata": { "id": "66eb83dc-97af-45ce-9560-f0d2bb2a7199" }, "source": [ "#### Create the connection" ] }, { "cell_type": "code", "execution_count": 31, "metadata": { "id": "1ad86053-1f41-4812-823b-4af5cf530996" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Creating connections...\n", "SUCCESS\n" ] } ], "source": [ "conn_meta_props= {\n", " client.connections.ConfigurationMetaNames.NAME: f\"Connection to Database - {db_name} \",\n", " client.connections.ConfigurationMetaNames.DATASOURCE_TYPE: client.connections.get_datasource_type_uid_by_name(db_name),\n", " client.connections.ConfigurationMetaNames.DESCRIPTION: \"Connection to external Database\",\n", " client.connections.ConfigurationMetaNames.PROPERTIES: {\n", " 'bucket': bucket_name,\n", " 'access_key': cos_credentials['cos_hmac_keys']['access_key_id'],\n", " 'secret_key': cos_credentials['cos_hmac_keys']['secret_access_key'],\n", " 'iam_url': 'https://iam.cloud.ibm.com/identity/token',\n", " 'url': 'https://s3.us.cloud-object-storage.appdomain.cloud'\n", " }\n", "}\n", "\n", "conn_details = client.connections.create(meta_props=conn_meta_props)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Note**: The above connection can be initialized alternatively with `api_key` and `resource_instance_id`. \n", "The above cell can be replaced with:\n", "\n", "\n", "```\n", "conn_meta_props= {\n", " client.connections.ConfigurationMetaNames.NAME: f\"Connection to Database - {db_name} \",\n", " client.connections.ConfigurationMetaNames.DATASOURCE_TYPE: client.connections.get_datasource_type_uid_by_name(db_name),\n", " client.connections.ConfigurationMetaNames.DESCRIPTION: \"Connection to external Database\",\n", " client.connections.ConfigurationMetaNames.PROPERTIES: {\n", " 'bucket': bucket_name,\n", " 'api_key': cos_credentials['apikey'],\n", " 'resource_instance_id': cos_credentials['resource_instance_id'],\n", " 'iam_url': 'https://iam.cloud.ibm.com/identity/token',\n", " 'url': 'https://s3.us.cloud-object-storage.appdomain.cloud'\n", " }\n", "}\n", "\n", "conn_details = client.connections.create(meta_props=conn_meta_props)\n", "\n", "```" ] }, { "cell_type": "code", "execution_count": 32, "metadata": { "id": "3c36c589-f247-4269-9abd-be39e194809b" }, "outputs": [], "source": [ "connection_id = client.connections.get_uid(conn_details)" ] }, { "cell_type": "markdown", "metadata": { "id": "a4cd6fb1-c24a-4bb4-ad5a-11d9a61b815a" }, "source": [ "## 5.4 Scoring" ] }, { "cell_type": "markdown", "metadata": { "id": "a51a21e4-45a8-4e26-811e-a06cc5aedc28" }, "source": [ "You can create a batch job using methods listed below." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Upload batch data to the specified location.\n", "**Hint**: To install `pandas` execute `!pip install pandas`" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "from ibm_watson_machine_learning.helpers import DataConnection, S3Location\n", "\n", "\n", "conn = DataConnection(\n", " connection_asset_id=connection_id,\n", " location=S3Location(\n", " bucket=bucket_name,\n", " path=file_name\n", " )\n", ")\n", "\n", "conn._wml_client = client\n", "conn.write(data=pd.DataFrame(data=score_data), remote_name=file_name)" ] }, { "cell_type": "code", "execution_count": 34, "metadata": { "id": "46281d0b-ae4f-4202-ac24-7577ba4577fb" }, "outputs": [], "source": [ "job_payload_ref = {\n", " client.deployments.ScoringMetaNames.INPUT_DATA_REFERENCES: [\n", " {\n", " \"id\": f\"Connection to Database - {db_name}\",\n", " \"name\": \"input_data_href\",\n", " \"type\": \"connection_asset\",\n", " \"connection\": {\n", " \"id\": connection_id\n", " },\n", " \"location\": {\n", " \"bucket\": bucket_name,\n", " 'file_name': file_name\n", " }\n", " }\n", " ],\n", " client.deployments.ScoringMetaNames.OUTPUT_DATA_REFERENCE: {\n", " \"type\": \"connection_asset\",\n", " \"connection\": {\n", " \"id\": connection_id\n", " },\n", " \"location\": {\n", " \"bucket\": bucket_name,\n", " \"file_name\": 'output'\n", " }\n", " }\n", "}\n", "\n", "job = client.deployments.create_job(deployment_uid, meta_props=job_payload_ref)\n", "job_id = client.deployments.get_job_uid(job)" ] }, { "cell_type": "code", "execution_count": 37, "metadata": { "id": "0c4dde7222f7470c89b0c673a1467aa0" }, "outputs": [ { "data": { "text/plain": [ "{'entity': {'deployment': {'id': 'b2d346aa-1fe5-451a-9977-fe17887d96f0'},\n", " 'platform_job': {'job_id': 'b07c0682-bad0-4e9c-bac7-59502c331825',\n", " 'run_id': '2decf6fa-72aa-46b2-9a8d-594d3112a7dc'},\n", " 'scoring': {'input_data_references': [{'connection': {'id': '3cef301b-16f6-4231-b56b-d8dd3703c2d9'},\n", " 'id': 'Connection to Database - bluemixcloudobjectstorage',\n", " 'location': {'bucket': 'tests-wml-samples',\n", " 'file_name': 'mnist_scoring.csv'},\n", " 'type': 'connection_asset'}],\n", " 'output_data_reference': {'connection': {'id': '3cef301b-16f6-4231-b56b-d8dd3703c2d9'},\n", " 'location': {'bucket': 'tests-wml-samples', 'file_name': 'output'},\n", " 'type': 'connection_asset'},\n", " 'status': {'completed_at': '2021-07-19T11:34:34.504993Z',\n", " 'running_at': '2021-07-19T11:34:23.099998Z',\n", " 'state': 'completed'}}},\n", " 'metadata': {'created_at': '2021-07-19T11:34:06.227Z',\n", " 'id': '5731ee76-a3ed-4987-97cd-29c581ba9c1f',\n", " 'modified_at': '2021-07-19T11:34:34.584Z',\n", " 'name': 'name_d72336cd-efb1-4457-a74e-fa67bf2b649f',\n", " 'space_id': '97cebfee-a9da-4c04-822d-f36540c1070d'}}" ] }, "execution_count": 37, "metadata": {}, "output_type": "execute_result" } ], "source": [ "client.deployments.get_job_details(job_id)" ] }, { "cell_type": "markdown", "metadata": { "id": "73c4a886-940b-4b37-b371-0697da6230ce" }, "source": [ "### Monitor job execution\n", "Here you can check the status of your batch scoring. When the batch job is completed the results will be written to an output table." ] }, { "cell_type": "code", "execution_count": 36, "metadata": { "id": "d2efbb31-02a8-4a65-8ca1-99bb13142254" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " Current state: queued\n", " Current state: queued\n", " Current state: running\n", " Current state: completed\n", "{'entity': {'deployment': {'id': 'b2d346aa-1fe5-451a-9977-fe17887d96f0'}, 'platform_job': {'job_id': 'b07c0682-bad0-4e9c-bac7-59502c331825', 'run_id': '2decf6fa-72aa-46b2-9a8d-594d3112a7dc'}, 'scoring': {'input_data_references': [{'connection': {'id': '3cef301b-16f6-4231-b56b-d8dd3703c2d9'}, 'id': 'Connection to Database - bluemixcloudobjectstorage', 'location': {'bucket': 'tests-wml-samples', 'file_name': 'mnist_scoring.csv'}, 'type': 'connection_asset'}], 'output_data_reference': {'connection': {'id': '3cef301b-16f6-4231-b56b-d8dd3703c2d9'}, 'location': {'bucket': 'tests-wml-samples', 'file_name': 'output'}, 'type': 'connection_asset'}, 'status': {'completed_at': '2021-07-19T11:34:34.504993Z', 'running_at': '2021-07-19T11:34:23.099998Z', 'state': 'completed'}}}, 'metadata': {'created_at': '2021-07-19T11:34:06.227Z', 'id': '5731ee76-a3ed-4987-97cd-29c581ba9c1f', 'modified_at': '2021-07-19T11:34:34.584Z', 'name': 'name_d72336cd-efb1-4457-a74e-fa67bf2b649f', 'space_id': '97cebfee-a9da-4c04-822d-f36540c1070d'}}\n" ] } ], "source": [ "import time\n", "\n", "elapsed_time = 0\n", "while client.deployments.get_job_status(job_id).get('state') != 'completed' and elapsed_time < 300:\n", " print(f\" Current state: {client.deployments.get_job_status(job_id).get('state')}\")\n", " elapsed_time += 10\n", " time.sleep(10)\n", "if client.deployments.get_job_status(job_id).get('state') == 'completed':\n", " print(f\" Current state: {client.deployments.get_job_status(job_id).get('state')}\")\n", " job_details_do = client.deployments.get_job_details(job_id)\n", " print(job_details_do)\n", "else:\n", " print(\"Job hasn't completed successfully in 5 minutes.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "## 7. Cleanup " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you want to clean up all created assets:\n", "- experiments\n", "- trainings\n", "- pipelines\n", "- model definitions\n", "- models\n", "- functions\n", "- deployments\n", "\n", "follow the steps listed in this sample [notebook](https://github.com/IBM/watson-machine-learning-samples/blob/master/cpd4.0/notebooks/python_sdk/instance-management/Machine%20Learning%20artifacts%20management.ipynb)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "## 8. Summary and next steps" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " You successfully completed this notebook! You learned how to use scikit-learn machine learning as well as Watson Machine Learning for model creation and deployment. \n", " \n", " Check out our [Online Documentation](https://dataplatform.cloud.ibm.com/docs/content/analyze-data/wml-setup.html) for more samples, tutorials, documentation, how-tos, and blog posts. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Authors\n", "\n", "**Daniel Ryszka**, Software Engineer" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Copyright © 2020-2025 IBM. This notebook and its source code are released under the terms of the MIT License." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "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.9.11" } }, "nbformat": 4, "nbformat_minor": 4 }