running k-means and getting different results run after run?

I am running k-means clustering algorithm on a data, and I don't understand why I am getting different silhouette plots each time I run this. Is there a way to stabilise this? (or set the number of iterations) so I get the same results?

3 Comments

Generally, k-means clustering generates different results depending on starting conditions; that's why you'd normally run it a few times with randomized starting conditions.
I don't know the specific MATLAB implementation of k-means, but I'd assume it runs multiple times with random initialization.
Could you give an example of your data/results so we can see if the issue is in the (application of the) algorithm or in the data?
<<
These are two results of the the same data, and the same number of clusters (2). Is the data just that bad? Or I am not getting something right here?
Thanks for your insights.
>>

Sign in to comment.

 Accepted Answer

That's normal. Specify 'Replicates' to get convergence.
% Do kmeans clustering on the gray scale image.
grayLevels = double(grayImage(:)); % Convert to column vector.
[clusterIndexes, clusterCenters] = kmeans(grayLevels, numberOfClusters,...
'distance', 'sqEuclidean', ...
'Replicates', 2);
labeledImage = reshape(clusterIndexes, rows, columns);
See attached demo.

3 Comments

Hi,
I have the same problem
my code is;
x=xlsread('ucd1.xlsx', 'A:A');
y=xlsread('ucd1.xlsx', 'B:B');
z=xlsread('ucd1.xlsx', 'C:C');
a=xlsread('ucd2.xlsx', 'A:A');
b=xlsread('ucd2.xlsx', 'B:B');
c=xlsread('ucd2.xlsx', 'C:C');
xyz=[x y z];
abc=[a b c];
[idx1,C1] = kmeans(xyz,150,'Replicates',3);
[idx2,C2] = kmeans(abc,150,'Replicates',3);
plot3(C1(:,1),C1(:,2),C1(:,3),'kx','color','b')
hold on
plot3(C2(:,1),C2(:,2),C2(:,3),'ko','Color','r')
and i get the error given below;
Warning: Failed to converge in 100 iterations during replicate 2.
> In kmeans/loopBody (line 476)
In internal.stats.parallel.smartForReduce (line 136)
In kmeans (line 343)
In tt (line 11)
What may be the problem?
Thank you
You forgot to attach 'ucd1.xlsx', or even any scatterplots. Please do so, so we can help you.
You can find Ucd1 and ucd2.xlsx file in attachment. Thank you

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!