DecisionNode::__construct()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 11
c 1
b 0
f 0
dl 0
loc 17
rs 9.9
cc 3
nc 3
nop 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Phpml\Tree\Node;
6
7
use Phpml\Exception\InvalidArgumentException;
8
9
class DecisionNode extends BinaryNode implements PurityNode
10
{
11
    /**
12
     * @var int
13
     */
14
    private $column;
15
16
    /**
17
     * @var mixed
18
     */
19
    private $value;
20
21
    /**
22
     * @var array
23
     */
24
    private $groups = [];
25
26
    /**
27
     * @var float
28
     */
29
    private $impurity;
30
31
    /**
32
     * @var int
33
     */
34
    private $samplesCount;
35
36
    /**
37
     * @param mixed $value
38
     */
39
    public function __construct(int $column, $value, array $groups, float $impurity)
40
    {
41
        if (count($groups) !== 2) {
42
            throw new InvalidArgumentException('The number of groups must be exactly two.');
43
        }
44
45
        if ($impurity < 0.) {
46
            throw new InvalidArgumentException('Impurity cannot be less than 0.');
47
        }
48
49
        $this->column = $column;
50
        $this->value = $value;
51
        $this->groups = $groups;
52
        $this->impurity = $impurity;
53
        $this->samplesCount = (int) array_sum(array_map(static function (array $group): int {
54
            return count($group[0]);
55
        }, $groups));
56
    }
57
58
    public function column(): int
59
    {
60
        return $this->column;
61
    }
62
63
    /**
64
     * @return mixed
65
     */
66
    public function value()
67
    {
68
        return $this->value;
69
    }
70
71
    public function groups(): array
72
    {
73
        return $this->groups;
74
    }
75
76
    public function impurity(): float
77
    {
78
        return $this->impurity;
79
    }
80
81
    public function samplesCount(): int
82
    {
83
        return $this->samplesCount;
84
    }
85
86
    public function purityIncrease(): float
87
    {
88
        $impurity = $this->impurity;
89
90
        if ($this->left() instanceof PurityNode) {
91
            $impurity -= $this->left()->impurity()
92
                * ($this->left()->samplesCount() / $this->samplesCount);
93
        }
94
95
        if ($this->right() instanceof PurityNode) {
96
            $impurity -= $this->right()->impurity()
97
                * ($this->right()->samplesCount() / $this->samplesCount);
98
        }
99
100
        return $impurity;
101
    }
102
103
    public function cleanup(): void
104
    {
105
        $this->groups = [[], []];
106
    }
107
}
108