-
Notifications
You must be signed in to change notification settings - Fork 1
/
tree.c
654 lines (527 loc) · 18.1 KB
/
tree.c
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "header.h"
#include "util.h"
#include "mpi.h"
/* Notes: Use main to test functions.
*
* TODO: Make threshold midpoint between last left and first right, or inf.
*
*/
int BestSplit(double **data, int n, int first, int col, int pos, double *impurity) {
/* Returns the row/index of the table with the least impurity after splitting
* for fixed column/feature col. Partition rows up to and including that index
* from everything afterwards.
*
* data = array of data sorted on index a
* n = length of table (# of rows/samples)
* col = sorting/splitting feature/column of data
* pos = number of positive labels
*
* Thus:
* (pos - lpos) = right pos count
* i = total left count
* n - i = total right count
*
*
*/
int lpos = 0;
int argmin = n - 1;//start with the whole node
double threshold;
double threshmin;
double P;
double Pmin = GINI(pos, n);//initial impurity of node
//Tabulate impurity for each possible threshold split
int i = 0;
while (i < n) {
threshold = data[first+i][col];
while (i < n && (data[first+i][col] == threshold)) {
if (data[first+i][D-1] > 0)
lpos += 1;
++i;
}
//Note that points on left = i, right = n-i
/*
If i=n, this is the whole node and the impurity is the initial
which is already done. i=n would cause error below.
*/
if (i < n) {
P = GINI(lpos, i)*i/n + GINI(pos-lpos, n-i)*(n-i)/n;
//Save threshold/index with min impurity
if (P < Pmin) {
Pmin = P;
argmin = i - 1;
threshmin = threshold;
}
}
}
//Save the minimum impurity to compare against other indices
*impurity = Pmin;
return argmin;
}
int WeightedBestSplit(double **data, int n, int first, int feat, double pos, double tot, double *impurity) {
/* Returns the row/index of the table with the least impurity after splitting
* for fixed column/feature feat. Partition rows up to and including that index
* from everything afterwards.
*
* data = array of data sorted on index a
* n = length of table (# of rows/samples)
* first = first index in the node
* feat = sorting/splitting feature/column of data
* pos = weight of positive labels
* tot = total weight of all labels
* impurity = pointer to save impurity after split
*
* Thus:
* (pos - lpos) = right pos count
* i = total left count
* n - i = total right count
*
*
*/
double lpos = 0;
double left = 0;
int argmin = n - 1;//start with the whole node
double threshold;
double threshmin;
double P;
double Pmin = GINI(pos, tot);//initial impurity of node
//Tabulate impurity for each possible threshold split
int i = 0;
while (i < n) {
threshold = data[first+i][feat];
while (i < n && (data[first+i][feat] == threshold)) {
if (data[first+i][D-1] > 0)
lpos += data[first+i][D];
left += data[first+i][D];
++i;
}
//Note that points on left = i, right = n-i
/*
If i=n, this is the whole node and the impurity is the initial
which is already done. i=n would cause error below.
*/
if (i < n) {
P = GINI(lpos, left)*left/tot + GINI(pos-lpos, tot-left)*(tot-left)/tot;
//Save threshold/index with min impurity
if (P < Pmin) {
Pmin = P;
argmin = i - 1;
threshmin = threshold;
}
}
}
//Save the minimum impurity to compare against other indices
*impurity = Pmin;
return argmin;
}
int PodWBS(Pod **data, int n, int first, int feat, double pos, double tot, double *impurity) {
/* Pod version of WeightedBestSplit
*
* data = array of data sorted by value in Pod form
* n = length of table (# of rows/samples)
* first = first index in the node
* pos = weight of positive labels
* tot = total weight of all labels
* impurity = pointer to save impurity after split
*
*/
double lpos = 0;
double left = 0;
int argmin = first + n - 1;//start with the whole node
double threshold;
double threshmin;
double P;
double Pmin = GINI(pos, tot);//initial impurity of node
//Tabulate impurity for each possible threshold split
int i = first;
while (i < first+n) {
threshold = data[i]->val[feat];
while ((i < first+n) && (data[i]->val[feat] == threshold)) {
if (data[i]->label > 0)
lpos += data[i]->weight;
left += data[i]->weight;
++i;
}
//Note that points on left = i, right = n-i
/*
If i=first+n, this is the whole node and the impurity is the initial
which is already done. i=first+n would cause error below.
*/
if (i < first+n) {
P = GINI(lpos, left)*left/tot + GINI(pos-lpos, tot-left)*(tot-left)/tot;
//Save threshold/index with min impurity
if (P < Pmin) {
Pmin = P;
argmin = i - 1;
threshmin = threshold;
}
}
}
//Save the minimum impurity to compare against other indices
*impurity = Pmin;
return argmin;
}
void SplitNode(Node *node, double **data, int n, int first, int level) {
/* Creates two branches of the decision tree on the array data. End condition
* creates leaf if the purity of the node is small or if there are few
* samples on the branch of node
*
* node = pointer to node in decision tree
* data = table of unsorted data with features and labels (with last
* column as the label (data[i][d-1]))
* n = length of table (# of rows/samples) on branch of node
* first = first index of samples on branch of node
* level = the depth of node in the tree
*/
timestamp_type sort_start, sort_stop, split_start, split_stop;
double sort_time = 0.;
double split_time = 0.;
int max_level = 3;
int min_points = 6;
node->left = NULL;
node->right = NULL;
node->index = -1;
//Get initial counts for positive/negative labels
int i;
int pos = 0;
double pos_w = 0;//positive weight
double tot = 0;//total weight
for (i = 0; i < n; ++i) {
tot += data[first+i][D];
if (data[first+i][D-1] > 0){
pos += 1;
pos_w += data[first+i][D];
}
}
int neg = n - pos;
double neg_w = tot - pos_w;
//Declare class for node in case of pruning on child
if (pos_w > neg_w)
node->label = 1;
else if (pos_w < neg_w)
node->label = -1;
else if (node->parent)
node->label = node->parent->label;
else {
//printf("Root node is evenly balanced.\n");
node->label = 0;
}
//If branch is small or almost pure, make leaf
if (n < min_points) {
//printf("small branch: %d points\n", n, level);
return;
}
else if (level == max_level) {
//printf("leaf node: level = max\n");
return;
}
else if (pos == 0 || neg == 0) {
//printf("pure node\n");
return;
}
///////////////TEST//////////////////
//printf("LEVEL: %d\n", level);
//printf("pos=%d, neg=%d, posw=%f, negw=%f, lab=%f\n", pos, neg, pos_w, neg_w, node->label);
//printf("GINI: %f\n", GINI(pos_w, tot));
/////////////////////////////////////
int col;
int row; //best row to split at for particular column/feature
int localrow; //first + localrow = row; receives BestSplit which returns integer in [-1, n-1]
double threshold; //best threshold to split at for column/feature
double impurity; //impurity for best split in feature/column
int bestcol = -1; //feature with best split
int bestrow = first+n-1; //best row to split for best feature
double bestthresh; //threshold split for best feature (data[bestrow][bestcol])
double Pmin = GINI(pos_w, tot); //minimum impurity seen so far
//Sort table. Then find best column/feature, threshold, and impurity
for (col = 0; col < D-1; ++col) {
//printf("\r%5d/%5d", col, D);
//fflush(stdout);
get_timestamp(&sort_start);
Sort(data, first, first+n-1, col);
get_timestamp(&sort_stop);
get_timestamp(&split_start);
localrow = WeightedBestSplit(data, n, first, col, pos_w, tot, &impurity);
get_timestamp(&split_stop);
sort_time += timestamp_diff_in_seconds(sort_start, sort_stop);
split_time += timestamp_diff_in_seconds(split_start, split_stop);
row = first + localrow;
threshold = data[row][col];
//If current column has better impurity, save col, thresh, and Pmin
if (impurity < Pmin) {
bestcol = col;
bestrow = row;
bestthresh = threshold;
Pmin = impurity;
}
}
//printf("\r \r");
//printf("Sort time: %f sec\nSplit time: %f sec\n", sort_time, split_time);
//If splitting doesn't improve purity (best split is at the end) stop
if (bestrow == first+n-1) {
//printf("no improvement\n");
return;
}
Sort(data, first, first+n-1, bestcol);
//For feature, threshold with best impurity, save to node attributes
node->index = bestcol;
node->threshold = bestthresh;
printf("Best feature: %d, Best thresh: %f, Impurity: %f\n", node->index, node->threshold, Pmin);
//Create right and left children
Node *l = malloc(sizeof(Node));
Node *r = malloc(sizeof(Node));
l->parent = node;
r->parent = node;
l->right = NULL;
l->left = NULL;
r->right = NULL;
r->left = NULL;
node->left = l;
node->right = r;
int first_r = bestrow+1;
int n_l = first_r - first;
int n_r = n - n_l;
//printf("LEFT\n");
SplitNode(l, data, n_l, first, level+1);
//printf("RIGHT\n");
SplitNode(r, data, n_r, first_r, level+1);
return;
}
void ParallelSplit(Node *node, Pod ***data, int n, int first, int level, int rank, int num_features) {
/* ParallelSplit copies SplitNode but enacts parallelized decision tree
* construction. We use MPI and design it so that each processor holds the
* data for one feature plus the labels and a pointer to the sample ("pod")
* with index to be used as a key.
*
* Each processor has its data sorted before ParallelSplit is called.
*
*/
int max_level = 3;
int min_points = 6;
node->left = NULL;
node->right = NULL;
node->index = -1;
//int tag = 21; //Timmy
int i;
int feat;
int last = first+n-1;
//Get initial counts for positive/negative labels
int pos = 0;
double pos_w = 0;//positive weight
double tot = 0;//total weight
for (i = first; i < last+1; ++i) {
tot += data[0][i]->weight;
if (data[0][i]->label > 0) {
pos += 1;
pos_w += data[0][i]->weight;
}
}
int neg = n - pos;
double neg_w = tot - pos_w;
//Declare class for node in case of pruning on child
if (pos_w > neg_w)
node->label = 1;
else if (pos_w < neg_w)
node->label = -1;
else if (node->parent)
node->label = node->parent->label;
else {
//printf("Root node is evenly balanced.\n");
node->label = 0;
}
//If branch is small or almost pure, make leaf
if (n < min_points) {
//printf("small branch: %d points\n", n, level);
return;
}
else if (level == max_level) {
//printf("leaf node: level = max\n");
return;
}
else if (pos == 0 || neg == 0) {
//printf("pure node\n");
return;
}
int feat_row;//best row to split at for column/feature of this process
int row = last;//best row for best feature
int best_feat = -1;//best feature to split on, so other processes save in tree
double threshold;//best threshold to split at for feature
double impurity;//impurity for best split in feature
double Pmin = GINI(pos_w, tot);//minimum impurity seen so far
//get_timestamp(&split_start);
for (feat = 0; feat < num_features; ++feat) {
feat_row = PodWBS(data[feat], n, first, feat, pos_w, tot, &impurity);
if (impurity < Pmin) {
row = feat_row;
threshold = data[feat][row]->val[feat];
Pmin = impurity;
best_feat = feat;
}
}
//get_timestamp(&split_stop);
//split_time += timestamp_diff_in_seconds(split_start, split_stop);
//Save impurity and process rank to structure for MPI communication
struct {
double P; //impurity
int R; //rank
} in, out;
in.P = Pmin;
in.R = rank;
/* AllReduce to find min impurity and corresponding process (MPI_MINLOC), then
* receive best row and hence size of next left/right nodes
*/
MPI_Allreduce(&in, &out, 1, MPI_DOUBLE_INT, MPI_MINLOC, MPI_COMM_WORLD);
MPI_Bcast(&row, 1, MPI_INT, out.R, MPI_COMM_WORLD);
//printf("rank %d row %d\n", rank, row);
//If splitting doesn't improve purity (best split is at the end) stop
if (row == last) {
//printf("no improvement\n");
return;
}
MPI_Bcast(&best_feat, 1, MPI_INT, out.R, MPI_COMM_WORLD);
MPI_Bcast(&threshold, 1, MPI_DOUBLE, out.R, MPI_COMM_WORLD);
/*
/////////////////////////////////////////////////////
printf("CHECK:%f \n", data[42][12696]->val[42]);
for (feat = 0; feat < num_features; feat++) {
for (i = first; i < last; ++i) {
if (data[feat][i]->val[feat] > data[feat][i+1]->val[feat]) {
printf("PRESORT FAILED, i = %d, feat = %d, first = %d", i, feat, first);
printf("%f then %f\n", data[feat][i]->val[feat], data[feat][i+1]->val[feat]);
abort();
}
}
}
printf("Correctly Sorted.\n");
////////////////////////////////////////////////////////
*/
int first_r = row+1;
int n_l = row+1-first; //first_r-first
int n_r = n - n_l;
//For min processor, construct and broadcast list telling which node each point goes to
char *keys = malloc(N*sizeof(char));
for (i = 0; i < N; ++i)
keys[i] = -1;
if (rank == out.R) {
for (i = first; i < row+1; ++i)
keys[data[best_feat][i]->key] = 1;//left
for (i = row+1; i < last+1; ++i)
keys[data[best_feat][i]->key] = 0;//right
}
MPI_Bcast(keys, N, MPI_CHAR, out.R, MPI_COMM_WORLD);
//Sort pod pointer list into ordered right node and left node
Pod **holder = malloc(n*sizeof(Pod*));
int l_ind;
int r_ind;
for (feat = 0; feat < num_features; feat++) {
l_ind = 0;
r_ind = 0;
for (i = 0; i < n; ++i) {
if (keys[data[feat][first+i]->key] == 1) {
holder[l_ind] = data[feat][first+i];
l_ind++;
}
else if (keys[data[feat][first+i]->key] == 0) {
holder[n_l+r_ind] = data[feat][first+i];
r_ind++;
}
}
for (i = 0; i < n; ++i)
data[feat][first+i] = holder[i];
}
/*
/////////////////////////////////////////////////////
for (feat = 0; feat < num_features; feat++) {
for (i = first; i < row; ++i) {
if (data[feat][i]->val[feat] > data[feat][i+1]->val[feat]) {
printf("POST SORT FAILED, i = %d, feat = %d, first = %d", i, feat, first);
printf("%f then %f\n", data[feat][i]->val[feat], data[feat][i+1]->val[feat]);
abort();
}
}
for (i = row+1; i < last; ++i) {
if (data[feat][i]->val[feat] > data[feat][i+1]->val[feat]) {
printf("POST SORT FAILED, i = %d, feat = %d, first = %d", i, feat, first);
printf("%f then %f\n", data[feat][i]->val[feat], data[feat][i+1]->val[feat]);
abort();
}
}
}
printf("Correctly POST Sorted\n");
printf("CHECK:%f \n", data[42][12696]->val[42]);
printf("CHECK:%f \n", data[42][12697]->val[42]);
////////////////////////////////////////////////////////
*/
free(keys);
free(holder);
int p;
MPI_Comm_size(MPI_COMM_WORLD, &p);
int remainder = (D-1)%p;
int fpp = (D-1)/p;
if (out.R < remainder)
node->index = out.R*(fpp + 1) + best_feat;
else
node->index = remainder*(fpp + 1) + (out.R-remainder)*fpp + best_feat;
node->threshold = threshold;
if (rank == 0)
printf("Best feature: %d, Best thresh: %f, Impurity %f, n_l %d\n", node->index, node->threshold, out.P, n_l);
//Create right and left children
Node *l = malloc(sizeof(Node));
Node *r = malloc(sizeof(Node));
l->parent = node;
r->parent = node;
l->right = NULL;
l->left = NULL;
r->right = NULL;
r->left = NULL;
node->left = l;
node->right = r;
//Make MPI Barrier, then begin next round; check level, entropy, or purity to decide
//printf("LEFT\n");
ParallelSplit(l, data, n_l, first, level+1, rank, num_features);
//printf("RIGHT\n");
ParallelSplit(r, data, n_r, first_r, level+1, rank, num_features);
return;
}
void BuildTree(Node *root, double **data, int n) {
/* Wrapper function to initiate decision tree construction
*/
SplitNode(root, data, n, 0, 0);
return;
}
void TreeFree(Node *node) {
/* Recursively frees dynamically allocated trees
*/
if (node == NULL)
return;
TreeFree(node->left);
TreeFree(node->right);
free(node);
return;
}
double TestPoint(Node *root, double *data) {
int ind;
Node *node = root;
while (node->left != NULL) {
ind = node->index;
if (data[ind] <= node->threshold)
node = node->left;
else
node = node->right;
}
return node->label;
}
void TreePrint(Node *node, int level) {
if (!node)
return;
TreePrint(node->left, level+1);
printf("Node: level %d\n", level);
printf("Index: %d\n", node->index);
printf("Threshold: %f\n", node->threshold);
printf("Class: %f", node->label);
printf("\n");
TreePrint(node->right, level+1);
return;
}