Use Spark and batch deployment to predict customer churn with ibm-watsonx-ai¶

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 uses Python 3.11 and Apache® Spark 3.4.

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.

Learning goals¶

The learning goals of this notebook are:

  • Load a CSV file into an Apache® Spark DataFrame.
  • Explore data.
  • Prepare data for training and evaluation.
  • Create an Apache® Spark machine learning pipeline.
  • Train and evaluate a model.
  • Persist a pipeline and model in Watson Machine Learning repository.
  • Explore and visualize prediction results using the plotly package.
  • Deploy a model for batch scoring using Wastson Machine Learning API.

Contents¶

This notebook contains the following parts:

  1. Set up the environment
  2. Load and explore data
  3. Create spark ml model
  4. Persist model
  5. Predict locally and visualize
  6. Deploy and score in a Cloud
  7. Clean up
  8. Summary and next steps

1. Set up the environment¶

Before you use the sample code in this notebook, you must perform the following setup tasks:

  • Create a Watson Machine Learning (WML) Service instance (a free plan is offered and information about how to create the instance can be found here).

Install and import the ibm-watsonx-ai and dependecies¶

Note: ibm-watsonx-ai documentation can be found here.

In [ ]:
!pip install wget
!pip install pyspark==3.4.3 | tail -n 1
!pip install -U ibm-watsonx-ai | tail -n 1

Connection to WML¶

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.

In [1]:
api_key = 'PASTE YOUR PLATFORM API KEY HERE'
location = 'PASTE YOUR INSTANCE LOCATION HERE'
In [1]:
from ibm_watsonx_ai import Credentials

credentials = Credentials(
    api_key=api_key,
    url='https://' + location + '.ml.cloud.ibm.com'
)
In [2]:
from ibm_watsonx_ai import APIClient

client = APIClient(credentials)

Working with spaces¶

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.

  • Click New Deployment Space
  • Create an empty space
  • Select Cloud Object Storage
  • Select Watson Machine Learning instance and press Create
  • 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

In [3]:
space_id = 'PASTE YOUR SPACE ID HERE'

You can use list method to print all existing spaces.

In [ ]:
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.

In [4]:
client.set.default_space(space_id)
Out[4]:
'SUCCESS'

Test Spark¶

In [5]:
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

2. Load and explore data¶

In this section you will load the data as an Apache® Spark DataFrame and perform a basic exploration.

In [6]:
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)
In [ ]:
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:

  • print schema
  • count all records
  • show distribution of label classes
In [8]:
df_data.printSchema()

print("Number of fields: %3g" % len(df_data.schema))
root
 |-- customerID: string (nullable = true)
 |-- gender: string (nullable = true)
 |-- SeniorCitizen: integer (nullable = true)
 |-- Partner: string (nullable = true)
 |-- Dependents: string (nullable = true)
 |-- tenure: integer (nullable = true)
 |-- PhoneService: string (nullable = true)
 |-- MultipleLines: string (nullable = true)
 |-- InternetService: string (nullable = true)
 |-- OnlineSecurity: string (nullable = true)
 |-- OnlineBackup: string (nullable = true)
 |-- DeviceProtection: string (nullable = true)
 |-- TechSupport: string (nullable = true)
 |-- StreamingTV: string (nullable = true)
 |-- StreamingMovies: string (nullable = true)
 |-- Contract: string (nullable = true)
 |-- PaperlessBilling: string (nullable = true)
 |-- PaymentMethod: string (nullable = true)
 |-- MonthlyCharges: double (nullable = true)
 |-- TotalCharges: double (nullable = true)
 |-- Churn: string (nullable = true)

Number of fields:  21

As you can see, the data contains 21 fields. "Churn" field is the one we would like to predict (label).

In [9]:
print("Total number of records: " + str(df_data.count()))
Total number of records: 7043

Data set contains 7043 records.

Now you will check if all records have complete data.

