Path: blob/master/cpd4.0/notebooks/python_sdk/experiments/autoai/Use AutoAI and Lale to predict credit risk.ipynb
6383 views
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:
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
.
Alternatively you can use username
and password
to authenticate WML services.
Install and import the ibm-watson-machine-learning
package
Note: ibm-watson-machine-learning
documentation can be found here.
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
tabCopy
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
You can use the list
method to print all existing spaces.
To be able to interact with all resources available in Watson Machine Learning, you need to set the space which you will be using.
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
.
Create connection
Download training data
Hint: To install pandas
execute !pip install pandas
Optimizer configuration
Provide the input information for AutoAI optimizer:
name
- experiment nameprediction_type
- type of the problemprediction_column
- target column namescoring
- optimization metric
Configuration parameters can be retrieved via get_params()
.
You can use the get_run_status()
method to monitor AutoAI jobs in background mode.
You can visualize the scoring metric calculated on a holdout data set.
Get selected pipeline model
Download and reconstruct a scikit-learn pipeline model object from the AutoAI training job.
Check confusion matrix for selected pipeline.
Check features importance for selected pipeline.
Convert the pipeline model to a Python script and download it
Visualize pipeline
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
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
Test pipeline model locally
To list historical runs use method list()
. You can filter runs by providing experiment name.
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.
Get executed optimizer's configuration parameters
Get historical optimizer instance and training details
List trained pipelines for selected optimizer
Get selected pipeline and test locally
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.
Pipeline decomposition and new definition
Start by removing the last step of the pipeline, i.e., the final estimator.
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 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.
Pipeline model tests and visualization
Webservice deployment creation
Deployment object could be printed to show basic information:
To show all available information about the deployment use the .get_params()
method:
Scoring of webservice
You can make scoring request by calling score()
on deployed pipeline.
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()
methodGet 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.
Create batch deployment for Pipeline_2
created in AutoAI experiment with the run_id
.
Score batch deployment with inline payload as pandas DataFrame.
Score batch deployment with payload as connected asset.
Simmilary to training use created connection in order to locate tabe in used database.
Run scoring job for batch deployment.
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()
.
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.