Passed
Pull Request — master (#262)
by
unknown
03:02
created

KMeans   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 2
dl 0
loc 56
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 2
A cluster() 0 14 3
A acluster() 0 14 3
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
    public function __construct(int $clustersNumber, int $initialization = self::INIT_KMEANS_PLUS_PLUS)
27
    {
28
        if ($clustersNumber <= 0) {
29
            throw new InvalidArgumentException('Invalid clusters number');
30
        }
31
32
        $this->clustersNumber = $clustersNumber;
33
        $this->initialization = $initialization;
34
    }
35
36
    public function cluster(array $samples): array
37
    {
38
        $space = new Space(count($samples[0]));
39
        foreach ($samples as $sample) {
40
            $space->addPoint($sample);
41
        }
42
43
        $clusters = [];
44
        foreach ($space->cluster($this->clustersNumber, $this->initialization) as $cluster) {
45
            $clusters[] = $cluster->getPoints();
46
        }
47
48
        return $clusters;
49
    }
50
51
    public function acluster(array $samples): array
52
    {
53
        $space = new Space(count(reset($samples)));
54
        foreach ($samples as $key => $sample) {
55
            $space->addPointWithLabels($sample, $key);
56
        }
57
58
        $clusters = [];
59
        foreach ($space->cluster($this->clustersNumber, $this->initialization) as $cluster) {
60
            $clusters[] = $cluster->getPointsWithLabels();
61
        }
62
63
        return $clusters;
64
    }
65
}
66