References
- Python UDF Reference — detailed description of the entire UDF API
- Running UDFs — detailed description on running Python UDFs
- Example UDFs — example UDFs written in Python
Prerequisites
The general prerequisites for using UDFs in Kinetica can be found under UDF Prerequisites.This example cannot run on Mac OSX
- Python 3
- Miniconda
Visit the Conda website to download
the Miniconda installer for Python 3.
UDF API Download
This example requires local access to the Python UDF API repository. In the desired directory, run the following but be sure to replace<kinetica-version> with the name of the installed Kinetica version, e.g,
v7.2:
Relevant Scripts
There are six files associated with the distributed model UDF example, all of which can be found in the Python UDF API repo.-
A database setup script (
test_environment.py) that is called from the initialization script -
An initialization script (
setup_db.py) that creates input tables and inserts data into them and creates an output ensemble table -
Two scripts to register and execute the UDFs:
- a
register_execute_train.pyscript to register and execute the model training UDF - a
register_execute_test.pyscript to register and execute the prediction model combination UDF
- a
-
Two UDFs to train and test the model:
- a
dt_trainUDF that trains and stores a decision tree model - a
dt_testUDF that combines model predictions into an ensemble
- a
conda_env_py3.yml file found in the
Python UDF API repository.
-
In the same directory you cloned the API, change directory into the root
folder of the Python UDF API repository:
-
Create the Conda environment, replacing
<environment name>with the desired name:It may take a few minutes to create the environment. -
Verify the environment was created properly:
-
Activate the new environment:
-
Install PyGDF:
-
Install the Kinetica Python API:
-
Add the Python UDF API repo’s root directory to the PYTHONPATH:
-
Edit the
util/test_environment.pyscript for the correct database url, user, and password for your Kinetica instance:
UDF Deployment
-
Change directory into the UDF distributed model example directory:
-
Run the UDF initialization script:
-
Run the execute script for the training UDF:
-
Run the execute script for the model combination UDF:
-
Verify the results in GAdmin, either on the
logging page or in the
example_loan_inference_resultoutput table on the table view page.
Execution Detail
This example details two distributed UDFs to train and test model prediction accuracy. The training and testing occurs using the following schema and tables:example_udf_python— the schema containing all of the below tablesexample_loan_train_data— the training table and input table for thedt_trainproc. The algorithm to predict if a loan is bad or not is trained against this table.ensemble_models— the intermediary model storage table that stores all the models after they’ve been trained against the training tableexample_loan_test_data— the testing table and input table for thedt_testproc. The trained algorithm is tested against this table and the accuracy of the algorithm’s predictions are calculated.example_loan_inference_result— the results table and output table for thedt_testproc. The actual bad loan boolean and predicted bad loan boolean are compared per loan in this table.
loan_sample dataset (located in kinetica-udf-api-python/util/):
loan_amnt— a float column representing the loan amountint_rate— a float column representing the loan’s interest rateemp_length— a float column representing the borrower’s employment lengthannual_inc— a float column representing the borrower’s annual incomedti— a float column representing the borrower’s debt-to-income ratiodelinq_2yrs— a float column representing delinquent payments against the loan for the last two yearsrevol_util— a float column representing the borrower’s revolving line utilization ratetotal_acc— a float column representing the borrower’s total amount of accountsbad_loan— a float column representing if the loan was bad (1) or not (0)longest_credit_length— a float column representing the borrower’s longest credit line lengthrecord_id— a float column to identify the loan
record_id— a float column to identify the loanbad_loan_actual— a float column that is thebad_loanvalue from the test tablebad_loan_predicted— a float column that is thebad_loanvalue from the models
dt_train, uses the training table to train
decision tree models, evaluate the models’ accuracy against the
training table, and then store the models in the model storage table in
Kinetica.
The model storage table contains six columns:
model— a bytes column that stores the modelname— an unrestricted string column that is the name of the modelrank— an int column that represents the processing node container that holds the processing nodes for the databasetom— an int column that represents the processing node that contains the many shards of data inside the databasenum_input_data— an int column that is the number of records used as input data for the modeldate_created— a datetime column that is the date and time the model was created
dt_test, combines all the models
in the model storage table and evaluates the combined ensemble accuracy
and predictions against the testing table. The average accuracy of the
individual models and the ensemble are calculated. The predictions vs.
actual values against each loan are then stored in the results table.
Any output to the system log can be viewed in the GAdmin
logging page.
Database Setup
The setup script,setup_db.py, which creates all the necessary tables for
the UDFs, imports the test_environment.py script to access its methods:
test_environment.py:
test_environment.py require a connection to Kinetica.
This is done by instantiating an object of the GPUdb class with a provided
connection URL. See Connecting via API for details on the URL format and
how to look it up.
create_schema() method creates the schema that will contain all tables
used in the example:
prepare_loan_data() method creates the types and tables for the
testing, training, and results tables, but the tables are removed first
if they already exist:
loan_sample data into a pandas data frame. Two
lists are initialized, which will be used to insert records into the training
table and the testing table. A simple counter is initialized as well:
create_ensemble_model_table() method creates the type and table for the
model storage table, but the table is removed first if it already exists:
Model Training UDF (dt_train.py)
First, several packages are imported to access the Kinetica Python UDF API, decision tree modeling, object serialization,test_environment.py methods,
and an accuracy score calculation:
ProcData() class:
example_loan_train_data)—excluding the
records with NaN or null values—is converted to a pandas dataframe. The
number of input records is derived from the dataframe. Let y be the label
with the bad_loan column values; let X be the attributes with
rest of the column values:
X and y:
y (actual
bad_loan values) to the model’s predictions based on the values
in X. The accuracy of the algorithm is then output:
complete() to tell Kinetica the proc code is finished:
Training UDF Registration (register_execute_train.py)
To interact with Kinetica, an object of theGPUdb class is instantiated
while providing the connection URL of the database server.
dt_train.py, kinetica_proc.py, and test_environment.py
files to Kinetica, they will first need to be read in as bytes and added to a
file data map:
distributed_train
proc is created in Kinetica and the files are associated with it:
The proc requires the proper
command and args to be executed. In
this case, the assembled command line would be:Model Testing UDF (dt_test.py)
First, several packages are imported to access the Kinetica Python UDF API, object serialization,test_environment.py methods, an accuracy score
calculation, and numpy math methods:
ProcData() class:
example_loan_test_data)—excluding the
records with NaN or null values—is converted to a pandas dataframe. The
number of input records is derived from the dataframe. Let y_actual
be the label with the bad_loan column values; let X be the attributes
with the rest of the column values. Let record_ids represent the loan IDs:
example_loan_inference_result). Its size is expanded to match the number of
records from the dataframe; this will allocated enough memory to copy all
input records to the output table. Handles are created for the columns that
will be written to: record_id, bad_loan_actual, and
bad_loan_predicted:
0. values equal to the number of input records, and an empty list is
initialized:
load_ensemble_models method from test_environment.py gets the
models, decodes the records, and places them in a list:
bad_loan
values is calculated. The calculated accuracy is added to the accuracies
list, and the prediction value is added to the summed predictions array:
bad_loan
value, and predicted bad_loan value are added as values to the matching
output table columns.
complete() to tell Kinetica the proc code is finished:
Testing UDF Registration (register_execute_test.py)
To interact with Kinetica, an object of theGPUdb class is instantiated
while providing the connection URL of the database server.
dt_test.py, kinetica_proc.py, and test_environment.py
files to Kinetica, they will first need to be read in as bytes and added to a
file data map:
distributed_test
proc is created in Kinetica and the files are associated with it:
The proc requires the proper
command and args to be executed. In
this case, the assembled command line would be: