Pacific-Design.com

    
Home Index

1. Machine Learning

2. 8 K-Means Clustering

Machine Learning / 8 K-Means Clustering /

K-means Clustering

% K-means Clustering
clc; format short
%--------------------------%
% points     X       Y
%--------------------------%
point1 = [ 1.0    1.5 ];   
point2 = [ 1.0    4.5 ]; 
point3 = [ 2.0    1.5 ];   
point4 = [ 2.0    3.5 ];
point5 = [ 3.0    2.5 ];
point6 = [ 5.0    6.5 ];

fprintf('------------- Euclidean Smaller Distance C1 ------------------\n')
m = containers.Map
m('p1_p2') = abs(sqrt( (point1(1) - point2(1))^2 - (point1(2) - point2(2))^2 ));
m('p1_p3') = abs(sqrt( (point1(1) - point3(1))^2 - (point1(2) - point3(2))^2 ));
m('p1_p4') = abs(sqrt( (point1(1) - point4(1))^2 - (point1(2) - point4(2))^2 ));
m('p1_p5') = abs(sqrt( (point1(1) - point5(1))^2 - (point1(2) - point5(2))^2 ));
m('p1_p6') = abs(sqrt( (point1(1) - point6(1))^2 - (point1(2) - point6(2))^2 ));

m.keys
m.values

%for k = m.keys
%  disp(k)
%end
% p1_p3 = 1 = shortest distance from point 1 to point 3
C1 = [ 1.0  1.5 ] % <== point 1
C2 = [ 2.0  1.5 ] % <== point 3

% K Number of clusters
K = 2;

%----------------------------------------------------%
% Compute a distance from each instance to C1 and C2
% and choose the smaller value of C1 and C2.
%----------------------------------------------------%
                  

disp('------------- Euclidean Distance for C1 ----------------------\n')
Point1_distance_c1 = sqrt( (point1(1) - C1(1))^2 + (point1(2) - C1(2))^2 );
Point2_distance_c1 = sqrt( (point2(1) - C1(1))^2 + (point2(2) - C1(2))^2 );
Point3_distance_c1 = sqrt( (point3(1) - C1(1))^2 + (point3(2) - C1(2))^2 );
Point4_distance_c1 = sqrt( (point4(1) - C1(1))^2 + (point4(2) - C1(2))^2 );
Point5_distance_c1 = sqrt( (point5(1) - C1(1))^2 + (point5(2) - C1(2))^2 );
Point6_distance_c1 = sqrt( (point6(1) - C1(1))^2 + (point6(2) - C1(2))^2 );


disp('------------- Euclidean Distance for C2 ----------------------\n')
Point1_distance_c2 = sqrt( (point1(1) - C2(1))^2 + (point1(2) - C2(2))^2 );
Point2_distance_c2 = sqrt( (point2(1) - C2(1))^2 + (point2(2) - C2(2))^2 );
Point3_distance_c2 = sqrt( (point3(1) - C2(1))^2 + (point3(2) - C2(2))^2 );
Point4_distance_c2 = sqrt( (point4(1) - C2(1))^2 + (point4(2) - C2(2))^2 );
Point5_distance_c2 = sqrt( (point5(1) - C2(1))^2 + (point5(2) - C2(2))^2 );
Point6_distance_c2 = sqrt( (point6(1) - C2(1))^2 + (point6(2) - C2(2))^2 );

disp('------------- Computer New C1 & C2 ----------------------\n')

New_C1a = (point1(1) + point2(1) + point3(1)) / 3;
New_C1b = (point1(2) + point2(2) + point3(2)) / 3;
New_C1  = [ New_C1a  New_C1b]

New_C2a = (point4(1) + point5(1) + point6(1)) / 3;
New_C2b = (point4(2) + point5(2) + point6(2)) / 3;
New_C2  = [ New_C2a  New_C2b]