|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types=1); |
|
3
|
|
|
|
|
4
|
|
|
namespace Phpml\Classification\Ensemble; |
|
5
|
|
|
|
|
6
|
|
|
use Phpml\Classification\Ensemble\Bagging; |
|
7
|
|
|
use Phpml\Classification\DecisionTree; |
|
8
|
|
|
use Phpml\Classification\NaiveBayes; |
|
9
|
|
|
|
|
10
|
|
|
class RandomForest extends Bagging |
|
11
|
|
|
{ |
|
12
|
|
|
/** |
|
13
|
|
|
* @var array |
|
14
|
|
|
*/ |
|
15
|
|
|
protected $classifierColumns; |
|
16
|
|
|
|
|
17
|
|
|
/** |
|
18
|
|
|
* @var float |
|
19
|
|
|
*/ |
|
20
|
|
|
protected $featureSubsetRatio = 0.7; |
|
21
|
|
|
|
|
22
|
|
|
public function setFeatureSubsetRatio(float $ratio) |
|
23
|
|
|
{ |
|
24
|
|
|
if ($ratio < 0.1 || $ratio > 1.0) { |
|
25
|
|
|
throw new Exception("Feature subset ratio should be between 0.1 and 1.0"); |
|
26
|
|
|
} |
|
27
|
|
|
$this->featureSubsetRatio = $ratio; |
|
28
|
|
|
return $this; |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* @param int $index |
|
33
|
|
|
*/ |
|
34
|
|
|
protected function getRandomSubset($index) |
|
35
|
|
|
{ |
|
36
|
|
|
list($subset, $targets) = parent::getRandomSubset($index); |
|
37
|
|
|
|
|
38
|
|
|
$featureCount = (int)ceil($this->featureSubsetRatio * $this->featureCount); |
|
39
|
|
|
if ($featureCount >= $this->featureCount) { |
|
40
|
|
|
$featureCount = $this->featureCount; |
|
41
|
|
|
} |
|
42
|
|
|
$features = range(0, $this->featureCount - 1); |
|
43
|
|
|
shuffle($features); |
|
44
|
|
|
$features = array_slice($features, 0, $featureCount, false); |
|
45
|
|
|
sort($features); |
|
46
|
|
|
$this->classifierColumns[$index] = $features; |
|
47
|
|
|
|
|
48
|
|
|
$columns = []; |
|
49
|
|
|
foreach ($features as $colIndex) { |
|
50
|
|
|
$columns[] = array_column($subset, $colIndex); |
|
51
|
|
|
} |
|
52
|
|
|
$subset= array_map(null, ...$columns); |
|
53
|
|
|
|
|
54
|
|
|
return [$subset, $targets]; |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
/** |
|
58
|
|
|
* @param array $sample |
|
59
|
|
|
* @return mixed |
|
60
|
|
|
*/ |
|
61
|
|
|
protected function predictSample(array $sample) |
|
62
|
|
|
{ |
|
63
|
|
|
$predictions = []; |
|
64
|
|
|
for ($i=0; $i<count($this->classifiers); $i++) { |
|
|
|
|
|
|
65
|
|
|
$samplePiece = []; |
|
66
|
|
|
foreach ($this->classifierColumns[$i] as $colIndex) { |
|
67
|
|
|
$samplePiece[] = $sample[$colIndex]; |
|
68
|
|
|
} |
|
69
|
|
|
/* @var $classifier Classifier */ |
|
70
|
|
|
$predictions[] = $this->classifiers[$i]->predict($samplePiece); |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
|
|
$counts = array_count_values($predictions); |
|
74
|
|
|
arsort($counts); |
|
75
|
|
|
reset($counts); |
|
76
|
|
|
return key($counts); |
|
77
|
|
|
} |
|
78
|
|
|
} |
|
79
|
|
|
|
If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration: