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

Use Spark to recommend mitigation 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.9 and Apache® Spark 3.0.

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.9 with Spark 3.0, 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 api_key.

username = 'PASTE YOUR USERNAME HERE' api_key = 'PASTE YOUR API_KEY HERE' url = 'PASTE THE PLATFORM URL HERE'
wml_credentials = { "username": username, "apikey": api_key, "url": url, "instance_id": 'openshift', "version": '4.5' }

Alternatively you can use username and password to authenticate WML services.

wml_credentials = { "username": ***, "password": ***, "url": ***, "instance_id": 'openshift', "version": '4.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'

Note: Please restart the kernel (Kernel -> Restart)

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 DB2 database and show sample record.

Load data

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/cpd4.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. Action 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

As you can see, the data set contains 486 records.

df_data.select('Business_area').groupBy('Business_area').count().show()
+--------------------+-----+ | Business_area|count| +--------------------+-----+ |Service: Accessib...| 26| |Product: Functioning| 150| | Service: Attitude| 24| |Service: Orders/C...| 32| |Product: Availabi...| 42| |Product: Pricing ...| 24| |Product: Information| 8| | Service: Knowledge| 180| +--------------------+-----+
df_data.select('Action').groupBy('Action').count().show(truncate=False)
+-------------------------+-----+ |Action |count| +-------------------------+-----+ |NA |274 | |Voucher |42 | |Premium features |30 | |On-demand pickup location|56 | |Free Upgrade |84 | +-------------------------+-----+

3. Create an Apache Spark machine learning model

In this section you will learn how to:

3.1 Prepare data for training a model

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

train_data, test_data = df_data.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: 401 Number of testing records : 85

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 OneHotEncoder, StringIndexer, IndexToString, VectorAssembler, HashingTF, IDF, Tokenizer from pyspark.ml.classification import DecisionTreeClassifier from pyspark.ml.evaluation import MulticlassClassificationEvaluator from pyspark.ml import Pipeline, Model

In the following step, use the StringIndexer transformer to convert all the string fields to numeric ones.

string_indexer_gender = StringIndexer(inputCol="Gender", outputCol="gender_ix") string_indexer_customer_status = StringIndexer(inputCol="Customer_Status", outputCol="customer_status_ix") string_indexer_status = StringIndexer(inputCol="Status", outputCol="status_ix") string_indexer_owner = StringIndexer(inputCol="Car_Owner", outputCol="owner_ix") string_business_area = StringIndexer(inputCol="Business_Area", outputCol="area_ix")
assembler = VectorAssembler(inputCols=["gender_ix", "customer_status_ix", "status_ix", "owner_ix", "area_ix", "Children", "Age", "Satisfaction"], outputCol="features")
string_indexer_action = StringIndexer(inputCol="Action", outputCol="label").fit(df_data)
label_action_converter = IndexToString(inputCol="prediction", outputCol="predictedLabel", labels=string_indexer_action.labels)
dt_action = DecisionTreeClassifier()
pipeline_action = Pipeline(stages=[string_indexer_gender, string_indexer_customer_status, string_indexer_status, string_indexer_action, string_indexer_owner, string_business_area, assembler, dt_action, label_action_converter])
model_action = pipeline_action.fit(train_data)
predictions_action = model_action.transform(test_data) predictions_action.select('Business_Area','Action','probability','predictedLabel').show(2)
+--------------------+--------------------+--------------------+--------------------+ | Business_Area| Action| probability| predictedLabel| +--------------------+--------------------+--------------------+--------------------+ |Service: Accessib...| Free Upgrade|[0.0,1.0,0.0,0.0,...| Free Upgrade| | Service: Attitude|On-demand pickup ...|[0.0,0.15625,0.59...|On-demand pickup ...| +--------------------+--------------------+--------------------+--------------------+ only showing top 2 rows
evaluator = MulticlassClassificationEvaluator(labelCol="label", predictionCol="prediction", metricName="accuracy") accuracy = evaluator.evaluate(predictions_action) print("Accuracy = %g" % accuracy)
Accuracy = 0.870588

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

4.2 Save the pipeline and model

saved_model = client.repository.store_model( model=model_action, meta_props={ client.repository.ModelMetaNames.NAME:"CARS4U - Action Recommendation Model", client.repository.ModelMetaNames.TYPE: "mllib_3.2", client.repository.ModelMetaNames.SOFTWARE_SPEC_UID: client.software_specifications.get_id_by_name('spark-mllib_3.2'), client.repository.ModelMetaNames.LABEL_FIELD: "Action", }, training_data=train_data, pipeline=pipeline_action)

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: 6b1e3d04-045f-4202-8743-1bf026f6c502

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': {'hybrid_pipeline_software_specs': [], 'label_column': 'Action', 'pipeline': {'id': '96df067f-33f1-42d0-9c60-ed7390e0ad79'}, 'software_spec': {'id': '5c1b0ca2-4977-5c2e-9439-ffd44ea8ffe9', 'name': 'spark-mllib_3.2'}, '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': 'Gender', 'nullable': True, 'type': 'string'}, {'metadata': {}, 'name': 'Status', 'nullable': True, 'type': 'string'}, {'metadata': {}, 'name': 'Children', 'nullable': True, 'type': 'integer'}, {'metadata': {}, 'name': 'Age', 'nullable': True, 'type': 'double'}, {'metadata': {}, 'name': 'Customer_Status', 'nullable': True, 'type': 'string'}, {'metadata': {}, 'name': 'Car_Owner', 'nullable': True, 'type': 'string'}, {'metadata': {}, 'name': 'Customer_Service', 'nullable': True, 'type': 'string'}, {'metadata': {}, 'name': 'Satisfaction', 'nullable': True, 'type': 'integer'}, {'metadata': {}, 'name': 'Business_Area', 'nullable': True, 'type': 'string'}, {'metadata': {'modeling_role': 'target'}, 'name': 'Action', 'nullable': True, 'type': 'string'}], 'id': '1', 'type': 'struct'}, 'type': 'fs'}], 'type': 'mllib_3.2'}, 'metadata': {'created_at': '2022-02-03T12:49:33.572Z', 'id': '6b1e3d04-045f-4202-8743-1bf026f6c502', 'modified_at': '2022-02-03T12:49:40.224Z', 'name': 'CARS4U - Action Recommendation Model', 'owner': '1000330999', 'resource_key': '2efe70b6-2d55-4fca-84ae-98fb948cacd3', 'space_id': '779349f5-b119-496d-9a2b-3fcd6df73f91'}, 'system': {'warnings': []}}

5. Deploy model in the IBM Cloud

You can use following command to create online deployment in cloud.

deployment_details = client.deployments.create( published_model_id, meta_props={ client.deployments.ConfigurationMetaNames.NAME: "CARS4U - Action Recommendation model deployment", client.deployments.ConfigurationMetaNames.ONLINE: {} } )
####################################################################################### Synchronous deployment creation for uid: '6b1e3d04-045f-4202-8743-1bf026f6c502' started ####################################################################################### initializing Note: online_url is deprecated and will be removed in a future release. Use serving_urls instead. ready ------------------------------------------------------------------------------------------------ Successfully finished deployment creation, deployment_uid='e870ee28-042a-47c2-9d59-57fa1874a658' ------------------------------------------------------------------------------------------------
deployment_details
{'entity': {'asset': {'id': '6b1e3d04-045f-4202-8743-1bf026f6c502'}, 'custom': {}, 'deployed_asset_type': 'model', 'hardware_spec': {'id': 'e7ed1d6c-2e89-42d7-aed5-863b972c1d2b', 'name': 'S', 'num_nodes': 1}, 'name': 'CARS4U - Action Recommendation model deployment', 'online': {}, 'space_id': '779349f5-b119-496d-9a2b-3fcd6df73f91', 'status': {'online_url': {'url': 'https://cpd-zen.apps.ocp46wmlautoaix2.cp.fyre.ibm.com/ml/v4/deployments/e870ee28-042a-47c2-9d59-57fa1874a658/predictions'}, 'serving_urls': ['https://cpd-zen.apps.ocp46wmlautoaix2.cp.fyre.ibm.com/ml/v4/deployments/e870ee28-042a-47c2-9d59-57fa1874a658/predictions'], 'state': 'ready'}}, 'metadata': {'created_at': '2022-02-03T12:55:43.166Z', 'id': 'e870ee28-042a-47c2-9d59-57fa1874a658', 'modified_at': '2022-02-03T12:55:43.166Z', 'name': 'CARS4U - Action Recommendation model deployment', 'owner': '1000330999', 'space_id': '779349f5-b119-496d-9a2b-3fcd6df73f91'}, 'system': {'warnings': [{'id': 'Deprecated', 'message': 'online_url is deprecated and will be removed in a future release. Use serving_urls instead.'}]}}

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", "gender_ix", "customer_status_ix", "status_ix", "label", "owner_ix", "area_ix", "features", "rawPrediction", "probability", "prediction", "predictedLabel" ], "values": [ [ 3785, "Male", "S", 1, 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.0, 1.0, 1.0, 0.0, 1.0, 7.0, [ 0.0, 1.0, 1.0, 1.0, 7.0, 1.0, 17.0, 0.0 ], [ 0.0, 0.0, 6.0, 0.0, 0.0 ], [ 0.0, 0.0, 1.0, 0.0, 0.0 ], 2.0, "On-demand pickup location" ] ] } ] }

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.