ibm-watson-machine-learning
¶This notebook contains steps and code to develop a predictive model, and start scoring new data. This notebook introduces commands for getting data and for basic data cleaning and exploration, pipeline creation, model training, 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 a data set, Telco Customer Churn, which details anonymous customer data from a telecommunication company. Use the details of this data set to predict customer churn which is very critical to business as it's easier to retain existing customers rather than acquiring new ones.
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, 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.
!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, 'WA_FnUseC_TelcoCustomerChurn.csv')
if not os.path.isfile(filename):
filename = download("https://github.com/IBM/watson-machine-learning-samples/raw/master/cloud/data/customer_churn/WA_FnUseC_TelcoCustomerChurn.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')\
.option('nanValue', ' ')\
.option('nullValue', ' ')\
.load(filename)
Explore the loaded data by using the following Apache® Spark DataFrame methods:
df_data.printSchema()
print("Number of fields: %3g" % len(df_data.schema))
As you can see, the data contains 21 fields. "Churn" field is the one we would like to predict (label).
print("Total number of records: " + str(df_data.count()))
Data set contains 7043 records.
Now you will check if all records have complete data.
df_complete = df_data.dropna()
print("Number of records with complete data: %3g" % df_complete.count())
You can see that there are some missing values you can investigate that all missing values are present in TotalCharges
feature. We will use dataset with missing values removed for model training and evaluation.
Now you will inspect distribution of classes in label column.
df_complete.groupBy('Churn').count().show()
In this section you will learn how to prepare data, create an Apache® Spark machine learning pipeline, and train a model.
In this subsection you will split your data into: train, test and predict datasets.
(train_data, test_data, predict_data) = df_complete.randomSplit([0.8, 0.18, 0.02], 24)
print("Number of records for training: " + str(train_data.count()))
print("Number of records for evaluation: " + str(test_data.count()))
print("Number of records for prediction: " + str(predict_data.count()))
As you can see our data has been successfully split into three datasets:
In this section you will create an Apache® Spark machine learning pipeline and then train the model.
In the first step you need to import the Apache® Spark machine learning packages that will be needed in the subsequent steps.
from pyspark.ml.feature import StringIndexer, IndexToString, RFormula
from pyspark.ml.classification import LogisticRegression
from pyspark.ml.evaluation import MulticlassClassificationEvaluator
from pyspark.ml import Pipeline, Model
In the following step, convert all the predictors to features vector and label feature convert to numeric.
lab = StringIndexer(inputCol = 'Churn', outputCol = 'label')
features = RFormula(formula = "~ gender + SeniorCitizen + Partner + Dependents + tenure + PhoneService + MultipleLines + InternetService + OnlineSecurity + OnlineBackup + DeviceProtection + TechSupport + StreamingTV + StreamingMovies + Contract + PaperlessBilling + PaymentMethod + MonthlyCharges + TotalCharges - 1")
Next, define estimators you want to use for classification. Logistic Regression is used in the following example.
lr = LogisticRegression(maxIter = 10)
Let's build the pipeline now. A pipeline consists of transformers and an estimator.
pipeline_lr = Pipeline(stages = [features, lab , lr])
Now, you can train your Logistic Regression model using the previously defined pipeline and train data."
model_lr = pipeline_lr.fit(train_data)
You can check your model accuracy now. To evaluate the model, use test data.
predictions = model_lr.transform(test_data)
evaluator = MulticlassClassificationEvaluator(labelCol="label", predictionCol="prediction", metricName="accuracy")
accuracy = evaluator.evaluate(predictions)
print("Test dataset:")
print("Accuracy = %3.2f" % accuracy)
You can tune your model now to achieve better accuracy. For simplicity of this example tuning section is omitted.
In this section you will learn how to store your pipeline and model in Watson Machine Learning repository using Python client libraries.
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 = {
"apikey": "***",
"cos_hmac_keys": {
"access_key_id": "***",
"secret_access_key": "***"
},
"endpoints": "***",
"iam_apikey_description": "***",
"iam_apikey_name": "***",
"iam_role_crn": "***",
"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 instance 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 WA_FnUseC_TelcoCustomerChurn.csv.
from uuid import uuid4
bucket_uid = str(uuid4())
score_filename = "WA_FnUseC_TelcoCustomerChurn.csv"
buckets = ["churn-" + 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.
training_data_references = [
{
"id": "customer churn",
"type": "connection_asset",
"connection": {
"id": connection_id
},
"location": {
"bucket": buckets[0],
"file_name": score_filename,
}
}
]
saved_model = client.repository.store_model(
model=model_lr,
meta_props={
client.repository.ModelMetaNames.NAME:'Customer Churn 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: "Churn",
},
training_data=train_data,
pipeline=pipeline_lr)
Get saved model metadata from Watson Machine Learning.
published_model_ID = client.repository.get_model_id(saved_model)
print("Model Id: " + str(published_model_ID))
Model Id can be used to retrive latest model version from Watson Machine Learning instance.
In this subsection you will learn how to load back saved model from specified instance of Watson Machine Learning.
loaded_model = client.repository.load(published_model_ID)
print(type(loaded_model))
As you can see the name is correct. You have already learned how save and load the model from Watson Machine Learning repository.
In this section you will learn how to load data from batch scoring and visualize the prediction results with plotly package.
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, truncate=False, vertical=True)
By tabulating a count, you can see the split between labels.
predictions.select("prediction").groupBy("prediction").count().show(truncate=False)
In this section you will learn how to create batch deployment and to score a new data record by using the Watson Machine Learning REST API. For more information about REST APIs, see the Swagger Documentation.
First, download scoring data into notebook's filesystem
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, 'scoreInput.csv')
if not os.path.isfile(filename):
filename = download("https://github.com/IBM/watson-machine-learning-samples/raw/master/cloud/data/customer_churn/scoreInput.csv", out=sample_dir)
Now you can create a batch scoring endpoint. Execute the following sample code that uses the published_model_ID value to create the scoring endpoint for predictions.
meta_data = {
client.deployments.ConfigurationMetaNames.NAME: "Customer Churn batch deployment",
client.deployments.ConfigurationMetaNames.BATCH: {},
client.deployments.ConfigurationMetaNames.HARDWARE_SPEC: {
"name": "S",
"num_nodes": 1
}
}
deployment_details = client.deployments.create(published_model_ID, meta_props=meta_data)
Batch deployment has been created.
You can retrieve now your deployment ID.
deployment_uid = client.deployments.get_uid(deployment_details)
You can also list all deployments in your space.
client.deployments.list()
If you want to get additional information on your deployment, you can do it as below.
client.deployments.get_details(deployment_uid)
Tip: To install pandas execute !pip install pandas
.
import pandas as pd
score_input = pd.read_csv(filename).astype('object')
job_payload_ref = {
client.deployments.ScoringMetaNames.INPUT_DATA: [
{
"fields": score_input.columns.tolist(),
"values": [score_input.loc[0].tolist()]
}
]
}
job = client.deployments.create_job(deployment_uid, meta_props=job_payload_ref)
Now, your job has been submitted to Spark runtime.
You can retrieve now your job ID.
job_id = client.deployments.get_job_uid(job)
You can also list all jobs in your space.
client.deployments.list_jobs()
If you want to get additional information on your job, you can do it as below.
client.deployments.get_job_details(job_id)
Here you can check status of your batch scoring. When status of Spark job is completed
the results will be written to scoring_output file in Object Storage.
import time
elapsed_time = 0
while client.deployments.get_job_status(job_id).get('state') != 'completed' and elapsed_time < 300:
print(f" Current state: {client.deployments.get_job_status(job_id).get('state')}")
elapsed_time += 10
time.sleep(10)
if client.deployments.get_job_status(job_id).get('state') == 'completed':
print(f" Current state: {client.deployments.get_job_status(job_id).get('state')}")
job_details_do = client.deployments.get_job_details(job_id)
print(job_details_do)
else:
print("Job hasn't completed successfully in 5 minutes.")
Get scored data
import json
print(json.dumps(client.deployments.get_job_details(job_id), indent=1))
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.