Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ibm
GitHub Repository: ibm/watson-machine-learning-samples
Path: blob/master/cpd4.0/notebooks/python_sdk/lifecycle-management/Use scikit-learn and AI lifecycle capabilities to predict Boston house prices.ipynb
6405 views
Kernel: Python 3 (ipykernel)

Use scikit-learn and AI lifecycle capabilities to predict Boston house prices with ibm-watson-machine-learning

This notebook contains steps and code to demonstrate support of AI Lifecycle features in Watson Machine Learning Service. It contains steps and code to work with ibm-watson-machine-learning library available in PyPI repository. It also introduces commands for getting model and training data, persisting model, deploying model, scoring it, updating the model and redeploying it.

Some familiarity with Python is helpful. This notebook uses Python 3.9.

Learning goals

The learning goals of this notebook are:

  • Download an externally trained scikit-learn model with dataset.

  • Persist an external model in Watson Machine Learning repository.

  • Deploy model for online scoring using client library.

  • Score sample records using client library.

  • Update previously persisted model.

  • Redeploy model in-place.

  • Scale deployment.

Contents

This notebook contains the following parts:

  1. Setup

  2. Download externally created scikit model and data

  3. Persist externally created scikit model

  4. Deploy and score in a Cloud

  5. Persist new version of the model

  6. Redeploy new version of the model

  7. Deployment scaling

  8. Clean up

  9. Summary and next steps

1. Set up the environment

Before you use the sample code in this notebook, you must perform the following setup tasks:

  • Contact with your Cloud Pack for Data administrator and ask him for your account credentials

Connection to WML

Authenticate the Watson Machine Learning service on IBM Cloud Pack for Data. You need to provide platform url, your username and api_key.

username = 'PASTE YOUR USERNAME HERE' api_key = 'PASTE YOUR API_KEY HERE' url = 'PASTE THE PLATFORM URL HERE'
wml_credentials = { "username": username, "apikey": api_key, "url": url, "instance_id": 'openshift', "version": '4.0' }

Alternatively you can use username and password to authenticate WML services.

wml_credentials = { "username": ***, "password": ***, "url": ***, "instance_id": 'openshift', "version": '4.0' }

Install and import the ibm-watson-machine-learning package

Note: ibm-watson-machine-learning documentation can be found here.

!pip install -U ibm-watson-machine-learning
from ibm_watson_machine_learning import APIClient client = APIClient(wml_credentials)

Working with spaces

First of all, you need to create a space that will be used for your work. If you do not have space already created, you can use {PLATFORM_URL}/ml-runtime/spaces?context=icp4data to create one.

  • Click New Deployment Space

  • Create an empty space

  • Go to space Settings tab

  • Copy space_id and paste it below

Tip: You can also use SDK to prepare the space for your work. More information can be found here.

Action: Assign space ID below

space_id = 'PASTE YOUR SPACE ID HERE'

You can use list method to print all existing spaces.

client.spaces.list(limit=10)

To be able to interact with all resources available in Watson Machine Learning, you need to set space which you will be using.

client.set.default_space(space_id)
'SUCCESS'

2. Download externally created scikit model and data

In this section, you will download externally created scikit models and data used for training it.

import os import wget data_dir = 'BOSTON_HOUSE_PRICES_DATA' if not os.path.isdir(data_dir): os.mkdir(data_dir) model_path = os.path.join(data_dir, 'boston_regressor_0_23_1.tar.gz') new_model_path = os.path.join(data_dir, 'boston_regressor_new_0_23_1.tar.gz') if not os.path.isfile(model_path): wget.download("https://github.com/IBM/watson-machine-learning-samples/raw/master/cpd4.0/models/scikit/boston_house_price/model/boston_regressor_0_23_1.tar.gz", out=data_dir) if not os.path.isfile(new_model_path): wget.download("https://github.com/IBM/watson-machine-learning-samples/raw/master/cpd4.0/models/scikit/boston_house_price/model/boston_regressor_new_0_23_1.tar.gz", out=data_dir)
from sklearn import datasets import pandas as pd boston_data = datasets.load_boston() boston_df = pd.DataFrame(boston_data.data) boston_df.columns = boston_data.feature_names boston_df['PRICE'] = boston_data.target
train_df = boston_df test_df = boston_df.drop(['PRICE'], axis=1)

