Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ibm
GitHub Repository: ibm/watson-machine-learning-samples
Path: blob/master/cloud/notebooks/python_sdk/converters/Use ONNX model converted from TensorFlow to recognize hand-written digits.ipynb
9339 views
Kernel: .venv_watsonx_ai_samples_py_312

Use ONNX model converted from TensorFlow to recognize hand-written digits with ibm-watsonx-ai

This notebook facilitates ONNX, Tensorflow (and TF.Keras), and watsonx.ai Runtime service. It contains steps and code to work with ibm-watsonx-ai library available in PyPI repository in order to convert the TensorFlow model to ONNX format. 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.12.

Learning goals

The learning goals of this notebook are:

  • Download an externally trained TensorFlow model with dataset.

  • Convert TensorFlow model to ONNX format

  • Persist converted model in watsonx.ai Runtime repository.

  • Deploy model for online scoring using client library.

  • Score sample records using client library.

Contents

This notebook contains the following parts:

  1. Setting up the environment

  2. Downloading externally created TensorFlow model and data

  3. Converting TensorFlow model to ONNX format

  4. Persisting converted ONNX model

  5. Deploying and scoring ONNX model

  6. Cleaning up

  7. Summary and next steps

1. Setting up the environment

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

Install dependencies

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 %pip install "tensorflow==2.18" | tail -n 1 %pip install "tf2onnx==1.16" | tail -n 1 %pip install "onnxruntime==1.21.0" | tail -n 1 %pip install "numpy>=1.26.4,<2" | tail -n 1
Successfully installed wget-3.2 Successfully installed contourpy-1.3.3 cycler-0.12.1 fonttools-4.61.1 kiwisolver-1.4.9 matplotlib-3.10.8 numpy-2.4.2 pillow-12.1.1 pyparsing-3.3.2 Successfully installed anyio-4.12.1 cachetools-7.0.1 certifi-2026.1.4 charset_normalizer-3.4.4 h11-0.16.0 httpcore-1.0.9 httpx-0.28.1 ibm-cos-sdk-2.14.3 ibm-cos-sdk-core-2.14.3 ibm-cos-sdk-s3transfer-2.14.3 ibm-watsonx-ai-1.5.2 idna-3.11 jmespath-1.0.1 lomond-0.3.3 pandas-2.3.3 pytz-2025.2 requests-2.32.5 tabulate-0.9.0 typing_extensions-4.15.0 tzdata-2025.3 urllib3-2.6.3 Successfully installed absl-py-2.4.0 astunparse-1.6.3 flatbuffers-25.12.19 gast-0.7.0 google-pasta-0.2.0 grpcio-1.78.0 h5py-3.15.1 keras-3.13.2 libclang-18.1.1 markdown-3.10.2 markdown-it-py-4.0.0 markupsafe-3.0.3 mdurl-0.1.2 ml-dtypes-0.4.1 namex-0.1.0 numpy-2.0.2 opt-einsum-3.4.0 optree-0.18.0 protobuf-5.29.6 rich-14.3.2 tensorboard-2.18.0 tensorboard-data-server-0.7.2 tensorflow-2.18.0 termcolor-3.3.0 werkzeug-3.1.5 wheel-0.46.3 wrapt-2.1.1 Successfully installed onnx-1.17.0 protobuf-3.20.3 tf2onnx-1.16.0 Successfully installed coloredlogs-15.0.1 humanfriendly-10.0 mpmath-1.3.0 onnxruntime-1.21.0 sympy-1.14.0 Successfully installed numpy-1.26.4

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 url and api_key in the following cell.

import getpass from ibm_watsonx_ai import Credentials credentials = Credentials( url="https://us-south.ml.cloud.ibm.com", api_key=getpass.getpass("Please enter your watsonx.ai api key (hit enter): "), )
from ibm_watsonx_ai import APIClient client = APIClient(credentials)

1.3. 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 the ibm_watsonx_ai SDK to prepare the space for your work. More information can be found here.

Action: Assign space ID below

space_id = "ENTER 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. Downloading externally created TensorFlow model and data

In this section, you will download externally created TensorFlow models and data used for training it. You can choose to download either a TensorFlow or a Keras model.

2.1. Downloading dataset

from pathlib import Path data_dir = Path("MNIST_DATA") if not data_dir.is_dir(): data_dir.mkdir()
import wget data_path = data_dir / "mnist.npz" if not data_path.is_file(): wget.download("https://s3.amazonaws.com/img-datasets/mnist.npz", out=str(data_dir))
import numpy as np dataset = np.load(data_path) x_test = dataset["x_test"]

2.2. Downloading TensorFlow model

tf_model_name = "mnist-tf-model" model_tar_name = f"{tf_model_name}.tar.gz" model_path = data_dir / model_tar_name if not model_path.is_file(): wget.download( f"https://github.com/IBM/watsonx-ai-samples/raw/master/cloud/models/tensorflow/mnist/{model_tar_name}", out=str(data_dir), )

