-
Notifications
You must be signed in to change notification settings - Fork 0
/
ML_assign5_2_clustering.m
62 lines (51 loc) · 1.67 KB
/
ML_assign5_2_clustering.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
function [SS, centroids, ind] = ML_assign5_2_clustering(X, k, rand_cent)
X_size = size(X);
fprintf('\nSize of cluster, k= %d',k);
centroids = zeros(k,size(X,2));
if rand_cent
randidx = randperm(size(X,1));
centroids = X(randidx(1:k), :);
else
centroids = X(1:k,1:X_size(2));
end
ind = zeros(X_size(1),1);
prev_ind = zeros(X_size(1),1);
SS = 0;
for i = 1:20
% clustering
for points = 1:X_size(1)
sp = 1;
dist_min = sqrt(sum((X(points,1:X_size(2))- centroids (1,1:X_size(2))).^2));
for center = 2:k
dist = sqrt(sum((X(points,1:X_size(2))- centroids (center,1:X_size(2))).^2));
if (dist_min > dist)
dist_min = dist;
sp = center;
end
end
ind(points) = sp;
end
% Recalculating Centroids
for j = 1:k
m = X(ind == j,1:X_size(2));
centroids (j,1:X_size(2)) = mean(m);
%SS = SS + sum(sum((m - mean(m)).^2));
end
%Checking the change in centroids
if isequal(prev_ind,ind)
%fprintf('\nbreaking...');
break;
else
prev_ind = ind;
end
end
fprintf('\nExiting on iteration = %d\n',i);
for j = 1:k
m = X(ind == j,1:X_size(2));
centroids (j,1:X_size(2)) = mean(m);
SS = SS + sum(sum((m - mean(m)).^2));
end
centroids = centroids';
%fprintf('total within group sum of squares = %d\n',SS);
%gscatter(X,Y,ind);
end