3. Persist externally created scikit model

In this section, you will learn how to store your model in Watson Machine Learning repository by using the Watson Machine Learning Client.

3.1: Publish model

Publish model in Watson Machine Learning repository on Cloud.

Define model name, autor name and email.

sofware_spec_uid = client.software_specifications.get_id_by_name("runtime-22.1-py3.9")
metadata = { client.repository.ModelMetaNames.NAME: 'External scikit model', client.repository.ModelMetaNames.TYPE: 'scikit-learn_1.0', client.repository.ModelMetaNames.SOFTWARE_SPEC_UID: sofware_spec_uid } published_model = client.repository.store_model( model=model_path, meta_props=metadata, training_data=train_df)

3.2: Get model details

import json published_model_uid = client.repository.get_model_id(published_model) model_details = client.repository.get_details(published_model_uid) print(json.dumps(model_details, indent=2))

3.3 Get all models

models_details = client.repository.list_models(limit=10)

4. Deploy and score in a Cloud

In this section you will learn how to create online scoring and to score a new data record by using the Watson Machine Learning Client.

4.1: Create model deployment

Create online deployment for published model

metadata = { client.deployments.ConfigurationMetaNames.NAME: "Deployment of external scikit model", client.deployments.ConfigurationMetaNames.ONLINE: {} } created_deployment = client.deployments.create(published_model_uid, meta_props=metadata)
####################################################################################### Synchronous deployment creation for uid: 'adf70e8b-d060-4f50-b37d-5760797e5052' started ####################################################################################### initializing. ready ------------------------------------------------------------------------------------------------ Successfully finished deployment creation, deployment_uid='47fce40d-2e2c-43da-af37-1cd8c131a18d' ------------------------------------------------------------------------------------------------

Note: Here we use deployment url saved in published_model object. In next section, we show how to retrive deployment url from Watson Machine Learning instance.

deployment_uid = client.deployments.get_uid(created_deployment)

Now you can print an online scoring endpoint.

scoring_endpoint = client.deployments.get_scoring_href(created_deployment) print(scoring_endpoint)
https://wmlgmc-cpd-wmlgmc.apps.wmlautoai.cp.fyre.ibm.com/ml/v4/deployments/47fce40d-2e2c-43da-af37-1cd8c131a18d/predictions

You can also list existing deployments.

client.deployments.list(limit=10)

4.2: Get deployment details

print(json.dumps(client.deployments.get_details(deployment_uid), indent=2))

4.3: Score

You can use below method to do test scoring request against deployed model.

Action: Prepare scoring payload with records to score.

score_0 = list(test_df.iloc[0]) score_1 = list(test_df.iloc[1])
scoring_payload = {"input_data": [{"values": [score_0, score_1]}]}

Use client.deployments.score() method to run scoring.

predictions = client.deployments.score(deployment_uid, scoring_payload)
print(json.dumps(predictions, indent=2))
{ "predictions": [ { "fields": [ "prediction" ], "values": [ [ 30.0038433770168 ], [ 25.025562379053415 ] ] } ] }

5. Persist new version of the model

In this section, you'll learn how to store new version of your model in Watson Machine Learning repository by using the Watson Machine Learning Client.

5.1: Publish new version of the model

Save the current model version.

print(json.dumps(client.repository.create_model_revision(published_model_uid), indent=2))

Define new model name and update model content.

metadata = { client.repository.ModelMetaNames.NAME: 'External scikit model - updated' } published_model = client.repository.update_model( model_uid=published_model_uid, update_model=new_model_path, updated_meta_props=metadata )

Save new model revision of the updated model.

new_model_revision = client.repository.create_model_revision(published_model_uid) print(json.dumps(new_model_revision, indent=2))

Note: Model revisions can be identified by model id and rev number.

Get model rev number from creation details:

rev_id = new_model_revision['metadata'].get('rev')

You can list existing revisions of the model.

client.repository.list_models_revisions(published_model_uid)
-- ------------------------------- ------------------------ ID NAME CREATED 2 External scikit model - updated 2020-12-08T13:40:52.523Z 1 External scikit model 2020-12-08T13:40:52.523Z -- ------------------------------- ------------------------

