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.
The learning goals of this notebook are:
This notebook contains the following parts:
Before you use the sample code in this notebook, you must perform the following setup tasks:
Authenticate the Watson Machine Learning 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 Watson Machine Learning docs. You can check your instance location in your Watson Machine Learning (WML) 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 WML_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.
api_key = 'PASTE YOUR API KEY HERE'
location = 'us-south'
wml_credentials = {
"apikey": api_key,
"url": 'https://' + location + '.ml.cloud.ibm.com'
}
!pip install -U ibm-watson-machine-learning | tail -n 1
!pip install -U autoai-libs | tail -n 1
!pip install -U scikit-learn==1.1.1 | tail -n 1
!pip install wget | tail -n 1
!pip install matplotlib | tail -n 1
from ibm_watson_machine_learning import APIClient
client = APIClient(wml_credentials)
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.
space_id
and paste it belowTip: 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 = ''
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)
In next cell we read the COS credentials from the space.
cos_credentials = client.spaces.get_details(space_id=space_id)['entity']['storage']['properties']
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'
bucketname = cos_credentials['bucket_name']
Download training data from git repository.
import os, wget
url = 'https://raw.githubusercontent.com/IBM/watson-machine-learning-samples/master/cloud/data/credit_risk/credit_risk_training_light.csv'
if not os.path.isfile(filename): wget.download(url)
datasource_type_name='PUT YOUR DATASOURCE TYPE NAME HERE'
db_name='PUT YOUR DATABASE NAME HERE'
schema_name='PUT YOUR SCHEMA NAME HERE'
# datasource_type_name='db2'
# db_name='BLUDB'
# schema_name='ZL'
table_name='CREDIT_RISK'
db_credentials= {
"database":db_name,
"password":"***",
"port":"***",
"host":"***",
"ssl":"***",
"username":"***"
}
conn_meta_props= {
client.connections.ConfigurationMetaNames.NAME: f"Connection to Database - {datasource_name}:{db_name} ",
client.connections.ConfigurationMetaNames.DATASOURCE_TYPE: client.connections.get_datasource_type_uid_by_name(datasource_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)
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_uid_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_uid(conn_details)
Define connection information to training data.
from ibm_watson_machine_learning.helpers import DataConnection, S3Location
credit_risk_conn = DataConnection(
connection_asset_id=connection_id,
location=S3Location(bucket=bucketname,
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()
Provide the input information for AutoAI optimizer:
name
- experiment nameprediction_type
- type of the problemprediction_column
- target column namescoring
- optimization metricfrom ibm_watson_machine_learning.experiment import AutoAI
experiment = AutoAI(wml_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()
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)
You can use the get_run_status()
method to monitor AutoAI jobs in background mode.
pipeline_optimizer.get_run_status()
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()
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']
from ibm_watson_machine_learning.helpers import pipeline_to_script
pipeline_to_script(best_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.
best_pipeline.pretty_print(ipython_display=True, astype='sklearn')
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)
.
train_df = pipeline_optimizer.get_data_connections()[0].read()
train_X = train_df.drop(['Risk'], axis=1).values
train_y = train_df.Risk.values
predicted_y = best_pipeline.predict(train_X)
predicted_y[:5]
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']
experiment.runs.get_params(run_id=run_id)
historical_opt = experiment.runs.get_optimizer(run_id)
run_details = historical_opt.get_run_details()
historical_opt.summary()
hist_pipeline = historical_opt.get_pipeline(pipeline_name='Pipeline_3')
predicted_y = hist_pipeline.predict(train_X)
predicted_y[:5]
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()
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()
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)
pipeline_model = hyperopt_pipelines.get_pipeline()
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%}')
pipeline_model.visualize()
In this section you will learn how to deploy and score pipeline model as webservice using WML instance.
pipeline_name = "Pipeline_1"
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_name,
deployment_name="Credit Risk Deployment AutoAI")
Deployment object could be printed to show basic information:
print(service)
To show all available information about the deployment use the .get_params()
method:
service.get_params()
You can make scoring request by calling score()
on deployed pipeline.
predictions = service.score(payload=train_df.drop(['Risk'], axis=1).iloc[:10])
predictions
If you want to work with the web service in an external Python application you can retrieve the service object by:
service = WebService(wml_credentials)
service.list()
methodservice.get('deployment_id')
methodAfter that you can call service.score()
method.
You can delete the existing deployment by calling the service.delete()
command.
To list the existing web services you can use service.list()
.
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_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")
scoring_params = service_batch.run_job(
payload=batch_payload_df,
background_mode=False)
scoring_params['entity']['scoring'].get('predictions')
If you want to clean up all created assets:
please follow up this sample notebook.
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.
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, 2021, 2022 IBM. This notebook and its source code are released under the terms of the MIT License.