Skip to content

Commit fefe387

Browse files
Merge pull request #106 from tidymodels/fix-104
stop silhuette from erroring with 1 centroid models
2 parents 910117f + 8b6bae4 commit fefe387

File tree

3 files changed

+30
-0
lines changed

3 files changed

+30
-0
lines changed

NEWS.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
# tidyclust (development version)
22

3+
* `silhouette()` and `silhouette_avg()` now return NAs instead of erroring when applied to a clustering object with 1 cluster. (#104)
4+
35
* Fixed bug where `extract_cluster_assignment()` doesn't work for `hier_clust()` models in workflows where `num_clusters` is specified in `extract_cluster_assignment()`.
46

57
# tidyclust 0.1.0

R/metric-silhouette.R

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,16 @@ silhouette <- function(object, new_data = NULL, dists = NULL,
3131

3232
sil <- cluster::silhouette(clust_int, preproc$dists)
3333

34+
if (!inherits(sil, "silhouette")) {
35+
res <- tibble::tibble(
36+
cluster = preproc$clusters,
37+
neighbor = factor(rep(NA_character_, length(preproc$clusters)),
38+
levels = levels(preproc$clusters)),
39+
sil_width = NA_real_
40+
)
41+
return(res)
42+
}
43+
3444
sil %>%
3545
unclass() %>%
3646
tibble::as_tibble() %>%
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
test_that("multiplication works", {
2+
kmeans_spec <- k_means(num_clusters = 1) %>%
3+
set_engine("stats")
4+
5+
kmeans_fit <- fit(kmeans_spec, ~., mtcars)
6+
7+
dists <- mtcars %>%
8+
as.matrix() %>%
9+
dist()
10+
11+
res <- silhouette(kmeans_fit, dists = dists)
12+
exp_res <- tibble::tibble(
13+
cluster = rep(factor("Cluster_1"), 32),
14+
neighbor = rep(factor(NA, levels = "Cluster_1"), 32),
15+
sil_width = rep(NA_real_, 32)
16+
)
17+
expect_identical(res, exp_res)
18+
})

0 commit comments

Comments
 (0)