| 1 | # [[[ HEADER ]]] | ||
| 2 | package MLPerl::Classifier::KNeighbors; | ||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | use RPerl::AfterSubclass; | ||
| 6 | our $VERSION = 0.007_000; | ||
| 7 | |||
| 8 | # [[[ OO INHERITANCE ]]] | ||
| 9 | use parent qw(MLPerl::Classifier); | ||
| 10 | use MLPerl::Classifier; | ||
| 11 | |||
| 12 | # [[[ CRITICS ]]] | ||
| 13 | ## no critic qw(ProhibitUselessNoCritic ProhibitMagicNumbers RequireCheckedSyscalls) # USER DEFAULT 1: allow numeric values & print operator | ||
| 14 | ## no critic qw(RequireInterpolationOfMetachars) # USER DEFAULT 2: allow single-quoted control characters & sigils | ||
| 15 | ## no critic qw(ProhibitCStyleForLoops) # USER DEFAULT 6: allow C-style for() loop headers | ||
| 16 | ## no critic qw(ProhibitParensWithBuiltins) # USER DEFAULT 7: allow explicit parentheses for clearer order-of-operations precedence | ||
| 17 | ## no critic qw(ProhibitExcessComplexity) # SYSTEM SPECIAL 5: allow complex code inside subroutines, must be after line 1 | ||
| 18 | ## no critic qw(RequireCarping) # SYSTEM SPECIAL 13: allow die instead of croak | ||
| 19 | |||
| 20 | # [[[ INCLUDES ]]] | ||
| 21 | use MLPerl::Classifier::KNeighbors::Neighbor2D; | ||
| 22 | #use Data::Dumper; | ||
| 23 | |||
| 24 | # DEV NOTE, CORRELATION #MLCKNN00: unpredictable behavior when (number of unique train_classifications > 2) or (n_neighbors is even) | ||
| 25 | # because this allows nearest neighbors' classification counts to be equal; | ||
| 26 | # see 'NEED ANSWER: selects arbitrary classification when counts are equal, properly handle equal classification counts?' | ||
| 27 | |||
| 28 | # PYTHON | ||
| 29 | # KNeighborsClassifier( | ||
| 30 | # algorithm='auto', | ||
| 31 | # leaf_size=30, | ||
| 32 | # metric='minkowski', | ||
| 33 | # metric_params=None, | ||
| 34 | # n_jobs=None, | ||
| 35 | # n_neighbors=3, | ||
| 36 | # p=2, | ||
| 37 | # weights='uniform') | ||
| 38 | |||
| 39 | # [[[ OO PROPERTIES ]]] | ||
| 40 | our hashref $properties = { | ||
| 41 | algorithm => my string $TYPED_algorithm = 'auto', # default | ||
| 42 | leaf_size => my integer $TYPED_leaf_size = 30, # default | ||
| 43 | metric => my string $TYPED_metric = 'minkowski', # default | ||
| 44 | # metric_params => my FOO $TYPED_metric_params = ..., # NEED UPGRADE: what kind of data structure should this be? | ||
| 45 | n_jobs => my integer $TYPED_n_jobs = 1, # number of parallel jobs to run for neighbors search; -1 means using all processors | ||
| 46 | n_neighbors => my integer $TYPED_n_neighbors = 3, # default | ||
| 47 | p => my integer $TYPED_p = 2, # default; power parameter for the Minkowski metric | ||
| 48 | weights => my string $TYPED_weights = 'uniform', # default | ||
| 49 | |||
| 50 | train_data => my number_arrayref_arrayref $TYPED_train_data = undef, | ||
| 51 | train_classifications => my string_arrayref $TYPED_train_classifications = undef | ||
| 52 | }; | ||
| 53 | |||
| 54 | # NEED UPGRADE: change Neighbor2D to inherit from MathPerl::...::Point2D??? | ||
| 55 | |||
| 56 | # NEED UPGRADE, FUTURE META-PARAMETERS: choice between parallelizing across training points VS serial saving only nearest k training points VS hybrid serialized nearest k training points w/ follow-up combination of nearest k's | ||
| 57 | |||
| 58 | # [[[ SUBROUTINES & OO METHODS ]]] | ||
| 59 | |||
| 60 | # no actual fitting for KNN, just set properties | ||
| 61 | sub fit { | ||
| 62 | { my void::method $RETURN_TYPE }; | ||
| 63 | ( my MLPerl::Classifier::KNeighbors $self, | ||
| 64 | my number_arrayref_arrayref $train_data, | ||
| 65 | my string_arrayref $train_classifications ) = @ARG; | ||
| 66 | |||
| 67 | $self->{train_data} = $train_data; | ||
| 68 | $self->{train_classifications} = $train_classifications; | ||
| 69 | |||
| 70 | return; | ||
| 71 | } | ||
| 72 | |||
| 73 | |||
| 74 | # repeatedly call predict() for timing purposes | ||
| 75 | sub predict_repeat { | ||
| 76 | { my string_arrayref::method $RETURN_TYPE }; | ||
| 77 | ( my MLPerl::Classifier::KNeighbors $self, my number_arrayref_arrayref $test_data, my integer $timing_repetitions ) = @ARG; | ||
| 78 | |||
| 79 | my string_arrayref $tests_classifications; | ||
| 80 | |||
| 81 | for (my integer $repetition = 0; $repetition < $timing_repetitions; $repetition++) { | ||
| 82 | $tests_classifications = $self->predict($test_data); | ||
| 83 | } | ||
| 84 | |||
| 85 | # print {*STDERR} 'in MLPerl::Classifier::KNeighbors::predict_repeat(), about to return $tests_classifications =', "\n", string_arrayref_to_string($tests_classifications), "\n"; | ||
| 86 | |||
| 87 | return $tests_classifications; | ||
| 88 | } | ||
| 89 | |||
| 90 | |||
| 91 | # repeatedly call predict_metric_euclidean_weights_uniform() for timing purposes | ||
| 92 | sub predict_repeat_metric_euclidean_weights_uniform { | ||
| 93 | { my string_arrayref::method $RETURN_TYPE }; | ||
| 94 | ( my MLPerl::Classifier::KNeighbors $self, my number_arrayref_arrayref $test_data, my integer $timing_repetitions ) = @ARG; | ||
| 95 | |||
| 96 | my string_arrayref $tests_classifications; | ||
| 97 | |||
| 98 | for (my integer $repetition = 0; $repetition < $timing_repetitions; $repetition++) { | ||
| 99 | $tests_classifications = $self->predict_metric_euclidean_weights_uniform($test_data); | ||
| 100 | } | ||
| 101 | |||
| 102 | # print {*STDERR} 'in MLPerl::Classifier::KNeighbors::predict_repeat_metric_euclidean_weights_uniform(), about to return $tests_classifications =', "\n", string_arrayref_to_string($tests_classifications), "\n"; | ||
| 103 | |||
| 104 | return $tests_classifications; | ||
| 105 | } | ||
| 106 | |||
| 107 | |||
| 108 | # predict the class labels for the provided data | ||
| 109 | sub predict { | ||
| 110 | { my string_arrayref::method $RETURN_TYPE }; | ||
| 111 | ( my MLPerl::Classifier::KNeighbors $self, my number_arrayref_arrayref $test_data ) = @ARG; | ||
| 112 | |||
| 113 | my integer $test_data_count = scalar @{$test_data}; | ||
| 114 | |||
| 115 | # AVOID SEGMENTATION FAULT: create new string_arrayref of size $test_data_count, to receive predict_single() return values | ||
| 116 | # my string_arrayref $tests_classifications = []; | ||
| 117 | my string_arrayref $tests_classifications->[$test_data_count - 1] = undef; | ||
| 118 | |||
| 119 | # call KNN for each testing point | ||
| 120 | # PARALLEL__CALL_PREDICT_SINGLE: | ||
| 121 | for (my integer $i = 0; $i < $test_data_count; $i++) { | ||
| 122 | # print {*STDERR} 'in MLPerl::Classifier::KNeighbors::predict(), have $i = ', $i, ', about to call predict_single()...', "\n"; | ||
| 123 | |||
| 124 | $tests_classifications->[$i] = $self->predict_single($test_data->[$i]); | ||
| 125 | |||
| 126 | # print {*STDERR} 'in MLPerl::Classifier::KNeighbors::predict(), have $i = ', $i, ', returned from predict_single()...', "\n"; | ||
| 127 | } | ||
| 128 | |||
| 129 | # print {*STDERR} 'in MLPerl::Classifier::KNeighbors::predict(), about to return $tests_classifications =', "\n", string_arrayref_to_string($tests_classifications), "\n"; | ||
| 130 | |||
| 131 | return $tests_classifications; | ||
| 132 | } | ||
| 133 | |||
| 134 | |||
| 135 | # predict the class labels for the provided data, optimized for Euclidean distance and uniform weights | ||
| 136 | sub predict_metric_euclidean_weights_uniform { | ||
| 137 | { my string_arrayref::method $RETURN_TYPE }; | ||
| 138 | ( my MLPerl::Classifier::KNeighbors $self, my number_arrayref_arrayref $test_data ) = @ARG; | ||
| 139 | |||
| 140 | my integer $test_data_count = scalar @{$test_data}; | ||
| 141 | |||
| 142 | # AVOID SEGMENTATION FAULT: create new string_arrayref of size $test_data_count, to receive predict_single() return values | ||
| 143 | # my string_arrayref $tests_classifications = []; | ||
| 144 | my string_arrayref $tests_classifications->[$test_data_count - 1] = undef; | ||
| 145 | |||
| 146 | # call KNN for each testing point | ||
| 147 | # PARALLEL__CALL_PREDICT_SINGLE: | ||
| 148 | for (my integer $i = 0; $i < $test_data_count; $i++) { | ||
| 149 | $tests_classifications->[$i] = $self->predict_single_metric_euclidean_weights_uniform($test_data->[$i]); | ||
| 150 | } | ||
| 151 | |||
| 152 | return $tests_classifications; | ||
| 153 | } | ||
| 154 | |||
| 155 | |||
| 156 | # find the K Nearest Neighbors and classification of a test point in 2D | ||
| 157 | sub predict_single { | ||
| 158 | { my string::method $RETURN_TYPE }; | ||
| 159 | ( my MLPerl::Classifier::KNeighbors $self, my number_arrayref $test_data_single ) = @ARG; | ||
| 160 | |||
| 161 | my integer $train_data_count = scalar @{$self->{train_data}}; | ||
| 162 | my integer $n_neighbors_index_max = $self->{n_neighbors} - 1; | ||
| 163 | |||
| 164 | # initialize size of $neighbors to n_neighbors | ||
| 165 | my MLPerl::Classifier::KNeighbors::Neighbor2D_arrayref $neighbors->[$self->{n_neighbors} - 1] = undef; | ||
| 166 | |||
| 167 | # [ OPTIMIZED FOR MEMORY & SPEED ] | ||
| 168 | # store only n_neighbors distances, faster, uses less memory | ||
| 169 | for (my integer $i = 0; $i <= $n_neighbors_index_max; $i++) { | ||
| 170 | $neighbors->[$i] = MLPerl::Classifier::KNeighbors::Neighbor2D->new(); | ||
| 171 | $neighbors->[$i]->{distance} = -1; | ||
| 172 | } | ||
| 173 | |||
| 174 | # print {*STDERR} 'in MLPerl::Classifier::KNeighbors::predict_single(), done initializing $neighbors', "\n"; | ||
| 175 | |||
| 176 | # NEED FIX: RPerl incorrectly believes for-loop-scoped variable instantiations overlap | ||
| 177 | # ERROR ECOGEASRP012, CODE GENERATOR, ABSTRACT SYNTAX TO RPERL: variable '$train_data_single' already declared in this scope, namespace 'MLPerl::Classifier::KNeighbors::', subroutine/method 'predict_single()', dying | ||
| 178 | my number_arrayref $train_data_single; | ||
| 179 | my number $distance; | ||
| 180 | my number $neighbor_largest_distance_value; | ||
| 181 | my integer $neighbor_largest_distance_index; | ||
| 182 | |||
| 183 | # print {*STDERR} 'in MLPerl::Classifier::KNeighbors::predict_single(), have $self->{metric} = ', $self->{metric}, "\n"; | ||
| 184 | |||
| 185 | # calculate the Manhattan or Euclidean or Minkowski distance between $test_data_single and each $train_data_single; | ||
| 186 | if ($self->{metric} eq 'manhattan') { | ||
| 187 | # SERIAL__CALCULATE_DISTANCES_MANHATTAN: | ||
| 188 | for (my integer $i = 0; $i < $train_data_count; $i++) { | ||
| 189 | $train_data_single = $self->{train_data}->[$i]; | ||
| 190 | |||
| 191 | # [ PARALLEL, UN-OPTIMIZED FOR MEMORY & SPEED ] | ||
| 192 | # store all distances, slower, uses more memory; | ||
| 193 | # attach calculated distance to each $train_data_single by creating new Neighbor object; | ||
| 194 | # does not modify more than one element of $neighbors at a time, so thread safe here in for() loop; | ||
| 195 | # does not modify $self->{train_data} directly, so thread safe in parent subroutine predict() | ||
| 196 | # $neighbors->[$i] = MLPerl::Classifier::KNeighbors::Neighbor2D->new(); | ||
| 197 | # $neighbors->[$i]->{data} = $train_data_single; | ||
| 198 | # $neighbors->[$i]->{classification} = $self->{train_classifications}->[$i]; | ||
| 199 | # $neighbors->[$i]->{distance} = (abs ($train_data_single->[0] - $test_data_single->[0])) + | ||
| 200 | # (abs ($train_data_single->[1] - $test_data_single->[1])); | ||
| 201 | |||
| 202 | # [ SERIAL, OPTIMIZED FOR MEMORY & SPEED ] | ||
| 203 | # store only n_neighbors distances, faster, uses less memory; | ||
| 204 | # attach calculated distance to a $train_data_single only if among lowest n_neighbors distances; | ||
| 205 | # does modify more than one element of $neighbors at a time, so NOT thread safe here in for() loop; | ||
| 206 | # does not modify $self->{train_data} directly, so thread safe in parent subroutine predict() | ||
| 207 | $distance = (abs ($train_data_single->[0] - $test_data_single->[0])) + | ||
| 208 | (abs ($train_data_single->[1] - $test_data_single->[1])); | ||
| 209 | |||
| 210 | # DEV NOTE, CORRELATION #MLCKNN01: begin duplicate code | ||
| 211 | # store first n_neighbors distances directly, do not test values | ||
| 212 | if ( $i <= $n_neighbors_index_max ) { | ||
| 213 | $neighbors->[$i]->{data} = $train_data_single; | ||
| 214 | $neighbors->[$i]->{classification} = $self->{train_classifications}->[$i]; | ||
| 215 | $neighbors->[$i]->{distance} = $distance; | ||
| 216 | } | ||
| 217 | else { # before storing additional distances, test values | ||
| 218 | # [ OPTIMIZED FOR SPEED ] | ||
| 219 | # search for largest distance, O(n_neighbors) | ||
| 220 | $neighbor_largest_distance_value = $neighbors->[0]->{distance}; | ||
| 221 | $neighbor_largest_distance_index = 0; | ||
| 222 | for (my integer $j = 1; $j <= $n_neighbors_index_max; $j++) { | ||
| 223 | # NEED ANSWER: selects arbitrary neighbor when distances are equal, properly handle equal distances? | ||
| 224 | if ($neighbors->[$j]->{distance} > $neighbor_largest_distance_value) { | ||
| 225 | $neighbor_largest_distance_value = $neighbors->[$j]->{distance}; | ||
| 226 | $neighbor_largest_distance_index = $j; | ||
| 227 | } | ||
| 228 | } | ||
| 229 | # only test largest stored distance, overwrite if beaten | ||
| 230 | if ( $neighbors->[$neighbor_largest_distance_index]->{distance} > $distance ) { | ||
| 231 | $neighbors->[$neighbor_largest_distance_index]->{data} = $train_data_single; | ||
| 232 | $neighbors->[$neighbor_largest_distance_index]->{classification} = $self->{train_classifications}->[$i]; | ||
| 233 | $neighbors->[$neighbor_largest_distance_index]->{distance} = $distance; | ||
| 234 | } | ||
| 235 | # DEV NOTE, CORRELATION #MLCKNN01: end duplicate code | ||
| 236 | |||
| 237 | # [ UN-OPTIMIZED FOR SPEED ] | ||
| 238 | # # NEED ANSWER: selects arbitrary neighbor when distances are equal, properly handle equal distances? | ||
| 239 | # # sort distances, O(n_neighbors**2) | ||
| 240 | # $neighbors = [ sort {$a->{distance} <=> $b->{distance}} @{$neighbors} ]; | ||
| 241 | # # only test largest stored distance, overwrite if beaten | ||
| 242 | # if ( $neighbors->[$n_neighbors_index_max]->{distance} > $distance ) { | ||
| 243 | # $neighbors->[$n_neighbors_index_max]->{data} = $train_data_single; | ||
| 244 | # $neighbors->[$n_neighbors_index_max]->{classification} = $self->{train_classifications}->[$i]; | ||
| 245 | # $neighbors->[$n_neighbors_index_max]->{distance} = $distance; | ||
| 246 | # } | ||
| 247 | } | ||
| 248 | } | ||
| 249 | } | ||
| 250 | elsif ($self->{metric} eq 'euclidean') { | ||
| 251 | # SERIAL__CALCULATE_DISTANCES_EUCLIDEAN: | ||
| 252 | for (my integer $i = 0; $i < $train_data_count; $i++) { | ||
| 253 | $train_data_single = $self->{train_data}->[$i]; | ||
| 254 | |||
| 255 | # store only n_neighbors distances | ||
| 256 | $distance = sqrt(($train_data_single->[0] - $test_data_single->[0])**2 + | ||
| 257 | ($train_data_single->[1] - $test_data_single->[1])**2); | ||
| 258 | |||
| 259 | # print {*STDERR} 'in MLPerl::Classifier::KNeighbors::predict_single(), have $i = ', $i, ', $distance = ', $distance, "\n"; | ||
| 260 | |||
| 261 | # DEV NOTE, CORRELATION #MLCKNN01: begin duplicate code | ||
| 262 | # store first n_neighbors distances directly, do not test values | ||
| 263 | if ( $i <= $n_neighbors_index_max ) { | ||
| 264 | $neighbors->[$i]->{data} = $train_data_single; | ||
| 265 | $neighbors->[$i]->{classification} = $self->{train_classifications}->[$i]; | ||
| 266 | $neighbors->[$i]->{distance} = $distance; | ||
| 267 | } | ||
| 268 | else { # before storing additional distances, test values | ||
| 269 | # search for largest distance, O(n_neighbors) | ||
| 270 | $neighbor_largest_distance_value = $neighbors->[0]->{distance}; | ||
| 271 | $neighbor_largest_distance_index = 0; | ||
| 272 | for (my integer $j = 1; $j <= $n_neighbors_index_max; $j++) { | ||
| 273 | # NEED ANSWER: selects arbitrary neighbor when distances are equal, properly handle equal distances? | ||
| 274 | if ($neighbors->[$j]->{distance} > $neighbor_largest_distance_value) { | ||
| 275 | $neighbor_largest_distance_value = $neighbors->[$j]->{distance}; | ||
| 276 | $neighbor_largest_distance_index = $j; | ||
| 277 | } | ||
| 278 | } | ||
| 279 | # only test largest stored distance, overwrite if beaten | ||
| 280 | if ( $neighbors->[$neighbor_largest_distance_index]->{distance} > $distance ) { | ||
| 281 | $neighbors->[$neighbor_largest_distance_index]->{data} = $train_data_single; | ||
| 282 | $neighbors->[$neighbor_largest_distance_index]->{classification} = $self->{train_classifications}->[$i]; | ||
| 283 | $neighbors->[$neighbor_largest_distance_index]->{distance} = $distance; | ||
| 284 | } | ||
| 285 | } | ||
| 286 | # DEV NOTE, CORRELATION #MLCKNN01: end duplicate code | ||
| 287 | } | ||
| 288 | } | ||
| 289 | elsif ($self->{metric} eq 'minkowski') { | ||
| 290 | if ($self->{p} <= 0) { | ||
| 291 | die 'ERROR EMLKNN2D01: Minkowski distance power must be greater than 0, dying'; | ||
| 292 | } | ||
| 293 | |||
| 294 | # SERIAL__CALCULATE_DISTANCES_MINKOWSKI: | ||
| 295 | for (my integer $i = 0; $i < $train_data_count; $i++) { | ||
| 296 | $train_data_single = $self->{train_data}->[$i]; | ||
| 297 | |||
| 298 | # store only n_neighbors distances | ||
| 299 | $distance = (((abs ($train_data_single->[0] - $test_data_single->[0])) ** $self->{p}) + | ||
| 300 | ((abs ($train_data_single->[1] - $test_data_single->[1])) ** $self->{p})) | ||
| 301 | ** (1 / $self->{p}); | ||
| 302 | |||
| 303 | # DEV NOTE, CORRELATION #MLCKNN01: begin duplicate code | ||
| 304 | # store first n_neighbors distances directly, do not test values | ||
| 305 | if ( $i <= $n_neighbors_index_max ) { | ||
| 306 | $neighbors->[$i]->{data} = $train_data_single; | ||
| 307 | $neighbors->[$i]->{classification} = $self->{train_classifications}->[$i]; | ||
| 308 | $neighbors->[$i]->{distance} = $distance; | ||
| 309 | } | ||
| 310 | else { # before storing additional distances, test values | ||
| 311 | # search for largest distance, O(n_neighbors) | ||
| 312 | $neighbor_largest_distance_value = $neighbors->[0]->{distance}; | ||
| 313 | $neighbor_largest_distance_index = 0; | ||
| 314 | for (my integer $j = 1; $j <= $n_neighbors_index_max; $j++) { | ||
| 315 | # NEED ANSWER: selects arbitrary neighbor when distances are equal, properly handle equal distances? | ||
| 316 | if ($neighbors->[$j]->{distance} > $neighbor_largest_distance_value) { | ||
| 317 | $neighbor_largest_distance_value = $neighbors->[$j]->{distance}; | ||
| 318 | $neighbor_largest_distance_index = $j; | ||
| 319 | } | ||
| 320 | } | ||
| 321 | # only test largest stored distance, overwrite if beaten | ||
| 322 | if ( $neighbors->[$neighbor_largest_distance_index]->{distance} > $distance ) { | ||
| 323 | $neighbors->[$neighbor_largest_distance_index]->{data} = $train_data_single; | ||
| 324 | $neighbors->[$neighbor_largest_distance_index]->{classification} = $self->{train_classifications}->[$i]; | ||
| 325 | $neighbors->[$neighbor_largest_distance_index]->{distance} = $distance; | ||
| 326 | } | ||
| 327 | } | ||
| 328 | # DEV NOTE, CORRELATION #MLCKNN01: end duplicate code | ||
| 329 | } | ||
| 330 | } | ||
| 331 | else { | ||
| 332 | die q{ERROR EMLKNN2D00: Unknown distance metric '} . $self->{metric} . | ||
| 333 | q{', must be 'manhattan' or 'euclidean' or 'minkowski', dying}; | ||
| 334 | } | ||
| 335 | |||
| 336 | # print {*STDERR} 'in MLPerl::Classifier::KNeighbors::predict_single(), after calculating distances, have $neighbors = ', Dumper($neighbors), "\n"; | ||
| 337 | |||
| 338 | # count occurrences of each classification, O(n_neighbors); | ||
| 339 | # does not modify $self->{train_data} directly, so thread safe in parent subroutine predict() | ||
| 340 | my integer_hashref $k_nearest_classification_counts = {}; | ||
| 341 | |||
| 342 | # SERIAL__COUNT_GROUPS: | ||
| 343 | for (my integer $i = 0; $i < $self->{n_neighbors}; $i++) { | ||
| 344 | my string $classification = $neighbors->[$i]->{classification}; | ||
| 345 | if (not exists $k_nearest_classification_counts->{$classification}) { | ||
| 346 | $k_nearest_classification_counts->{$classification} = 0; | ||
| 347 | } | ||
| 348 | if ($self->{weights} eq 'uniform') { | ||
| 349 | $k_nearest_classification_counts->{$classification} += 1; | ||
| 350 | } | ||
| 351 | elsif ($self->{weights} eq 'distance') { | ||
| 352 | |||
| 353 | |||
| 354 | # NEED TEST: ensure we are actually getting the correct inverse-distance | ||
| 355 | # NEED TEST: ensure we are actually getting the correct inverse-distance | ||
| 356 | # NEED TEST: ensure we are actually getting the correct inverse-distance | ||
| 357 | |||
| 358 | |||
| 359 | $k_nearest_classification_counts->{$classification} += (1 / $neighbors->[$i]->{distance}); | ||
| 360 | } | ||
| 361 | else { | ||
| 362 | die q{ERROR EMLKNN2D02: Unknown weight function '} . $self->{weights} . | ||
| 363 | q{', must be 'uniform' or 'distance' or callable subroutine, dying}; | ||
| 364 | } | ||
| 365 | } | ||
| 366 | |||
| 367 | # print {*STDERR} 'in MLPerl::Classifier::KNeighbors::predict_single(), after selecting K nearest neighbors and counting classification occurrences, have $k_nearest_classification_counts = ', Dumper($k_nearest_classification_counts), "\n"; | ||
| 368 | |||
| 369 | # [ UN-OPTIMIZED FOR SPEED ] | ||
| 370 | # # sort classifications by count, O(unique classifications ** 2) | ||
| 371 | # # NEED ANSWER: selects arbitrary classification when counts are equal, properly handle equal classification counts? | ||
| 372 | # my string_hashref $k_nearest_classifications_sorted = | ||
| 373 | # [ sort { $k_nearest_classification_counts->{$a} <=> $k_nearest_classification_counts->{$b} } | ||
| 374 | # keys %{$k_nearest_classification_counts} ]; | ||
| 375 | # print {*STDERR} 'in MLPerl::Classifier::KNeighbors::predict_single(), have $k_nearest_classifications_sorted = ', Dumper($k_nearest_classifications_sorted), "\n"; | ||
| 376 | # # select highest classification by count | ||
| 377 | # my string $k_nearest_classification = $k_nearest_classifications_sorted->[-1]; | ||
| 378 | # my integer $k_nearest_classification_count = $k_nearest_classification_counts->{$k_nearest_classification}; | ||
| 379 | |||
| 380 | # [ OPTIMIZED FOR SPEED ] | ||
| 381 | # search for largest classification count, O(unique classifications) | ||
| 382 | my string_arrayref $k_nearest_classification_counts_keys = [keys %{$k_nearest_classification_counts}]; | ||
| 383 | my number $classifications_largest_count_value = $k_nearest_classification_counts->{$k_nearest_classification_counts_keys->[0]}; | ||
| 384 | my string $classifications_largest_count_key = $k_nearest_classification_counts_keys->[0]; | ||
| 385 | my integer $k_nearest_classification_counts_keys_count = scalar @{$k_nearest_classification_counts_keys}; | ||
| 386 | # NEED ANSWER: selects arbitrary classification when counts are equal, properly handle equal classification counts? | ||
| 387 | # SERIAL__FIND_LARGEST_GROUP: | ||
| 388 | for (my integer $j = 1; $j < $k_nearest_classification_counts_keys_count; $j++) { | ||
| 389 | if ($k_nearest_classification_counts->{$k_nearest_classification_counts_keys->[$j]} > $classifications_largest_count_value) { | ||
| 390 | $classifications_largest_count_value = $k_nearest_classification_counts->{$k_nearest_classification_counts_keys->[$j]}; | ||
| 391 | $classifications_largest_count_key = $k_nearest_classification_counts_keys->[$j]; | ||
| 392 | } | ||
| 393 | } | ||
| 394 | |||
| 395 | # print {*STDERR} 'in MLPerl::Classifier::KNeighbors::predict_single(), have final $classifications_largest_count_value = ', $classifications_largest_count_value, "\n"; | ||
| 396 | # print {*STDERR} 'in MLPerl::Classifier::KNeighbors::predict_single(), about to return $classifications_largest_count_key = ', $classifications_largest_count_key, "\n"; | ||
| 397 | |||
| 398 | return $classifications_largest_count_key; | ||
| 399 | } | ||
| 400 | |||
| 401 | |||
| 402 | # find the K Nearest Neighbors and classification of a test point in 2D, optimized for Euclidean distance and uniform weights | ||
| 403 | sub predict_single_metric_euclidean_weights_uniform { | ||
| 404 | { my string::method $RETURN_TYPE }; | ||
| 405 | ( my MLPerl::Classifier::KNeighbors $self, my number_arrayref $test_data_single ) = @ARG; | ||
| 406 | |||
| 407 | my integer $train_data_count = scalar @{$self->{train_data}}; | ||
| 408 | my integer $n_neighbors_index_max = $self->{n_neighbors} - 1; | ||
| 409 | |||
| 410 | # initialize size of $neighbors to n_neighbors | ||
| 411 | my MLPerl::Classifier::KNeighbors::Neighbor2D_arrayref $neighbors->[$self->{n_neighbors} - 1] = undef; | ||
| 412 | |||
| 413 | # [ OPTIMIZED FOR MEMORY & SPEED ] | ||
| 414 | # store only n_neighbors distances, faster, uses less memory | ||
| 415 | for (my integer $i = 0; $i <= $n_neighbors_index_max; $i++) { | ||
| 416 | $neighbors->[$i] = MLPerl::Classifier::KNeighbors::Neighbor2D->new(); | ||
| 417 | $neighbors->[$i]->{distance} = -1; | ||
| 418 | } | ||
| 419 | |||
| 420 | # NEED FIX: RPerl incorrectly believes for-loop-scoped variable instantiations overlap; | ||
| 421 | # does not actually affect this subroutine because only euclidean distance is implemented, make change here to match predict_single() | ||
| 422 | # ERROR ECOGEASRP012, CODE GENERATOR, ABSTRACT SYNTAX TO RPERL: variable '$train_data_single' already declared in this scope, namespace 'MLPerl::Classifier::KNeighbors::', subroutine/method 'predict_single()', dying | ||
| 423 | my number_arrayref $train_data_single; | ||
| 424 | my number $distance; | ||
| 425 | my number $neighbor_largest_distance_value; | ||
| 426 | my integer $neighbor_largest_distance_index; | ||
| 427 | |||
| 428 | # calculate the Euclidean distance between $test_data_single and each $train_data_single; | ||
| 429 | # attach calculated distance to each $train_data_single by creating new Neighbor object; | ||
| 430 | # does not modify $self->{train_data} directly, so thread safe in parent subroutine predict() | ||
| 431 | # SERIAL__CALCULATE_DISTANCES_EUCLIDEAN: | ||
| 432 | for (my integer $i = 0; $i < $train_data_count; $i++) { | ||
| 433 | $train_data_single = $self->{train_data}->[$i]; | ||
| 434 | |||
| 435 | # store only n_neighbors distances | ||
| 436 | $distance = sqrt(($train_data_single->[0] - $test_data_single->[0])**2 + | ||
| 437 | ($train_data_single->[1] - $test_data_single->[1])**2); | ||
| 438 | |||
| 439 | # DEV NOTE, CORRELATION #MLCKNN01: begin duplicate code | ||
| 440 | # store first n_neighbors distances directly, do not test values | ||
| 441 | if ( $i <= $n_neighbors_index_max ) { | ||
| 442 | $neighbors->[$i]->{data} = $train_data_single; | ||
| 443 | $neighbors->[$i]->{classification} = $self->{train_classifications}->[$i]; | ||
| 444 | $neighbors->[$i]->{distance} = $distance; | ||
| 445 | } | ||
| 446 | else { # before storing additional distances, test values | ||
| 447 | $neighbor_largest_distance_value = $neighbors->[0]->{distance}; | ||
| 448 | $neighbor_largest_distance_index = 0; | ||
| 449 | # search for largest distance, O(n_neighbors) | ||
| 450 | for (my integer $j = 1; $j <= $n_neighbors_index_max; $j++) { | ||
| 451 | # NEED ANSWER: selects arbitrary neighbor when distances are equal, properly handle equal distances? | ||
| 452 | if ($neighbors->[$j]->{distance} > $neighbor_largest_distance_value) { | ||
| 453 | $neighbor_largest_distance_value = $neighbors->[$j]->{distance}; | ||
| 454 | $neighbor_largest_distance_index = $j; | ||
| 455 | } | ||
| 456 | } | ||
| 457 | # only test largest stored distance, overwrite if beaten | ||
| 458 | if ( $neighbors->[$neighbor_largest_distance_index]->{distance} > $distance ) { | ||
| 459 | $neighbors->[$neighbor_largest_distance_index]->{data} = $train_data_single; | ||
| 460 | $neighbors->[$neighbor_largest_distance_index]->{classification} = $self->{train_classifications}->[$i]; | ||
| 461 | $neighbors->[$neighbor_largest_distance_index]->{distance} = $distance; | ||
| 462 | } | ||
| 463 | } | ||
| 464 | # DEV NOTE, CORRELATION #MLCKNN01: end duplicate code | ||
| 465 | } | ||
| 466 | |||
| 467 | # print {*STDERR} 'in MLPerl::Classifier::KNeighbors::predict_single_metric_euclidean_weights_uniform(), after calculating distances, have $neighbors = ', Dumper($neighbors), "\n"; | ||
| 468 | |||
| 469 | # count occurrences of each classification, O(n_neighbors); | ||
| 470 | # does not modify $self->{train_data} directly, so thread safe in parent subroutine predict() | ||
| 471 | my integer_hashref $k_nearest_classification_counts = {}; | ||
| 472 | |||
| 473 | # SERIAL__COUNT_GROUPS__WEIGHTS_UNIFORM: | ||
| 474 | for (my integer $i = 0; $i < $self->{n_neighbors}; $i++) { | ||
| 475 | my string $classification = $neighbors->[$i]->{classification}; | ||
| 476 | if (not exists $k_nearest_classification_counts->{$classification}) { | ||
| 477 | $k_nearest_classification_counts->{$classification} = 0; | ||
| 478 | } | ||
| 479 | $k_nearest_classification_counts->{$classification} += 1; | ||
| 480 | } | ||
| 481 | |||
| 482 | # print {*STDERR} 'in MLPerl::Classifier::KNeighbors::predict_single_metric_euclidean_weights_uniform(), after selecting K nearest neighbors and counting classification occurrences, have $k_nearest_classification_counts = ', Dumper($k_nearest_classification_counts), "\n"; | ||
| 483 | |||
| 484 | # search for largest classification count, O(unique classifications) | ||
| 485 | my string_arrayref $k_nearest_classification_counts_keys = [keys %{$k_nearest_classification_counts}]; | ||
| 486 | my number $classifications_largest_count_value = $k_nearest_classification_counts->{$k_nearest_classification_counts_keys->[0]}; | ||
| 487 | my string $classifications_largest_count_key = $k_nearest_classification_counts_keys->[0]; | ||
| 488 | my integer $k_nearest_classification_counts_keys_count = scalar @{$k_nearest_classification_counts_keys}; | ||
| 489 | # NEED ANSWER: selects arbitrary classification when counts are equal, properly handle equal classification counts? | ||
| 490 | # SERIAL__FIND_LARGEST_GROUP: | ||
| 491 | for (my integer $j = 1; $j < $k_nearest_classification_counts_keys_count; $j++) { | ||
| 492 | if ($k_nearest_classification_counts->{$k_nearest_classification_counts_keys->[$j]} > $classifications_largest_count_value) { | ||
| 493 | $classifications_largest_count_value = $k_nearest_classification_counts->{$k_nearest_classification_counts_keys->[$j]}; | ||
| 494 | $classifications_largest_count_key = $k_nearest_classification_counts_keys->[$j]; | ||
| 495 | } | ||
| 496 | } | ||
| 497 | |||
| 498 | # print {*STDERR} 'in MLPerl::Classifier::KNeighbors::predict_single_metric_euclidean_weights_uniform(), have final $classifications_largest_count_value = ', $classifications_largest_count_value, "\n"; | ||
| 499 | # print {*STDERR} 'in MLPerl::Classifier::KNeighbors::predict_single_metric_euclidean_weights_uniform(), about to return $classifications_largest_count_key = ', $classifications_largest_count_key, "\n"; | ||
| 500 | |||
| 501 | return $classifications_largest_count_key; | ||
| 502 | } | ||
| 503 | |||
| 504 | 1; # end of class |