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

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.12.

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:

  • Contact with your Cloud Pak for Data administrator and ask them for your account credentials

Install dependencies

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

%pip install wget | tail -n 1 %pip install "ibm-watsonx-ai>=1.3.14" | tail -n 1 %pip install "scikit-learn==1.6.1" | tail -n 1
Successfully installed wget-3.2 Successfully installed ibm-watsonx-ai-1.3.14 Successfully installed scikit-learn-1.6.1

Define credentials

Authenticate the watsonx.ai Runtime service on IBM Cloud Pak for Data. You need to provide the admin's username and the platform url.

username = "PASTE YOUR USERNAME HERE" url = "PASTE THE PLATFORM URL HERE"

Use the admin's api_key to authenticate watsonx.ai Runtime:

import getpass from ibm_watsonx_ai import Credentials credentials = Credentials( username=username, api_key=getpass.getpass("Enter your watsonx.ai API key and hit enter: "), url=url, instance_id="openshift", version="5.2", )

Alternatively you can use the admin's password:

import getpass from ibm_watsonx_ai import Credentials if "credentials" not in locals() or not credentials.api_key: credentials = Credentials( username=username, password=getpass.getpass("Enter your watsonx.ai password and hit enter: "), url=url, instance_id="openshift", version="5.2", )

Create APIClient instance

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 {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 watsonx.ai, 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/cpd5.2/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/cpd5.2/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 Pak for Data.

Define model name, author name and email.

sofware_spec_id = client.software_specifications.get_id_by_name("runtime-25.1-py3.12")
metadata = { client.repository.ModelMetaNames.NAME: "External scikit model", client.repository.ModelMetaNames.TYPE: "scikit-learn_1.6", 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))
{ "metadata": { "name": "External scikit model", "space_id": "2c457214-b038-44f9-b05d-4f5a67633853", "resource_key": "05496178-b554-4296-bec7-3ecd7a6275dd", "id": "3513f8b7-9c2d-46b3-86a8-781cb797db84", "created_at": "2025-04-30T13:02:33Z", "rov": { "member_roles": { "1000331001": { "user_iam_id": "1000331001", "roles": [ "OWNER" ] } } }, "owner": "1000331001" }, "entity": { "software_spec": { "id": "f47ae1c3-198e-5718-b59d-2ea471561e9e" }, "type": "scikit-learn_1.6" } }

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: '3513f8b7-9c2d-46b3-86a8-781cb797db84' started ###################################################################################### initializing Note: online_url is deprecated and will be removed in a future release. Use serving_urls instead. ready ----------------------------------------------------------------------------------------------- Successfully finished deployment creation, deployment_id='9425c145-66e0-4c59-926b-62268fb80f17' -----------------------------------------------------------------------------------------------

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)

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

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.13735959280643 ], [ 3.9916712643047543 ] ] } ] }

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))
{ "metadata": { "name": "External scikit model", "space_id": "2c457214-b038-44f9-b05d-4f5a67633853", "resource_key": "05496178-b554-4296-bec7-3ecd7a6275dd", "id": "3513f8b7-9c2d-46b3-86a8-781cb797db84", "created_at": "2025-04-30T13:02:33Z", "rev": "1", "commit_info": { "committed_at": "2025-04-30T13:03:02Z" }, "rov": { "member_roles": { "1000331001": { "user_iam_id": "1000331001", "roles": [ "OWNER" ] } } }, "owner": "1000331001" }, "entity": { "software_spec": { "id": "f47ae1c3-198e-5718-b59d-2ea471561e9e" }, "type": "scikit-learn_1.6" } }

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_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))
{ "metadata": { "name": "External scikit model - updated", "space_id": "2c457214-b038-44f9-b05d-4f5a67633853", "resource_key": "aefaa88a-84f5-4bc9-9ad3-20c9ae965e92", "id": "3513f8b7-9c2d-46b3-86a8-781cb797db84", "created_at": "2025-04-30T13:02:33Z", "rev": "2", "commit_info": { "committed_at": "2025-04-30T13:03:34Z" }, "rov": { "member_roles": { "1000331001": { "user_iam_id": "1000331001", "roles": [ "OWNER" ] } } }, "owner": "1000331001" }, "entity": { "software_spec": { "id": "f47ae1c3-198e-5718-b59d-2ea471561e9e" }, "type": "scikit-learn_1.6" } }

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))
{ "metadata": { "name": "External scikit model - updated", "space_id": "2c457214-b038-44f9-b05d-4f5a67633853", "resource_key": "aefaa88a-84f5-4bc9-9ad3-20c9ae965e92", "id": "3513f8b7-9c2d-46b3-86a8-781cb797db84", "created_at": "2025-04-30T13:02:33Z", "commit_info": { "committed_at": "2025-04-30T13:02:33Z" }, "rov": { "member_roles": { "1000331001": { "user_iam_id": "1000331001", "roles": [ "OWNER" ] } } }, "owner": "1000331001" }, "entity": { "software_spec": { "id": "f47ae1c3-198e-5718-b59d-2ea471561e9e" }, "type": "scikit-learn_1.6" } }

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 need to be restarted. ######################################################################## Deployment update for id: '9425c145-66e0-4c59-926b-62268fb80f17' started ######################################################################## updating ready --------------------------------------------------------------------------------------------- Successfully finished deployment update, deployment_id='9425c145-66e0-4c59-926b-62268fb80f17' ---------------------------------------------------------------------------------------------

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)
. Note: online_url is deprecated and will be removed in a future release. Use serving_urls instead. Deployment update finished with status: ready

6.2 Get updated deployment details

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

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)
######################################################################## Deployment update for id: '9425c145-66e0-4c59-926b-62268fb80f17' started ######################################################################## ready. --------------------------------------------------------------------------------------------- Successfully finished deployment update, deployment_id='9425c145-66e0-4c59-926b-62268fb80f17' ---------------------------------------------------------------------------------------------

7.2 Get scaled deployment details

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

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.1362218361724805 ], [ 3.9894813058082876 ] ] } ] }

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

Jan Sołtysik, Intern

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.