Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ibm
GitHub Repository: ibm/watson-machine-learning-samples
Path: blob/master/cloud/notebooks/python_sdk/experiments/autoai/Use AutoAI and Lale to predict credit risk.ipynb
6405 views
Kernel: Python 3.11

Use AutoAI and Lale to predict credit risk with ibm-watsonx-ai

This notebook contains the steps and code to demonstrate support of AutoAI experiments in watsonx.ai Runtime service. It introduces commands for data retrieval, training experiments, persisting pipelines, testing pipelines, refining pipelines, and scoring.

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

Learning goals

The learning goals of this notebook are:

  • Work with watsonx.ai Runtime experiments to train AutoAI models.

  • Compare trained models quality and select the best one for further refinement.

  • Refine the best model and test new variations.

  • Online deployment and score the trained model.

Contents

This notebook contains the following parts:

  1. Setup

  2. Optimizer definition

  3. Experiment Run

  4. Pipelines comparison and testing

  5. Historical runs

  6. Pipeline refinement and testing

  7. Deploy and Score

  8. Cleanup

  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:

  • Create a watsonx.ai Runtime Service instance (a free plan is offered and information about how to create the instance can be found here).

  • Create a Cloud Object Storage (COS) instance (a lite plan is offered and information about how to order storage can be found here).
    Note: When using Watson Studio, you already have a COS instance associated with the project you are running the notebook in.

Install and import the ibm-watsonx-ai and dependecies

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

%pip install -U wget | tail -n 1 %pip install -U nbformat | tail -n 1 %pip install -U autoai-libs | tail -n 1 %pip install -U hyperopt | tail -n 1 %pip install lale | tail -n 1 %pip install "scikit-learn==1.3.0" | tail -n 1 %pip install -U ibm-watsonx-ai | tail -n 1
Successfully installed wget-3.2 Successfully installed nbformat-5.10.4 Requirement already satisfied: sortedcontainers~=2.2 in /opt/conda/envs/Python-RT24.1/lib/python3.11/site-packages (from portion->jsonsubschema>=0.0.6->lale~=0.8.0->autoai-libs) (2.4.0) Successfully installed hyperopt-0.2.7 Requirement already satisfied: sortedcontainers~=2.2 in /opt/conda/envs/Python-RT24.1/lib/python3.11/site-packages (from portion->jsonsubschema>=0.0.6->lale) (2.4.0) Requirement already satisfied: threadpoolctl>=2.0.0 in /opt/conda/envs/Python-RT24.1/lib/python3.11/site-packages (from scikit-learn==1.3.0) (2.2.0) Successfully installed ibm-watsonx-ai-1.3.30

Connection to watsonx.ai Runtime

Authenticate the watsonx.ai Runtime service on IBM Cloud. You need to provide Cloud API key and location.

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 use IBM Cloud CLI to retrieve the instance location.

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

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

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

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

Working with spaces

You need to create a space that will be used for your work. If you do not have a space, 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 the list method to print all existing spaces.

client.spaces.list(limit=100)

To be able to interact with all resources available in watsonx.ai Runtime, you need to set the space which you will be using.

client.set.default_space(space_id)
'SUCCESS'

Connections to COS

In next cell we read the COS credentials from the space.

space_details = client.spaces.get_details(space_id=space_id) cos_credentials = space_details["entity"]["storage"]["properties"]

2. Optimizer definition

Training data connection

Define connection information to COS bucket and training data CSV file. This example uses the German Credit Risk dataset.

The code in next cell uploads training data to the bucket.

filename = "credit_risk_training_light.csv" datasource_name = "bluemixcloudobjectstorage" bucket_name = cos_credentials["bucket_name"]

Download training data from git repository.

import os, wget url = "https://raw.githubusercontent.com/IBM/watsonx-ai-samples/master/cloud/data/credit_risk/credit_risk_training_light.csv" if not os.path.isfile(filename): wget.download(url)

Create connection

