Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ibm
GitHub Repository: ibm/watson-machine-learning-samples
Path: blob/master/cpd3.5/notebooks/python_sdk/deployments/spark/cars-4-you/Use Spark to predict business area for car rental company.ipynb
6408 views
Kernel: Python 3

Use Spark to predict business area for car rental company with ibm-watson-machine-learning

This notebook contains steps and code to create a predictive model, and deploy it on WML. This notebook introduces commands for 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.6 and Apache® Spark 2.4.

You will use car_rental_training dataset.

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.

  • Deploy a model for online scoring using Wastson Machine Learning API.

  • Score sample scoring data using the Watson Machine Learning API.

Contents

This notebook contains the following parts:

  1. Setup

  2. Load and explore data

  3. Create an Apache Spark machine learning model

  4. Store the model in the Watson Machine Learning repository

  5. Deploy the model

  6. Score

  7. Clean up

  8. Summary and next steps

Note: This notebook works correctly with kernel Python 3.6 with Spark 2.4, please do not change kernel.

1. Set up the environment

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

  • Contact with your Cloud Pack for Data administrator and ask him for your account credentials

Connection to WML

Authenticate the Watson Machine Learning service on IBM Cloud Pack for Data. You need to provide platform url, your username and password.

username = 'PASTE YOUR USERNAME HERE' password = 'PASTE YOUR PASSWORD HERE' url = 'PASTE THE PLATFORM URL HERE'
wml_credentials = { "username": username, "password": password, "url": url, "instance_id": 'openshift', "version": '3.5' }

Install and import the ibm-watson-machine-learning package

Note: ibm-watson-machine-learning documentation can be found here.

!pip install -U ibm-watson-machine-learning
from ibm_watson_machine_learning import APIClient client = APIClient(wml_credentials)

Working with spaces

First of all, you need to create a space that will be used for your work. If you do not have space already created, you can use {PLATFORM_URL}/ml-runtime/spaces?context=icp4data to create one.

  • Click New Deployment Space

  • Create an empty space

  • Go to space Settings tab

  • 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

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)
'SUCCESS'

Test Spark

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.

