Implementation of kmeans clustering using R
$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?
k-means
$endgroup$
add a comment |
$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?
k-means
$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
add a comment |
$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?
k-means
$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
k-means
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
add a comment |
$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
add a comment |
1 Answer
1
active
oldest
votes
$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](https://i.stack.imgur.com/KygZy.png)
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.
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$
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
$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](https://i.stack.imgur.com/KygZy.png)
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.
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$
add a comment |
$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](https://i.stack.imgur.com/KygZy.png)
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.
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$
add a comment |
$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](https://i.stack.imgur.com/KygZy.png)
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.
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](https://i.stack.imgur.com/KygZy.png)
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.
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.
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.
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
$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