Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ibm
GitHub Repository: ibm/watson-machine-learning-samples
Path: blob/master/cloud/notebooks/python_sdk/lifecycle-management/Use scikit-learn and AI lifecycle capabilities to predict California house prices.ipynb
6405 views
Kernel: watsonx-ai-samples-py-3-11

Use scikit-learn and AI lifecycle capabilities to predict California house prices with ibm-watsonx-ai

This notebook contains steps and code to demonstrate support of AI Lifecycle features in watsonx.ai Runtime service. It contains steps and code to work with ibm-watsonx-ai 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.11.

Learning goals

The learning goals of this notebook are:

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

  • Persist an external model in watsonx.ai Runtime 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:

Install and import the ibm-watsonx-ai and dependencies

Note: ibm-watsonx-ai documentation can be found here.

%pip install wget | tail -n 1 %pip install -U ibm-watsonx-ai | tail -n 1 %pip install "scikit-learn==1.3.2" | tail -n 1
Successfully installed wget-3.2 Successfully installed anyio-4.8.0 certifi-2025.1.31 charset-normalizer-3.4.1 h11-0.14.0 httpcore-1.0.7 httpx-0.28.1 ibm-cos-sdk-2.13.6 ibm-cos-sdk-core-2.13.6 ibm-cos-sdk-s3transfer-2.13.6 ibm-watsonx-ai-1.2.8 idna-3.10 jmespath-1.0.1 lomond-0.3.3 numpy-1.26.4 pandas-2.1.4 pytz-2025.1 requests-2.32.2 sniffio-1.3.1 tabulate-0.9.0 tzdata-2025.1 urllib3-2.3.0 Successfully installed joblib-1.4.2 scikit-learn-1.3.2 scipy-1.15.2 threadpoolctl-3.5.0

Connection to watsonx.ai Runtime

Authenticate the watsonx.ai Runtime service on IBM Cloud. You need to provide platform api_key and instance location.

You can use IBM Cloud CLI to retrieve platform API Key and instance location.

API Key can be generated in the following way:

ibmcloud login ibmcloud iam api-key-create API_KEY_NAME

In result, get the value of api_key from the output.

Location of your watsonx.ai Runtime instance can be retrieved in the following way:

ibmcloud login --apikey API_KEY -a https://cloud.ibm.com ibmcloud resource service-instance INSTANCE_NAME

In result, get the value of location from the output.

Tip: Your Cloud API key can be generated by going to the Users section of the Cloud console. 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 watsonx.ai Runtime docs. You can check your instance location in your watsonx.ai Runtime Service instance details.

You can also get service specific apikey by going to the Service IDs section of the Cloud Console. From that page, click Create, then copy the created key and paste it below.

Action: Enter your api_key and location in the following cell.

