ibm-watson-machine-learning
¶This notebook introduces commands for model persistance to Watson Machine Learning repository, model deployment, and scoring.
Some familiarity with Python is helpful. This notebook runs on Python and Spark.
You will use German Credit Risk dataset.
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 platform api_key
and instance location
.
You can use IBM Cloud CLI to retrieve platform API Key and instance location.
API Key can be generated in the following way:
ibmcloud login
ibmcloud iam api-key-create API_KEY_NAME
In result, get the value of api_key
from the output.
Location of your WML instance can be retrieved in the following way:
ibmcloud login --apikey API_KEY -a https://cloud.ibm.com
ibmcloud resource service-instance WML_INSTANCE_NAME
In result, get the value of location
from the output.
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 also get service specific apikey by going to the Service IDs section of the Cloud Console. From that page, click Create, then copy the created key and paste it below.
Action: Enter your api_key
and location
in the following cell.
api_key = 'PASTE YOUR PLATFORM API KEY HERE'
location = 'PASTE YOUR INSTANCE LOCATION HERE'
wml_credentials = {
"apikey": api_key,
"url": 'https://' + location + '.ml.cloud.ibm.com'
}
!rm -rf /home/spark/shared/user-libs/python3.10*
!pip install -U --user ibm-watson-machine-learning
from ibm_watson_machine_learning import APIClient
client = APIClient(wml_credentials)
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 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 = 'PASTE YOUR SPACE ID HERE'
You can use 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 space which you will be using.
client.set.default_space(space_id)
try:
from pyspark.sql import SparkSession
except:
print('Error: Spark runtime is missing. If you are using Watson Studio change the notebook runtime to Spark.')
raise
In this section you will load the data as an Apache® Spark DataFrame and perform a basic exploration.
The csv file for German Credit Risk is available on the same repository as this notebook. Load the file to Apache® Spark DataFrame using code below.
!pip install wget
import os
from wget import download
sample_dir = 'spark_sample_model'
if not os.path.isdir(sample_dir):
os.mkdir(sample_dir)
filename = os.path.join(sample_dir, 'credit_risk_training.csv')
if not os.path.isfile(filename):
filename = download('https://github.com/IBM/watson-machine-learning-samples/raw/master/cloud/data/credit_risk/credit_risk_training.csv', out=sample_dir)
spark = SparkSession.builder.getOrCreate()
df_data = spark.read\
.format('org.apache.spark.sql.execution.datasources.csv.CSVFileFormat')\
.option('header', 'true')\
.option('inferSchema', 'true')\
.load(filename)
Explore the loaded data by using the following Apache® Spark DataFrame methods:
df_data.printSchema()
As you can see, the data contains 21 fields. Risk field is the one we would like to predict (label).
df_data.show(n=5, truncate=False, vertical=True)
print("Number of records: " + str(df_data.count()))
As you can see, the data set contains 5000 records.
In this subsection you will split your data into: train, test and predict datasets.
splitted_data = df_data.randomSplit([0.8, 0.18, 0.02], 24)
train_data = splitted_data[0]
test_data = splitted_data[1]
predict_data = splitted_data[2]
print("Number of training records: " + str(train_data.count()))
print("Number of testing records : " + str(test_data.count()))
print("Number of prediction records : " + str(predict_data.count()))
As you can see our data has been successfully split into three datasets:
In this section you will learn how to store your pipeline and model in Watson Machine Learning repository by using python client libraries.
Note: Apache® Spark is required.
ibm-cos-sdk library allows Python developers to manage Cloud Object Storage (COS).
import ibm_boto3
from ibm_botocore.client import Config
Action: Put credentials from Object Storage Service in Bluemix here.
cos_credentials = {
PASTE YOUR COS CREDENTIALS HERE
}
# example:
# cos_credentials = {
# "apikey": "***",
# "cos_hmac_keys": {
# "access_key_id": "***",
# "secret_access_key": "***"
# },
# "endpoints": "https://cos-service.bluemix.net/endpoints",
# "iam_apikey_description": "***",
# "iam_apikey_name": "***",
# "iam_role_crn": "crn:v1:bluemix:public:iam::::serviceRole:Writer",
# "iam_serviceid_crn": "***",
# "resource_instance_id": "***"
# }
connection_apikey = cos_credentials['apikey']
connection_resource_instance_id = cos_credentials["resource_instance_id"]
connection_access_key_id = cos_credentials['cos_hmac_keys']['access_key_id']
connection_secret_access_key = cos_credentials['cos_hmac_keys']['secret_access_key']
Action: Define the service endpoint we will use.
Tip: You can find this information in Endpoints section of your Cloud Object Storage intance's dashbord.
service_endpoint = 'https://s3.us.cloud-object-storage.appdomain.cloud'
You also need IBM Cloud authorization endpoint to be able to create COS resource object.
auth_endpoint = 'https://iam.cloud.ibm.com/identity/token'
We create COS resource to be able to write data to Cloud Object Storage.
cos = ibm_boto3.resource('s3',
ibm_api_key_id=cos_credentials['apikey'],
ibm_service_instance_id=cos_credentials['resource_instance_id'],
ibm_auth_endpoint=auth_endpoint,
config=Config(signature_version='oauth'),
endpoint_url=service_endpoint)
Now you will create bucket in COS and copy training dataset
for model from credit_risk_training.csv.
from uuid import uuid4
bucket_uid = str(uuid4())
score_filename = "credit_risk_training.csv"
buckets = ["credit-risk-" + bucket_uid]
for bucket in buckets:
if not cos.Bucket(bucket) in cos.buckets.all():
print('Creating bucket "{}"...'.format(bucket))
try:
cos.create_bucket(Bucket=bucket)
except ibm_boto3.exceptions.ibm_botocore.client.ClientError as e:
print('Error: {}.'.format(e.response['Error']['Message']))
bucket_obj = cos.Bucket(buckets[0])
print('Uploading data {}...'.format(score_filename))
with open(filename, 'rb') as f:
bucket_obj.upload_fileobj(f, score_filename)
print('{} is uploaded.'.format(score_filename))
datasource_type = client.connections.get_datasource_type_uid_by_name('bluemixcloudobjectstorage')
conn_meta_props= {
client.connections.ConfigurationMetaNames.NAME: "COS connection - spark",
client.connections.ConfigurationMetaNames.DATASOURCE_TYPE: datasource_type,
client.connections.ConfigurationMetaNames.PROPERTIES: {
'bucket': buckets[0],
'access_key': connection_access_key_id,
'secret_key': connection_secret_access_key,
'iam_url': auth_endpoint,
'url': service_endpoint
}
}
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)
In this subsection you will learn how to save pipeline and model artifacts to your Watson Machine Learning instance.
Download pipeline and model archives
import os
from wget import download
sample_dir = 'spark_sample_model'
if not os.path.isdir(sample_dir):
os.mkdir(sample_dir)
pipeline_filename = os.path.join(sample_dir, 'credit_risk_spark_pipeline.tar.gz')
if not os.path.isfile(pipeline_filename):
pipeline_filename = download('https://github.com/IBM/watson-machine-learning-samples/raw/master/cloud/models/spark/credit-risk/model/credit_risk_spark_pipeline.tar.gz', out=sample_dir)
model_filename = os.path.join(sample_dir, 'credit_risk_spark_model.gz')
if not os.path.isfile(model_filename):
model_filename = download('https://github.com/IBM/watson-machine-learning-samples/raw/master/cloud/models/spark/credit-risk/model/credit_risk_spark_model.gz', out=sample_dir)
Store piepline and model
To be able to store your Spark model, you need to provide a training data reference, this will allow to read the model schema automatically.
training_data_references = [
{
"type": "connection_asset",
"connection": {
"id": connection_id,
},
"location": {
"bucket": buckets[0],
"file_name": score_filename,
},
"schema": {
"id": "training_schema",
"fields": [
{
"metadata": {},
"name": "CheckingStatus",
"nullable": True,
"type": "string"
},
{
"metadata": {},
"name": "LoanDuration",
"nullable": True,
"type": "integer"
},
{
"metadata": {},
"name": "CreditHistory",
"nullable": True,
"type": "string"
},
{
"metadata": {},
"name": "LoanPurpose",
"nullable": True,
"type": "string"
},
{
"metadata": {},
"name": "LoanAmount",
"nullable": True,
"type": "integer"
},
{
"metadata": {},
"name": "ExistingSavings",
"nullable": True,
"type": "string"
},
{
"metadata": {},
"name": "EmploymentDuration",
"nullable": True,
"type": "string"
},
{
"metadata": {},
"name": "InstallmentPercent",
"nullable": True,
"type": "integer"
},
{
"metadata": {},
"name": "Sex",
"nullable": True,
"type": "string"
},
{
"metadata": {},
"name": "OthersOnLoan",
"nullable": True,
"type": "string"
},
{
"metadata": {},
"name": "CurrentResidenceDuration",
"nullable": True,
"type": "integer"
},
{
"metadata": {},
"name": "OwnsProperty",
"nullable": True,
"type": "string"
},
{
"metadata": {},
"name": "Age",
"nullable": True,
"type": "integer"
},
{
"metadata": {},
"name": "InstallmentPlans",
"nullable": True,
"type": "string"
},
{
"metadata": {},
"name": "Housing",
"nullable": True,
"type": "string"
},
{
"metadata": {},
"name": "ExistingCreditsCount",
"nullable": True,
"type": "integer"
},
{
"metadata": {},
"name": "Job",
"nullable": True,
"type": "string"
},
{
"metadata": {},
"name": "Dependents",
"nullable": True,
"type": "integer"
},
{
"metadata": {},
"name": "Telephone",
"nullable": True,
"type": "string"
},
{
"metadata": {},
"name": "ForeignWorker",
"nullable": True,
"type": "string"
},
{
"metadata": {
"modeling_role": "target"
},
"name": "Risk",
"nullable": True,
"type": "string"
}
]
}
}
]
published_model_details = client.repository.store_model(
model=model_filename,
meta_props={
client.repository.ModelMetaNames.NAME:'Credit Risk model',
client.repository.ModelMetaNames.TYPE: "mllib_3.3",
client.repository.ModelMetaNames.SOFTWARE_SPEC_UID: client.software_specifications.get_id_by_name('spark-mllib_3.3'),
client.repository.ModelMetaNames.TRAINING_DATA_REFERENCES: training_data_references,
client.repository.ModelMetaNames.LABEL_FIELD: "Risk",
},
training_data=train_data,
pipeline=pipeline_filename)
model_id = client.repository.get_model_id(published_model_details)
print(model_id)
client.repository.get_model_details(model_id)
Get saved model metadata from Watson Machine Learning.
Tip: Use client.repository.ModelMetaNames.show()
to get the list of available props.
client.repository.ModelMetaNames.show()
In this subsection you will learn how to load back saved model from specified instance of Watson Machine Learning.
loaded_model = client.repository.load(model_id)
You can print for example model name to make sure that model has been loaded correctly.
print(type(loaded_model))
In this section you will learn how to score test data using loaded model.
In this subsection you will score predict_data data set.
predictions = loaded_model.transform(predict_data)
Preview the results by calling the show() method on the predictions DataFrame.
predictions.show(5, vertical=True)
By tabulating a count, you can see which product line is the most popular.
predictions.select("predictedLabel").groupBy("predictedLabel").count().show(truncate=False)
In this section you will learn how to create online scoring and to score a new data record using ibm-watson-machine-learning
.
Note: You can also use REST API to deploy and score. For more information about REST APIs, see the Swagger Documentation.
Now you can create an online scoring endpoint.
deployment_details = client.deployments.create(
model_id,
meta_props={
client.deployments.ConfigurationMetaNames.NAME: "Credit Risk model deployment",
client.deployments.ConfigurationMetaNames.ONLINE: {}
}
)
deployment_details
Now, you can send new scoring records (new data) for which you would like to get predictions. To do that, execute the following sample code:
fields = ["CheckingStatus", "LoanDuration", "CreditHistory", "LoanPurpose", "LoanAmount", "ExistingSavings",
"EmploymentDuration", "InstallmentPercent", "Sex", "OthersOnLoan", "CurrentResidenceDuration",
"OwnsProperty", "Age", "InstallmentPlans", "Housing", "ExistingCreditsCount", "Job", "Dependents",
"Telephone", "ForeignWorker"]
values = [
["no_checking", 13, "credits_paid_to_date", "car_new", 1343, "100_to_500", "1_to_4", 2, "female", "none", 3,
"savings_insurance", 46, "none", "own", 2, "skilled", 1, "none", "yes"],
["no_checking", 24, "prior_payments_delayed", "furniture", 4567, "500_to_1000", "1_to_4", 4, "male", "none",
4, "savings_insurance", 36, "none", "free", 2, "management_self-employed", 1, "none", "yes"],
["0_to_200", 26, "all_credits_paid_back", "car_new", 863, "less_100", "less_1", 2, "female", "co-applicant",
2, "real_estate", 38, "none", "own", 1, "skilled", 1, "none", "yes"],
["0_to_200", 14, "no_credits", "car_new", 2368, "less_100", "1_to_4", 3, "female", "none", 3, "real_estate",
29, "none", "own", 1, "skilled", 1, "none", "yes"],
["0_to_200", 4, "no_credits", "car_new", 250, "less_100", "unemployed", 2, "female", "none", 3,
"real_estate", 23, "none", "rent", 1, "management_self-employed", 1, "none", "yes"],
["no_checking", 17, "credits_paid_to_date", "car_new", 832, "100_to_500", "1_to_4", 2, "male", "none", 2,
"real_estate", 42, "none", "own", 1, "skilled", 1, "none", "yes"],
["no_checking", 33, "outstanding_credit", "appliances", 5696, "unknown", "greater_7", 4, "male",
"co-applicant", 4, "unknown", 54, "none", "free", 2, "skilled", 1, "yes", "yes"],
["0_to_200", 13, "prior_payments_delayed", "retraining", 1375, "100_to_500", "4_to_7", 3, "male", "none", 3,
"real_estate", 37, "none", "own", 2, "management_self-employed", 1, "none", "yes"]
]
payload_scoring = {"input_data": [{"fields": fields, "values": values}]}
deployment_id = client.deployments.get_id(deployment_details)
client.deployments.score(deployment_id, payload_scoring)
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 Apache Spark machine learning as well as Watson Machine Learning for model creation and deployment. Check out our Online Documentation for more samples, tutorials, documentation, how-tos, and blog posts.
Amadeusz Masny, Python Software Developer in Watson Machine Learning at IBM
Copyright © 2020-2024 IBM. This notebook and its source code are released under the terms of the MIT License.