Completed
Pull Request — master (#427)
by
unknown
03:32
created

KMeans::centronoids()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Phpml\Clustering;
6
7
use Phpml\Clustering\KMeans\Space;
8
use Phpml\Exception\InvalidArgumentException;
9
10
class KMeans implements Clusterer
11
{
12
    public const INIT_RANDOM = 1;
13
14
    public const INIT_KMEANS_PLUS_PLUS = 2;
15
16
    /**
17
     * @var int
18
     */
19
    private $clustersNumber;
20
21
    /**
22
     * @var int
23
     */
24
    private $initialization;
25
26
     /**
27
     * @var array
28
     */
29
    private $centronoids = [];
30
31
    public function __construct(int $clustersNumber, int $initialization = self::INIT_KMEANS_PLUS_PLUS)
32
    {
33
        if ($clustersNumber <= 0) {
34
            throw new InvalidArgumentException('Invalid clusters number');
35
        }
36
37
        $this->clustersNumber = $clustersNumber;
38
        $this->initialization = $initialization;
39
    }
40
41
    public function cluster(array $samples): array
42
    {
43
        $space = new Space(count(reset($samples)));
44
        foreach ($samples as $key => $sample) {
45
            $space->addPoint($sample, $key);
46
        }
47
48
        $clusters = [];
49
        foreach ($space->cluster($this->clustersNumber, $this->initialization) as $cluster) {
50
            $clusters[] = $cluster->getPoints();
51
            $arrayCluster = $cluster->toArray();
52
            $this->centronoids[] = $arrayCluster['centroid'];
53
        }
54
55
        return $clusters;
56
    }
57
58
    public function centronoids(): array
59
    {
60
        return $this->centronoids;
61
    }
62
}
63