import getpass api_key = getpass.getpass("Enter your watsonx.ai API key and hit enter: ") location = "PASTE YOUR INSTANCE LOCATION HERE"
from ibm_watsonx_ai import Credentials credentials = Credentials( api_key=api_key, url="https://" + location + ".ml.cloud.ibm.com" )
from ibm_watsonx_ai import APIClient client = APIClient(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 Deployment Spaces Dashboard to create one.

  • Click New Deployment Space

  • Create an empty space

  • Select Cloud Object Storage

  • Select watsonx.ai Runtime instance and press Create

  • 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 watsonx.ai Runtime, 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 = "CALIFORNIA_HOUSE_PRICES_DATA" if not os.path.isdir(data_dir): os.mkdir(data_dir) model_path = os.path.join(data_dir, "california_house_prices_model.tar.gz") updated_model_path = os.path.join(data_dir, "updated_california_house_prices_model.tar.gz") if not os.path.isfile(model_path): wget.download("https://github.com/IBM/watsonx-ai-samples/raw/master/cloud/models/scikit/california_house_prices/model/california_house_prices_model.tar.gz", out=data_dir) if not os.path.isfile(updated_model_path): wget.download("https://github.com/IBM/watsonx-ai-samples/raw/master/cloud/models/scikit/california_house_prices/model/updated_california_house_prices_model.tar.gz", out=data_dir)
import pandas as pd from sklearn import datasets california_data = datasets.fetch_california_housing(as_frame=True) train_df: pd.DataFrame = california_data.frame test_df: pd.DataFrame = california_data.data

3. Persist externally created scikit model

In this section, you will learn how to store your model in watsonx.ai Runtime repository by using the watsonx.ai Client.

3.1: Publish model

Publish model in watsonx.ai Runtime repository on Cloud.

Define model name, author name and email.

sofware_spec_id = client.software_specifications.get_id_by_name("runtime-24.1-py3.11")
metadata = { client.repository.ModelMetaNames.NAME: "External scikit model", client.repository.ModelMetaNames.TYPE: "scikit-learn_1.3", client.repository.ModelMetaNames.SOFTWARE_SPEC_ID: sofware_spec_id } 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_id = client.repository.get_model_id(published_model) model_details = client.repository.get_details(published_model_id) print(json.dumps(model_details, indent=2))
{ "entity": { "hybrid_pipeline_software_specs": [], "software_spec": { "id": "45f12dfe-aa78-5b8d-9f38-0ee223c47309", "name": "runtime-24.1-py3.11" }, "type": "scikit-learn_1.3" }, "metadata": { "created_at": "2025-02-21T10:31:50.012Z", "id": "48a0bb9b-c283-4eb0-8b73-5e0f1da0cd3a", "modified_at": "2025-02-21T10:32:00.720Z", "name": "External scikit model", "owner": "IBMid-696000GJGB", "resource_key": "ed6e17cf-e1c3-4447-8d71-74a374c3cf18", "space_id": "0a20f52a-d5b2-4d22-bfeb-191afc5ab561" }, "system": { "warnings": [] } }

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 watsonx.ai 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_id, meta_props=metadata)
###################################################################################### Synchronous deployment creation for id: '48a0bb9b-c283-4eb0-8b73-5e0f1da0cd3a' started ###################################################################################### initializing ready ----------------------------------------------------------------------------------------------- Successfully finished deployment creation, deployment_id='2ac2960c-9677-4acb-a65f-6403da574f96' -----------------------------------------------------------------------------------------------

Note: Here we use deployment url saved in published_model object. In next section, we show how to retrieve deployment url from watsonx.ai Runtime instance.

deployment_id = client.deployments.get_id(created_deployment)

Now you can print an online scoring endpoint.

scoring_endpoint = client.deployments.get_scoring_href(created_deployment) print(scoring_endpoint)
https://us-south.ml.cloud.ibm.com/ml/v4/deployments/2ac2960c-9677-4acb-a65f-6403da574f96/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_id), indent=2))
{ "entity": { "asset": { "id": "48a0bb9b-c283-4eb0-8b73-5e0f1da0cd3a" }, "custom": {}, "deployed_asset_type": "model", "hardware_spec": { "id": "e7ed1d6c-2e89-42d7-aed5-863b972c1d2b", "name": "S", "num_nodes": 1 }, "name": "Deployment of external scikit model", "online": {}, "space_id": "0a20f52a-d5b2-4d22-bfeb-191afc5ab561", "status": { "inference": [ { "url": "https://us-south.ml.cloud.ibm.com/ml/v4/deployments/2ac2960c-9677-4acb-a65f-6403da574f96/predictions" } ], "online_url": { "url": "https://us-south.ml.cloud.ibm.com/ml/v4/deployments/2ac2960c-9677-4acb-a65f-6403da574f96/predictions" }, "serving_urls": [ "https://us-south.ml.cloud.ibm.com/ml/v4/deployments/2ac2960c-9677-4acb-a65f-6403da574f96/predictions" ], "state": "ready" } }, "metadata": { "created_at": "2025-02-21T10:32:08.241Z", "id": "2ac2960c-9677-4acb-a65f-6403da574f96", "modified_at": "2025-02-21T10:32:08.241Z", "name": "Deployment of external scikit model", "owner": "IBMid-696000GJGB", "space_id": "0a20f52a-d5b2-4d22-bfeb-191afc5ab561" }, "system": { "warnings": [] } }

