Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ibm
GitHub Repository: ibm/watson-machine-learning-samples
Path: blob/master/cpd4.0/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-watson-machine-learning

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

  • 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

  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:

  • 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.0' }

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

wml_credentials = { "username": ***, "password": ***, "url": ***, "instance_id": 'openshift', "version": '4.0' }

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'

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/cpd4.0/data/product-line-prediction/GoSales_Tx.csv', out=sample_dir)
100% [......................................................] 2470333 / 2470333
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)
[Row(GENDER='M', AGE=27, MARITAL_STATUS='Single', PROFESSION='Professional', PRODUCT_LINE='Personal Accessories'), Row(GENDER='F', AGE=39, MARITAL_STATUS='Single', PROFESSION='Executive', PRODUCT_LINE='Personal Accessories'), Row(GENDER='M', AGE=39, MARITAL_STATUS='Married', PROFESSION='Student', PRODUCT_LINE='Mountaineering Equipment')]

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

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))
Accuracy = 0.699899 Test Error = 0.300101

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 by using python client libraries.

Note: Apache® Spark 3.0 is required.

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.

saved_model = client.repository.store_model( model=model_rf, meta_props={ client.repository.ModelMetaNames.NAME:'Product Line model', client.repository.ModelMetaNames.TYPE: "mllib_3.0", client.repository.ModelMetaNames.SOFTWARE_SPEC_UID: client.software_specifications.get_id_by_name('spark-mllib_3.0'), client.repository.ModelMetaNames.LABEL_FIELD: "PRODUCT_LINE", }, training_data=train_data, pipeline=pipeline_rf)

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: 3feb28e0-da2a-4ab5-b8c5-4e4f136772ad

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': 'PRODUCT_LINE', 'pipeline': {'id': '3606205f-a904-4de3-86c4-22963eab85d2'}, 'software_spec': {'id': '5c1b0ca2-4977-5c2e-9439-ffd44ea8ffe9', 'name': 'spark-mllib_3.0'}, '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': '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': 'fs'}], 'type': 'mllib_3.0'}, 'metadata': {'created_at': '2022-02-03T12:33:58.484Z', 'id': '3feb28e0-da2a-4ab5-b8c5-4e4f136772ad', 'modified_at': '2022-02-03T12:34:05.694Z', 'name': 'Product Line model', 'owner': '1000330999', 'resource_key': '41ff27cb-e519-44fb-b95b-52a60020a6d2', 'space_id': '779349f5-b119-496d-9a2b-3fcd6df73f91'}, 'system': {'warnings': []}}

4.2: Load model

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

loaded_model = client.repository.load(published_model_id)
print(type(loaded_model))
<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 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.07841678964036... probability | [0.05392083948201... 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.07841678964036... probability | [0.05392083948201... 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 | [12.1288200441685... probability | [0.60644100220842... 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 | [0.99156395369068... probability | [0.04957819768453... 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 | [0.99156395369068... probability | [0.04957819768453... 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| 525| | Golf Equipment| 133| | Outdoor Protection| 33| |Mountaineering Eq...| 225| |Personal Accessories| 256| +--------------------+-----+

6. Deploy and score

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: '3feb28e0-da2a-4ab5-b8c5-4e4f136772ad' 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='d525816b-ff2d-4a91-b3f0-b2329cee0d2d' ------------------------------------------------------------------------------------------------
deployment_details
{'entity': {'asset': {'id': '3feb28e0-da2a-4ab5-b8c5-4e4f136772ad'}, 'custom': {}, 'deployed_asset_type': 'model', 'hardware_spec': {'id': 'e7ed1d6c-2e89-42d7-aed5-863b972c1d2b', 'name': 'S', 'num_nodes': 1}, 'name': 'Product Line 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/d525816b-ff2d-4a91-b3f0-b2329cee0d2d/predictions'}, 'serving_urls': ['https://cpd-zen.apps.ocp46wmlautoaix2.cp.fyre.ibm.com/ml/v4/deployments/d525816b-ff2d-4a91-b3f0-b2329cee0d2d/predictions'], 'state': 'ready'}}, 'metadata': {'created_at': '2022-02-03T12:34:24.012Z', 'id': 'd525816b-ff2d-4a91-b3f0-b2329cee0d2d', 'modified_at': '2022-02-03T12:34:24.012Z', 'name': 'Product Line 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.'}]}}

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