5.2: Get model details

import json published_model_uid = client.repository.get_model_id(published_model) model_details = client.repository.get_details(published_model_uid) print(json.dumps(model_details, indent=2))

6. Redeploy new version of the model

In this section, you'll learn how to redeploy new version of the model by using the Watson Machine Learning Client.

6.1 Redeploy model

metadata = { client.deployments.ConfigurationMetaNames.ASSET: { "id": published_model_uid, "rev": rev_id } } updated_deployment = client.deployments.update(deployment_uid=deployment_uid, changes=metadata)
Since ASSET is patched, deployment with new asset id/rev is being started. Monitor the status using deployments.get_details(deployment_uid) api

Wait for the deployment update:

import time status = None while status not in ['ready', 'failed']: print('.', end=' ') time.sleep(2) deployment_details = client.deployments.get_details(deployment_uid) status = deployment_details['entity']['status'].get('state') print("\nDeployment update finished with status: ", status)
. . Deployment update finished with status: ready

6.2 Get updated deployment details

print(json.dumps(client.deployments.get_details(deployment_uid), indent=2))

7. Deployment scaling

In this section, you'll learn how to scale your deployment by creating more copies of stored model with Watson Machine Learning Client. This feature is for providing High-Availability and to support higher throughput

7.1 Scale deployment

In this example, 2 deployment copies will be made.

metadata = { client.deployments.ConfigurationMetaNames.NAME: "Deployment of external scikit model - scaling", client.deployments.ConfigurationMetaNames.HARDWARE_SPEC: { "name": "S", "num_nodes": 2 } }
scaled_deployment = client.deployments.update(deployment_uid, metadata)

7.2 Get scaled deployment details

print(json.dumps(client.deployments.get_details(deployment_uid), indent=2))
{ "entity": { "asset": { "id": "adf70e8b-d060-4f50-b37d-5760797e5052", "rev": "2" }, "custom": {}, "deployed_asset_type": "model", "hardware_spec": { "id": "Not_Applicable", "name": "S", "num_nodes": 2 }, "name": "Deployment of external scikit model - scaling", "online": {}, "space_id": "cc59083a-923f-4c35-8947-10c126343bd0", "status": { "message": { "text": "scaling_status: completed;requested_copies: 2;deployed_copies: 2;more_info: Successfully patched the asset ", "level": "warning" }, "online_url": { "url": "https://wmlgmc-cpd-wmlgmc.apps.wmlautoai.cp.fyre.ibm.com/ml/v4/deployments/47fce40d-2e2c-43da-af37-1cd8c131a18d/predictions" }, "state": "ready" } }, "metadata": { "created_at": "2020-12-08T13:41:07.003Z", "id": "47fce40d-2e2c-43da-af37-1cd8c131a18d", "modified_at": "2020-12-08T13:42:27.361Z", "name": "Deployment of external scikit model - scaling", "owner": "1000330999", "space_id": "cc59083a-923f-4c35-8947-10c126343bd0" } }

7.3 Score updated deployment

You can use below method to do test scoring request against deployed model.

Action: Prepare scoring payload with records to score.

score_0 = list(test_df.iloc[0]) score_1 = list(test_df.iloc[1])
scoring_payload = {"input_data": [{"values": [score_0, score_1]}]}

Use client.deployments.score() method to run scoring.

predictions = client.deployments.score(deployment_uid, scoring_payload)
print(json.dumps(predictions, indent=2))
{ "predictions": [ { "fields": [ "prediction" ], "values": [ [ 25.340000000000003 ], [ 22.06799999999997 ] ] } ] }

8. Clean up

If you want to clean up all created assets:

  • experiments

  • trainings

  • pipelines

  • model definitions

  • models

  • functions

  • deployments

please follow up this sample notebook.

9. Summary and next steps

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 for more samples, tutorials, documentation, how-tos, and blog posts.

Authors

Daniel Ryszka, Software Engineer Jan Sołtysik, Intern

Copyright © 2020-2025 IBM. This notebook and its source code are released under the terms of the MIT License.