Completed
Push — develop ( 01a249...bb9e1a )
by Arkadiusz
02:44
created

KMeans::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 9
rs 9.6666
cc 2
eloc 5
nc 2
nop 2
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
    const INIT_RANDOM = 1;
13
    const INIT_KMEANS_PLUS_PLUS = 2;
14
15
    /**
16
     * @var int
17
     */
18
    private $clustersNumber;
19
20
    /**
21
     * @var int
22
     */
23
    private $initialization;
24
25
    /**
26
     * @param int $clustersNumber
27
     * @param int $initialization
28
     *
29
     * @throws InvalidArgumentException
30
     */
31
    public function __construct(int $clustersNumber, int $initialization = self::INIT_KMEANS_PLUS_PLUS)
32
    {
33
        if ($clustersNumber <= 0) {
34
            throw InvalidArgumentException::invalidClustersNumber();
35
        }
36
37
        $this->clustersNumber = $clustersNumber;
38
        $this->initialization = $initialization;
39
    }
40
41
    /**
42
     * @param array $samples
43
     *
44
     * @return array
45
     */
46
    public function cluster(array $samples)
47
    {
48
        $space = new Space(count($samples[0]));
49
        foreach ($samples as $sample) {
50
            $space->addPoint($sample);
51
        }
52
53
        $clusters = [];
54
        foreach ($space->solve($this->clustersNumber, $this->initialization) as $cluster) {
55
            $clusters[] = $cluster->getPoints();
56
        }
57
58
        return $clusters;
59
    }
60
}
61