-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrandom_forest.php
More file actions
47 lines (36 loc) · 865 Bytes
/
random_forest.php
File metadata and controls
47 lines (36 loc) · 865 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<?php
require_once __DIR__ . '/decision_tree.php';
function random_forest_train($data, $m, $n_features)
{
$trees = array();
for ($i = 0; $i < $m; ++$i) {
$sample = sample_data($data);
$trees[] = train_tree($sample, $n_features);
}
return $trees;
}
function sample_data($data, $n = 0)
{
$count = count($data);
if ($n <= 0) {
$n = $count;
}
$result = array();
for ($i = 0; $i < $n; ++$i) {
$result[] = $data[mt_rand(0, $count - 1)];
}
return $result;
}
function random_forest_classify($trees, $data)
{
$candidates = array_map(
function ($t) use ($data) { return $t->species($data); },
$trees);
return vote($candidates);
}
function vote($candidates)
{
$result = array_count_values($candidates);
arsort($result);
return array_keys($result)[0];
}