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

Use AutoAI and Lale to predict credit risk with ibm-watson-machine-learning

This notebook contains the steps and code to demonstrate support of AutoAI experiments in Watson Machine Learning 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.9.

Learning goals

The learning goals of this notebook are:

  • Work with Watson Machine Learning 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.

  • Perform 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. Clean up

  9. Summary and next steps

1. Set up the environment

Before you use the sample code in this notebook, contact with your Cloud Pack for Data administrator and ask for your account credentials.

Connection to WML

Authenticate the Watson Machine Learning service on IBM Cloud Pack 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'
wml_credentials = { "username": username, "apikey": api_key, "url": url, "instance_id": 'openshift', "version": '4.0' }

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

wml_credentials = { "username": ***, "password": ***, "url": ***, "instance_id": 'openshift', "version": '4.0' }

Install and import the ibm-watson-machine-learning package

Note: ibm-watson-machine-learning documentation can be found here.

!pip install ibm-watson-machine-learning | tail -n 1 !pip install -U autoai-libs | tail -n 1 !pip install -U lale | tail -n 1 !pip install -U scikit-learn==1.0.2 | tail -n 1
from ibm_watson_machine_learning import APIClient client = APIClient(wml_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 the 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 the space which you will be using.

client.set.default_space(space_id)
'SUCCESS'

2. Optimizer definition

Training data connection

Define connection information to an external database.

This example uses the German Credit Risk dataset. The dataset can be downloaded from here.

Connection configuration

Credentials for database should be passed as a python dictionary. For the vast number of supported datasets the credentials should follow the bellow pattern. Warning: Database name should be slected from the list of all the supported databases, in order to look it up use client.connections.list_datasource_types() Warning: Input table should be uploaded in database under the location /schema_name/table_name.

db_name = 'PUT YOUR DATABASE NAME HERE' schema_name = 'PUT YOUR SCHEMA NAME HERE'
table_name = 'CREDIT_RISK'
db_credentials = { "database": "***", "password": "***", "port": "***", "host": "***", "ssl": "***", "username": "***" }

Create connection

conn_meta_props= { client.connections.ConfigurationMetaNames.NAME: f"Connection to Database - {db_name} ", client.connections.ConfigurationMetaNames.DATASOURCE_TYPE: client.connections.get_datasource_type_uid_by_name(db_name), client.connections.ConfigurationMetaNames.DESCRIPTION: "Connection to external Database", client.connections.ConfigurationMetaNames.PROPERTIES: db_credentials } conn_details = client.connections.create(meta_props=conn_meta_props)
connection_id = client.connections.get_uid(conn_details)

Download training data

!wget -q 'https://raw.githubusercontent.com/IBM/watson-machine-learning-samples/master/cpd4.0/data/credit_risk/german_credit_data_biased_training.csv' -O \ 'credit_risk.csv'

Hint: To install pandas execute !pip install pandas

import pandas as pd from ibm_watson_machine_learning.helpers import DataConnection, DatabaseLocation credit_risk_conn = DataConnection( connection_asset_id=connection_id, location=DatabaseLocation( schema_name=schema_name, table_name=table_name ) ) credit_risk_conn._wml_client = client credit_risk_conn.write(pd.read_csv("credit_risk.csv")) training_data_reference=[credit_risk_conn]

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_watson_machine_learning.experiment import AutoAI experiment = AutoAI(wml_credentials, space_id=space_id) pipeline_optimizer = experiment.optimizer( name='Credit Risk Prediction - AutoAI', desc='Sample notebook', 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': 'Sample notebook', 'prediction_type': 'binary', 'prediction_column': 'Risk', 'scoring': 'roc_auc', 'test_size': 0.1, 'max_num_daub_ensembles': 2, 't_shirt_size': 'm', 'train_sample_rows_test_size': None, 'daub_include_only_estimators': ['ExtraTreesClassifierEstimator', 'GradientBoostingClassifierEstimator', 'LGBMClassifierEstimator', 'LogisticRegressionEstimator', 'RandomForestClassifierEstimator', 'XGBClassifierEstimator', 'DecisionTreeClassifierEstimator'], 'cognito_transform_names': None, 'data_join_graph': False, 'csv_separator': ',', 'excel_sheet': 0, 'encoding': 'utf-8', 'positive_label': 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 91e1541a-fee1-4bb9-8211-68eed6abfdc4 completed: 100%|████████| [10:01<00:00, 6.01s/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 pd.options.plotting.backend = "plotly" summary.holdout_roc_auc.plot()
Image in a Jupyter notebook

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_watson_machine_learning.helpers import pipeline_to_script pipeline_to_script(best_pipeline)

Visualize pipeline

best_pipeline.visualize()
Image in a Jupyter notebook

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)

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

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', 'No Risk', 'No Risk', 'Risk'], dtype=object)

5. Historical runs

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

To list historical runs use method list(). 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(filter='Credit Risk Prediction - AutoAI').get_params(run_id=run_id)
{'name': 'Credit Risk Prediction - AutoAI', 'desc': 'Sample notebook', 'prediction_type': 'binary', 'prediction_column': 'Risk', 'scoring': 'roc_auc', 'test_size': 0.1, 'max_num_daub_ensembles': 2.0, 't_shirt_size': 'c076e82c-b2a7-4d20-9c0f-1f0c2fdf5a24', 'daub_include_only_estimators': ['ExtraTreesClassifierEstimator', 'GradientBoostingClassifierEstimator', 'LGBMClassifierEstimator', 'LogisticRegressionEstimator', 'RandomForestClassifierEstimator', 'XGBClassifierEstimator', 'DecisionTreeClassifierEstimator'], 'cognito_transform_names': None, 'train_sample_rows_test_size': None, 'csv_separator': ',', 'excel_sheet': 0, 'encoding': 'utf-8'}

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

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()
Image in a Jupyter notebook

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()
Image in a Jupyter notebook

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 [02:12<00:00, 6.63s/trial, best loss: -0.8336535460343567]
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 75.1%
pipeline_model.visualize()
Image in a Jupyter notebook

7. Deploy and Score

In this section you will learn how to deploy and score pipeline model as webservice and batch using WML instance.

Webservice deployment creation

from ibm_watson_machine_learning.deployment import WebService service = WebService(wml_credentials, source_space_id=space_id) service.create( experiment_run_id=run_id, model='Pipeline_1', deployment_name="Credit Risk Deployment AutoAI")
Preparing an AutoAI Deployment... Published model uid: 014ffcfa-dcf1-4c26-add5-369243b140dd Deploying model 014ffcfa-dcf1-4c26-add5-369243b140dd using V4 client. ####################################################################################### Synchronous deployment creation for uid: '014ffcfa-dcf1-4c26-add5-369243b140dd' started ####################################################################################### initializing.. ready ------------------------------------------------------------------------------------------------ Successfully finished deployment creation, deployment_uid='e0f705fd-2fcb-437f-bc83-b17d5296b01d' ------------------------------------------------------------------------------------------------

Deployment object could be printed to show basic information:

print(service)
name: Credit Risk Deployment AutoAI, id: e0f705fd-2fcb-437f-bc83-b17d5296b01d, scoring_url: https://cpd-wmlautoai-may12.apps.ocp46wmlautoaai.cp.fyre.ibm.com/ml/v4/deployments/e0f705fd-2fcb-437f-bc83-b17d5296b01d/predictions, asset_id: 014ffcfa-dcf1-4c26-add5-369243b140dd

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

service.get_params()
{'entity': {'asset': {'id': '014ffcfa-dcf1-4c26-add5-369243b140dd'}, 'custom': {}, 'deployed_asset_type': 'model', 'hardware_spec': {'id': 'c076e82c-b2a7-4d20-9c0f-1f0c2fdf5a24', 'name': 'M', 'num_nodes': 1}, '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': 'fbd2dc3a-634a-46d5-9edd-8faa22d27b8d', 'status': {'online_url': {'url': 'https://cpd-wmlautoai-may12.apps.ocp46wmlautoaai.cp.fyre.ibm.com/ml/v4/deployments/e0f705fd-2fcb-437f-bc83-b17d5296b01d/predictions'}, 'state': 'ready'}}, 'metadata': {'created_at': '2021-05-20T08:23:53.001Z', 'id': 'e0f705fd-2fcb-437f-bc83-b17d5296b01d', 'modified_at': '2021-05-20T08:23:53.001Z', 'name': 'Credit Risk Deployment AutoAI', 'owner': '1000330999', 'space_id': 'fbd2dc3a-634a-46d5-9edd-8faa22d27b8d'}}

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.6743601502735059, 0.32563984972649407]], ['No Risk', [0.7892372484049005, 0.21076275159509952]], ['No Risk', [0.560817617610811, 0.43918238238918905]], ['No Risk', [0.8068670237279646, 0.1931329762720355]], ['Risk', [0.3344503240926395, 0.6655496759073605]], ['Risk', [0.10565678467912125, 0.8943432153208788]], ['No Risk', [0.7361802572321648, 0.2638197427678351]], ['No Risk', [0.8315661007516614, 0.1684338992483386]], ['No Risk', [0.8599408631598607, 0.1400591368401393]], ['Risk', [0.12661051706745757, 0.8733894829325424]]]}]}

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

  • Initialize the service using service = WebService(wml_credentials)

  • Get deployment_id using the service.list() method

  • Get webservice object using the 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 or processes from data asset and writes the output to a file.

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_watson_machine_learning.deployment import Batch service_batch = Batch(wml_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: 35a98cac-c3b7-448e-9a02-245400c93a82 Deploying model 35a98cac-c3b7-448e-9a02-245400c93a82 using V4 client. ####################################################################################### Synchronous deployment creation for uid: '35a98cac-c3b7-448e-9a02-245400c93a82' started ####################################################################################### ready. ------------------------------------------------------------------------------------------------ Successfully finished deployment creation, deployment_uid='756558ad-78f1-4d74-9e6d-555aa9cfff21' ------------------------------------------------------------------------------------------------

Score batch deployment with inline payload as pandas DataFrame.

scoring_params = service_batch.run_job( payload=batch_payload_df, background_mode=False)
########################################################################## Synchronous scoring for id: '478b6b5b-a80f-43f5-98f9-63e9da889720' started ########################################################################## queued.. running completed Scoring job '478b6b5b-a80f-43f5-98f9-63e9da889720' finished successfully.
scoring_params['entity']['scoring'].get('predictions')
[{'fields': ['prediction', 'probability'], 'values': [['No Risk', [0.7743273377418518, 0.225672647356987]], ['No Risk', [0.8309863209724426, 0.16901369392871857]], ['No Risk', [0.8892747759819031, 0.11072523891925812]], ['No Risk', [0.7456686496734619, 0.2543313801288605]], ['Risk', [0.22297507524490356, 0.7770249247550964]]]}]

Score batch deployment with payload as connected asset.

Simmilary to training use created connection in order to locate tabe in used database.

from ibm_watson_machine_learning.helpers.connections import AssetLocation, DeploymentOutputAssetLocation batch_payload_filename = "credit_risk_batch_payload.csv" batch_payload_df.to_csv(batch_payload_filename, index=False) asset_details = client.data_assets.create( name=batch_payload_filename, file_path=batch_payload_filename) asset_id = client.data_assets.get_id(asset_details) payload_reference = DataConnection(data_asset_id=asset_id) results_reference = DataConnection( location=DeploymentOutputAssetLocation(name="batch_output_credit_risk.csv"))
Creating data asset... SUCCESS

Run scoring job for batch deployment.

scoring_params = service_batch.run_job( payload=[payload_reference], output_data_reference=results_reference, background_mode=False)
########################################################################## Synchronous scoring for id: '80664cc6-3bf8-4fae-9309-f8622972a119' started ########################################################################## queued......... running. completed Scoring job '80664cc6-3bf8-4fae-9309-f8622972a119' finished successfully.

Deleting deployment

You can delete the existing deployment by calling the service_batch.delete() command. To list the existing:

  • batch services you can use service_batch.list(),

  • scoring jobs you can use service_batch.list_jobs().

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-watson-machine-learning 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 in Watson Machine Learning at IBM

Kiran Kate, Senior Software Engineer at IBM Research AI

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

Jan Sołtysik, Intern in Watson Machine Learning

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