How to find the range of kmeans clusters?

Viewed 72

if I have this

   x = c(0.5,0.1,0.3,6,5,2,1,4,2,1,0.9,3,6,99,22,11,44,55)

apply kmeans

   kmeans(x, centers=5, iter.max = 10, nstart = 1)

this gives:

        Cluster means:
          [,1]
    1 99.00
    2 49.50
    3  22.00
    4  7.00
    5  1.48

     Clustering vector:
      [1] 5 5 5 4 4 5 5 5 5 5 5 5 4 1 3 4 2 2

Now I want to classify my values in x2 based on the clusters of x (1,2,3,4,5). How to do this?

x2 = c(0.3,1,3,0.66,0.5,0.2,0.1,64,92,21,0.93,93,6,99,22,11,44,55)
2 Answers

Here is a naive approch based on distance to centroids of each cluster:

km <-  kmeans(x, centers=5, iter.max = 10, nstart = 1)
group <- sapply(x2, function(xx) which.min(abs(km$centers - xx)))

plot(x = x, y = rep(1, length(x)), col = km$cluster)
points(x = km$centers, y = rep(1, length(km$centers)), col = "purple", pch = "*")
points(x = x2, y = rep(1, length(x2)), col = group, pch = "+")

Please check the link provided by @neilfws about doing predictions with kmeans.

There is a predict method for kmeans clusters in the fdm2id package. Load the package and type ?KMEANS and ?predict.kmeans for more information.

library(data.table)
library(fdm2id)
#
x  <- c(0.5,0.1,0.3,6,5,2,1,4,2,1,0.9,3,6,99,22,11,44,55)
dt <- data.table(x2 = c(0.3,1,3,0.66,0.5,0.2,0.1,64,92,21,0.93,93,6,99,22,11,44,55))
dt[, pred:=predict(KMEANS(x, k = 5), newdata=x2)]

Note that the cluster numbers are arbitrary in the sense that they merely distinguish between clusters, so the numbering might not be the same but the cluster membership should align.

Related