-
Notifications
You must be signed in to change notification settings - Fork 0
/
randomforest.go
86 lines (68 loc) · 1.86 KB
/
randomforest.go
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package DragonBlood
import (
"fmt"
"log"
"github.com/mawicks/DragonBlood/stats"
)
type RandomForestRegressor struct {
nTrees int
trees []*DecisionTreeNode
nFeatures int
grower *decisionTreeGrower
}
func NewRandomForestRegressor(nTrees int) *RandomForestRegressor {
return &RandomForestRegressor{
nTrees,
make([]*DecisionTreeNode, 0, nTrees),
0,
&decisionTreeGrower{MaxFeatures: 10, MinLeafSize: 1},
}
}
func (rf *RandomForestRegressor) Fit(features []OrderedFeature, target Feature) []float64 {
rf.nFeatures = len(features)
oobPrediction := make([]stats.Accumulator, features[0].Len())
for i := range oobPrediction {
oobPrediction[i] = stats.NewMeanAccumulator()
}
for _, f := range features {
f.Prepare()
}
for i := 0; i < rf.nTrees; i++ {
bag := NewBag(features[0].Len())
log.Printf("bag: %v", bag)
rf.trees = append(rf.trees, rf.grower.grow(features, target, bag, oobPrediction))
}
result := make([]float64, len(oobPrediction))
for i, p := range oobPrediction {
result[i] = p.Value()
}
return result
}
func (rf *RandomForestRegressor) Predict(features []Feature) []float64 {
result := make([]float64, features[0].Len())
for i, tree := range rf.trees {
if tree != nil {
for j, p := range tree.Predict(features) {
result[j] += (p - result[j]) / float64(i+1)
}
}
}
return result
}
func (rf *RandomForestRegressor) Importances() []float64 {
fmt.Printf("Importances(): nFeatures: %d\n", rf.nFeatures)
forestImportances := make([]float64, rf.nFeatures)
treeImportances := make([]float64, rf.nFeatures)
for i, tree := range rf.trees {
if tree != nil {
for j := range treeImportances {
treeImportances[j] = 0.0
}
tree.Importances(treeImportances)
for j, imp := range treeImportances {
forestImportances[j] += (imp - forestImportances[j]) / float64(i+1)
}
}
}
return forestImportances
}