Completed
Pull Request — master (#36)
by
unknown
03:10
created

DecisionTree::predictSample()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 19
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 13
nc 6
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Phpml\Classification;
6
7
use Phpml\Helper\Predictable;
8
use Phpml\Helper\Trainable;
9
use Phpml\Math\Statistic\Mean;
10
use Phpml\Classification\DecisionTree\DecisionTreeLeaf;
11
12
class DecisionTree implements Classifier
13
{
14
    use Trainable, Predictable;
15
16
    const CONTINUOS = 1;
17
    const NOMINAL = 2;
18
19
    /**
20
     * @var array
21
     */
22
    private $samples = [];
23
24
    /**
25
     * @var array
26
     */
27
    private $columnTypes;
28
29
    /**
30
     * @var array
31
     */
32
    private $labels = [];
33
34
    /**
35
     * @var int
36
     */
37
    private $featureCount = 0;
38
39
    /**
40
     * @var DecisionTreeLeaf
41
     */
42
    private $tree = null;
43
44
    /**
45
     * @var int
46
     */
47
    private $maxDepth;
48
49
    /**
50
     * @var int
51
     */
52
    public $actualDepth = 0;
53
54
    /**
55
     * @param int $maxDepth
56
     */
57
    public function __construct($maxDepth = 10)
58
    {
59
        $this->maxDepth = $maxDepth;
60
    }
61
    /**
62
     * @param array $samples
63
     * @param array $targets
64
     */
65
    public function train(array $samples, array $targets)
66
    {
67
68
        $this->samples = array_merge($this->samples, $samples);
69
        $this->targets = array_merge($this->targets, $targets);
70
71
        $this->featureCount = count($this->samples[0]);
72
        $this->columnTypes = $this->getColumnTypes($this->samples);
73
        $this->labels = array_keys(array_count_values($this->targets));
74
        $this->tree = $this->getSplitLeaf(range(0, count($this->samples) - 1));
75
    }
76
77
    protected function getColumnTypes(array $samples)
78
    {
79
        $types = [];
80
        for ($i=0; $i<$this->featureCount; $i++) {
81
            $values = array_column($samples, $i);
82
            $isCategorical = $this->isCategoricalColumn($values);
83
            $types[] = $isCategorical ? self::NOMINAL : self::CONTINUOS;
84
        }
85
        return $types;
86
    }
87
88
    /**
89
     * @param null|array $records
90
     * @return DecisionTreeLeaf
91
     */
92
    protected function getSplitLeaf($records, $depth = 0)
93
    {
94
        $split = $this->getBestSplit($records);
0 ignored issues
show
Bug introduced by
It seems like $records defined by parameter $records on line 92 can also be of type null; however, Phpml\Classification\DecisionTree::getBestSplit() does only seem to accept array, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
95
        $split->level = $depth;
96
        if ($this->actualDepth < $depth) {
97
            $this->actualDepth = $depth;
98
        }
99
        $leftRecords = [];
100
        $rightRecords= [];
101
        $remainingTargets = [];
102
        $prevRecord = null;
103
        $allSame = true;
104
        foreach ($records as $recordNo) {
0 ignored issues
show
Bug introduced by
The expression $records of type null|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
105
            $record = $this->samples[$recordNo];
106
            if ($prevRecord && $prevRecord != $record) {
107
                $allSame = false;
108
            }
109
            $prevRecord = $record;
110
            if ($split->evaluate($record)) {
111
                $leftRecords[] = $recordNo;
112
            } else {
113
                $rightRecords[]= $recordNo;
114
            }
115
            $target = $this->targets[$recordNo];
116
            if (! in_array($target, $remainingTargets)) {
117
                $remainingTargets[] = $target;
118
            }
119
        }
120
121
        if (count($remainingTargets) == 1 || $allSame || $depth >= $this->maxDepth) {
122
            $split->isTerminal = 1;
0 ignored issues
show
Documentation Bug introduced by
The property $isTerminal was declared of type boolean, but 1 is of type integer. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
123
            $classes = array_count_values($remainingTargets);
124
            arsort($classes);
125
            $split->classValue = key($classes);
126
        } else {
127
            if ($leftRecords) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $leftRecords of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
128
                $split->leftLeaf = $this->getSplitLeaf($leftRecords, $depth + 1);
129
            }
130
            if ($rightRecords) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $rightRecords of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
131
                $split->rightLeaf= $this->getSplitLeaf($rightRecords, $depth + 1);
132
            }
133
        }
134
        return $split;
135
    }
136
137
    /**
138
     * @param array $records
139
     * @return DecisionTreeLeaf[]
140
     */
141
    protected function getBestSplit($records)