In [10]:
df_complete = df_data.dropna()

print("Number of records with complete data: %3g" % df_complete.count())
Number of records with complete data: 7032

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.

In [11]:
df_complete.groupBy('Churn').count().show()
+-----+-----+
|Churn|count|
+-----+-----+
|   No| 5163|
|  Yes| 1869|
+-----+-----+

3. Create an Apache® Spark machine learning model¶

In this section you will learn how to prepare data, create an Apache® Spark machine learning pipeline, and train a model.

3.1: Prepare data¶

In this subsection you will split your data into: train, test and predict datasets.

In [12]:
(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()))
Number of records for training: 5638
Number of records for evaluation: 1261
Number of records for prediction: 133

As you can see our data has been successfully split into three datasets:

  • The train data set, which is the largest group, is used for training.
  • The test data set will be used for model evaluation and is used to test the assumptions of the model.
  • The predict data set will be used for prediction.

3.2: Create pipeline and train a model¶

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.

In [13]:
from pyspark.ml.feature import StringIndexer, RFormula
from pyspark.ml.classification import LogisticRegression
from pyspark.ml.evaluation import MulticlassClassificationEvaluator
from pyspark.ml import Pipeline

In the following step, convert all the predictors to features vector and label feature convert to numeric.

In [14]:
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.

In [15]:
lr = LogisticRegression(maxIter = 10)

Let's build the pipeline now. A pipeline consists of transformers and an estimator.

In [16]:
pipeline_lr = Pipeline(stages = [features, lab , lr])

Now, you can train your Logistic Regression model using the previously defined pipeline and train data."

In [17]:
model_lr = pipeline_lr.fit(train_data)
                                                                                

You can check your model accuracy now. To evaluate the model, use test data.

In [18]:
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)
Test dataset:
Accuracy = 0.80

You can tune your model now to achieve better accuracy. For simplicity of this example tuning section is omitted.

4. Persist model¶

In this section you will learn how to store your pipeline and model in Watson Machine Learning repository using Python client libraries.

Note: Apache® Spark 3.4 is required.

Save training data in your Cloud Object Storage¶

ibm-cos-sdk library allows Python developers to manage Cloud Object Storage (COS).

In [19]:
import ibm_boto3
from ibm_botocore.client import Config

Action: Put credentials from Object Storage Service in Bluemix here.

In [20]:
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": "***"
                }
In [21]:
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.

In [22]:
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.

In [23]:
auth_endpoint = 'https://iam.cloud.ibm.com/identity/token'

We create COS resource to be able to write data to Cloud Object Storage.

In [24]:
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.

In [25]:
from uuid import uuid4

bucket_id = str(uuid4())

score_filename = "WA_FnUseC_TelcoCustomerChurn.csv"
buckets = ["churn-" + bucket_id]
In [27]:
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']))
Creating bucket "churn-e5460ab4-2104-4655-b519-318dbf3d5187"...
In [28]:
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))
Uploading data WA_FnUseC_TelcoCustomerChurn.csv...
WA_FnUseC_TelcoCustomerChurn.csv is uploaded.

Create connections to a COS bucket¶

In [29]:
datasource_type = client.connections.get_datasource_type_id_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)
Creating connections...
SUCCESS

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_id_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)

In [30]:
connection_id = client.connections.get_id(conn_details)

4.1: Save pipeline and model¶

In this subsection you will learn how to save pipeline and model artifacts to your Watson Machine Learning instance.

In [31]:
training_data_references = [
                {
                    "id": "customer churn",
                    "type": "connection_asset",
                    "connection": {
                        "id": connection_id
                    },
                    "location": {
                        "bucket": buckets[0],
                        "file_name": score_filename,
                    }
                }
            ]
