RegressionTree.pm untested

filter: Statementstmt 0.0% 0 / 1178 Branchbran 0.0% 0 / 274 Conditioncond 0.0% 0 / 86 MC/DCmcdc 0.0% 0 / 49 Subroutinesub 0.0% 0 / 61 Podpod 0.0% 0 / 51 totaltotal 0.0% 0 / 1699 CC 138 SCAR 54.2
CC
138
Cov
0%
estimate_regression_coefficients
650.0
best_feature_calculator
552.0
_error_for_given_sequence_of_features_and_values_or_thresholds
462.0
CRAP 226.9
1 package Algorithm::RegressionTree;
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::RegressionTree is a Perl module for constructing regression trees. It calls
9 # on the main Algorithm::DecisionTree module for some of its functionality.
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 File::Basename;
19 use Algorithm::DecisionTree 3.43;
20 use List::Util qw(reduce min max pairmap sum);
21 use Math::GSL::Matrix;
22 use Graphics::GnuplotIF;
23  
24 our $VERSION = '3.43';
25  
26 @Algorithm::RegressionTree::ISA = ('Algorithm::DecisionTree');
27  
28 ############################################ Constructor ##############################################
29 sub new {
30 my ($class, %args) = @_;
31 my @params = keys %args;
32 croak "\nYou have used a wrong name for a keyword argument --- perhaps a misspelling\n"
33 if check_for_illegal_params(@params) == 0;
34 my %dtargs = %args;
35 delete $dtargs{dependent_variable_column};
36 delete $dtargs{predictor_columns};
37 delete $dtargs{mse_threshold};
38 delete $dtargs{need_data_normalization};
39 delete $dtargs{jacobian_choice};
40 delete $dtargs{debug1_r};
41 delete $dtargs{debug2_r};
42 delete $dtargs{debug3_r};
43 my $instance = Algorithm::DecisionTree->new(%dtargs);
44 bless $instance, $class;
45 $instance->{_dependent_variable_column} = $args{dependent_variable_column} || undef;
46 $instance->{_predictor_columns} = $args{predictor_columns} || 0;
47 $instance->{_mse_threshold} = $args{mse_threshold} || 0.01;
48 $instance->{_jacobian_choice} = $args{jacobian_choice} || 0;
49 $instance->{_need_data_normalization} = $args{need_data_normalization} || 0;
50 $instance->{_dependent_var} = undef;
51 $instance->{_dependent_var_values} = undef;
52 $instance->{_samples_dependent_var_val_hash} = undef;
53 $instance->{_root_node} = undef;
54 $instance->{_debug1_r} = $args{debug1_r} || 0;
55 $instance->{_debug2_r} = $args{debug2_r} || 0;
56 $instance->{_debug3_r} = $args{debug3_r} || 0;
57 $instance->{_sample_points_for_dependent_var} = [];
58 $instance->{_output_for_plots} = {};
59 $instance->{_output_for_surface_plots} = {};
60 bless $instance, $class;
61 }
62  
63 ############################################## Methods #################################################
64 sub get_training_data_for_regression {
65 my $self = shift;
66 die("Aborted. get_training_data_csv() is only for CSV files") unless $self->{_training_datafile} =~ /\.csv$/;
67 my @dependent_var_values;
68 my %all_record_ids_with_dependent_var_values;
69 my $firstline;
70 my %data_hash;
71 $|++;
72 open FILEIN, $self->{_training_datafile};
73 my $record_index = 0;
74 while (<FILEIN>) {
75 next if /^[ ]*\r?\n?$/;
76 $_ =~ s/\r?\n?$//;
77 my $record = $self->{_csv_cleanup_needed} ? cleanup_csv($_) : $_;
78 if ($record_index == 0) {
79 $firstline = $record;
80 $record_index++;
81 next;
82 }
83 my @parts = split /,/, $record;
84 my $record_label = shift @parts;
85 $record_label =~ s/^\s*\"|\"\s*$//g;
86 $data_hash{$record_label} = \@parts;
87 push @dependent_var_values, $parts[$self->{_dependent_variable_column}-1];
88 $all_record_ids_with_dependent_var_values{$parts[0]} = $parts[$self->{_dependent_variable_column}-1];
89 print "." if $record_index % 10000 == 0;
90 $record_index++;
91 }
92 close FILEIN;
93 $self->{_how_many_total_training_samples} = $record_index; #it's less by 1 from total num of records; okay
94 print "\n\nTotal number of training samples: $self->{_how_many_total_training_samples}\n" if $self->{_debug1_r};
95 my @all_feature_names = grep $_, split /,/, substr($firstline, index($firstline,','));
96 my $dependent_var_column_heading = $all_feature_names[$self->{_dependent_variable_column} - 1];
97 my @feature_names = map {$all_feature_names[$_-1]} @{$self->{_predictor_columns}};
98 my %dependent_var_value_for_sample_hash = map {"sample_" . $_ => "$dependent_var_column_heading=" . $data_hash{$_}->[$self->{_dependent_variable_column} - 1 ] } keys %data_hash;
99 my @sample_names = map {"sample_$_"} keys %data_hash;
100 my %feature_values_for_samples_hash = map {my $sampleID = $_; "sample_" . $sampleID => [map {my $fname = $all_feature_names[$_-1]; $fname . "=" . eval{$data_hash{$sampleID}->[$_-1] =~ /^\d+$/ ? sprintf("%.1f", $data_hash{$sampleID}->[$_-1] ) : $data_hash{$sampleID}->[$_-1] } } @{$self->{_predictor_columns}} ] } keys %data_hash;
101 my %features_and_values_hash = map { my $a = $_; {$all_feature_names[$a-1] => [ map {my $b = $_; $b =~ /^\d+$/ ? sprintf("%.1f",$b) : $b} map {$data_hash{$_}->[$a-1]} keys %data_hash ]} } @{$self->{_predictor_columns}};
102 my %numeric_features_valuerange_hash = ();
103 my %feature_values_how_many_uniques_hash = ();
104 my %features_and_unique_values_hash = ();
105 my $numregex = '[+-]?\ *(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?';
106 foreach my $feature (keys %features_and_values_hash) {
107 my %seen = ();
108 my @unique_values_for_feature = grep {$_ if $_ ne 'NA' && !$seen{$_}++} @{$features_and_values_hash{$feature}};
109 $feature_values_how_many_uniques_hash{$feature} = scalar @unique_values_for_feature;
110 my $not_all_values_float = 0;
111 map {$not_all_values_float = 1 if $_ !~ /^$numregex$/} @unique_values_for_feature;
112 if ($not_all_values_float == 0) {
113 my @minmaxvalues = minmax(\@unique_values_for_feature);
114 $numeric_features_valuerange_hash{$feature} = \@minmaxvalues;
115 }
116 $features_and_unique_values_hash{$feature} = \@unique_values_for_feature;
117 }
118 if ($self->{_debug1_r}) {
119 print "\nDependent var values: @dependent_var_values\n";
120 print "\nEach sample data record:\n";
121 foreach my $kee (sort {sample_index($a) <=> sample_index($b)} keys %feature_values_for_samples_hash) {
122 print "$kee => @{$feature_values_for_samples_hash{$kee}}\n";
123 }
124 print "\ndependent var value for each data sample:\n";
125 foreach my $kee (sort {sample_index($a) <=> sample_index($b)} keys %dependent_var_value_for_sample_hash) {
126 print "$kee => $dependent_var_value_for_sample_hash{$kee}\n";
127 }
128 print "\nfeatures and the values taken by them:\n";
129 for my $kee (sort keys %features_and_values_hash) {
130 print "$kee => @{$features_and_values_hash{$kee}}\n";
131 }
132 print "\nnumeric features and their ranges:\n";
133 for my $kee (sort keys %numeric_features_valuerange_hash) {
134 print "$kee => @{$numeric_features_valuerange_hash{$kee}}\n";
135 }
136 print "\nnumber of unique values in each feature:\n";
137 for my $kee (sort keys %feature_values_how_many_uniques_hash) {
138 print "$kee => $feature_values_how_many_uniques_hash{$kee}\n";
139 }
140 }
141 $self->{_XMatrix} = undef;
142 $self->{_YVector} = undef;
143 $self->{_dependent_var} = $dependent_var_column_heading;
144 $self->{_dependent_var_values} = \@dependent_var_values;
145 $self->{_feature_names} = \@feature_names;
146 $self->{_samples_dependent_var_val_hash} = \%dependent_var_value_for_sample_hash;
147 $self->{_training_data_hash} = \%feature_values_for_samples_hash;
148 $self->{_features_and_values_hash} = \%features_and_values_hash;
149 $self->{_features_and_unique_values_hash} = \%features_and_unique_values_hash;
150 $self->{_numeric_features_valuerange_hash} = \%numeric_features_valuerange_hash;
151 $self->{_feature_values_how_many_uniques_hash} = \%feature_values_how_many_uniques_hash;
152 $self->SUPER::calculate_first_order_probabilities();
153 }
154  
155 sub construct_XMatrix_and_YVector_all_data {
156 my $self = shift;
157 my $matrix_rows_as_lists = [ map {my @arr = @$_; [map substr($_,index($_,'=')+1), @arr] } map {$self->{_training_data_hash}->{$_}} sort {sample_index($a) <=> sample_index($b)} keys %{$self->{_training_data_hash}} ];
158 map {push @$_, 1} @{$matrix_rows_as_lists};
159 map {print "XMatrix row: @$_\n"} @{$matrix_rows_as_lists} if $self->{_debug1_r};
160 my $XMatrix = Math::GSL::Matrix->new(scalar @{$matrix_rows_as_lists}, scalar @{$matrix_rows_as_lists->[0]});
161 pairmap {$XMatrix->set_row($a,$b)} ( 0..@{$matrix_rows_as_lists}-1, @{$matrix_rows_as_lists} )
162 [ map { $_, $_ + @{$matrix_rows_as_lists} } ( 0 .. @{$matrix_rows_as_lists}-1 ) ];
163 if ($self->{_debug1_r}) {
164 foreach my $rowindex (0..@{$matrix_rows_as_lists}-1) {
165 my @onerow = $XMatrix->row($rowindex)->as_list;
166 print "XMatrix row again: @onerow\n";
167 }
168 }
169 $self->{_XMatrix} = $XMatrix;
170 my @dependent_var_values = map {my $val = $self->{_samples_dependent_var_val_hash}->{$_}; substr($val,index($val,'=')+1)} sort {sample_index($a) <=> sample_index($b)} keys %{$self->{_samples_dependent_var_val_hash}};
171 print "dependent var values: @dependent_var_values\n" if $self->{_debug1_r};
172 my $YVector = Math::GSL::Matrix->new(scalar @{$matrix_rows_as_lists}, 1);
173 pairmap {$YVector->set_row($a,$b)} ( 0..@{$matrix_rows_as_lists}-1, map {[$_]} @dependent_var_values )
174 [ map { $_, $_ + @{$matrix_rows_as_lists} } ( 0 .. @{$matrix_rows_as_lists}-1 ) ];
175 if ($self->{_debug1_r}) {
176 foreach my $rowindex (0..@{$matrix_rows_as_lists}-1) {
177 my @onerow = $YVector->row($rowindex)->as_list;
178 print "YVector row: @onerow\n";
179 }
180 }
181 $self->{_YVector} = $YVector;
182 return ($XMatrix, $YVector);
183 }
184  
185 sub estimate_regression_coefficients {
186 my $self = shift;
187 my ($XMatrix, $YVector, $display) = @_;
188 $display = 0 unless defined $display;
189 my ($nrows, $ncols) = $XMatrix->dim;
190 print "nrows=$nrows ncols=$ncols\n" if $self->{_debug2_r};
191 my $jacobian_choice = $self->{_jacobian_choice};
192 my $X = $XMatrix->copy();
193 my $y = $YVector->copy();
194 if ($self->{_need_data_normalization}) {
195 die "normalization feature is yet to be added to the module --- sorry";
196 }
197 my $beta0 = (transpose($X) * $X)->inverse() * transpose($X) * $y;
198 my ($betarows, $betacols) = $beta0->dim;
199 die "Something has gone wrong with the calculation of beta coefficients" if $betacols > 1;
200 if ($jacobian_choice == 0) {
201 # my $error = sum(abs_vector_as_list( $y - ($X * $beta) )) / $nrows;
202 my $error = sum( map abs, ($y - ($X * $beta0) )->col(0)->as_list ) / $nrows;
203 my $predictions = $X * $beta0;
204 if ($display) {
205 if ($ncols == 2) {
206 my @xvalues = $X->col(0)->as_list;
207 my @yvalues = $predictions->col(0)->as_list;
208 $self->{_output_for_plots}->{scalar(keys %{$self->{_output_for_plots}}) + 1} = [\@xvalues,\@yvalues];
209 } elsif ($ncols == 3) {
210 my @xvalues;
211 my @yvalues = $predictions->col(0)->as_list;
212 foreach my $row_index (0 .. $X->rows - 1) {
213 my @onerow = $X->row($row_index)->as_list;
214 pop @onerow;
215 push @xvalues, "@onerow";
216 }
217 $self->{_output_for_surface_plots}->{scalar(keys %{$self->{_output_for_surface_plots}}) + 1} = [\@xvalues,\@yvalues];
218 } else {
219 print "no display when the overall dimensionality of the data exceeds 3\n";
220 }
221 }
222 return ($error, $beta0);
223 }
224 my $beta = $beta0;
225 if ($self->{_debug2_r}) {
226 print "\ndisplaying beta0 matrix\n";
227 display_matrix($beta);
228 }
229 my $gamma = 0.1;
230 my $iterate_again_flag = 1;
231 my $delta = 0.001;
232 my $master_interation_index = 0;
233 $|++;
234 while (1) {
235 print "*" unless $master_interation_index++ % 100;
236 last unless $iterate_again_flag;
237 $gamma *= 0.1;
238 $beta0 = 0.99 * $beta0;
239 print "\n\n======== starting iterations with gamma= $gamma ===========\n\n\n" if $self->{_debug2_r};
240 $beta = $beta0;
241 my $beta_old = Math::GSL::Matrix->new($betarows, 1)->zero;
242 my $error_old = sum( map abs, ($y - ($X * $beta_old) )->col(0)->as_list ) / $nrows;
243 my $error;
244 foreach my $iteration (0 .. 1499) {
245 print "." unless $iteration % 100;
246 $beta_old = $beta->copy;
247 my $jacobian;
248 if ($jacobian_choice == 1) {
249 $jacobian = $X;
250 } elsif ($jacobian_choice == 2) {
251 my $x_times_delta_beta = $delta * $X * $beta;
252 $jacobian = Math::GSL::Matrix->new($nrows, $ncols);
253 foreach my $i (0 .. $nrows - 1) {
254 my @row = ($x_times_delta_beta->get_elem($i,0)) x $ncols;
255 $jacobian->set_row($i, \@row);
256 }
257 $jacobian = (1.0/$delta) * $jacobian;
258 } else {
259 die "wrong choice for the jacobian_choice";
260 }
261 # $beta = $beta_old + 2 * $gamma * transpose($X) * ( $y - ($X * $beta) );
262 $beta = $beta_old + 2 * $gamma * transpose($jacobian) * ( $y - ($X * $beta) );
263 $error = sum( map abs, ($y - ($X * $beta) )->col(0)->as_list ) / $nrows;
264 if ($error > $error_old) {
265 if (vector_norm($beta - $beta_old) < (0.00001 * vector_norm($beta_old))) {
266 $iterate_again_flag = 0;
267 last;
268 } else {
269 last;
270 }
271 }
272 if ($self->{_debug2_r}) {
273 print "\n\niteration: $iteration gamma: $gamma current error: $error\n";
274 print "\nnew beta:\n";
275 display_matrix $beta;
276 }
277 if ( vector_norm($beta - $beta_old) < (0.00001 * vector_norm($beta_old)) ) {
278 print "iterations used: $iteration with gamma: $gamma\n" if $self->{_debug2_r};
279 $iterate_again_flag = 0;
280 last;
281 }
282 $error_old = $error;
283 }
284 }
285 display_matrix($beta) if $self->{_debug2_r};
286 my $predictions = $X * $beta;
287 my @error_distribution = ($y - ($X * $beta))->as_list;
288 my $squared_error = sum map abs, @error_distribution;
289 my $error = $squared_error / $nrows;
290 if ($display) {
291 if ($ncols == 2) {
292 my @xvalues = $X->col(0)->as_list;
293 my @yvalues = $predictions->col(0)->as_list;
294 $self->{_output_for_plots}->{scalar(keys %{$self->{_output_for_plots}}) + 1} = [\@xvalues,\@yvalues];
295 } elsif ($ncols == 3) {
296 my @xvalues;
297 my @yvalues = $predictions->col(0)->as_list;
298 foreach my $row_index (0 .. $X->rows - 1) {
299 my @onerow = $X->row($row_index)->as_list;
300 pop @onerow;
301 push @xvalues, "@onerow";
302 }
303 $self->{_output_for_surface_plots}->{scalar(keys %{$self->{_output_for_surface_plots}}) + 1} = [\@xvalues,\@yvalues];
304 } else {
305 print "no display when the overall dimensionality of the data exceeds 3\n";
306 }
307 }
308 return ($error, $beta);
309 }
310  
311 ##------------------------------- Construct Regression Tree ------------------------------------
312  
313  
314 ## At the root node, you do ordinary linear regression for the entire dataset so that you
315 ## can later compare the linear regression fit with the results obtained through the
316 ## regression tree. Subsequently, you call the recursive_descent() method to construct
317 ## the tree.
318  
319 sub construct_regression_tree {
320 my $self = shift;
321 print "\nConstructing regression tree...\n";
322 my $root_node = RTNode->new(undef, undef, undef, [], $self, 'root');
323 my ($XMatrix,$YVector) = $self->construct_XMatrix_and_YVector_all_data();
324 my ($error,$beta) = $self->estimate_regression_coefficients($XMatrix, $YVector, 1);
325 $root_node->set_node_XMatrix($XMatrix);
326 $root_node->set_node_YVector($YVector);
327 $root_node->set_node_error($error);
328 $root_node->set_node_beta($beta);
329 $root_node->set_num_data_points($XMatrix->cols);
330 print "\nerror at root: $error\n";
331 print "\nbeta at root:\n";
332 display_matrix($beta);
333 $self->{_root_node} = $root_node;
334 $self->recursive_descent($root_node) if $self->{_max_depth_desired} > 0;
335 return $root_node;
336 }
337  
338 ## We first look for a feature, along with its partitioning point, that yields the
339 ## largest reduction in MSE compared to the MSE at the parent node. This feature and
340 ## its partitioning point are then used to create two child nodes in the tree.
341 sub recursive_descent {
342 my $self = shift;
343 my $node = shift;
344 print "\n==================== ENTERING RECURSIVE DESCENT ==========================\n";
345 my $node_serial_number = $node->get_serial_num();
346 my @features_and_values_or_thresholds_on_branch = @{$node->get_branch_features_and_values_or_thresholds()};
347 my @copy_of_path_attributes = @{deep_copy_array(\@features_and_values_or_thresholds_on_branch)};
348 if (@features_and_values_or_thresholds_on_branch > 0) {
349 my ($error,$beta,$XMatrix,$YVector) =
350 $self->_error_for_given_sequence_of_features_and_values_or_thresholds(\@copy_of_path_attributes);
351 $node->set_node_XMatrix($XMatrix);
352 $node->set_node_YVector($YVector);
353 $node->set_node_error($error);
354 $node->set_node_beta($beta);
355 $node->set_num_data_points($XMatrix->cols);
356 print "\nNODE SERIAL NUMBER: $node_serial_number\n";
357 print "\nFeatures and values or thresholds on branch: @features_and_values_or_thresholds_on_branch\n";
358 return if $error <= $self->{_mse_threshold};
359 }
360 my ($best_feature,$best_minmax_error_at_partitioning_point,$best_feature_partitioning_point) =
361 $self->best_feature_calculator(\@copy_of_path_attributes);
362 return unless defined $best_feature_partitioning_point;
363 print "\nBest feature found: $best_feature\n";
364 print "Best feature partitioning_point: $best_feature_partitioning_point\n";
365 print "Best minmax error at partitioning point: $best_minmax_error_at_partitioning_point\n";
366 $node->set_feature($best_feature);
367 $node->display_node() if $self->{_debug2_r};
368 return if (defined $self->{_max_depth_desired}) &&
369 (@features_and_values_or_thresholds_on_branch >= $self->{_max_depth_desired});
370 if ($best_minmax_error_at_partitioning_point > $self->{_mse_threshold}) {
371 my @extended_branch_features_and_values_or_thresholds_for_lessthan_child =
372 @{deep_copy_array(\@features_and_values_or_thresholds_on_branch)};
373 my @extended_branch_features_and_values_or_thresholds_for_greaterthan_child =
374 @{deep_copy_array(\@features_and_values_or_thresholds_on_branch)};
375 my $feature_threshold_combo_for_less_than = "$best_feature" . '<' . "$best_feature_partitioning_point";
376 my $feature_threshold_combo_for_greater_than = "$best_feature" . '>' . "$best_feature_partitioning_point";
377 push @extended_branch_features_and_values_or_thresholds_for_lessthan_child,
378 $feature_threshold_combo_for_less_than;
379 push @extended_branch_features_and_values_or_thresholds_for_greaterthan_child,
380 $feature_threshold_combo_for_greater_than;
381 my $left_child_node = RTNode->new(undef, undef, undef,
382 \@extended_branch_features_and_values_or_thresholds_for_lessthan_child, $self);
383 $node->add_child_link($left_child_node);
384 $self->recursive_descent($left_child_node);
385 my $right_child_node = RTNode->new(undef, undef, undef,
386 \@extended_branch_features_and_values_or_thresholds_for_greaterthan_child, $self);
387 $node->add_child_link($right_child_node);
388 $self->recursive_descent($right_child_node);
389 }
390 }
391  
392 ## This is the heart of the regression tree constructor. Its main job is to figure
393 ## out the best feature to use for partitioning the training data samples at the
394 ## current node. The partitioning criterion is that the largest of the MSE's in
395 ## the two partitions should be smaller than the error associated with the parent
396 ## node.
397 sub best_feature_calculator {
398 my $self = shift;
399 my $features_and_values_or_thresholds_on_branch = shift;
400 my @features_and_values_or_thresholds_on_branch = @$features_and_values_or_thresholds_on_branch;
401 print "\n\nfeatures_and_values_or_thresholds_on_branch: @features_and_values_or_thresholds_on_branch\n";
402 if (@features_and_values_or_thresholds_on_branch == 0) {
403 my $best_partition_point_for_feature_hash = { map {$_ => undef} @{$self->{_feature_names}} };
404 my $best_minmax_error_for_feature_hash = { map {$_ => undef} @{$self->{_feature_names}} };
405 foreach my $i (0 .. @{$self->{_feature_names}}-1) {
406 my $feature_name = $self->{_feature_names}->[$i];
407 my @values = @{$self->{_sampling_points_for_numeric_feature_hash}->{$feature_name}};
408 my @partitioning_errors;
409 my %partitioning_error_hash;
410 foreach my $value (@values[10 .. $#values - 10]) {
411 my $feature_and_less_than_value_string = "$feature_name" . '<' . "$value";
412 my $feature_and_greater_than_value_string = "$feature_name" . '>' . "$value";
413 my @for_left_child;
414 my @for_right_child;
415 if (@features_and_values_or_thresholds_on_branch) {
416 @for_left_child = @{deep_copy_array(\@features_and_values_or_thresholds_on_branch)};
417 push @for_left_child, $feature_and_less_than_value_string;
418 @for_right_child = @{deep_copy_array(\@features_and_values_or_thresholds_on_branch)};
419 push @for_right_child, $feature_and_greater_than_value_string;
420 } else {
421 @for_left_child = ($feature_and_less_than_value_string);
422 @for_right_child = ($feature_and_greater_than_value_string);
423 }
424 my ($error1,$beta1,$XMatrix1,$YVector1) =
425 $self->_error_for_given_sequence_of_features_and_values_or_thresholds(\@for_left_child);
426 my ($error2,$beta2,$XMatrix2,$YVector2) =
427 $self->_error_for_given_sequence_of_features_and_values_or_thresholds(\@for_right_child);
428 my $partitioning_error = max($error1, $error2);
429 push @partitioning_errors, $partitioning_error;
430 $partitioning_error_hash{$partitioning_error} = $value;
431 }
432 my $min_max_error_for_feature = min(@partitioning_errors);
433 $best_partition_point_for_feature_hash->{$feature_name} =
434 $partitioning_error_hash{$min_max_error_for_feature};
435 $best_minmax_error_for_feature_hash->{$feature_name} = $min_max_error_for_feature;
436 }
437 my $best_feature_name;
438 my $best_feature_paritioning_point;
439 my $best_minmax_error_at_partitioning_point;
440 foreach my $feature (keys %{$best_minmax_error_for_feature_hash}) {
441 if (! defined $best_minmax_error_at_partitioning_point) {
442 $best_minmax_error_at_partitioning_point = $best_minmax_error_for_feature_hash->{$feature};
443 $best_feature_name = $feature;
444 } elsif ($best_minmax_error_at_partitioning_point > $best_minmax_error_for_feature_hash->{$feature}) {
445 $best_minmax_error_at_partitioning_point = $best_minmax_error_for_feature_hash->{$feature};
446 $best_feature_name = $feature;
447 }
448 }
449 my $best_feature_partitioning_point = $best_partition_point_for_feature_hash->{$best_feature_name};
450 return ($best_feature_name,$best_minmax_error_at_partitioning_point,$best_feature_partitioning_point);
451 } else {
452 my $pattern1 = '(.+)=(.+)';
453 my $pattern2 = '(.+)<(.+)';
454 my $pattern3 = '(.+)>(.+)';
455 my @true_numeric_types;
456 my @symbolic_types;
457 my @true_numeric_types_feature_names;
458 my @symbolic_types_feature_names;
459 foreach my $item (@features_and_values_or_thresholds_on_branch) {
460 if ($item =~ /$pattern2/) {
461 push @true_numeric_types, $item;
462 push @true_numeric_types_feature_names, $1;
463 } elsif ($item =~ /$pattern3/) {
464 push @true_numeric_types, $item;
465 push @true_numeric_types_feature_names, $1;
466 } elsif ($item =~ /$pattern1/) {
467 push @symbolic_types, $item;
468 push @symbolic_types_feature_names, $1;
469 } else {
470 die "format error in the representation of feature and values or thresholds";
471 }
472 }
473 my %seen = ();
474 @true_numeric_types_feature_names = grep {$_ if !$seen{$_}++} @true_numeric_types_feature_names;
475 %seen = ();
476 @symbolic_types_feature_names = grep {$_ if !$seen{$_}++} @symbolic_types_feature_names;
477 my @bounded_intervals_numeric_types =
478 @{$self->find_bounded_intervals_for_numeric_features(\@true_numeric_types)};
479 # Calculate the upper and the lower bounds to be used when searching for the best
480 # threshold for each of the numeric features that are in play at the current node:
481 my (%upperbound, %lowerbound);
482 foreach my $feature (@true_numeric_types_feature_names) {
483 $upperbound{$feature} = undef;
484 $lowerbound{$feature} = undef;
485 }
486 foreach my $item (@bounded_intervals_numeric_types) {
487 foreach my $feature_grouping (@$item) {
488 if ($feature_grouping->[1] eq '>') {
489 $lowerbound{$feature_grouping->[0]} = $feature_grouping->[2];
490 } else {
491 $upperbound{$feature_grouping->[0]} = $feature_grouping->[2];
492 }
493 }
494 }
495 my $best_partition_point_for_feature_hash = { map {$_ => undef} @{$self->{_feature_names}} };
496 my $best_minmax_error_for_feature_hash = { map {$_ => undef} @{$self->{_feature_names}} };
497 foreach my $i (0 .. @{$self->{_feature_names}}-1) {
498 my $feature_name = $self->{_feature_names}->[$i];
499 my @values = @{$self->{_sampling_points_for_numeric_feature_hash}->{$feature_name}};
500 my @newvalues;
501 if (contained_in($feature_name, @true_numeric_types_feature_names)) {
502 if (defined($upperbound{$feature_name}) && defined($lowerbound{$feature_name}) &&
503 $lowerbound{$feature_name} >= $upperbound{$feature_name}) {
504 next;
505 } elsif (defined($upperbound{$feature_name}) && defined($lowerbound{$feature_name}) &&
506 $lowerbound{$feature_name} < $upperbound{$feature_name}) {
507 foreach my $x (@values) {
508 push @newvalues, $x if $x > $lowerbound{$feature_name} && $x <= $upperbound{$feature_name};
509 }
510 } elsif (defined($upperbound{$feature_name})) {
511 foreach my $x (@values) {
512 push @newvalues, $x if $x <= $upperbound{$feature_name};
513 }
514 } elsif (defined($lowerbound{$feature_name})) {
515 foreach my $x (@values) {
516 push @newvalues, $x if $x > $lowerbound{$feature_name};
517 }
518 } else {
519 die "Error is bound specifications in best feature calculator";
520 }
521 } else {
522 @newvalues = @{deep_copy_array(\@values)};
523 }
524 next if @newvalues < 30;
525 my @partitioning_errors;
526 my %partitioning_error_hash;
527 foreach my $value (@newvalues[10 .. $#newvalues - 10]) {
528 my $feature_and_less_than_value_string = "$feature_name" . '<' . "$value";
529 my $feature_and_greater_than_value_string = "$feature_name" . '>' . "$value";
530 my @for_left_child;
531 my @for_right_child;
532 if (@features_and_values_or_thresholds_on_branch) {
533 @for_left_child = @{deep_copy_array(\@features_and_values_or_thresholds_on_branch)};
534 push @for_left_child, $feature_and_less_than_value_string;
535 @for_right_child = @{deep_copy_array(\@features_and_values_or_thresholds_on_branch)};
536 push @for_right_child, $feature_and_greater_than_value_string;
537 } else {
538 @for_left_child = ($feature_and_less_than_value_string);
539 @for_right_child = ($feature_and_greater_than_value_string);
540 }
541 my ($error1,$beta1,$XMatrix1,$YVector1) =
542 $self->_error_for_given_sequence_of_features_and_values_or_thresholds(\@for_left_child);
543 my ($error2,$beta2,$XMatrix2,$YVector2) =
544 $self->_error_for_given_sequence_of_features_and_values_or_thresholds(\@for_right_child);
545 my $partitioning_error = max($error1, $error2);
546 push @partitioning_errors, $partitioning_error;
547 $partitioning_error_hash{$partitioning_error} = $value;
548 }
549 my $min_max_error_for_feature = min(@partitioning_errors);
550 $best_partition_point_for_feature_hash->{$feature_name} =
551 $partitioning_error_hash{$min_max_error_for_feature};
552 $best_minmax_error_for_feature_hash->{$feature_name} = $min_max_error_for_feature;
553 }
554 my $best_feature_name;
555 my $best_feature_paritioning_point;
556 my $best_minmax_error_at_partitioning_point;
557 foreach my $feature (keys %{$best_minmax_error_for_feature_hash}) {
558 if (! defined $best_minmax_error_at_partitioning_point) {
559 $best_minmax_error_at_partitioning_point = $best_minmax_error_for_feature_hash->{$feature};
560 $best_feature_name = $feature;
561 } elsif ($best_minmax_error_at_partitioning_point > $best_minmax_error_for_feature_hash->{$feature}) {
562 $best_minmax_error_at_partitioning_point = $best_minmax_error_for_feature_hash->{$feature};
563 $best_feature_name = $feature;
564 }
565 }
566 my $best_feature_partitioning_point = $best_partition_point_for_feature_hash->{$best_feature_name};
567 return ($best_feature_name,$best_minmax_error_at_partitioning_point,$best_feature_partitioning_point);
568 }
569 }
570  
571 ## This method requires that all truly numeric types only be expressed as '<' or '>'
572 ## constructs in the array of branch features and thresholds
573 sub _error_for_given_sequence_of_features_and_values_or_thresholds{
574 my $self = shift;
575 my $array_of_features_and_values_or_thresholds = shift;
576 if (@$array_of_features_and_values_or_thresholds == 0) {
577 my ($XMatrix,$YVector) = $self->construct_XMatrix_and_YVector_all_data();
578 my ($errors,$beta) = $self->estimate_regression_coefficients($XMatrix,$YVector);
579 return ($errors,$beta,$XMatrix,$YVector)
580 }
581 my $pattern1 = '(.+)=(.+)';
582 my $pattern2 = '(.+)<(.+)';
583 my $pattern3 = '(.+)>(.+)';
584 my @true_numeric_types;
585 my @symbolic_types;
586 my @true_numeric_types_feature_names;
587 my @symbolic_types_feature_names;
588 foreach my $item (@$array_of_features_and_values_or_thresholds) {
589 if ($item =~ /$pattern2/) {
590 push @true_numeric_types, $item;
591 push @true_numeric_types_feature_names, $1;
592 } elsif ($item =~ /$pattern3/) {
593 push @true_numeric_types, $item;
594 push @true_numeric_types_feature_names, $1;
595 } elsif ($item =~ /$pattern1/) {
596 push @symbolic_types, $item;
597 push @symbolic_types_feature_names, $1;
598 } else {
599 die "format error in the representation of feature and values or thresholds";
600 }
601 }
602 my %seen = ();
603 @true_numeric_types_feature_names = grep {$_ if !$seen{$_}++} @true_numeric_types_feature_names;
604 %seen = ();
605 @symbolic_types_feature_names = grep {$_ if !$seen{$_}++} @symbolic_types_feature_names;
606 my @bounded_intervals_numeric_types =
607 @{$self->find_bounded_intervals_for_numeric_features(\@true_numeric_types)};
608 # Calculate the upper and the lower bounds to be used when searching for the best
609 # threshold for each of the numeric features that are in play at the current node:
610 my (%upperbound, %lowerbound);
611 foreach my $feature (@true_numeric_types_feature_names) {
612 $upperbound{$feature} = undef;
613 $lowerbound{$feature} = undef;
614 }
615 foreach my $item (@bounded_intervals_numeric_types) {
616 foreach my $feature_grouping (@$item) {
617 if ($feature_grouping->[1] eq '>') {
618 $lowerbound{$feature_grouping->[0]} = $feature_grouping->[2];
619 } else {
620 $upperbound{$feature_grouping->[0]} = $feature_grouping->[2];
621 }
622 }
623 }
624 my %training_samples_at_node;
625 foreach my $feature_name (@true_numeric_types_feature_names) {
626 if ((defined $lowerbound{$feature_name}) && (defined $upperbound{$feature_name}) &&
627 ($upperbound{$feature_name} <= $lowerbound{$feature_name})) {
628 return (undef,undef,undef,undef);
629 } elsif ((defined $lowerbound{$feature_name}) && (defined $upperbound{$feature_name})) {
630 foreach my $sample (keys %{$self->{_training_data_hash}}) {
631 my @feature_val_pairs = @{$self->{_training_data_hash}->{$sample}};
632 foreach my $feature_and_val (@feature_val_pairs) {
633 my $value_for_feature = substr($feature_and_val, index($feature_and_val,'=')+1 );
634 my $feature_involved = substr($feature_and_val, 0, index($feature_and_val,'=') );
635 if (($feature_name eq $feature_involved) &&
636 ($lowerbound{$feature_name} < $value_for_feature) &&
637 ($value_for_feature <= $upperbound{$feature_name})) {
638 $training_samples_at_node{$sample} = 1;
639 last;
640 }
641 }
642 }
643 } elsif ((defined $upperbound{$feature_name}) && (! defined $lowerbound{$feature_name})) {
644 foreach my $sample (keys %{$self->{_training_data_hash}}) {
645 my @feature_val_pairs = @{$self->{_training_data_hash}->{$sample}};
646 foreach my $feature_and_val (@feature_val_pairs) {
647 my $value_for_feature = substr($feature_and_val, index($feature_and_val,'=')+1 );
648 my $feature_involved = substr($feature_and_val, 0, index($feature_and_val,'=') );
649 if (($feature_name eq $feature_involved) &&
650 ($value_for_feature <= $upperbound{$feature_name})) {
651 $training_samples_at_node{$sample} = 1;
652 last;
653 }
654 }
655 }
656 } elsif ((defined $lowerbound{$feature_name}) && (! defined $upperbound{$feature_name})) {
657 foreach my $sample (keys %{$self->{_training_data_hash}}) {
658 my @feature_val_pairs = @{$self->{_training_data_hash}->{$sample}};
659 foreach my $feature_and_val (@feature_val_pairs) {
660 my $value_for_feature = substr($feature_and_val, index($feature_and_val,'=')+1 );
661 my $feature_involved = substr($feature_and_val, 0, index($feature_and_val,'=') );
662 if (($feature_name eq $feature_involved) &&
663 ($value_for_feature > $lowerbound{$feature_name})) {
664 $training_samples_at_node{$sample} = 1;
665 last;
666 }
667 }
668 }
669 } else {
670 die "Ill formatted call to the '_error_for_given_sequence_...' method";
671 }
672 }
673 foreach my $feature_and_value (@symbolic_types) {
674 if ($feature_and_value =~ /$pattern1/) {
675 my ($feature,$value) = ($1,$2);
676 foreach my $sample (keys %{$self->{_training_data_hash}}) {
677 my @feature_val_pairs = @{$self->{_training_data_hash}->{$sample}};
678 foreach my $feature_and_val (@feature_val_pairs) {
679 my $feature_in_sample = substr($feature_and_val, 0, index($feature_and_val,'=') );
680 my $value_in_sample = substr($feature_and_val, index($feature_and_val,'=')+1 );
681 if (($feature eq $feature_in_sample) && ($value eq $value_in_sample)) {
682 $training_samples_at_node{$sample} = 1;
683 last;
684 }
685 }
686 }
687 }
688 }
689 my @training_samples_at_node = keys %training_samples_at_node;
690 my $matrix_rows_as_lists = [ map {my @arr = @$_; [map substr($_,index($_,'=')+1), @arr] } map {$self->{_training_data_hash}->{$_}} sort {sample_index($a) <=> sample_index($b)} @training_samples_at_node ];;
691 map {push @$_, 1} @{$matrix_rows_as_lists};
692 my $XMatrix = Math::GSL::Matrix->new(scalar @{$matrix_rows_as_lists}, scalar @{$matrix_rows_as_lists->[0]});
693 pairmap {$XMatrix->set_row($a,$b)} ( 0..@{$matrix_rows_as_lists}-1, @{$matrix_rows_as_lists} )
694 [ map { $_, $_ + @{$matrix_rows_as_lists} } ( 0 .. @{$matrix_rows_as_lists}-1 ) ];
695 if ($self->{_debug3_r}) {
696 print "\nXMatrix as its transpose:";
697 my $displayX = transpose($XMatrix);
698 display_matrix($displayX);
699 }
700 my @dependent_var_values = map {my $val = $self->{_samples_dependent_var_val_hash}->{$_}; substr($val,index($val,'=')+1)} sort {sample_index($a) <=> sample_index($b)} @training_samples_at_node;
701 print "dependent var values: @dependent_var_values\n" if $self->{_debug1_r};
702 my $YVector = Math::GSL::Matrix->new(scalar @{$matrix_rows_as_lists}, 1);
703 pairmap {$YVector->set_row($a,$b)} ( 0..@{$matrix_rows_as_lists}-1, map {[$_]} @dependent_var_values )
704 [ map { $_, $_ + @{$matrix_rows_as_lists} } ( 0 .. @{$matrix_rows_as_lists}-1 ) ];
705 if ($self->{_debug3_r}) {
706 print "\nYVector:";
707 my $displayY = transpose($YVector);
708 display_matrix($displayY);
709 }
710 my ($error,$beta) = $self->estimate_regression_coefficients($XMatrix, $YVector);
711 if ($self->{_debug3_r}) {
712 display_matrix($beta);
713 print("\n\nerror distribution at node: ", $error);
714 }
715 return ($error,$beta,$XMatrix,$YVector);
716 }
717  
718 #----------------------------- Predict with Regression Tree ------------------------------
719  
720 sub predictions_for_all_data_used_for_regression_estimation {
721 my $self = shift;
722 my $root_node = shift;
723 my %predicted_values;
724 my %leafnode_for_values;
725 my $ncols = $self->{_XMatrix}->cols;
726 if ($ncols == 2) {
727 foreach my $sample (keys %{$self->{_training_data_hash}}) {
728 my $pattern = '(\S+)\s*=\s*(\S+)';
729 $self->{_training_data_hash}->{$sample}->[0] =~ /$pattern/;
730 my ($feature,$value) = ($1, $2);
731 my $new_feature_and_value = "$feature=$value";
732 my $answer = $self->prediction_for_single_data_point($root_node, [$new_feature_and_value]);
733 $predicted_values{$value} = $answer->{'prediction'};
734 $leafnode_for_values{"$value,$predicted_values{$value}"} = $answer->{'solution_path'}->[-1];
735 }
736 my @leaf_nodes_used = keys %{{map {$_ => 1} values %leafnode_for_values}};
737 foreach my $leaf (@leaf_nodes_used) {
738 my @xvalues;
739 my @yvalues;
740 foreach my $x (sort {$a <=> $b} keys %predicted_values) {
741 if ($leaf == $leafnode_for_values{"$x,$predicted_values{$x}"}) {
742 push @xvalues, $x;
743 push @yvalues, $predicted_values{$x};
744 }
745 }
746 $self->{_output_for_plots}->{scalar(keys %{$self->{_output_for_plots}}) + 1} = [\@xvalues,\@yvalues];
747 }
748 } elsif ($ncols == 3) {
749 foreach my $sample (keys %{$self->{_training_data_hash}}) {
750 my $pattern = '(\S+)\s*=\s*(\S+)';
751 my @features_and_vals;
752 my @newvalues;
753 foreach my $feature_and_val (@{$self->{_training_data_hash}->{$sample}}) {
754 $feature_and_val =~ /$pattern/;
755 my ($feature,$value) = ($1, $2);
756 push @newvalues, $value;
757 my $new_feature_and_value = "$feature=$value";
758 push @features_and_vals, $new_feature_and_value;
759 }
760 my $answer = $self->prediction_for_single_data_point($root_node, \@features_and_vals);
761 $predicted_values{"@newvalues"} = $answer->{'prediction'};
762 $leafnode_for_values{"@newvalues"} = $answer->{'solution_path'}->[-1];
763 }
764 my @leaf_nodes_used = keys %{{map {$_ => 1} values %leafnode_for_values}};
765 foreach my $leaf (@leaf_nodes_used) {
766 my @xvalues;
767 my @yvalues;
768 foreach my $kee (keys %predicted_values) {
769 if ($leaf == $leafnode_for_values{$kee}) {
770 push @xvalues, $kee;
771 push @yvalues, $predicted_values{$kee};
772 }
773 }
774 $self->{_output_for_surface_plots}->{scalar(keys %{$self->{_output_for_surface_plots}}) + 1} = [\@xvalues,\@yvalues];
775 }
776 } else {
777 die "\nThe module does not yet include regression based predictions when you have more than " .
778 "two predictor variables --- on account of the difficulty of properly visualizing the " .
779 "quality of such predictions. Future versions of this modue may nonetheless allow for " .
780 "regression based predictions in such cases (depending on user feedback)";
781 }
782 }
783  
784 sub bulk_predictions_for_data_in_a_csv_file {
785 my $self = shift;
786 my ($root_node, $filename, $columns) = @_;
787 die("Aborted. bulk_predictions_for_data_in_a_csv_file() is only for CSV files") unless $filename =~ /\.csv$/;
788 my $basefilename = basename($filename, '.csv');
789 my $out_file_name = $basefilename . "_output.csv";
790 unlink $out_file_name if -e $out_file_name;
791 open FILEOUT, "> $out_file_name" or die "Unable to open $out_file_name: $!";
792 $|++;
793 open FILEIN, $filename or die "Unable to open $filename: $!";
794 my $record_index = 0;
795 my @fieldnames;
796 while (<FILEIN>) {
797 next if /^[ ]*\r?\n?$/;
798 $_ =~ s/\r?\n?$//;
799 my $record = $self->{_csv_cleanup_needed} ? cleanup_csv($_) : $_;
800 if ($record_index == 0) {
801 @fieldnames = grep $_, split /,/, substr($record, index($record,','));
802 $record_index++;
803 next;
804 }
805 my @feature_vals = grep $_, split /,/, $record;
806 my @features_and_vals;
807 foreach my $col_index (@$columns) {
808 push @features_and_vals, "$fieldnames[$col_index-1]=$feature_vals[$col_index-1]"
809 }
810 my $answer = $self->prediction_for_single_data_point($root_node, \@features_and_vals);
811 print FILEOUT "$record => $answer->{'prediction'}\n";
812 }
813 close FILEIN;
814 close FILEOUT;
815 }
816  
817 sub mse_for_tree_regression_for_all_training_samples {
818 my $self = shift;
819 my $root_node = shift;
820 my %predicted_values;
821 my %dependent_var_values;
822 my %leafnode_for_values;
823 my $total_error = 0.0;
824 my %samples_at_leafnode;
825 foreach my $sample (keys %{$self->{_training_data_hash}}) {
826 my $pattern = '(\S+)\s*=\s*(\S+)';
827 my @features_and_vals;
828 my $newvalue;
829 foreach my $feature_and_val (@{$self->{_training_data_hash}->{$sample}}) {
830 $feature_and_val =~ /$pattern/;
831 my ($feature,$value) = ($1, $2);
832 if (contained_in($feature, @{$self->{_feature_names}})) {
833 my $new_feature_and_value = "$feature=$value";
834 push @features_and_vals, "$feature=$value";
835 }
836 $newvalue = $value;
837 }
838 my $answer = $self->prediction_for_single_data_point($root_node, \@features_and_vals);
839 $predicted_values{"@features_and_vals"} = $answer->{'prediction'};
840 $self->{_samples_dependent_var_val_hash}->{$sample} =~ /$pattern/;
841 my ($dep_feature,$dep_value) = ($1, $2);
842 $dependent_var_values{"@features_and_vals"} = $dep_value;
843 my $leafnode_for_sample = $answer->{'solution_path'}->[-1];
844 $leafnode_for_values{"@features_and_vals"} = $answer->{'solution_path'}->[-1];
845 my $error_for_sample = abs($predicted_values{"@features_and_vals"} - $dependent_var_values{"@features_and_vals"});
846 $total_error += $error_for_sample;
847 if (exists $samples_at_leafnode{$leafnode_for_sample}) {
848 push @{$samples_at_leafnode{$leafnode_for_sample}}, $sample;
849 } else {
850 $samples_at_leafnode{$leafnode_for_sample} = [$sample];
851 }
852 }
853 my @leafnodes_used = keys %{{map {$_ => 1} values %leafnode_for_values}};
854 my $errors_at_leafnode = { map {$_ => 0.0} @leafnodes_used };
855 foreach my $kee (keys %predicted_values) {
856 foreach my $leaf (@leafnodes_used) {
857 $errors_at_leafnode->{$leaf} += abs($predicted_values{$kee} - $dependent_var_values{$kee})
858 if $leaf == $leafnode_for_values{$kee};
859 }
860 }
861 my $total_error_per_data_point = $total_error / (scalar keys %{$self->{_training_data_hash}});
862 print "\n\nTree Regression: Total MSE per sample with tree regression: $total_error_per_data_point\n";
863 foreach my $leafnode (@leafnodes_used) {
864 my $error_per_data_point = $errors_at_leafnode->{$leafnode} / @{$samples_at_leafnode{$leafnode}};
865 print " MSE per sample at leafnode $leafnode: $error_per_data_point\n";
866 }
867 my $error_with_linear_regression = $self->{_root_node}->get_node_error();
868 print "For comparision, the MSE per sample error with Linear Regression: $error_with_linear_regression\n";
869 }
870  
871 ## Calculated the predicted value for the dependent variable from a given value for all
872 ## the predictor variables.
873 sub prediction_for_single_data_point {
874 my $self = shift;
875 my $root_node = shift;
876 my $features_and_values = shift;
877 die "Error in the names you have used for features and/or values when calling " .
878 "prediction_for_single_data_point()" unless $self->_check_names_used($features_and_values);
879 my $pattern = '(\S+)\s*=\s*(\S+)';
880 my @new_features_and_values;
881 foreach my $feature_and_value (@$features_and_values) {
882 $feature_and_value =~ /$pattern/;
883 my ($feature,$value) = ($1, $2);
884 push @new_features_and_values, "$feature=$value";
885 }
886 my %answer;
887 $answer{'solution_path'} = [];
888 my $prediction = $self->recursive_descent_for_prediction($root_node,\@new_features_and_values, \%answer);
889 $answer{'solution_path'} = [reverse( @{$answer{'solution_path'}} )];
890 return \%answer;
891 }
892  
893 sub recursive_descent_for_prediction {
894 my $self = shift;
895 my $node = shift;
896 my $feature_and_values = shift;
897 my $answer = shift;
898 my @children = @{$node->get_children()};
899 if (@children == 0) {
900 my $leaf_node_prediction = $node->node_prediction_from_features_and_values($feature_and_values);
901 $answer->{'prediction'} = $leaf_node_prediction;
902 push @{$answer->{'solution_path'}}, $node->get_serial_num();
903 return $answer;
904 }
905 my $feature_tested_at_node = $node->get_feature();
906 print "\nFeature tested at node for prediction: $feature_tested_at_node\n" if $self->{_debug3};
907 my $value_for_feature;
908 my $path_found;
909 my $pattern = '(\S+)\s*=\s*(\S+)';
910 my ($feature,$value);
911 foreach my $feature_and_value (@$feature_and_values) {
912 $feature_and_value =~ /$pattern/;
913 my ($feature,$value) = ($1, $2);
914 if ($feature eq $feature_tested_at_node) {
915 $value_for_feature = $value;
916 }
917 }
918 if (! defined $value_for_feature) {
919 my $leaf_node_prediction = $node->node_prediction_from_features_and_values($feature_and_values);
920 $answer->{'prediction'} = $leaf_node_prediction;
921 push @{$answer->{'solution_path'}}, $node->get_serial_num();
922 return $answer;
923 }
924 foreach my $child (@children) {
925 my @branch_features_and_values = @{$child->get_branch_features_and_values_or_thresholds()};
926 my $last_feature_and_value_on_branch = $branch_features_and_values[-1];
927 my $pattern1 = '(.+)<(.+)';
928 my $pattern2 = '(.+)>(.+)';
929 if ($last_feature_and_value_on_branch =~ /$pattern1/) {
930 my ($feature,$threshold) = ($1, $2);
931 if ($value_for_feature <= $threshold) {
932 $path_found = 1;
933 $answer = $self->recursive_descent_for_prediction($child, $feature_and_values, $answer);
934 push @{$answer->{'solution_path'}}, $node->get_serial_num();
935 last;
936 }
937 }
938 if ($last_feature_and_value_on_branch =~ /$pattern2/) {
939 my ($feature,$threshold) = ($1, $2);
940 if ($value_for_feature > $threshold) {
941 $path_found = 1;
942 $answer = $self->recursive_descent_for_prediction($child, $feature_and_values, $answer);
943 push @{$answer->{'solution_path'}}, $node->get_serial_num();
944 last;
945 }
946 }
947 }
948 return $answer if $path_found;
949 }
950  
951 #-------------------------------------- Utility Methods ----------------------------------------
952  
953 ## This method is used to verify that you used legal feature names in the test
954 ## sample that you want to classify with the decision tree.
955 sub _check_names_used {
956 my $self = shift;
957 my $features_and_values_test_data = shift;
958 my @features_and_values_test_data = @$features_and_values_test_data;
959 my $pattern = '(\S+)\s*=\s*(\S+)';
960 foreach my $feature_and_value (@features_and_values_test_data) {
961 $feature_and_value =~ /$pattern/;
962 my ($feature,$value) = ($1,$2);
963 die "Your test data has formatting error" unless defined($feature) && defined($value);
964 return 0 unless contained_in($feature, @{$self->{_feature_names}});
965 }
966 return 1;
967 }
968  
969 sub display_all_plots {
970 my $self = shift;
971 my $ncols = $self->{_XMatrix}->cols;
972 unlink "regression_plots.png" if -e "regression_plots.png";
973 my $master_datafile = $self->{_training_datafile};
974 my $filename = basename($master_datafile);
975 my $temp_file = "__temp_" . $filename;
976 unlink $temp_file if -e $temp_file;
977 open OUTPUT, ">$temp_file"
978 or die "Unable to open a temp file in this directory: $!\n";
979 if ($ncols == 2) {
980 my @predictor_entries = $self->{_XMatrix}->col(0)->as_list;
981 my @dependent_val_vals = $self->{_YVector}->col(0)->as_list;
982 map {print OUTPUT "$predictor_entries[$_] $dependent_val_vals[$_]\n"} 0 .. $self->{_XMatrix}->rows - 1;
983 print OUTPUT "\n\n";
984 foreach my $plot (sort {$a <=> $b} keys %{$self->{_output_for_plots}}) {
985 map {print OUTPUT "$self->{_output_for_plots}->{$plot}->[0]->[$_] $self->{_output_for_plots}->{$plot}->[1]->[$_]\n"} 0 .. @{$self->{_output_for_plots}->{$plot}->[0]} - 1;
986 print OUTPUT "\n\n"
987 }
988 close OUTPUT;
989 my $gplot = Graphics::GnuplotIF->new( persist => 1 );
990 my $hardcopy_plot = Graphics::GnuplotIF->new();
991 $hardcopy_plot->gnuplot_cmd('set terminal png', "set output \"regression_plots.png\"");
992 $gplot->gnuplot_cmd( "set noclip" );
993 $gplot->gnuplot_cmd( "set pointsize 2" );
994 my $arg_string = "";
995 foreach my $i (0 .. scalar(keys %{$self->{_output_for_plots}})) {
996 if ($i == 0) {
997 $arg_string .= "\"$temp_file\" index $i using 1:2 notitle with points lt -1 pt 1, ";
998 } elsif ($i == 1) {
999 $arg_string .= "\"$temp_file\" index $i using 1:2 title \"linear regression\" with lines lt 1 lw 4, ";
1000 } elsif ($i == 2) {
1001 $arg_string .= "\"$temp_file\" index $i using 1:2 title \"tree regression\" with lines lt 3 lw 4, ";
1002 } else {
1003 $arg_string .= "\"$temp_file\" index $i using 1:2 notitle with lines lt 3 lw 4, ";
1004 }
1005 }
1006 $arg_string = $arg_string =~ /^(.*),[ ]+$/;
1007 $arg_string = $1;
1008 $hardcopy_plot->gnuplot_cmd( "plot $arg_string" );
1009 $gplot->gnuplot_cmd( "plot $arg_string" );
1010 $gplot->gnuplot_pause(-1);
1011 } elsif ($ncols == 3) {
1012 my @dependent_val_vals = $self->{_YVector}->col(0)->as_list;
1013 foreach my $i (0 .. $self->{_XMatrix}->rows - 1) {
1014 my @onerow = $self->{_XMatrix}->row($i)->as_list;
1015 pop @onerow;
1016 print OUTPUT "@onerow $dependent_val_vals[$i]\n";
1017 }
1018 print OUTPUT "\n\n";
1019 foreach my $plot (sort {$a <=> $b} keys %{$self->{_output_for_surface_plots}}) {
1020 my @plot_data = @{$self->{_output_for_surface_plots}->{$plot}};
1021 my @predictors = @{$plot_data[0]};
1022 my @predictions = @{$plot_data[1]};
1023 map {print OUTPUT "$predictors[$_] $predictions[$_]\n"} 0 .. @predictions - 1;
1024 print OUTPUT "\n\n"
1025 }
1026 close OUTPUT;
1027 my $gplot = Graphics::GnuplotIF->new( persist => 1 );
1028 my $hardcopy_plot = Graphics::GnuplotIF->new();
1029 $hardcopy_plot->gnuplot_cmd('set terminal png', "set output \"regression_plots.png\"");
1030 $gplot->gnuplot_cmd( "set noclip" );
1031 $gplot->gnuplot_cmd( "set pointsize 2" );
1032 my $arg_string = "";
1033 foreach my $i (0 .. scalar(keys %{$self->{_output_for_surface_plots}})) {
1034 if ($i == 0) {
1035 $arg_string .= "\"$temp_file\" index $i using 1:2:3 notitle with points lt -1 pt 1, ";
1036 } elsif ($i == 1) {
1037 $arg_string .= "\"$temp_file\" index $i using 1:2:3 title \"linear regression\" with points lt 1 pt 2, ";
1038 } elsif ($i == 2) {
1039 $arg_string .= "\"$temp_file\" index $i using 1:2:3 title \"tree regression\" with points lt 3 pt 3, ";
1040 } else {
1041 $arg_string .= "\"$temp_file\" index $i using 1:2:3 notitle with points lt 3 pt 3, ";
1042 }
1043 }
1044 $arg_string = $arg_string =~ /^(.*),[ ]+$/;
1045 $arg_string = $1;
1046 $hardcopy_plot->gnuplot_cmd( "splot $arg_string" );
1047 $gplot->gnuplot_cmd( "splot $arg_string" );
1048 $gplot->gnuplot_pause(-1);
1049 } else {
1050 die "no visual displays for regression from more then 2 predictor vars";
1051 }
1052 }
1053  
1054 sub DESTROY {
1055 unlink glob "__temp_*";
1056 }
1057  
1058 ############################################## Utility Routines ##########################################
1059 # checks whether an element is in an array:
1060 sub contained_in {
1061 my $ele = shift;
1062 my @array = @_;
1063 my $count = 0;
1064 map {$count++ if $ele eq $_} @array;
1065 return $count;
1066 }
1067  
1068 sub minmax {
1069 my $arr = shift;
1070 my ($min, $max);
1071 foreach my $i (0..@{$arr}-1) {
1072 if ( (!defined $min) || ($arr->[$i] < $min) ) {
1073 $min = $arr->[$i];
1074 }
1075 if ( (!defined $max) || ($arr->[$i] > $max) ) {
1076 $max = $arr->[$i];
1077 }
1078 }
1079 return ($min, $max);
1080 }
1081  
1082 sub sample_index {
1083 my $arg = shift;
1084 $arg =~ /_(.+)$/;
1085 return $1;
1086 }
1087  
1088 sub check_for_illegal_params {
1089 my @params = @_;
1090 my @legal_params = qw / training_datafile
1091 max_depth_desired
1092 dependent_variable_column
1093 predictor_columns
1094 mse_threshold
1095 need_data_normalization
1096 jacobian_choice
1097 csv_cleanup_needed
1098 debug1_r
1099 debug2_r
1100 debug3_r
1101 /;
1102 my $found_match_flag;
1103 foreach my $param (@params) {
1104 foreach my $legal (@legal_params) {
1105 $found_match_flag = 0;
1106 if ($param eq $legal) {
1107 $found_match_flag = 1;
1108 last;
1109 }
1110 }
1111 last if $found_match_flag == 0;
1112 }
1113 return $found_match_flag;
1114 }
1115  
1116 sub cleanup_csv {
1117 my $line = shift;
1118 $line =~ tr/\/:?()[]{}'/ /;
1119 # my @double_quoted = substr($line, index($line,',')) =~ /\"[^\"]+\"/g;
1120 my @double_quoted = substr($line, index($line,',')) =~ /\"[^\"]*\"/g;
1121 for (@double_quoted) {
1122 my $item = $_;
1123 $item = substr($item, 1, -1);
1124 $item =~ s/^\s+|,|\s+$//g;
1125 $item = join '_', split /\s+/, $item;
1126 substr($line, index($line, $_), length($_)) = $item;
1127 }
1128 my @white_spaced = $line =~ /,(\s*[^,]+)(?=,|$)/g;
1129 for (@white_spaced) {
1130 my $item = $_;
1131 $item =~ s/\s+/_/g;
1132 $item =~ s/^\s*_|_\s*$//g;
1133 substr($line, index($line, $_), length($_)) = $item;
1134 }
1135 $line =~ s/,\s*(?=,|$)/,NA/g;
1136 return $line;
1137 }
1138  
1139 sub transpose {
1140 my $matrix = shift;
1141 my $num_rows = $matrix->rows();
1142 my $num_cols = $matrix->cols();
1143 my $transpose = Math::GSL::Matrix->new($num_cols, $num_rows);
1144 foreach my $i (0..$num_rows-1) {
1145 my @row = $matrix->row($i)->as_list;
1146 $transpose->set_col($i, \@row );
1147 }
1148 return $transpose;
1149 }
1150  
1151 sub vector_subtract {
1152 my $vec1 = shift;
1153 my $vec2 = shift;
1154 die "wrong data types for vector subtract calculation\n" if @$vec1 != @$vec2;
1155 my @result;
1156 foreach my $i (0..@$vec1-1){
1157 push @result, $vec1->[$i] - $vec2->[$i];
1158 }
1159 return @result;
1160 }
1161  
1162 sub vector_norm {
1163 my $vec = shift; # assume it to be a column vector
1164 my ($rows, $cols) = $vec->dim;
1165 die "vector_norm() can only be called for a single column matrix" if $cols > 1;
1166 my @norm = (transpose($vec) * $vec)->as_list;
1167 return sqrt($norm[0]);
1168 }
1169  
1170 sub display_matrix {
1171 my $matrix = shift;
1172 my $nrows = $matrix->rows();
1173 my $ncols = $matrix->cols();
1174 print "\nDisplaying a matrix of size $nrows rows and $ncols columns:\n";
1175 foreach my $i (0..$nrows-1) {
1176 my $row = $matrix->row($i);
1177 my @row_as_list = $row->as_list;
1178 map { printf("%.4f ", $_) } @row_as_list;
1179 print "\n";
1180 }
1181 print "\n\n";
1182 }
1183  
1184 # Meant only for an array of strings (no nesting):
1185 sub deep_copy_array {
1186 my $ref_in = shift;
1187 my $ref_out;
1188 return [] if scalar @$ref_in == 0;
1189 foreach my $i (0..@{$ref_in}-1) {
1190 $ref_out->[$i] = $ref_in->[$i];
1191 }
1192 return $ref_out;
1193 }
1194  
1195  
1196 ############################################# Class RTNode #############################################
1197  
1198 # The nodes of a regression tree are instances of this class:
1199 package RTNode;
1200  
1201 use strict;
1202 use Carp;
1203  
1204 # $feature is the feature test at the current node. $branch_features_and_values is
1205 # an anonymous array holding the feature names and corresponding values on the path
1206 # from the root to the current node:
1207 sub new {
1208 my ($class, $feature, $error, $beta, $branch_features_and_values_or_thresholds, $rt, $root_or_not) = @_;
1209 $root_or_not = '' if !defined $root_or_not;
1210 if ($root_or_not eq 'root') {
1211 $rt->{nodes_created} = -1;
1212 $rt->{class_names} = undef;
1213 }
1214 my $self = {
1215 _rt => $rt,
1216 _feature => $feature,
1217 _error => $error,
1218 _beta => $beta,
1219 _branch_features_and_values_or_thresholds => $branch_features_and_values_or_thresholds,
1220 _num_data_points => undef,
1221 _XMatrix => undef,
1222 _YVector => undef,
1223 _linked_to => [],
1224 };
1225 bless $self, $class;
1226 $self->{_serial_number} = $self->get_next_serial_num();
1227 return $self;
1228 }
1229  
1230 sub node_prediction_from_features_and_values {
1231 my $self = shift;
1232 my $feature_and_values = shift;
1233 my $ncols = $self->{_XMatrix}->cols;
1234 my $pattern = '(\S+)\s*=\s*(\S+)';
1235 my ($feature,$value);
1236 my @Xlist;
1237 foreach my $feature_name (@{$self->{_rt}->{_feature_names}}) {
1238 foreach my $feature_and_value (@{$feature_and_values}) {
1239 $feature_and_value =~ /$pattern/;
1240 my ($feature, $value) = ($1, $2);
1241 push @Xlist, $value if $feature_name eq $feature;
1242 }
1243 }
1244 push @Xlist, 1;
1245 my $dataMatrix = Math::GSL::Matrix->new(1, $ncols);
1246 $dataMatrix->set_row(0, \@Xlist);
1247 my $prediction = $dataMatrix * $self->get_node_beta();
1248 return $prediction->get_elem(0,0);
1249 }
1250  
1251 sub node_prediction_from_data_as_matrix {
1252 my $self = shift;
1253 my $dataMatrix = shift;
1254 my $prediction = $dataMatrix * $self->get_node_beta();
1255 return $prediction->get_elem(0,0);
1256 }
1257  
1258 sub node_prediction_from_data_as_list {
1259 my $self = shift;
1260 my $data_as_list = shift;
1261 my @data_arr = @{$data_as_list};
1262 my $ncols = $self->{_XMatrix}->cols;
1263 die "wrong number of elements in data list" if @data_arr != $ncols - 1;
1264 push @data_arr, 1;
1265 my $dataMatrix = Math::GSL::Matrix->new(1, $self->{_XMatrix}->cols);
1266 my $prediction = $dataMatrix * $self->get_node_beta();
1267 return $prediction->get_elem(0,0);
1268 }
1269  
1270 sub how_many_nodes {
1271 my $self = shift;
1272 return $self->{_rt}->{nodes_created} + 1;
1273 }
1274  
1275 sub get_num_data_points {
1276 my $self = shift;
1277 return $self->{_num_data_points};
1278 }
1279  
1280 sub set_num_data_points {
1281 my $self = shift;
1282 my $how_many = shift;
1283 $self->{_num_data_points} = $how_many;
1284 }
1285  
1286 sub set_node_XMatrix {
1287 my $self = shift;
1288 my $xmatrix = shift;
1289 $self->{_XMatrix} = $xmatrix;
1290 }
1291  
1292 sub get_node_XMatrix {
1293 my $self = shift;
1294 return $self->{_XMatrix};
1295 }
1296  
1297 sub set_node_YVector {
1298 my $self = shift;
1299 my $yvector = shift;
1300 $self->{_YVector} = $yvector;
1301 }
1302  
1303 sub get_node_YVector {
1304 my $self = shift;
1305 return $self->{_YVector};
1306 }
1307  
1308 sub set_node_error {
1309 my $self = shift;
1310 my $error = shift;
1311 $self->{_error} = $error;
1312 }
1313  
1314 sub get_node_error {
1315 my $self = shift;
1316 return $self->{_error};
1317 }
1318  
1319 sub set_node_beta {
1320 my $self = shift;
1321 my $beta = shift;
1322 $self->{_beta} = $beta;
1323 }
1324  
1325 sub get_node_beta {
1326 my $self = shift;
1327 return $self->{_beta};
1328 }
1329  
1330 sub get_next_serial_num {
1331 my $self = shift;
1332 $self->{_rt}->{nodes_created} += 1;
1333 return $self->{_rt}->{nodes_created};
1334 }
1335  
1336 sub get_serial_num {
1337 my $self = shift;
1338 $self->{_serial_number};
1339 }
1340  
1341 # this returns the feature test at the current node
1342 sub get_feature {
1343 my $self = shift;
1344 return $self->{ _feature };
1345 }
1346  
1347 sub set_feature {
1348 my $self = shift;
1349 my $feature = shift;
1350 $self->{_feature} = $feature;
1351 }
1352  
1353 sub get_branch_features_and_values_or_thresholds {
1354 my $self = shift;
1355 return $self->{_branch_features_and_values_or_thresholds};
1356 }
1357  
1358 sub get_children {
1359 my $self = shift;
1360 return $self->{_linked_to};
1361 }
1362  
1363 sub add_child_link {
1364 my ($self, $new_node, ) = @_;
1365 push @{$self->{_linked_to}}, $new_node;
1366 }
1367  
1368 sub delete_all_links {
1369 my $self = shift;
1370 $self->{_linked_to} = undef;
1371 }
1372  
1373 sub display_node {
1374 my $self = shift;
1375 my $feature_at_node = $self->get_feature() || " ";
1376 my $serial_num = $self->get_serial_num();
1377 my @branch_features_and_values_or_thresholds = @{$self->get_branch_features_and_values_or_thresholds()};
1378 print "\n\nNODE $serial_num" .
1379 ":\n Branch features and values to this node: @branch_features_and_values_or_thresholds" .
1380 "\n Best feature test at current node: $feature_at_node\n\n";
1381 $self->{_rt}->estimate_regression_coefficients($self->get_node_XMatrix(), $self->get_node_YVector(), 1);
1382 }
1383  
1384 sub display_regression_tree {
1385 my $self = shift;
1386 my $offset = shift;
1387 my $serial_num = $self->get_serial_num();
1388 if (@{$self->get_children()} > 0) {
1389 my $feature_at_node = $self->get_feature() || " ";
1390 my @branch_features_and_values_or_thresholds = @{$self->get_branch_features_and_values_or_thresholds()};
1391 print "NODE $serial_num: $offset BRANCH TESTS TO NODE: @branch_features_and_values_or_thresholds\n";
1392 my $second_line_offset = "$offset" . " " x (8 + length("$serial_num"));
1393 print "$second_line_offset" . "Decision Feature: $feature_at_node\n\n";
1394 $offset .= " ";
1395 foreach my $child (@{$self->get_children()}) {
1396 $child->display_regression_tree($offset);
1397 }
1398 } else {
1399 my @branch_features_and_values_or_thresholds = @{$self->get_branch_features_and_values_or_thresholds()};
1400 print "NODE $serial_num: $offset BRANCH TESTS TO LEAF NODE: @branch_features_and_values_or_thresholds\n";
1401 my $second_line_offset = "$offset" . " " x (8 + length("$serial_num"));
1402 }
1403 }
1404  
1405 1;