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 BatchedTreeEnsemble to solve large tabular problems.ipynb
6405 views
Kernel: watsonx-ai-samples-py-311

Use AutoAI and BatchedTreeEnsemble for incremental learning of AutoAI pipelines 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. Create connection

  3. Optimizer definition

  4. Experiment Run

  5. Pipelines comparison and testing

  6. Incremental learning

  7. Cleanup

  8. 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 plotly | tail -n 1 %pip install -U matplotlib | tail -n 1 %pip install -U autoai-libs | tail -n 1 %pip install -U ibm-watsonx-ai | tail -n 1 %pip install "scikit-learn==1.3.0" | tail -n 1
Successfully installed wget-3.2 Successfully installed narwhals-1.42.0 plotly-6.1.2 Successfully installed matplotlib-3.10.3 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 ibm-watsonx-ai-1.3.24 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)

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 from ibm_watsonx_ai import Credentials location = "us-south" credentials = Credentials( url=f"https://{location}.ml.cloud.ibm.com", api_key=getpass.getpass("Enter your watsonx.ai api key and hit enter: "), )
Enter your watsonx.ai api key and hit enter: ········
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=10)

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'

2. Connections to COS

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

The dataset can be downloaded from here.

Action: Upload training data to COS bucket and enter location information below.

space_details = client.spaces.get_details(space_id=space_id) cos_credentials = space_details["entity"]["storage"]["properties"] filename = "electricity.csv" datasource_name = "bluemixcloudobjectstorage" bucketname = cos_credentials["bucket_name"]

Download training data from git repository.

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

Create a 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": bucketname, "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
from ibm_watsonx_ai.helpers import DataConnection, S3Location connection_id = client.connections.get_id(conn_details) electricity_conn = DataConnection( connection_asset_id=connection_id, location=S3Location(bucket=bucketname, path=filename), ) electricity_conn.set_client(client) training_data_reference = [electricity_conn] electricity_conn.write(data=filename, remote_name=filename)

3. Optimizer definition

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 from ibm_watsonx_ai.utils.autoai.enums import ClassificationAlgorithms as CA from ibm_watsonx_ai.utils.autoai.enums import BatchedClassificationAlgorithms as BCA experiment = AutoAI(credentials, space_id=space_id) pipeline_optimizer = experiment.optimizer( name="Electricity Prediction - AutoAI", prediction_type=AutoAI.PredictionType.CLASSIFICATION, prediction_column="class", scoring=AutoAI.Metrics.ROC_AUC_SCORE, sample_size_limit=635897, sampling_type="first_n_records", retrain_on_holdout=True, include_only_estimators=[CA.EX_TREES, CA.LGBM, CA.RF, CA.SnapRF, CA.SnapBM, CA.XGB], include_batched_ensemble_estimators=[ BCA.EX_TREES, BCA.LGBM, BCA.RF, BCA.SnapBM, BCA.SnapRF, BCA.XGB, ], use_flight=True, )

Configuration parameters can be retrieved via get_params().