4.3: Score

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

Action: Prepare scoring payload with records to score.

input_to_score_0 = test_df.iloc[0].to_list() input_to_score_1 = test_df.iloc[1].to_list()
scoring_payload = { "input_data": [ { "values": [ input_to_score_0, input_to_score_1 ] } ] }

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

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

5. Persist new version of the model

In this section, you'll learn how to store new version of your model in watsonx.ai Runtime repository by using the watsonx.ai Client.

5.1: Publish new version of the model

Save the current model version.

print(json.dumps(client.repository.create_model_revision(published_model_id), indent=2))
{ "entity": { "hybrid_pipeline_software_specs": [], "software_spec": { "id": "45f12dfe-aa78-5b8d-9f38-0ee223c47309", "name": "runtime-24.1-py3.11" }, "type": "scikit-learn_1.3" }, "metadata": { "commit_info": { "committed_at": "2025-02-21T10:32:37.002Z" }, "created_at": "2025-02-21T10:31:50.012Z", "id": "48a0bb9b-c283-4eb0-8b73-5e0f1da0cd3a", "modified_at": "2025-02-21T10:32:00.720Z", "name": "External scikit model", "owner": "IBMid-696000GJGB", "resource_key": "ed6e17cf-e1c3-4447-8d71-74a374c3cf18", "rev": "1", "space_id": "0a20f52a-d5b2-4d22-bfeb-191afc5ab561" }, "system": { "warnings": [] } }

Define new model name and update model content.

metadata = { client.repository.ModelMetaNames.NAME: "External scikit model - updated" } published_model = client.repository.update_model( model_id=published_model_id, update_model=updated_model_path, updated_meta_props=metadata )

Save new model revision of the updated model.

new_model_revision = client.repository.create_model_revision(published_model_id) print(json.dumps(new_model_revision, indent=2))
{ "entity": { "hybrid_pipeline_software_specs": [], "software_spec": { "id": "45f12dfe-aa78-5b8d-9f38-0ee223c47309", "name": "runtime-24.1-py3.11" }, "type": "scikit-learn_1.3" }, "metadata": { "commit_info": { "committed_at": "2025-02-21T10:32:48.002Z" }, "created_at": "2025-02-21T10:31:50.012Z", "id": "48a0bb9b-c283-4eb0-8b73-5e0f1da0cd3a", "modified_at": "2025-02-21T10:32:47.367Z", "name": "External scikit model - updated", "owner": "IBMid-696000GJGB", "resource_key": "15beac5b-a1c6-477c-a107-362c41d6547b", "rev": "2", "space_id": "0a20f52a-d5b2-4d22-bfeb-191afc5ab561" }, "system": { "warnings": [] } }

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_id)

5.2: Get model details

import json published_model_id = client.repository.get_model_id(published_model) model_details = client.repository.get_details(published_model_id) print(json.dumps(model_details, indent=2))
{ "entity": { "hybrid_pipeline_software_specs": [], "software_spec": { "id": "45f12dfe-aa78-5b8d-9f38-0ee223c47309", "name": "runtime-24.1-py3.11" }, "type": "scikit-learn_1.3" }, "metadata": { "commit_info": { "committed_at": "2025-02-21T10:32:57.361Z" }, "created_at": "2025-02-21T10:31:50.012Z", "id": "48a0bb9b-c283-4eb0-8b73-5e0f1da0cd3a", "modified_at": "2025-02-21T10:32:52.696Z", "name": "External scikit model - updated", "owner": "IBMid-696000GJGB", "resource_key": "15beac5b-a1c6-477c-a107-362c41d6547b", "space_id": "0a20f52a-d5b2-4d22-bfeb-191afc5ab561" }, "system": { "warnings": [] } }

6. Redeploy new version of the model

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

6.1 Redeploy model