3. Converting TensorFlow model to ONNX format

In this section, you will unpack externally created TensorFlow models, provided in either SavedModel or Keras format (depending on your earlier selection), from the tar archive and convert them to the ONNX format. More information can be found here.

onnx_model_name = "tf_model.onnx"

3.1. Converting TensorFlow SavedModel

import os import tarfile os.makedirs(tf_model_name, exist_ok=True) tar_path = f"MNIST_DATA/{model_tar_name}" with tarfile.open(tar_path, "r:gz") as tar: tar.extractall(path=tf_model_name, filter="data")

Note: If you are working with TensorFlow Lite models, make sure to use the --tflite flag instead of --saved-model.

Tip: You can also run this command from the CLI:

python -m tf2onnx.convert --saved-model $tf_model_name --output $onnx_model_name
import logging import runpy import sys old_argv = sys.argv try: sys.argv = ["python", "--saved-model", tf_model_name, "--output", onnx_model_name] runpy.run_module("tf2onnx.convert", run_name="__main__") finally: sys.argv = old_argv logging.getLogger().setLevel(logging.WARNING)
<frozen runpy>:128: RuntimeWarning: 'tf2onnx.convert' found in sys.modules after import of package 'tf2onnx', but prior to execution of 'tf2onnx.convert'; this may result in unpredictable behaviour 2026-02-16 08:12:33,049 - WARNING - ***IMPORTANT*** Installed protobuf is not cpp accelerated. Conversion will be extremely slow. See https://github.com/onnx/tensorflow-onnx/issues/1557 2026-02-16 08:12:33,051 - WARNING - '--tag' not specified for saved_model. Using --tag serve 2026-02-16 08:12:33,190 - INFO - Signatures found in model: [serving_default]. 2026-02-16 08:12:33,191 - WARNING - '--signature_def' not specified, using first signature: serving_default 2026-02-16 08:12:33,191 - INFO - Output names: ['output_0'] 2026-02-16 08:12:33,191 - WARNING - Could not search for non-variable resources. Concrete function internal representation may have changed. WARNING: All log messages before absl::InitializeLog() is called are written to STDERR I0000 00:00:1771225953.195756 41231 devices.cc:76] Number of eligible GPUs (core count >= 8, compute capability >= 0.0): 0 (Note: TensorFlow was not compiled with CUDA or ROCm support) WARNING: All log messages before absl::InitializeLog() is called are written to STDERR I0000 00:00:1771225953.195882 41231 single_machine.cc:361] Starting new session I0000 00:00:1771225953.242144 41231 devices.cc:76] Number of eligible GPUs (core count >= 8, compute capability >= 0.0): 0 (Note: TensorFlow was not compiled with CUDA or ROCm support) I0000 00:00:1771225953.242191 41231 single_machine.cc:361] Starting new session 2026-02-16 08:12:33,260 - INFO - Using tensorflow=2.18.0, onnx=1.17.0, tf2onnx=1.16.0/5dd776 2026-02-16 08:12:33,261 - INFO - Using opset <onnx, 15> 2026-02-16 08:12:33,266 - INFO - Computed 0 values for constant folding 2026-02-16 08:12:33,273 - INFO - Optimizing ONNX model 2026-02-16 08:12:33,293 - INFO - After optimization: Cast -1 (1->0), Const +1 (9->10), Identity -2 (2->0), Reshape +1 (1->2), Transpose -5 (6->1) 2026-02-16 08:12:33,295 - INFO - 2026-02-16 08:12:33,296 - INFO - Successfully converted TensorFlow model mnist-tf-model to ONNX 2026-02-16 08:12:33,296 - INFO - Model inputs: ['inputs'] 2026-02-16 08:12:33,296 - INFO - Model outputs: ['output_0'] 2026-02-16 08:12:33,296 - INFO - ONNX model is saved at tf_model.onnx
import onnx onnx_model = onnx.load(onnx_model_name)

3.2. (OPTIONAL) Converting TensorFLow Keras model

