This repository has been archived by the owner on Jun 25, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Tree.h
333 lines (269 loc) · 9.74 KB
/
Tree.h
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
#pragma once
// This file defines the Tree class, which is used to represent decision trees.
#include <assert.h>
#include <cstring>
#include <iostream>
#include <vector>
#include <string>
#include <stdexcept>
#ifdef _OPENMP
#include <omp.h>
#endif
#include "Interfaces.h"
#include "Node.h"
namespace MicrosoftResearch { namespace Cambridge { namespace Sherwood
{
template<class F, class S> class TreeTrainer;
template<class F, class S> class ParallelTreeTrainer;
/// <summary>
/// A decision tree, comprising multiple nodes.
/// </summary>
template<class F, class S>
class Tree // where F:IFeatureResponse where S:IStatisticsAggregator<S>
{
static const char* binaryFileHeader_;
typedef typename std::vector<unsigned int>::size_type DataPointIndex;
int decisionLevels_;
std::vector<Node<F,S> > nodes_;
public:
// Implementation only
Tree(int decisionLevels):decisionLevels_(decisionLevels)
{
if(decisionLevels<0)
throw std::runtime_error("Tree can't have less than 0 decision levels.");
if(decisionLevels>22)
throw std::runtime_error("Tree can't have more than 22 decision levels.");
// This full allocation of node storage may be wasteful of memory
// if trees are unbalanced but is efficient otherwise. Because child
// node indices can determined directly from the parent node's index
// it isn't necessary to store parent-child references within the
// nodes.
nodes_.resize((1 << (decisionLevels + 1)) - 1);
}
std::vector<Node<F,S> > & GetNodes() { return nodes_;}
public:
/// <summary>
/// Apply the decision tree to a collection of test data points.
/// </summary>
/// <param name="data">The test data.</param>
/// <returns>An array of leaf node indices per data point.</returns>
void Apply(const IDataPointCollection& data, std::vector<int>& leafNodeIndices)
{
CheckValid();
leafNodeIndices.resize(data.Count()); // of leaf node reached per data point
// Allocate temporary storage for data point indices and response values
std::vector<unsigned int> dataIndices_(data.Count());
for (unsigned int i = 0; i < data.Count(); i++)
dataIndices_[i] = i;
std::vector<float> responses_(data.Count());
// This doesn't really utilise cores for a lot of the time, try separating image into 6-8 sections then recombining?
#if defined(_OPENMP)
ApplyNodeParallel(0, data, dataIndices_, 0, data.Count(), leafNodeIndices, responses_);
#else
ApplyNode(0, data, dataIndices_, 0, data.Count(), leafNodeIndices, responses_);
#endif
}
void Serialize(std::ostream& o) const
{
const int majorVersion = 0, minorVersion = 0;
o.write(binaryFileHeader_, strlen(binaryFileHeader_));
o.write((const char*)(&majorVersion), sizeof(majorVersion));
o.write((const char*)(&minorVersion), sizeof(minorVersion));
// NB. We could allow IFeatureResponse and IStatisticsAggregrator to
// write type information here for safer deserialization (and
// friendlier exception descriptions in the event that the user
// tries to deserialize a tree of the wrong type).
o.write((const char*)(&decisionLevels_), sizeof(decisionLevels_));
for(int n=0; n<NodeCount(); n++)
nodes_[n].Serialize(o);
}
static std::unique_ptr<Tree<F,S> > Deserialize(std::istream& i)
{
std::unique_ptr<Tree<F,S> > tree;
std::vector<char> buffer(strlen(binaryFileHeader_)+1);
i.read(&buffer[0], strlen(binaryFileHeader_));
buffer[buffer.size()-1] = '\0';
if(strcmp(&buffer[0], binaryFileHeader_)!=0)
throw std::runtime_error("Unsupported forest format.");
int majorVersion = 0, minorVersion = 0;
i.read((char*)(&majorVersion), sizeof(majorVersion));
i.read((char*)(&minorVersion), sizeof(minorVersion));
if(majorVersion==0 && minorVersion==0)
{
int decisionLevels;
i.read((char*)(&decisionLevels), sizeof(decisionLevels));
if(decisionLevels<=0)
throw std::runtime_error("Invalid data");
tree = std::unique_ptr<Tree<F,S> >(new Tree<F, S>(decisionLevels));
for(int n=0; n<tree->NodeCount(); n++)
tree->nodes_[n].Deserialize(i);
tree->CheckValid();
}
else
throw std::runtime_error("Unsupported file version number.");
return tree;
}
/// <summary>
/// The number of nodes in the tree, including decision, leaf, and null nodes.
/// </summary>
int NodeCount() const
{
return nodes_.size();
}
/// <summary>
/// Return the specified tree node.
/// </summary>
/// <param name="index">A zero-based node index.</param>
/// <returns>The node.</returns>
const Node<F,S>& GetNode(int index) const
{
return nodes_[index];
}
/// <summary>
/// Return the specified tree node.
/// </summary>
/// <param name="index">A zero-based node index.</param>
/// <returns>The node.</returns>
Node<F,S>& GetNode(int index)
{
return nodes_[index];
}
static DataPointIndex Partition(std::vector<float>& keys, std::vector<unsigned int>& values, DataPointIndex i0, DataPointIndex i1, float threshold)
{
assert(i1 > i0); // past-the-end element index must be greater than start element index.
int i = (int)(i0); // index of first element
int j = int(i1 - 1); // index of last element
while (i != j)
{
if (keys[i] >= threshold)
{
// Swap keys[i] with keys[j]
float key = keys[i];
unsigned int value = values[i];
keys[i] = keys[j];
values[i] = values[j];
keys[j] = key;
values[j] = value;
j--;
}
else
{
i++;
}
}
return keys[i] >= threshold ? i : i + 1;
}
void CheckValid() const
{
if(NodeCount()==0)
throw std::runtime_error("Valid tree must have at least one node.");
if(GetNode(0).IsNull()==true)
throw std::runtime_error("A valid tree must have non-null root node.");
CheckValidRecurse(0);
}
private:
void CheckValidRecurse(int index, bool bHaveReachedLeaf=false) const
{
if (bHaveReachedLeaf==false && GetNode(index).IsLeaf())
{
// First time I have encountered a leaf node
bHaveReachedLeaf = true;
}
else
{
if (bHaveReachedLeaf)
{
// Have encountered a leaf node already, this node had better be null
if (GetNode(index).IsNull() == false)
throw std::runtime_error("Valid tree must have all descendents of leaf nodes set as null nodes.");
}
else
{
// Have not encountered a leaf node yet, this node had better be a split node
if (GetNode(index).IsSplit() == false)
throw std::runtime_error("Valid tree must have all antecents of leaf nodes set as split nodes.");
}
}
if (index >= (NodeCount() - 1) / 2)
{
// At maximum depth, this node had better be a leaf
if (bHaveReachedLeaf == false)
throw std::runtime_error("Valid tree must have all branches terminated by leaf nodes.");
}
else
{
CheckValidRecurse(2 * index + 1, bHaveReachedLeaf);
CheckValidRecurse(2 * index + 2, bHaveReachedLeaf);
}
}
public:
static std::string GetPrettyPrintPrefix(int nodeIndex)
{
std::string prefix = nodeIndex > 0 ? (nodeIndex % 2 == 1 ? "|-o " : "+-o ") : "o ";
for (int l = (nodeIndex - 1) / 2; l > 0; l = (l - 1) / 2)
prefix = (l % 2 == 1 ? "| " : " ") + prefix;
return prefix;
}
private:
void ApplyNode(
int nodeIndex,
const IDataPointCollection& data,
std::vector<unsigned int>& dataIndices,
int i0,
int i1,
std::vector<int>& leafNodeIndices,
std::vector<float>& responses_)
{
assert(nodes_[nodeIndex].IsNull()==false);
Node<F,S>& node = nodes_[nodeIndex];
if (node.IsLeaf())
{
for (int i = i0; i < i1; i++)
leafNodeIndices[dataIndices[i]] = nodeIndex;
return;
}
if (i0 == i1) // No samples left
return;
for (int i = i0; i < i1; i++)
{
responses_[i] = node.Feature.GetResponse(data, dataIndices[i]);
}
int ii = Partition(responses_, dataIndices, i0, i1, node.Threshold);
// Recurse for child nodes.
ApplyNode(nodeIndex * 2 + 1, data, dataIndices, i0, ii, leafNodeIndices, responses_);
ApplyNode(nodeIndex * 2 + 2, data, dataIndices, ii, i1, leafNodeIndices, responses_);
}
void ApplyNodeParallel(
int nodeIndex,
const IDataPointCollection& data,
std::vector<unsigned int>& dataIndices,
int i0,
int i1,
std::vector<int>& leafNodeIndices,
std::vector<float>& responses_)
{
assert(nodes_[nodeIndex].IsNull() == false);
Node<F, S>& node = nodes_[nodeIndex];
if (node.IsLeaf())
{
for (int i = i0; i < i1; i++)
leafNodeIndices[dataIndices[i]] = nodeIndex;
return;
}
if (i0 == i1) // No samples left
return;
int max_threads = omp_get_max_threads();
#pragma omp parallel for num_threads(max_threads)
for (int i = i0; i < i1; i++)
{
responses_[i] = node.Feature.GetResponse(data, dataIndices[i]);
}
int ii = Partition(responses_, dataIndices, i0, i1, node.Threshold);
// Recurse for child nodes.
ApplyNodeParallel(nodeIndex * 2 + 1, data, dataIndices, i0, ii, leafNodeIndices, responses_);
ApplyNodeParallel(nodeIndex * 2 + 2, data, dataIndices, ii, i1, leafNodeIndices, responses_);
}
};
template<class F, class S>
const char* Tree<F,S>::binaryFileHeader_ = "MicrosoftResearch.Cambridge.Sherwood.Tree";
} } }