Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ibm
GitHub Repository: ibm/watson-machine-learning-samples
Path: blob/master/cpd5.1/notebooks/python_sdk/deployments/tensorflow/Use Tensorflow to recognize hand-written digits.ipynb
6405 views
Kernel: Python 3 (ipykernel)

Use Tensorflow to recognize hand-written digits with ibm-watsonx-ai

This notebook facilitates Tensorflow and Watson Machine Learning 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 and scoring 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 Tensorflow 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.

Contents

This notebook contains the following parts:

  1. Setup

  2. Download externally created Tensorflow model and data

  3. Persist externally created Tensforflow model

  4. Deploy and score

  5. Clean up

  6. 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 and import the ibm-watsonx-ai and dependecies

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

!pip install wget | tail -n 1 !pip install matplotlib | tail -n 1 !pip install -U ibm-watsonx-ai | tail -n 1

Connection to WML

Authenticate the Watson Machine Learning service on IBM Cloud Pak 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'
from ibm_watsonx_ai import Credentials credentials = Credentials( username=username, api_key=api_key, url=url, instance_id="openshift", version="5.1" )

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

credentials = Credentials( username=***, password=***, url=***, instance_id="openshift", version="5.1" )
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 Watson Machine Learning, you need to set space which you will be using.

client.set.default_space(space_id)
'SUCCESS'

2. Download externally created Tensorflow model and data

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

import os import wget data_dir = 'MNIST_DATA' if not os.path.isdir(data_dir): os.mkdir(data_dir) model_path = os.path.join(data_dir, 'mnist-tf-hpo-saved-model.tar.gz') if not os.path.isfile(model_path): wget.download("https://github.com/IBM/watson-machine-learning-samples/raw/master/cpd5.1/models/tensorflow/mnist/mnist-tf-hpo-saved-model.tar.gz", out=data_dir)
data_dir = 'MNIST_DATA' if not os.path.isdir(data_dir): os.mkdir(data_dir) filename = os.path.join(data_dir, 'mnist.npz') if not os.path.isfile(filename): wget.download('https://s3.amazonaws.com/img-datasets/mnist.npz', out=data_dir)
import numpy as np dataset = np.load(filename) x_test = dataset['x_test']

3. Persist externally created Tensorflow model

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

3.1: Publish model

Publish model in Watson Machine Learning repository on Cloud.

Define model name, autor name and email.

sofware_spec_id = client.software_specifications.get_id_by_name("runtime-24.1-py3.11")
metadata = { client.repository.ModelMetaNames.NAME: 'External Tensorflow model', client.repository.ModelMetaNames.TYPE: 'tensorflow_2.14', client.repository.ModelMetaNames.SOFTWARE_SPEC_ID: sofware_spec_id } published_model = client.repository.store_model( model=model_path, meta_props=metadata)

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

3.3 Get all models

models_details = client.repository.list_models()

4. Deploy and score

In this section you will learn how to create online scoring and to score a new data record by using the IBM watsonx.ai SDK.

4.1: Create model deployment

Create online deployment for published model

metadata = { client.deployments.ConfigurationMetaNames.NAME: "Deployment of external Tensorflow model", client.deployments.ConfigurationMetaNames.ONLINE: {} } created_deployment = client.deployments.create(published_model_id, meta_props=metadata)
###################################################################################### Synchronous deployment creation for id: '48fcb424-6fe4-4480-b2f3-3949e6e70234' 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='6c455efb-a93a-4cd9-9c42-c1d241ebc2a8' -----------------------------------------------------------------------------------------------

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

4.2: Get deployment details

client.deployments.get_details(deployment_id)

4.3: Score

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

Let's first visualize two samples from dataset, we'll use for scoring.

%matplotlib inline import matplotlib.pyplot as plt
for i, image in enumerate([x_test[0], x_test[1]]): plt.subplot(2, 2, i + 1) plt.axis('off') plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
Image in a Jupyter notebook

Prepare scoring payload with records to score.

score_0 = x_test[0].flatten().tolist() score_1 = x_test[1].flatten().tolist()
scoring_payload = {"input_data": [{"values": [score_0, score_1]}]}

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

predictions = client.deployments.score(deployment_id, scoring_payload)

Let's print the result of predictions.

import json print(json.dumps(predictions, indent=2))
{ "predictions": [ { "id": "classes", "values": [ 7, 2 ] } ] }

As you can see, predicted values are the same one as displayed above from test dataset.

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

6. Summary and next steps

You successfully completed this notebook! You learned how to use Pytorch machine learning library 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

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