Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ibm
GitHub Repository: ibm/watson-machine-learning-samples
Path: blob/master/cloud/notebooks/python_sdk/deployments/spark/Use Spark to predict product line.ipynb
6405 views
Kernel: Python 3 (ipykernel)

Use Spark to predict product line with ibm-watsonx-ai

This notebook contains steps and code to get data from the IBM Data Science Experience Community, create a predictive model, and start scoring new data. It introduces commands for getting data and for basic data cleaning and exploration, pipeline creation, model training, model persistance to watsonx.ai Runtime 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 publicly available data set, GoSales Transactions, which details anonymous outdoor equipment purchases. Use the details of this data set to predict clients' interests in terms of product line, such as golf accessories, camping equipment, and others.

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 watsonx.ai Runtime repository.

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

  • Score sample scoring data using the watsonx.ai API.

  • Explore and visualize prediction result using the plotly package.

Contents

This notebook contains the following parts:

  1. Setup

  2. Load and explore data

  3. Create spark ml model

  4. Persist model

  5. Predict locally

  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:

Install and import the ibm-watsonx-ai and dependecies

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

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

Connection to watsonx.ai Runtime

Authenticate the watsonx.ai Runtime 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 watsonx.ai Runtime instance can be retrieved in the following way:

ibmcloud login --apikey API_KEY -a https://cloud.ibm.com ibmcloud resource service-instance 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 watsonx.ai Runtime docs. You can check your instance location in your watsonx.ai Runtime 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'
credentials = { "apikey": api_key, "url": 'https://' + location + '.ml.cloud.ibm.com' }
from ibm_watsonx_ai import APIClient client = APIClient(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 Deployment Spaces Dashboard to create one.

  • Click New Deployment Space

  • Create an empty space

  • Select Cloud Object Storage

  • Select watsonx.ai Runtime 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

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 watsonx.ai Runtime, you need to set space which you will be using.

client.set.default_space(space_id)
'SUCCESS'

2. Load and explore data

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

Load the data to the Spark DataFrame by using wget to upload the data to gpfs and then read method.

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

The csv file GoSales_Tx.csv is availble on the same repository where this notebook is located. Load the file to Apache® Spark DataFrame using code below.

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, 'GoSales_Tx.csv') if not os.path.isfile(filename): filename = download('https://github.com/IBM/watson-machine-learning-samples/raw/master/cloud/data/product-line-prediction/GoSales_Tx.csv', out=sample_dir)
spark = SparkSession.builder.getOrCreate() df_data = spark.read\ .format('org.apache.spark.sql.execution.datasources.csv.CSVFileFormat')\ .option('header', 'true')\ .option('inferSchema', 'true')\ .load(filename) df_data.take(3)

Explore the loaded data by using the following Apache® Spark DataFrame methods:

  • print schema

  • print top ten records

  • count all records

df_data.printSchema()
root |-- GENDER: string (nullable = true) |-- AGE: integer (nullable = true) |-- MARITAL_STATUS: string (nullable = true) |-- PROFESSION: string (nullable = true) |-- PRODUCT_LINE: string (nullable = true)

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

df_data.show()
+------+---+--------------+------------+--------------------+ |GENDER|AGE|MARITAL_STATUS| PROFESSION| PRODUCT_LINE| +------+---+--------------+------------+--------------------+ | M| 27| Single|Professional|Personal Accessories| | F| 39| Single| Executive|Personal Accessories| | M| 39| Married| Student|Mountaineering Eq...| | F| 56| Single| Hospitality|Personal Accessories| | M| 45| Married| Retired| Golf Equipment| | M| 45| Married| Retired| Golf Equipment| | M| 39| Married| Student| Camping Equipment| | M| 49| Married| Student| Camping Equipment| | F| 49| Married| Retired| Outdoor Protection| | M| 47| Married| Retired| Golf Equipment| | M| 47| Married| Retired| Golf Equipment| | M| 21| Single| Retail|Mountaineering Eq...| | F| 66| Single| Executive|Personal Accessories| | M| 35| Married|Professional| Camping Equipment| | M| 20| Single| Sales|Mountaineering Eq...| | M| 20| Single| Sales|Mountaineering Eq...| | M| 20| Single| Sales|Mountaineering Eq...| | F| 37| Single| Executive|Personal Accessories| | M| 42| Married| Student| Camping Equipment| | M| 24| Married| Retail| Camping Equipment| +------+---+--------------+------------+--------------------+ only showing top 20 rows
df_data.count()
60252

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

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.

