Implementation of kmeans clustering using R












1












$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?










share|improve this question











$endgroup$












  • $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$


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?










share|improve this question











$endgroup$












  • $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












1








1


1



$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?










share|improve this question











$endgroup$




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?







k-means






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 11 '18 at 7:25









Toros91

1,9762628




1,9762628










asked Jan 10 '18 at 16:54









user44436user44436

61




61












  • $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


















  • $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
















$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$
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$
@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




$begingroup$
@DavidMarx: Probably what you said is true, I did but long time ago.
$endgroup$
– Toros91
Jan 11 '18 at 8:25










1 Answer
1






active

oldest

votes


















0












$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.






share|improve this answer








New contributor




georg_un is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






$endgroup$













    Your Answer





    StackExchange.ifUsing("editor", function () {
    return StackExchange.using("mathjaxEditing", function () {
    StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
    StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["$", "$"], ["\\(","\\)"]]);
    });
    });
    }, "mathjax-editing");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "557"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdatascience.stackexchange.com%2fquestions%2f26491%2fimplementation-of-kmeans-clustering-using-r%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0












    $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.






    share|improve this answer








    New contributor




    georg_un is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.






    $endgroup$


















      0












      $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.






      share|improve this answer








      New contributor




      georg_un is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      $endgroup$
















        0












        0








        0





        $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.






        share|improve this answer








        New contributor




        georg_un is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.






        $endgroup$



        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.







        share|improve this answer








        New contributor




        georg_un is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.









        share|improve this answer



        share|improve this answer






        New contributor




        georg_un is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.









        answered 11 hours ago









        georg_ungeorg_un

        1




        1




        New contributor




        georg_un is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.





        New contributor





        georg_un is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.






        georg_un is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Data Science Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            Use MathJax to format equations. MathJax reference.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdatascience.stackexchange.com%2fquestions%2f26491%2fimplementation-of-kmeans-clustering-using-r%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Callistus I

            Tabula Rosettana

            How to label and detect the document text images