BoostedDecisionTree.pm untested

filter: Statementstmt 0.0% 0 / 512 Branchbran 0.0% 0 / 94 Conditioncond 0.0% 0 / 13 MC/DCmcdc 0.0% 0 / 8 Subroutinesub 0.0% 0 / 26 Podpod 0.0% 0 / 21 totaltotal 0.0% 0 / 674 CC 48 SCAR 48.9
CC
48
Cov
0%
construct_cascade_of_trees
342.0
get_training_data_for_base_tree
210.0
evaluate_one_stage_of_cascade
56.0
CRAP 132.7
1 package Algorithm::BoostedDecisionTree;
2  
3 #--------------------------------------------------------------------------------------
4 # Copyright (c) 2017 Avinash Kak. All rights reserved. This program is free
5 # software. You may modify and/or distribute it under the same terms as Perl itself.
6 # This copyright notice must remain attached to the file.
7 #
8 # Algorithm::BoostedDecisionTree is a Perl module for boosted decision-tree based
9 # classification of multidimensional data.
10 # -------------------------------------------------------------------------------------
11  
12 #use lib 'blib/lib', 'blib/arch';
13  
14 #use 5.10.0;
15 use strict;
16 use warnings;
17 use Carp;
18 use Algorithm::DecisionTree 3.43;
19 use List::Util qw(reduce min max);
20  
21 our $VERSION = '3.43';
22  
23 @Algorithm::BoostedDecisionTree::ISA = ('Algorithm::DecisionTree');
24  
25 ############################################ Constructor ##############################################
26 sub new {
27 my ($class, %args) = @_;
28 my @params = keys %args;
29 croak "\nYou have used a wrong name for a keyword argument --- perhaps a misspelling\n"
30 if check_for_illegal_params(@params) == 0;
31 my %dtargs = %args;
32 delete $dtargs{how_many_stages};
33 my $instance = Algorithm::DecisionTree->new(%dtargs);
34 bless $instance, $class;
35 $instance->{_how_many_stages} = $args{how_many_stages} || undef;
36 $instance->{_stagedebug} = $args{stagedebug} || 0;
37 $instance->{_training_samples} = {map {$_ => []} 0..$args{how_many_stages}};
38 $instance->{_all_trees} = {map {$_ => Algorithm::DecisionTree->new(%dtargs)} 0..$args{how_many_stages}};
39 $instance->{_root_nodes} = {map {$_ => undef} 0..$args{how_many_stages}};
40 $instance->{_sample_selection_probs} = {map {$_ => {}} 0..$args{how_many_stages}};
41 $instance->{_trust_factors} = {map {$_ => undef} 0..$args{how_many_stages}};
42 $instance->{_misclassified_samples} = {map {$_ => []} 0..$args{how_many_stages}};
43 $instance->{_classifications} = undef;
44 $instance->{_trust_weighted_decision_classes} = undef;
45 bless $instance, $class;
46 }
47  
48 ############################################## Methods #################################################
49 sub get_training_data_for_base_tree {
50 my $self = shift;
51 die("Aborted. get_training_data_csv() is only for CSV files") unless $self->{_training_datafile} =~ /\.csv$/;
52 my %class_names = ();
53 my %all_record_ids_with_class_labels;
54 my $firstline;
55 my %data_hash;
56 $|++;
57 open FILEIN, $self->{_training_datafile};
58 my $record_index = 0;
59 my $firsetline;
60 while (<FILEIN>) {
61 next if /^[ ]*\r?\n?$/;
62 $_ =~ s/\r?\n?$//;
63 my $record = $self->{_csv_cleanup_needed} ? cleanup_csv($_) : $_;
64 if ($record_index == 0) {
65 $firstline = $record;
66 $record_index++;
67 next;
68 }
69 my @parts = split /,/, $record;
70 my $classname = $parts[$self->{_csv_class_column_index}];
71 $class_names{$classname} = 1;
72 my $record_label = shift @parts;
73 $record_label =~ s/^\s*\"|\"\s*$//g;
74 $data_hash{$record_label} = \@parts;
75 $all_record_ids_with_class_labels{$record_label} = $classname;
76 print "." if $record_index % 10000 == 0;
77 $record_index++;
78 }
79 close FILEIN;
80 $|--;
81 $self->{_how_many_total_training_samples} = $record_index - 1; # must subtract 1 for the header record
82 print "\n\nTotal number of training samples: $self->{_how_many_total_training_samples}\n" if $self->{_debug1};
83 my @all_feature_names = split /,/, substr($firstline, index($firstline,','));
84 my $class_column_heading = $all_feature_names[$self->{_csv_class_column_index}];
85 my @feature_names = map {$all_feature_names[$_]} @{$self->{_csv_columns_for_features}};
86 my %class_for_sample_hash = map {"sample_" . $_ => "$class_column_heading=" . $data_hash{$_}->[$self->{_csv_class_column_index} - 1 ] } keys %data_hash;
87 my @sample_names = map {"sample_$_"} keys %data_hash;
88 my %feature_values_for_samples_hash = map {my $sampleID = $_; "sample_" . $sampleID => [map {my $fname = $all_feature_names[$_]; $fname . "=" . eval{$data_hash{$sampleID}->[$_-1] =~ /^\d+$/ ? sprintf("%.1f", $data_hash{$sampleID}->[$_-1] ) : $data_hash{$sampleID}->[$_-1] } } @{$self->{_csv_columns_for_features}} ] } keys %data_hash;
89 my %features_and_values_hash = map { my $a = $_; {$all_feature_names[$a] => [ map {my $b = $_; $b =~ /^\d+$/ ? sprintf("%.1f",$b) : $b} map {$data_hash{$_}->[$a-1]} keys %data_hash ]} } @{$self->{_csv_columns_for_features}};
90 my @all_class_names = sort keys %{ {map {$_ => 1} values %class_for_sample_hash } };
91 $self->{_number_of_training_samples} = scalar @sample_names;
92 if ($self->{_debug2}) {
93 print "\nDisplaying features and their values for entire training data:\n\n";
94 foreach my $fname (keys %features_and_values_hash) {
95 print " $fname => @{$features_and_values_hash{$fname}}\n";
96 }
97 }
98 my %features_and_unique_values_hash = ();
99 my %feature_values_how_many_uniques_hash = ();
100 my %numeric_features_valuerange_hash = ();
101 my $numregex = '[+-]?\ *(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?';
102 foreach my $feature (keys %features_and_values_hash) {
103 my %seen = ();
104 my @unique_values_for_feature = grep {$_ if $_ ne 'NA' && !$seen{$_}++} @{$features_and_values_hash{$feature}};
105 $feature_values_how_many_uniques_hash{$feature} = scalar @unique_values_for_feature;
106 my $not_all_values_float = 0;
107 map {$not_all_values_float = 1 if $_ !~ /^$numregex$/} @unique_values_for_feature;
108 if ($not_all_values_float == 0) {
109 my @minmaxvalues = minmax(\@unique_values_for_feature);
110 $numeric_features_valuerange_hash{$feature} = \@minmaxvalues;
111 }
112 $features_and_unique_values_hash{$feature} = \@unique_values_for_feature;
113 }
114 $self->{_all_trees}->{0}->{_class_names} = \@all_class_names;
115 $self->{_all_trees}->{0}->{_feature_names} = \@feature_names;
116 $self->{_all_trees}->{0}->{_samples_class_label_hash} = \%class_for_sample_hash;
117 $self->{_all_trees}->{0}->{_training_data_hash} = \%feature_values_for_samples_hash;
118 $self->{_all_trees}->{0}->{_features_and_values_hash} = \%features_and_values_hash;
119 $self->{_all_trees}->{0}->{_features_and_unique_values_hash} = \%features_and_unique_values_hash;
120 $self->{_all_trees}->{0}->{_numeric_features_valuerange_hash} = \%numeric_features_valuerange_hash;
121 $self->{_all_trees}->{0}->{_feature_values_how_many_uniques_hash} = \%feature_values_how_many_uniques_hash;
122 $self->{_all_training_data} = \%feature_values_for_samples_hash;
123 $self->{_all_sample_names} = [sort {sample_index($a) cmp sample_index($b)} keys %feature_values_for_samples_hash];
124 if ($self->{_debug1}) {
125 print "\n\n=========================== data ingested for the base tree ==================================\n\n";
126 print "\nAll class names: @{$self->{_all_trees}->{0}->{_class_names}}\n";
127 print "\nEach sample data record:\n";
128 foreach my $kee (sort {sample_index($a) <=> sample_index($b)} keys %{$self->{_all_trees}->{0}->{_training_data_hash}}) {
129 print "$kee => @{$self->{_all_trees}->{0}->{_training_data_hash}->{$kee}}\n";
130 }
131 print "\nclass label for each data sample:\n";
132 foreach my $kee (sort {sample_index($a) <=> sample_index($b)} keys %{$self->{_all_trees}->{0}->{_samples_class_label_hash}}) {
133 print "$kee => $self->{_all_trees}->{0}->{_samples_class_label_hash}->{$kee}\n";
134 }
135 print "\nfeatures and the values taken by them:\n";
136 for my $kee (sort keys %{$self->{_all_trees}->{0}->{_features_and_values_hash}}) {
137 print "$kee => @{$self->{_all_trees}->{0}->{_features_and_values_hash}->{$kee}}\n";
138 }
139 print "\nnumeric features and their ranges:\n";
140 for my $kee (sort keys %{$self->{_all_trees}->{0}->{_numeric_features_valuerange_hash}}) {
141 print "$kee => @{$self->{_all_trees}->{0}->{_numeric_features_valuerange_hash}->{$kee}}\n";
142 }
143 print "\nunique values for the features:\n";
144 for my $kee (sort keys %{$self->{_all_trees}->{0}->{_features_and_unique_values_hash}}) {
145 print "$kee => @{$self->{_all_trees}->{0}->{_features_and_unique_values_hash}->{$kee}}\n";
146 }
147 print "\nnumber of unique values in each feature:\n";
148 for my $kee (sort keys %{$self->{_all_trees}->{0}->{_feature_values_how_many_uniques_hash}}) {
149 print "$kee => $self->{_all_trees}->{0}->{_feature_values_how_many_uniques_hash}->{$kee}\n";
150 }
151 }
152 }
153  
154 sub show_training_data_for_base_tree {
155 my $self = shift;
156 $self->{_all_trees}->{0}->show_training_data();
157 }
158  
159 sub calculate_first_order_probabilities_and_class_priors {
160 my $self = shift;
161 $self->{_all_trees}->{0}->calculate_first_order_probabilities();
162 $self->{_all_trees}->{0}->calculate_class_priors();
163 $self->{_sample_selection_probs}->{0} = {map { $_ => 1.0/@{$self->{_all_sample_names}} } @{$self->{_all_sample_names}}};
164 }
165  
166 sub construct_base_decision_tree {
167 my $self = shift;
168 $self->{_root_nodes}->{0} = $self->{_all_trees}->{0}->construct_decision_tree_classifier();
169 }
170  
171 sub display_base_decision_tree {
172 my $self = shift;
173 $self->{_root_nodes}->{0}->display_decision_tree(" ");
174 }
175  
176 sub construct_cascade_of_trees {
177 my $self = shift;
178 $self->{_training_samples}->{0} = $self->{_all_sample_names};
179 $self->{_misclassified_samples}->{0} = $self->evaluate_one_stage_of_cascade($self->{_all_trees}->{0}, $self->{_root_nodes}->{0});
180 if ($self->{_stagedebug}) {
181 $self->show_class_labels_for_misclassified_samples_in_stage(0);
182 print "\n\nSamples misclassified by base classifier: @{$self->{_misclassified_samples}->{0}}\n";
183 my $how_many = @{$self->{_misclassified_samples}->{0}};
184 print "\nNumber of misclassified samples: $how_many\n";
185 }
186 my $misclassification_error_rate = reduce {$a+$b} map {$self->{_sample_selection_probs}->{0}->{$_}} @{$self->{_misclassified_samples}->{0}};
187 print "\nMisclassification_error_rate for base classifier: $misclassification_error_rate\n" if $self->{_stagedebug};
188 $self->{_trust_factors}->{0} = 0.5 * log((1-$misclassification_error_rate)/$misclassification_error_rate);
189 print "\nBase class trust factor: $self->{_trust_factors}->{0}\n" if $self->{_stagedebug};
190 foreach my $stage_index (1 .. $self->{_how_many_stages} - 1) {
191 print "\n\n========================== Constructing stage indexed $stage_index =========================\n"
192 if $self->{_stagedebug};
193 $self->{_sample_selection_probs}->{$stage_index} = { map {$_ => $self->{_sample_selection_probs}->{$stage_index-1}->{$_} * exp(-1.0 * $self->{_trust_factors}->{$stage_index - 1} * (contained_in($_, @{$self->{_misclassified_samples}->{$stage_index - 1}}) ? -1.0 : 1.0) ) } @{$self->{_all_sample_names}} };
194 my $normalizer = reduce {$a + $b} values %{$self->{_sample_selection_probs}->{$stage_index}};
195 print "\nThe normalizer is: $normalizer\n" if $self->{_stagedebug};
196 map {$self->{_sample_selection_probs}->{$stage_index}->{$_} /= $normalizer} keys %{$self->{_sample_selection_probs}->{$stage_index}};
197 my @training_samples_this_stage = ();
198 my $sum_of_probs = 0.0;
199 foreach my $sample (sort {$self->{_sample_selection_probs}->{$stage_index}->{$b} <=> $self->{_sample_selection_probs}->{$stage_index}->{$a}} keys %{$self->{_sample_selection_probs}->{$stage_index}}) {
200 $sum_of_probs += $self->{_sample_selection_probs}->{$stage_index}->{$sample};
201 push @training_samples_this_stage, $sample if $sum_of_probs < 0.5;
202 last if $sum_of_probs > 0.5;
203 }
204 $self->{_training_samples}->{$stage_index} = [sort {sample_index($a) <=> sample_index($b)} @training_samples_this_stage];
205 if ($self->{_stagedebug}) {
206 print "\nTraining samples for stage $stage_index: @{$self->{_training_samples}->{$stage_index}}\n\n";
207 my $num_of_training_samples = @{$self->{_training_samples}->{$stage_index}};
208 print "\nNumber of training samples this stage $num_of_training_samples\n\n";
209 }
210 # find intersection of two sets:
211 my %misclassified_samples = map {$_ => 1} @{$self->{_misclassified_samples}->{$stage_index-1}};
212 my @training_samples_selection_check = grep $misclassified_samples{$_}, @{$self->{_training_samples}->{$stage_index}};
213 if ($self->{_stagedebug}) {
214 my @training_in_misclassified = sort {sample_index($a) <=> sample_index($b)} @training_samples_selection_check;
215 print "\nTraining samples in the misclassified set: @training_in_misclassified\n";
216 my $how_many = @training_samples_selection_check;
217 print "\nNumber_of_miscalssified_samples_in_training_set: $how_many\n";
218 }
219 my $dt_this_stage = Algorithm::DecisionTree->new('boostingmode');
220 $dt_this_stage->{_training_data_hash} = { map {$_ => $self->{_all_training_data}->{$_} } @{$self->{_training_samples}->{$stage_index}} };
221  
222 $dt_this_stage->{_class_names} = $self->{_all_trees}->{0}->{_class_names};
223 $dt_this_stage->{_feature_names} = $self->{_all_trees}->{0}->{_feature_names};
224 $dt_this_stage->{_entropy_threshold} = $self->{_all_trees}->{0}->{_entropy_threshold};
225 $dt_this_stage->{_max_depth_desired} = $self->{_all_trees}->{0}->{_max_depth_desired};
226 $dt_this_stage->{_symbolic_to_numeric_cardinality_threshold} = $self->{_all_trees}->{0}->{_symbolic_to_numeric_cardinality_threshold};
227 $dt_this_stage->{_samples_class_label_hash} = {map {$_ => $self->{_all_trees}->{0}->{_samples_class_label_hash}->{$_}} keys %{$dt_this_stage->{_training_data_hash}}};
228 $dt_this_stage->{_features_and_values_hash} = {map {$_ => []} keys %{$self->{_all_trees}->{0}->{_features_and_values_hash}}};
229 my $pattern = '(\S+)\s*=\s*(\S+)';
230 foreach my $sample (sort {sample_index($a) <=> sample_index($b)} keys %{$dt_this_stage->{_training_data_hash}}) {
231 foreach my $feature_and_value (@{$dt_this_stage->{_training_data_hash}->{$sample}}) {
232 $feature_and_value =~ /$pattern/;
233 my ($feature, $value) = ($1, $2);
234 push @{$dt_this_stage->{_features_and_values_hash}->{$feature}}, $value if $value ne 'NA';
235 }
236 }
237 $dt_this_stage->{_features_and_unique_values_hash} = {map {my $feature = $_; $feature => [sort keys %{{map {$_ => 1} @{$dt_this_stage->{_features_and_values_hash}->{$feature}}}}]} keys %{$dt_this_stage->{_features_and_values_hash}}};
238 $dt_this_stage->{_numeric_features_valuerange_hash} = {map {$_ => []} keys %{$self->{_all_trees}->{0}->{_numeric_features_valuerange_hash}}};
239 $dt_this_stage->{_numeric_features_valuerange_hash} = {map {my $feature = $_; $feature => [min(@{$dt_this_stage->{_features_and_unique_values_hash}->{$feature}}), max(@{$dt_this_stage->{_features_and_unique_values_hash}->{$feature}})]} keys %{$self->{_all_trees}->{0}->{_numeric_features_valuerange_hash}}};
240 if ($self->{_stagedebug}) {
241 print "\n\nPrinting features and their values in the training set:\n\n";
242 foreach my $kee (sort keys %{$dt_this_stage->{_features_and_values_hash}}) {
243 print "$kee => @{$dt_this_stage->{_features_and_values_hash}->{$kee}}\n";
244 }
245 print "\n\nPrinting unique values for features:\n\n";
246 foreach my $kee (sort keys %{$dt_this_stage->{_features_and_unique_values_hash}}) {
247 print "$kee => @{$dt_this_stage->{_features_and_unique_values_hash}->{$kee}}\n";
248 }
249 print "\n\nPrinting unique value ranges for features:\n\n";
250 foreach my $kee (sort keys %{$dt_this_stage->{_numeric_features_valuerange_hash}}) {
251 print "$kee => @{$dt_this_stage->{_numeric_features_valuerange_hash}->{$kee}}\n";
252 }
253 }
254 $dt_this_stage->{_feature_values_how_many_uniques_hash} = {map {$_ => undef} keys %{$self->{_all_trees}->{0}->{_features_and_unique_values_hash}}};
255 $dt_this_stage->{_feature_values_how_many_uniques_hash} = {map {$_ => scalar @{$dt_this_stage->{_features_and_unique_values_hash}->{$_}}} keys %{$self->{_all_trees}->{0}->{_features_and_unique_values_hash}}};
256 $dt_this_stage->calculate_first_order_probabilities();
257 $dt_this_stage->calculate_class_priors();
258 print "\n\n>>>>>>>Done with the initialization of the tree for stage $stage_index<<<<<<<<<<\n" if $self->{_stagedebug};
259 my $root_node_this_stage = $dt_this_stage->construct_decision_tree_classifier();
260 $root_node_this_stage->display_decision_tree(" ") if $self->{_stagedebug};
261  
262 $self->{_all_trees}->{$stage_index} = $dt_this_stage;
263 $self->{_root_nodes}->{$stage_index} = $root_node_this_stage;
264 $self->{_misclassified_samples}->{$stage_index} = $self->evaluate_one_stage_of_cascade($self->{_all_trees}->{$stage_index}, $self->{_root_nodes}->{$stage_index});
265 if ($self->{_stagedebug}) {
266 print "\nSamples misclassified by stage $stage_index classifier: @{$self->{_misclassified_samples}->{$stage_index}}\n";
267 printf("\nNumber of misclassified samples: %d\n", scalar @{$self->{_misclassified_samples}->{$stage_index}});
268 $self->show_class_labels_for_misclassified_samples_in_stage($stage_index);
269 }
270 my $misclassification_error_rate = reduce {$a+$b} map {$self->{_sample_selection_probs}->{$stage_index}->{$_}} @{$self->{_misclassified_samples}->{$stage_index}};
271 print "\nStage $stage_index misclassification_error_rate: $misclassification_error_rate\n" if $self->{_stagedebug};
272  
273 $self->{_trust_factors}->{$stage_index} = 0.5 * log((1-$misclassification_error_rate)/$misclassification_error_rate);
274 print "\nStage $stage_index trust factor: $self->{_trust_factors}->{$stage_index}\n" if $self->{_stagedebug};
275 }
276 }
277  
278 sub evaluate_one_stage_of_cascade {
279 my $self = shift;
280 my $trainingDT = shift;
281 my $root_node = shift;
282 my @misclassified_samples = ();
283 foreach my $test_sample_name (@{$self->{_all_sample_names}}) {
284 my @test_sample_data = @{$self->{_all_trees}->{0}->{_training_data_hash}->{$test_sample_name}};
285 print "original data in $test_sample_name:@test_sample_data\n" if $self->{_stagedebug};
286 @test_sample_data = map {$_ if $_ !~ /=NA$/} @test_sample_data;
287 print "$test_sample_name: @test_sample_data\n" if $self->{_stagedebug};
288 my %classification = %{$trainingDT->classify($root_node, \@test_sample_data)};
289 my @solution_path = @{$classification{'solution_path'}};
290 delete $classification{'solution_path'};
291 my @which_classes = keys %classification;
292 @which_classes = sort {$classification{$b} <=> $classification{$a}} @which_classes;
293 my $most_likely_class_label = $which_classes[0];
294 if ($self->{_stagedebug}) {
295 print "\nClassification:\n\n";
296 print " class probability\n";
297 print " ---------- -----------\n";
298 foreach my $which_class (@which_classes) {
299 my $classstring = sprintf("%-30s", $which_class);
300 my $valuestring = sprintf("%-30s", $classification{$which_class});
301 print " $classstring $valuestring\n";
302 }
303 print "\nSolution path in the decision tree: @solution_path\n";
304 print "\nNumber of nodes created: " . $root_node->how_many_nodes() . "\n";
305 }
306 my $true_class_label_for_test_sample = $self->{_all_trees}->{0}->{_samples_class_label_hash}->{$test_sample_name};
307 printf("%s: true_class: %s estimated_class: %s\n", $test_sample_name, $true_class_label_for_test_sample, $most_likely_class_label) if $self->{_stagedebug};
308 push @misclassified_samples, $test_sample_name if $true_class_label_for_test_sample ne $most_likely_class_label;
309 }
310 return [sort {sample_index($a) <=> sample_index($b)} @misclassified_samples];
311 }
312  
313 sub show_class_labels_for_misclassified_samples_in_stage {
314 my $self = shift;
315 my $stage_index = shift;
316 die "\nYou must first call 'construct_cascade_of_trees()' before invoking 'show_class_labels_for_misclassified_samples_in_stage()'" unless @{$self->{_misclassified_samples}->{0}} > 0;
317 my @classes_for_misclassified_samples = ();
318 my @just_class_labels = ();
319  
320 for my $sample (@{$self->{_misclassified_samples}->{$stage_index}}) {
321 my $true_class_label_for_sample = $self->{_all_trees}->{0}->{_samples_class_label_hash}->{$sample};
322 push @classes_for_misclassified_samples, sprintf("%s => %s", $sample, $true_class_label_for_sample);
323 push @just_class_labels, $true_class_label_for_sample;
324 }
325 print "\nSamples misclassified by the classifier for Stage $stage_index: @{$self->{_misclassified_samples}->{$stage_index}}\n";
326 my $how_many = @{$self->{_misclassified_samples}->{$stage_index}};
327 print "\nNumber of misclassified samples: $how_many\n";
328 print "\nShowing class labels for samples misclassified by stage $stage_index: ";
329 print "\nClass labels for samples: @classes_for_misclassified_samples\n";
330 my @class_names_unique = sort keys %{{map {$_ => 1} @just_class_labels}};
331 print "\nClass names (unique) for misclassified samples: @class_names_unique\n";
332 print "\nFinished displaying class labels for samples misclassified by stage $stage_index\n\n";
333 }
334  
335 sub display_decision_trees_for_different_stages {
336 my $self = shift;
337 print "\nDisplaying the decisions trees for all stages:\n\n";
338 foreach my $i (0..$self->{_how_many_stages}-1) {
339 print "\n\n============================= For stage $i ==================================\n\n";
340 $self->{_root_nodes}->{$i}->display_decision_tree(" ");
341 }
342 print "\n==================================================================================\n\n\n";
343 }
344  
345 sub classify_with_boosting {
346 my $self = shift;
347 my $test_sample = shift;
348 $self->{_classifications} = [map $self->{_all_trees}->{$_}->classify($self->{_root_nodes}->{$_}, $test_sample), 0..$self->{_how_many_stages}-1];
349 }
350  
351 sub display_classification_results_for_each_stage {
352 my $self = shift;
353 my @classifications = @{$self->{_classifications}};
354 die "You must first call 'classify_with_boosting()' before invoking 'display_classification_results_for_each_stage()'\n"
355 unless @classifications;
356 my @solution_paths = map $_->{'solution_path'}, @classifications;
357 foreach my $i (0..$self->{_how_many_stages}-1) {
358 print "\n\n============================= For stage $i ==================================\n\n";
359 my %classification = %{$classifications[$i]};
360 delete $classification{'solution_path'};
361 my @which_classes = keys %classification;
362 @which_classes = sort {$classification{$b} <=> $classification{$a}} @which_classes;
363 print "\nClassification:\n\n";
364 print "Classifier trust: $self->{_trust_factors}->{$i}\n\n";
365 print " class probability\n";
366 print " ---------- -----------\n";
367 foreach my $which_class (@which_classes) {
368 my $classstring = sprintf("%-30s", $which_class);
369 my $valuestring = sprintf("%-30s", $classification{$which_class});
370 print " $classstring $valuestring\n";
371 }
372  
373 print "\nSolution path in the decision tree: @{$solution_paths[$i]}\n";
374 printf("\nNumber of nodes created: %d\n", $self->{_root_nodes}->{$i}->how_many_nodes());
375 }
376 print "\n=================================================================================\n\n";
377 }
378  
379 sub trust_weighted_majority_vote_classifier {
380 my $self = shift;
381 my @classifications = @{$self->{_classifications}};
382 die "You must first call 'classify_with_boosting()' before invoking 'trust_weighted_majority_vote_classifier()'\n"
383 unless @classifications;
384 my %decision_classes = map {$_ => 0} @{$self->{_all_trees}->{0}->{_class_names}};
385 foreach my $i (0..$self->{_how_many_stages}-1) {
386 my %classification = %{$classifications[$i]};
387 delete $classification{'solution_path'} if exists $classification{'solution_path'};
388 my @sorted_classes = sort {$classification{$b} <=> $classification{$a}} keys %classification;
389 $decision_classes{$sorted_classes[0]} += $self->{_trust_factors}->{$i};
390 }
391 my @sorted_by_weighted_votes_decision_classes = sort {$decision_classes{$b} <=> $decision_classes{$a}} keys %decision_classes;
392 my @sorted_class_and_weight_pairs;
393 foreach my $class_name (sort {$decision_classes{$b} <=> $decision_classes{$a}} keys %decision_classes) {
394 push @sorted_class_and_weight_pairs, [$class_name, $decision_classes{$class_name}];
395 }
396 $self->{_trust_weighted_decision_classes} = \@sorted_class_and_weight_pairs;
397 return $sorted_by_weighted_votes_decision_classes[0];
398 }
399  
400 sub display_trust_weighted_decision_for_test_sample {
401 my $self = shift;
402 die "You must first call 'trust_weighted_majority_vote_classifier() before invoking display_trust_weighted_decision_for_test_sample()'\n"
403 unless $self->{_trust_weighted_decision_classes};
404 print "\nClassifier labels for test sample sorted by trust weights (The greater the trust weight, the greater the confidence we have in the classification label):\n\n";
405 foreach my $item (@{$self->{_trust_weighted_decision_classes}}) {
406 print "$item->[0] => $item->[1]\n";
407 }
408 }
409  
410 sub classify_with_base_decision_tree {
411 my $self = shift;
412 my $test_sample = shift;
413 return $self->{_all_trees}->{0}->classify($self->{_root_nodes}->{0}, $test_sample);
414 }
415  
416 sub get_all_class_names {
417 my $self = shift;
418 return $self->{_all_trees}->{0}->{_class_names};
419 }
420  
421 ############################################## Utility Routines ##########################################
422 # checks whether an element is in an array:
423 sub contained_in {
424 my $ele = shift;
425 my @array = @_;
426 my $count = 0;
427 map {$count++ if $ele eq $_} @array;
428 return $count;
429 }
430  
431 sub minmax {
432 my $arr = shift;
433 my ($min, $max);
434 foreach my $i (0..@{$arr}-1) {
435 if ( (!defined $min) || ($arr->[$i] < $min) ) {
436 $min = $arr->[$i];
437 }
438 if ( (!defined $max) || ($arr->[$i] > $max) ) {
439 $max = $arr->[$i];
440 }
441 }
442 return ($min, $max);
443 }
444  
445 sub sample_index {
446 my $arg = shift;
447 $arg =~ /_(.+)$/;
448 return $1;
449 }
450  
451 sub check_for_illegal_params {
452 my @params = @_;
453 my @legal_params = qw / how_many_stages
454 training_datafile
455 entropy_threshold
456 max_depth_desired
457 csv_class_column_index
458 csv_columns_for_features
459 symbolic_to_numeric_cardinality_threshold
460 number_of_histogram_bins
461 csv_cleanup_needed
462 debug1
463 debug2
464 debug3
465 /;
466 my $found_match_flag;
467 foreach my $param (@params) {
468 foreach my $legal (@legal_params) {
469 $found_match_flag = 0;
470 if ($param eq $legal) {
471 $found_match_flag = 1;
472 last;
473 }
474 }
475 last if $found_match_flag == 0;
476 }
477 return $found_match_flag;
478 }
479  
480 sub cleanup_csv {
481 my $line = shift;
482 $line =~ tr/\/:?()[]{}'/ /;
483 # my @double_quoted = substr($line, index($line,',')) =~ /\"[^\"]+\"/g;
484 my @double_quoted = substr($line, index($line,',')) =~ /\"[^\"]*\"/g;
485 for (@double_quoted) {
486 my $item = $_;
487 $item = substr($item, 1, -1);
488 $item =~ s/^\s+|,|\s+$//g;
489 $item = join '_', split /\s+/, $item;
490 substr($line, index($line, $_), length($_)) = $item;
491 }
492 my @white_spaced = $line =~ /,(\s*[^,]+)(?=,|$)/g;
493 for (@white_spaced) {
494 my $item = $_;
495 $item =~ s/\s+/_/g;
496 $item =~ s/^\s*_|_\s*$//g;
497 substr($line, index($line, $_), length($_)) = $item;
498 }
499 $line =~ s/,\s*(?=,|$)/,NA/g;
500 return $line;
501 }
502  
503 1;