K-means Clustering and Voronoi Sets
Join the DZone community and get the full member experience.Join For Free
in the context of -means , we want to partition the space of our observations into classes. each observation belongs to the cluster with the nearest mean. here “nearest” is in the sense of some norm, usually the (euclidean) norm.
consider the case where we have 2 classes. the means being respectively the 2 black dots. if we partition based on the nearest mean, with the (euclidean) norm we get the graph on the left, and with the (manhattan) norm, the one on the right,
points in the red region are closer to the mean in the upper part, while points in the blue region are closer to the mean in the lower part. here, we will always use the standard (euclidean) norm. note that the graph above is related to voronoi diagrams (or voronoy, from вороний in ukrainian, or вороно́й in russian) with 2 points, the 2 means.
here, we have 5 groups. so let us run a 5-means algorithm here.
- we draw randomly 5 points in the space (intial values for the means),
- in the assignment step , we assign each point to the nearest mean
- in the update step , we compute the new centroids of the clusters
to visualize it, see:
the code the get the clusters is:
kmeans(pts, centers=5, nstart = 1, algorithm = "lloyd")
observe that the assignment step is based on computations of voronoi sets. this can be done in r using:
library(tripack) v <- voronoi.mosaic(means[,1],means[,2]) p <- voronoi.polygons(v) points(v,pch=19) plot(v,add=true)
this is what we can visualize below:
km1 <- kmeans(pts, centers=5, nstart = 1, algorithm = "lloyd") library(tripack) library(rcolorbrewer) cl5 <- brewer.pal(5, "pastel1") v <- voronoi.mosaic(km1$centers[,1],km1$centers[,2]) p <- voronoi.polygons(v) plot(pts,pch=19,xlim=0:1,ylim=0:1,xlab="",ylab="",col=cl5[km1$cluster]) points(km1$centers[,1],km1$centers[,2],pch=3,cex=1.5,lwd=2) plot(v,add=true)
here, starting points are draw randomly. if we run it again, we might get:
on that dataset, it is difficult to get cluster that are the five groups we can actually see. if we use:
set.seed(1) a <- c(rep(.2,100),rep(.2,100),rep(.5,100),rep(.8,100),rep(.8,100)) b <- c(rep(.2,100),rep(.8,100),rep(.5,100),rep(.2,100),rep(.8,100)) pts <- cbind(x=rnorm(500,a,.075),y=rnorm(500,b,.075))
we usually get something better.
Published at DZone with permission of Arthur Charpentier, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.