Teradata Package for Python Function Reference | 20.00 - KMeans Clustering - Teradata Package for Python - Look here for syntax, methods and examples for the functions included in the Teradata Package for Python.

Teradata® Package for Python Function Reference - 20.00

Deployment
VantageCloud
VantageCore
Edition
Enterprise
IntelliFlex
VMware
Product
Teradata Package for Python
Release Number
20.00
Published
March 2024
Language
English (United States)
Last Update
2024-04-10
dita:id
TeradataPython_FxRef_Enterprise_2000
Product Category
Teradata Vantage

H2OPredict() using KMeans model.

Setup

In [1]:
import tempfile
import getpass
import teradataml as td
from teradataml import create_context, remove_context, load_example_data, DataFrame, \
db_drop_table, save_byom, retrieve_byom, delete_byom, list_byom
from teradataml.options.configure import configure
from teradataml.analytics.byom.H2OPredict import H2OPredict
import h2o
In [2]:
# Create the connection.
host = getpass.getpass("Host: ")
username = getpass.getpass("Username: ")
password = getpass.getpass("Password: ")

con = create_context(host=host, username=username, password=password)

Load example data and use sample() for splitting input data into testing and training dataset.

In [3]:
load_example_data("byom", "iris_input")
iris_input = DataFrame("iris_input")

# Create 2 samples of input data - sample 1 will have 80% of total rows and sample 2 will have 20% of total rows. 
iris_sample = iris_input.sample(frac=[0.8, 0.2])
In [4]:
# Create train dataset from sample 1 by filtering on "sampleid" and drop "sampleid" column as it is not required for training model.
iris_train = iris_sample[iris_sample.sampleid == "1"].drop("sampleid", axis = 1)
iris_train
Out[4]:
id sepal_length sepal_width petal_length petal_width species
99 5.1 2.5 3.0 1.1 2
120 6.0 2.2 5.0 1.5 3
57 6.3 3.3 4.7 1.6 2
141 6.7 3.1 5.6 2.4 3
139 6.0 3.0 4.8 1.8 3
61 5.0 2.0 3.5 1.0 2
38 4.9 3.6 1.4 0.1 1
78 6.7 3.0 5.0 1.7 2
17 5.4 3.9 1.3 0.4 1
80 5.7 2.6 3.5 1.0 2
In [5]:
# Create test dataset from sample 2 by filtering on "sampleid" and drop "sampleid" column as it is not required for scoring.
iris_test = iris_sample[iris_sample.sampleid == "2"].drop("sampleid", axis = 1)
iris_test
Out[5]:
id sepal_length sepal_width petal_length petal_width species
47 5.1 3.8 1.6 0.2 1
127 6.2 2.8 4.8 1.8 3
62 5.9 3.0 4.2 1.5 2
139 6.0 3.0 4.8 1.8 3
104 6.3 2.9 5.6 1.8 3
38 4.9 3.6 1.4 0.1 1
116 6.4 3.2 5.3 2.3 3
3 4.7 3.2 1.3 0.2 1
51 7.0 3.2 4.7 1.4 2
40 5.1 3.4 1.5 0.2 1

Prepare dataset for creating a KMeans model.

In [6]:
h2o.init()

# Since H2OFrame accepts pandas DataFrame, converting teradataml DataFrame to pandas DataFrame.
iris_train_pd = iris_train.to_pandas()
h2o_df_train = h2o.H2OFrame(iris_train_pd)
h2o_df_train
Checking whether there is an H2O instance running at http://localhost:54321 . connected.
H2O_cluster_uptime: 9 mins 58 secs
H2O_cluster_timezone: America/Los_Angeles
H2O_data_parsing_timezone: UTC
H2O_cluster_version: 3.32.1.6
H2O_cluster_version_age: 1 month and 21 days
H2O_cluster_name: H2O_from_python_gp186005_ip5q0u
H2O_cluster_total_nodes: 1
H2O_cluster_free_memory: 3.998 Gb
H2O_cluster_total_cores: 12
H2O_cluster_allowed_cores: 12
H2O_cluster_status: locked, healthy
H2O_connection_url: http://localhost:54321
H2O_connection_proxy: {"http": null, "https": null}
H2O_internal_security: False
H2O_API_Extensions: Amazon S3, XGBoost, Algos, AutoML, Core V3, TargetEncoder, Core V4
Python_version: 3.7.3 final
Parse progress: |█████████████████████████████████████████████████████████| 100%
sepal_length sepal_width petal_length petal_width species
5 2 3.5 1 2
6.3 3.3 6 2.5 3
5.1 3.4 1.5 0.2 1
6.6 2.9 4.6 1.3 2
4.9 3.6 1.4 0.1 1
6.7 3.1 5.6 2.4 3
6 2.2 5 1.5 3
5.1 2.5 3 1.1 2
6.7 3 5 1.7 2
5.4 3.9 1.3 0.4 1
Out[6]:

In [7]:
# Since H2OFrame accepts pandas DataFrame, converting teradataml DataFrame to pandas DataFrame.
iris_test_pd = iris_test.to_pandas()
h2o_df_test = h2o.H2OFrame(iris_test_pd)
h2o_df_test
Parse progress: |█████████████████████████████████████████████████████████| 100%
sepal_length sepal_width petal_length petal_width species
5 2 3.5 1 2
6 3 4.8 1.8 3
5.7 2.6 3.5 1 2
5.7 2.9 4.2 1.3 2
6.4 2.8 5.6 2.2 3
4.8 3 1.4 0.1 1
6.3 3.3 4.7 1.6 2
6.3 3.4 5.6 2.4 3
4.7 3.2 1.3 0.2 1
5.2 3.5 1.5 0.2 1
Out[7]:

Train KMeans Model.

In [8]:
# Import required libraries.
from h2o.estimators import H2OKMeansEstimator
In [9]:
# Add the code for training model. 
h2o_df_train["species"] = h2o_df_train["species"].asfactor()
predictors = h2o_df_train.columns
response = "species"
In [10]:
iris_kmeans = H2OKMeansEstimator(k=10, estimate_k=True, standardize=False, seed=1234)
In [11]:
iris_kmeans.train(x=predictors, training_frame=h2o_df_train, validation_frame=h2o_df_test)
kmeans Model Build progress: |████████████████████████████████████████████| 100%

Save the model in MOJO format.

In [12]:
# Saving H2O Model to a file.
temp_dir = tempfile.TemporaryDirectory()
model_file_path = iris_kmeans.save_mojo(path=f"{temp_dir.name}", force=True)

Save the model in Vantage.

In [13]:
# Save the H2O Model in Vantage.
save_byom("h2o_kmeans_iris", model_file_path, "byom_models")
Created the model table 'byom_models' as it does not exist.
Model is saved.

List the models from Vantage.

In [14]:
# List the models from "byom_models".
list_byom("byom_models")
                                    model
model_id                                 
h2o_kmeans_iris  b'504B03041400080808...'

Retrieve the model from Vantage.

In [15]:
# Retrieve the model from table "byom_models", using the model id 'h2o_kmeans_iris'.
modeldata = retrieve_byom("h2o_kmeans_iris", "byom_models")

Set "configure.byom_install_location" to the database where BYOM functions are installed.

In [16]:
configure.byom_install_location = getpass.getpass("byom_install_location: ")

Score the model.

In [17]:
result = H2OPredict(newdata=iris_test,
                    newdata_partition_column='id',
                    newdata_order_column='id',
                    modeldata=modeldata,
                    modeldata_order_column='model_id',
                    accumulate=['id', 'sepal_length', 'petal_length'],
                    overwrite_cached_models='*',
                    model_type='OpenSource'
                   )
In [18]:
# Print the query.
print(result.show_query())
SELECT * FROM "mldb".H2OPredict(
	ON "MLDB"."ml__select__16344484461915" AS InputTable
	PARTITION BY "id"
	ORDER BY "id" 
	ON (select model_id,model from "MLDB"."ml__filter__16346196198222") AS ModelTable
	DIMENSION
	ORDER BY "model_id"
	USING
	Accumulate('id','sepal_length','petal_length')
	OverwriteCachedModel('*')
) as sqlmr
In [19]:
# Print the result.
result.result
Out[19]:
id sepal_length petal_length prediction json_report
21 5.4 1.7 0 {"cluster":0}
27 5.0 1.6 0 {"cluster":0}
35 4.9 1.5 0 {"cluster":0}
17 5.4 1.3 0 {"cluster":0}
89 5.6 4.1 1 {"cluster":1}
43 4.4 1.3 0 {"cluster":0}
56 5.7 4.5 1 {"cluster":1}
60 5.2 3.9 1 {"cluster":1}
64 6.1 4.7 1 {"cluster":1}
22 5.1 1.5 0 {"cluster":0}

Cleanup.

In [20]:
# Delete the model from table "byom_models", using the model id 'h2o_kmeans_iris'.
delete_byom("h2o_kmeans_iris", "byom_models")
Model is deleted.
In [21]:
# Drop models table.
db_drop_table("byom_models")
Out[21]:
True
In [22]:
# Drop input data table.
db_drop_table("iris_input")
Out[22]:
True
In [23]:
# One must run remove_context() to close the connection and garbage collect internally generated objects.
remove_context()
Out[23]:
True
In [ ]: