Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab:K-means clustering

I have a matrice of A(369x10) which I want to cluster in 19 clusters. I use this method

[idx ctrs]=kmeans(A,19)

which yields idx(369x1) and ctrs(19x10)

I get the point up to here.All my rows in A is clustered in 19 clusters.

Now I have an array B(49x10).I want to know where the rows of this B corresponds in the among given 19 clusters.

How is it possible in MATLAB?

Thank you in advance

like image 783
tguclu Avatar asked Sep 03 '09 13:09

tguclu


People also ask

How does Matlab calculate k-means clustering?

idx = kmeans( X , k ) performs k-means clustering to partition the observations of the n-by-p data matrix X into k clusters, and returns an n-by-1 vector ( idx ) containing cluster indices of each observation. Rows of X correspond to points and columns correspond to variables.

What is k-means clustering explain with example?

K-Means Clustering is an Unsupervised Learning algorithm, which groups the unlabeled dataset into different clusters. Here K defines the number of pre-defined clusters that need to be created in the process, as if K=2, there will be two clusters, and for K=3, there will be three clusters, and so on.

What is K in k-means clustering?

The number of clusters found from data by the method is denoted by the letter 'K' in K-means. In this method, data points are assigned to clusters in such a way that the sum of the squared distances between the data points and the centroid is as small as possible.


1 Answers

The following is a a complete example on clustering:

%% generate sample data
K = 3;
numObservarations = 100;
dimensions = 3;
data = rand([numObservarations dimensions]);

%% cluster
opts = statset('MaxIter', 500, 'Display', 'iter');
[clustIDX, clusters, interClustSum, Dist] = kmeans(data, K, 'options',opts, ...
    'distance','sqEuclidean', 'EmptyAction','singleton', 'replicates',3);

%% plot data+clusters
figure, hold on
scatter3(data(:,1),data(:,2),data(:,3), 50, clustIDX, 'filled')
scatter3(clusters(:,1),clusters(:,2),clusters(:,3), 200, (1:K)', 'filled')
hold off, xlabel('x'), ylabel('y'), zlabel('z')

%% plot clusters quality
figure
[silh,h] = silhouette(data, clustIDX);
avrgScore = mean(silh);


%% Assign data to clusters
% calculate distance (squared) of all instances to each cluster centroid
D = zeros(numObservarations, K);     % init distances
for k=1:K
    %d = sum((x-y).^2).^0.5
    D(:,k) = sum( ((data - repmat(clusters(k,:),numObservarations,1)).^2), 2);
end

% find  for all instances the cluster closet to it
[minDists, clusterIndices] = min(D, [], 2);

% compare it with what you expect it to be
sum(clusterIndices == clustIDX)
like image 139
Amro Avatar answered Sep 27 '22 21:09

Amro