142
    {
143
        $targets = array_intersect_key($this->targets, array_flip($records));
144
        $samples = array_intersect_key($this->samples, array_flip($records));
145
        $samples = array_combine($records, $this->preprocess($samples));
146
        $bestGiniVal = 1;
147
        $bestSplit = null;
148
        for ($i=0; $i<$this->featureCount; $i++) {
149
            $colValues = [];
150
            $baseValue = null;
151
            foreach ($samples as $index => $row) {
152
                $colValues[$index] = $row[$i];
153
                if ($baseValue === null) {
154
                    $baseValue = $row[$i];
155
                }
156
            }
157
            $gini = $this->getGiniIndex($baseValue, $colValues, $targets);
158
            if ($bestSplit == null || $bestGiniVal > $gini) {
159
                $split = new DecisionTreeLeaf();
160
                $split->value = $baseValue;
161
                $split->giniIndex = $gini;
0 ignored issues
show
Documentation Bug introduced by
It seems like $gini can also be of type integer. However, the property $giniIndex is declared as type double. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
162
                $split->columnIndex = $i;
163
                $split->records = $records;
164
                $bestSplit = $split;
165
                $bestGiniVal = $gini;
166
            }
167
        }
168
        return $bestSplit;
169
    }
170
171
    /**
172
     * @param string $baseValue
173
     * @param array $colValues
174
     * @param array $targets
175
     */
176
    public function getGiniIndex($baseValue, $colValues, $targets)
177
    {
178
        $countMatrix = [];
179
        foreach ($this->labels as $label) {
180
            $countMatrix[$label] = [0, 0];
181
        }
182
        foreach ($colValues as $index => $value) {
183
            $label = $targets[$index];
184
            $rowIndex = $value == $baseValue ? 0 : 1;
185
            $countMatrix[$label][$rowIndex]++;
186
        }
187
        $giniParts = [0, 0];
188
        for ($i=0; $i<=1; $i++) {
189
            $part = 0;
190
            $sum = array_sum(array_column($countMatrix, $i));
191
            if ($sum > 0) {
192
                foreach ($this->labels as $label) {
193
                    $part += pow($countMatrix[$label][$i] / floatval($sum), 2);
194
                }
195
            }
196
            $giniParts[$i] = (1 - $part) * $sum;
197
        }
198
        return array_sum($giniParts) / count($colValues);
199
    }
200
201
    /**
202
     * @param array $samples
203
     * @return array
204
     */
205
    protected function preprocess(array $samples)
206
    {
207
        // Detect and convert continuous data column values into
208
        // discrete values by using the median as a threshold value
209
        $columns = [];
210
        for ($i=0; $i<$this->featureCount; $i++) {
211
            $values = array_column($samples, $i);
212
            if ($this->columnTypes[$i] == self::CONTINUOS) {
213
                $median = Mean::median($values);
214
                foreach ($values as &$value) {
215
                    if ($value <= $median) {
216
                        $value = "<= $median";
217
                    } else {
218
                        $value = "> $median";
219
                    }
220
                }
221
            }
222
            $columns[] = $values;
223
        }
224
        // Below method is a strange yet very simple & efficient method
225
        // to get the transpose of a 2D array
226
        return array_map(null, ...$columns);
227
    }
228
229
    /**
230
     * @param array $columnValues
231
     * @return bool
232
     */
233
    protected function isCategoricalColumn(array $columnValues)
234
    {
235
        $count = count($columnValues);
236
        // There are two main indicators that *may* show whether a
237
        // column is composed of discrete set of values:
238
        // 1- Column may contain string values
239
        // 2- Number of unique values in the column is only a small fraction of
240
        //	  all values in that column (Lower than or equal to %20 of all values)
241
        $numericValues = array_filter($columnValues, 'is_numeric');
242
        if (count($numericValues) != $count) {
243
            return true;
244
        }
245
        $distinctValues = array_count_values($columnValues);
246
        if (count($distinctValues) <= $count / 5) {
247
            return true;
248
        }
249
        return false;
250
    }
251
252
    /**
253
     * @return string
254
     */
255
    public function getHtml()
256
    {
257
        return $this->tree->__toString();
258
    }
259
260
    /**
261
     * @param array $sample
262
     * @return mixed
263
     */
264
    protected function predictSample(array $sample)
265
    {
266
        $node = $this->tree;
267
        do {
268
            if ($node->isTerminal) {
269
                break;
270
            }
271
            if ($node->evaluate($sample)) {
272
                $node = $node->leftLeaf;
273
            } else {
274
                $node = $node->rightLeaf;
275
            }
276
        } while ($node);
277
278
		if ($node) {
279
            return $node->classValue;
280
        }
281
        return $this->labels[0];
282
    }
283
}
284