conn_meta_props = { client.connections.ConfigurationMetaNames.NAME: f"Connection to Database - {datasource_name} ", client.connections.ConfigurationMetaNames.DATASOURCE_TYPE: client.connections.get_datasource_type_id_by_name( datasource_name ), client.connections.ConfigurationMetaNames.DESCRIPTION: "Connection to external Database", client.connections.ConfigurationMetaNames.PROPERTIES: { "bucket": bucket_name, "access_key": cos_credentials["credentials"]["editor"]["access_key_id"], "secret_key": cos_credentials["credentials"]["editor"]["secret_access_key"], "iam_url": "https://iam.cloud.ibm.com/identity/token", "url": cos_credentials["endpoint_url"], }, } conn_details = client.connections.create(meta_props=conn_meta_props)
Creating connections... SUCCESS

Note: The above connection can be initialized alternatively with api_key and resource_instance_id. The above cell can be replaced with:

conn_meta_props= { client.connections.ConfigurationMetaNames.NAME: f"Connection to Database - {db_name} ", client.connections.ConfigurationMetaNames.DATASOURCE_TYPE: client.connections.get_datasource_type_id_by_name(db_name), client.connections.ConfigurationMetaNames.DESCRIPTION: "Connection to external Database", client.connections.ConfigurationMetaNames.PROPERTIES: { "bucket": bucket_name, "api_key": cos_credentials["apikey"], "resource_instance_id": cos_credentials["resource_instance_id"], "iam_url": "https://iam.cloud.ibm.com/identity/token", "url": "https://s3.us.cloud-object-storage.appdomain.cloud" } } conn_details = client.connections.create(meta_props=conn_meta_props)
connection_id = client.connections.get_id(conn_details)

Define connection information to training data.

from ibm_watsonx_ai.helpers import DataConnection, S3Location credit_risk_conn = DataConnection( connection_asset_id=connection_id, location=S3Location(bucket=bucket_name, path=filename), ) training_data_reference = [credit_risk_conn]

Check the connection information. Upload the data and validate.

credit_risk_conn.set_client(client) credit_risk_conn.write(data=filename, remote_name=filename) credit_risk_conn.read()

Optimizer configuration

Provide the input information for AutoAI optimizer:

  • name - experiment name

  • prediction_type - type of the problem

  • prediction_column - target column name

  • scoring - optimization metric

from ibm_watsonx_ai.experiment import AutoAI experiment = AutoAI(credentials, space_id=space_id) pipeline_optimizer = experiment.optimizer( name="Credit Risk Prediction - AutoAI", prediction_type=AutoAI.PredictionType.BINARY, prediction_column="Risk", scoring=AutoAI.Metrics.ROC_AUC_SCORE, )

Configuration parameters can be retrieved via get_params().

pipeline_optimizer.get_params()
{'name': 'Credit Risk Prediction - AutoAI', 'desc': '', 'prediction_type': 'binary', 'prediction_column': 'Risk', 'prediction_columns': None, 'timestamp_column_name': None, 'scoring': 'roc_auc', 'holdout_size': None, 'max_num_daub_ensembles': None, 't_shirt_size': 'l', 'train_sample_rows_test_size': None, 'include_only_estimators': None, 'include_batched_ensemble_estimators': None, 'backtest_num': None, 'lookback_window': None, 'forecast_window': None, 'backtest_gap_length': None, 'cognito_transform_names': None, 'csv_separator': ',', 'excel_sheet': None, 'encoding': 'utf-8', 'positive_label': None, 'drop_duplicates': True, 'outliers_columns': None, 'text_processing': None, 'word2vec_feature_number': None, 'daub_give_priority_to_runtime': None, 'text_columns_names': None, 'sampling_type': None, 'sample_size_limit': None, 'sample_rows_limit': None, 'sample_percentage_limit': None, 'number_of_batch_rows': None, 'n_parallel_data_connections': None, 'test_data_csv_separator': ',', 'test_data_excel_sheet': None, 'test_data_encoding': 'utf-8', 'categorical_imputation_strategy': None, 'numerical_imputation_strategy': None, 'numerical_imputation_value': None, 'imputation_threshold': None, 'retrain_on_holdout': True, 'feature_columns': None, 'pipeline_types': None, 'supporting_features_at_forecast': None, 'numerical_columns': None, 'categorical_columns': None, 'confidence_level': None, 'incremental_learning': None, 'early_stop_enabled': None, 'early_stop_window_size': None, 'time_ordered_data': None, 'feature_selector_mode': None, 'run_id': None}

