Classifies graduation to given centroids

I am trying to assign datapoints (across Euclidean distance) to a known, predefined set of center points, assigning points to the nearest center point.

I have the feeling that I probably too often compromise / skip something basic, but I tried to do this with the implementation of kmeans with predefined centers and without iterations. However, in accordance with the code below and probably because the algorithm will perform one iteration, this will not work (cl $ -centers "move" and are not equal to the original centroids)

Is there another simple way to assign points in the matrix X to the nearest centers?

Thanks a lot in advance, W

x <- rbind(matrix(rnorm(100, sd = 0.3), ncol = 2), matrix(rnorm(100, mean = 1, sd = 0.3), ncol = 2)) colnames(x) <- c("x", "y") vector=c(0.25,0.5,0.75,1) ccenters <- as.matrix(cbind(vector,vector)) colnames(ccenters) <- c("x", "y") ccenters (cl <- kmeans(x, centers=ccenters,iter.max=1)) plot(x, col = cl$cluster) points(cl$centers, col = 1:4, pch = 8, cex = 2) cl$centers cl$centers==ccenters 
+4
source share
1 answer

You can directly calculate the distances between each point and each center and look at the nearest center.

 # All the distances (you could also use a loop) distances <- outer( 1:nrow(x), 1:nrow(ccenters), Vectorize( function(i,j) { sum( (x[i,] - ccenters[j,])^2 ) } ) ) # Find the nearest cluster clusters <- apply( distances, 1, which.min ) # Plot plot( x, col=clusters, pch=15 ) segments( ccenters[clusters,1], ccenters[clusters,2], x[,1], x[,2], col=clusters ) 
+3
source

All Articles