Read data into Spark DataFrame from file.

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, 'car_rental_training_data.csv') if not os.path.isfile(filename): filename = download('https://github.com/IBM/watson-machine-learning-samples/raw/master/cpd3.5/data/cars-4-you/car_rental_training_data.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("delimiter", ";")\ .load(filename) df_data.take(3)
[Row(ID=83, Gender='Female', Status='M', Children=2, Age=48.85, Customer_Status='Inactive', Car_Owner='Yes', Customer_Service='I thought the representative handled the initial situation badly. The company was out of cars, with none coming in that day. Then the representative tried to find us a car at another franchise. There they were successful.', Satisfaction=0, Business_Area='Product: Availability/Variety/Size', Action='Free Upgrade'), Row(ID=1307, Gender='Female', Status='M', Children=0, Age=55.0, Customer_Status='Inactive', Car_Owner='No', Customer_Service='I have had a few recent rentals that have taken a very very long time, with no offer of apology. In the most recent case, the agent subsequently offered me a car type on an upgrade coupon and then told me it was no longer available because it had just be', Satisfaction=0, Business_Area='Product: Availability/Variety/Size', Action='Voucher'), Row(ID=1737, Gender='Male', Status='M', Children=0, Age=42.35, Customer_Status='Inactive', Car_Owner='Yes', Customer_Service="car cost more because I didn't pay when I reserved it", Satisfaction=0, Business_Area='Product: Availability/Variety/Size', Action='Free Upgrade')]

Explore data

df_data.printSchema()
root |-- ID: integer (nullable = true) |-- Gender: string (nullable = true) |-- Status: string (nullable = true) |-- Children: integer (nullable = true) |-- Age: double (nullable = true) |-- Customer_Status: string (nullable = true) |-- Car_Owner: string (nullable = true) |-- Customer_Service: string (nullable = true) |-- Satisfaction: integer (nullable = true) |-- Business_Area: string (nullable = true) |-- Action: string (nullable = true)

As you can see, the data contains eleven fields. Business_Area field is the one you would like to predict using feedback data in Customer_Service field.

print("Number of records: " + str(df_data.count()))
Number of records: 486

Let's see distribution of target field.

df_data.select('Business_Area').groupBy('Business_Area').count().show(truncate=False)
+----------------------------------+-----+ |Business_Area |count| +----------------------------------+-----+ |Service: Accessibility |26 | |Product: Functioning |150 | |Service: Attitude |24 | |Service: Orders/Contracts |32 | |Product: Availability/Variety/Size|42 | |Product: Pricing and Billing |24 | |Product: Information |8 | |Service: Knowledge |180 | +----------------------------------+-----+

3. Create an Apache Spark machine learning model

In this section you will learn how to:

3.1 Prepare data for model training and evaluation

In this subsection you will split your data into: train and test data set.

train_data, test_data = df_data.select("ID", "Customer_Service", "Business_Area").randomSplit([0.8, 0.2], 24) print("Number of training records: " + str(train_data.count())) print("Number of testing records : " + str(test_data.count()))
Number of training records: 391 Number of testing records : 95

3.2 Create the pipeline

In this section you will create an Apache Spark machine learning pipeline and then train the model.

from pyspark.ml.feature import StringIndexer, IndexToString, HashingTF, IDF, Tokenizer from pyspark.ml.classification import DecisionTreeClassifier from pyspark.ml.evaluation import MulticlassClassificationEvaluator from pyspark.ml import Pipeline, Model from pyspark.sql.types import *

In the first data preprocessing step, create features from Customer_Service field.

tokenizer = Tokenizer(inputCol="Customer_Service", outputCol="words") hashing_tf = HashingTF(inputCol=tokenizer.getOutputCol(), outputCol='hash') idf = IDF(inputCol=hashing_tf.getOutputCol(), outputCol="features", minDocFreq=5)

In the following step, use the StringIndexer transformer to convert Business_Area to numeric.

string_indexer_label = StringIndexer(inputCol="Business_Area", outputCol="label").fit(train_data)

Add decision tree model to predict Business_Area.

dt_area = DecisionTreeClassifier(labelCol="label", featuresCol=idf.getOutputCol())

Finally, setup transformer to convert the indexed labels back to original labels.

label_converter = IndexToString(inputCol="prediction", outputCol="predictedLabel", labels=string_indexer_label.labels)
pipeline = Pipeline(stages=[tokenizer, hashing_tf, idf, string_indexer_label, dt_area, label_converter])

3.3 Train the model

In this subsection you will train model and evaluate its accuracy.

model = pipeline.fit(train_data)
predictions = model.transform(test_data) predictions.select('Customer_Service','Business_Area','predictedLabel').show(3)
+--------------------+--------------------+------------------+ | Customer_Service| Business_Area| predictedLabel| +--------------------+--------------------+------------------+ |Agents always wan...| Service: Attitude|Service: Knowledge| |Did not have some...|Service: Accessib...|Service: Knowledge| |I was penalty cha...|Product: Pricing ...|Service: Knowledge| +--------------------+--------------------+------------------+ only showing top 3 rows
predictions.printSchema()
root |-- ID: integer (nullable = true) |-- Customer_Service: string (nullable = true) |-- Business_Area: string (nullable = true) |-- words: array (nullable = true) | |-- element: string (containsNull = true) |-- hash: vector (nullable = true) |-- features: vector (nullable = true) |-- label: double (nullable = false) |-- rawPrediction: vector (nullable = true) |-- probability: vector (nullable = true) |-- prediction: double (nullable = false) |-- predictedLabel: string (nullable = true)
evaluator = MulticlassClassificationEvaluator(labelCol="label", predictionCol="prediction", metricName="accuracy") accuracy = evaluator.evaluate(predictions) print("Accuracy = %3.2f" % accuracy)
Accuracy = 0.52

Note: Accuracy of the model is low, however based on customer comment more than one Business Area could be selected. In such cases top k (for example k=3) would be more suited for model evaluation.

4. Persist model

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 2.4 is required.

4.2 Save the pipeline and model

saved_model = client.repository.store_model( model=model, meta_props={ client.repository.ModelMetaNames.NAME:"CARS4U - Business Area Prediction Modeljj", client.repository.ModelMetaNames.TYPE: "mllib_2.4", client.repository.ModelMetaNames.SOFTWARE_SPEC_UID: client.software_specifications.get_id_by_name('spark-mllib_2.4'), client.repository.ModelMetaNames.LABEL_FIELD: "Business_Area", }, training_data=train_data, pipeline=pipeline)

Get saved model metadata from Watson Machine Learning.

published_model_id = client.repository.get_model_uid(saved_model) print("Model Id: " + str(published_model_id))
Model Id: 148a067b-4433-4d18-9db9-836469cdef98

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

Below you can see stored model details.

client.repository.get_model_details(published_model_id)
{'entity': {'label_column': 'Business_Area', 'pipeline': {'id': 'ed76a0be-4ebc-4467-a639-64dcadd58ab4'}, 'software_spec': {'id': '390d21f8-e58b-4fac-9c55-d7ceda621326', 'name': 'spark-mllib_2.4'}, 'training_data_references': [{'connection': {'access_key_id': 'not_applicable', 'endpoint_url': 'not_applicable', 'secret_access_key': 'not_applicable'}, 'id': '1', 'location': {}, 'schema': {'fields': [{'metadata': {}, 'name': 'ID', 'nullable': True, 'type': 'integer'}, {'metadata': {}, 'name': 'Customer_Service', 'nullable': True, 'type': 'string'}, {'metadata': {'modeling_role': 'target'}, 'name': 'Business_Area', 'nullable': True, 'type': 'string'}], 'id': '1', 'type': 'struct'}, 'type': 'fs'}], 'type': 'mllib_2.4'}, 'metadata': {'created_at': '2020-12-08T12:18:54.736Z', 'id': '148a067b-4433-4d18-9db9-836469cdef98', 'modified_at': '2020-12-08T12:18:57.352Z', 'name': 'CARS4U - Business Area Prediction Modeljj', 'owner': '1000330999', 'space_id': '83b00166-9047-4159-b777-83dcb498e7ab'}, 'system': {'warnings': []}}

5. Deploy model in the IBM Cloud

In this section you will learn how to create model deployment in the IBM Cloud and retreive information about scoring endpoint.

deployment_details = client.deployments.create( published_model_id, meta_props={ client.deployments.ConfigurationMetaNames.NAME: "CARS4U - Business Area Prediction Model deployment", client.deployments.ConfigurationMetaNames.ONLINE: {} } )
####################################################################################### Synchronous deployment creation for uid: '148a067b-4433-4d18-9db9-836469cdef98' started ####################################################################################### initializing ready ------------------------------------------------------------------------------------------------ Successfully finished deployment creation, deployment_uid='dcb4d6d3-4165-49ad-bca6-9c6d27d9ae71' ------------------------------------------------------------------------------------------------
deployment_details
{'entity': {'asset': {'id': '148a067b-4433-4d18-9db9-836469cdef98'}, 'custom': {}, 'deployed_asset_type': 'model', 'hardware_spec': {'id': 'Not_Applicable', 'name': 'S', 'num_nodes': 1}, 'name': 'CARS4U - Business Area Prediction Model deployment', 'online': {}, 'space_id': '83b00166-9047-4159-b777-83dcb498e7ab', 'status': {'online_url': {'url': 'https://wmlgmc-cpd-wmlgmc.apps.wmlautoai.cp.fyre.ibm.com/ml/v4/deployments/dcb4d6d3-4165-49ad-bca6-9c6d27d9ae71/predictions'}, 'state': 'ready'}}, 'metadata': {'created_at': '2020-12-08T12:19:26.660Z', 'id': 'dcb4d6d3-4165-49ad-bca6-9c6d27d9ae71', 'modified_at': '2020-12-08T12:19:26.660Z', 'name': 'CARS4U - Business Area Prediction Model deployment', 'owner': '1000330999', 'space_id': '83b00166-9047-4159-b777-83dcb498e7ab'}}

6. Score

fields = ['ID', 'Gender', 'Status', 'Children', 'Age', 'Customer_Status','Car_Owner', 'Customer_Service', 'Business_Area', 'Satisfaction'] values = [3785, 'Male', 'S', 1, 17, 'Inactive', 'Yes', 'The car should have been brought to us instead of us trying to find it in the lot.', 'Product: Information', 0]
import json payload_scoring = {"input_data": [{"fields": fields,"values": [values]}]} scoring_response = client.deployments.score(client.deployments.get_id(deployment_details), payload_scoring) print(json.dumps(scoring_response, indent=3))
{ "predictions": [ { "fields": [ "ID", "Gender", "Status", "Children", "Age", "Customer_Status", "Car_Owner", "Customer_Service", "Business_Area", "Satisfaction", "words", "hash", "features", "label", "rawPrediction", "probability", "prediction", "predictedLabel" ], "values": [ [ 3785, "Male", "S", 1.0, 17.0, "Inactive", "Yes", "The car should have been brought to us instead of us trying to find it in the lot.", "Product: Information", 0.0, [ "the", "car", "should", "have", "been", "brought", "to", "us", "instead", "of", "us", "trying", "to", "find", "it", "in", "the", "lot." ], [ 262144, [ 9639, 21872, 74079, 86175, 91878, 99585, 103838, 175817, 205044, 218965, 222453, 227152, 227431, 229772, 253475 ], [ 1.0, 2.0, 1.0, 1.0, 1.0, 1.0, 2.0, 1.0, 2.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 ] ], [ 262144, [ 9639, 21872, 74079, 86175, 91878, 99585, 103838, 175817, 205044, 218965, 222453, 227152, 227431, 229772, 253475 ], [ 1.7371553351932032, 5.586416018885034, 0.0, 1.589235205116581, 3.332204510175204, 3.406312482328926, 1.3359138634627736, 3.8918202981106265, 1.5789565789967548, 4.179502370562408, 1.8603879756171513, 0.0, 3.573366566992092, 1.1270747533318712, 1.8281271133989299 ] ], 7.0, [ 139.0, 81.0, 12.0, 16.0, 13.0, 14.0, 13.0, 7.0 ], [ 0.4711864406779661, 0.2745762711864407, 0.04067796610169491, 0.05423728813559322, 0.04406779661016949, 0.04745762711864407, 0.04406779661016949, 0.023728813559322035 ], 0.0, "Service: Knowledge" ] ] } ] }

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.

Authors

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

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