3. Experiment run

Call the fit() method to trigger the AutoAI experiment. You can either use interactive mode (synchronous job) or background mode (asychronous job) by specifying background_model=True.

run_details = pipeline_optimizer.fit( training_data_reference=training_data_reference, background_mode=False )
Training job a9a97f00-6cfd-412d-a921-b1d6e643286b completed: 100%|████████| [03:59<00:00, 2.39s/it]

You can use the get_run_status() method to monitor AutoAI jobs in background mode.

pipeline_optimizer.get_run_status()
'completed'

4. Pipelines comparison and testing

You can list trained pipelines and evaluation metrics information in the form of a Pandas DataFrame by calling the summary() method. You can use the DataFrame to compare all discovered pipelines and select the one you like for further testing.

summary = pipeline_optimizer.summary() summary

You can visualize the scoring metric calculated on a holdout data set.

import pandas as pd import plotly.io as pio pio.renderers.default = "notebook" pd.options.plotting.backend = "plotly" summary.holdout_accuracy.plot()

Get selected pipeline model

Download and reconstruct a scikit-learn pipeline model object from the AutoAI training job.

best_pipeline = pipeline_optimizer.get_pipeline()

Check confusion matrix for selected pipeline.

pipeline_optimizer.get_pipeline_details()["confusion_matrix"]

Check features importance for selected pipeline.

pipeline_optimizer.get_pipeline_details()["features_importance"]

Convert the pipeline model to a Python script and download it

from ibm_watsonx_ai.helpers import pipeline_to_script pipeline_to_script(best_pipeline)

Visualize pipeline

best_pipeline.visualize()

Each node in the visualization is a machine-learning operator (transformer or estimator). Each edge indicates data flow (transformed output from one operator becomes input to the next). The input to the root nodes is the initial dataset and the output from the sink node is the final prediction. When you hover the mouse pointer over a node, a tooltip shows you the configuration arguments of the corresponding operator (tuned hyperparameters). When you click on the hyperlink of a node, it brings you to a documentation page for the operator.

Pipeline source code

best_pipeline.pretty_print(ipython_display=True, astype="sklearn")
from autoai_libs.transformers.exportable import NumpyColumnSelector from autoai_libs.transformers.exportable import CompressStrings from autoai_libs.transformers.exportable import NumpyReplaceMissingValues from autoai_libs.transformers.exportable import NumpyReplaceUnknownValues from autoai_libs.transformers.exportable import boolean2float from autoai_libs.transformers.exportable import CatImputer from autoai_libs.transformers.exportable import CatEncoder import numpy as np from autoai_libs.transformers.exportable import float32_transform from sklearn.pipeline import make_pipeline from autoai_libs.transformers.exportable import FloatStr2Float from autoai_libs.transformers.exportable import NumImputer from autoai_libs.transformers.exportable import OptStandardScaler from sklearn.pipeline import make_union from autoai_libs.transformers.exportable import NumpyPermuteArray from snapml import SnapLogisticRegression numpy_column_selector_0 = NumpyColumnSelector( columns=[0, 2, 3, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19] ) compress_strings = CompressStrings( compress_type="hash", dtypes_list=[ "char_str", "char_str", "char_str", "char_str", "char_str", "float_int_num", "char_str", "char_str", "float_int_num", "char_str", "char_str", "char_str", "float_int_num", "char_str", "float_int_num", "char_str", "char_str", ], missing_values_reference_list=["", "-", "?", float("nan")], misslist_list=[ [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], ], ) numpy_replace_missing_values_0 = NumpyReplaceMissingValues( filling_values=float("nan"), missing_values=[] ) numpy_replace_unknown_values = NumpyReplaceUnknownValues( filling_values=float("nan"), filling_values_list=[ float("nan"), float("nan"), float("nan"), float("nan"), float("nan"), 100001, float("nan"), float("nan"), 100001, float("nan"), float("nan"), float("nan"), 100001, float("nan"), 100001, float("nan"), float("nan"), ], missing_values_reference_list=["", "-", "?", float("nan")], ) cat_imputer = CatImputer( missing_values=float("nan"), sklearn_version_family="1", strategy="most_frequent", ) cat_encoder = CatEncoder( dtype=np.float64, handle_unknown="error", sklearn_version_family="1", encoding="ordinal", categories="auto", ) pipeline_0 = make_pipeline( numpy_column_selector_0, compress_strings, numpy_replace_missing_values_0, numpy_replace_unknown_values, boolean2float(), cat_imputer, cat_encoder, float32_transform(), ) numpy_column_selector_1 = NumpyColumnSelector(columns=[1, 4, 12]) float_str2_float = FloatStr2Float( dtypes_list=["float_int_num", "float_int_num", "float_int_num"], missing_values_reference_list=[], ) numpy_replace_missing_values_1 = NumpyReplaceMissingValues( filling_values=float("nan"), missing_values=[] ) num_imputer = NumImputer(missing_values=float("nan"), strategy="median") opt_standard_scaler = OptStandardScaler(use_scaler_flag=False) pipeline_1 = make_pipeline( numpy_column_selector_1, float_str2_float, numpy_replace_missing_values_1, num_imputer, opt_standard_scaler, float32_transform(), ) union = make_union(pipeline_0, pipeline_1) numpy_permute_array = NumpyPermuteArray( axis=0, permutation_indices=[ 0, 2, 3, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 1, 4, 12, ], ) snap_logistic_regression = SnapLogisticRegression( class_weight="balanced", dual=False, random_state=33, fit_intercept=True, normalize=True, ) pipeline = make_pipeline(union, numpy_permute_array, snap_logistic_regression)

