-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmktree.c
1605 lines (1433 loc) · 55.9 KB
/
mktree.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
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/****************************************************************/
/* Copyright 1993, 1994 */
/* Johns Hopkins University */
/* Department of Computer Science */
/****************************************************************/
/* Contact : murthy@cs.jhu.edu */
/****************************************************************/
/* File Name : mktree.c */
/* Author : Sreerama K. Murthy */
/* Last modified : September 1994 */
/* (unnormalize_hyperplane corrected - 9/21/94).*/
/* Contains modules : main */
/* allocate_structures */
/* deallocate_structures */
/* build_tree */
/* build_subtree */
/* axis_parallel_split */
/* oblique_split */
/* cross_validate */
/* print_log_and_exit */
/* mktree_help */
/* Uses modules in : oc1.h */
/* util.c */
/* load_data.c */
/* classify.c */
/* train_util.c */
/* classify_util.c */
/* compute_impurity.c */
/* perturb.c */
/* prune.c */
/* Is used by modules in : None. */
/* Remarks : This file has the OC1 modules, that */
/* build the decision trees recursively. */
/****************************************************************/
#include "oc1.h"
char *pname;
char dt_file[LINESIZE],animation_file[LINESIZE],train_data[LINESIZE];
char test_data[LINESIZE],misclassified_data[LINESIZE];
char log_file[LINESIZE];
int no_of_dimensions=0,no_of_coeffs,no_of_categories=0;
int no_of_restarts=20,no_of_folds=0;
int normalize = TRUE;
int unlabeled = FALSE,verbose=FALSE,veryverbose = FALSE;
int order_of_perturbation = SEQUENTIAL;
int oblique = TRUE;
int axis_parallel = TRUE;
int cart_mode = FALSE;
int coeff_modified = FALSE;
int cycle_count=0;
int *left_count=NULL, *right_count=NULL;
int max_no_of_random_perturbations = 5;
int no_of_stagnant_perturbations,no_of_missing_values=0;
int no_of_train_points=0,no_of_test_points=0;
int stop_splitting();
float compute_impurity();
float *coeff_array,*modified_coeff_array,*best_coeff_array;
float prune_portion=0.1;
float myabs(),ap_bias=1.0;
float zeroing_tendency = 0.1;
float *attribute_min,*attribute_avg,*attribute_sdev;
double *temp_val;
void srand48();
struct unidim *candidates;
struct test_outcome estimate_accuracy();
FILE *animationfile=NULL;
FILE *perturb_file=NULL;
POINT **train_points=NULL,**test_points=NULL;
/************************************************************************/
/* Module name : main */
/* Functionality : Accepts user's options as input, sets control */
/* variables accordingly, and invokes the appro- */
/* priate data-reading, tree-building and */
/* classifying routines. */
/* Parameters : argc,argv : See any standard C textbook for details. */
/* Returns : nothing. */
/* Calls modules : mktree_help */
/* print_log_and_exit */
/* read_data (load_data.c) */
/* allocate_structures */
/* build_tree */
/* write_tree (train_util.c) */
/* cross_validate */
/* deallocate_structures */
/* read_tree (classify_util.c) */
/* estimate_accuracy (classify.c) */
/* classify (classify.c) */
/* Is called by modules : None. */
/************************************************************************/
main (argc, argv)
int argc;
char *argv[];
{
extern char *optarg;
extern int optind;
int c1,leaf_count(),tree_depth();
int i,j,no_of_correctly_classified_test_points;
struct tree_node *root = NULL,*build_tree(),*read_tree();
struct test_outcome result;
float accuracy;
strcpy(train_data,"\0");
strcpy(test_data,"\0");
strcpy(dt_file,"\0");
strcpy(animation_file,"\0");
strcpy(misclassified_data,"\0");
strcpy(log_file,"oc1.log");
pname = argv[0];
if (argc==1) usage(pname);
while ((c1 =
getopt (argc, argv, "aA:b:Bc:d:D:i:j:Kl:m:M:n:Nop:r:R:s:t:T:uvV:"))
!= EOF)
switch (c1)
{
case 'a': /*Axis parallel splits only */
oblique = FALSE;
break;
case 'A': /*File into which all the locations of the
hyperplanes considered by OC1 are output.
The program "display" can be used to see an
animation of the tree building process, using
this output. */
strcpy(animation_file,optarg);
break;
case 'b': /* This option specifies the bias the user has
toward axis parallel splits, denoted by ap_bias.
ap_bias is a positive number greater than or equal
to 1.0. An oblique split will be preferred to an
axis parallel split only if
axis parallel impurity / oblique impurity > ap_bias */
ap_bias = atof(optarg);
if (ap_bias < 1.0) ap_bias = 1.0;
break;
case 'B':
if (oblique == FALSE) usage(pname);
order_of_perturbation = BEST_FIRST;
break;
case 'c':
no_of_categories = atoi (optarg);
if (no_of_categories <= 0) usage(pname);
break;
case 'd':
no_of_dimensions = atoi (optarg);
if (no_of_dimensions <= 0) usage(pname);
break;
case 'D': /*The decision tree file.
If OC1 is used in the training mode, the
decision tree is output to this file.
In testing mode, the decision tree is read
from this file. */
strcpy(dt_file,optarg);
break;
case 'i': /*No. of restarts at each node of the tree.
Retained for compatibility with previous
versions of OC1.*/
if (oblique == FALSE) usage(pname);
no_of_restarts = atoi (optarg);
if (no_of_restarts <= 0) usage(pname);
break;
case 'j': /*Maximum number of random perturbations tried when
stuck in a local minimum. */
if (oblique == FALSE) usage(pname);
max_no_of_random_perturbations = atoi(optarg);
if (max_no_of_random_perturbations < 0) usage(pname);
break;
case 'K': /*Run in CART Multivariate mode */
cart_mode = TRUE;
break;
case 'l': /*File into which a log of the running of
OC1 is written. Default=oc1.log*/
strcpy(log_file,optarg);
break;
case 'm': /*Maximum number of random perturbations tried when
stuck in a local minimum. */
if (oblique == FALSE) usage(pname);
max_no_of_random_perturbations = atoi(optarg);
if (max_no_of_random_perturbations < 0) usage(pname);
break;
case 'M': /*File into which the test instances on which the
classifier fails are written. */
strcpy(misclassified_data,optarg);
break;
case 'n':
no_of_train_points = atoi (optarg);
if (no_of_train_points < 0) usage(pname);
break;
case 'N': /*Do not normalize attributes before inducing each
oblique hyperplane. */
normalize = FALSE;
break;
case 'o': /*Oblique splits only */
axis_parallel = FALSE;
break;
case 'p':
prune_portion = atof(optarg);
if (prune_portion < 0 ||
prune_portion >= 1) usage(pname);
break;
case 'r': /*Number of restarts at each node of the tree. */
if (oblique == FALSE) usage(pname);
no_of_restarts = atoi (optarg);
if (no_of_restarts <= 0) usage(pname);
break;
case 'R':
if (oblique == FALSE) usage(pname);
order_of_perturbation = RANDOM;
cycle_count = atoi(optarg);
break;
case 's': /*Seed for the random number generator */
srand48(atol(optarg));
break;
case 't': /*Data for training. */
strcpy(train_data,optarg);
break;
case 'T': /*Data for testing. */
strcpy(test_data,optarg);
break;
case 'u': /*Test data is unlabeled. Classify it, and write*/
unlabeled = TRUE; /*the classified data to <test_data>.classified */
break;
case 'v':
if (verbose == TRUE) veryverbose = TRUE;
else verbose = TRUE;
break;
case 'V':
no_of_folds = atoi (optarg);
/* If this is nonzero, V-fold cross-validation is used
for estimating the accuracy.
Overrides the -T option.
This number can be -1, denoting "leave-one-out"
cross-validation. */
break;
default : usage(pname);
}
if (unlabeled == TRUE && !strlen(test_data)) usage(pname);
if (strlen(train_data))
{
if (strlen(test_data) || no_of_folds != 0)
{
j = unlabeled;
unlabeled = FALSE;
read_data(train_data,0);
unlabeled = j;
}
else
{
i = no_of_train_points;
j = unlabeled;
unlabeled = FALSE;
read_data(train_data,i);
/*this call loads training, and test point sets.
see the module header of read_data. */
unlabeled = j;
}
if (verbose)
{
printf("%d training examples loaded from %s.\n",
no_of_train_points,train_data);
if (no_of_folds == 0 && no_of_test_points != 0)
printf("%d testing examples loaded from %s.\n",
no_of_test_points,train_data);
if (no_of_missing_values)
printf("%d missing values filled with respective attribute means.\n",
no_of_missing_values);
printf("Attributes = %d, Classes = %d\n",
no_of_dimensions,no_of_categories);
}
allocate_structures(no_of_train_points);
if (no_of_folds == 0) /* No cross validation. */
{
if (!strlen(dt_file)) sprintf(dt_file,"%s.dt",train_data);
root = build_tree(train_points,no_of_train_points,dt_file);
}
else
{
if (no_of_folds == -1) no_of_folds = no_of_train_points;
if (no_of_folds <= 1 || no_of_folds > no_of_train_points) usage(pname);
cross_validate(train_points,no_of_train_points);
}
deallocate_structures(no_of_train_points);
if (no_of_folds != 0) print_log_and_exit();
}
if (strlen(test_data))
{
read_data(test_data,-1);
if (verbose)
{
printf("%d testing examples loaded from %s.\n",
no_of_test_points,test_data);
if (no_of_missing_values)
printf("%d missing values filled with respective attribute means.\n",
no_of_missing_values);
}
}
if (no_of_test_points)
{
if (root == NULL)
{
if ((root = read_tree(dt_file)) != NULL)
{ if (verbose) printf("Decision tree read from %s.\n",dt_file); }
else
{
fprintf(stderr,"Mktree: Cannot read %s.\n",dt_file);
print_log_and_exit();
}
}
if (unlabeled == TRUE)
{
char out_file[LINESIZE];
FILE *outfile;
sprintf(out_file,"%s.classified",test_data);
classify(test_points,no_of_test_points,root,out_file);
printf("Test instances with labels written to %s.\n", out_file);
}
else
{
result = estimate_accuracy (test_points,no_of_test_points,root);
printf("accuracy = %.2f\t#leaves = %.2f\tmax depth = %.2f\n",
result.accuracy,result.leaf_count,result.tree_depth);
if (verbose)
for (i=1;i<=no_of_categories;i++)
if (result.class[2*i] != 0)
printf("Category %d : accuracy = %.2f (%d/%d)\n",
i, 100.0 * result.class[2*i-1]/result.class[2*i],
result.class[2*i-1],result.class[2*i]);
}
}
else
{
result = estimate_accuracy (train_points,no_of_train_points,root);
printf("acc. on training set = %.2f\t#leaves = %.0f\tmax depth = %.0f\n",
result.accuracy,result.leaf_count,result.tree_depth);
if (verbose)
for (i=1;i<=no_of_categories;i++)
if (result.class[2*i] != 0)
printf("Category %d : accuracy = %.2f (%d/%d)\n",
i, 100.0 * result.class[2*i-1]/result.class[2*i],
result.class[2*i-1],result.class[2*i]);
}
print_log_and_exit();
}
/************************************************************************/
/* Module name : allocate_structures */
/* Functionality : Allocates space for some global data structures.*/
/* Parameters : no_of_points : size of the training dataset. */
/* Returns : nothing. */
/* Calls modules : vector (util.c) */
/* ivector (util.c) */
/* dvector (util.c) */
/* Is called by modules : main */
/************************************************************************/
allocate_structures(no_of_points)
int no_of_points;
{
int i;
no_of_coeffs = no_of_dimensions+1;
coeff_array = vector(1,no_of_coeffs);
modified_coeff_array = vector(1,no_of_coeffs);
best_coeff_array = vector(1,no_of_coeffs);
left_count = ivector(1,no_of_categories);
right_count = ivector(1,no_of_categories);
candidates = (struct unidim *)malloc((unsigned)no_of_points *
sizeof(struct unidim));
candidates -= 1;
attribute_min = vector(1,no_of_dimensions);
attribute_avg = vector(1,no_of_dimensions);
attribute_sdev = vector(1,no_of_dimensions);
temp_val = dvector(1,no_of_points);
}
/************************************************************************/
/* Module name : deallocate_structures */
/* Functionality : Frees space allocated to some global data structures.*/
/* Parameters : no_of_points : size of the training dataset. */
/* Returns : nothing. */
/* Calls modules : free_vector (util.c) */
/* free_ivector (util.c) */
/* free_dvector (util.c) */
/* Is called by modules : main */
/************************************************************************/
deallocate_structures(no_of_points)
int no_of_points;
{
free_vector(coeff_array,1,no_of_coeffs);
free_vector(modified_coeff_array,1,no_of_coeffs);
free_ivector(left_count,1,no_of_categories);
free_ivector(right_count,1,no_of_categories);
free_vector(best_coeff_array,1,no_of_coeffs);
free((char *)(candidates+1));
free_vector(attribute_min,1,no_of_dimensions);
free_vector(attribute_avg,1,no_of_dimensions);
free_vector(attribute_sdev,1,no_of_dimensions);
free_dvector(temp_val,1,no_of_points);
}
/************************************************************************/
/* Module name : Build_Tree */
/* Functionality : Top level tree to induce, prune and write a decision */
/* tree to a file. */
/* Parameters : points = array of training instances */
/* no_of_points = instance count */
/* dt_file = file into which the decision tree is to be */
/* written. */
/* Returns : Pointer to the root of the tree induced. */
/* Calls modules : build_subtree */
/* prune (prune.c) */
/* write_tree (train_util.c) */
/* allocate_point_array (load_data.c) */
/* Is called by modules : main */
/* cross_validate */
/* Important Variables used : */
/* Remarks : */
/************************************************************************/
struct tree_node *build_tree(points,no_of_points,dt_file)
struct point **points;
int no_of_points;
char *dt_file;
{
struct tree_node *prune(),*root,*build_subtree();
struct point **allocate_point_array(),**ptest_points = NULL;
struct point **train_points = NULL;
struct test_outcome result;
struct tree_node *proot;
int i,j,k,no_of_ptest_points,no_of_train_points;
/* initialize the animation file */
if (strlen(animation_file) && no_of_dimensions == 2 && no_of_folds == 0)
{
animationfile = fopen(animation_file,"w");
if (verbose)
{
printf("All hyperplane perturbations being written to %s.\n",
animation_file);
printf("Use the Display() program for animation.\n");
}
}
write_header(animationfile);
/* divide the training instances into a training set and a pruning set*/
no_of_ptest_points = (int)(no_of_points * prune_portion);
if (no_of_ptest_points)
{
no_of_train_points = no_of_points - no_of_ptest_points;
if (verbose) printf("%d randomly chosen instances kept away for pruning.\n\n",
no_of_ptest_points);
/* "randomly chosen" because the points are shuffled in Read_Data. */
train_points = allocate_point_array(train_points,no_of_train_points,0);
for (i=1;i<=no_of_train_points;i++)
{
for (j=1;j<=no_of_dimensions;j++)
train_points[i]->dimension[j] = points[i]->dimension[j];
train_points[i]->category = points[i]->category;
train_points[i]->val = points[i]->val;
}
ptest_points = allocate_point_array(ptest_points,no_of_ptest_points,0);
for (i=no_of_train_points+1;i<=no_of_points;i++)
{
k = i - no_of_train_points;
for (j=1;j<=no_of_dimensions;j++)
ptest_points[k]->dimension[j] = points[i]->dimension[j];
ptest_points[k]->category = points[i]->category;
ptest_points[k]->val = points[i]->val;
}
}
else
{
train_points = points;
no_of_train_points = no_of_points;
}
/* Build the tree recursively. */
root = build_subtree("\0",train_points,no_of_train_points);
if (root == NULL)
{
fprintf(stderr,"No split could be found with the current parameter settings.\n");
fprintf(stderr,"Try increasing the values of restarts and random jumps.\n");
print_log_and_exit();
}
else root->parent = NULL;
/* Prune.*/
if (prune_portion != 0)
proot = prune(root,ptest_points,no_of_ptest_points);
else proot = root;
/* Write the trees to files. */
if (strlen(dt_file))
{
write_tree(proot,dt_file);
if (proot == root) /* No pruning was done. */
printf("Unpruned decision tree written to %s.\n",dt_file);
else
{
char temp_str[LINESIZE];
printf("Pruned decision tree written to %s.\n",dt_file);
sprintf(temp_str,"%s.unpruned",dt_file);
write_tree(root,temp_str);
printf("Unpruned decision tree written to %s.\n",temp_str);
root = proot;
}
}
return(root);
}
/************************************************************************/
/* Module name : build_subtree */
/* Functionality : Recursively builds a decision tree. i.e., finds */
/* the best (heuristic) hyperplane separating the */
/* given set of points, and recurses on both sides */
/* of the hyperplane. The best axis-parallel split */
/* is considered if -o option is not chosen, */
/* before computing oblique splits. */
/* Parameters : node_str : Label to be assigned to the decision tree */
/* node to be created. */
/* cur_points : array of pointers to the points under */
/* consideration. */
/* cur_no_of_points : Number of points. */
/* Returns : pointer to the decision tree node created. */
/* NULL, if a node couldn't be created. */
/* Calls modules : set_counts (compute_impurity.c) */
/* compute_impurity (compute_impurity.c) */
/* axis_parallel_split */
/* vector (util.c) */
/* oblique_split */
/* free_vector (util.c) */
/* error (util.c) */
/* find_values (perturb.c) */
/* largest_element (compute_impurity.c) */
/* build_subtree */
/* Is called by modules : main */
/* build_tree */
/* build_subtree */
/* cross_validate */
/* Important Variables used : initial_impurity: "inherent" impurity in*/
/* the point set under consideration. ie., */
/* impurity when the separating hyperplane */
/* lies on one side of the point set. */
/* If any amount of perturbations (bounded */
/* by the parametric settings) can not */
/* result in a hyperplane that has a lesser*/
/* impurity than this value, no new tree */
/* node is created. */
/************************************************************************/
struct tree_node *build_subtree(node_str,cur_points,cur_no_of_points)
char *node_str;
POINT **cur_points;
int cur_no_of_points;
{
struct tree_node *cur_node;
struct tree_node *build_subtree(),*create_tree_node();
POINT **lpoints = NULL,**rpoints = NULL;
int i,lindex,rindex,lpt,rpt;
float oblique_split(),axis_parallel_split(),cart_split();
float initial_impurity,cur_impurity;
char lnode_str[MAX_DT_DEPTH],rnode_str[MAX_DT_DEPTH];
/* Validation checks */
if (cur_no_of_points <= TOO_SMALL_FOR_ANY_SPLIT) return(NULL);
if (strlen(node_str) > MAX_DT_DEPTH)
{
fprintf(stderr,"Tree growing aborted along this branch. \n");
fprintf(stderr,"Depth cannot be more than MAX_DT_DEPTH, set in oc1.h.\n");
return(NULL);
}
set_counts(cur_points,cur_no_of_points,0);
cur_impurity = initial_impurity = compute_impurity(cur_no_of_points);
if (cur_impurity == 0.0) return(NULL);
if (cart_mode)
{
cur_impurity = axis_parallel_split(cur_points,cur_no_of_points);
if (cur_impurity && (strlen(node_str) == 0 ||
cur_no_of_points > TOO_SMALL_FOR_OBLIQUE_SPLIT))
cur_impurity = cart_split(cur_points,cur_no_of_points,node_str);
}
else
{
if (axis_parallel)
cur_impurity = axis_parallel_split(cur_points,cur_no_of_points);
if (cur_impurity && oblique && cur_no_of_points > TOO_SMALL_FOR_OBLIQUE_SPLIT)
{
float *ap_coeff_array,oblique_impurity;
ap_coeff_array = vector(1,no_of_coeffs);
for (i=1;i<=no_of_coeffs;i++) ap_coeff_array[i] = coeff_array[i];
if (normalize) normalize_data(cur_points,cur_no_of_points);
oblique_impurity = oblique_split(cur_points,cur_no_of_points,node_str);
if (normalize)
{
unnormalize_data(cur_points,cur_no_of_points);
unnormalize_hyperplane();
for (i=1;i<=no_of_dimensions;i++) attribute_min[i] = 0;
}
if (ap_bias * oblique_impurity >= cur_impurity)
{
for (i=1;i<=no_of_coeffs;i++) coeff_array[i] = ap_coeff_array[i];
coeff_modified = TRUE;
}
else cur_impurity = oblique_impurity;
free_vector(ap_coeff_array,1,no_of_coeffs);
}
}
if (cur_impurity >= initial_impurity) return(NULL);
/*Can not find any split given current parameter settings. */
find_values(cur_points,cur_no_of_points);
set_counts(cur_points,cur_no_of_points,1);
if (verbose)
{
if (strlen(node_str)) printf("** \"%s\": ",node_str);
else printf("** Root: ");
printf("Left:[");
for (i=1;i<no_of_categories;i++) printf("%d,",left_count[i]);
printf("%d] Right:[",left_count[no_of_categories]);
for (i=1;i<no_of_categories;i++) printf("%d,",right_count[i]);
printf("%d]\n",right_count[no_of_categories]);
}
for (i=1,lpt=0, rpt=0;i<=no_of_categories;i++)
{ lpt += left_count[i]; rpt += right_count[i]; }
cur_node = create_tree_node();
cur_node->no_of_points = cur_no_of_points;
strcpy(cur_node->label,node_str);
write_hp(cur_node,animationfile);
if (cur_impurity == 0) return(cur_node);
lpoints = rpoints = NULL;
if (left_count[cur_node->left_cat] != lpt)
/* Left region is not homogeneous. */
{
if ((lpoints = (POINT **) malloc ((unsigned)lpt * sizeof(POINT *)))
== NULL) error("BUILD_DT : Memory allocation failure.");
lpoints--;
lindex = 0;
}
if (right_count[cur_node->right_cat] != rpt)
/* Right region is not homogeneous. */
{
if ((rpoints = (POINT **) malloc ((unsigned)rpt * sizeof(POINT *)))
== NULL) error("BUILD_DT : Memory allocation failure.");
rpoints--;
rindex = 0;
}
for (i=1;i<=cur_no_of_points;i++)
if (cur_points[i]->val < 0 )
{ if (lpoints != NULL) lpoints[++lindex] = cur_points[i];}
else
{ if (rpoints != NULL) rpoints[++rindex] = cur_points[i];}
if (lpoints != NULL)
{
strcpy(lnode_str,node_str);
strcat(lnode_str,"l");
cur_node->left = build_subtree(lnode_str,lpoints,lpt);
if (cur_node->left != NULL) (cur_node->left)->parent = cur_node;
free((char *)(lpoints+1));
}
if (rpoints != NULL)
{
strcpy(rnode_str,node_str);
strcat(rnode_str,"r");
cur_node->right = build_subtree(rnode_str,rpoints,rpt);
if (cur_node->right != NULL) (cur_node->right)->parent = cur_node;
free((char *)(rpoints+1));
}
return(cur_node);
}
/************************************************************************/
/* Module name : Cart_Split */
/* Functionality : Implements the CART-Linear Combinations (Breiman et */
/* al, 1984, Chapter 5) hill climbing coefficient */
/* perturbation algorithm. */
/* Parameters : cur_points: Array of pointers to the current points. */
/* cur_no_of_points: */
/* cur_label: Label of the tree node for which current */
/* split is being induced. */
/* Returns : impurity of the induced hyperplane. */
/* Calls modules : cart_perturb (perturb.c) */
/* cart_perturb_constant (perturb.c) */
/* write_hyperplane */
/* find_values (compute_impurity.c) */
/* set_counts (compute_impurity.c) */
/* Is called by modules : build_subtree */
/* Remarks : See the CART book for a description of the algorithm. */
/************************************************************************/
float cart_split(cur_points,cur_no_of_points,cur_label)
POINT **cur_points;
int cur_no_of_points;
char *cur_label;
{
int cur_coeff;
float cur_error,new_error,prev_impurity,myabs();
float cart_perturb(),cart_perturb_constant();
/*Starts with the best axis parallel hyperplane. */
write_hyperplane(animationfile,cur_label);
find_values(cur_points,cur_no_of_points);
set_counts(cur_points,cur_no_of_points,1);
cur_error = compute_impurity(cur_no_of_points);
cycle_count = 0;
while (TRUE)
{
if (cur_error == 0.0) break;
cycle_count++;
if (cycle_count != 1) prev_impurity = cur_error;
for (cur_coeff = 1; cur_coeff < no_of_coeffs;cur_coeff++)
{
new_error = cart_perturb(cur_points,cur_no_of_points,cur_coeff,cur_error);
if (alter_coefficients(cur_points,cur_no_of_points))
{
if (veryverbose)
printf("\tCART hill climbing for coeff. %d. impurity %.3f -> %.3f\n",
cur_coeff,cur_error,new_error);
cur_error = new_error;
write_hyperplane(animationfile,cur_label);
if (cur_error == 0) break;
}
}
if (cur_error != 0)
{
new_error = cart_perturb_constant(cur_points,cur_no_of_points,cur_error);
if (alter_coefficients(cur_points,cur_no_of_points))
{
if (veryverbose)
printf("\tCART hill climbing for coeff. %d. impurity %.3f -> %.3f\n",
no_of_coeffs,cur_error,new_error);
cur_error = new_error;
write_hyperplane(animationfile,cur_label);
}
}
if (cycle_count > MAX_CART_CYCLES)
/* Cart multivariate algorithm can get stuck in some domains.
Arbitrary tie breaker. */
break;
if (cycle_count != 1 && myabs(prev_impurity - cur_error)<TOLERANCE)
break;
}
return(cur_error);
}
/************************************************************************/
/* Module name : Create_Tree_Node */
/* Functionality : Creates a tree node structure, and sets some fields. */
/* Parameters : None. */
/* Returns : Pointer to the tree node created. */
/* Calls modules : error (util.c) */
/* vector (util.c) */
/* ivector (util.c) */
/* largest_element (compute_impurity.c) */
/* Is called by modules : build_subtree */
/* Remarks : Assumes that the left_count, right_count arrays and the */
/* coeff_array are set correctly. */
/************************************************************************/
struct tree_node *create_tree_node()
{
struct tree_node *cur_node;
int i, largest_element();
cur_node = (struct tree_node *)malloc(sizeof(struct tree_node));
if (cur_node == NULL) error("Create_Tree_Node : Memory allocation failure.");
cur_node->coefficients = vector(1,no_of_coeffs);
for (i=1;i<=no_of_coeffs;i++) cur_node->coefficients[i] = coeff_array[i];
cur_node->left_count = ivector(1,no_of_categories);
cur_node->right_count = ivector(1,no_of_categories);
for (i=1;i<=no_of_categories;i++)
{
cur_node->left_count[i] = left_count[i];
cur_node->right_count[i] = right_count[i];
}
cur_node->parent = cur_node->left = cur_node->right = NULL;
cur_node->left_cat = largest_element(left_count,no_of_categories);
cur_node->right_cat = largest_element(right_count,no_of_categories);
return(cur_node);
}
/************************************************************************/
/* Module name : oblique_split */
/* Functionality : Attempts to find the hyperplane, at an unrestri-*/
/* cted orientation, that best separates */
/* "cur_points" (minimizing the current impurity */
/* measure), using hill climbing and randomization.*/
/* Parameters : cur_points : array of pointers to the points (samples) */
/* under consideration. */
/* cur_no_of_points : number of points under consideration.*/
/* Returns : the impurity measure of the best hyperplane found. */
/* The hyperplane itself is returned through the global */
/* array "coeff_array". */
/* Calls modules : generate_random_hyperplane */
/* find_values (perturb.c) */
/* set_counts (compute_impurity.c) */
/* compute_impurity (compute_impurity.c) */
/* myrandom (util.c) */
/* suggest_perturbation (perturb.c) */
/* perturb_randomly (perturb.c) */
/* Is called by modules : build_subtree */
/************************************************************************/
float oblique_split(cur_points,cur_no_of_points,cur_label)
POINT **cur_points;
int cur_no_of_points;
char *cur_label;
{
char c;
int i,j,old_nsp,restart_count = 1;
int alter_coefficients();
int cur_coeff,improved_in_this_cycle,best_coeff_to_improve;
float perturb_randomly();
float cur_error,old_cur_error,best_cur_error,least_error;
float x,changeinval;
float new_error,suggest_perturbation();
/*Start with the best axis parallel hyperplane if axis_parallel is true.
Otherwise start with a random hyperplane. */
if (axis_parallel != TRUE )
{
generate_random_hyperplane(coeff_array,no_of_coeffs,MAX_COEFFICIENT);
coeff_modified = TRUE;
}
find_values(cur_points,cur_no_of_points);
set_counts(cur_points,cur_no_of_points,1);
least_error = cur_error = compute_impurity(cur_no_of_points);
for (i=1;i<=no_of_coeffs;i++) best_coeff_array[i] = coeff_array[i];
write_hyperplane(animationfile,cur_label);
/* Repeat this loop once for every restart*/
while (least_error != 0.0 && restart_count <= no_of_restarts)
{
if (veryverbose)
printf(" Restart %d: Initial Impurity = %.3f\n",restart_count,cur_error);
no_of_stagnant_perturbations = 0;
if (order_of_perturbation == RANDOM)
{
if (cycle_count <= 0) cycle_count = 10 * no_of_coeffs;
for (i=1;i<=cycle_count;i++)
{
if (cur_error == 0.0) break;
cur_coeff = 0;
while (!cur_coeff)
cur_coeff = (int)myrandom(1.0,(float)(no_of_coeffs+1));
new_error = suggest_perturbation(cur_points,cur_no_of_points,
cur_coeff,cur_error);
if (new_error <= cur_error &&
alter_coefficients(cur_points,cur_no_of_points))
{
if (veryverbose)
printf("\thill climbing for coeff. %d. impurity %.3f -> %.3f\n",
cur_coeff,cur_error,new_error);
cur_error = new_error;
improved_in_this_cycle = TRUE;
write_hyperplane(animationfile,cur_label);
if (cur_error == 0) break;
}
else /*Try improving in a random direction*/
{
improved_in_this_cycle = FALSE;
j = 0;
while (cur_error != 0 &&
!improved_in_this_cycle &&
++j<=max_no_of_random_perturbations)
{
new_error = perturb_randomly
(cur_points,cur_no_of_points,cur_error);
if (alter_coefficients(cur_points,cur_no_of_points))
{
if (veryverbose)
printf("\trandom jump. impurity %.3f -> %.3f\n",
cur_error,new_error);
cur_error = new_error;
improved_in_this_cycle = TRUE;
write_hyperplane(animationfile,cur_label);
}
}
}
}
}
else /* best_first or sequential orders of perturbation.*/
{
improved_in_this_cycle = TRUE;
cycle_count = 0;
while (improved_in_this_cycle)
{
if (cur_error == 0.0) break;
cycle_count++;
improved_in_this_cycle = FALSE;
if (order_of_perturbation == BEST_FIRST)
{
best_cur_error = HUGE;
best_coeff_to_improve = 1;
old_nsp = no_of_stagnant_perturbations;
}
for (cur_coeff = 1; cur_coeff < no_of_coeffs;cur_coeff++)
{
new_error = suggest_perturbation(cur_points,cur_no_of_points,
cur_coeff,cur_error);
if (order_of_perturbation == BEST_FIRST)
{
if (new_error < best_cur_error)
{
best_cur_error = new_error;
best_coeff_to_improve = cur_coeff;
}
no_of_stagnant_perturbations = old_nsp;
if (best_cur_error == 0) break;
}
else if (new_error <= cur_error &&
alter_coefficients(cur_points,cur_no_of_points))
{
if (veryverbose)
printf("\thill climbing for coeff. %d. impurity %.3f -> %.3f\n",
cur_coeff,cur_error,new_error);
cur_error = new_error;
improved_in_this_cycle = TRUE;
write_hyperplane(animationfile,cur_label);
if (cur_error == 0) break;
}
}
if (order_of_perturbation == BEST_FIRST
&& best_cur_error <= cur_error)
{
cur_coeff = best_coeff_to_improve;
new_error = suggest_perturbation(cur_points,cur_no_of_points,
cur_coeff,cur_error);
if (alter_coefficients(cur_points,cur_no_of_points))
{
if (veryverbose)
printf("\thill climbing for coeff. %d. impurity %.3f -> %.3f\n",
cur_coeff,cur_error,new_error);