2
$\begingroup$

I have implemented kmeans clustering on iris dataset (inbuilt dataset) in R. The code is given below:

X=as.matrix(iris[-5]);

K=3;

prevCentroids=matrix(0,K,dim(X)[2]);
centroids=X[sample(1:dim(X)[1],K),];

dot=numeric(3);
C=numeric(150);

while(!isTRUE(all.equal(centroids,prevCentroids)))
{
  for(i in 1:dim(X)[1])
   {
    for(j in 1:dim(centroids)[1])
     {
       dot[j]=(X[i,]-centroids[j,])%*%(X[i,]-centroids[j,]);
     }
     C[i]=which.min(dot);
   }

  prevCentroids=centroids;

  for(k in 1:K)
   {
     centroids[k,]=colMeans(X[which(C==k),]);
   }
}

print(cbind(iris,C));

Sometimes, with this code, I get 85% clustering correct. But sometimes, it is just 37% as correct, if I compare it with the already clustered inbuilt iris dataset.

Could anyone please tell me where I am going wrong?

$\endgroup$
3
  • $\begingroup$ why didn't you use set.seed(), so that the same sample is extracted every-time you run the code. since you haven't enabled it, your outcome changes every-time . Why are you trying to implement everything by yourself rather than using KMeans directly in R? $\endgroup$ – Toros91 Jan 11 '18 at 7:47
  • $\begingroup$ @toros91 probably because implementing an algorithm is the best way to understand how it works. You've never implemented kmeans? $\endgroup$ – David Marx Jan 11 '18 at 8:17
  • $\begingroup$ @DavidMarx: Probably what you said is true, I did but long time ago. $\endgroup$ – Toros91 Jan 11 '18 at 8:25
1
$\begingroup$

Actually, this is the expected behavior for running a k-means algorithm on the iris dataset. The iris dataset contains only two distinct clusters. So if you randomly set up three centroids, the third centroid will either end up on the right or on the wrong cluster, causing the algorithm to split that cluster into two (see the left picture).

Your outcome with 37% accuracy will most probably look somewhat similar to the left picture where the left cluster has been split into two clusters. The 85% accuracy will most probably come from those times in which the right cluster has been split into two clusters (you cannot be sure though without printing the results).

Chire [Public domain], from Wikimedia Commons

For testing purposes, you can simply use set.seed(123) before running the algorithm, so that you always get the same results. However, this doesn't solve the problem that the iris dataset isn't ideal for clustering purposes. I would suggest you check out other datasets or you give the R-package cluster.datasets a try.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.