In the pretty-printed code, >> is the pipe combinator (dataflow edge) and & is the and combinator (combining multiple subpipelines). They correspond to the make_pipeline and make_union functions from scikit-learn, respectively. If you prefer the functions, you can instead pretty-print your pipeline with best_pipeline.pretty_print(ipython_display=True, combinators=False).

Reading training data from COS

train_df = pipeline_optimizer.get_data_connections()[0].read() train_X = train_df.drop(["Risk"], axis=1).values train_y = train_df.Risk.values

Test pipeline model locally

predicted_y = best_pipeline.predict(train_X) predicted_y[:5]
array(['No Risk', 'No Risk', 'Risk', 'No Risk', 'Risk'], dtype='<U32')

5. Historical runs

In this section you learn to work with historical AutoPipelines fit jobs (runs).

To list historical runs use method list().

Note: You can filter runs by providing experiment name.

experiment.runs(filter="Credit Risk Prediction - AutoAI").list()

To work with historical pipelines found during a particular optimizer run, you need to first provide the run_id to select the fitted optimizer.

Note: you can assign selected run_id to the run_id variable.

run_id = run_details["metadata"]["id"]

Get executed optimizer's configuration parameters

experiment.runs.get_params(run_id=run_id)
{'name': 'Credit Risk Prediction - AutoAI', 'desc': '', 'prediction_type': 'binary', 'prediction_column': 'Risk', 'prediction_columns': None, 'timestamp_column_name': None, 'holdout_size': None, 'max_num_daub_ensembles': None, 't_shirt_size': 'a6c4923b-b8e4-444c-9f43-8a7ec3020110', 'include_only_estimators': None, 'cognito_transform_names': None, 'train_sample_rows_test_size': None, 'text_processing': None, 'train_sample_columns_index_list': None, 'daub_give_priority_to_runtime': None, 'positive label': None, 'incremental_learning': None, 'early_stop_enabled': None, 'early_stop_window_size': None, 'outliers_columns': None, 'numerical_columns': None, 'categorical_columns': None, 'time_ordered_data': None, 'feature_selector_mode': None, 'test_data_csv_separator': ',', 'test_data_excel_sheet': None, 'test_data_encoding': 'utf-8', 'drop_duplicates': True, 'csv_separator': ',', 'excel_sheet': None, 'encoding': 'utf-8', 'retrain_on_holdout': True, 'scoring': 'roc_auc'}

Get historical optimizer instance and training details

historical_opt = experiment.runs.get_optimizer(run_id)
run_details = historical_opt.get_run_details()

List trained pipelines for selected optimizer

historical_opt.summary()

Get selected pipeline and test locally