In [32]:
saved_model = client.repository.store_model(
    model=model_lr, 
    meta_props={
        client.repository.ModelMetaNames.NAME:'Customer Churn model',
        client.repository.ModelMetaNames.TYPE: "mllib_3.4",
        client.repository.ModelMetaNames.SOFTWARE_SPEC_ID: client.software_specifications.get_id_by_name('spark-mllib_3.4'),
        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.

In [33]:
published_model_ID = client.repository.get_model_id(saved_model)

print("Model Id: " + str(published_model_ID))
Model Id: 2020c57d-62d7-421f-8c4e-941a791cfe8b

Model Id can be used to retrive latest model version from Watson Machine Learning instance.

4.2: Load model¶

In this subsection you will learn how to load back saved model from specified instance of Watson Machine Learning.

In [34]:
loaded_model = client.repository.load(published_model_ID)
                                                                                
In [35]:
print(type(loaded_model))
<class 'pyspark.ml.pipeline.PipelineModel'>

As you can see the name is correct. You have already learned how save and load the model from Watson Machine Learning repository.

5. Predict locally¶

In this section you will learn how to load data from batch scoring and visualize the prediction results with plotly package.

5.1: Make local prediction using previously loaded model and test data¶

In this subsection you will score predict_data data set.

In [36]:
predictions = loaded_model.transform(predict_data)

Preview the results by calling the show() method on the predictions DataFrame.

In [37]:
predictions.show(5, truncate=False, vertical=True)
24/03/06 14:36:05 WARN package: Truncated the string representation of a plan since it was too large. This behavior can be adjusted by setting 'spark.sql.debug.maxToStringFields'.
-RECORD 0-----------------------------------------------------------------------------------------------------------------------------------------
 customerID       | 0117-LFRMW                                                                                                                    
 gender           | Male                                                                                                                          
 SeniorCitizen    | 0                                                                                                                             
 Partner          | Yes                                                                                                                           
 Dependents       | Yes                                                                                                                           
 tenure           | 37                                                                                                                            
 PhoneService     | No                                                                                                                            
 MultipleLines    | No phone service                                                                                                              
 InternetService  | DSL                                                                                                                           
 OnlineSecurity   | Yes                                                                                                                           
 OnlineBackup     | Yes                                                                                                                           
 DeviceProtection | Yes                                                                                                                           
 TechSupport      | No                                                                                                                            
 StreamingTV      | No                                                                                                                            
 StreamingMovies  | No                                                                                                                            
 Contract         | Month-to-month                                                                                                                
 PaperlessBilling | No                                                                                                                            
 PaymentMethod    | Bank transfer (automatic)                                                                                                     
 MonthlyCharges   | 40.2                                                                                                                          
 TotalCharges     | 1448.8                                                                                                                        
 Churn            | Yes                                                                                                                           
 features         | (31,[0,5,10,12,14,16,17,19,21,23,28,29,30],[1.0,37.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,40.2,1448.8])                        
 label            | 1.0                                                                                                                           
 rawPrediction    | [2.1157559265159356,-2.1157559265159356]                                                                                      
 probability      | [0.8924251659626177,0.10757483403738233]                                                                                      
 prediction       | 0.0                                                                                                                           
-RECORD 1-----------------------------------------------------------------------------------------------------------------------------------------
 customerID       | 0121-SNYRK                                                                                                                    
 gender           | Male                                                                                                                          
 SeniorCitizen    | 0                                                                                                                             
 Partner          | No                                                                                                                            
 Dependents       | No                                                                                                                            
 tenure           | 50                                                                                                                            
 PhoneService     | No                                                                                                                            
 MultipleLines    | No phone service                                                                                                              
 InternetService  | DSL                                                                                                                           
 OnlineSecurity   | Yes                                                                                                                           
 OnlineBackup     | No                                                                                                                            
 DeviceProtection | No                                                                                                                            
 TechSupport      | Yes                                                                                                                           
 StreamingTV      | No                                                                                                                            
 StreamingMovies  | No                                                                                                                            
 Contract         | One year                                                                                                                      
 PaperlessBilling | Yes                                                                                                                           
 PaymentMethod    | Mailed check                                                                                                                  
 MonthlyCharges   | 35.4                                                                                                                          
 TotalCharges     | 1748.9                                                                                                                        
 Churn            | No                                                                                                                            
 features         | (31,[0,3,4,5,10,12,13,15,18,19,21,25,27,29,30],[1.0,1.0,1.0,50.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,35.4,1748.9])            
 label            | 0.0                                                                                                                           
 rawPrediction    | [2.919009391240401,-2.919009391240401]                                                                                        
 probability      | [0.9487781787299795,0.05122182127002051]                                                                                      
 prediction       | 0.0                                                                                                                           
-RECORD 2-----------------------------------------------------------------------------------------------------------------------------------------
 customerID       | 0314-TKOSI                                                                                                                    
 gender           | Female                                                                                                                        
 SeniorCitizen    | 0                                                                                                                             
 Partner          | No                                                                                                                            
 Dependents       | No                                                                                                                            
 tenure           | 6                                                                                                                             
 PhoneService     | Yes                                                                                                                           
 MultipleLines    | No                                                                                                                            
 InternetService  | DSL                                                                                                                           
 OnlineSecurity   | Yes                                                                                                                           
 OnlineBackup     | Yes                                                                                                                           
 DeviceProtection | No                                                                                                                            
 TechSupport      | No                                                                                                                            
 StreamingTV      | No                                                                                                                            
 StreamingMovies  | No                                                                                                                            
 Contract         | Month-to-month                                                                                                                
 PaperlessBilling | No                                                                                                                            
 PaymentMethod    | Mailed check                                                                                                                  
 MonthlyCharges   | 55.15                                                                                                                         
 TotalCharges     | 322.9                                                                                                                         
 Churn            | No                                                                                                                            
 features         | (31,[1,3,4,5,6,7,10,12,14,15,17,19,21,23,27,29,30],[1.0,1.0,1.0,6.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,55.15,322.9]) 
 label            | 0.0                                                                                                                           
 rawPrediction    | [1.384000162011289,-1.384000162011289]                                                                                        
 probability      | [0.7996326754890671,0.20036732451093286]                                                                                      
 prediction       | 0.0                                                                                                                           
-RECORD 3-----------------------------------------------------------------------------------------------------------------------------------------
 customerID       | 0365-TRTPY                                                                                                                    
 gender           | Female                                                                                                                        
 SeniorCitizen    | 0                                                                                                                             
 Partner          | No                                                                                                                            
 Dependents       | No                                                                                                                            
 tenure           | 37                                                                                                                            
 PhoneService     | Yes                                                                                                                           
 MultipleLines    | Yes                                                                                                                           
 InternetService  | Fiber optic                                                                                                                   
 OnlineSecurity   | Yes                                                                                                                           
 OnlineBackup     | Yes                                                                                                                           
 DeviceProtection | Yes                                                                                                                           
 TechSupport      | No                                                                                                                            
 StreamingTV      | No                                                                                                                            
 StreamingMovies  | No                                                                                                                            
 Contract         | Month-to-month                                                                                                                
 PaperlessBilling | No                                                                                                                            
 PaymentMethod    | Bank transfer (automatic)                                                                                                     
 MonthlyCharges   | 91.2                                                                                                                          
 TotalCharges     | 3382.3                                                                                                                        
 Churn            | No                                                                                                                            
 features         | (31,[1,3,4,5,6,8,9,12,14,16,17,19,21,23,28,29,30],[1.0,1.0,1.0,37.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,91.2,3382.3]) 
 label            | 0.0                                                                                                                           
 rawPrediction    | [1.2619544615514307,-1.2619544615514307]                                                                                      
 probability      | [0.7793623739634478,0.22063762603655224]                                                                                      
 prediction       | 0.0                                                                                                                           
-RECORD 4-----------------------------------------------------------------------------------------------------------------------------------------
 customerID       | 0384-LPITE                                                                                                                    
 gender           | Male                                                                                                                          
 SeniorCitizen    | 0                                                                                                                             
 Partner          | No                                                                                                                            
 Dependents       | No                                                                                                                            
 tenure           | 40                                                                                                                            
 PhoneService     | No                                                                                                                            
 MultipleLines    | No phone service                                                                                                              
 InternetService  | DSL                                                                                                                           
 OnlineSecurity   | Yes                                                                                                                           
 OnlineBackup     | Yes                                                                                                                           
 DeviceProtection | Yes                                                                                                                           
 TechSupport      | No                                                                                                                            
 StreamingTV      | Yes                                                                                                                           
 StreamingMovies  | Yes                                                                                                                           
 Contract         | One year                                                                                                                      
 PaperlessBilling | No                                                                                                                            
 PaymentMethod    | Credit card (automatic)                                                                                                       
 MonthlyCharges   | 62.05                                                                                                                         
 TotalCharges     | 2511.55                                                                                                                       
 Churn            | No                                                                                                                            
 features         | (31,[0,3,4,5,10,12,14,16,17,20,22,29,30],[1.0,1.0,1.0,40.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,62.05,2511.55])                        
 label            | 0.0                                                                                                                           
 rawPrediction    | [2.2727488523528008,-2.2727488523528008]                                                                                      
 probability      | [0.9065948226759218,0.09340517732407816]                                                                                      
 prediction       | 0.0                                                                                                                           
only showing top 5 rows

By tabulating a count, you can see the split between labels.

In [38]:
predictions.select("prediction").groupBy("prediction").count().show(truncate=False)
+----------+-----+
|prediction|count|
+----------+-----+
|0.0       |103  |
|1.0       |30   |
+----------+-----+

6. Deploy model and score in a Cloud¶

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.

6.1 Prepare scoring data for batch job¶

Get data for prediction¶

First, download scoring data into notebook's filesystem

In [41]:
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)

6.2: Create batch deployment¶

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.

Create batch deployment for published model¶

In [40]:
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)

