Testing Waters

Searchâ€¦

Projects

Patterns

Geometry

Lists

K Mean

K-Means is one of the most popular "clustering" algorithms

K-means stores **k** centroids that it uses to define clusters. A point is considered to be in a particular cluster if it is closer to that cluster's centroid than any other centroid.

Grouping points into k (no.s) clusters

1

// Group by Centroid

2

def k1(pnts:var[]..[],cnts:var[]..[])

3

{

4

//Labels

5

lbl1 = "A"..#(List.Count(cnts))..1;

6

â€‹

7

//Distance to Centroids

8

dst1 = pnts<1>.DistanceTo(cnts<2>);

9

dst2 = List.SortByKey(lbl1,dst1<1>);

10

dst3 = List.FirstItem(dst2["sortedList"]<1>);

11

â€‹

12

//Group by Closest to Centroid

13

pnt1 = List.GroupByKey(pnts,dst3)["groups"];

14

return pnt1;

15

};

16

â€‹

17

// Centroid

18

def ctr (pnts:var[]..[])

19

{

20

return Point.ByCoordinates(Math.Average(pnts.X),

21

Math.Average(pnts.Y),Math.Average(pnts.Z));

22

};

23

â€‹

24

// K Mean

25

def kMean (pnts:var[]..[],k:int)

26

{

27

pnt1 = k1(pnts,pnts[1..k]);

28

cnt1 = 1;

29

pnt2 = [];

30

pts1 = [Imperative]

31

{

32

while (cnt1 <= k)

33

{

34

ctr1 = ctr(pnt1);

35

pnt2 = k1(List.Flatten(pnt1,-1),ctr1);

36

cnt1 = cnt1 + 1;

37

pnt1 = pnt2;

38

}

39

return pnt2;

40

}

41

return pts1;

42

};

Copied!

Last modified 8mo ago

Copy link