| 1 | # Licensed to the Apache Software Foundation (ASF) under one | ||
| 2 | # or more contributor license agreements. See the NOTICE file | ||
| 3 | # distributed with this work for additional information | ||
| 4 | # regarding copyright ownership. The ASF licenses this file | ||
| 5 | # to you under the Apache License, Version 2.0 (the | ||
| 6 | # "License"); you may not use this file except in compliance | ||
| 7 | # with the License. You may obtain a copy of the License at | ||
| 8 | # | ||
| 9 | # http://www.apache.org/licenses/LICENSE-2.0 | ||
| 10 | # | ||
| 11 | # Unless required by applicable law or agreed to in writing, | ||
| 12 | # software distributed under the License is distributed on an | ||
| 13 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
| 14 | # KIND, either express or implied. See the License for the | ||
| 15 | # specific language governing permissions and limitations | ||
| 16 | # under the License. | ||
| 17 | |||
| 18 | package AI::MXNet::Metric; | ||
| 19 | use strict; | ||
| 20 | use warnings; | ||
| 21 | use AI::MXNet::NS; | ||
| 22 | use AI::MXNet::Function::Parameters; | ||
| 23 | use Scalar::Util qw/blessed/; | ||
| 24 | use JSON::PP; | ||
| 25 | |||
| 26 | =encoding utf-8 | ||
| 27 | |||
| 28 | =head1 NAME | ||
| 29 | |||
| 30 | AI::MXNet::Metric - Evaluation Metric API. | ||
| 31 | =head1 DESCRIPTION | ||
| 32 | |||
| 33 | This module hosts all the evaluation metrics available to evaluate the performance of a learned model. | ||
| 34 | L<Python Docs|https://mxnet.apache.org/api/python/metric/metric.html> | ||
| 35 | =cut | ||
| 36 | |||
| 37 | # Check to see if the two arrays are the same size. | ||
| 38 | sub _calculate_shape | ||
| 39 | { | ||
| 40 | my $input = shift; | ||
| 41 | my ($shape); | ||
| 42 | if(blessed($input)) | ||
| 43 | { | ||
| 44 | if($input->isa('PDL')) | ||
| 45 | { | ||
| 46 | $shape = $input->shape->at(-1); | ||
| 47 | } | ||
| 48 | else | ||
| 49 | { | ||
| 50 | $shape = $input->shape->[0]; | ||
| 51 | } | ||
| 52 | } | ||
| 53 | else | ||
| 54 | { | ||
| 55 | $shape = @{ $input }; | ||
| 56 | } | ||
| 57 | return $shape; | ||
| 58 | } | ||
| 59 | func check_label_shapes( | ||
| 60 | ArrayRef|AI::MXNet::NDArray|PDL $labels, | ||
| 61 | ArrayRef|AI::MXNet::NDArray|PDL $preds | ||
| 62 | ) | ||
| 63 | { | ||
| 64 | my ($label_shape, $pred_shape) = (_calculate_shape($labels), _calculate_shape($preds)); | ||
| 65 | Carp::confess( | ||
| 66 | "Shape of labels $label_shape does not " | ||
| 67 | ."match shape of predictions $pred_shape" | ||
| 68 | ) unless $pred_shape == $label_shape; | ||
| 69 | } | ||
| 70 | |||
| 71 | package AI::MXNet::EvalMetric; | ||
| 72 | use Mouse; | ||
| 73 | use overload '""' => sub { | ||
| 74 | return "EvalMetric: " | ||
| 75 | .Data::Dumper->new( | ||
| 76 | [shift->get_name_value()] | ||
| 77 | )->Purity(1)->Deepcopy(1)->Terse(1)->Dump | ||
| 78 | }, fallback => 1; | ||
| 79 | has 'name' => (is => 'rw', isa => 'Str'); | ||
| 80 | has 'num' => (is => 'rw', isa => 'Int'); | ||
| 81 | has 'num_inst' => (is => 'rw', isa => 'Maybe[Int|ArrayRef[Int]]'); | ||
| 82 | has 'sum_metric' => (is => 'rw', isa => 'Maybe[Num|ArrayRef[Num]]'); | ||
| 83 | has '_kwargs' => (is => 'rw', init_arg => undef); | ||
| 84 | around BUILDARGS => \&AI::MXNet::Base::process_arguments; | ||
| 85 | |||
| 86 | sub BUILD | ||
| 87 | { | ||
| 88 | my ($self, $kwargs) = @_; | ||
| 89 | $self->reset; | ||
| 90 | $self->_kwargs($kwargs); | ||
| 91 | } | ||
| 92 | |||
| 93 | method _class_name() | ||
| 94 | { | ||
| 95 | my $class = ref $self || $self; | ||
| 96 | $class =~ s/^.+:://; | ||
| 97 | $class; | ||
| 98 | } | ||
| 99 | |||
| 100 | =head2 get_config | ||
| 101 | |||
| 102 | Save configurations of metric. Can be recreated | ||
| 103 | from configs with mx->metric->create(%{ $config }) | ||
| 104 | =cut | ||
| 105 | |||
| 106 | method get_config() | ||
| 107 | { | ||
| 108 | my %config = %{ $self->_kwargs }; | ||
| 109 | %config = (%config, | ||
| 110 | metric => $self->_class_name, | ||
| 111 | name => $self->name | ||
| 112 | ); | ||
| 113 | return \%config; | ||
| 114 | } | ||
| 115 | |||
| 116 | method update($label, $pred) | ||
| 117 | { | ||
| 118 | confess('NotImplemented'); | ||
| 119 | } | ||
| 120 | |||
| 121 | method reset() | ||
| 122 | { | ||
| 123 | if(not defined $self->num) | ||
| 124 | { | ||
| 125 | $self->num_inst(0); | ||
| 126 | $self->sum_metric(0); | ||
| 127 | } | ||
| 128 | else | ||
| 129 | { | ||
| 130 | $self->num_inst([(0) x $self->num]); | ||
| 131 | $self->sum_metric([(0) x $self->num]); | ||
| 132 | } | ||
| 133 | } | ||
| 134 | |||
| 135 | method get() | ||
| 136 | { | ||
| 137 | if(not defined $self->num) | ||
| 138 | { | ||
| 139 | if($self->num_inst == 0) | ||
| 140 | { | ||
| 141 | return ($self->name, 'nan'); | ||
| 142 | } | ||
| 143 | else | ||
| 144 | { | ||
| 145 | return ($self->name, $self->sum_metric / $self->num_inst); | ||
| 146 | } | ||
| 147 | } | ||
| 148 | else | ||
| 149 | { | ||
| 150 | my $names = [map { sprintf('%s_%d', $self->name, $_) } 0..$self->num-1]; | ||
| 151 | my $values = []; | ||
| 152 | for (my $i = 0; $i < @{ $self->sum_metric }; $i++) | ||
| 153 | { | ||
| 154 | my ($x, $y) = ($self->sum_metric->[$i], $self->num_inst->[$i]); | ||
| 155 | if($y != 0) | ||
| 156 | { | ||
| 157 | push (@$values, $x/$y); | ||
| 158 | } | ||
| 159 | else | ||
| 160 | { | ||
| 161 | push (@$values, 'nan'); | ||
| 162 | } | ||
| 163 | } | ||
| 164 | return ($names, $values); | ||
| 165 | } | ||
| 166 | } | ||
| 167 | |||
| 168 | method get_name_value() | ||
| 169 | { | ||
| 170 | my ($name, $value) = $self->get; | ||
| 171 | $name = [$name] unless ref $name; | ||
| 172 | $value = [$value] unless ref $value; | ||
| 173 | my %ret; | ||
| 174 | @ret{ @$name } = @$value; | ||
| 175 | return \%ret; | ||
| 176 | } | ||
| 177 | |||
| 178 | package AI::MXNet::CompositeEvalMetric; | ||
| 179 | use Mouse; | ||
| 180 | |||
| 181 | extends 'AI::MXNet::EvalMetric'; | ||
| 182 | has 'metrics' => (is => 'rw', isa => 'ArrayRef[AI::MXNet::EvalMetric]', default => sub { [] }); | ||
| 183 | has '+name' => (default => 'composite'); | ||
| 184 | method python_constructor_arguments() { ['metrics'] } | ||
| 185 | |||
| 186 | # Add a child metric. | ||
| 187 | method add(AI::MXNet::EvalMetric $metric) | ||
| 188 | { | ||
| 189 | push @{ $self->metrics }, $metric; | ||
| 190 | } | ||
| 191 | |||
| 192 | # Get a child metric. | ||
| 193 | method get_metric(int $index) | ||
| 194 | { | ||
| 195 | my $max = @{ $self->metrics } - 1; | ||
| 196 | confess("Metric index $index is out of range 0 and $max") | ||
| 197 | if $index > $max; | ||
| 198 | return $self->metrics->[$index]; | ||
| 199 | } | ||
| 200 | |||
| 201 | method update(ArrayRef[AI::MXNet::NDArray] $labels, ArrayRef[AI::MXNet::NDArray] $preds) | ||
| 202 | { | ||
| 203 | for my $metric (@{ $self->metrics }) | ||
| 204 | { | ||
| 205 | $metric->update($labels, $preds); | ||
| 206 | } | ||
| 207 | } | ||
| 208 | |||
| 209 | method reset() | ||
| 210 | { | ||
| 211 | for my $metric (@{ $self->metrics }) | ||
| 212 | { | ||
| 213 | $metric->reset; | ||
| 214 | } | ||
| 215 | } | ||
| 216 | |||
| 217 | method get() | ||
| 218 | { | ||
| 219 | my $names = []; | ||
| 220 | my $results = []; | ||
| 221 | for my $metric (@{ $self->metrics }) | ||
| 222 | { | ||
| 223 | my ($name, $result) = $metric->get; | ||
| 224 | $name = [$name] unless ref $name; | ||
| 225 | $result = [$result] unless ref $result; | ||
| 226 | push @$names, @$name; | ||
| 227 | push @$results, @$result; | ||
| 228 | } | ||
| 229 | return ($names, $results); | ||
| 230 | } | ||
| 231 | |||
| 232 | |||
| 233 | ######################## | ||
| 234 | # CLASSIFICATION METRICS | ||
| 235 | ######################## | ||
| 236 | |||
| 237 | =head1 NAME | ||
| 238 | |||
| 239 | AI::MXNet::Accuracy - Computes accuracy classification score. | ||
| 240 | =cut | ||
| 241 | |||
| 242 | =head1 DESCRIPTION | ||
| 243 | |||
| 244 | The accuracy score is defined as | ||
| 245 | |||
| 246 | accuracy(y, y^) = (1/n) * sum(i=0..n-1) { y^(i)==y(i) } | ||
| 247 | |||
| 248 | Parameters: | ||
| 249 | axis (Int, default=1) – The axis that represents classes. | ||
| 250 | name (Str, default='accuracy') – Name of this metric instance for display. | ||
| 251 | |||
| 252 | pdl> use AI::MXNet qw(mx) | ||
| 253 | pdl> $predicts = [mx->nd->array([[0.3, 0.7], [0, 1.], [0.4, 0.6]])] | ||
| 254 | pdl> $labels = [mx->nd->array([[0, 1, 1]])] | ||
| 255 | pdl> $acc = mx->metric->Accuracy() | ||
| 256 | pdl> $acc->update($labels, $predicts) | ||
| 257 | pdl> use Data::Dumper | ||
| 258 | pdl> print Dumper([$acc->get]) | ||
| 259 | $VAR1 = [ | ||
| 260 | 'accuracy', | ||
| 261 | '0.666666666666667' | ||
| 262 | ]; | ||
| 263 | |||
| 264 | =cut | ||
| 265 | |||
| 266 | package AI::MXNet::Accuracy; | ||
| 267 | use Mouse; | ||
| 268 | use AI::MXNet::Base; | ||
| 269 | extends 'AI::MXNet::EvalMetric'; | ||
| 270 | has '+name' => (default => 'accuracy'); | ||
| 271 | has 'axis' => (is => 'ro', isa => 'Int', default => 1); | ||
| 272 | |||
| 273 | method update(ArrayRef[AI::MXNet::NDArray] $labels, ArrayRef[AI::MXNet::NDArray] $preds) | ||
| 274 | { | ||
| 275 | AI::MXNet::Metric::check_label_shapes($labels, $preds); | ||
| 276 | for(zip($labels, $preds)) { | ||
| 277 | my ($label, $pred_label) = @$_; | ||
| 278 | if(join(',', @{$pred_label->shape}) ne join(',', @{$label->shape})) | ||
| 279 | { | ||
| 280 | $pred_label = AI::MXNet::NDArray->argmax_channel($pred_label, { axis => $self->axis }); | ||
| 281 | } | ||
| 282 | my $sum = ($pred_label->aspdl->flat == $label->aspdl->flat)->sum; | ||
| 283 | $self->sum_metric($self->sum_metric + $sum); | ||
| 284 | $self->num_inst($self->num_inst + $pred_label->size); | ||
| 285 | } | ||
| 286 | } | ||
| 287 | |||
| 288 | =head1 NAME | ||
| 289 | |||
| 290 | AI::MXNet::TopKAccuracy - Computes top k predictions accuracy. | ||
| 291 | =cut | ||
| 292 | |||
| 293 | =head1 DESCRIPTION | ||
| 294 | |||
| 295 | TopKAccuracy differs from Accuracy in that it considers the prediction | ||
| 296 | to be True as long as the ground truth label is in the top K predicated labels. | ||
| 297 | |||
| 298 | If top_k = 1, then TopKAccuracy is identical to Accuracy. | ||
| 299 | |||
| 300 | Parameters: | ||
| 301 | top_k(Int, default 1) – Whether targets are in top k predictions. | ||
| 302 | name (Str, default 'top_k_accuracy') – Name of this metric instance for display. | ||
| 303 | |||
| 304 | use AI::MXNet qw(mx); | ||
| 305 | $top_k = 3; | ||
| 306 | $predicts = [mx->nd->array( | ||
| 307 | [[0.80342804, 0.5275223 , 0.11911147, 0.63968144, 0.09092526, | ||
| 308 | 0.33222568, 0.42738095, 0.55438581, 0.62812652, 0.69739294], | ||
| 309 | [0.78994969, 0.13189035, 0.34277045, 0.20155961, 0.70732423, | ||
| 310 | 0.03339926, 0.90925004, 0.40516066, 0.76043547, 0.47375838], | ||
| 311 | [0.28671892, 0.75129249, 0.09708994, 0.41235779, 0.28163896, | ||
| 312 | 0.39027778, 0.87110921, 0.08124512, 0.55793117, 0.54753428], | ||
| 313 | [0.33220307, 0.97326881, 0.2862761 , 0.5082575 , 0.14795074, | ||
| 314 | 0.19643398, 0.84082001, 0.0037532 , 0.78262101, 0.83347772], | ||
| 315 | [0.93790734, 0.97260166, 0.83282304, 0.06581761, 0.40379256, | ||
| 316 | 0.37479349, 0.50750135, 0.97787696, 0.81899021, 0.18754124], | ||
| 317 | [0.69804812, 0.68261077, 0.99909815, 0.48263116, 0.73059268, | ||
| 318 | 0.79518236, 0.26139168, 0.16107376, 0.69850315, 0.89950917], | ||
| 319 | [0.91515562, 0.31244902, 0.95412616, 0.7242641 , 0.02091039, | ||
| 320 | 0.72554552, 0.58165923, 0.9545687 , 0.74233195, 0.19750339], | ||
| 321 | [0.94900651, 0.85836332, 0.44904621, 0.82365038, 0.99726878, | ||
| 322 | 0.56413064, 0.5890016 , 0.42402702, 0.89548786, 0.44437266], | ||
| 323 | [0.57723744, 0.66019353, 0.30244304, 0.02295771, 0.83766937, | ||
| 324 | 0.31953292, 0.37552193, 0.18172362, 0.83135182, 0.18487429], | ||
| 325 | [0.96968683, 0.69644561, 0.60566253, 0.49600661, 0.70888438, | ||
| 326 | 0.26044186, 0.65267488, 0.62297362, 0.83609334, 0.3572364 ]] | ||
| 327 | )]; | ||
| 328 | $labels = [mx->nd->array([2, 6, 9, 2, 3, 4, 7, 8, 9, 6])]; | ||
| 329 | $acc = mx->metric->TopKAccuracy(top_k=>$top_k); | ||
| 330 | $acc->update($labels, $predicts); | ||
| 331 | use Data::Dumper; | ||
| 332 | print Dumper([$acc->get]); | ||
| 333 | $VAR1 = [ | ||
| 334 | 'top_k_accuracy_3', | ||
| 335 | '0.3' | ||
| 336 | ]; | ||
| 337 | |||
| 338 | |||
| 339 | =cut | ||
| 340 | |||
| 341 | package AI::MXNet::TopKAccuracy; | ||
| 342 | use Mouse; | ||
| 343 | use List::Util qw/min/; | ||
| 344 | use AI::MXNet::Base; | ||
| 345 | extends 'AI::MXNet::EvalMetric'; | ||
| 346 | has '+name' => (default => 'top_k_accuracy'); | ||
| 347 | has 'top_k' => (is => 'rw', isa => 'Int', default => 1); | ||
| 348 | method python_constructor_arguments() { ['top_k'] } | ||
| 349 | |||
| 350 | sub BUILD | ||
| 351 | { | ||
| 352 | my $self = shift; | ||
| 353 | confess("Please use Accuracy if top_k is no more than 1") | ||
| 354 | unless $self->top_k > 1; | ||
| 355 | $self->name($self->name . "_" . $self->top_k); | ||
| 356 | } | ||
| 357 | |||
| 358 | method update(ArrayRef[AI::MXNet::NDArray] $labels, ArrayRef[AI::MXNet::NDArray] $preds) | ||
| 359 | { | ||
| 360 | AI::MXNet::Metric::check_label_shapes($labels, $preds); | ||
| 361 | for(zip($labels, $preds)) { | ||
| 362 | my ($label, $pred_label) = @$_; | ||
| 363 | confess('Predictions should be no more than 2 dims') | ||
| 364 | unless @{ $pred_label->shape } <= 2; | ||
| 365 | $pred_label = $pred_label->aspdl->qsorti; | ||
| 366 | $label = $label->astype('int32')->aspdl; | ||
| 367 | AI::MXNet::Metric::check_label_shapes($label, $pred_label); | ||
| 368 | my $num_samples = $pred_label->shape->at(-1); | ||
| 369 | my $num_dims = $pred_label->ndims; | ||
| 370 | if($num_dims == 1) | ||
| 371 | { | ||
| 372 | my $sum = ($pred_label->flat == $label->flat)->sum; | ||
| 373 | $self->sum_metric($self->sum_metric + $sum); | ||
| 374 | } | ||
| 375 | elsif($num_dims == 2) | ||
| 376 | { | ||
| 377 | my $num_classes = $pred_label->shape->at(0); | ||
| 378 | my $top_k = min($num_classes, $self->top_k); | ||
| 379 | for my $j (0..$top_k-1) | ||
| 380 | { | ||
| 381 | my $sum = ($pred_label->slice($num_classes -1 - $j, 'X')->flat == $label->flat)->sum; | ||
| 382 | $self->sum_metric($self->sum_metric + $sum); | ||
| 383 | } | ||
| 384 | } | ||
| 385 | $self->num_inst($self->num_inst + $num_samples); | ||
| 386 | } | ||
| 387 | } | ||
| 388 | |||
| 389 | package _BinaryClassificationMetrics { | ||
| 390 | use Mouse; | ||
| 391 | #Private container class for classification metric statistics. True/false positive and | ||
| 392 | # true/false negative counts are sufficient statistics for various classification metrics. | ||
| 393 | #This class provides the machinery to track those statistics across mini-batches of | ||
| 394 | #(label, prediction) pairs. | ||
| 395 | has [qw/true_positives | ||
| 396 | false_negatives | ||
| 397 | false_positives | ||
| 398 | true_negatives/] => (is => 'rw', isa => 'Int', default => 0); | ||
| 399 | |||
| 400 | method update_binary_stats(AI::MXNet::NDArray $label, AI::MXNet::NDArray $pred) | ||
| 401 | { | ||
| 402 | $pred = AI::MXNet::NDArray->argmax($pred, { axis => 1 })->aspdl; | ||
| 403 | $label = $label->astype('int32')->aspdl; | ||
| 404 | |||
| 405 | AI::MXNet::Metric::check_label_shapes($label, $pred); | ||
| 406 | if($label->uniq->len > 2) | ||
| 407 | { | ||
| 408 | confess("Currently only support binary classification."); | ||
| 409 | } | ||
| 410 | |||
| 411 | my $pred_true = ($pred == 1); | ||
| 412 | my $pred_false = 1 - $pred_true; | ||
| 413 | my $label_true = ($label == 1); | ||
| 414 | my $label_false = 1 - $label_true; | ||
| 415 | |||
| 416 | $self->true_positives($self->true_positives + ($pred_true * $label_true)->sum); | ||
| 417 | $self->false_positives($self->false_positives + ($pred_true * $label_false)->sum); | ||
| 418 | $self->false_negatives($self->false_negatives + ($pred_false * $label_true)->sum); | ||
| 419 | $self->true_negatives($self->true_negatives + ($pred_false * $label_false)->sum); | ||
| 420 | } | ||
| 421 | |||
| 422 | method precision() | ||
| 423 | { | ||
| 424 | if($self->true_positives + $self->false_positives > 0) | ||
| 425 | { | ||
| 426 | return $self->true_positives / ($self->true_positives + $self->false_positives); | ||
| 427 | } | ||
| 428 | else | ||
| 429 | { | ||
| 430 | return 0; | ||
| 431 | } | ||
| 432 | } | ||
| 433 | |||
| 434 | method recall() | ||
| 435 | { | ||
| 436 | if($self->true_positives + $self->false_negatives > 0) | ||
| 437 | { | ||
| 438 | return $self->true_positives / ($self->true_positives + $self->false_negatives); | ||
| 439 | } | ||
| 440 | else | ||
| 441 | { | ||
| 442 | return 0; | ||
| 443 | } | ||
| 444 | } | ||
| 445 | |||
| 446 | method fscore() | ||
| 447 | { | ||
| 448 | if($self->precision + $self->recall > 0) | ||
| 449 | { | ||
| 450 | return 2 * $self->precision * $self->recall / ($self->precision + $self->recall); | ||
| 451 | } | ||
| 452 | else | ||
| 453 | { | ||
| 454 | return 0; | ||
| 455 | } | ||
| 456 | } | ||
| 457 | |||
| 458 | method matthewscc() | ||
| 459 | { | ||
| 460 | if(not $self->total_examples) | ||
| 461 | { | ||
| 462 | return 0; | ||
| 463 | } | ||
| 464 | my @terms = ( | ||
| 465 | $self->true_positives + $self->false_positives, | ||
| 466 | $self->true_positives + $self->false_negatives, | ||
| 467 | $self->true_negatives + $self->false_positives, | ||
| 468 | $self->true_negatives + $self->false_negatives | ||
| 469 | ); | ||
| 470 | my $denom = 1; | ||
| 471 | for my $t (grep { $_ } @terms) | ||
| 472 | { | ||
| 473 | $denom *= $t; | ||
| 474 | } | ||
| 475 | return (($self->true_positives * $self->true_negatives) - ($self->false_positives * $self->false_negatives)) / sqrt($denom); | ||
| 476 | } | ||
| 477 | |||
| 478 | method total_examples() | ||
| 479 | { | ||
| 480 | return $self->false_negatives + $self->false_positives + | ||
| 481 | $self->true_negatives + $self->true_positives; | ||
| 482 | } | ||
| 483 | |||
| 484 | method reset_stats() | ||
| 485 | { | ||
| 486 | $self->false_positives(0); | ||
| 487 | $self->false_negatives(0); | ||
| 488 | $self->true_positives(0); | ||
| 489 | $self->true_negatives(0); | ||
| 490 | } | ||
| 491 | }; | ||
| 492 | |||
| 493 | =head1 NAME | ||
| 494 | |||
| 495 | AI::MXNet::F1 - Calculate the F1 score of a binary classification problem. | ||
| 496 | =cut | ||
| 497 | |||
| 498 | =head1 DESCRIPTION | ||
| 499 | |||
| 500 | The F1 score is equivalent to harmonic mean of the precision and recall, | ||
| 501 | where the best value is 1.0 and the worst value is 0.0. The formula for F1 score is: | ||
| 502 | |||
| 503 | F1 = 2 * (precision * recall) / (precision + recall) | ||
| 504 | The formula for precision and recall is: | ||
| 505 | |||
| 506 | precision = true_positives / (true_positives + false_positives) | ||
| 507 | recall = true_positives / (true_positives + false_negatives) | ||
| 508 | Note: | ||
| 509 | |||
| 510 | This F1 score only supports binary classification. | ||
| 511 | |||
| 512 | Parameters: | ||
| 513 | name (Str, default 'f1') – Name of this metric instance for display. | ||
| 514 | average (Str, default 'macro') – | ||
| 515 | Strategy to be used for aggregating across mini-batches. | ||
| 516 | “macro”: average the F1 scores for each batch. “micro”: compute a single F1 score across all batches. | ||
| 517 | |||
| 518 | |||
| 519 | $predicts = [mx.nd.array([[0.3, 0.7], [0., 1.], [0.4, 0.6]])]; | ||
| 520 | $labels = [mx.nd.array([0., 1., 1.])]; | ||
| 521 | $f1 = mx->metric->F1(); | ||
| 522 | $f1->update($labels, $predicts); | ||
| 523 | print $f1->get; | ||
| 524 | f1 0.8 | ||
| 525 | |||
| 526 | =cut | ||
| 527 | |||
| 528 | package AI::MXNet::F1; | ||
| 529 | use Mouse; | ||
| 530 | use AI::MXNet::Base; | ||
| 531 | extends 'AI::MXNet::EvalMetric'; | ||
| 532 | has '+name' => (default => 'f1'); | ||
| 533 | has 'average' => (is => 'ro', isa => 'Str', default => 'macro'); | ||
| 534 | has 'metrics' => (is => 'rw', init_arg => undef, default => sub { _BinaryClassificationMetrics->new }); | ||
| 535 | has 'method' => (is => 'ro', init_arg => undef, default => 'fscore'); | ||
| 536 | method python_constructor_arguments() { [qw/name average/] } | ||
| 537 | |||
| 538 | method update(ArrayRef[AI::MXNet::NDArray] $labels, ArrayRef[AI::MXNet::NDArray] $preds) | ||
| 539 | { | ||
| 540 | my $method = $self->method; | ||
| 541 | AI::MXNet::Metric::check_label_shapes($labels, $preds); | ||
| 542 | for(zip($labels, $preds)) { | ||
| 543 | my ($label, $pred) = @$_; | ||
| 544 | $self->metrics->update_binary_stats($label, $pred); | ||
| 545 | if($self->average eq "macro") | ||
| 546 | { | ||
| 547 | $self->sum_metric($self->sum_metric + $self->metrics->$method); | ||
| 548 | $self->num_inst($self->num_inst + 1); | ||
| 549 | $self->metrics->reset_stats(); | ||
| 550 | } | ||
| 551 | else | ||
| 552 | { | ||
| 553 | $self->sum_metric($self->metrics->fscore * $self->metrics->total_examples); | ||
| 554 | $self->num_inst($self->metrics->total_examples); | ||
| 555 | } | ||
| 556 | } | ||
| 557 | } | ||
| 558 | |||
| 559 | method reset() | ||
| 560 | { | ||
| 561 | $self->sum_metric(0); | ||
| 562 | $self->num_inst(0); | ||
| 563 | $self->metrics->reset_stats(); | ||
| 564 | } | ||
| 565 | |||
| 566 | =head1 NAME | ||
| 567 | |||
| 568 | AI::MXNet::MCC - Computes the Matthews Correlation Coefficient of a binary classification problem. | ||
| 569 | =cut | ||
| 570 | |||
| 571 | =head1 DESCRIPTION | ||
| 572 | |||
| 573 | While slower to compute than F1 the MCC can give insight that F1 or Accuracy cannot. | ||
| 574 | For instance, if the network always predicts the same result | ||
| 575 | then the MCC will immeadiately show this. The MCC is also symetric with respect | ||
| 576 | to positive and negative categorization, however, there needs to be both | ||
| 577 | positive and negative examples in the labels or it will always return 0. | ||
| 578 | MCC of 0 is uncorrelated, 1 is completely correlated, and -1 is negatively correlated. | ||
| 579 | |||
| 580 | MCC = (TP * TN - FP * FN)/sqrt( (TP + FP)*( TP + FN )*( TN + FP )*( TN + FN ) ) | ||
| 581 | |||
| 582 | where 0 terms in the denominator are replaced by 1. | ||
| 583 | |||
| 584 | This version of MCC only supports binary classification. | ||
| 585 | |||
| 586 | Parameters | ||
| 587 | ---------- | ||
| 588 | name : str, 'mcc' | ||
| 589 | Name of this metric instance for display. | ||
| 590 | average : str, default 'macro' | ||
| 591 | Strategy to be used for aggregating across mini-batches. | ||
| 592 | "macro": average the MCC for each batch. | ||
| 593 | "micro": compute a single MCC across all batches. | ||
| 594 | |||
| 595 | Examples | ||
| 596 | -------- | ||
| 597 | In this example the network almost always predicts positive | ||
| 598 | >>> $false_positives = 1000 | ||
| 599 | >>> $false_negatives = 1 | ||
| 600 | >>> $true_positives = 10000 | ||
| 601 | >>> $true_negatives = 1 | ||
| 602 | >>> $predicts = [mx->nd->array( | ||
| 603 | [ | ||
| 604 | ([.3, .7])x$false_positives, | ||
| 605 | ([.7, .3])x$true_negatives, | ||
| 606 | ([.7, .3])x$false_negatives, | ||
| 607 | ([.3, .7])xtrue_positives | ||
| 608 | ] | ||
| 609 | )]; | ||
| 610 | >>> $labels = [mx->nd->array( | ||
| 611 | [ | ||
| 612 | (0)x($false_positives + $true_negatives), | ||
| 613 | (1)x($false_negatives + $true_positives) | ||
| 614 | ] | ||
| 615 | )]; | ||
| 616 | >>> $f1 = mx->metric->F1(); | ||
| 617 | >>> $f1->update($labels, $predicts); | ||
| 618 | >>> $mcc = mx->metric->MCC() | ||
| 619 | >>> $mcc->update($labels, $predicts) | ||
| 620 | >>> print $f1->get(); | ||
| 621 | f1 0.95233560306652054 | ||
| 622 | >>> print $mcc->get(); | ||
| 623 | mcc 0.01917751877733392 | ||
| 624 | |||
| 625 | =cut | ||
| 626 | |||
| 627 | package AI::MXNet::MCC; | ||
| 628 | use Mouse; | ||
| 629 | extends 'AI::MXNet::F1'; | ||
| 630 | has '+name' => (default => 'mcc'); | ||
| 631 | has '+method' => (default => 'matthewscc'); | ||
| 632 | |||
| 633 | package AI::MXNet::Perplexity; | ||
| 634 | use Mouse; | ||
| 635 | use AI::MXNet::Base; | ||
| 636 | extends 'AI::MXNet::EvalMetric'; | ||
| 637 | has '+name' => (default => 'Perplexity'); | ||
| 638 | has 'ignore_label' => (is => 'ro', isa => 'Maybe[Int]'); | ||
| 639 | has 'axis' => (is => 'ro', isa => 'Int', default => -1); | ||
| 640 | method python_constructor_arguments() { ['ignore_label', 'axis'] } | ||
| 641 | |||
| 642 | around BUILDARGS => sub { | ||
| 643 | my $orig = shift; | ||
| 644 | my $class = shift; | ||
| 645 | return $class->$orig(ignore_label => $_[0]) if @_ == 1; | ||
| 646 | return $class->$orig(@_); | ||
| 647 | }; | ||
| 648 | |||
| 649 | =head1 NAME | ||
| 650 | |||
| 651 | AI::MXNet::Perplexity - Calculate perplexity. | ||
| 652 | =cut | ||
| 653 | |||
| 654 | =head1 DESCRIPTION | ||
| 655 | |||
| 656 | Perplexity is a measurement of how well a probability distribution or model predicts a sample. | ||
| 657 | A low perplexity indicates the model is good at predicting the sample. | ||
| 658 | |||
| 659 | Parameters | ||
| 660 | ---------- | ||
| 661 | ignore_label : int or undef | ||
| 662 | index of invalid label to ignore when | ||
| 663 | counting. usually should be -1. Include | ||
| 664 | all entries if undef. | ||
| 665 | axis : int (default -1) | ||
| 666 | The axis from prediction that was used to | ||
| 667 | compute softmax. By default uses the last | ||
| 668 | axis. | ||
| 669 | |||
| 670 | $predicts = [mx->nd->array([[0.3, 0.7], [0, 1.], [0.4, 0.6]])]; | ||
| 671 | $labels = [mx->nd->array([0, 1, 1])]; | ||
| 672 | $perp = mx->metric->Perplexity(ignore_label=>undef); | ||
| 673 | $perp->update($labels, $predicts); | ||
| 674 | print $perp->get() | ||
| 675 | Perplexity 1.77109762851559 | ||
| 676 | |||
| 677 | =cut | ||
| 678 | |||
| 679 | method update(ArrayRef[AI::MXNet::NDArray] $labels, ArrayRef[AI::MXNet::NDArray] $preds) | ||
| 680 | { | ||
| 681 | AI::MXNet::Metric::check_label_shapes($labels, $preds); | ||
| 682 | my ($loss, $num) = (0, 0); | ||
| 683 | for(zip($labels, $preds)) { | ||
| 684 | my ($label, $pred) = @$_; | ||
| 685 | my $label_shape = $label->shape; | ||
| 686 | my $pred_shape = $pred->shape; | ||
| 687 | assert( | ||
| 688 | (product(@{ $label_shape }) == product(@{ $pred_shape })/$pred_shape->[-1]), | ||
| 689 | "shape mismatch: (@$label_shape) vs. (@$pred_shape)" | ||
| 690 | ); | ||
| 691 | $label = $label->as_in_context($pred->context)->reshape([$label->size]); | ||
| 692 | $pred = AI::MXNet::NDArray->pick($pred, $label->astype('int32'), { axis => $self->axis }); | ||
| 693 | if(defined $self->ignore_label) | ||
| 694 | { | ||
| 695 | my $ignore = ($label == $self->ignore_label); | ||
| 696 | $num -= $ignore->sum->asscalar; | ||
| 697 | $pred = $pred*(1-$ignore) + $ignore; | ||
| 698 | } | ||
| 699 | $loss -= $pred->maximum(1e-10)->log->sum->asscalar; | ||
| 700 | $num += $pred->size; | ||
| 701 | } | ||
| 702 | $self->sum_metric($self->sum_metric + $loss); | ||
| 703 | $self->num_inst($self->num_inst + $num); | ||
| 704 | } | ||
| 705 | |||
| 706 | method get() | ||
| 707 | { | ||
| 708 | return ($self->name, exp($self->sum_metric / $self->num_inst)); | ||
| 709 | } | ||
| 710 | |||
| 711 | #################### | ||
| 712 | # REGRESSION METRICS | ||
| 713 | #################### | ||
| 714 | |||
| 715 | =head1 NAME | ||
| 716 | |||
| 717 | AI::MXNet::MAE - Calculate Mean Absolute Error loss | ||
| 718 | =head1 DESCRIPTION | ||
| 719 | |||
| 720 | >>> $predicts = [mx->nd->array([3, -0.5, 2, 7])->reshape([4,1])] | ||
| 721 | >>> $labels = [mx->nd->array([2.5, 0.0, 2, 8])->reshape([4,1])] | ||
| 722 | >>> $mean_absolute_error = mx->metric->MAE() | ||
| 723 | >>> $mean_absolute_error->update($labels, $predicts) | ||
| 724 | >>> print $mean_absolute_error->get() | ||
| 725 | ('mae', 0.5) | ||
| 726 | |||
| 727 | =cut | ||
| 728 | |||
| 729 | |||
| 730 | package AI::MXNet::MAE; | ||
| 731 | use Mouse; | ||
| 732 | use AI::MXNet::Base; | ||
| 733 | extends 'AI::MXNet::EvalMetric'; | ||
| 734 | has '+name' => (default => 'mae'); | ||
| 735 | |||
| 736 | method update(ArrayRef[AI::MXNet::NDArray] $labels, ArrayRef[AI::MXNet::NDArray] $preds) | ||
| 737 | { | ||
| 738 | AI::MXNet::Metric::check_label_shapes($labels, $preds); | ||
| 739 | for(zip($labels, $preds)) { | ||
| 740 | my ($label, $pred) = @$_; | ||
| 741 | $label = $label->aspdl; | ||
| 742 | $pred = $pred->aspdl; | ||
| 743 | if($label->ndims == 1) | ||
| 744 | { | ||
| 745 | $label = $label->reshape(1, $label->shape->at(0)); | ||
| 746 | } | ||
| 747 | $self->sum_metric($self->sum_metric + ($label - $pred)->abs->avg); | ||
| 748 | $self->num_inst($self->num_inst + 1); | ||
| 749 | } | ||
| 750 | } | ||
| 751 | |||
| 752 | =head1 NAME | ||
| 753 | |||
| 754 | AI::MXNet::MSE - Calculate Mean Squared Error loss | ||
| 755 | =head1 DESCRIPTION | ||
| 756 | |||
| 757 | >>> $predicts = [mx->nd->array([3, -0.5, 2, 7])->reshape([4,1])] | ||
| 758 | >>> $labels = [mx->nd->array([2.5, 0.0, 2, 8])->reshape([4,1])] | ||
| 759 | >>> $mean_squared_error = mx->metric->MSE() | ||
| 760 | >>> $mean_squared_error->update($labels, $predicts) | ||
| 761 | >>> print $mean_squared_error->get() | ||
| 762 | ('mse', 0.375) | ||
| 763 | |||
| 764 | =cut | ||
| 765 | |||
| 766 | package AI::MXNet::MSE; | ||
| 767 | use Mouse; | ||
| 768 | use AI::MXNet::Base; | ||
| 769 | extends 'AI::MXNet::EvalMetric'; | ||
| 770 | has '+name' => (default => 'mse'); | ||
| 771 | |||
| 772 | method update(ArrayRef[AI::MXNet::NDArray] $labels, ArrayRef[AI::MXNet::NDArray] $preds) | ||
| 773 | { | ||
| 774 | AI::MXNet::Metric::check_label_shapes($labels, $preds); | ||
| 775 | for(zip($labels, $preds)) { | ||
| 776 | my ($label, $pred) = @$_; | ||
| 777 | $label = $label->aspdl; | ||
| 778 | $pred = $pred->aspdl; | ||
| 779 | if($label->ndims == 1) | ||
| 780 | { | ||
| 781 | $label = $label->reshape(1, $label->shape->at(0)); | ||
| 782 | } | ||
| 783 | $self->sum_metric($self->sum_metric + (($label - $pred)**2)->avg); | ||
| 784 | $self->num_inst($self->num_inst + 1); | ||
| 785 | } | ||
| 786 | } | ||
| 787 | |||
| 788 | =head1 NAME | ||
| 789 | |||
| 790 | AI::MXNet::RMSE - Calculate Root Mean Squred Error loss | ||
| 791 | =head1 DESCRIPTION | ||
| 792 | |||
| 793 | >>> $predicts = [mx->nd->array([3, -0.5, 2, 7])->reshape([4,1])] | ||
| 794 | >>> $labels = [mx->nd->array([2.5, 0.0, 2, 8])->reshape([4,1])] | ||
| 795 | >>> $root_mean_squared_error = mx->metric->RMSE() | ||
| 796 | >>> $root_mean_squared_error->update($labels, $predicts) | ||
| 797 | >>> print $root_mean_squared_error->get() | ||
| 798 | 'rmse', 0.612372457981 | ||
| 799 | |||
| 800 | =cut | ||
| 801 | |||
| 802 | package AI::MXNet::RMSE; | ||
| 803 | use Mouse; | ||
| 804 | use AI::MXNet::Base; | ||
| 805 | extends 'AI::MXNet::EvalMetric'; | ||
| 806 | has '+name' => (default => 'rmse'); | ||
| 807 | |||
| 808 | method update(ArrayRef[AI::MXNet::NDArray] $labels, ArrayRef[AI::MXNet::NDArray] $preds) | ||
| 809 | { | ||
| 810 | AI::MXNet::Metric::check_label_shapes($labels, $preds); | ||
| 811 | for(zip($labels, $preds)) { | ||
| 812 | my ($label, $pred) = @$_; | ||
| 813 | $label = $label->aspdl; | ||
| 814 | $pred = $pred->aspdl; | ||
| 815 | if($label->ndims == 1) | ||
| 816 | { | ||
| 817 | $label = $label->reshape(1, $label->shape->at(0)); | ||
| 818 | } | ||
| 819 | $self->sum_metric($self->sum_metric + sqrt((($label - $pred)**2)->avg)); | ||
| 820 | $self->num_inst($self->num_inst + 1); | ||
| 821 | } | ||
| 822 | } | ||
| 823 | |||
| 824 | |||
| 825 | =head1 NAME | ||
| 826 | |||
| 827 | AI::MXNet::CrossEntropy - Calculate Cross Entropy loss | ||
| 828 | =head1 DESCRIPTION | ||
| 829 | |||
| 830 | >>> $predicts = [mx->nd->array([[0.3, 0.7], [0, 1.], [0.4, 0.6]])] | ||
| 831 | >>> $labels = [mx->nd->array([0, 1, 1])] | ||
| 832 | >>> $ce = mx->metric->CrossEntropy() | ||
| 833 | >>> $ce->update($labels, $predicts) | ||
| 834 | >>> print $ce->get() | ||
| 835 | ('cross-entropy', 0.57159948348999023) | ||
| 836 | |||
| 837 | =cut | ||
| 838 | |||
| 839 | # Calculate Cross Entropy loss | ||
| 840 | package AI::MXNet::CrossEntropy; | ||
| 841 | use Mouse; | ||
| 842 | use AI::MXNet::Base; | ||
| 843 | extends 'AI::MXNet::EvalMetric'; | ||
| 844 | has '+name' => (default => 'cross-entropy'); | ||
| 845 | has 'eps' => (is => 'ro', isa => 'Num', default => 1e-12); | ||
| 846 | method python_constructor_arguments() { ['eps'] } | ||
| 847 | |||
| 848 | method update(ArrayRef[AI::MXNet::NDArray] $labels, ArrayRef[AI::MXNet::NDArray] $preds) | ||
| 849 | { | ||
| 850 | AI::MXNet::Metric::check_label_shapes($labels, $preds); | ||
| 851 | for(zip($labels, $preds)) { | ||
| 852 | my ($label, $pred) = @$_; | ||
| 853 | $label = $label->aspdl->flat; | ||
| 854 | $pred = $pred->aspdl; | ||
| 855 | my $label_shape = $label->shape->at(0); | ||
| 856 | my $pred_shape = $pred->shape->at(-1); | ||
| 857 | confess( | ||
| 858 | "Size of label $label_shape and | ||
| 859 | .first dimension of pred $pred_shape do not match" | ||
| 860 | ) unless $label_shape == $pred_shape; | ||
| 861 | my $prob = $pred->index($label); | ||
| 862 | $self->sum_metric($self->sum_metric + (-($prob + $self->eps)->log)->sum); | ||
| 863 | $self->num_inst($self->num_inst + $label_shape); | ||
| 864 | } | ||
| 865 | } | ||
| 866 | |||
| 867 | =head1 NAME | ||
| 868 | |||
| 869 | AI::MXNet::NegativeLogLikelihood - Computes the negative log-likelihood loss. | ||
| 870 | =head1 DESCRIPTION | ||
| 871 | |||
| 872 | >>> $predicts = [mx->nd->array([[0.3, 0.7], [0, 1.], [0.4, 0.6]])] | ||
| 873 | >>> $labels = [mx->nd->array([0, 1, 1])] | ||
| 874 | >>> $nll_loss = mx->metric->NegativeLogLikelihood | ||
| 875 | >>> $nll_loss->update($labels, $predicts) | ||
| 876 | >>> print $nll_loss->get() | ||
| 877 | ('cross-entropy', 0.57159948348999023) | ||
| 878 | |||
| 879 | =cut | ||
| 880 | |||
| 881 | package AI::MXNet::NegativeLogLikelihood; | ||
| 882 | use Mouse; | ||
| 883 | use AI::MXNet::Base; | ||
| 884 | extends 'AI::MXNet::CrossEntropy'; | ||
| 885 | has '+name' => (default => 'nll_loss'); | ||
| 886 | |||
| 887 | package AI::MXNet::PearsonCorrelation; | ||
| 888 | use Mouse; | ||
| 889 | use AI::MXNet::Base; | ||
| 890 | extends 'AI::MXNet::EvalMetric'; | ||
| 891 | has '+name' => (default => 'pearson-correlation'); | ||
| 892 | |||
| 893 | =head1 NAME | ||
| 894 | |||
| 895 | AI::MXNet::PearsonCorrelation - Computes Pearson correlation. | ||
| 896 | =cut | ||
| 897 | |||
| 898 | =head1 DESCRIPTION | ||
| 899 | |||
| 900 | Computes Pearson correlation. | ||
| 901 | |||
| 902 | Parameters | ||
| 903 | ---------- | ||
| 904 | name : str | ||
| 905 | Name of this metric instance for display. | ||
| 906 | |||
| 907 | Examples | ||
| 908 | -------- | ||
| 909 | >>> $predicts = [mx->nd->array([[0.3, 0.7], [0, 1.], [0.4, 0.6]])] | ||
| 910 | >>> $labels = [mx->nd->array([[1, 0], [0, 1], [0, 1]])] | ||
| 911 | >>> $pr = mx->metric->PearsonCorrelation() | ||
| 912 | >>> $pr->update($labels, $predicts) | ||
| 913 | >>> print pr->get() | ||
| 914 | ('pearson-correlation', '0.421637061887229') | ||
| 915 | =cut | ||
| 916 | |||
| 917 | method update(ArrayRef[AI::MXNet::NDArray] $labels, ArrayRef[AI::MXNet::NDArray] $preds) | ||
| 918 | { | ||
| 919 | AI::MXNet::Metric::check_label_shapes($labels, $preds); | ||
| 920 | for(zip($labels, $preds)) { | ||
| 921 | my ($label, $pred) = @$_; | ||
| 922 | AI::MXNet::Metric::check_label_shapes($label, $pred); | ||
| 923 | $label = $label->aspdl->flat; | ||
| 924 | $pred = $pred->aspdl->flat; | ||
| 925 | my ($label_mean, $label_stdv) = ($label->stats)[0, 6]; | ||
| 926 | my ($pred_mean, $pred_stdv) = ($pred->stats)[0, 6]; | ||
| 927 | $self->sum_metric( | ||
| 928 | $self->sum_metric | ||
| 929 | + | ||
| 930 | ((($label-$label_mean)*($pred-$pred_mean))->sum/$label->nelem)/(($label_stdv*$pred_stdv)->at(0)) | ||
| 931 | ); | ||
| 932 | $self->num_inst($self->num_inst + 1); | ||
| 933 | } | ||
| 934 | } | ||
| 935 | |||
| 936 | package AI::MXNet::Loss; | ||
| 937 | use Mouse; | ||
| 938 | use AI::MXNet::Base; | ||
| 939 | extends 'AI::MXNet::EvalMetric'; | ||
| 940 | has '+name' => (default => 'loss'); | ||
| 941 | |||
| 942 | =head1 NAME | ||
| 943 | |||
| 944 | AI::MXNet::Loss - Dummy metric for directly printing loss. | ||
| 945 | =cut | ||
| 946 | |||
| 947 | =head1 DESCRIPTION | ||
| 948 | |||
| 949 | Dummy metric for directly printing loss. | ||
| 950 | |||
| 951 | Parameters | ||
| 952 | ---------- | ||
| 953 | name : str | ||
| 954 | Name of this metric instance for display. | ||
| 955 | =cut | ||
| 956 | |||
| 957 | method update($labels, ArrayRef[AI::MXNet::NDArray] $preds) | ||
| 958 | { | ||
| 959 | for my $pred (@{ $preds }) | ||
| 960 | { | ||
| 961 | $self->sum_metric($self->sum_metric + $pred->sum->asscalar); | ||
| 962 | $self->num_inst($self->num_inst + $pred->size); | ||
| 963 | } | ||
| 964 | } | ||
| 965 | |||
| 966 | package AI::MXNet::Confidence; | ||
| 967 | use Mouse; | ||
| 968 | |||
| 969 | =head1 NAME | ||
| 970 | |||
| 971 | AI::MXNet::Confidence - Accuracy by confidence buckets. | ||
| 972 | =cut | ||
| 973 | |||
| 974 | =head1 DESCRIPTION | ||
| 975 | |||
| 976 | Accuracy by confidence buckets. | ||
| 977 | |||
| 978 | Parameters | ||
| 979 | ---------- | ||
| 980 | name : str | ||
| 981 | Name of this metric instance for display. | ||
| 982 | num_classes: Int | ||
| 983 | number of classes | ||
| 984 | confidence_thresholds: ArrayRef[Num] | ||
| 985 | confidence buckets | ||
| 986 | For example | ||
| 987 | my $composite_metric = AI::MXNet::CompositeEvalMetric->new; | ||
| 988 | $composite_metric->add(mx->metric->create('acc')); | ||
| 989 | $composite_metric->add( | ||
| 990 | AI::MXNet::Confidence->new( | ||
| 991 | num_classes => 2, | ||
| 992 | confidence_thresholds => [ 0.5, 0.7, 0.8, 0.9 ], | ||
| 993 | ) | ||
| 994 | ); | ||
| 995 | =cut | ||
| 996 | |||
| 997 | extends 'AI::MXNet::EvalMetric'; | ||
| 998 | has 'num_classes', is => 'ro', isa => 'Int', required => 1; | ||
| 999 | has 'confidence_thresholds', is => 'ro', isa => 'ArrayRef[Num]', required => 1; | ||
| 1000 | has '+name' => (default => 'confidence'); | ||
| 1001 | has '+sum_metric', isa => 'PDL'; | ||
| 1002 | has '+num_inst', isa => 'PDL'; | ||
| 1003 | method python_constructor_arguments() { ['num_classes', 'confidence_thresholds'] } | ||
| 1004 | |||
| 1005 | sub _hot | ||
| 1006 | { | ||
| 1007 | my($m, $n) = @_; | ||
| 1008 | my $md = $m->dim(-1); | ||
| 1009 | my $hot = PDL->zeros($n, $md); | ||
| 1010 | $hot->index2d($m->flat(), PDL->sequence($md)) .= 1; | ||
| 1011 | return $hot; | ||
| 1012 | } | ||
| 1013 | |||
| 1014 | sub reset | ||
| 1015 | { | ||
| 1016 | my($self) = @_; | ||
| 1017 | my $nt = @{$self->confidence_thresholds}; | ||
| 1018 | my $n = $self->num_classes; | ||
| 1019 | $self->sum_metric(PDL->zeroes($nt, $n)); | ||
| 1020 | $self->num_inst(PDL->zeroes($nt, $n)); | ||
| 1021 | return; | ||
| 1022 | } | ||
| 1023 | |||
| 1024 | sub update | ||
| 1025 | { | ||
| 1026 | my($self, $labels, $preds) = @_; | ||
| 1027 | my $n = $self->num_classes; | ||
| 1028 | my $ct = PDL->new($self->confidence_thresholds); | ||
| 1029 | my $nt = $ct->nelem; | ||
| 1030 | for(0 .. @$labels - 1) | ||
| 1031 | { | ||
| 1032 | my $label = _hot($labels->[$_]->aspdl, $n); | ||
| 1033 | my $pred = $preds->[$_]->aspdl; | ||
| 1034 | for my $c (0 .. $n - 1) | ||
| 1035 | { | ||
| 1036 | my $ls = $label->slice($c); | ||
| 1037 | my $pm = $pred->slice($c) > $ct; | ||
| 1038 | $self->sum_metric->slice(":,$c") += ($pm & $ls); | ||
| 1039 | $self->num_inst->slice(":,$c") += $pm; | ||
| 1040 | } | ||
| 1041 | } | ||
| 1042 | return; | ||
| 1043 | } | ||
| 1044 | |||
| 1045 | sub get | ||
| 1046 | { | ||
| 1047 | my($self) = @_; | ||
| 1048 | my(@names, @values); | ||
| 1049 | my $val = $self->sum_metric / $self->num_inst; | ||
| 1050 | my $ct = $self->confidence_thresholds; | ||
| 1051 | my $n = $self->num_classes; | ||
| 1052 | for my $c (0 .. $n - 1) | ||
| 1053 | { | ||
| 1054 | for my $t (0 .. @$ct - 1) | ||
| 1055 | { | ||
| 1056 | my $sm = $self->sum_metric->at($t, $c); | ||
| 1057 | my $ni = $self->num_inst->at($t, $c); | ||
| 1058 | push @names, "P(v=$c|Conf>$ct->[$t])=($sm/$ni)"; | ||
| 1059 | push @values, $val->at($t, $c); | ||
| 1060 | } | ||
| 1061 | } | ||
| 1062 | return(\@names, \@values); | ||
| 1063 | } | ||
| 1064 | |||
| 1065 | =head1 NAME | ||
| 1066 | |||
| 1067 | AI::MXNet::CustomMetric - Custom evaluation metric that takes a sub ref. | ||
| 1068 | =cut | ||
| 1069 | |||
| 1070 | =head1 DESCRIPTION | ||
| 1071 | |||
| 1072 | Custom evaluation metric that takes a sub ref. | ||
| 1073 | |||
| 1074 | Parameters | ||
| 1075 | ---------- | ||
| 1076 | eval_function : subref | ||
| 1077 | Customized evaluation function. | ||
| 1078 | name : str, optional | ||
| 1079 | The name of the metric | ||
| 1080 | allow_extra_outputs : bool | ||
| 1081 | If true, the prediction outputs can have extra outputs. | ||
| 1082 | This is useful in RNN, where the states are also produced | ||
| 1083 | in outputs for forwarding. | ||
| 1084 | =cut | ||
| 1085 | |||
| 1086 | |||
| 1087 | package AI::MXNet::CustomMetric; | ||
| 1088 | use Mouse; | ||
| 1089 | use AI::MXNet::Base; | ||
| 1090 | extends 'AI::MXNet::EvalMetric'; | ||
| 1091 | has 'eval_function' => (is => 'ro', isa => 'CodeRef'); | ||
| 1092 | has 'allow_extra_outputs' => (is => 'ro', isa => 'Int', default => 0); | ||
| 1093 | method python_constructor_arguments() { ['eval_function', 'allow_extra_outputs'] } | ||
| 1094 | |||
| 1095 | method update(ArrayRef[AI::MXNet::NDArray] $labels, ArrayRef[AI::MXNet::NDArray] $preds) | ||
| 1096 | { | ||
| 1097 | AI::MXNet::Metric::check_label_shapes($labels, $preds) | ||
| 1098 | unless $self->allow_extra_outputs; | ||
| 1099 | for(zip($labels, $preds)) { | ||
| 1100 | my ($label, $pred) = @$_; | ||
| 1101 | $label = $label->aspdl; | ||
| 1102 | $pred = $pred->aspdl; | ||
| 1103 | my $value = $self->eval_function->($label, $pred); | ||
| 1104 | my $sum_metric = ref $value ? $value->[0] : $value; | ||
| 1105 | my $num_inst = ref $value ? $value->[1] : 1; | ||
| 1106 | $self->sum_metric($self->sum_metric + $sum_metric); | ||
| 1107 | $self->num_inst($self->num_inst + $num_inst); | ||
| 1108 | } | ||
| 1109 | } | ||
| 1110 | |||
| 1111 | package AI::MXNet::Metric; | ||
| 1112 | |||
| 1113 | =head2 create | ||
| 1114 | |||
| 1115 | Create an evaluation metric. | ||
| 1116 | |||
| 1117 | Parameters | ||
| 1118 | ---------- | ||
| 1119 | metric : str or sub ref | ||
| 1120 | The name of the metric, or a function | ||
| 1121 | providing statistics given pred, label NDArray. | ||
| 1122 | =cut | ||
| 1123 | |||
| 1124 | my %metrics = qw/ | ||
| 1125 | acc AI::MXNet::Accuracy | ||
| 1126 | accuracy AI::MXNet::Accuracy | ||
| 1127 | ce AI::MXNet::CrossEntropy | ||
| 1128 | crossentropy AI::MXNet::CrossEntropy | ||
| 1129 | nll_loss AI::MXNet::NegativeLogLikelihood | ||
| 1130 | f1 AI::MXNet::F1 | ||
| 1131 | mcc AI::MXNet::MCC | ||
| 1132 | mae AI::MXNet::MAE | ||
| 1133 | mse AI::MXNet::MSE | ||
| 1134 | rmse AI::MXNet::RMSE | ||
| 1135 | top_k_accuracy AI::MXNet::TopKAccuracy | ||
| 1136 | topkaccuracy AI::MXNet::TopKAccuracy | ||
| 1137 | perplexity AI::MXNet::Perplexity | ||
| 1138 | pearsonr AI::MXNet::PearsonCorrelation | ||
| 1139 | pearsoncorrelation AI::MXNet::PearsonCorrelation | ||
| 1140 | loss AI::MXNet::Loss | ||
| 1141 | compositeevalmetric AI::MXNet::CompositeEvalMetric | ||
| 1142 | confidence AI::MXNet::Confidence | ||
| 1143 | /; | ||
| 1144 | |||
| 1145 | method create(Metric|ArrayRef[Metric] $metric, @kwargs) | ||
| 1146 | { | ||
| 1147 | Carp::confess("metric must be defined") unless defined $metric; | ||
| 1148 | return $metric if blessed $metric and $metric->isa('AI::MXNet::EvalMetric'); | ||
| 1149 | if(my $ref = ref $metric) | ||
| 1150 | { | ||
| 1151 | if($ref eq 'ARRAY') | ||
| 1152 | { | ||
| 1153 | my $composite_metric = AI::MXNet::CompositeEvalMetric->new(); | ||
| 1154 | for my $child_metric (@{ $metric }) | ||
| 1155 | { | ||
| 1156 | $composite_metric->add(__PACKAGE__->create($child_metric, @kwargs)) | ||
| 1157 | } | ||
| 1158 | return $composite_metric; | ||
| 1159 | } | ||
| 1160 | else | ||
| 1161 | { | ||
| 1162 | return AI::MXNet::CustomMetric->new(eval_function => $metric, @kwargs); | ||
| 1163 | } | ||
| 1164 | } | ||
| 1165 | else | ||
| 1166 | { | ||
| 1167 | if(not exists $metrics{ lc($metric) } and not $metric =~ /^{/) | ||
| 1168 | { | ||
| 1169 | my @metrics = keys %metrics; | ||
| 1170 | Carp::confess("Metric must be either subref or one of [@metrics]"); | ||
| 1171 | } | ||
| 1172 | if($metric =~ /^{/ and not @kwargs) | ||
| 1173 | { | ||
| 1174 | my $config = decode_json($metric); | ||
| 1175 | $metric = delete $config->{metric}; | ||
| 1176 | @kwargs = %{ $config }; | ||
| 1177 | } | ||
| 1178 | return $metrics{ lc($metric) }->new(@kwargs); | ||
| 1179 | } | ||
| 1180 | } | ||
| 1181 | |||
| 1182 | { | ||
| 1183 | no strict 'refs'; | ||
| 1184 | no warnings 'redefine'; | ||
| 1185 | for my $metric (values %metrics) | ||
| 1186 | { | ||
| 1187 | my ($name) = $metric =~ /(\w+)$/; | ||
| 1188 | *{__PACKAGE__."::$name"} = sub { shift; $metric->new(@_); }; | ||
| 1189 | } | ||
| 1190 | } | ||
| 1191 | |||
| 1192 | 1; |