-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathserialize.go
More file actions
185 lines (165 loc) · 5.1 KB
/
Copy pathserialize.go
File metadata and controls
185 lines (165 loc) · 5.1 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
package randomforest
import (
"encoding/json"
"fmt"
"math"
)
var JSONNumbersPrecisionDecPlaces = 5
type jsonFloat float64
func (v jsonFloat) MarshalJSON() ([]byte, error) {
multiplier := math.Pow(10, float64(JSONNumbersPrecisionDecPlaces))
rounded := math.Round(float64(v)*multiplier) / multiplier
format := fmt.Sprintf("%%.%df", JSONNumbersPrecisionDecPlaces)
return []byte(fmt.Sprintf(format, rounded)), nil
}
func (v jsonFloat) Float64() float64 {
return float64(v)
}
func floatJSONSlice(slice []float64) []jsonFloat {
ans := make([]jsonFloat, len(slice))
for i, v := range slice {
ans[i] = jsonFloat(v)
}
return ans
}
func floatJSONSliceRev(slice []jsonFloat) []float64 {
ans := make([]float64, len(slice))
for i, v := range slice {
ans[i] = v.Float64()
}
return ans
}
type jsonTreeNode struct {
ID int `json:"id"`
Attribute int `json:"attribute"`
Branch0 int `json:"branch0"`
Branch1 int `json:"branch1"`
Value jsonFloat `json:"value"`
LeafValue []jsonFloat `json:"leafValue"`
Gini jsonFloat `json:"gini"`
GiniGain jsonFloat `json:"giniGain"`
Size int `json:"size"`
Depth int `json:"depth"`
}
type jsonTree struct {
Nodes []*jsonTreeNode `json:"nodes"`
Validation jsonFloat `json:"validation"`
}
type jsonForest struct {
Trees []*jsonTree `json:"trees"`
Features int `json:"features"`
Classes int `json:"classes"`
LeafSize int `json:"leafSize"`
MFeatures int `json:"mFeatures"`
NTrees int `json:"nTrees"`
NSize int `json:"nSize"`
MaxDepth int `json:"maxDepth"`
FeatureImportance []jsonFloat `json:"featureImportance"`
}
func attachIDs(tree *Tree) *jsonTree {
jsonTree := &jsonTree{
Nodes: make([]*jsonTreeNode, 0, 100),
Validation: jsonFloat(tree.Validation),
}
dfsProcNode(&tree.Root, jsonTree, 0)
return jsonTree
}
// dfsProcNode walks (in DFS manner) through a tree with root in the `node`
// and attaches numeric IDs to nodes.
func dfsProcNode(node *Branch, outTree *jsonTree, availID int) int {
newNode := &jsonTreeNode{
ID: availID,
Attribute: node.Attribute,
Value: jsonFloat(node.Value),
LeafValue: floatJSONSlice(node.LeafValue),
Gini: jsonFloat(node.Gini),
GiniGain: jsonFloat(node.GiniGain),
Size: node.Size,
Depth: node.Depth,
}
lastID := availID
if node.Branch0 != nil {
newNode.Branch0 = lastID + 1
lastID = dfsProcNode(node.Branch0, outTree, newNode.Branch0)
} else {
newNode.Branch0 = -1
}
if node.Branch1 != nil {
newNode.Branch1 = lastID + 1
lastID = dfsProcNode(node.Branch1, outTree, newNode.Branch1)
} else {
newNode.Branch1 = -1
}
outTree.Nodes = append(outTree.Nodes, newNode)
return lastID
}
func deserializeJsonTreeNode(nodeID int, mapping map[int]*jsonTreeNode) *Branch {
node := mapping[nodeID]
br := Branch{
Attribute: node.Attribute,
Value: node.Value.Float64(),
IsLeaf: node.Branch0 == -1 && node.Branch1 == -1,
LeafValue: floatJSONSliceRev(node.LeafValue),
Gini: node.Gini.Float64(),
GiniGain: node.GiniGain.Float64(),
Size: node.Size,
Depth: node.Depth,
}
if node.Branch0 > -1 {
br.Branch0 = deserializeJsonTreeNode(node.Branch0, mapping)
}
if node.Branch1 > -1 {
br.Branch1 = deserializeJsonTreeNode(node.Branch1, mapping)
}
return &br
}
// -------- Forest's JSON interface methods ----
// UnmarshalJSON implements the json.Unmarshaler method.
func (forest *Forest) UnmarshalJSON(b []byte) error {
var sForest jsonForest
if err := json.Unmarshal(b, &sForest); err != nil {
return fmt.Errorf("failed to load the Forest model from JSON: %w", err)
}
forest.Features = sForest.Features
forest.Classes = sForest.Classes
forest.LeafSize = sForest.LeafSize
forest.MFeatures = sForest.MFeatures
forest.NTrees = sForest.NTrees
forest.NSize = sForest.NSize
forest.MaxDepth = sForest.MaxDepth
forest.FeatureImportance = floatJSONSliceRev(sForest.FeatureImportance)
forest.Trees = make([]Tree, len(sForest.Trees))
idMap := make(map[int]*jsonTreeNode)
for i, tree := range sForest.Trees {
t := Tree{
Validation: tree.Validation.Float64(),
}
// let's not rely on node order and map IDs properly
for _, nd := range tree.Nodes {
idMap[nd.ID] = nd
}
t.Root = *deserializeJsonTreeNode(0, idMap)
forest.Trees[i] = t
}
return nil
}
// MarshalJSON implements json.Marshaler interface allowing
// for Forest serialization in a standard way via json.Marshal function.
func (forest Forest) MarshalJSON() ([]byte, error) {
toSave := jsonForest{
Trees: make([]*jsonTree, len(forest.Trees)),
Features: forest.Features,
Classes: forest.Classes,
LeafSize: forest.LeafSize,
MFeatures: forest.MFeatures,
NTrees: forest.NTrees,
NSize: forest.NSize,
MaxDepth: forest.MaxDepth,
FeatureImportance: floatJSONSlice(forest.FeatureImportance),
}
for i, tr := range forest.Trees {
tmp := attachIDs(&tr)
toSave.Trees[i] = tmp
}
return json.Marshal(toSave)
}