MXNet/Gluon/Loss.pm untested

filter: Statementstmt 0.0% 0 / 270 Branchbran 0.0% 0 / 38 Conditioncond 0.0% 0 / 3 MC/DCmcdc 0.0% 0 / 2 Subroutinesub 0.0% 0 / 24 Podpod 0.0% 0 / 2 totaltotal 0.0% 0 / 339 CC 2 SCAR 8.4
CC
2
Cov
0%
BUILD
6.0
BUILD
2.0
BEGIN
2.0
CRAP 2.3
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 use strict;
19 use warnings;
20 package AI::MXNet::Gluon::Loss;
21 use AI::MXNet::NS;
22 use AI::MXNet::Gluon::Block;
23 use AI::MXNet::Function::Parameters;
24  
25 =head1 NAME
26  
27 AI::MXNet::Gluon::Loss - Base class for loss.
28 =cut
29  
30 =head2 DESCRIPTION
31  
32 Base class for loss.
33  
34 Parameters
35 ----------
36 weight : float or None
37 Global scalar weight for loss.
38 batch_axis : int, default 0
39 The axis that represents mini-batch.
40 =cut
41  
42 =head2 _apply_weighting
43  
44 Apply weighting to loss.
45  
46 Parameters
47 ----------
48 loss : Symbol
49 The loss to be weighted.
50 weight : float or None
51 Global scalar weight for loss.
52 sample_weight : Symbol or None
53 Per sample weighting. Must be broadcastable to
54 the same shape as loss. For example, if loss has
55 shape (64, 10) and you want to weight each sample
56 in the batch separately, `sample_weight` should have
57 shape (64, 1).
58  
59 Returns
60 -------
61 loss : Symbol
62 Weighted loss
63 =cut
64  
65  
66 method _apply_weighting(Str $F, GluonInput $loss, Maybe[Num] $weight=, Maybe[GluonInput] $sample_weight=)
67 {
68 if(defined $sample_weight)
69 {
70 $loss = $F->broadcast_mul($loss, $sample_weight);
71 }
72 if(defined $weight)
73 {
74 $loss = $loss * $weight;
75 }
76 return $loss;
77 }
78  
79 # Reshapes x to the same shape as y
80 method _reshape_like(GluonClass $F, GluonInput $x, GluonInput $y)
81 {
82 if($F eq 'AI::MXNet::NDArray')
83 {
84 return $x->reshape($y->shape);
85 }
86 else
87 {
88 return $F->reshape_like($x, $y);
89 }
90 }
91  
92 use AI::MXNet::Gluon::Mouse;
93 extends 'AI::MXNet::Gluon::HybridBlock';
94 has 'weight' => (is => 'rw', isa => 'Num');
95 has 'batch_axis' => (is => 'rw', isa => 'Int', default => 0);
96  
97 use overload '""' => sub {
98 my $self = shift;
99 sprintf(
100 "%s(batch_axis=%s, w=%s)",
101 $self->_class_name,
102 $self->batch_axis,
103 $self->weight
104 );
105 };
106  
107 method hybrid_forward($F, $x, @args)
108 {
109 confess('NotImplementedError');
110 }
111  
112 package AI::MXNet::Gluon::L2Loss;
113 use AI::MXNet::Gluon::Mouse;
114 extends 'AI::MXNet::Gluon::Loss';
115  
116 =head1 NAME
117  
118 AI::MXNet::Gluon::L2Loss
119 =cut
120  
121 =head1 DESCRIPTION
122  
123 Calculates the mean squared error between output and label:
124  
125 Output and label can have arbitrary shape as long as they have the same
126 number of elements.
127  
128 Parameters
129 ----------
130 weight : float or None
131 Global scalar weight for loss.
132 sample_weight : Symbol or None
133 Per sample weighting. Must be broadcastable to
134 the same shape as loss. For example, if loss has
135 shape (64, 10) and you want to weight each sample
136 in the batch, `sample_weight` should have shape (64, 1).
137 batch_axis : int, default 0
138 The axis that represents mini-batch.
139 =cut
140 has '+weight' => (default => 1);
141 has '+batch_axis' => (default => 0);
142  
143 method hybrid_forward(GluonClass $F, GluonInput $pred, GluonInput $label, Maybe[GluonInput] $sample_weight=)
144 {
145  
146 $label = __PACKAGE__->_reshape_like($F, $label, $pred);
147 my $loss = $F->square($pred - $label);
148 $loss = __PACKAGE__->_apply_weighting($F, $loss, $self->weight/2, $sample_weight);
149 return $F->mean($loss, axis => $self->batch_axis, exclude => 1);
150 }
151  
152 __PACKAGE__->register('AI::MXNet::Gluon::Loss');
153  
154 package AI::MXNet::Gluon::L1Loss;
155 use AI::MXNet::Gluon::Mouse;
156 extends 'AI::MXNet::Gluon::Loss';
157 has '+weight' => (default => 1);
158 has '+batch_axis' => (default => 0);
159  
160 =head1 NAME
161  
162 AI::MXNet::Gluon::L1Loss
163 =cut
164  
165 =head1 DESCRIPTION
166  
167 Calculates the mean absolute error between output and label:
168  
169 .. math::
170 L = \\frac{1}{2}\\sum_i \\vert {output}_i - {label}_i \\vert.
171  
172 Output and label must have the same shape.
173  
174 Parameters
175 ----------
176 weight : float or None
177 Global scalar weight for loss.
178 sample_weight : Symbol or None
179 Per sample weighting. Must be broadcastable to
180 the same shape as loss. For example, if loss has
181 shape (64, 10) and you want to weight each sample
182 in the batch, `sample_weight` should have shape (64, 1).
183 batch_axis : int, default 0
184 The axis that represents mini-batch.
185 =cut
186  
187 method hybrid_forward(GluonClass $F, GluonInput $pred, GluonInput $label, Maybe[GluonInput] $sample_weight=)
188 {
189 $label = __PACKAGE__->_reshape_like($F, $label, $pred);
190 my $loss = $F->abs($pred - $label);
191 $loss = __PACKAGE__->_apply_weighting($F, $loss, $self->weight, $sample_weight);
192 return $F->mean($loss, axis => $self->batch_axis, exclude => 1);
193 }
194  
195 __PACKAGE__->register('AI::MXNet::Gluon::Loss');
196  
197 package AI::MXNet::Gluon::SigmoidBinaryCrossEntropyLoss;
198 use AI::MXNet::Gluon::Mouse;
199 extends 'AI::MXNet::Gluon::Loss';
200 has 'from_sigmoid' => (is => 'ro', isa => 'Bool', default => 0);
201 has '+batch_axis' => (default => 0);
202  
203 =head1 NAME
204  
205 AI::MXNet::Gluon::SigmoidBinaryCrossEntropyLoss
206 =cut
207  
208 =head1 DESCRIPTION
209  
210 The cross-entropy loss for binary classification. (alias: SigmoidBCELoss)
211  
212 BCE loss is useful when training logistic regression.
213  
214 .. math::
215 loss(o, t) = - 1/n \sum_i (t[i] * log(o[i]) + (1 - t[i]) * log(1 - o[i]))
216  
217  
218 Parameters
219 ----------
220 from_sigmoid : bool, default is `False`
221 Whether the input is from the output of sigmoid. Set this to false will make
222 the loss calculate sigmoid and then BCE, which is more numerically stable through
223 log-sum-exp trick.
224 weight : float or None
225 Global scalar weight for loss.
226 sample_weight : Symbol or None
227 Per sample weighting. Must be broadcastable to
228 the same shape as loss. For example, if loss has
229 shape (64, 10) and you want to weight each sample
230 in the batch, `sample_weight` should have shape (64, 1).
231 batch_axis : int, default 0
232 The axis that represents mini-batch.
233 =cut
234  
235 method hybrid_forward(GluonClass $F, GluonInput $pred, GluonInput $label, Maybe[GluonInput] $sample_weight=)
236 {
237 $label = __PACKAGE__->_reshape_like($F, $label, $pred);
238 my $loss;
239 if(not $self->from_sigmoid)
240 {
241 $loss = $F->relu($pred) - $pred * $label + $F->Activation(-$F->abs($pred), act_type=>'softrelu');
242 }
243 else
244 {
245 $loss = -($F->log($pred+1e-12)*$label + $F->log(1-$pred+1e-12)*(1-$label));
246 }
247 $loss = __PACKAGE__->_apply_weighting($F, $loss, $self->weight, $sample_weight);
248 return $F->mean($loss, axis => $self->batch_axis, exclude => 1);
249 }
250  
251 __PACKAGE__->register('AI::MXNet::Gluon::Loss');
252  
253 package AI::MXNet::Gluon::SigmoidBCELoss;
254 use AI::MXNet::Gluon::Mouse;
255 extends 'AI::MXNet::Gluon::SigmoidBinaryCrossEntropyLoss';
256  
257 __PACKAGE__->register('AI::MXNet::Gluon::Loss');
258  
259 package AI::MXNet::Gluon::SoftmaxCrossEntropyLoss;
260 use AI::MXNet::Gluon::Mouse;
261 extends 'AI::MXNet::Gluon::Loss';
262  
263  
264 =head1 NAME
265  
266 AI::MXNet::Gluon::SoftmaxCrossEntropyLoss
267 =cut
268  
269 =head1 DESCRIPTION
270  
271 Computes the softmax cross entropy loss. (alias: SoftmaxCELoss)
272  
273 If `sparse_label` is `True`, label should contain integer category indicators:
274  
275 .. math::
276 p = {softmax}({output})
277  
278 L = -\\sum_i {log}(p_{i,{label}_i})
279  
280 Label's shape should be output's shape without the `axis` dimension. i.e. for
281 `output.shape` = (1,2,3,4) and axis = 2, `label.shape` should be (1,2,4).
282  
283 If `sparse_label` is `False`, label should contain probability distribution
284 with the same shape as output:
285  
286 .. math::
287 p = {softmax}({output})
288  
289 L = -\\sum_i \\sum_j {label}_j {log}(p_{ij})
290  
291 Parameters
292 ----------
293 axis : int, default -1
294 The axis to sum over when computing softmax and entropy.
295 sparse_label : bool, default True
296 Whether label is an integer array instead of probability distribution.
297 from_logits : bool, default False
298 Whether input is a log probability (usually from log_softmax) instead
299 of unnormalized numbers.
300 weight : float or None
301 Global scalar weight for loss.
302 sample_weight : Symbol or None
303 Per sample weighting. Must be broadcastable to
304 the same shape as loss. For example, if loss has
305 shape (64, 10) and you want to weight each sample
306 in the batch, `sample_weight` should have shape (64, 1).
307 batch_axis : int, default 0
308 The axis that represents mini-batch.
309 =cut
310  
311 has 'axis' => (is => 'ro', isa => 'Int', default => -1);
312 has '+batch_axis' => (default => 0);
313 has 'sparse_label' => (is => 'ro', isa => 'Bool', default => 1);
314 has 'from_logits' => (is => 'ro', isa => 'Bool', default => 0);
315  
316 method hybrid_forward(GluonClass $F, GluonInput $pred, GluonInput $label, Maybe[GluonInput] $sample_weight=)
317 {
318 if(not $self->from_logits)
319 {
320 $pred = $F->log_softmax($pred, axis => $self->axis);
321 }
322 my $loss;
323 if($self->sparse_label)
324 {
325 $loss = -$F->pick($pred, $label, axis=>$self->axis, keepdims => 1);
326 }
327 else
328 {
329 __PACKAGE__->reshape_like($F, $label, $pred);
330 $loss = -$F->sum($pred*$label, axis => $self->axis, keepdims => 1);
331 }
332 $loss = __PACKAGE__->_apply_weighting($F, $loss, $self->weight, $sample_weight);
333 return $F->mean($loss, axis => $self->batch_axis, exclude => 1);
334 }
335  
336 __PACKAGE__->register('AI::MXNet::Gluon::Loss');
337  
338 package AI::MXNet::Gluon::SoftmaxCELoss;
339 use AI::MXNet::Gluon::Mouse;
340 extends 'AI::MXNet::Gluon::SoftmaxCrossEntropyLoss';
341  
342 __PACKAGE__->register('AI::MXNet::Gluon::Loss');
343  
344  
345 package AI::MXNet::Gluon::KLDivLoss;
346 use AI::MXNet::Gluon::Mouse;
347 extends 'AI::MXNet::Gluon::Loss';
348 has '+batch_axis' => (default => 0);
349 has 'axis' => (is => 'ro', isa => 'Int', default => -1);
350 has 'from_logits' => (is => 'ro', isa => 'Bool', default => 1);
351  
352 =head1 NAME
353  
354 AI::MXNet::Gluon::KLDivLoss
355 =cut
356  
357 =head1 DESCRIPTION
358  
359 The Kullback-Leibler divergence loss.
360  
361 KL divergence is a useful distance measure for continuous distributions
362 and is often useful when performing direct regression over the space of
363 (discretely sampled) continuous output distributions.
364  
365 .. _Kullback-Leibler divergence:
366 https://en.wikipedia.org/wiki/Kullback-Leibler_divergence
367 .. math::
368 L = 1/n \\sum_i (label_i * (log(label_i) - output_i))
369  
370 Label's shape should be the same as output's.
371  
372 Parameters
373 ----------
374 from_logits : bool, default is `True`
375 Whether the input is log probability (usually from log_softmax) instead
376 of unnormalized numbers.
377 weight : float or None
378 Global scalar weight for loss.
379 axis : int, default -1
380 The dimension along with to compute softmax. Only used when `from_logits`
381 is False.
382 sample_weight : Symbol or None
383 Per sample weighting. Must be broadcastable to
384 the same shape as loss. For example, if loss has
385 shape (64, 10) and you want to weight each sample
386 in the batch, `sample_weight` should have shape (64, 1).
387 batch_axis : int, default 0
388 The axis that represents mini-batch.
389 =cut
390  
391 method hybrid_forward(GluonClass $F, GluonInput $pred, GluonInput $label, Maybe[GluonInput] $sample_weight=)
392 {
393 if(not $self->from_logits)
394 {
395 $pred = $F->log_softmax($pred, axis => $self->axis);
396 }
397 my $loss = $label * ($F->log($label+1e-12) - $pred);
398 $loss = __PACKAGE__->_apply_weighting($F, $loss, $self->weight, $sample_weight);
399 return $F->mean($loss, axis => $self->batch_axis, exclude => 1);
400 }
401  
402 __PACKAGE__->register('AI::MXNet::Gluon::Loss');
403  
404 package AI::MXNet::Gluon::CTCLoss;
405 use AI::MXNet::Gluon::Mouse;
406 extends 'AI::MXNet::Gluon::Loss';
407 has 'layout' => (is => 'rw', isa => 'Str', default => 'NTC');
408 has 'label_layout' => (is => 'rw', isa => 'Str', default => 'NT');
409  
410 =head1 NAME
411  
412 AI::MXNet::Gluon::CTCLoss
413 =cut
414  
415 =head1 DESCRIPTION
416  
417 Connectionist Temporal Classification Loss.
418  
419 See `"Connectionist Temporal Classification: Labelling Unsegmented
420 Sequence Data with Recurrent Neural Networks"
421 <http://www.cs.toronto.edu/~graves/icml_2006.pdf>`_ paper for more information.
422  
423 Parameters
424 ----------
425 layout : str, default 'NTC'
426 Layout of the output sequence activation vector.
427 label_layout : str, default 'NT'
428 Layout of the labels.
429 weight : float or None
430 Global scalar weight for loss.
431 sample_weight : Symbol or None
432 Per sample weighting. Must be broadcastable to
433 the same shape as loss. For example, if loss has
434 shape (64, 10) and you want to weight each sample
435 in the batch, `sample_weight` should have shape (64, 1).
436 This should be used as the fifth argument when calling this loss.
437  
438 Input shapes:
439 `data` is an activation tensor (i.e. before softmax).
440 Its shape depends on `layout`. For `layout='TNC'`, this
441 input has shape `(sequence_length, batch_size, alphabet_size)`
442 Note that the last dimension with index `alphabet_size-1` is reserved for special
443 blank character.
444  
445 `label` is the label index matrix with zero-indexed labels.
446 Its shape depends on `label_layout`. For `label_layout='TN'`, this
447 input has shape `(label_sequence_length, batch_size)`. Padding mask of value ``-1``
448 is available for dealing with unaligned label lengths.
449 When `label_lengths` is specified, label lengths are directly used and padding mask
450 is not allowed in the label.
451 When `label_lengths` is not specified, the first occurrence of ``-1``
452 in each sample marks the end of the label sequence of that sample.
453  
454 For example, suppose the vocabulary is `[a, b, c]`, and in one batch we have three
455 sequences 'ba', 'cbb', and 'abac'. We can index the labels as `{'a': 0, 'b': 1, 'c': 2}`.
456 The alphabet size should be 4, and we reserve the channel index 3 for blank label
457 in data tensor. The padding mask value for extra length is -1, so the resulting `label`
458 tensor should be padded to be::
459  
460 [[1, 0, -1, -1], [2, 1, 1, -1], [0, 1, 0, 2]]
461  
462 `data_lengths` is optional and defaults to None.
463 When specified, it represents the actual lengths of data.
464 The shape should be (batch_size,).
465 If None, the data lengths are treated as being equal to the max sequence length.
466 This should be used as the third argument when calling this loss.
467  
468 `label_lengths` is optional and defaults to None.
469 When specified, it represents the actual lengths of labels.
470 The shape should be (batch_size,).
471 If None, the label lengths are derived from the first occurrence of
472 the value specified by `padding_mask`.
473 This should be used as the fourth argument when calling this loss.
474  
475 Output shape:
476 The CTC loss output has the shape (batch_size,).
477 =cut
478 use AI::MXNet::Base;
479  
480 sub BUILD
481 {
482 my $self = shift;
483 assert(
484 (grep { $_ eq $self->layout } ('NTC', 'TNC')),
485 "Only 'NTC' and 'TNC' layouts for output are supported. Got: ${\ $self->layout }"
486 );
487 assert(
488 (grep { $_ eq $self->label_layout } ('NT', 'TN')),
489 "Only 'NT' and 'TN' layouts for label are supported. Got: ${\ $self->label_layout }"
490 );
491 $self->batch_axis(index($self->label_layout, 'N'));
492 }
493  
494 method hybrid_forward(
495 GluonClass $F, GluonInput $data, GluonInput $label,
496 Maybe[GluonInput] $data_lengths=, Maybe[GluonInput] $label_lengths=, Maybe[GluonInput] $sample_weight=
497 )
498 {
499 if($self->layout eq 'NTC')
500 {
501 $data = $F->swapaxes($data, dim1 => 0, dim2 => 1);
502 }
503 if($self->batch_axis == 1)
504 {
505 $label = $F->swapaxes($label, dim1 => 0, dim2 => 1);
506 }
507 my $loss = $F->contrib->CTCLoss(
508 $data, $label,
509 (defined $data_lengths ? $data_lengths : ()),
510 (defined $label_lengths ? $label_lengths : ()),
511 use_data_lengths => defined $data_lengths ? 1 : 0,
512 use_label_lengths => defined $label_lengths ? 1 : 0,
513 blank_label=>'last'
514 );
515 return $self->_apply_weighting($F, $loss, $self->weight, $sample_weight);
516 }
517  
518 __PACKAGE__->register('AI::MXNet::Gluon::Loss');
519  
520 package AI::MXNet::Gluon::HuberLoss;
521 use AI::MXNet::Gluon::Mouse;
522 extends 'AI::MXNet::Gluon::Loss';
523 has 'rho' => (is => 'rw', isa => 'Num', default => 1);
524  
525 =head1 NAME
526  
527 AI::MXNet::Gluon::HuberLoss
528 =cut
529  
530 =head1 DESCRIPTION
531  
532 Calculates smoothed L1 loss that is equal to L1 loss if absolute error
533 exceeds rho but is equal to L2 loss otherwise. Also called SmoothedL1 loss.
534  
535 .. math::
536 L = \sum_i \begin{cases} \frac{1}{2 {rho}} ({pred}_i - {label}_i)^2 &
537 \text{ if } |{pred}_i - {label}_i| < {rho} \\
538 |{pred}_i - {label}_i| - \frac{{rho}}{2} &
539 \text{ otherwise }
540 \end{cases}
541  
542 `pred` and `label` can have arbitrary shape as long as they have the same
543 number of elements.
544  
545 Parameters
546 ----------
547 rho : float, default 1
548 Threshold for trimmed mean estimator.
549 weight : float or None
550 Global scalar weight for loss.
551 batch_axis : int, default 0
552 The axis that represents mini-batch.
553  
554  
555 Inputs:
556 - **pred**: prediction tensor with arbitrary shape
557 - **label**: target tensor with the same size as pred.
558 - **sample_weight**: element-wise weighting tensor. Must be broadcastable
559 to the same shape as pred. For example, if pred has shape [64, 10]
560 and you want to weigh each sample in the batch separately,
561 sample_weight should have shape [64, 1].
562  
563 Outputs:
564 - **loss**: loss tensor with shape [batch_size]. Dimenions other than
565 batch_axis are averaged out.
566 =cut
567  
568 method hybrid_forward(
569 GluonClass $F, GluonInput $pred, GluonInput $label, Maybe[GluonInput] $sample_weight=
570 )
571 {
572 $label = __PACKAGE__->_reshape_like($F, $label, $pred);
573 my $loss = $F->abs($pred - $label);
574 $loss = $F->where(
575 $loss > $self->rho, $loss - 0.5 * $self->rho,
576 (0.5/$self->rho) * $F->square($loss)
577 );
578 $loss = __PACKAGE__->_apply_weighting($F, $loss, $self->weight, $sample_weight);
579 return $F->mean($loss, axis => $self->batch_axis, exclude => 1);
580 }
581  
582 __PACKAGE__->register('AI::MXNet::Gluon::Loss');
583  
584 package AI::MXNet::Gluon::HingeLoss;
585 use AI::MXNet::Gluon::Mouse;
586 extends 'AI::MXNet::Gluon::Loss';
587 has 'margin' => (is => 'rw', isa => 'Num', default => 1);
588  
589 =head1 NAME
590  
591 AI::MXNet::Gluon::HingeLoss
592 =cut
593  
594 =head1 DESCRIPTION
595  
596 Calculates the hinge loss function often used in SVMs:
597  
598 .. math::
599 L = \sum_i max(0, {margin} - {pred}_i \cdot {label}_i)
600  
601 where `pred` is the classifier prediction and `label` is the target tensor
602 containing values -1 or 1. `pred` and `label` must have the same number of
603 elements.
604  
605 Parameters
606 ----------
607 margin : float
608 The margin in hinge loss. Defaults to 1.0
609 weight : float or None
610 Global scalar weight for loss.
611 batch_axis : int, default 0
612 The axis that represents mini-batch.
613  
614  
615 Inputs:
616 - **pred**: prediction tensor with arbitrary shape.
617 - **label**: truth tensor with values -1 or 1. Must have the same size
618 as pred.
619 - **sample_weight**: element-wise weighting tensor. Must be broadcastable
620 to the same shape as pred. For example, if pred has shape (64, 10)
621 and you want to weigh each sample in the batch separately,
622 sample_weight should have shape (64, 1).
623  
624 Outputs:
625 - **loss**: loss tensor with shape (batch_size,). Dimenions other than
626 batch_axis are averaged out.
627 =cut
628  
629 method hybrid_forward(
630 GluonClass $F, GluonInput $pred, GluonInput $label, Maybe[GluonInput] $sample_weight=
631 )
632 {
633 $label = __PACKAGE__->_reshape_like($F, $label, $pred);
634 my $loss = $F->relu($self->margin - $pred * $label);
635 $loss = __PACKAGE__->_apply_weighting($F, $loss, $self->weight, $sample_weight);
636 return $F->mean($loss, axis => $self->batch_axis, exclude => 1);
637 }
638  
639 __PACKAGE__->register('AI::MXNet::Gluon::Loss');
640  
641 package AI::MXNet::Gluon::SquaredHingeLoss;
642 use AI::MXNet::Gluon::Mouse;
643 extends 'AI::MXNet::Gluon::Loss';
644 has 'margin' => (is => 'rw', isa => 'Num', default => 1);
645  
646 =head1 NAME
647  
648 AI::MXNet::Gluon::SquaredHingeLoss
649 =cut
650  
651 =head1 DESCRIPTION
652  
653 Calculates the soft-margin loss function used in SVMs:
654  
655 .. math::
656 L = \sum_i max(0, {margin} - {pred}_i \cdot {label}_i)^2
657  
658 where `pred` is the classifier prediction and `label` is the target tensor
659 containing values -1 or 1. `pred` and `label` can have arbitrary shape as
660 long as they have the same number of elements.
661  
662 Parameters
663 ----------
664 margin : float
665 The margin in hinge loss. Defaults to 1.0
666 weight : float or None
667 Global scalar weight for loss.
668 batch_axis : int, default 0
669 The axis that represents mini-batch.
670  
671  
672 Inputs:
673 - **pred**: prediction tensor with arbitrary shape
674 - **label**: truth tensor with values -1 or 1. Must have the same size
675 as pred.
676 - **sample_weight**: element-wise weighting tensor. Must be broadcastable
677 to the same shape as pred. For example, if pred has shape (64, 10)
678 and you want to weigh each sample in the batch separately,
679 sample_weight should have shape (64, 1).
680  
681 Outputs:
682 - **loss**: loss tensor with shape (batch_size,). Dimenions other than
683 batch_axis are averaged out.
684 =cut
685  
686 method hybrid_forward(
687 GluonClass $F, GluonInput $pred, GluonInput $label, Maybe[GluonInput] $sample_weight=
688 )
689 {
690 $label = __PACKAGE__->_reshape_like($F, $label, $pred);
691 my $loss = $F->square($F->relu($self->margin - $pred * $label));
692 $loss = __PACKAGE__->_apply_weighting($F, $loss, $self->weight, $sample_weight);
693 return $F->mean($loss, axis => $self->batch_axis, exclude => 1);
694 }
695  
696 __PACKAGE__->register('AI::MXNet::Gluon::Loss');
697  
698 package AI::MXNet::Gluon::LogisticLoss;
699 use AI::MXNet::Gluon::Mouse;
700 extends 'AI::MXNet::Gluon::Loss';
701 has 'label_format' => (is => 'rw', isa => 'Str', default => 'signed');
702  
703 =head1 NAME
704  
705 AI::MXNet::Gluon::LogisticLoss
706 =cut
707  
708 =head1 DESCRIPTION
709  
710 Calculates the logistic loss (for binary losses only):
711  
712 .. math::
713 L = \sum_i \log(1 + \exp(- {pred}_i \cdot {label}_i))
714  
715 where `pred` is the classifier prediction and `label` is the target tensor
716 containing values -1 or 1 (0 or 1 if `label_format` is binary).
717 `pred` and `label` can have arbitrary shape as long as they have the same number of elements.
718  
719 Parameters
720 ----------
721 weight : float or None
722 Global scalar weight for loss.
723 batch_axis : int, default 0
724 The axis that represents mini-batch.
725 label_format : str, default 'signed'
726 Can be either 'signed' or 'binary'. If the label_format is 'signed', all label values should
727 be either -1 or 1. If the label_format is 'binary', all label values should be either
728 0 or 1.
729  
730 Inputs:
731 - **pred**: prediction tensor with arbitrary shape.
732 - **label**: truth tensor with values -1/1 (label_format is 'signed')
733 or 0/1 (label_format is 'binary'). Must have the same size as pred.
734 - **sample_weight**: element-wise weighting tensor. Must be broadcastable
735 to the same shape as pred. For example, if pred has shape (64, 10)
736 and you want to weigh each sample in the batch separately,
737 sample_weight should have shape (64, 1).
738  
739 Outputs:
740 - **loss**: loss tensor with shape (batch_size,). Dimenions other than
741 batch_axis are averaged out.
742 =cut
743  
744 sub BUILD
745 {
746 my $self = shift;
747 if(not ($self->label_format eq 'signed' or $self->label_format eq 'binary'))
748 {
749 confess(sprintf("label_format can only be signed or binary, recieved %s", $self->label_format));
750 }
751 }
752  
753 method hybrid_forward(
754 GluonClass $F, GluonInput $pred, GluonInput $label, Maybe[GluonInput] $sample_weight=
755 )
756 {
757 $label = __PACKAGE__->_reshape_like($F, $label, $pred);
758 if($self->label_format eq 'signed')
759 {
760 $label = ($label + 1) / 2; # Transform label to be either 0 or 1
761 }
762 # Use a stable formula in computation
763 my $loss = $F->relu($pred) - $pred * $label + $F->Activation(-$F->abs($pred), act_type=>'softrelu');
764 $loss = __PACKAGE__->_apply_weighting($F, $loss, $self->weight, $sample_weight);
765 return $F->mean($loss, axis => $self->batch_axis, exclude => 1);
766 }
767  
768 __PACKAGE__->register('AI::MXNet::Gluon::Loss');
769  
770 package AI::MXNet::Gluon::TripletLoss;
771 use AI::MXNet::Gluon::Mouse;
772 extends 'AI::MXNet::Gluon::Loss';
773 has 'margin' => (is => 'rw', isa => 'Num', default => 1);
774  
775 =head1 NAME
776  
777 AI::MXNet::Gluon::TripletLoss
778 =cut
779  
780 =head1 DESCRIPTION
781  
782 Calculates triplet loss given three input tensors and a positive margin.
783 Triplet loss measures the relative similarity between prediction, a positive
784 example and a negative example:
785  
786 .. math::
787 L = \sum_i \max(\Vert {pred}_i - {pos_i} \Vert_2^2 -
788 \Vert {pred}_i - {neg_i} \Vert_2^2 + {margin}, 0)
789  
790 `pred`, `positive` and `negative` can have arbitrary shape as long as they
791 have the same number of elements.
792  
793 Parameters
794 ----------
795 margin : float
796 Margin of separation between correct and incorrect pair.
797 weight : float or None
798 Global scalar weight for loss.
799 batch_axis : int, default 0
800 The axis that represents mini-batch.
801  
802  
803 Inputs:
804 - **pred**: prediction tensor with arbitrary shape
805 - **positive**: positive example tensor with arbitrary shape. Must have
806 the same size as pred.
807 - **negative**: negative example tensor with arbitrary shape Must have
808 the same size as pred.
809  
810 Outputs:
811 - **loss**: loss tensor with shape (batch_size,).
812 =cut
813  
814 method hybrid_forward(
815 GluonClass $F, GluonInput $pred, GluonInput $positive, GluonInput $negative, Maybe[GluonInput] $sample_weight=
816 )
817 {
818 $positive = __PACKAGE__->_reshape_like($F, $positive, $pred);
819 $negative = __PACKAGE__->_reshape_like($F, $negative, $pred);
820 my $loss = $F->sum($F->square($pred-$positive) - $F->square($pred-$negative),
821 axis=>$self->batch_axis, exclude=>1);
822 $loss = $F->relu($loss + $self->margin);
823 return __PACKAGE__->_apply_weighting($F, $loss, $self->weight, $sample_weight);
824 }
825  
826 __PACKAGE__->register('AI::MXNet::Gluon::Loss');
827  
828 package AI::MXNet::Gluon::PoissonNLLLoss;
829 use AI::MXNet::Gluon::Mouse;
830 extends 'AI::MXNet::Gluon::Loss';
831 has 'from_logits' => (is => 'ro', isa => 'Bool', default => 1);
832 has 'compute_full' => (is => 'ro', isa => 'Bool', default => 0);
833  
834 =head1 NAME
835  
836 AI::MXNet::Gluon::PoissonNLLLoss
837 =cut
838  
839 =head1 DESCRIPTION
840  
841 For a target (Random Variable) in a Poisson distribution, the function calculates the Negative
842 Log likelihood loss.
843 PoissonNLLLoss measures the loss accrued from a poisson regression prediction made by the model.
844  
845 .. math::
846 L = \text{pred} - \text{target} * \log(\text{pred}) +\log(\text{target!})
847  
848 `pred`, `target` can have arbitrary shape as long as they have the same number of elements.
849  
850 Parameters
851 ----------
852 from_logits : boolean, default True
853 indicating whether log(predicted) value has already been computed. If True, the loss is computed as
854 :math:`\exp(\text{pred}) - \text{target} * \text{pred}`, and if False, then loss is computed as
855 :math:`\text{pred} - \text{target} * \log(\text{pred}+\text{epsilon})`.The default value
856 weight : float or None
857 Global scalar weight for loss.
858 batch_axis : int, default 0
859 The axis that represents mini-batch.
860 compute_full: boolean, default False
861 Indicates whether to add an approximation(Stirling factor) for the Factorial term in the formula for the loss.
862 The Stirling factor is:
863 :math:`\text{target} * \log(\text{target}) - \text{target} + 0.5 * \log(2 * \pi * \text{target})`
864 epsilon: float, default 1e-08
865 This is to avoid calculating log(0) which is not defined.
866  
867  
868 Inputs:
869 - **pred**: Predicted value
870 - **target**: Random variable(count or number) which belongs to a Poisson distribution.
871 - **sample_weight**: element-wise weighting tensor. Must be broadcastable
872 to the same shape as pred. For example, if pred has shape (64, 10)
873 and you want to weigh each sample in the batch separately,
874 sample_weight should have shape (64, 1).
875  
876 Outputs:
877 - **loss**: Average loss (shape=(1,1)) of the loss tensor with shape (batch_size,).
878 =cut
879  
880 method hybrid_forward(
881 GluonClass $F, GluonInput $pred, GluonInput $target,
882 Maybe[GluonInput] $sample_weight=, Maybe[Num] $epsilon=1e-08
883 )
884 {
885 $target = __PACKAGE__->_reshape_like($F, $target, $pred);
886 my $loss;
887 if($self->from_logits)
888 {
889 $loss = $F->exp($pred) - $target * $pred;
890 }
891 else
892 {
893 $loss = $pred - $target * $F->log($pred + $epsilon);
894 if($self->compute_full)
895 {
896 my $stirling_factor = $target * $F->log($target) - $target + 0.5 * $F->log(2 * $target * 3.1415926);
897 $stirling_factor *= ($target > 1);
898 $loss += $stirling_factor;
899 }
900 $loss = __PACKAGE__->_apply_weighting($F, $loss, $self->weight, $sample_weight);
901 }
902 return $F->mean($loss);
903 }
904  
905 __PACKAGE__->register('AI::MXNet::Gluon::Loss');
906  
907 package AI::MXNet::Gluon::CosineEmbeddingLoss;
908 use AI::MXNet::Gluon::Mouse;
909 extends 'AI::MXNet::Gluon::Loss';
910 has 'margin' => (is => 'rw', isa => 'Num', default => 0);
911  
912 =head1 NAME
913  
914 AI::MXNet::Gluon::CosineEmbeddingLoss
915 =cut
916  
917 =head1 DESCRIPTION
918  
919 For a target label 1 or -1, vectors input1 and input2, the function computes the cosine distance
920 between the vectors. This can be interpreted as how similar/dissimilar two input vectors are.
921  
922 .. math::
923  
924 L = \sum_i \begin{cases} 1 - {cos\_sim({input1}_i, {input2}_i)} & \text{ if } {label}_i = 1\\
925 {cos\_sim({input1}_i, {input2}_i)} & \text{ if } {label}_i = -1 \end{cases}\\
926 cos\_sim(input1, input2) = \frac{{input1}_i.{input2}_i}{||{input1}_i||.||{input2}_i||}
927  
928 `input1`, `input2` can have arbitrary shape as long as they have the same number of elements.
929  
930 Parameters
931 ----------
932 weight : float or None
933 Global scalar weight for loss.
934 batch_axis : int, default 0
935 The axis that represents mini-batch.
936 margin : float
937 Margin of separation between correct and incorrect pair.
938  
939  
940 Inputs:
941 - **input1**: a tensor with arbitrary shape
942 - **input2**: another tensor with same shape as pred to which input1 is
943 compared for similarity and loss calculation
944 - **label**: A 1-D tensor indicating for each pair input1 and input2, target label is 1 or -1
945 - **sample_weight**: element-wise weighting tensor. Must be broadcastable
946 to the same shape as input1. For example, if input1 has shape (64, 10)
947 and you want to weigh each sample in the batch separately,
948 sample_weight should have shape (64, 1).
949  
950 Outputs:
951 - **loss**: The loss tensor with shape (batch_size,).
952 =cut
953  
954 method hybrid_forward(
955 GluonClass $F, GluonInput $input1, GluonInput $input2, GluonInput $label, Maybe[GluonInput] $sample_weight=
956 )
957 {
958 $input1 = __PACKAGE__->_reshape_like($F, $input1, $input2);
959 $label = $label->reshape([-1, 1]);
960 my $cos_sim = $self->_cosine_similarity($F, $input1, $input2);
961 my $y_1 = $label == 1;
962 my $y_minus_1 = $label == -1;
963 my $cos_sim_a = (1 - $cos_sim) * $y_1;
964  
965 my $z_array;
966 if($F eq 'AI::MXNet::NDArray')
967 {
968 $z_array = $F->array([0]);
969 }
970 else
971 {
972 $z_array = $F->zeros([1, 1]);
973 }
974 my $cos_sim_b = $F->broadcast_maximum($z_array, $y_minus_1 * ($cos_sim - $self->margin), { axis=>1 });
975 my $loss = $cos_sim_a + $cos_sim_b;
976 $loss = __PACKAGE__->_apply_weighting($F, $loss, $self->weight, $sample_weight);
977 return $loss;
978 }
979  
980 method _cosine_similarity($F, $x, $y, $axis=-1)
981 {
982 my $x_norm = $F->norm($x, axis=>$axis)->reshape([-1, 1]);
983 my $y_norm = $F->norm($y, axis=>$axis)->reshape([-1, 1]);
984 my $x_dot_y = $F->sum($x*$y, axis=>$axis)->reshape([-1, 1]);
985 my $eps_arr;
986 if($F eq 'AI::MXNet::NDArray')
987 {
988 $eps_arr = $F->array([1e-12]);
989 }
990 else
991 {
992 $eps_arr = $F->full([1, 1], 1e-12);
993 }
994 return ($x_dot_y / $F->broadcast_maximum($x_norm * $y_norm, $eps_arr));
995 }
996  
997 __PACKAGE__->register('AI::MXNet::Gluon::Loss');
998  
999 1;