### Load Setup Libraries Source: https://tidyclust.tidymodels.org/articles/gm_clust.html Load the necessary tidymodels and clustering libraries. ```R library(workflows) library(parsnip) ``` ```R library(tidyclust) library(tidyverse) library(tidymodels) library(mclust) ``` -------------------------------- ### silhouette_avg examples Source: https://tidyclust.tidymodels.org/reference/silhouette_avg.html Examples demonstrating how to calculate the average silhouette using a fitted kmeans model and a distance matrix. ```R kmeans_spec <- k_means(num_clusters = 5) |> set_engine("stats") kmeans_fit <- fit(kmeans_spec, ~., mtcars) dists <- mtcars |> as.matrix() |> dist() silhouette_avg(kmeans_fit, dists = dists) #> # A tibble: 1 × 3 #> .metric .estimator .estimate #> #> 1 silhouette_avg standard 0.345 silhouette_avg_vec(kmeans_fit, dists = dists) #> [1] 0.3450963 ``` -------------------------------- ### Example usage of bandwidth Source: https://tidyclust.tidymodels.org/reference/bandwidth.html Displays the default configuration of the bandwidth parameter object. ```R bandwidth() #> Bandwidth (quantitative) #> Range: (0.01, 1] ``` -------------------------------- ### reconcile_clusterings_mapping examples Source: https://tidyclust.tidymodels.org/reference/reconcile_clusterings_mapping.html Examples demonstrating default one-to-one mapping and disabling the one-to-one constraint. ```R factor1 <- c("Apple", "Apple", "Carrot", "Carrot", "Banana", "Banana") factor2 <- c("Dog", "Dog", "Cat", "Dog", "Fish", "Fish") reconcile_clusterings_mapping(factor1, factor2) #> # A tibble: 6 × 3 #> primary alt alt_recoded #> #> 1 Apple Dog Carrot #> 2 Apple Dog Carrot #> 3 Carrot Cat Banana #> 4 Carrot Dog Carrot #> 5 Banana Fish Apple #> 6 Banana Fish Apple factor1 <- c("Apple", "Apple", "Carrot", "Carrot", "Banana", "Banana") factor2 <- c("Dog", "Dog", "Cat", "Dog", "Fish", "Parrot") reconcile_clusterings_mapping(factor1, factor2, one_to_one = FALSE) #> # A tibble: 6 × 3 #> primary alt alt_recoded #> #> 1 Apple Dog Apple #> 2 Apple Dog Apple #> 3 Carrot Cat Carrot #> 4 Carrot Dog Apple #> 5 Banana Fish Banana #> 6 Banana Parrot Banana ``` -------------------------------- ### Update k-means cluster specification examples Source: https://tidyclust.tidymodels.org/reference/tidyclust_update.html Examples demonstrating how to update a k-means specification using direct arguments, the fresh argument, and a tibble of parameters. ```R kmeans_spec <- k_means(num_clusters = 5) kmeans_spec #> K Means Cluster Specification (partition) #> #> Main Arguments: #> num_clusters = 5 #> #> Computational engine: stats #> update(kmeans_spec, num_clusters = 1) #> K Means Cluster Specification (partition) #> #> Main Arguments: #> num_clusters = 1 #> #> Computational engine: stats #> update(kmeans_spec, num_clusters = 1, fresh = TRUE) #> K Means Cluster Specification (partition) #> #> Main Arguments: #> num_clusters = 1 #> #> Computational engine: stats #> param_values <- tibble::tibble(num_clusters = 10) kmeans_spec |> update(param_values) #> K Means Cluster Specification (partition) #> #> Main Arguments: #> num_clusters = 10 #> #> Computational engine: stats #> ``` -------------------------------- ### Examples of tidy() with cluster_fit Source: https://tidyclust.tidymodels.org/reference/tidy.cluster_fit.html Examples showing how to use tidy() with k-means and hierarchical clustering models. Note that support depends on the underlying engine and may require the broom package. ```R # tidy() support depends on the underlying engine. For the stats engine, # broom must be installed. if (FALSE) { # \dontrun{ kmeans_fit <- k_means(num_clusters = 3) |> set_engine("stats") |> fit(~., mtcars) tidy(kmeans_fit) hclust_fit <- hier_clust(num_clusters = 3) |> set_engine("stats") |> fit(~., mtcars) tidy(hclust_fit) } # } ``` -------------------------------- ### Getting started with tidyclust Source: https://tidyclust.tidymodels.org/reference/tidyclust-package.html Demonstrates the basic workflow of creating a model specification, fitting it to data, and extracting results. ```R # Create a specification spec <- k_means(num_clusters = 3) # Fit to data fit <- fit(spec, ~., data = mtcars) # Extract results extract_centroids(fit) extract_cluster_assignment(fit) ``` -------------------------------- ### Install tidyclust Source: https://tidyclust.tidymodels.org/index.html Use the pak package to install the tidyclust development version from GitHub. ```R pak::pak("tidymodels/tidyclust") ``` -------------------------------- ### Examples of control_cluster configuration Source: https://tidyclust.tidymodels.org/reference/control_cluster.html Demonstrates various configurations for control_cluster, including error catching and different verbosity levels. ```R control_cluster() #> tidyclust control object # Catch errors instead of stopping — useful inside loops or tune_cluster() control_cluster(catch = TRUE) #> tidyclust control object #> - fit errors will be caught # Suppress all output during fitting control_cluster(verbosity = 0L) #> tidyclust control object # Show model output but suppress package loading messages (default) control_cluster(verbosity = 1L) #> tidyclust control object # Show all output including package loading messages control_cluster(verbosity = 2L) #> tidyclust control object #> - verbose level 2 ``` -------------------------------- ### Example usage of radius Source: https://tidyclust.tidymodels.org/reference/radius.html Displays the default configuration of the radius parameter object. ```R radius() #> Radius (quantitative) #> Range: (0, ?] ``` -------------------------------- ### Load Required Libraries Source: https://tidyclust.tidymodels.org/articles/hier_clust.html Initial setup to load the necessary packages for workflow management and model specification. ```R library(workflows) library(parsnip) ``` -------------------------------- ### Examples of Gaussian mixture covariance parameters Source: https://tidyclust.tidymodels.org/reference/gm_clust_params.html Examples showing the output of calling the covariance structure parameter functions. ```R circular() #> Circular MVG (qualitative) #> 2 possible values include: #> TRUE and FALSE zero_covariance() #> Zero Covariance (qualitative) #> 2 possible values include: #> TRUE and FALSE shared_orientation() #> Shared Orientation (qualitative) #> 2 possible values include: #> TRUE and FALSE shared_shape() #> Shared Shape (qualitative) #> 2 possible values include: #> TRUE and FALSE shared_size() #> Shared Size (qualitative) #> 2 possible values include: #> TRUE and FALSE ``` -------------------------------- ### gm_clust usage examples Source: https://tidyclust.tidymodels.org/reference/gm_clust.html Demonstrates how to retrieve available engines for the gm_clust model and how to initialize the model specification. ```R # Show all engines modelenv::get_from_env("gm_clust") #> # A tibble: 1 × 2 #> engine mode #> #> 1 mclust partition gm_clust() #> GMM Clustering Specification (partition) #> #> Main Arguments: #> circular = TRUE #> zero_covariance = TRUE #> shared_orientation = TRUE #> shared_shape = TRUE #> shared_size = TRUE #> #> Computational engine: mclust #> ``` -------------------------------- ### Example usage of min_points Source: https://tidyclust.tidymodels.org/reference/min_points.html Displays the default range for the min_points parameter. ```R min_points() #> Minimum Number of Points (quantitative) #> Range: [2, 20] ``` -------------------------------- ### Calculate SSE within clusters example Source: https://tidyclust.tidymodels.org/reference/sse_within.html An example demonstrating how to fit a k-means model using the stats engine and calculate the SSE within each cluster. ```R kmeans_spec <- k_means(num_clusters = 5) |> set_engine("stats") kmeans_fit <- fit(kmeans_spec, ~., mtcars) sse_within(kmeans_fit) #> # A tibble: 5 × 3 #> .cluster wss n_members #> #> 1 Cluster_1 7256. 6 #> 2 Cluster_2 3617. 7 #> 3 Cluster_3 6356. 6 #> 4 Cluster_4 46659. 9 #> 5 Cluster_5 208. 4 ``` -------------------------------- ### Install tidyclust from CRAN Source: https://tidyclust.tidymodels.org/index.html Use this command to install the stable release of the tidyclust package from CRAN. ```R install.packages("tidyclust") ``` -------------------------------- ### Load required libraries Source: https://tidyclust.tidymodels.org/articles/k_means.html Initial setup to load the necessary packages for workflow management, model specification, and data manipulation. ```R library(workflows) library(parsnip) ``` ```R library(tidyclust) library(tidyverse) library(tidymodels) ``` -------------------------------- ### Example usage of cut_height Source: https://tidyclust.tidymodels.org/reference/cut_height.html Displays the default output of the cut_height function. ```R cut_height() #> Cut Height (quantitative) #> Range: [0, ?] ``` -------------------------------- ### Examples of linkage_method Source: https://tidyclust.tidymodels.org/reference/linkage_method.html Displays the available linkage methods and the output of the linkage_method() function. ```R values_linkage_method #> [1] "ward.D" "ward.D2" "single" "complete" "average" "mcquitty" #> [7] "median" "centroid" linkage_method() #> Linkage Method (qualitative) #> 8 possible values include: #> 'ward.D', 'ward.D2', 'single', 'complete', 'average', 'mcquitty', #> 'median', and 'centroid' ``` -------------------------------- ### Fit a k-means model using formula and x interfaces Source: https://tidyclust.tidymodels.org/reference/fit.html Demonstrates training a k-means model with 5 clusters using both the formula interface with fit() and the matrix interface with fit_xy(). Both examples utilize the stats engine. ```R library(dplyr) kmeans_mod <- k_means(num_clusters = 5) using_formula <- kmeans_mod |> set_engine("stats") |> fit(~., data = mtcars) using_x <- kmeans_mod |> set_engine("stats") |> fit_xy(x = mtcars) ``` -------------------------------- ### Example of calculating silhouette Source: https://tidyclust.tidymodels.org/reference/silhouette.html Demonstrates fitting a k-means model and calculating silhouette widths using a distance matrix. ```R kmeans_spec <- k_means(num_clusters = 5) |> set_engine("stats") kmeans_fit <- fit(kmeans_spec, ~., mtcars) dists <- mtcars |> as.matrix() |> dist() silhouette(kmeans_fit, dists = dists) #> # A tibble: 32 × 3 #> cluster neighbor sil_width #> #> 1 Cluster_1 Cluster_2 0.572 #> 2 Cluster_1 Cluster_2 0.572 #> 3 Cluster_1 Cluster_2 0.752 #> 4 Cluster_2 Cluster_1 0.540 #> 5 Cluster_3 Cluster_4 0.149 #> 6 Cluster_2 Cluster_1 0.224 #> 7 Cluster_3 Cluster_4 0.649 #> 8 Cluster_1 Cluster_2 0.613 #> 9 Cluster_1 Cluster_2 0.692 #> 10 Cluster_1 Cluster_2 0.460 #> # ℹ 22 more rows ``` -------------------------------- ### Example of glance with k-means Source: https://tidyclust.tidymodels.org/reference/glance.cluster_fit.html Demonstrates how to use glance on a fitted k-means model. Note that support depends on the underlying engine. ```R # glance() support depends on the underlying engine. if (FALSE) { # \dontrun{ kmeans_fit <- k_means(num_clusters = 3) |> set_engine("stats") |> fit(~., mtcars) glance(kmeans_fit) } # } ``` -------------------------------- ### Example usage of sse_ratio and sse_ratio_vec Source: https://tidyclust.tidymodels.org/reference/sse_ratio.html Demonstrates calculating the SSE ratio using a fitted k-means model on the mtcars dataset. ```R kmeans_spec <- k_means(num_clusters = 5) |> set_engine("stats") kmeans_fit <- fit(kmeans_spec, ~., mtcars) sse_ratio(kmeans_fit) #> # A tibble: 1 × 3 #> .metric .estimator .estimate #> #> 1 sse_ratio standard 0.0687 sse_ratio_vec(kmeans_fit) #> [1] 0.06873637 ``` -------------------------------- ### Example of axing a cluster_fit object Source: https://tidyclust.tidymodels.org/reference/axe-cluster_fit.html Demonstrates creating a k-means model using tidyclust and applying the butcher function to reduce its size. ```R k_fit <- k_means(num_clusters = 3) |> parsnip::set_engine("stats") |> fit(~., data = mtcars) butcher::butcher(k_fit) #> tidyclust cluster object #> #> K-means clustering with 3 clusters of sizes 7, 11, 14 #> #> Cluster means: #> mpg cyl disp hp drat wt qsec vs #> 1 19.74286 6 183.3143 122.28571 3.585714 3.117143 17.97714 0.5714286 #> 2 26.66364 4 105.1364 82.63636 4.070909 2.285727 19.13727 0.9090909 #> 3 15.10000 8 353.1000 209.21429 3.229286 3.999214 16.77214 0.0000000 #> am gear carb #> 1 0.4285714 3.857143 3.428571 #> 2 0.7272727 4.090909 1.545455 #> 3 0.1428571 3.285714 3.500000 #> #> Clustering vector: #> integer(0) #> #> Within cluster sum of squares by cluster: #> [1] 13954.34 11848.37 93643.90 #> (between_SS / total_SS = 80.8 %) #> #> Available components: #> #> [1] "cluster" "centers" "totss" "withinss" #> [5] "tot.withinss" "betweenss" "size" "iter" #> [9] "ifault" ``` -------------------------------- ### Create and fit a tidymodels workflow with tidyclust Source: https://tidyclust.tidymodels.org/articles/tidyclust.html This example shows how to define a recipe for data normalization, add it to a workflow with a k-means model, and fit the workflow to the mtcars dataset. ```r library(recipes) #> Loading required package: dplyr #> #> Attaching package: 'dplyr' #> The following objects are masked from 'package:stats': #> #> filter, lag #> The following objects are masked from 'package:base': #> #> intersect, setdiff, setequal, union #> #> Attaching package: 'recipes' #> The following object is masked from 'package:stats': #> #> step 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) #> # A tibble: 32 × 12 #> .pred_cluster mpg cyl disp hp drat wt qsec vs am #> * #> 1 Cluster_1 21 6 160 110 3.9 2.62 16.5 0 1 #> 2 Cluster_1 21 6 160 110 3.9 2.88 17.0 0 1 #> 3 Cluster_1 22.8 4 108 93 3.85 2.32 18.6 1 1 #> 4 Cluster_2 21.4 6 258 110 3.08 3.22 19.4 1 0 #> 5 Cluster_3 18.7 8 360 175 3.15 3.44 17.0 0 0 #> 6 Cluster_2 18.1 6 225 105 2.76 3.46 20.2 1 0 #> 7 Cluster_3 14.3 8 360 245 3.21 3.57 15.8 0 0 #> 8 Cluster_2 24.4 4 147. 62 3.69 3.19 20 1 0 #> 9 Cluster_2 22.8 4 141. 95 3.92 3.15 22.9 1 0 #> 10 Cluster_2 19.2 6 168. 123 3.92 3.44 18.3 1 0 #> # ℹ 22 more rows #> # ℹ 2 more variables: gear , carb ``` -------------------------------- ### Extracting summary from a k-means model Source: https://tidyclust.tidymodels.org/reference/extract_fit_summary.html Example demonstrating how to fit a k-means model using the stats engine and extract its summary information. ```R kmeans_spec <- k_means(num_clusters = 5) |> set_engine("stats") kmeans_fit <- fit(kmeans_spec, ~., mtcars) kmeans_fit |> extract_fit_summary() #> $cluster_names #> [1] Cluster_1 Cluster_2 Cluster_3 Cluster_4 Cluster_5 #> Levels: Cluster_1 Cluster_2 Cluster_3 Cluster_4 Cluster_5 #> #> $centroids #> # A tibble: 5 × 11 #> mpg cyl disp hp drat wt qsec vs am gear carb #> #> 1 24.5 4.62 122. 96.9 4.00 2.52 18.5 0.75 0.688 4.12 2.44 #> 2 19.8 6 242. 108. 2.92 3.34 19.8 1 0 3 1 #> 3 16.4 8 302. 169. 3.04 3.66 17.4 0 0 3 2.5 #> 4 14.6 8 340. 272. 3.68 3.54 15.1 0 0.5 4 5 #> 5 13.7 8 443 206. 3.06 4.97 17.6 0 0 3 3.5 #> #> $n_members #> [1] 16 2 6 4 4 #> #> $sse_within_total_total #> [1] 32837.9972 562.8304 6815.5541 7654.1463 4665.0415 #> #> $sse_total #> [1] 623387.5 #> #> $orig_labels #> [1] 1 1 1 2 3 2 4 1 1 1 1 3 3 3 5 5 5 1 1 1 1 3 3 4 5 1 1 1 4 1 4 1 #> #> $cluster_assignments #> [1] Cluster_1 Cluster_1 Cluster_1 Cluster_2 Cluster_3 Cluster_2 #> [7] Cluster_4 Cluster_1 Cluster_1 Cluster_1 Cluster_1 Cluster_3 #> [13] Cluster_3 Cluster_3 Cluster_5 Cluster_5 Cluster_5 Cluster_1 #> [19] Cluster_1 Cluster_1 Cluster_1 Cluster_3 Cluster_3 Cluster_4 #> [25] Cluster_5 Cluster_1 Cluster_1 Cluster_1 Cluster_4 Cluster_1 #> [31] Cluster_4 Cluster_1 #> Levels: Cluster_1 Cluster_2 Cluster_3 Cluster_4 Cluster_5 ``` -------------------------------- ### DBSCAN engine and specification examples Source: https://tidyclust.tidymodels.org/reference/db_clust.html Retrieves available engines for db_clust and displays a default model specification. ```R # Show all engines modelenv::get_from_env("db_clust") #> # A tibble: 2 × 2 #> engine mode #> #> 1 dbscan partition #> 2 hdbscan partition db_clust() #> DBSCAN Clustering Specification (partition) #> #> Computational engine: dbscan #> ``` -------------------------------- ### Translate k_means to ClusterR engine Source: https://tidyclust.tidymodels.org/reference/details_k_means_ClusterR.html This example demonstrates how to define a K-means model specification, set the engine to ClusterR, and translate it to the underlying package format. ```R k_means(num_clusters = integer(1)) |> set_engine("ClusterR") |> set_mode("partition") |> translate_tidyclust() ``` ```R ## K Means Cluster Specification (partition) ## ## Main Arguments: ## num_clusters = integer(1) ## ## Computational engine: ClusterR ## ## Model fit template: ## tidyclust::.k_means_fit_ClusterR(data = missing_arg(), clusters = missing_arg(), ## clusters = integer(1)) ``` -------------------------------- ### Mean Shift Engine and Specification Examples Source: https://tidyclust.tidymodels.org/reference/mean_shift.html Retrieving available engines for the mean_shift model and creating a default model specification. ```R # Show all engines modelenv::get_from_env("mean_shift") #> # A tibble: 2 × 2 #> engine mode #> #> 1 LPCM partition #> 2 meanShiftR partition mean_shift() #> Mean Shift Clustering Specification (partition) #> #> Computational engine: LPCM #> ``` -------------------------------- ### Translate tidyclust GMM specification to mclust Source: https://tidyclust.tidymodels.org/reference/details_gm_clust_mclust.html This example demonstrates how to define a GMM clustering model with specific parameters and translate it to the mclust engine. ```R gm_clust(num_clusters = 3, circular = FALSE, zero_covariance = FALSE) %>% set_engine("mclust") %>% set_mode("partition") %>% translate_tidyclust() ``` ```R ## GMM Clustering Specification (partition) ## ## Main Arguments: ## num_clusters = 3 ## circular = FALSE ## zero_covariance = FALSE ## shared_orientation = TRUE ## shared_shape = TRUE ## shared_size = TRUE ## ## Computational engine: mclust ## ## Model fit template: ## tidyclust::.gm_clust_fit_mclust(x = missing_arg(), num_clusters = missing_arg(), ## circular = missing_arg(), zero_covariance = missing_arg(), ## shared_orientation = missing_arg(), shared_shape = missing_arg(), ## shared_size = missing_arg(), num_clusters = 3, circular = FALSE, ## zero_covariance = FALSE, shared_orientation = TRUE, shared_shape = TRUE, ## shared_size = TRUE) ``` -------------------------------- ### Calculate total sum of squares example Source: https://tidyclust.tidymodels.org/reference/sse_total.html Demonstrates fitting a k-means model and calculating the total sum of squares using both sse_total and sse_total_vec. ```R kmeans_spec <- k_means(num_clusters = 5) |> set_engine("stats") kmeans_fit <- fit(kmeans_spec, ~., mtcars) sse_total(kmeans_fit) #> # A tibble: 1 × 3 #> .metric .estimator .estimate #> #> 1 sse_total standard 623387. sse_total_vec(kmeans_fit) #> [1] 623387.5 ``` -------------------------------- ### Augmenting data with a k-means model Source: https://tidyclust.tidymodels.org/reference/augment.html This example demonstrates fitting a k-means model using the stats engine and appending cluster predictions to the mtcars dataset. ```R kmeans_spec <- k_means(num_clusters = 5) |> set_engine("stats") kmeans_fit <- fit(kmeans_spec, ~., mtcars) kmeans_fit |> augment(new_data = mtcars) ``` -------------------------------- ### Set global contrasts option Source: https://tidyclust.tidymodels.org/reference/fit.html Example of setting the global contrasts option to use Helmert contrasts for unordered factors. ```R options(contrasts = c(unordered = "contr.helmert", ordered = "contr.poly")) ``` -------------------------------- ### fit() with formula interface Source: https://tidyclust.tidymodels.org/reference/fit.html Fits a cluster specification using the formula interface. The example uses a k-means model with 5 clusters and the stats engine. ```APIDOC ## fit() with formula interface ### Description Fits a cluster specification using the formula interface. ### Method fit ### Usage fit(object, formula, data, ...) ### Parameters - **object** (cluster_spec) - Required - A cluster specification object. - **formula** (formula) - Required - A formula specifying the model terms. - **data** (data.frame) - Required - The data to fit the model on. - **...** - Optional - Additional arguments passed to the underlying engine. ### Request Example ```r library(dplyr) kmeans_mod <- k_means(num_clusters = 5) using_formula <- kmeans_mod |> set_engine("stats") |> fit(~., data = mtcars) ``` ### Response Returns a fitted cluster model object. ``` -------------------------------- ### Extracting centroids from a k-means model Source: https://tidyclust.tidymodels.org/reference/extract_centroids.html Example showing how to fit a k-means model and extract its centroids, including an option to override default cluster labels. ```R set.seed(1234) kmeans_spec <- k_means(num_clusters = 5) |> set_engine("stats") kmeans_fit <- fit(kmeans_spec, ~., mtcars) kmeans_fit |> extract_centroids() ``` ```R kmeans_fit |> extract_centroids(labels = c("A", "B", "C", "D", "E")) ``` -------------------------------- ### Complete clustering tuning workflow Source: https://tidyclust.tidymodels.org/reference/tune_cluster.html Demonstrates the full process of defining a recipe and model, creating a workflow, setting up cross-validation folds, tuning the model, and collecting metrics. ```r library(recipes) library(rsample) library(workflows) library(tune) rec_spec <- recipe(~., data = mtcars) |> step_normalize(all_numeric_predictors()) |> step_pca(all_numeric_predictors()) kmeans_spec <- k_means(num_clusters = tune()) wflow <- workflow() |> add_recipe(rec_spec) |> add_model(kmeans_spec) grid <- tibble(num_clusters = 1:3) set.seed(4400) folds <- vfold_cv(mtcars, v = 2) res <- tune_cluster( wflow, resamples = folds, grid = grid ) res #> # Tuning results #> # 2-fold cross-validation #> # A tibble: 2 × 4 #> splits id .metrics .notes #> #> 1 Fold1 #> 2 Fold2 collect_metrics(res) #> # A tibble: 6 × 7 #> num_clusters .metric .estimator mean n std_err .config #> #> 1 1 sse_total standard 167. 2 7.78 pre0_mo… #> 2 1 sse_within_total standard 167. 2 7.78 pre0_mo… #> 3 2 sse_total standard 167. 2 7.78 pre0_mo… #> 4 2 sse_within_total standard 82.2 2 5.76 pre0_mo… #> 5 3 sse_total standard 167. 2 7.78 pre0_mo… #> 6 3 sse_within_total standard 71.5 2 2.59 pre0_mo… ``` -------------------------------- ### Retrieve and initialize k_means model Source: https://tidyclust.tidymodels.org/reference/k_means.html Demonstrates how to list available engines for the k_means model and initialize the model with default settings. ```R # Show all engines modelenv::get_from_env("k_means") #> # A tibble: 4 × 2 #> engine mode #> #> 1 stats partition #> 2 ClusterR partition #> 3 clustMixType partition #> 4 klaR partition k_means() #> K Means Cluster Specification (partition) #> #> Computational engine: stats #> ``` -------------------------------- ### tunable.cluster_spec Source: https://tidyclust.tidymodels.org/reference/tunable.cluster_spec.html S3 method for class 'cluster_spec' to get tunable parameters for a cluster specification. ```APIDOC ## tunable.cluster_spec ### Description Get tunable parameters for a cluster specification. ### Usage ```r # S3 method for class 'cluster_spec' tunable(x, ...) ``` ### Arguments - **x** (object) - Required - An object, such as a recipe, recipe step, workflow, or model specification. - **...** (other arguments) - Optional - Other arguments passed to methods. ### Value A tibble with columns `name`, `call_info`, `source`, `component`, and `component_id` describing each tunable parameter. ``` -------------------------------- ### tunable.db_clust Source: https://tidyclust.tidymodels.org/reference/tunable.cluster_spec.html S3 method for class 'db_clust' to get tunable parameters for a density-based clustering specification. ```APIDOC ## tunable.db_clust ### Description Get tunable parameters for a density-based clustering specification. ### Usage ```r # S3 method for class 'db_clust' tunable(x, ...) ``` ### Arguments - **x** (object) - Required - An object, such as a recipe, recipe step, workflow, or model specification. - **...** (other arguments) - Optional - Other arguments passed to methods. ### Value A tibble with columns `name`, `call_info`, `source`, `component`, and `component_id` describing each tunable parameter. ``` -------------------------------- ### tunable.k_means Source: https://tidyclust.tidymodels.org/reference/tunable.cluster_spec.html S3 method for class 'k_means' to get tunable parameters for a k-means clustering specification. ```APIDOC ## tunable.k_means ### Description Get tunable parameters for a k-means clustering specification. ### Usage ```r # S3 method for class 'k_means' tunable(x, ...) ``` ### Arguments - **x** (object) - Required - An object, such as a recipe, recipe step, workflow, or model specification. - **...** (other arguments) - Optional - Other arguments passed to methods. ### Value A tibble with columns `name`, `call_info`, `source`, `component`, and `component_id` describing each tunable parameter. ``` -------------------------------- ### tunable.hier_clust Source: https://tidyclust.tidymodels.org/reference/tunable.cluster_spec.html S3 method for class 'hier_clust' to get tunable parameters for a hierarchical clustering specification. ```APIDOC ## tunable.hier_clust ### Description Get tunable parameters for a hierarchical clustering specification. ### Usage ```r # S3 method for class 'hier_clust' tunable(x, ...) ``` ### Arguments - **x** (object) - Required - An object, such as a recipe, recipe step, workflow, or model specification. - **...** (other arguments) - Optional - Other arguments passed to methods. ### Value A tibble with columns `name`, `call_info`, `source`, `component`, and `component_id` describing each tunable parameter. ``` -------------------------------- ### tunable.gm_clust Source: https://tidyclust.tidymodels.org/reference/tunable.cluster_spec.html S3 method for class 'gm_clust' to get tunable parameters for a Gaussian model clustering specification. ```APIDOC ## tunable.gm_clust ### Description Get tunable parameters for a Gaussian model clustering specification. ### Usage ```r # S3 method for class 'gm_clust' tunable(x, ...) ``` ### Arguments - **x** (object) - Required - An object, such as a recipe, recipe step, workflow, or model specification. - **...** (other arguments) - Optional - Other arguments passed to methods. ### Value A tibble with columns `name`, `call_info`, `source`, `component`, and `component_id` describing each tunable parameter. ``` -------------------------------- ### Incorrect prediction workflow Source: https://tidyclust.tidymodels.org/reference/extract-tidyclust.html An example of an incorrect workflow that bypasses tidyclust preprocessing by predicting directly on the extracted engine fit. ```R tidyclust_fit |> extract_fit_engine() |> predict(new_data) ``` -------------------------------- ### .k_means_fit_ClusterR(data, clusters, num_init, max_iters, initializer, fuzzy, verbose, CENTROIDS, tol, tol_optimal_init, seed) Source: https://tidyclust.tidymodels.org/reference/dot-k_means_fit_ClusterR.html Runs k-means clustering using ClusterR::KMeans_rcpp() and adds column names to the centroids field and reorders the clusters. Returns a list with clustering results. ```APIDOC ## .k_means_fit_ClusterR ### Description Runs k-means clustering using ClusterR::KMeans_rcpp() and adds column names to the centroids field and reorders the clusters. ### Usage .k_means_fit_ClusterR( data, clusters, num_init = 1, max_iters = 100, initializer = "kmeans++", fuzzy = FALSE, verbose = FALSE, CENTROIDS = NULL, tol = 1e-04, tol_optimal_init = 0.3, seed = 1 ) ### Arguments - **data** (matrix or data frame) - Required - The input data for clustering. - **clusters** (numeric) - Required - The number of clusters. - **num_init** (numeric) - Optional - Number of times the algorithm will be run with different centroid seeds. Default: 1. - **max_iters** (numeric) - Optional - The maximum number of clustering iterations. Default: 100. - **initializer** (character) - Optional - The method of initialization. One of: optimal_init, quantile_init, kmeans++ and random. Default: "kmeans++". - **fuzzy** (logical) - Optional - If TRUE, prediction probabilities will be calculated using the distance between observations and centroids. Default: FALSE. - **verbose** (logical) - Optional - If TRUE, progress is printed during clustering. Default: FALSE. - **CENTROIDS** (matrix) - Optional - A matrix of initial cluster centroids. The rows should equal the number of clusters and the columns should equal the columns of the data. Default: NULL. - **tol** (numeric) - Optional - A float number. If, in case of an iteration (iteration > 1 and iteration < max_iters) 'tol' is greater than the squared norm of the centroids, then kmeans has converged. Default: 1e-04. - **tol_optimal_init** (numeric) - Optional - Tolerance value for the 'optimal_init' initializer. The higher this value is, the far appart from each other the centroids are. Default: 0.3. - **seed** (integer) - Optional - Integer value for random number generator (RNG). Default: 1. ### Value A list with the following attributes: clusters, fuzzy_clusters (if fuzzy = TRUE), centroids, total_SSE, best_initialization, WCSS_per_cluster, obs_per_cluster, between.SS_DIV_total.SS. ``` -------------------------------- ### Using tidymodels workflows with tidyclust Source: https://tidyclust.tidymodels.org/articles/k_means.html Shows how to create workflows with different recipes, including one with log-scaling, and extract centroids from the fitted models. ```r penguins_recipe_1 <- recipe(~ bill_length_mm + bill_depth_mm, data = penguins ) penguins_recipe_2 <- recipe(~ bill_length_mm + bill_depth_mm, data = penguins ) |> step_log(all_numeric_predictors()) wflow_1 <- workflow() |> add_model(kmeans_spec) |> add_recipe(penguins_recipe_1) wflow_2 <- workflow() |> add_model(kmeans_spec) |> add_recipe(penguins_recipe_2) wflow_1 |> fit(penguins) |> extract_centroids() #> # A tibble: 3 × 3 #> .cluster bill_length_mm bill_depth_mm #> #> 1 Cluster_1 38.4 18.3 #> 2 Cluster_2 45.5 15.6 #> 3 Cluster_3 50.9 17.3 wflow_2 |> fit(penguins) |> extract_centroids() #> # A tibble: 3 × 3 #> .cluster bill_length_mm bill_depth_mm #> #> 1 Cluster_1 3.65 2.90 #> 2 Cluster_2 3.90 2.92 #> 3 Cluster_3 3.85 2.70 ``` -------------------------------- ### Author a custom clustering metric Source: https://tidyclust.tidymodels.org/reference/new_cluster_metric.html Example of creating a custom metric using a non-default distance function and combining it into a metric set. ```R # Author a custom metric that uses a non-default distance function. Here we # use the average silhouette with Chebyshev (L-infinity) distance. linf_dist <- function(x) philentropy::distance(x, method = "chebyshev") linf_silhouette_avg <- new_cluster_metric( function(object, new_data = NULL, ...) { silhouette_avg(object, new_data = new_data, dist_fun = linf_dist, ...) }, direction = "maximize" ) # The custom metric can now be combined with others in a metric set. cluster_metric_set(linf_silhouette_avg, sse_ratio) #> # A tibble: 2 × 3 #> metric class direction #> #> 1 linf_silhouette_avg cluster_metric maximize #> 2 sse_ratio cluster_metric zero ```