#| include: false knitr::opts_chunk$set( collapse = TRUE, comment = "#>" )
library(tidyclust)
tidyclust provides a unified, tidy interface to clustering models, following the same design patterns as parsnip. It lets you swap clustering algorithms by changing a single line, and integrates seamlessly with the rest of the tidymodels ecosystem (recipes, workflows, tune).
Every tidyclust analysis follows the same four steps:
kmeans_spec <- k_means(num_clusters = 3) |> set_engine("stats") kmeans_spec
set.seed(1234) kmeans_fit <- fit(kmeans_spec, ~., data = mtcars) kmeans_fit
extract_cluster_assignment() returns the cluster label for each training
observation:
extract_cluster_assignment(kmeans_fit)
extract_centroids() returns the location (mean) of each cluster:
extract_centroids(kmeans_fit)
predict() assigns new observations to clusters:
predict(kmeans_fit, new_data = mtcars[1:5, ])
augment() appends the cluster assignment to the original data:
augment(kmeans_fit, new_data = mtcars)
tidyclust provides several cluster quality metrics:
sse_within_total(kmeans_fit, mtcars) sse_ratio(kmeans_fit, mtcars) silhouette_avg(kmeans_fit, mtcars)
Lower sse_within_total() and sse_ratio() indicate tighter clusters.
Higher silhouette_avg() (maximum 1) indicates better-separated clusters.
The same workflow applies to hier_clust(). The number of clusters is cut
from the dendrogram at fit time using num_clusters:
hclust_spec <- hier_clust(num_clusters = 3) |> set_engine("stats") hclust_fit <- fit(hclust_spec, ~., data = mtcars) extract_cluster_assignment(hclust_fit) extract_centroids(hclust_fit)
tidyclust works with the broader tidymodels ecosystem. For example, you can preprocess data with a recipe and bundle it with a model in a workflow:
library(recipes) library(workflows) rec <- recipe(~., data = mtcars) |> step_normalize(all_predictors()) wf <- workflow() |> add_recipe(rec) |> add_model(k_means(num_clusters = 3)) wf_fit <- fit(wf, data = mtcars) augment(wf_fit, new_data = mtcars)
vignette("tuning_and_metrics", package = "tidyclust").vignette("k_means", package = "tidyclust").vignette("hier_clust", package = "tidyclust").Any scripts or data that you put into this service are public.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.