Path: blob/master/cpd5.2/notebooks/python_sdk/deployments/spark/Use Spark to predict credit risk.ipynb
6412 views
Use Spark to predict credit risk with ibm-watsonx-ai
This notebook introduces commands for model persistence to watsonx.ai repository, model deployment, and scoring.
Some familiarity with Python is helpful. This notebook uses Python 3.12 and Apache® Spark 3.5 with OpenJDK 17.
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.
Persist a pipeline and model in watsonx.ai repository from tar.gz files.
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:
Install dependencies
Note: ibm-watsonx-ai
documentation can be found here.
Successfully installed wget-3.2
Successfully installed py4j-0.10.9.7 pyspark-3.5.5
Successfully installed anyio-4.9.0 certifi-2025.4.26 charset-normalizer-3.4.2 h11-0.16.0 httpcore-1.0.9 httpx-0.28.1 ibm-cos-sdk-2.14.1 ibm-cos-sdk-core-2.14.1 ibm-cos-sdk-s3transfer-2.14.1 ibm-watsonx-ai-1.3.18 idna-3.10 jmespath-1.0.1 lomond-0.3.3 numpy-2.2.5 pandas-2.2.3 pytz-2025.2 requests-2.32.2 sniffio-1.3.1 tabulate-0.9.0 typing_extensions-4.13.2 tzdata-2025.2 urllib3-2.4.0
Note: If you're encountering ModuleNotFoundError: No module named 'distutils'
exception, install the setuptools
package and try again.
Define credentials
Authenticate the watsonx.ai Runtime service on IBM Cloud Pak for Data. You need to provide the admin's username
and the platform url
.
Use the admin's api_key
to authenticate watsonx.ai Runtime services:
Alternatively you can use the admin's password
:
Create APIClient
instance
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
tabCopy
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
You can use list
method to print all existing spaces.
To be able to interact with all resources available in watsonx.ai, you need to set space which you will be using.
Test Spark
In this section you will load the data as an Apache® Spark DataFrame and perform a basic exploration.
The csv file for German Credit Risk is available on the same repository as this notebook. Load the file to Apache® Spark DataFrame using code below.
Explore the loaded data by using the following Apache® Spark DataFrame methods:
print schema
print top ten records
count all records
As you can see, the data contains 21 fields. Risk field is the one we would like to predict (label).
As you can see, the data set contains 5000 records.
2.1 Prepare data
In this subsection you will split your data into: train, test and predict datasets.
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.
In this section you will learn how to store your pipeline and model in watsonx.ai repository by using Python client libraries.
Note: Apache® Spark 3.5 is required.
3.1: Save pipeline and model
In this subsection you will learn how to save pipeline and model artifacts to your watsonx.ai instance.
Download pipeline and model archives
Store piepline and model
To be able to store your Spark model, you need to provide a training data reference, this will allow to read the model schema automatically.
Get saved model metadata from watsonx.ai.
Tip: Use client.repository.ModelMetaNames.show()
to get the list of available props.
3.2: Load model
In this subsection you will learn how to load back saved model from specified instance of watsonx.ai.
Verify that the model was loaded correctly.
In this section you will learn how to score test data using loaded model.
4.1: Make local prediction using previously loaded model and test data
In this subsection you will score predict_data data set.
Preview the results by calling the show() method on the predictions DataFrame.
By tabulating a count, you can see which product line is the most popular.
In this step, we will create both an online deployment and a batch deployment of Apache® Spark model using ibm-watsonx-ai
. Depending on your use-case, only one deployment out of these two might be necessary. You can learn more about batch deployments here.
Note: You can also use REST API to deploy and score. For more information about REST APIs, see the Swagger Documentation.
5.1: Create online scoring endpoint
Create online deployment for published model
You can retrieve now your online deployment ID
You can also list all deployments in your space
If you want to get additional information on your deployment, you can do it as below
5.2 Create batch scoring endpoint
Create batch deployment for published model
You can retrieve now your batch deployment ID
You can also list all deployments in your space
If you want to get additional information on your deployment, you can do it as below
Prepare scoring payload
5.1 Online deployment scoring
Scoring of online deployments can be performed using the score
method.
Batch deployment scoring
In order to score a model in batch deployment, a job needs to be created.
After submitting your job, you can retrieve its ID
You can also list all jobs in your space.
If you want to get additional information on your job, you can do it as below.
Here you can check status of your batch scoring.
After the job completes, you can retrieve its scoring data
If you want to clean up all created assets:
experiments
trainings
pipelines
model definitions
models
functions
deployments
please follow up this sample notebook.
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 at watsonx.ai
Rafał Chrzanowski, Software Engineer Intern at watsonx.ai.
Copyright © 2020-2025 IBM. This notebook and its source code are released under the terms of the MIT License.