splitted_data = df_data.randomSplit([0.8, 0.18, 0.02], 24) train_data = splitted_data[0] test_data = splitted_data[1] predict_data = splitted_data[2] print("Number of training records: " + str(train_data.count())) print("Number of testing records : " + str(test_data.count())) print("Number of prediction records : " + str(predict_data.count()))
Number of training records: 48237 Number of testing records : 10843 Number of prediction records : 1172

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.

from pyspark.ml.feature import StringIndexer, IndexToString, VectorAssembler from pyspark.ml.classification import RandomForestClassifier from pyspark.ml.evaluation import MulticlassClassificationEvaluator from pyspark.ml import Pipeline

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

stringIndexer_label = StringIndexer(inputCol="PRODUCT_LINE", outputCol="label").fit(df_data) stringIndexer_prof = StringIndexer(inputCol="PROFESSION", outputCol="PROFESSION_IX") stringIndexer_gend = StringIndexer(inputCol="GENDER", outputCol="GENDER_IX") stringIndexer_mar = StringIndexer(inputCol="MARITAL_STATUS", outputCol="MARITAL_STATUS_IX")

In the following step, create a feature vector by combining all features together.

vectorAssembler_features = VectorAssembler(inputCols=["GENDER_IX", "AGE", "MARITAL_STATUS_IX", "PROFESSION_IX"], outputCol="features")

Next, define estimators you want to use for classification. Random Forest is used in the following example.

rf = RandomForestClassifier(labelCol="label", featuresCol="features")

Finally, indexed labels back to original labels.

labelConverter = IndexToString(inputCol="prediction", outputCol="predictedLabel", labels=stringIndexer_label.labels)

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

pipeline_rf = Pipeline(stages=[stringIndexer_label, stringIndexer_prof, stringIndexer_gend, stringIndexer_mar, vectorAssembler_features, rf, labelConverter])

Now, you can train your Random Forest model by using the previously defined pipeline and train data.

train_data.printSchema()
root |-- GENDER: string (nullable = true) |-- AGE: integer (nullable = true) |-- MARITAL_STATUS: string (nullable = true) |-- PROFESSION: string (nullable = true) |-- PRODUCT_LINE: string (nullable = true)
model_rf = pipeline_rf.fit(train_data)

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

predictions = model_rf.transform(test_data) evaluatorRF = MulticlassClassificationEvaluator(labelCol="label", predictionCol="prediction", metricName="accuracy") accuracy = evaluatorRF.evaluate(predictions) print("Accuracy = %g" % accuracy) print("Test Error = %g" % (1.0 - accuracy))
[Stage 42:> (0 + 1) / 1]
Accuracy = 0.681269 Test Error = 0.318731

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 watsonx.ai Runtime repository by 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).

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 intance's dashbord.

service_endpoint = 'https://s3.us.cloud-object-storage.appdomain.cloud'

You also need IBM Cloud authorization endpoint to be able to create COS resource object.

auth_endpoint = 'https://iam.cloud.ibm.com/identity/token'

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

cos = ibm_boto3.resource('s3', ibm_api_key_id=cos_credentials['apikey'], ibm_service_instance_id=cos_credentials['resource_instance_id'], ibm_auth_endpoint=auth_endpoint, config=Config(signature_version='oauth'), endpoint_url=service_endpoint)

Now you will create bucket in COS and copy training dataset for model from GoSales_Tx.csv.csv.

