Created
March 11, 2019 15:01
-
-
Save akondas/be142e754f9c7db095eb79895e269acd to your computer and use it in GitHub Desktop.
php-ml k-means centronoids
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I not found
$cluster->centroid
function