Zadavanje točaka i početnog klastera

PI={{{-3,-3},{2,2},{3,2},{1,0}},{{1,1},{4,1},{0,-2}}};
S=Flatten[PI,1];
ListPlot[PI,PlotMarkers->Automatic]

LS k-means algoritam

Funkcija cilja

F[PI_,c_]:=Sum[Norm[c[[i]]-PI[[i,j]],2]^2,{i,Length[PI]},{j,Length[PI[[i]]]}]

Step 1

c=Table[Mean[PI[[i]]],{i,Length[PI]}]

F0=F[PI,c]

Step 2

NI=Table[{},{i,Length[PI]}];
Do[
min={Norm[c[[1 ]]-S[[i]],2],1};
Do[
If[Norm[c[[j ]]-S[[i]],2]<min[[1]],
min={Norm[c[[j ]]-S[[i]],2],j};
]
,{j,2,Length[PI]}]
AppendTo[NI[[min[[2]]]],S[[i]]];
,{i,Length[S]}]
NI
ListPlot[NI,PlotMarkers->Automatic]

d=Table[Mean[NI[[i]]],{i,Length[NI]}]

F1=F[NI,d]

Step 3

If[F1<F0,
PI=NI;
c=d;
F0=F1;
Print["Idi na korak 2."];
,Print["STOP"];
]

Manhattan k-means algoritam

Funkcija cilja

F[PI_,c_]:=Sum[Norm[c[[i]]-PI[[i,j]],1],{i,Length[PI]},{j,Length[PI[[i]]]}]

Step 1

c=Table[Median[PI[[i]]],{i,Length[PI]}]

F0=F[PI,c]

Step 2

NI=Table[{},{i,Length[PI]}];
Do[
min={Norm[c[[1 ]]-S[[i]],2],1};
Do[
If[Norm[c[[j ]]-S[[i]],2]<min[[1]],
min={Norm[c[[j ]]-S[[i]],2],j};
]
,{j,2,Length[PI]}]
AppendTo[NI[[min[[2]]]],S[[i]]];
,{i,Length[S]}]
NI
ListPlot[NI,PlotMarkers->Automatic]

d=Table[Median[NI[[i]]],{i,Length[NI]}]

F1=F[NI,d]

Step 3

If[F1<F0,
PI=NI;
c=d;
F0=F1;
Print["Idi na korak 2."];
,Print["STOP"];
]