xref: /plugin/aichat/vendor/bdelespierre/php-kmeans/demo.php (revision 3379af09b7ec10f96a8d4f23b1563bd7f9ae79ac)
1*3379af09SAndreas Gohr<?php
2*3379af09SAndreas Gohr
3*3379af09SAndreas Gohrrequire "vendor/autoload.php";
4*3379af09SAndreas Gohr
5*3379af09SAndreas Gohr// prepare 50 points of 2D space to be clustered
6*3379af09SAndreas Gohr$points = [
7*3379af09SAndreas Gohr    [80,55],[86,59],[19,85],[41,47],[57,58],
8*3379af09SAndreas Gohr    [76,22],[94,60],[13,93],[90,48],[52,54],
9*3379af09SAndreas Gohr    [62,46],[88,44],[85,24],[63,14],[51,40],
10*3379af09SAndreas Gohr    [75,31],[86,62],[81,95],[47,22],[43,95],
11*3379af09SAndreas Gohr    [71,19],[17,65],[69,21],[59,60],[59,12],
12*3379af09SAndreas Gohr    [15,22],[49,93],[56,35],[18,20],[39,59],
13*3379af09SAndreas Gohr    [50,15],[81,36],[67,62],[32,15],[75,65],
14*3379af09SAndreas Gohr    [10,47],[75,18],[13,45],[30,62],[95,79],
15*3379af09SAndreas Gohr    [64,11],[92,14],[94,49],[39,13],[60,68],
16*3379af09SAndreas Gohr    [62,10],[74,44],[37,42],[97,60],[47,73],
17*3379af09SAndreas Gohr];
18*3379af09SAndreas Gohr
19*3379af09SAndreas Gohr// create a 2-dimentions space
20*3379af09SAndreas Gohr$space = new KMeans\Space(2);
21*3379af09SAndreas Gohr
22*3379af09SAndreas Gohr// add points to space
23*3379af09SAndreas Gohrforeach ($points as $i => $coordinates) {
24*3379af09SAndreas Gohr    $space->addPoint($coordinates);
25*3379af09SAndreas Gohr}
26*3379af09SAndreas Gohr
27*3379af09SAndreas Gohr// cluster these 50 points in 3 clusters
28*3379af09SAndreas Gohr$clusters = $space->solve(3);
29*3379af09SAndreas Gohr
30*3379af09SAndreas Gohr// display the cluster centers and attached points
31*3379af09SAndreas Gohrforeach ($clusters as $num => $cluster) {
32*3379af09SAndreas Gohr    $coordinates = $cluster->getCoordinates();
33*3379af09SAndreas Gohr    printf(
34*3379af09SAndreas Gohr        "Cluster %s [%d,%d]: %d points\n",
35*3379af09SAndreas Gohr        $num,
36*3379af09SAndreas Gohr        $coordinates[0],
37*3379af09SAndreas Gohr        $coordinates[1],
38*3379af09SAndreas Gohr        count($cluster)
39*3379af09SAndreas Gohr    );
40*3379af09SAndreas Gohr}
41