from uuid import uuid4 bucket_id = str(uuid4()) score_filename = "GoSales_Tx.csv.csv" buckets = ["product-line-" + bucket_id]
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 "product-line-2a80a3b0-1767-4edf-85c1-a79cc37ba02e"...
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 GoSales_Tx.csv.csv... GoSales_Tx.csv.csv is uploaded.

Create connections to a COS bucket

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)
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 watsonx.ai Runtime instance.

training_data_references = [ { "id": "product line", "type": "connection_asset", "connection": { "id": connection_id }, "location": { "bucket": buckets[0], "file_name": score_filename, } } ]
saved_model = client.repository.store_model( model=model_rf, meta_props={ client.repository.ModelMetaNames.NAME:'Product Line 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: "PRODUCT_LINE", }, training_data=train_data, pipeline=pipeline_rf)

Get saved model metadata from watsonx.ai Runtime.

published_model_id = client.repository.get_model_id(saved_model) print("Model Id: " + str(published_model_id))
Model Id: e2f7636b-229f-41b6-bda6-721d6420d93c

Model Id can be used to retrive latest model version from watsonx.ai Runtime instance.

Below you can see stored model details.

client.repository.get_model_details(published_model_id)
{'entity': {'hybrid_pipeline_software_specs': [], 'label_column': 'PRODUCT_LINE', 'pipeline': {'id': '089ccf37-9d38-44d3-b6d7-ad0030491c27'}, 'schemas': {'input': [{'fields': [{'metadata': {}, 'name': 'GENDER', 'nullable': True, 'type': 'string'}, {'metadata': {}, 'name': 'AGE', 'nullable': True, 'type': 'integer'}, {'metadata': {}, 'name': 'MARITAL_STATUS', 'nullable': True, 'type': 'string'}, {'metadata': {}, 'name': 'PROFESSION', 'nullable': True, 'type': 'string'}], 'id': '1', 'type': 'struct'}], 'output': []}, 'software_spec': {'id': 'dabb5e1b-e1c7-5ef5-95ea-34a8223e436c', 'name': 'spark-mllib_3.4'}, 'training_data_references': [{'connection': {'id': '39a9bb94-739f-49f8-90af-f2eea1352fc9'}, 'id': 'product line', 'location': {'bucket': 'product-line-2a80a3b0-1767-4edf-85c1-a79cc37ba02e', 'file_name': 'GoSales_Tx.csv.csv'}, 'schema': {'fields': [{'metadata': {}, 'name': 'GENDER', 'nullable': True, 'type': 'string'}, {'metadata': {}, 'name': 'AGE', 'nullable': True, 'type': 'integer'}, {'metadata': {}, 'name': 'MARITAL_STATUS', 'nullable': True, 'type': 'string'}, {'metadata': {}, 'name': 'PROFESSION', 'nullable': True, 'type': 'string'}, {'metadata': {'modeling_role': 'target'}, 'name': 'PRODUCT_LINE', 'nullable': True, 'type': 'string'}], 'id': '1', 'type': 'struct'}, 'type': 'connection_asset'}], 'type': 'mllib_3.4'}, 'metadata': {'created_at': '2024-03-06T13:51:29.390Z', 'id': 'e2f7636b-229f-41b6-bda6-721d6420d93c', 'modified_at': '2024-03-06T13:51:36.640Z', 'name': 'Product Line model', 'owner': 'IBMid-55000091VC', 'resource_key': '02c6424c-f940-45c0-b16d-5907612cc75e', 'space_id': '93ee84d1-b7dd-42b4-b2ca-121bc0c86315'}, 'system': {'warnings': []}}

4.2: Load model

In this subsection you will learn how to load back saved model from specified instance of watsonx.ai Runtime.

loaded_model = client.repository.load(published_model_id)
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 watsonx.ai Runtime repository.

5. Predict locally

In this section you will learn how to score test data using loaded model 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.

predictions = loaded_model.transform(predict_data)

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

predictions.show(5, vertical=True)
-RECORD 0--------------------------------- GENDER | F AGE | 18 MARITAL_STATUS | Single PROFESSION | Retail PRODUCT_LINE | Mountaineering Eq... label | 2.0 PROFESSION_IX | 8.0 GENDER_IX | 1.0 MARITAL_STATUS_IX | 1.0 features | [1.0,18.0,1.0,8.0] rawPrediction | [1.05752493393474... probability | [0.05287624669673... prediction | 1.0 predictedLabel | Personal Accessories -RECORD 1--------------------------------- GENDER | F AGE | 18 MARITAL_STATUS | Single PROFESSION | Retail PRODUCT_LINE | Personal Accessories label | 1.0 PROFESSION_IX | 8.0 GENDER_IX | 1.0 MARITAL_STATUS_IX | 1.0 features | [1.0,18.0,1.0,8.0] rawPrediction | [1.05752493393474... probability | [0.05287624669673... prediction | 1.0 predictedLabel | Personal Accessories -RECORD 2--------------------------------- GENDER | F AGE | 19 MARITAL_STATUS | Married PROFESSION | Student PRODUCT_LINE | Camping Equipment label | 0.0 PROFESSION_IX | 0.0 GENDER_IX | 1.0 MARITAL_STATUS_IX | 0.0 features | [1.0,19.0,0.0,0.0] rawPrediction | [10.0152041708058... probability | [0.50076020854029... prediction | 0.0 predictedLabel | Camping Equipment -RECORD 3--------------------------------- GENDER | F AGE | 19 MARITAL_STATUS | Single PROFESSION | Executive PRODUCT_LINE | Personal Accessories label | 1.0 PROFESSION_IX | 2.0 GENDER_IX | 1.0 MARITAL_STATUS_IX | 1.0 features | [1.0,19.0,1.0,2.0] rawPrediction | [1.05752493393474... probability | [0.05287624669673... prediction | 1.0 predictedLabel | Personal Accessories -RECORD 4--------------------------------- GENDER | F AGE | 19 MARITAL_STATUS | Single PROFESSION | Executive PRODUCT_LINE | Personal Accessories label | 1.0 PROFESSION_IX | 2.0 GENDER_IX | 1.0 MARITAL_STATUS_IX | 1.0 features | [1.0,19.0,1.0,2.0] rawPrediction | [1.05752493393474... probability | [0.05287624669673... prediction | 1.0 predictedLabel | Personal Accessories only showing top 5 rows

By tabulating a count, you can see which product line is the most popular.

predictions.select("predictedLabel").groupBy("predictedLabel").count().show()
+--------------------+-----+ | predictedLabel|count| +--------------------+-----+ | Camping Equipment| 557| | Golf Equipment| 104| | Outdoor Protection| 28| |Mountaineering Eq...| 223| |Personal Accessories| 260| +--------------------+-----+

6. Deploy and score in a Cloud

In this section you will learn how to create online scoring and to score a new data record using ibm-watson-machine-learning.

Note: You can also use REST API to deploy and score. For more information about REST APIs, see the Swagger Documentation.

6.1: Create online scoring endpoint

Now you can create an online scoring endpoint.

Create online deployment for published model

deployment_details = client.deployments.create( published_model_id, meta_props={ client.deployments.ConfigurationMetaNames.NAME: "Product Line model deployment", client.deployments.ConfigurationMetaNames.ONLINE: {} } )
####################################################################################### Synchronous deployment creation for uid: 'e2f7636b-229f-41b6-bda6-721d6420d93c' started ####################################################################################### initializing Note: online_url and serving_urls are deprecated and will be removed in a future release. Use inference instead. ready ------------------------------------------------------------------------------------------------ Successfully finished deployment creation, deployment_uid='e02cc772-4d06-4cfc-a736-6fa594389a0f' ------------------------------------------------------------------------------------------------
deployment_details

Now, you can use above scoring url to make requests from your external application.

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 watsonx.ai Runtime 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 at watsonx.ai

Mateusz Szewczyk, Software Engineer at watsonx.ai

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