Skip to content

Instantly share code, notes, and snippets.

@akondas
Created March 11, 2019 15:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akondas/be142e754f9c7db095eb79895e269acd to your computer and use it in GitHub Desktop.
Save akondas/be142e754f9c7db095eb79895e269acd to your computer and use it in GitHub Desktop.
php-ml k-means centronoids
<?php
declare(strict_types=1);
namespace Phpml\Clustering;
use Phpml\Clustering\KMeans\Space;
use Phpml\Exception\InvalidArgumentException;
class KMeans implements Clusterer
{
public const INIT_RANDOM = 1;
public const INIT_KMEANS_PLUS_PLUS = 2;
/**
* @var int
*/
private $clustersNumber;
/**
* @var int
*/
private $initialization;
/**
* @var array
*/
private $centronoids = [];
public function __construct(int $clustersNumber, int $initialization = self::INIT_KMEANS_PLUS_PLUS)
{
if ($clustersNumber <= 0) {
throw new InvalidArgumentException('Invalid clusters number');
}
$this->clustersNumber = $clustersNumber;
$this->initialization = $initialization;
}
public function cluster(array $samples): array
{
$space = new Space(count(reset($samples)));
foreach ($samples as $key => $sample) {
$space->addPoint($sample, $key);
}
$clusters = [];
foreach ($space->cluster($this->clustersNumber, $this->initialization) as $cluster) {
$clusters[] = $cluster->getPoints();
$this->centronoids[] = $cluster->centroid();
}
return $clusters;
}
public function centronoids(): array
{
return $this->centronoids;
}
}
@geopamplona
Copy link

I not found $cluster->centroid function

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment