Completed
Pull Request — master (#36)
by
unknown
02:28
created

DecisionTree::predictSample()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 11
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
        $this->samples = array_merge($this->samples, $samples);
68
        $this->targets = array_merge($this->targets, $targets);
69
70
        $this->featureCount = count($this->samples[0]);
71
        $this->columnTypes = $this->getColumnTypes($this->samples);
72
        $this->labels = array_keys(array_count_values($this->targets));
73
        $this->tree = $this->getSplitLeaf(range(0, count($this->samples) - 1));
74
    }
75
76
    protected function getColumnTypes(array $samples)
77
    {
78
        $types = [];
79
        for ($i=0; $i<$this->featureCount; $i++) {
80
            $values = array_column($samples, $i);
81
            $isCategorical = $this->isCategoricalColumn($values);
82
            $types[] = $isCategorical ? self::NOMINAL : self::CONTINUOS;
83
        }
84
        return $types;
85
    }
86
87
    /**
88
     * @param null|array $records
89
     * @return DecisionTreeLeaf
90
     */
91
    protected function getSplitLeaf($records, $depth = 0)
92
    {
93
        $split = $this->getBestSplit($records);
0 ignored issues
show
Bug introduced by
It seems like $records defined by parameter $records on line 91 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...
94
        $split->level = $depth;
95
        if ($this->actualDepth < $depth) {
96
            $this->actualDepth = $depth;
97
        }
98
        $leftRecords = [];
99
        $rightRecords= [];
100
        $remainingTargets = [];
101
        $prevRecord = null;
102
        $allSame = true;
103
        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...
104
            $record = $this->samples[$recordNo];
105
            if ($prevRecord && $prevRecord != $record) {
106
                $allSame = false;
107
            }
108
            $prevRecord = $record;
109
            if ($split->evaluate($record)) {
110
                $leftRecords[] = $recordNo;
111
            } else {
112
                $rightRecords[]= $recordNo;
113
            }
114
            $target = $this->targets[$recordNo];
115
            if (! in_array($target, $remainingTargets)) {
116
                $remainingTargets[] = $target;
117
            }
118
        }
119
120
        if (count($remainingTargets) == 1 || $allSame || $depth >= $this->maxDepth) {
121
            $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...
122
            $classes = array_count_values($remainingTargets);
123
            arsort($classes);
124
            $split->classValue = key($classes);
125
        } else {
126
            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...
127
                $split->leftLeaf = $this->getSplitLeaf($leftRecords, $depth + 1);
128
            }
129
            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...
130
                $split->rightLeaf= $this->getSplitLeaf($rightRecords, $depth + 1);
131
            }
132
        }
133
        return $split;
134
    }
135
136
    /**
137
     * @param array $records
138
     * @return DecisionTreeLeaf[]
139
     */
140
    protected function getBestSplit($records)
141
    {
142
        $targets = array_intersect_key($this->targets, array_flip($records));
143
        $samples = array_intersect_key($this->samples, array_flip($records));
144
        $samples = array_combine($records, $this->preprocess($samples));
145
        $bestGiniVal = 1;
146
        $bestSplit = null;
147
        for ($i=0; $i<$this->featureCount; $i++) {
148
            $colValues = [];
149
            foreach ($samples as $index => $row) {
150
                $colValues[$index] = $row[$i];
151
            }
152
            $counts = array_count_values($colValues);
153
            arsort($counts);
154
            $baseValue = key($counts);
155
            $gini = $this->getGiniIndex($baseValue, $colValues, $targets);
156
            if ($bestSplit == null || $bestGiniVal > $gini) {
157
                $split = new DecisionTreeLeaf();
158
                $split->value = $baseValue;
159
                $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...
160
                $split->columnIndex = $i;
161
                $split->records = $records;
162
                $bestSplit = $split;
163
                $bestGiniVal = $gini;
164
            }
165
        }
166
        return $bestSplit;
167
    }
168
169
    /**
170
     * @param string $baseValue
171
     * @param array $colValues
172
     * @param array $targets
173
     */
174
    public function getGiniIndex($baseValue, $colValues, $targets)
175
    {
176
        $countMatrix = [];
177
        foreach ($this->labels as $label) {
178
            $countMatrix[$label] = [0, 0];
179
        }
180
        foreach ($colValues as $index => $value) {
181
            $label = $targets[$index];
182
            $rowIndex = $value == $baseValue ? 0 : 1;
183
            $countMatrix[$label][$rowIndex]++;
184
        }
185
        $giniParts = [0, 0];
186
        for ($i=0; $i<=1; $i++) {
187
            $part = 0;
188
            $sum = array_sum(array_column($countMatrix, $i));
189
            if ($sum > 0) {
190
                foreach ($this->labels as $label) {
191
                    $part += pow($countMatrix[$label][$i] / floatval($sum), 2);
192
                }
193
            }
194
            $giniParts[$i] = (1 - $part) * $sum;
195
        }
196
        return array_sum($giniParts) / count($colValues);
197
    }
198
199
    /**
200
     * @param array $samples
201
     * @return array
202
     */
203
    protected function preprocess(array $samples)
204
    {
205
        // Detect and convert continuous data column values into
206
        // discrete values by using the median as a threshold value
207
        $columns = [];
208
        for ($i=0; $i<$this->featureCount; $i++) {
209
            $values = array_column($samples, $i);
210
            if ($this->columnTypes[$i] == self::CONTINUOS) {
211
                $median = Mean::median($values);
212
                foreach ($values as &$value) {
213
                    if ($value <= $median) {
214
                        $value = "<= $median";
215
                    } else {
216
                        $value = "> $median";
217
                    }
218
                }
219
            }
220
            $columns[] = $values;
221
        }
222
        // Below method is a strange yet very simple & efficient method
223
        // to get the transpose of a 2D array
224
        return array_map(null, ...$columns);
225
    }
226
227
    /**
228
     * @param array $columnValues
229
     * @return bool
230
     */
231
    protected function isCategoricalColumn(array $columnValues)
232
    {
233
        $count = count($columnValues);
234
        // There are two main indicators that *may* show whether a
235
        // column is composed of discrete set of values:
236
        // 1- Column may contain string values
237
        // 2- Number of unique values in the column is only a small fraction of
238
        //	  all values in that column (Lower than or equal to %20 of all values)
239
        $numericValues = array_filter($columnValues, 'is_numeric');
240
        if (count($numericValues) != $count) {
241
            return true;
242
        }
243
        $distinctValues = array_count_values($columnValues);
244
        if (count($distinctValues) <= $count / 5) {
245
            return true;
246
        }
247
        return false;
248
    }
249
250
    /**
251
     * @return string
252
     */
253
    public function getHtml()
254
    {
255
        return $this->tree->__toString();
256
    }
257
258
    /**
259
     * @param array $sample
260
     * @return mixed
261
     */
262
    protected function predictSample(array $sample)
263
    {
264
        $node = $this->tree;
265
        do {
266
            if ($node->isTerminal) {
267
                break;
268
            }
269
            if ($node->evaluate($sample)) {
270
                $node = $node->leftLeaf;
271
            } else {
272
                $node = $node->rightLeaf;
273
            }
274
        } while ($node);
275
276
        return $node ? $node->classValue : $this->labels[0];
277
    }
278
}
279