pipeline_optimizer.get_params()
{'name': 'Electricity Prediction - AutoAI', 'desc': '', 'prediction_type': 'classification', 'prediction_column': 'class', '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': [<ClassificationAlgorithms.EX_TREES: 'ExtraTreesClassifier'>, <ClassificationAlgorithms.LGBM: 'LGBMClassifier'>, <ClassificationAlgorithms.RF: 'RandomForestClassifier'>, <ClassificationAlgorithms.SnapRF: 'SnapRandomForestClassifier'>, <ClassificationAlgorithms.SnapBM: 'SnapBoostingMachineClassifier'>, <ClassificationAlgorithms.XGB: 'XGBClassifier'>], 'include_batched_ensemble_estimators': [<BatchedClassificationAlgorithms.EX_TREES: 'BatchedTreeEnsembleClassifier(ExtraTreesClassifier)'>, <BatchedClassificationAlgorithms.LGBM: 'BatchedTreeEnsembleClassifier(LGBMClassifier)'>, <BatchedClassificationAlgorithms.RF: 'BatchedTreeEnsembleClassifier(RandomForestClassifier)'>, <BatchedClassificationAlgorithms.SnapBM: 'BatchedTreeEnsembleClassifier(SnapBoostingMachineClassifier)'>, <BatchedClassificationAlgorithms.SnapRF: 'BatchedTreeEnsembleClassifier(SnapRandomForestClassifier)'>, <BatchedClassificationAlgorithms.XGB: 'BatchedTreeEnsembleClassifier(XGBClassifier)'>], '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': 'first_n_records', 'sample_size_limit': 635897, '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}

4. 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 b7521332-f987-45db-9fa1-feb27c33d259 completed: 100%|████████| [11:25<00:00, 6.85s/it]
run_details

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

pipeline_optimizer.get_run_status()
'completed'

5. 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_roc_auc.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()

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 ColumnSelector 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 xgboost import XGBClassifier column_selector_0 = ColumnSelector(columns_indices_list=[0, 1, 2, 3, 4]) numpy_column_selector_0 = NumpyColumnSelector(columns=[1]) compress_strings = CompressStrings( compress_type="hash", dtypes_list=["float_int_num"], missing_values_reference_list=["", "-", "?", float("nan")], misslist_list=[[]], ) numpy_replace_missing_values_0 = NumpyReplaceMissingValues( filling_values=100001, missing_values=[] ) numpy_replace_unknown_values = NumpyReplaceUnknownValues( filling_values=100001, filling_values_list=[100001], missing_values_reference_list=["", "-", "?", float("nan")], ) cat_imputer = CatImputer( missing_values=100001, 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( column_selector_0, numpy_column_selector_0, compress_strings, numpy_replace_missing_values_0, numpy_replace_unknown_values, boolean2float(), cat_imputer, cat_encoder, float32_transform(), ) column_selector_1 = ColumnSelector(columns_indices_list=[0, 1, 2, 3, 4]) numpy_column_selector_1 = NumpyColumnSelector(columns=[0, 2, 3, 4]) float_str2_float = FloatStr2Float( dtypes_list=["float_num", "float_num", "float_num", "float_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( column_selector_1, 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=[1, 0, 2, 3, 4] ) xgb_classifier = XGBClassifier( gamma=0, learning_rate=0.8430908314686132, max_depth=5, min_child_weight=8, missing=float("nan"), n_estimators=474, n_jobs=4, random_state=33, reg_alpha=1, reg_lambda=0.6135895622487102, subsample=0.9994794487638453, tree_method="hist", verbosity=0, silent=True, ) pipeline = make_pipeline(union, numpy_permute_array, xgb_classifier)

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(["class"], axis=1).values train_y = train_df["class"].values

Test pipeline model locally

predicted_y = best_pipeline.predict(train_X) predicted_y[:5]
array([0., 0., 0., 0., 1.])

6. Incremental learning of BatchedTreeEnsemble pipelines

In this section you learn to train AutoAI models incrementally.

Data loader

Create DataLoader iterator to retrieve training dataset in batches (Pandas DataFrame). DataLoader is Torch compatible (torch.utils.data).

Note: If reading data results in an error, provide data as batches (Pandas DataFrame). It may be necessary to use methods for initial data pre-processing like: e.g. DataFrame.dropna(), DataFrame.drop_duplicates(), DataFrame.sample().

from ibm_watsonx_ai.data_loaders import experiment as data_loaders from ibm_watsonx_ai.data_loaders.datasets import experiment as datasets dataset = datasets.ExperimentIterableDataset( connection=training_data_reference[0], with_subsampling=False, experiment_metadata={"prediction_type": "classification"}, number_of_batch_rows=9062, _wml_client=client, ) data_loader = data_loaders.ExperimentDataLoader(dataset=dataset)

Continue model training

from sklearn.metrics import get_scorer scorer = get_scorer(AutoAI.Metrics.ROC_AUC_SCORE)
run_id = run_details["metadata"]["id"]

Fit pipeline model in batches (partial_fit)

In this cell, the pipeline is incrementally fitted using data batches.

Note: You can also use custom code for data reading and model training. The pipeline supports incremental learning via partial_fit calls.

If you need, you can evaluate the pipeline using custom holdout data. Provide the X_test, y_test and call scorer on them.

best_pipeline.steps[-1][-1].impl.max_sub_ensembles = 5
i = 0 iters = [] partial_fit_scores = [] for batch_df in data_loader: X_train = batch_df.drop(["class"], axis=1).values y_train = batch_df["class"].values pipeline_model = best_pipeline.partial_fit( X_train, y_train, classes=pd.unique(train_y).tolist(), freeze_trained_prefix=True, ) pipeline_score = scorer(pipeline_model, X_train, y_train) partial_fit_scores.append(pipeline_score) print("Pipeline - batch: {0} | score: {1}".format(iter, pipeline_score))
Pipeline - batch: <built-in function iter> | score: 0.9999978074066899 Pipeline - batch: <built-in function iter> | score: 0.9998779318325085 Pipeline - batch: <built-in function iter> | score: 0.5149091825280916 Pipeline - batch: <built-in function iter> | score: 0.5024080336257478 Pipeline - batch: <built-in function iter> | score: 0.5027342769485473 Pipeline - batch: <built-in function iter> | score: 0.5
import plotly.graph_objs as go y_values = partial_fit_scores x_labels = list(range(len(y_values))) trace = go.Scatter( x=x_labels, y=y_values, mode="lines+markers", marker=dict(color="blue", size=8), line=dict(color="blue", width=2), name="Data Points", ) layout = go.Layout( title="AutoAI incremental learning curve", yaxis=dict(title="BatchedEnsemble") ) fig = go.Figure(data=[trace], layout=layout) fig.show()

Test the fitted pipeline (predict).

pipeline_model.predict(train_X)
array([1., 1., 1., ..., 1., 1., 1.])

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

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

Szymon Kucharczyk, Staff Software Engineer at watsonx.ai

Mateusz Szewczyk, Software Engineer at watsonx.ai

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