1

I want to try this K-means clustering code on my own file how do I change it so it doesn't create random information but reads it from my own data source?

%% 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)
6
  • Can you clearly identify what part of the code you posted is generating the random data? If so, that's the variable where you should store your dataset in.
    – Pablo
    Oct 12, 2011 at 1:07
  • Please tell us more about your data source. Is it in a database, in a file (what format?), ...
    – Laurent'
    Oct 12, 2011 at 6:24
  • @Laurent', read OP's other questions.
    – Nzbuu
    Oct 12, 2011 at 10:40
  • 1
    @Nzbuu One shouldn't have to read the OP's question history to figure out the details. Each question should be stand-alone and if the OP can't put in a minimum effort into his own question (to which he supposedly needs an answer) and make it clear, why should others?
    – abcd
    Oct 12, 2011 at 19:09
  • @yoda, I agree completely. Just referring to the volume of OP's comments on this subject.
    – Nzbuu
    Oct 12, 2011 at 20:04

1 Answer 1

4

The line that creates the random data is:

data = rand([numObservarations dimensions]);

Just replace this line with code that reads your data (probably using matlab command such as textscan) into a variable named data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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