#######################################################################################

Synchronous deployment creation for uid: '2020c57d-62d7-421f-8c4e-941a791cfe8b' started

#######################################################################################


ready.


------------------------------------------------------------------------------------------------
Successfully finished deployment creation, deployment_uid='10629654-5f34-45ac-b97c-f8d0bdd705ca'
------------------------------------------------------------------------------------------------


Batch deployment has been created.

You can retrieve now your deployment ID.

In [42]:
deployment_id = client.deployments.get_id(deployment_details)

You can also list all deployments in your space.

In [ ]:
client.deployments.list()

If you want to get additional information on your deployment, you can do it as below.

In [44]:
client.deployments.get_details(deployment_id)
Out[44]:
{'entity': {'asset': {'id': '2020c57d-62d7-421f-8c4e-941a791cfe8b'},
  'batch': {},
  'custom': {},
  'deployed_asset_type': 'model',
  'hardware_spec': {'id': 'e7ed1d6c-2e89-42d7-aed5-863b972c1d2b',
   'name': 'S',
   'num_nodes': 1},
  'name': 'Customer Churn batch deployment',
  'space_id': '93ee84d1-b7dd-42b4-b2ca-121bc0c86315',
  'status': {'state': 'ready'}},
 'metadata': {'created_at': '2024-03-06T13:36:53.104Z',
  'id': '10629654-5f34-45ac-b97c-f8d0bdd705ca',
  'modified_at': '2024-03-06T13:36:53.104Z',
  'name': 'Customer Churn batch deployment',
  'owner': 'IBMid-55000091VC',
  'space_id': '93ee84d1-b7dd-42b4-b2ca-121bc0c86315'}}

