Created
February 21, 2024 15:58
-
-
Save HenrikMader/6068b7df8f078b5a1ea77d90f95a47a3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"cells": [ | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": "\n# Use scikit-learn to recognize hand-written digits with `ibm-watson-machine-learning`\n\nThis notebook contains steps and code to demonstrate how to persist and deploy locally trained scikit-learn model in Watson Machine Learning Service. This notebook contains steps and code to work with [ibm-watson-machine-learning](https://pypi.python.org/pypi/ibm-watson-machine-learning) library available in PyPI repository. This notebook introduces commands for getting model and training data, persisting model, deploying model, scoring it, updating the model and redeploying it.\n\nSome familiarity with Python is helpful. This notebook uses Python with the ibm-watson-machine-learning package." | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": "## Learning goals\n\nThe learning goals of this notebook are:\n\n- Train sklearn model.\n- Persist trained model in Watson Machine Learning repository.\n- Deploy model for online scoring using client library.\n- Score sample records using client library.\n\n\n## Contents\n\nThis notebook contains the following parts:\n\n1. [Setup](#setup)\n2. [Explore data and create scikit-learn model](#train)\n3. [Persist externally created scikit model](#persistence)\n4. [Deploy and score in a Cloud](#scoring)\n5. [Clean up](#cleanup)\n6. [Summary and next steps](#summary)" | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": "<a id=\"setup\"></a>\n## 1. Set up the environment\n\nBefore you use the sample code in this notebook, you must perform the following setup tasks:\n\n- Create a <a href=\"https://console.ng.bluemix.net/catalog/services/ibm-watson-machine-learning/\" target=\"_blank\" rel=\"noopener no referrer\">Watson Machine Learning (WML) Service</a> instance (a free plan is offered and information about how to create the instance can be found <a href=\"https://dataplatform.cloud.ibm.com/docs/content/wsj/analyze-data/ml-service-instance.html\" target=\"_blank\" rel=\"noopener no referrer\">here</a>)." | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": "### Connection to WML\n\nAuthenticate the Watson Machine Learning service on IBM Cloud. You need to provide platform `api_key` and instance `location`.\n\nYou can use [IBM Cloud CLI](https://cloud.ibm.com/docs/cli/index.html) to retrieve platform API Key and instance location.\n\nAPI Key can be generated in the following way:\n```\nibmcloud login\nibmcloud iam api-key-create API_KEY_NAME\n```\n\nIn result, get the value of `api_key` from the output.\n\n\nLocation of your WML instance can be retrieved in the following way:\n```\nibmcloud login --apikey API_KEY -a https://cloud.ibm.com\nibmcloud resource service-instance WML_INSTANCE_NAME\n```\n\nIn result, get the value of `location` from the output." | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": "**Tip**: Your `Cloud API key` can be generated by going to the [**Users** section of the Cloud console](https://cloud.ibm.com/iam#/users). From that page, click your name, scroll down to the **API Keys** section, and click **Create an IBM Cloud API key**. Give your key a name and click **Create**, then copy the created key and paste it below. You can also get a service specific url by going to the [**Endpoint URLs** section of the Watson Machine Learning docs](https://cloud.ibm.com/apidocs/machine-learning). You can check your instance location in your <a href=\"https://console.ng.bluemix.net/catalog/services/ibm-watson-machine-learning/\" target=\"_blank\" rel=\"noopener no referrer\">Watson Machine Learning (WML) Service</a> instance details.\n\nYou can also get service specific apikey by going to the [**Service IDs** section of the Cloud Console](https://cloud.ibm.com/iam/serviceids). From that page, click **Create**, then copy the created key and paste it below.\n\n**Action**: Enter your `api_key` and `location` in the following cell." | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"metadata": {}, | |
"outputs": [], | |
"source": "api_key = '1eIQDe46J-RURbJFeFkyQbohFqpySQzgGtXzKU449pQ0'\nlocation = 'PASTE YOUR INSTANCE LOCATION HERE'" | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"metadata": {}, | |
"outputs": [], | |
"source": "wml_credentials = {\n \"apikey\": api_key,\n \"url\": 'https://' + location + '.ml.cloud.ibm.com'\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 <a href=\"http://ibm-wml-api-pyclient.mybluemix.net/\" target=\"_blank\" rel=\"noopener no referrer\">here</a>." | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"metadata": {}, | |
"outputs": [], | |
"source": "!pip install -U ibm-watson-machine-learning" | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"metadata": {}, | |
"outputs": [], | |
"source": "from ibm_watson_machine_learning import APIClient\n\nclient = APIClient(wml_credentials)" | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": "### Working with spaces\n\nFirst, you need to create a space that will be used for your work. If you do not have space already created, you can use [Deployment Spaces Dashboard](https://dataplatform.cloud.ibm.com/ml-runtime/spaces) to create one.\n\n- Click New Deployment Space\n- Create an empty space\n- Select Cloud Object Storage\n- Select Watson Machine Learning instance and press Create\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/cloud/notebooks/python_sdk/instance-management/Space%20management.ipynb).\n\n**Action**: Assign space ID below" | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": "You can use `list` method to print all existing spaces." | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"metadata": {}, | |
"outputs": [], | |
"source": "client.spaces.list(limit=10)" | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"metadata": {}, | |
"outputs": [], | |
"source": "space_id = 'PASTE YOUR SPACE ID HERE'" | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": "To be able to interact with all resources available in Watson Machine Learning, you need to set the **space** which you will be using." | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"metadata": {}, | |
"outputs": [], | |
"source": "client.set.default_space(space_id)" | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": { | |
"pycharm": { | |
"name": "#%% md\n" | |
} | |
}, | |
"source": "<a id=\"train\"></a>\n## 2. Explore data and create a scikit-learn model\nIn this section, you will prepare and train handwritten digits model using scikit-learn library." | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": "### 2.1 Explore data" | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": "As a first step, you will load the data from scikit-learn sample datasets and perform a basic exploration." | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"metadata": { | |
"pycharm": { | |
"is_executing": false, | |
"name": "#%%\n" | |
} | |
}, | |
"outputs": [], | |
"source": "import sklearn\nfrom sklearn import datasets\n\ndigits = datasets.load_digits()" | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": "Loaded toy dataset consists of 8x8 pixels images of hand-written digits.\n\nLet's display first digit data and label using **data** and **target**." | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"metadata": {}, | |
"outputs": [], | |
"source": "print(digits.data[0])" | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"metadata": { | |
"pycharm": { | |
"is_executing": false, | |
"name": "#%%\n" | |
} | |
}, | |
"outputs": [], | |
"source": "print(digits.data[0].reshape((8, 8)))" | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"metadata": {}, | |
"outputs": [], | |
"source": "digits.target[0]" | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": "In the next step, you will count data examples." | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"metadata": {}, | |
"outputs": [], | |
"source": "samples_count = len(digits.images)\nprint(\"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": null, | |
"metadata": {}, | |
"outputs": [], | |
"source": "train_data = digits.data[: int(0.7*samples_count)]\ntrain_labels = digits.target[: int(0.7*samples_count)]\n\ntest_data = digits.data[int(0.7*samples_count): int(0.9*samples_count)]\ntest_labels = digits.target[int(0.7*samples_count): int(0.9*samples_count)]\n\nscore_data = digits.data[int(0.9*samples_count): ]\n\nprint(\"Number of training records: \" + str(len(train_data)))\nprint(\"Number of testing records : \" + str(len(test_data)))\nprint(\"Number of scoring records : \" + str(len(score_data)))" | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": "**Create pipeline**" | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": "Next, you'll create scikit-learn pipeline." | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": "In ths step, you will import scikit-learn machine learning packages that will be needed in next cells." | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"metadata": {}, | |
"outputs": [], | |
"source": "from sklearn.pipeline import Pipeline\nfrom sklearn import preprocessing\nfrom 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": null, | |
"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 radial basis function as kernel is used in the following example." | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"metadata": {}, | |
"outputs": [], | |
"source": "clf = svm.SVC(kernel='rbf')" | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": "Let's build the pipeline now. This pipeline consists of transformer and an estimator." | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"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": null, | |
"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": null, | |
"metadata": {}, | |
"outputs": [], | |
"source": "predicted = model.predict(test_data)\n\nprint(\"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 of this example tuning section is omitted." | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": "<a id=\"persistence\"></a>\n## 3. Persist locally created scikit-learn model" | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": "In this section, you will learn how to store your model in 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 model in Watson Machine Learning repository on Cloud." | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": "Define model name, autor name and email." | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"metadata": { | |
"pycharm": { | |
"is_executing": false, | |
"name": "#%%\n" | |
} | |
}, | |
"outputs": [], | |
"source": "sofware_spec_uid = client.software_specifications.get_id_by_name(\"runtime-23.1-py3.10\")" | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"metadata": {}, | |
"outputs": [], | |
"source": "print(sofware_spec_uid)" | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"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.1',\n client.repository.ModelMetaNames.SOFTWARE_SPEC_UID: sofware_spec_uid\n}\n\npublished_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\npublished_model_uid = client.repository.get_model_id(published_model)\nmodel_details = client.repository.get_details(published_model_uid)\nprint(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": "<a id=\"scoring\"></a>\n## 4. Deploy and score in a Cloud" | |
}, | |
{ | |
"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 model deployment" | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": "#### Create online deployment for published model" | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"metadata": { | |
"pycharm": { | |
"is_executing": false, | |
"name": "#%%\n" | |
} | |
}, | |
"outputs": [], | |
"source": "metadata = {\n client.deployments.ConfigurationMetaNames.NAME: \"Deployment of scikit model\",\n client.deployments.ConfigurationMetaNames.ONLINE: {}\n}\n\ncreated_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 next section, we show how to retrieve the deployment url from a Watson Machine Learning instance." | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"metadata": {}, | |
"outputs": [], | |
"source": "deployment_uid = client.deployments.get_uid(created_deployment)" | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": "Now you can print an online scoring endpoint. " | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"metadata": { | |
"pycharm": { | |
"is_executing": false, | |
"name": "#%%\n" | |
} | |
}, | |
"outputs": [], | |
"source": "scoring_endpoint = client.deployments.get_scoring_href(created_deployment)\nprint(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 do test scoring request against deployed model." | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": "**Action**: Prepare scoring payload with records to score." | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"metadata": {}, | |
"outputs": [], | |
"source": "score_0 = list(score_data[0])\nscore_1 = list(score_data[1])" | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"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": null, | |
"metadata": { | |
"pycharm": { | |
"is_executing": false, | |
"name": "#%%\n" | |
} | |
}, | |
"outputs": [], | |
"source": "predictions = client.deployments.score(deployment_uid, scoring_payload)" | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"metadata": { | |
"pycharm": { | |
"is_executing": false, | |
"name": "#%%\n" | |
} | |
}, | |
"outputs": [], | |
"source": "print(json.dumps(predictions, indent=2))" | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": "<a id=\"cleanup\"></a>\n## 5. Clean up" | |
}, | |
{ | |
"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\nplease follow up this sample [notebook](https://github.com/IBM/watson-machine-learning-samples/blob/master/cloud/notebooks/python_sdk/instance-management/Machine%20Learning%20artifacts%20management.ipynb)." | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": "<a id=\"summary\"></a>\n## 6. 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. Check out our _[Online Documentation](https://dataplatform.cloud.ibm.com/docs/content/wsj/getting-started/welcome-main.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 \u00a9 2020 IBM. This notebook and its source code are released under the terms of the MIT License." | |
} | |
], | |
"metadata": { | |
"kernelspec": { | |
"display_name": "Python 3.10", | |
"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.10.13" | |
}, | |
"pycharm": { | |
"stem_cell": { | |
"cell_type": "raw", | |
"metadata": { | |
"collapsed": false | |
}, | |
"source": [] | |
} | |
} | |
}, | |
"nbformat": 4, | |
"nbformat_minor": 4 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment