td-kmeans¶
Choose k, fit KMeans in the database, and register the cluster labels as a governed feature.
Source file
Lives at tdfs4ds/skills/td-kmeans/SKILL.md.
name: "Teradata KMeans: clusters as governed features"
description: "Generate Python and SQL to choose k, scale the features, fit teradataml KMeans in the database, and register the cluster labels as a governed tdfs4ds feature that run() can recompute, through a view over the stored scaling and model tables. Invoke when the user wants an unsupervised segmentation of entities or series on numeric features. SKIP for a supervised model or anything trained with tdstone2 (use fs-tdstone2), and for a chart of the clusters alone (use td-plot)."
argument-hint: "[source-table][id-column] [feature-columns]"
allowed-tools: "Read, Edit, Write, Bash, Glob, Grep"
Generate code to cluster entities with teradataml.KMeans, choose k, and register the cluster label as a governed tdfs4ds feature.
User context: $ARGUMENTS
Related skills¶
| Step | Skill | Why |
|---|---|---|
| Before | fs-setup |
Open the session and select the feature store and data domain. |
| Sibling | fs-upload |
What upload_features does, and Stay inside the framework. |
| After | td-plot |
Draw the clusters to check the segmentation. |
| After | fs-document |
Business description of the process. |
Ask for any missing values before generating code: - Source table or view: one row per entity, numeric columns already computed. - ID column: the entity key. - Feature columns to cluster on. - k: a range to explore, or a value already decided. - Names for the scaling table, the model table and the feature view.
Step 1: scale the features¶
KMeans is sensitive to scale.
import teradataml as tdml
import tdfs4ds
tdfs4ds.connect(database='<DATABASE>')
tdfs4ds.select_data_domain('<DATA_DOMAIN>')
data = tdml.DataFrame(tdml.in_schema('<SOURCE_DATABASE>', '<SOURCE_TABLE>'))
features = ['<FEATURE_1>', '<FEATURE_2>']
fit = tdml.ScaleFit(data=data, target_columns=features, scale_method='STD', miss_value='KEEP', global_scale=False)
scaled = tdml.ScaleTransform(data=data, object=fit.output, accumulate='<ID_COLUMN>').result
Step 2: choose k¶
Fit for a few values and read where the within-cluster sum of squares stops falling quickly. The model has one row per cluster.
wcss = {}
for k in [2, 3, 4, 5, 6, 7, 8]:
model = tdml.KMeans(data=scaled, id_column='<ID_COLUMN>', target_columns=features, num_clusters=k, seed=42)
wcss[k] = model.result.to_pandas()['td_withinss_kmeans'].dropna().sum()
print(wcss)
Step 3: fit, and keep the scaling and the model¶
The wrappers' results are temporary objects collected when the session ends, so store the two tables the feature view reads.
k = 3 # <CHOSEN_K>
model = tdml.KMeans(data=scaled, id_column='<ID_COLUMN>', target_columns=features, num_clusters=k, seed=42)
fit.output.to_sql('<SCALE_TABLE>', schema_name='<DATABASE>', if_exists='replace')
model.result.to_sql('<MODEL_TABLE>', schema_name='<DATABASE>', if_exists='replace')
Step 4: register the labels through a view¶
The view scores the source in SQL with the stored tables, so run() recomputes it in any session and scores new entities with the same model.
tdml.execute_sql("""
REPLACE VIEW <DATABASE>.<VIEW_NAME> AS
LOCKING ROW FOR ACCESS
SELECT <ID_COLUMN>, td_clusterid_kmeans
FROM TD_KMeansPredict(
ON (SELECT * FROM TD_ScaleTransform(
ON <SOURCE_DATABASE>.<SOURCE_TABLE> AS InputTable PARTITION BY ANY
ON <DATABASE>.<SCALE_TABLE> AS FitTable DIMENSION
USING Accumulate('<ID_COLUMN>')) s) AS InputTable PARTITION BY ANY
ON <DATABASE>.<MODEL_TABLE> AS ModelTable DIMENSION
USING IdColumn('<ID_COLUMN>')) p
""")
process_id = tdfs4ds.upload_features(
tdml.DataFrame(tdml.in_schema('<DATABASE>', '<VIEW_NAME>')),
entity_id=['<ID_COLUMN>'],
feature_names=['td_clusterid_kmeans'],
return_process_id=True,
)
Refresh it with tdfs4ds.run(process_id). To fit again, repeat Steps 2 and 3: the view reads the new tables.
Rules¶
- Do not use
crystallize_viewon these results.ScaleTransform,KMeansandKMeansPredictresults are tables, so it stops with Error 3854 ("is not a view"), seen with teradataml 20.0.0.10. A view over them would also disappear with the session. tdml.KMeansneedsid_column,target_columns, andnum_clustersunlesscentroids_datais given.KMeansPredict(object=model.result, data=scaled):objecttakes the model's.result, not the model. Its result is<ID_COLUMN>, td_clusterid_kmeans; use it to look at the labels before registering.- A label's number means nothing on its own, and it can change when you fit again. For a readable label, add a
CASE WHEN td_clusterid_kmeans = ... THEN '<LABEL>' ENDcolumn in the view and register it too, so the mapping is governed. - Register only what clustering adds: not a copy of a raw feature.
- The AI steps follow your configuration.
documentandoptimize_querydefault toNone. Seefs-upload. tdnpathviz.plot_elbowis an optional third-party chart (pip install tdnpathviz imageio). Itsscaling=Trueonly applies inside the chart, never to your fit.