DecisionTreeWithBagging.pm untested

filter: Statementstmt 0.0% 0 / 375 Branchbran 0.0% 0 / 70 Conditioncond 0.0% 0 / 23 MC/DCmcdc 0.0% 0 / 8 Subroutinesub 0.0% 0 / 22 Podpod 0.0% 0 / 18 totaltotal 0.0% 0 / 516 CC 36 SCAR 60.0
CC
36
Cov
0%
get_training_data_for_bagging
812.0
get_majority_vote_classification
12.0
minmax
12.0
CRAP 401.8
1 package Algorithm::DecisionTreeWithBagging;
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::DecisionTreeWithBagging is a Perl module for incorporating bagging in
9 # decision tree construction and in classification using decision trees.
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  
20 our $VERSION = '3.43';
21  
22 ############################################ Constructor ##############################################
23 sub new {
24 my ($class, %args) = @_;
25 my @params = keys %args;
26 my %dtargs = %args;
27 delete $dtargs{how_many_bags};
28 delete $dtargs{bag_overlap_fraction};
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 bless {
32 _training_datafile => $args{training_datafile},
33 _csv_class_column_index => $args{csv_class_column_index} || undef,
34 _csv_columns_for_features => $args{csv_columns_for_features} || undef,
35 _how_many_bags => $args{how_many_bags} || croak("you must specify how_many_bags"),
36 _bag_overlap_fraction => $args{bag_overlap_fraction} || 0.20,
37 _csv_cleanup_needed => $args{csv_cleanup_needed} || 0,
38 _debug1 => $args{debug1} || 0,
39 _number_of_training_samples => undef,
40 _segmented_training_data => {},
41 _all_trees => {map {$_ => Algorithm::DecisionTree->new(%dtargs)} 0..$args{how_many_bags} - 1},
42 _root_nodes => [],
43 _bag_sizes => [],
44 _classifications => undef,
45 }, $class;
46 }
47  
48 ############################################## Methods #################################################
49 sub get_training_data_for_bagging {
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} or die "Unable to open $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 @all_class_names = sort map {"$class_column_heading=$_"} keys %class_names;
86 my @feature_names = map {$all_feature_names[$_]} @{$self->{_csv_columns_for_features}};
87 my %class_for_sample_hash = map {"sample_" . $_ => "$class_column_heading=" . $data_hash{$_}->[$self->{_csv_class_column_index} - 1 ] } keys %data_hash;
88 my @sample_names = map {"sample_$_"} keys %data_hash;
89 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;
90 $self->{_number_of_training_samples} = scalar @sample_names;
91 fisher_yates_shuffle(\@sample_names);
92 print "\nsample names for all samples: @sample_names\n" if $self->{_debug2};
93 my $bag_size = int(@sample_names / $self->{_how_many_bags});
94 my @data_sample_bags;
95 push @data_sample_bags, [splice @sample_names, 0, $bag_size] while @sample_names;
96 if (@{$data_sample_bags[-1]} < $bag_size) {
97 push @{$data_sample_bags[-2]}, @{$data_sample_bags[-1]};
98 $#data_sample_bags = @data_sample_bags - 2;
99 }
100 $self->{_bag_sizes} = [map scalar(@$_), @data_sample_bags];
101 print "bag sizes: @{$self->{_bag_sizes}}\n" if $self->{_debug2};
102 my @augmented_data_sample_bags = ();
103 if ($self->{_bag_overlap_fraction}) {
104 my $number_of_samples_needed_from_other_bags = int(@{$data_sample_bags[0]} * $self->{_bag_overlap_fraction});
105 print "number of samples needed from other bags: $number_of_samples_needed_from_other_bags\n" if $self->{_debug2};
106 foreach my $i (0..$self->{_how_many_bags}-1) {
107 my @samples_in_other_bags = ();
108 foreach my $j (0..$self->{_how_many_bags}-1) {
109 push @samples_in_other_bags, @{$data_sample_bags[$j]} if $j != $i;
110 }
111 print "\n\nin other bags for i=$i: @samples_in_other_bags\n" if $self->{_debug2};
112 push @{$augmented_data_sample_bags[$i]}, @{$data_sample_bags[$i]};
113 push @{$augmented_data_sample_bags[$i]}, map $samples_in_other_bags[rand(@samples_in_other_bags)], 0 .. $number_of_samples_needed_from_other_bags -1;
114 print "\naugmented bage $i: @{$augmented_data_sample_bags[$i]}\n" if $self->{_debug2};
115 }
116 }
117 @data_sample_bags = @augmented_data_sample_bags;
118 $self->{_bag_sizes} = [map scalar(@$_), @data_sample_bags];
119 my %class_for_sample_hash_bags = map { $_ => { map { $_ => $class_for_sample_hash{$_} } @{$data_sample_bags[$_]} } } 0 .. $self->{_how_many_bags} - 1;
120 if ($self->{_debug2}) {
121 foreach my $bag_index (keys %class_for_sample_hash_bags) {
122 my %keyval = %{$class_for_sample_hash_bags{$bag_index}};
123 print "\nFor bag $bag_index =>:\n";
124 foreach my $sname (keys %keyval) {
125 print " $sname => $keyval{$sname}\n";
126 }
127 }
128 }
129 my %feature_values_for_samples_hash_bags = map { $_ => { map { $_ => $feature_values_for_samples_hash{$_} } @{$data_sample_bags[$_]} } } 0 .. $self->{_how_many_bags} - 1;
130 if ($self->{_debug2}) {
131 print "\nDisplaying samples and their values in each bag:\n\n";
132 foreach my $bag_index (keys %feature_values_for_samples_hash_bags) {
133 my %keyval = %{$feature_values_for_samples_hash_bags{$bag_index}};
134 print "\nFor bag $bag_index =>:\n";
135 foreach my $sname (keys %keyval) {
136 print " $sname => @{$keyval{$sname}}\n";
137 }
138 }
139 }
140 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}};
141 if ($self->{_debug2}) {
142 print "\nDisplaying features and their values for entire training data:\n\n";
143 foreach my $fname (keys %features_and_values_hash) {
144 print " $fname => @{$features_and_values_hash{$fname}}\n";
145 }
146 }
147 my %features_and_values_hash_bags = map { my $c = $_; { $c => { map { my $d = $_; {$all_feature_names[$d] => [ sort {$a cmp $b} map {my $f = $_; $f =~ /^\d+$/ ? sprintf("%.1f",$f) : $f} map {$data_hash{sample_index($_)}->[$d-1]} @{$data_sample_bags[$c]} ] } } @{$self->{_csv_columns_for_features}} } } } 0 .. $self->{_how_many_bags} - 1;
148 if ($self->{_debug2}) {
149 print "\nDisplaying features and their values in each bag:\n\n";
150 foreach my $bag_index (keys %features_and_values_hash_bags) {
151 my %keyval = %{$features_and_values_hash_bags{$bag_index}};
152 print "\nFor bag $bag_index =>:\n";
153 foreach my $fname (keys %keyval) {
154 print " $fname => @{$keyval{$fname}}\n";
155 }
156 }
157 }
158 my @all_class_names = sort keys %{ {map {$_ => 1} values %class_for_sample_hash } };
159 print "all class names: @all_class_names\n" if $self->{_debug2};
160 my %numeric_features_valuerange_hash_bags = map {$_ => {}} 0 .. $self->{_how_many_bags} - 1;
161 my %feature_values_how_many_uniques_hash_bags = map {$_ => {}} 0 .. $self->{_how_many_bags} - 1;
162 my %features_and_unique_values_hash_bags = map {$_ => {}} 0 .. $self->{_how_many_bags} - 1;
163 my $numregex = '[+-]?\ *(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?';
164 foreach my $i (0 .. $self->{_how_many_bags} - 1) {
165 foreach my $feature (keys %{$features_and_values_hash_bags{$i}}) {
166 my %seen = ();
167 my @unique_values_for_feature_in_bag = grep {$_ if $_ ne 'NA' && !$seen{$_}++} @{$features_and_values_hash_bags{$i}{$feature}};
168 $feature_values_how_many_uniques_hash_bags{$i}->{$feature} = scalar @unique_values_for_feature_in_bag;
169 my $not_all_values_float = 0;
170 map {$not_all_values_float = 1 if $_ !~ /^$numregex$/} @unique_values_for_feature_in_bag;
171 if ($not_all_values_float == 0) {
172 my @minmaxvalues = minmax(\@unique_values_for_feature_in_bag);
173 $numeric_features_valuerange_hash_bags{$i}->{$feature} = \@minmaxvalues;
174 }
175 $features_and_unique_values_hash_bags{$i}->{$feature} = \@unique_values_for_feature_in_bag;
176 }
177 }
178 if ($self->{_debug2}) {
179 print "\nDisplaying value ranges for numeric features in each bag:\n\n";
180 foreach my $bag_index (keys %numeric_features_valuerange_hash_bags) {
181 my %keyval = %{$numeric_features_valuerange_hash_bags{$bag_index}};
182 print "\nFor bag $bag_index =>:\n";
183 foreach my $fname (keys %keyval) {
184 print " $fname => @{$keyval{$fname}}\n";
185 }
186 }
187 print "\nDisplaying number of unique values for each features in each bag:\n\n";
188 foreach my $bag_index (keys %feature_values_how_many_uniques_hash_bags) {
189 my %keyval = %{$feature_values_how_many_uniques_hash_bags{$bag_index}};
190 print "\nFor bag $bag_index =>:\n";
191 foreach my $fname (keys %keyval) {
192 print " $fname => $keyval{$fname}\n";
193 }
194 }
195 print "\nDisplaying unique values for all features in each bag:\n\n";
196 foreach my $bag_index (keys %features_and_unique_values_hash_bags) {
197 my %keyval = %{$features_and_unique_values_hash_bags{$bag_index}};
198 print "\nFor bag $bag_index =>:\n";
199 foreach my $fname (keys %keyval) {
200 print " $fname => @{$keyval{$fname}}\n";
201 }
202 }
203 }
204 foreach my $i (0..$self->{_how_many_bags}-1) {
205 $self->{_all_trees}->{$i}->{_class_names} = \@all_class_names;
206 $self->{_all_trees}->{$i}->{_feature_names} = \@feature_names;
207 $self->{_all_trees}->{$i}->{_samples_class_label_hash} = $class_for_sample_hash_bags{$i};
208 $self->{_all_trees}->{$i}->{_training_data_hash} = $feature_values_for_samples_hash_bags{$i};
209 $self->{_all_trees}->{$i}->{_features_and_values_hash} = $features_and_values_hash_bags{$i};
210 $self->{_all_trees}->{$i}->{_features_and_unique_values_hash} = $features_and_unique_values_hash_bags{$i};
211 $self->{_all_trees}->{$i}->{_numeric_features_valuerange_hash} = $numeric_features_valuerange_hash_bags{$i};
212 $self->{_all_trees}->{$i}->{_feature_values_how_many_uniques_hash} = $feature_values_how_many_uniques_hash_bags{$i};
213 }
214 if ($self->{_debug1}) {
215 foreach my $i (0..$self->{_how_many_bags}-1) {
216 print "\n\n============================= For bag $i ==================================\n";
217 print "\nAll class names: @{$self->{_all_trees}->{$i}->{_class_names}}\n";
218 print "\nSamples and their feature values in each bag:\n";
219 foreach my $item (sort {sample_index($a) <=> sample_index($b)} keys %{$self->{_all_trees}->{$i}->{_training_data_hash}}) {
220 print "$item => @{$self->{_all_trees}->{$i}->{_training_data_hash}->{$item}}\n";
221 }
222 print "\nclass label for each data sample in each bag:\n";
223 foreach my $item (sort {sample_index($a) <=> sample_index($b)} keys %{$self->{_all_trees}->{$i}->{_samples_class_label_hash}} ) {
224 print "$item => $self->{_all_trees}->{$i}->{_samples_class_label_hash}->{$item}\n";
225 }
226 print "\nfeatures and the values taken by them:\n";
227 foreach my $item (sort keys %{$self->{_all_trees}->{$i}->{_features_and_values_hash}}) {
228 print "$item => @{$self->{_all_trees}->{$i}->{_features_and_values_hash}->{$item}}\n";
229 }
230 print "\nnumeric features and their ranges:\n";
231 foreach my $item (sort keys %{$self->{_all_trees}->{$i}->{_numeric_features_valuerange_hash}}) {
232 print "$item => @{$self->{_all_trees}->{$i}->{_numeric_features_valuerange_hash}->{$item}}\n";
233 }
234 print "\nnumber of unique values in each feature:\n";
235 foreach my $item (sort keys %{$self->{_all_trees}->{$i}->{_feature_values_how_many_uniques_hash}}) {
236 print "$item => $self->{_all_trees}->{$i}->{_feature_values_how_many_uniques_hash}->{$item}\n";
237 }
238 }
239 }
240 }
241  
242 sub get_number_of_training_samples {
243 my $self = shift;
244 return $self->{_number_of_training_samples};
245 }
246  
247 sub calculate_first_order_probabilities {
248 my $self = shift;
249 map $self->{_all_trees}->{$_}->calculate_first_order_probabilities(), 0 .. $self->{_how_many_bags}-1;
250 }
251  
252 sub show_training_data_in_bags {
253 my $self = shift;
254 foreach my $i (0..$self->{_how_many_bags}-1) {
255 print "\n\n============================= For bag $i ==================================\n";
256 $self->{_all_trees}->{$i}->show_training_data()
257 }
258 }
259  
260 sub calculate_class_priors {
261 my $self = shift;
262 map $self->{_all_trees}->{$_}->calculate_class_priors(), 0 .. $self->{_how_many_bags}-1;
263 }
264  
265 sub construct_decision_trees_for_bags {
266 my $self = shift;
267 $self->{_root_nodes} =
268 [map $self->{_all_trees}->{$_}->construct_decision_tree_classifier(), 0 .. $self->{_how_many_bags}-1];
269 }
270  
271 sub display_decision_trees_for_bags {
272 my $self = shift;
273 foreach my $i (0 .. $self->{_how_many_bags}-1) {
274 print "\n\n============================= For bag $i ==================================\n";
275 $self->{_root_nodes}->[$i]->display_decision_tree(" ");
276 }
277 }
278  
279 sub classify_with_bagging {
280 my $self = shift;
281 my $test_sample = shift;
282 $self->{_classifications} = [ map $self->{_all_trees}->{$_}->classify($self->{_root_nodes}->[$_], $test_sample), 0 .. $self->{_how_many_bags}-1 ];
283 }
284  
285 sub display_classification_results_for_each_bag {
286 my $self = shift;
287 die "You must first call 'classify_with_bagging()' before invoking 'display_classification_results_for_each_bag()'" unless $self->{_classifications};
288 my @classifications = @{$self->{_classifications}};
289 my @solution_paths = map $_->{'solution_path'}, @classifications;
290 foreach my $i (0 .. $self->{_how_many_bags}-1) {
291 print "\n\n============================= For bag $i ==================================\n";
292 print "\nbag size: $self->{_bag_sizes}->[$i]\n";
293 my $classification = $classifications[$i];
294 delete $classification->{'solution_path'};
295 my @which_classes = sort {$classification->{$b} <=> $classification->{$a}} keys %$classification;
296 print "\nClassification:\n\n";
297 print " class probability\n";
298 print " ---------- -----------\n";
299 foreach my $which_class (@which_classes) {
300 my $classstring = sprintf("%-30s", $which_class);
301 my $valuestring = sprintf("%-30s", $classification->{$which_class});
302 print " $classstring $valuestring\n";
303 }
304 print "\nSolution path in the decision tree: @{$solution_paths[$i]}\n";
305 print "\nNumber of nodes created: " . $self->{_root_nodes}->[$i]->how_many_nodes() . "\n";
306  
307 }
308 }
309  
310 sub get_majority_vote_classification {
311 my $self = shift;
312 die "You must first call 'classify_with_bagging()' before invoking 'get_majority_vote_classifiction()'" unless $self->{_classifications};
313 my @classifications = @{$self->{_classifications}};
314 my %decision_classes = map { $_ => 0 } @{$self->{_all_trees}->{0}->{_class_names}};
315 foreach my $i (0 .. $self->{_how_many_bags}-1) {
316 my $classification = $classifications[$i];
317 delete $classification->{'solution_path'} if exists $classification->{'solution_path'};
318 my @sorted_classes = sort {$classification->{$b} <=> $classification->{$a}} keys %$classification;
319 $decision_classes{$sorted_classes[0]}++;
320 }
321 my @sorted_by_votes_decision_classes = sort {$decision_classes{$b} <=> $decision_classes{$a}} keys %decision_classes;
322 return $sorted_by_votes_decision_classes[0];
323 }
324  
325 sub get_all_class_names {
326 my $self = shift;
327 return $self->{_all_trees}->{0}->{_class_names};
328 }
329  
330 ######################################### Utility Routimes #############################################
331 # Returns an array of two values, the min and the max, of an array of floats
332 sub minmax {
333 my $arr = shift;
334 my ($min, $max);
335 foreach my $i (0..@{$arr}-1) {
336 if ( (!defined $min) || ($arr->[$i] < $min) ) {
337 $min = $arr->[$i];
338 }
339 if ( (!defined $max) || ($arr->[$i] > $max) ) {
340 $max = $arr->[$i];
341 }
342 }
343 return ($min, $max);
344 }
345  
346 sub sample_index {
347 my $arg = shift;
348 $arg =~ /_(.+)$/;
349 return $1;
350 }
351  
352 sub bags {
353 my ($l,$n) = @_;
354 my @bags;
355 my $i;
356 for ($i=0; $i < int(@$l/$n); $i++) {
357 push @bags, [@{$l}[$i*$n..($i+1)*$n-1]];
358 }
359 push @{$bags[-1]}, @{$l}[$i*$n..@{$l}-1];
360 return \@bags;
361 }
362  
363 sub check_for_illegal_params {
364 my @params = @_;
365 my @legal_params = qw / how_many_bags
366 bag_overlap_fraction
367 training_datafile
368 entropy_threshold
369 max_depth_desired
370 csv_class_column_index
371 csv_columns_for_features
372 symbolic_to_numeric_cardinality_threshold
373 number_of_histogram_bins
374 csv_cleanup_needed
375 debug1
376 debug2
377 debug3
378 /;
379 my $found_match_flag;
380 foreach my $param (@params) {
381 foreach my $legal (@legal_params) {
382 $found_match_flag = 0;
383 if ($param eq $legal) {
384 $found_match_flag = 1;
385 last;
386 }
387 }
388 last if $found_match_flag == 0;
389 }
390 return $found_match_flag;
391 }
392  
393 # from perl docs:
394 sub fisher_yates_shuffle {
395 my $arr = shift;
396 my $i = @$arr;
397 while (--$i) {
398 my $j = int rand( $i + 1 );
399 @$arr[$i, $j] = @$arr[$j, $i];
400 }
401 }
402  
403 sub cleanup_csv {
404 my $line = shift;
405 $line =~ tr/\/:?()[]{}'/ /;
406 # my @double_quoted = substr($line, index($line,',')) =~ /\"[^\"]+\"/g;
407 my @double_quoted = substr($line, index($line,',')) =~ /\"[^\"]*\"/g;
408 for (@double_quoted) {
409 my $item = $_;
410 $item = substr($item, 1, -1);
411 $item =~ s/^\s+|,|\s+$//g;
412 $item = join '_', split /\s+/, $item;
413 substr($line, index($line, $_), length($_)) = $item;
414 }
415 my @white_spaced = $line =~ /,(\s*[^,]+)(?=,|$)/g;
416 for (@white_spaced) {
417 my $item = $_;
418 $item =~ s/\s+/_/g;
419 $item =~ s/^\s*_|_\s*$//g;
420 substr($line, index($line, $_), length($_)) = $item;
421 }
422 $line =~ s/,\s*(?=,|$)/,NA/g;
423 return $line;
424 }
425  
426 1;