sourcedemos/k-means/k-means.xtl
1⍝!/usr/bin/env xetal
2⍝│ k-means, step by step: 300 points in five blobs, five centers. Each
3⍝│ step gives every point the nearest center, then moves each center to
4⍝│ the mean of its points (the Learn library's k_step: a few array
5⍝│ expressions over all the points at once). From a poor start, five
6⍝│ points of one blob, the centers travel across the plane to the
7⍝│ blobs; from Learn's farthest-first start they barely need to.
8
9"ml:" u̲se< "Learn"
10
11⍝━━ The points: five blobs of 60, each its own center and spread
12n ← 300
13i ← o̲ffsets n
14b ← 1 + i d̲iv 60
15cx ← b s̲elect -0.6 0.5 0.0 -0.5 0.6
16cy ← b s̲elect 0.5 0.6 -0.05 -0.6 -0.5
17spread ← b s̲elect 0.12 0.16 0.1 0.2 0.08
18⍝│ A little noise, the sum of two draws (so it bunches toward the middle).
19ᵘn̲oise ← { m → (f̲loat (r̲oll! m r̲eshape 1001) + (r̲oll! m r̲eshape 1001) − 1002) ÷ 1000.0 }
20X ← o̲\ (2 c̲at n) r̲eshape (cx + spread × ᵘn̲oise n) c̲at cy + spread × ᵘn̲oise n
21
22⍝━━ The map: a grid of g x g points over the square -1 .. 1
23g ← 40
24c ← -1.0 + 2.0 × (0.5 + f̲loat o̲ffsets g) ÷ f̲loat g
25grid ← o̲\ (2 c̲at g × g) r̲eshape (r̲avel (o̲ffsets g) 'r̲ight t̲able c) c̲at r̲avel (r̲ev c) 'l̲eft t̲able o̲ffsets g
26⍝ -- end of the core ------------------------------------------
27
28⍝━━ Two starts, the same steps
29k ← 5
30⍝│ A poor start: the first five points, all in the first blob.
31C0 ← k t̲ake X
32⍝│ Learn's start: the first point, then each time the farthest from those so far.
33F0 ← k ᵐˡf̲arthest X
34⍝│ The inertia (the sum of squared distances to the nearest center)
35⍝│ after 0 to 10 steps, from each start: it never rises.
36ᵘr̲ound ← { a → (f̲loat f̲loor 0.5 + 1000.0 × a) ÷ 1000.0 }
37ᵘr̲ound '{ j → (j '{ C → X ᵐˡk̲step C } p̲ower C0) ᵐˡi̲nertia X } e̲ach o̲ffsets 11
38ᵘr̲ound '{ j → (j '{ C → X ᵐˡk̲step C } p̲ower F0) ᵐˡi̲nertia X } e̲ach o̲ffsets 11
39⍝│ The centers after 10 steps from the poor start, one per row.
40C10 ← 10 '{ C → X ᵐˡk̲step C } p̲ower C0
41ᵘr̲ound C10
42⍝│ Which center each point of the map is nearest (A to E).
43(g c̲at g) r̲eshape (C10 ᵐˡa̲ssign grid) s̲elect ⎕A