Skip to content

Instantly share code, notes, and snippets.

@akondas akondas/KMeans.php

Created Mar 11, 2019
Embed
What would you like to do?
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

This comment has been minimized.

Copy link

geopamplona commented Mar 19, 2020

I not found $cluster->centroid function

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.