hist_pipeline = historical_opt.get_pipeline(pipeline_name="Pipeline_3")
predicted_y = hist_pipeline.predict(train_X) predicted_y[:5]
array(['No Risk', 'No Risk', 'No Risk', 'No Risk', 'Risk'], dtype='<U32')

6. Pipeline refinement with Lale and testing

In this section you learn how to refine and retrain the best pipeline returned by AutoAI. There are many ways to refine a pipeline. For illustration, simply replace the final estimator in the pipeline by an interpretable model. The call to wrap_imported_operators() augments scikit-learn operators with schemas for hyperparameter tuning.

from sklearn.linear_model import LogisticRegression as LR from sklearn.tree import DecisionTreeClassifier as Tree from sklearn.neighbors import KNeighborsClassifier as KNN from lale.lib.lale import Hyperopt from lale import wrap_imported_operators wrap_imported_operators()

Pipeline decomposition and new definition

Start by removing the last step of the pipeline, i.e., the final estimator.

prefix = hist_pipeline.remove_last().freeze_trainable() prefix.visualize()

Next, add a new final step, which consists of a choice of three estimators. In this code, | is the or combinator (algorithmic choice). It defines a search space for another optimizer run.

new_pipeline = prefix >> (LR | Tree | KNN) new_pipeline.visualize()

New optimizer Hyperopt configuration and training

To automatically select the algorithm and tune its hyperparameters, we create an instance of the Hyperopt optimizer and fit it to the data.

from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split( train_X, train_y, test_size=0.15, random_state=33 )
hyperopt = Hyperopt(estimator=new_pipeline, cv=3, max_evals=20, scoring="roc_auc") hyperopt_pipelines = hyperopt.fit(X_train, y_train)
100%|██████████| 20/20 [00:04<00:00, 4.65trial/s, best loss: -0.8152585638998683]
pipeline_model = hyperopt_pipelines.get_pipeline()

Pipeline model tests and visualization

from sklearn.metrics import roc_auc_score predicted_y = pipeline_model.predict(X_test) score = roc_auc_score(predicted_y == "Risk", y_test == "Risk") print(f"roc_auc_score {score:.1%}")
roc_auc_score 79.3%
pipeline_model.visualize()

7. Deploy and Score

In this section you will learn how to deploy and score pipeline model as webservice using watsonx.ai Runtime instance.

pipeline_name = "Pipeline_1"

Online deployment creation

from ibm_watsonx_ai.deployment import WebService service = WebService(credentials, source_space_id=space_id) service.create( experiment_run_id=run_id, model=pipeline_name, deployment_name="Credit Risk Deployment AutoAI", )
Preparing an AutoAI Deployment... Published model uid: bf74f87e-a450-47d5-9f0d-4d7e4c2511ec Deploying model bf74f87e-a450-47d5-9f0d-4d7e4c2511ec using V4 client. ###################################################################################### Synchronous deployment creation for id: 'bf74f87e-a450-47d5-9f0d-4d7e4c2511ec' 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='1beb1120-da6c-4bdc-ad74-277fa6f021d8' -----------------------------------------------------------------------------------------------

Deployment object could be printed to show basic information:

print(service)
name: Credit Risk Deployment AutoAI, id: 1beb1120-da6c-4bdc-ad74-277fa6f021d8, scoring_url: https://us-south.ml.cloud.ibm.com/ml/v4/deployments/1beb1120-da6c-4bdc-ad74-277fa6f021d8/predictions, asset_id: bf74f87e-a450-47d5-9f0d-4d7e4c2511ec

To show all available information about the deployment use the .get_params() method:

service.get_params()
Note: online_url and serving_urls are deprecated and will be removed in a future release. Use inference instead.
{'entity': {'asset': {'id': 'bf74f87e-a450-47d5-9f0d-4d7e4c2511ec'}, 'chat_enabled': False, 'custom': {}, 'deployed_asset_type': 'model', 'hybrid_pipeline_hardware_specs': [{'hardware_spec': {'name': 'S', 'num_nodes': 1}, 'node_runtime_id': 'auto_ai.kb'}], 'name': 'Credit Risk Deployment AutoAI', 'online': {}, 'space_id': 'fb3d528a-bf16-460e-bcf6-06f05d8ba57c', 'status': {'inference': [{'url': 'https://us-south.ml.cloud.ibm.com/ml/v4/deployments/1beb1120-da6c-4bdc-ad74-277fa6f021d8/predictions'}], 'online_url': {'url': 'https://us-south.ml.cloud.ibm.com/ml/v4/deployments/1beb1120-da6c-4bdc-ad74-277fa6f021d8/predictions'}, 'serving_urls': ['https://us-south.ml.cloud.ibm.com/ml/v4/deployments/1beb1120-da6c-4bdc-ad74-277fa6f021d8/predictions'], 'state': 'ready'}}, 'metadata': {'created_at': '2025-07-14T13:30:21.100Z', 'id': '1beb1120-da6c-4bdc-ad74-277fa6f021d8', 'modified_at': '2025-07-14T13:30:21.100Z', 'name': 'Credit Risk Deployment AutoAI', 'owner': 'IBMid-696000GJGB', 'space_id': 'fb3d528a-bf16-460e-bcf6-06f05d8ba57c'}, 'system': {'warnings': [{'id': 'Deprecated', 'message': 'online_url and serving_urls are deprecated and will be removed in a future release. Use inference instead.'}]}}

Scoring of webservice

You can make scoring request by calling score() on deployed pipeline.

predictions = service.score(payload=train_df.drop(["Risk"], axis=1).iloc[:10]) predictions
{'predictions': [{'fields': ['prediction', 'probability'], 'values': [['No Risk', [0.815472082175866, 0.18452791782413402]], ['No Risk', [0.7501849542379176, 0.24981504576208238]], ['Risk', [0.44323551396938976, 0.5567644860306102]], ['No Risk', [0.7860837153311935, 0.2139162846688065]], ['Risk', [0.10388810002019544, 0.8961118999798046]], ['Risk', [0.05423329461659787, 0.9457667053834021]], ['Risk', [0.39761734701550944, 0.6023826529844906]], ['No Risk', [0.7195913804536169, 0.2804086195463831]], ['No Risk', [0.8252891188726869, 0.17471088112731317]], ['Risk', [0.05226738963105093, 0.9477326103689491]]]}]}

If you want to work with the web service in an external Python application you can retrieve the service object by:

  • Initialize the service by service = WebService(wml_credentials)

  • Get deployment_id by service.list() method

  • Get webservice object by service.get('deployment_id') method

After that you can call service.score() method.

Deleting deployment

You can delete the existing deployment by calling the service.delete() command. To list the existing web services you can use service.list().

Batch deployment creation

A batch deployment processes input data from a inline data and return predictions in scoring details.

batch_payload_df = train_df.drop(["Risk"], axis=1)[:5] batch_payload_df

Create batch deployment for Pipeline_2 created in AutoAI experiment with the run_id.

from ibm_watsonx_ai.deployment import Batch service_batch = Batch(credentials, source_space_id=space_id) service_batch.create( experiment_run_id=run_id, model="Pipeline_2", deployment_name="Credit Risk Batch Deployment AutoAI", )
Preparing an AutoAI Deployment... Published model uid: 10e0fc12-bdc5-420b-8ef9-3e3a3646bd86 Deploying model 10e0fc12-bdc5-420b-8ef9-3e3a3646bd86 using V4 client. ###################################################################################### Synchronous deployment creation for id: '10e0fc12-bdc5-420b-8ef9-3e3a3646bd86' started ###################################################################################### ready

Score batch deployment with inline payload as pandas DataFrame.

scoring_params = service_batch.run_job(payload=batch_payload_df, background_mode=False)
scoring_params["entity"]["scoring"].get("predictions")

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 ibm-watsonx-ai to run AutoAI experiments.

Check out our Online Documentation for more samples, tutorials, documentation, how-tos, and blog posts.

Authors

Lukasz Cmielowski, PhD, is an Automation Architect and Data Scientist at IBM with a track record of developing enterprise-level applications that substantially increases clients' ability to turn data into actionable knowledge.

Amadeusz Masny, Python Software Developer at watsonx.ai

Kiran Kate, Senior Software Engineer at IBM Research AI

Martin Hirzel, Research Staff Member and Manager at IBM Research AI

Mateusz Szewczyk, Software Engineer at watsonx.ai

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