Create and run Batch job¶

Tip: To install pandas execute !pip install pandas

In [45]:
import pandas as pd

score_input = pd.read_csv(filename).astype('object')
In [46]:
job_payload_ref = {
    client.deployments.ScoringMetaNames.INPUT_DATA: [
        {
            "fields": score_input.columns.tolist(),
            "values": [score_input.loc[0].tolist()]
        }
    ]
}
In [47]:
job = client.deployments.create_job(deployment_id, meta_props=job_payload_ref)

Now, your job has been submitted to Spark runtime.

You can retrieve now your job ID.

In [48]:
job_id = client.deployments.get_job_id(job)

You can also list all jobs in your space.

In [ ]:
client.deployments.list_jobs()

If you want to get additional information on your job, you can do it as below.

In [ ]:
client.deployments.get_job_details(job_id)

Monitor job execution¶

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.

In [51]:
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.")
 Current state: queued
 Current state: queued
 Current state: queued
 Current state: completed
{'entity': {'deployment': {'id': '10629654-5f34-45ac-b97c-f8d0bdd705ca'}, 'platform_job': {'job_id': '6f95e80e-f919-429b-a791-55e4b525e79d', 'run_id': 'bbe66cc3-c070-40bd-9c93-d05d566428d1'}, 'scoring': {'input_data': [{'fields': ['customerID', 'gender', 'SeniorCitizen', 'Partner', 'Dependents', 'tenure', 'PhoneService', 'MultipleLines', 'InternetService', 'OnlineSecurity', 'OnlineBackup', 'DeviceProtection', 'TechSupport', 'StreamingTV', 'StreamingMovies', 'Contract', 'PaperlessBilling', 'PaymentMethod', 'MonthlyCharges', 'TotalCharges', 'Churn', 'SampleWeight'], 'values': [['9237-HQITU', 'Female', 0, 'No', 'No', 2, 'Yes', 'No', 'Fiber optic', 'No', 'No', 'No', 'No', 'No', 'No', 'Month-to-month', 'Yes', 'Electronic check', 70.7, 151.65, 'Yes', 1]]}], 'predictions': [{'fields': ['customerID', 'gender', 'SeniorCitizen', 'Partner', 'Dependents', 'tenure', 'PhoneService', 'MultipleLines', 'InternetService', 'OnlineSecurity', 'OnlineBackup', 'DeviceProtection', 'TechSupport', 'StreamingTV', 'StreamingMovies', 'Contract', 'PaperlessBilling', 'PaymentMethod', 'MonthlyCharges', 'TotalCharges', 'Churn', 'SampleWeight', 'features', 'label', 'rawPrediction', 'probability', 'prediction'], 'values': [['9237-HQITU', 'Female', 0, 'No', 'No', 2, 'Yes', 'No', 'Fiber optic', 'No', 'No', 'No', 'No', 'No', 'No', 'Month-to-month', 'Yes', 'Electronic check', 70.7, 151.65, 'Yes', 1, [31, [1, 3, 4, 5, 6, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 26, 29, 30], [1.0, 1.0, 1.0, 2.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 70.7, 151.65]], 1.0, [-0.7671302889688807, 0.7671302889688807], [0.3171002090667438, 0.6828997909332561], 1.0]]}], 'status': {'completed_at': '2024-03-06T13:40:04.000Z', 'running_at': '2024-03-06T13:40:02.000Z', 'state': 'completed'}}}, 'metadata': {'created_at': '2024-03-06T13:39:27.594Z', 'id': '80e15c7a-28b6-439b-888d-45ea4df07864', 'modified_at': '2024-03-06T13:40:04.215Z', 'name': 'name_c8c5e8ba-ac5f-4cba-9ef6-d4b0a8588a1e', 'space_id': '93ee84d1-b7dd-42b4-b2ca-121bc0c86315'}}