To convert the TensorFLow Keras model to ONNX format, change the Markdown cells below to a Code cells and remove the triple backticks (```).

!tar xzf MNIST_DATA/{model_tar_name}
import logging from keras.models import load_model logging.getLogger().setLevel(logging.ERROR) model = load_model(tf_model_name) onnx_model, _ = tf2onnx.convert.from_keras(model) onnx.save(onnx_model, onnx_model_name)

3.3. Evaluating the ONNX Model

After exporting the model, you should verify its integrity and ensure that it functions as expected. We will use onnxruntime to load the model and perform inference on the test data. Additionally, we’ll use onnx's checker module to validate the exported ONNX model.

onnx.checker.check_model(onnx_model)
import onnxruntime as ort session = ort.InferenceSession(onnx_model_name) x_test = np.array(x_test, dtype=np.float32).reshape(-1, 28, 28, 1) input_data = {session.get_inputs()[0].name: x_test[:2]} session.run([], input_data)
[array([[2.9459990e-11, 2.6513208e-10, 5.7859739e-09, 1.4021280e-08, 9.0819036e-10, 2.0454895e-07, 3.2107092e-08, 9.9999964e-01, 8.8907576e-08, 3.6024445e-10], [1.1899501e-06, 2.6128285e-03, 9.7718209e-01, 1.6054348e-06, 4.1321553e-07, 1.1023610e-06, 2.0009710e-02, 3.6875292e-08, 1.9093615e-04, 1.7123283e-07]], dtype=float32)]

4. Persisting converted ONNX model

In this section, you will learn how to store your converted ONNX model in watsonx.ai Runtime repository using the IBM watsonx.ai SDK.

4.1. Publishing model in watsonx.ai Runtime repository

Define model name, type and software spec.

software_spec_id = client.software_specifications.get_id_by_name("onnxruntime_opset_19") onnx_model_zip = "tf_onnx.zip"
import zipfile with zipfile.ZipFile(onnx_model_zip, "w", zipfile.ZIP_DEFLATED) as zip_file: zip_file.write(onnx_model_name)
metadata = { client.repository.ModelMetaNames.NAME: "TensorFlow to ONNX converted model", client.repository.ModelMetaNames.TYPE: "onnxruntime_1.16", client.repository.ModelMetaNames.SOFTWARE_SPEC_ID: software_spec_id, } published_model = client.repository.store_model( model=onnx_model_zip, meta_props=metadata )

4.2. Getting 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": "TensorFlow to ONNX converted model", "space_id": "fb3d528a-bf16-460e-bcf6-06f05d8ba57c", "resource_key": "3a8eb861-6f55-4dff-851d-eac2c117dfe7", "id": "2c00ba66-2fac-4983-9a01-36bb5338db62", "created_at": "2026-02-16T07:13:09Z", "rov": { "member_roles": { "IBMid-696000GJGB": { "user_iam_id": "IBMid-696000GJGB", "roles": [ "OWNER" ] } } }, "owner": "IBMid-696000GJGB" }, "entity": { "software_spec": { "id": "368d2795-aaa7-59a0-834c-248c64a5a99e" }, "type": "onnxruntime_1.16" } }

5. Deploying and scoring ONNX model

In this section you'll learn how to create an online scoring service and predict on unseen data.

5.1. Creating online deployment for published model

metadata = { client.deployments.ConfigurationMetaNames.NAME: "Deployment of TensorFLow to ONNX converted model", client.deployments.ConfigurationMetaNames.ONLINE: {}, } created_deployment = client.deployments.create(published_model_id, meta_props=metadata)
###################################################################################### Synchronous deployment creation for id: '2c00ba66-2fac-4983-9a01-36bb5338db62' started ###################################################################################### initializing Note: online_url and serving_urls are deprecated and will be removed in a future release. Use inference instead. ...... ready ----------------------------------------------------------------------------------------------- Successfully finished deployment creation, deployment_id='10d18703-6032-41ed-87aa-53d71abd101f' -----------------------------------------------------------------------------------------------
deployment_id = client.deployments.get_id(created_deployment)

Now you can print an online scoring endpoint.

client.deployments.get_scoring_href(created_deployment)

5.2. Getting deployment details

client.deployments.get_details(deployment_id)

5.3. Scoring

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.reshape((28, 28)), cmap=plt.cm.gray_r, interpolation="nearest")
Image in a Jupyter notebook

Prepare scoring payload with records to score.

scoring_payload = {"input_data": [{"values": x_test[:2].tolist()}]}

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

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

Let's print the result of predictions.

print(json.dumps(predictions, indent=2))
{ "predictions": [ { "id": "output_0", "values": [ [ 2.9460045514184685e-11, 2.651320829549775e-10, 5.78599612666153e-09, 1.402130678229696e-08, 9.081955743006631e-10, 2.0454953642001783e-07, 3.2107216441090713e-08, 0.9999996423721313, 8.890791747262483e-08, 3.6024583316418557e-10 ], [ 1.1899520586666767e-06, 0.0026128317695111036, 0.9771818518638611, 1.6054360685302527e-06, 4.13216241668124e-07, 1.102363967220299e-06, 0.020009761676192284, 3.687535610197301e-08, 0.00019093610171694309, 1.7123278439612477e-07 ] ] } ] }
for i, prediction in enumerate(predictions["predictions"][0]["values"]): plt.bar(range(10), prediction) plt.title("Digit probability") plt.xlabel("Digit") plt.ylabel("Probability") plt.xticks(range(10)) plt.yscale("log") plt.show()
Image in a Jupyter notebookImage in a Jupyter notebook

As you can see, the predicted values are consistent with those calculated in the evaluation section.

6. Cleaning up

If you want to clean up after the notebook execution, i.e. remove any created assets like:

  • experiments

  • trainings

  • pipelines

  • model definitions

  • models

  • functions

  • deployments

please follow up this sample notebook.

7. Summary and next steps

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

Michał Koruszowic, Software Engineer

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