-
Notifications
You must be signed in to change notification settings - Fork 286
/
DecisionTreeThresholdNode.cpp
333 lines (259 loc) · 11.5 KB
/
DecisionTreeThresholdNode.cpp
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
333
#define GRT_DLL_EXPORTS
#include "DecisionTreeThresholdNode.h"
GRT_BEGIN_NAMESPACE
//Register the DecisionTreeThresholdNode module with the Node base class
RegisterNode< DecisionTreeThresholdNode > DecisionTreeThresholdNode::registerModule("DecisionTreeThresholdNode");
DecisionTreeThresholdNode::DecisionTreeThresholdNode() : DecisionTreeNode("DecisionTreeThresholdNode") {
clear();
}
DecisionTreeThresholdNode::~DecisionTreeThresholdNode(){
clear();
}
bool DecisionTreeThresholdNode::predict_(VectorFloat &x) {
if( x[ featureIndex ] >= threshold ) return true;
return false;
}
bool DecisionTreeThresholdNode::clear(){
//Call the base class clear function
DecisionTreeNode::clear();
featureIndex = 0;
threshold = 0;
return true;
}
bool DecisionTreeThresholdNode::print() const{
std::ostringstream stream;
if( getModel( stream ) ){
std::cout << stream.str();
return true;
}
return false;
}
bool DecisionTreeThresholdNode::getModel( std::ostream &stream ) const{
std::string tab = "";
for(UINT i=0; i<depth; i++) tab += "\t";
stream << tab << "depth: " << depth << " nodeSize: " << nodeSize << " featureIndex: " << featureIndex << " threshold " << threshold << " isLeafNode: " << isLeafNode << std::endl;
stream << tab << "ClassProbabilities: ";
for(UINT i=0; i<classProbabilities.size(); i++){
stream << classProbabilities[i] << "\t";
}
stream << std::endl;
if( leftChild != NULL ){
stream << tab << "LeftChild: " << std::endl;
leftChild->getModel( stream );
}
if( rightChild != NULL ){
stream << tab << "RightChild: " << std::endl;
rightChild->getModel( stream );
}
return true;
}
Node* DecisionTreeThresholdNode::deepCopy() const{
DecisionTreeThresholdNode *node = new DecisionTreeThresholdNode;
if( node == NULL ){
return NULL;
}
//Copy this node into the node
node->depth = depth;
node->isLeafNode = isLeafNode;
node->nodeID = nodeID;
node->predictedNodeID = predictedNodeID;
node->nodeSize = nodeSize;
node->featureIndex = featureIndex;
node->threshold = threshold;
node->classProbabilities = classProbabilities;
//Recursively deep copy the left child
if( leftChild ){
node->leftChild = leftChild->deepCopy();
node->leftChild->setParent( node );
}
//Recursively deep copy the right child
if( rightChild ){
node->rightChild = rightChild->deepCopy();
node->rightChild->setParent( node );
}
return dynamic_cast< Node* >( node );
}
UINT DecisionTreeThresholdNode::getFeatureIndex() const{
return featureIndex;
}
Float DecisionTreeThresholdNode::getThreshold() const{
return threshold;
}
bool DecisionTreeThresholdNode::set(const UINT nodeSize,const UINT featureIndex,const Float threshold,const VectorFloat &classProbabilities){
this->nodeSize = nodeSize;
this->featureIndex = featureIndex;
this->threshold = threshold;
this->classProbabilities = classProbabilities;
return true;
}
bool DecisionTreeThresholdNode::computeBestSplitBestIterativeSplit( const UINT &numSplittingSteps, const ClassificationData &trainingData, const Vector< UINT > &features, const Vector< UINT > &classLabels, UINT &featureIndex, Float &minError ){
const UINT M = trainingData.getNumSamples();
const UINT N = features.getSize();
const UINT K = classLabels.getSize();
if( N == 0 ) return false;
minError = grt_numeric_limits< Float >::max();
UINT bestFeatureIndex = 0;
Float bestThreshold = 0;
Float error = 0;
Float minRange = 0;
Float maxRange = 0;
Float step = 0;
Float giniIndexL = 0;
Float giniIndexR = 0;
Float weightL = 0;
Float weightR = 0;
Vector< UINT > groupIndex(M);
VectorFloat groupCounter(2,0);
Vector< MinMax > ranges = trainingData.getRanges();
MatrixFloat classProbabilities(K,2);
//Loop over each feature and try and find the best split point
for(UINT n=0; n<N; n++){
minRange = ranges[n].minValue;
maxRange = ranges[n].maxValue;
step = (maxRange-minRange)/Float(numSplittingSteps);
threshold = minRange;
featureIndex = features[n];
while( threshold <= maxRange ){
//Iterate over each sample and work out if it should be in the lhs (0) or rhs (1) group
groupCounter[0] = groupCounter[1] = 0;
classProbabilities.setAllValues(0);
for(UINT i=0; i<M; i++){
groupIndex[i] = trainingData[ i ][ featureIndex ] >= threshold ? 1 : 0;
groupCounter[ groupIndex[i] ]++;
classProbabilities[ getClassLabelIndexValue(trainingData[i].getClassLabel(),classLabels) ][ groupIndex[i] ]++;
}
//Compute the class probabilities for the lhs group and rhs group
for(UINT k=0; k<K; k++){
classProbabilities[k][0] = groupCounter[0]>0 ? classProbabilities[k][0]/groupCounter[0] : 0;
classProbabilities[k][1] = groupCounter[1]>0 ? classProbabilities[k][1]/groupCounter[1] : 0;
}
//Compute the Gini index for the lhs and rhs groups
giniIndexL = giniIndexR = 0;
for(UINT k=0; k<K; k++){
giniIndexL += classProbabilities[k][0] * (1.0-classProbabilities[k][0]);
giniIndexR += classProbabilities[k][1] * (1.0-classProbabilities[k][1]);
}
weightL = groupCounter[0]/M;
weightR = groupCounter[1]/M;
error = (giniIndexL*weightL) + (giniIndexR*weightR);
//Store the best threshold and feature index
if( error < minError ){
minError = error;
bestThreshold = threshold;
bestFeatureIndex = featureIndex;
}
//Update the threshold
threshold += step;
}
}
//Set the best feature index that will be returned to the DecisionTree that called this function
featureIndex = bestFeatureIndex;
//Store the node size, feature index, best threshold and class probabilities for this node
set(M,featureIndex,bestThreshold,trainingData.getClassProbabilities(classLabels));
return true;
}
bool DecisionTreeThresholdNode::computeBestSplitBestRandomSplit( const UINT &numSplittingSteps, const ClassificationData &trainingData, const Vector< UINT > &features, const Vector< UINT > &classLabels, UINT &featureIndex, Float &minError ){
const UINT M = trainingData.getNumSamples();
const UINT N = (UINT)features.size();
const UINT K = (UINT)classLabels.size();
if( N == 0 ) return false;
minError = grt_numeric_limits< Float >::max();
UINT bestFeatureIndex = 0;
Float bestThreshold = 0;
Float error = 0;
Float giniIndexL = 0;
Float giniIndexR = 0;
Float weightL = 0;
Float weightR = 0;
Random random;
Vector< UINT > groupIndex(M);
VectorFloat groupCounter(2,0);
MatrixFloat classProbabilities(K,2);
//Loop over each feature and try and find the best split point
UINT m,n;
const UINT numFeatures = features.getSize();
for(m=0; m<numSplittingSteps; m++){
//Chose a random feature
n = random.getRandomNumberInt(0,numFeatures);
featureIndex = features[n];
//Randomly choose the threshold, the threshold is based on a randomly selected sample with some random scaling
threshold = trainingData[ random.getRandomNumberInt(0,M) ][ featureIndex ] * random.getRandomNumberUniform(0.8,1.2);
//Iterate over each sample and work out if it should be in the lhs (0) or rhs (1) group
groupCounter[0] = groupCounter[1] = 0;
classProbabilities.setAllValues(0);
for(UINT i=0; i<M; i++){
groupIndex[i] = trainingData[ i ][ featureIndex ] >= threshold ? 1 : 0;
groupCounter[ groupIndex[i] ]++;
classProbabilities[ getClassLabelIndexValue(trainingData[i].getClassLabel(),classLabels) ][ groupIndex[i] ]++;
}
//Compute the class probabilities for the lhs group and rhs group
for(UINT k=0; k<K; k++){
classProbabilities[k][0] = groupCounter[0]>0 ? classProbabilities[k][0]/groupCounter[0] : 0;
classProbabilities[k][1] = groupCounter[1]>0 ? classProbabilities[k][1]/groupCounter[1] : 0;
}
//Compute the Gini index for the lhs and rhs groups
giniIndexL = giniIndexR = 0;
for(UINT k=0; k<K; k++){
giniIndexL += classProbabilities[k][0] * (1.0-classProbabilities[k][0]);
giniIndexR += classProbabilities[k][1] * (1.0-classProbabilities[k][1]);
}
weightL = groupCounter[0]/M;
weightR = groupCounter[1]/M;
error = (giniIndexL*weightL) + (giniIndexR*weightR);
//Store the best threshold and feature index
if( error < minError ){
minError = error;
bestThreshold = threshold;
bestFeatureIndex = featureIndex;
}
}
//Set the best feature index that will be returned to the DecisionTree that called this function
featureIndex = bestFeatureIndex;
//Store the node size, feature index, best threshold and class probabilities for this node
set(M,featureIndex,bestThreshold,trainingData.getClassProbabilities(classLabels));
return true;
}
bool DecisionTreeThresholdNode::saveParametersToFile( std::fstream &file ) const{
if(!file.is_open())
{
errorLog << "saveParametersToFile(fstream &file) - File is not open!" << std::endl;
return false;
}
//Save the DecisionTreeNode parameters
if( !DecisionTreeNode::saveParametersToFile( file ) ){
errorLog << "saveParametersToFile(fstream &file) - Failed to save DecisionTreeNode parameters to file!" << std::endl;
return false;
}
//Save the custom DecisionTreeThresholdNode parameters
file << "FeatureIndex: " << featureIndex << std::endl;
file << "Threshold: " << threshold << std::endl;
return true;
}
bool DecisionTreeThresholdNode::loadParametersFromFile( std::fstream &file ){
if(!file.is_open())
{
errorLog << "loadParametersFromFile(fstream &file) - File is not open!" << std::endl;
return false;
}
//Load the DecisionTreeNode parameters
if( !DecisionTreeNode::loadParametersFromFile( file ) ){
errorLog << "loadParametersFromFile(fstream &file) - Failed to load DecisionTreeNode parameters from file!" << std::endl;
return false;
}
std::string word;
//Load the custom DecisionTreeThresholdNode Parameters
file >> word;
if( word != "FeatureIndex:" ){
errorLog << "loadParametersFromFile(fstream &file) - Failed to find FeatureIndex header!" << std::endl;
return false;
}
file >> featureIndex;
file >> word;
if( word != "Threshold:" ){
errorLog << "loadParametersFromFile(fstream &file) - Failed to find Threshold header!" << std::endl;
return false;
}
file >> threshold;
return true;
}
GRT_END_NAMESPACE