PHP code example of crwgregory / php-kmeans

1. Go to this page and download the library: Download crwgregory/php-kmeans library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

crwgregory / php-kmeans example snippets


$points = [
    [80,55],[86,59],[19,85],[41,47],[57,58],
	[76,22],[94,60],[13,93],[90,48],[52,54],
	[62,46],[88,44],[85,24],[63,14],[51,40],
	[75,31],[86,62],[81,95],[47,22],[43,95],
	[71,19],[17,65],[69,21],[59,60],[59,12],
	[15,22],[49,93],[56,35],[18,20],[39,59],
	[50,15],[81,36],[67,62],[32,15],[75,65],
	[10,47],[75,18],[13,45],[30,62],[95,79],
	[64,11],[92,14],[94,49],[39,13],[60,68],
	[62,10],[74,44],[37,42],[97,60],[47,73],
];

// create a 2 dimentionnal space and fill it
$space = new KMeans\Space(2);

foreach ($points as $point)
    $space->addPoint($point);

 // resolve 3 clusters
$clusters = $space->solve(3);

foreach ($clusters as $i => $cluster)
    printf("Cluster %d [%d,%d]: %d points\n", $i, $cluster[0], $cluster[1], count($cluster));

// resolve 3 clusters using David Arthur and Sergei Vassilvitskii seeding algorithm
$clusters = $space->solve(3, KMeans\Space::SEED_DASV);

$x = $point[0];
$y = $point[1];

// or

list($x,$y) = $point->getCoordinates();

foreach ($cluster as $point)
    printf('[%d,%d]', $point[0], $point[1]);

$space->addPoint($coordinate, $data);

$data = $space[$point];

$clusters = $space->solve(3, KMeans\Space::SEED_DEFAULT, function($space, $clusters) {
    static $iterations = 0;

    printf("Iteration: %d\n", ++$iterations);

    foreach ($clusters as $i => $cluster)
        printf("Cluster %d [%d,%d]: %d points\n", $i, $cluster[0], $cluster[1], count($cluster));
});