Get scored data¶

In [53]:
import json

print(json.dumps(client.deployments.get_job_details(job_id), indent=1))
{
 "entity": {
  "deployment": {
   "id": "10629654-5f34-45ac-b97c-f8d0bdd705ca"
  },
  "platform_job": {
   "job_id": "6f95e80e-f919-429b-a791-55e4b525e79d",
   "run_id": "bbe66cc3-c070-40bd-9c93-d05d566428d1"
  },
  "scoring": {
   "input_data": [
    {
     "fields": [
      "customerID",
      "gender",
      "SeniorCitizen",
      "Partner",
      "Dependents",
      "tenure",
      "PhoneService",
      "MultipleLines",
      "InternetService",
      "OnlineSecurity",
      "OnlineBackup",
      "DeviceProtection",
      "TechSupport",
      "StreamingTV",
      "StreamingMovies",
      "Contract",
      "PaperlessBilling",
      "PaymentMethod",
      "MonthlyCharges",
      "TotalCharges",
      "Churn",
      "SampleWeight"
     ],
     "values": [
      [
       "9237-HQITU",
       "Female",
       0,
       "No",
       "No",
       2,
       "Yes",
       "No",
       "Fiber optic",
       "No",
       "No",
       "No",
       "No",
       "No",
       "No",
       "Month-to-month",
       "Yes",
       "Electronic check",
       70.7,
       151.65,
       "Yes",
       1
      ]
     ]
    }
   ],
   "predictions": [
    {
     "fields": [
      "customerID",
      "gender",
      "SeniorCitizen",
      "Partner",
      "Dependents",
      "tenure",
      "PhoneService",
      "MultipleLines",
      "InternetService",
      "OnlineSecurity",
      "OnlineBackup",
      "DeviceProtection",
      "TechSupport",
      "StreamingTV",
      "StreamingMovies",
      "Contract",
      "PaperlessBilling",
      "PaymentMethod",
      "MonthlyCharges",
      "TotalCharges",
      "Churn",
      "SampleWeight",
      "features",
      "label",
      "rawPrediction",
      "probability",
      "prediction"
     ],
     "values": [
      [
       "9237-HQITU",
       "Female",
       0,
       "No",
       "No",
       2,
       "Yes",
       "No",
       "Fiber optic",
       "No",
       "No",
       "No",
       "No",
       "No",
       "No",
       "Month-to-month",
       "Yes",
       "Electronic check",
       70.7,
       151.65,
       "Yes",
       1,
       [
        31,
        [
         1,
         3,
         4,
         5,
         6,
         7,
         9,
         11,
         13,
         15,
         17,
         19,
         21,
         23,
         25,
         26,
         29,
         30
        ],
        [
         1.0,
         1.0,
         1.0,
         2.0,
         1.0,
         1.0,
         1.0,
         1.0,
         1.0,
         1.0,
         1.0,
         1.0,
         1.0,
         1.0,
         1.0,
         1.0,
         70.7,
         151.65
        ]
       ],
       1.0,
       [
        -0.7671302889688807,
        0.7671302889688807
       ],
       [
        0.3171002090667438,
        0.6828997909332561
       ],
       1.0
      ]
     ]
    }
   ],
   "status": {
    "completed_at": "2024-03-06T13:40:04.000Z",
    "running_at": "2024-03-06T13:40:02.000Z",
    "state": "completed"
   }
  }
 },
 "metadata": {
  "created_at": "2024-03-06T13:39:27.594Z",
  "id": "80e15c7a-28b6-439b-888d-45ea4df07864",
  "modified_at": "2024-03-06T13:40:04.215Z",
  "name": "name_c8c5e8ba-ac5f-4cba-9ef6-d4b0a8588a1e",
  "space_id": "93ee84d1-b7dd-42b4-b2ca-121bc0c86315"
 }
}

7. 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.

8. Summary and next steps¶

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.

Author¶

Amadeusz Masny, Python Software Developer in Watson Machine Learning at IBM

Mateusz Szewczyk, Software Engineer at Watson Machine Learning

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