metadata = { client.deployments.ConfigurationMetaNames.ASSET: { "id": published_model_id, "rev": rev_id } } updated_deployment = client.deployments.update(deployment_id=deployment_id, changes=metadata)
Since ASSET is patched, deployment with new asset id/rev is being started. Monitor the status using deployments.get_details(deployment_id) 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_id) 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_id), indent=2))
{ "entity": { "asset": { "id": "48a0bb9b-c283-4eb0-8b73-5e0f1da0cd3a", "rev": "2" }, "custom": {}, "deployed_asset_type": "model", "hardware_spec": { "id": "e7ed1d6c-2e89-42d7-aed5-863b972c1d2b", "name": "S", "num_nodes": 1 }, "name": "Deployment of external scikit model", "online": {}, "space_id": "0a20f52a-d5b2-4d22-bfeb-191afc5ab561", "status": { "inference": [ { "url": "https://us-south.ml.cloud.ibm.com/ml/v4/deployments/2ac2960c-9677-4acb-a65f-6403da574f96/predictions" } ], "message": { "level": "warning", "text": "Successfully patched the asset." }, "online_url": { "url": "https://us-south.ml.cloud.ibm.com/ml/v4/deployments/2ac2960c-9677-4acb-a65f-6403da574f96/predictions" }, "serving_urls": [ "https://us-south.ml.cloud.ibm.com/ml/v4/deployments/2ac2960c-9677-4acb-a65f-6403da574f96/predictions" ], "state": "ready" } }, "metadata": { "created_at": "2025-02-21T10:32:08.241Z", "id": "2ac2960c-9677-4acb-a65f-6403da574f96", "modified_at": "2025-02-21T10:33:02.266Z", "name": "Deployment of external scikit model", "owner": "IBMid-696000GJGB", "space_id": "0a20f52a-d5b2-4d22-bfeb-191afc5ab561" }, "system": { "warnings": [] } }

7. Deployment scaling

In this section, you'll learn how to scale your deployment by creating more copies of stored model with watsonx.ai 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_id, metadata)

7.2 Get scaled deployment details

print(json.dumps(client.deployments.get_details(deployment_id), indent=2))
{ "entity": { "asset": { "id": "48a0bb9b-c283-4eb0-8b73-5e0f1da0cd3a", "rev": "2" }, "custom": {}, "deployed_asset_type": "model", "hardware_spec": { "id": "e7ed1d6c-2e89-42d7-aed5-863b972c1d2b", "name": "S", "num_nodes": 1 }, "name": "Deployment of external scikit model - scaling", "online": {}, "space_id": "0a20f52a-d5b2-4d22-bfeb-191afc5ab561", "status": { "inference": [ { "url": "https://us-south.ml.cloud.ibm.com/ml/v4/deployments/2ac2960c-9677-4acb-a65f-6403da574f96/predictions" } ], "message": { "level": "warning", "text": "scaling_status: inprogress; requested_copies: 2; deployed_copies: 1; more_info: Successfully patched the asset." }, "online_url": { "url": "https://us-south.ml.cloud.ibm.com/ml/v4/deployments/2ac2960c-9677-4acb-a65f-6403da574f96/predictions" }, "scaling": { "attempted_at": "2025-02-21T10:33:10.447Z", "deployed_replicas": 1, "requested_replicas": 2, "state": "in_progress" }, "serving_urls": [ "https://us-south.ml.cloud.ibm.com/ml/v4/deployments/2ac2960c-9677-4acb-a65f-6403da574f96/predictions" ], "state": "ready" } }, "metadata": { "created_at": "2025-02-21T10:32:08.241Z", "id": "2ac2960c-9677-4acb-a65f-6403da574f96", "modified_at": "2025-02-21T10:33:10.638Z", "name": "Deployment of external scikit model - scaling", "owner": "IBMid-696000GJGB", "space_id": "0a20f52a-d5b2-4d22-bfeb-191afc5ab561" }, "system": { "warnings": [] } }

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.

input_to_score_0 = test_df.iloc[0].to_list() input_to_score_1 = test_df.iloc[1].to_list()
scoring_payload = { "input_data": [ { "values": [ input_to_score_0, input_to_score_1 ] } ] }

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

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

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 watsonx.ai 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

Mateusz Szewczyk, Software Engineer watsonx.ai

Rafał Chrzanowski, Software Engineer Intern at watsonx.ai

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