|
| 1 | +test_that("fitting", { |
| 2 | + skip_if_not_installed("ClusterR") |
| 3 | + |
| 4 | + set.seed(1234) |
| 5 | + spec <- k_means(num_clusters = 3) %>% |
| 6 | + set_engine("ClusterR") |
| 7 | + |
| 8 | + expect_no_error( |
| 9 | + res <- fit(spec, ~., mtcars) |
| 10 | + ) |
| 11 | + |
| 12 | + expect_no_error( |
| 13 | + res <- fit_xy(spec, mtcars) |
| 14 | + ) |
| 15 | +}) |
| 16 | + |
| 17 | +test_that("predicting", { |
| 18 | + skip_if_not_installed("ClusterR") |
| 19 | + |
| 20 | + set.seed(1234) |
| 21 | + spec <- k_means(num_clusters = 3) %>% |
| 22 | + set_engine("ClusterR") |
| 23 | + |
| 24 | + res <- fit(spec, ~., mtcars) |
| 25 | + |
| 26 | + preds <- predict(res, mtcars[c(1:5), ]) |
| 27 | + |
| 28 | + expect_identical( |
| 29 | + preds, |
| 30 | + tibble::tibble(.pred_cluster = factor(paste0("Cluster_", c(1, 1, 1, 2, 2)), |
| 31 | + paste0("Cluster_", 1:3))) |
| 32 | + ) |
| 33 | +}) |
| 34 | + |
| 35 | +test_that("extract_centroids() works", { |
| 36 | + skip_if_not_installed("ClusterR") |
| 37 | + |
| 38 | + set.seed(1234) |
| 39 | + spec <- k_means(num_clusters = 3) %>% |
| 40 | + set_engine("ClusterR") |
| 41 | + |
| 42 | + res <- fit(spec, ~., mtcars) |
| 43 | + |
| 44 | + centroids <- extract_centroids(res) |
| 45 | + |
| 46 | + expected <- vctrs::vec_cbind( |
| 47 | + tibble::tibble(.cluster = factor(paste0("Cluster_", 1:3))), |
| 48 | + tibble::as_tibble(res$fit$centroids) |
| 49 | + ) |
| 50 | + |
| 51 | + expect_identical( |
| 52 | + centroids, |
| 53 | + expected |
| 54 | + ) |
| 55 | +}) |
| 56 | + |
| 57 | +test_that("extract_cluster_assignment() works", { |
| 58 | + skip_if_not_installed("ClusterR") |
| 59 | + |
| 60 | + set.seed(1234) |
| 61 | + spec <- k_means(num_clusters = 3) %>% |
| 62 | + set_engine("ClusterR") |
| 63 | + |
| 64 | + res <- fit(spec, ~., mtcars) |
| 65 | + |
| 66 | + clusters <- extract_cluster_assignment(res) |
| 67 | + |
| 68 | + exp_cluster <- res$fit$cluster |
| 69 | + exp_cluster <- order(unique(exp_cluster))[exp_cluster] |
| 70 | + |
| 71 | + expected <- vctrs::vec_cbind( |
| 72 | + tibble::tibble(.cluster = factor(paste0("Cluster_", exp_cluster))) |
| 73 | + ) |
| 74 | + |
| 75 | + expect_identical( |
| 76 | + clusters, |
| 77 | + expected |
| 78 | + ) |
| 79 | +}) |
0 commit comments