/
losses.R
1674 lines (1632 loc) · 48.4 KB
/
losses.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#' Computes the cross-entropy loss between true labels and predicted labels.
#'
#' @description
#' Use this cross-entropy loss for binary (0 or 1) classification applications.
#' The loss function requires the following inputs:
#'
#' - `y_true` (true label): This is either 0 or 1.
#' - `y_pred` (predicted value): This is the model's prediction, i.e, a single
#' floating-point value which either represents a
#' [logit](https://en.wikipedia.org/wiki/Logit), (i.e, value in `[-inf, inf]`
#' when `from_logits=TRUE`) or a probability (i.e, value in `[0., 1.]` when
#' `from_logits=FALSE`).
#'
#' # Examples
#' ```{r}
#' y_true <- rbind(c(0, 1), c(0, 0))
#' y_pred <- rbind(c(0.6, 0.4), c(0.4, 0.6))
#' loss <- loss_binary_crossentropy(y_true, y_pred)
#' loss
#' ```
#' **Recommended Usage:** (set `from_logits=TRUE`)
#'
#' With `compile()` API:
#'
#' ```{r, eval = FALSE}
#' model %>% compile(
#' loss = loss_binary_crossentropy(from_logits=TRUE),
#' ...
#' )
#' ```
#'
#' As a standalone function:
#'
#' ```{r}
#' # Example 1: (batch_size = 1, number of samples = 4)
#' y_true <- op_array(c(0, 1, 0, 0))
#' y_pred <- op_array(c(-18.6, 0.51, 2.94, -12.8))
#' bce <- loss_binary_crossentropy(from_logits = TRUE)
#' bce(y_true, y_pred)
#' ```
#'
#' ```{r}
#' # Example 2: (batch_size = 2, number of samples = 4)
#' y_true <- rbind(c(0, 1), c(0, 0))
#' y_pred <- rbind(c(-18.6, 0.51), c(2.94, -12.8))
#' # Using default 'auto'/'sum_over_batch_size' reduction type.
#' bce <- loss_binary_crossentropy(from_logits = TRUE)
#' bce(y_true, y_pred)
#'
#' # Using 'sample_weight' attribute
#' bce(y_true, y_pred, sample_weight = c(0.8, 0.2))
#' # 0.243
#' # Using 'sum' reduction` type.
#' bce <- loss_binary_crossentropy(from_logits = TRUE, reduction = "sum")
#' bce(y_true, y_pred)
#'
#' # Using 'none' reduction type.
#' bce <- loss_binary_crossentropy(from_logits = TRUE, reduction = NULL)
#' bce(y_true, y_pred)
#' ```
#'
#' **Default Usage:** (set `from_logits=FALSE`)
#'
#' ```{r}
#' # Make the following updates to the above "Recommended Usage" section
#' # 1. Set `from_logits=FALSE`
#' loss_binary_crossentropy() # OR ...('from_logits=FALSE')
#' # 2. Update `y_pred` to use probabilities instead of logits
#' y_pred <- c(0.6, 0.3, 0.2, 0.8) # OR [[0.6, 0.3], [0.2, 0.8]]
#' ```
#'
#' @returns
#' Binary crossentropy loss value. shape = `[batch_size, d0, .. dN-1]`.
#'
#' @param from_logits
#' Whether to interpret `y_pred` as a tensor of
#' [logit](https://en.wikipedia.org/wiki/Logit) values. By default, we
#' assume that `y_pred` is probabilities (i.e., values in `[0, 1)).`
#'
#' @param label_smoothing
#' Float in range `[0, 1].` When 0, no smoothing occurs.
#' When > 0, we compute the loss between the predicted labels
#' and a smoothed version of the true labels, where the smoothing
#' squeezes the labels towards 0.5. Larger values of
#' `label_smoothing` correspond to heavier smoothing.
#'
#' @param axis
#' The axis along which to compute crossentropy (the features axis).
#' Defaults to `-1`.
#'
#' @param reduction
#' Type of reduction to apply to the loss. In almost all cases
#' this should be `"sum_over_batch_size"`.
#' Supported options are `"sum"`, `"sum_over_batch_size"` or `NULL`.
#'
#' @param name
#' Optional name for the loss instance.
#'
#' @param y_true
#' Ground truth values. shape = `[batch_size, d0, .. dN]`.
#'
#' @param y_pred
#' The predicted values. shape = `[batch_size, d0, .. dN]`.
#'
#' @param ...
#' For forward/backward compatability.
#'
#' @export
#' @family losses
#' @seealso
#' + <https://keras.io/api/losses/probabilistic_losses#binarycrossentropy-class>
# + <https://www.tensorflow.org/api_docs/python/tf/keras/losses/BinaryCrossentropy>
#'
#' @tether keras.losses.BinaryCrossentropy
loss_binary_crossentropy <-
function (y_true, y_pred, from_logits = FALSE, label_smoothing = 0,
axis = -1L, ..., reduction = "sum_over_batch_size", name = "binary_crossentropy")
{
args <- capture_args(list(axis = as_axis, y_true = function (x)
if (is_py_object(x))
x
else np_array(x), y_pred = function (x)
if (is_py_object(x))
x
else np_array(x)))
callable <- if (missing(y_true) && missing(y_pred))
keras$losses$BinaryCrossentropy
else keras$losses$binary_crossentropy
do.call(callable, args)
}
#' Computes focal cross-entropy loss between true labels and predictions.
#'
#' @description
#' According to [Lin et al., 2018](https://arxiv.org/pdf/1708.02002.pdf), it
#' helps to apply a focal factor to down-weight easy examples and focus more on
#' hard examples. By default, the focal tensor is computed as follows:
#'
#' `focal_factor = (1 - output)^gamma` for class 1
#' `focal_factor = output^gamma` for class 0
#' where `gamma` is a focusing parameter. When `gamma` = 0, there is no focal
#' effect on the binary crossentropy loss.
#'
#' If `apply_class_balancing == TRUE`, this function also takes into account a
#' weight balancing factor for the binary classes 0 and 1 as follows:
#'
#' `weight = alpha` for class 1 (`target == 1`)
#' `weight = 1 - alpha` for class 0
#' where `alpha` is a float in the range of `[0, 1]`.
#'
#' Binary cross-entropy loss is often used for binary (0 or 1) classification
#' tasks. The loss function requires the following inputs:
#'
#' - `y_true` (true label): This is either 0 or 1.
#' - `y_pred` (predicted value): This is the model's prediction, i.e, a single
#' floating-point value which either represents a
#' [logit](https://en.wikipedia.org/wiki/Logit), (i.e, value in `[-inf, inf]`
#' when `from_logits=TRUE`) or a probability (i.e, value in `[0., 1.]` when
#' `from_logits=FALSE`).
#'
#' According to [Lin et al., 2018](https://arxiv.org/pdf/1708.02002.pdf), it
#' helps to apply a "focal factor" to down-weight easy examples and focus more
#' on hard examples. By default, the focal tensor is computed as follows:
#'
#' `focal_factor = (1 - output) ** gamma` for class 1
#' `focal_factor = output ** gamma` for class 0
#' where `gamma` is a focusing parameter. When `gamma=0`, this function is
#' equivalent to the binary crossentropy loss.
#'
#' # Examples
#' ```{r}
#' y_true <- rbind(c(0, 1), c(0, 0))
#' y_pred <- rbind(c(0.6, 0.4), c(0.4, 0.6))
#' loss <- loss_binary_focal_crossentropy(y_true, y_pred, gamma = 2)
#' loss
#' ```
#' With the `compile()` API:
#'
#' ```{r, eval = FALSE}
#' model %>% compile(
#' loss = loss_binary_focal_crossentropy(
#' gamma = 2.0, from_logits = TRUE),
#' ...
#' )
#' ```
#'
#' As a standalone function:
#'
#' ```{r}
#' # Example 1: (batch_size = 1, number of samples = 4)
#' y_true <- op_array(c(0, 1, 0, 0))
#' y_pred <- op_array(c(-18.6, 0.51, 2.94, -12.8))
#' loss <- loss_binary_focal_crossentropy(gamma = 2, from_logits = TRUE)
#' loss(y_true, y_pred)
#' ```
#'
#' ```{r}
#' # Apply class weight
#' loss <- loss_binary_focal_crossentropy(
#' apply_class_balancing = TRUE, gamma = 2, from_logits = TRUE)
#' loss(y_true, y_pred)
#' ```
#'
#' ```{r}
#' # Example 2: (batch_size = 2, number of samples = 4)
#' y_true <- rbind(c(0, 1), c(0, 0))
#' y_pred <- rbind(c(-18.6, 0.51), c(2.94, -12.8))
#' # Using default 'auto'/'sum_over_batch_size' reduction type.
#' loss <- loss_binary_focal_crossentropy(
#' gamma = 3, from_logits = TRUE)
#' loss(y_true, y_pred)
#' ```
#'
#' ```{r}
#' # Apply class weight
#' loss <- loss_binary_focal_crossentropy(
#' apply_class_balancing = TRUE, gamma = 3, from_logits = TRUE)
#' loss(y_true, y_pred)
#' ```
#'
#' ```{r}
#' # Using 'sample_weight' attribute with focal effect
#' loss <- loss_binary_focal_crossentropy(
#' gamma = 3, from_logits = TRUE)
#' loss(y_true, y_pred, sample_weight = c(0.8, 0.2))
#' ```
#'
#' ```{r}
#' # Apply class weight
#' loss <- loss_binary_focal_crossentropy(
#' apply_class_balancing = TRUE, gamma = 3, from_logits = TRUE)
#' loss(y_true, y_pred, sample_weight = c(0.8, 0.2))
#' ```
#'
#' ```{r}
#' # Using 'sum' reduction` type.
#' loss <- loss_binary_focal_crossentropy(
#' gamma = 4, from_logits = TRUE,
#' reduction = "sum")
#' loss(y_true, y_pred)
#' ```
#'
#' ```{r}
#' # Apply class weight
#' loss <- loss_binary_focal_crossentropy(
#' apply_class_balancing = TRUE, gamma = 4, from_logits = TRUE,
#' reduction = "sum")
#' loss(y_true, y_pred)
#' ```
#'
#' ```{r}
#' # Using 'none' reduction type.
#' loss <- loss_binary_focal_crossentropy(
#' gamma = 5, from_logits = TRUE,
#' reduction = NULL)
#' loss(y_true, y_pred)
#' ```
#'
#' ```{r}
#' # Apply class weight
#' loss <- loss_binary_focal_crossentropy(
#' apply_class_balancing = TRUE, gamma = 5, from_logits = TRUE,
#' reduction = NULL)
#' loss(y_true, y_pred)
#' ```
#'
#' @returns
#' Binary focal crossentropy loss value
#' with shape = `[batch_size, d0, .. dN-1]`.
#'
#' @param apply_class_balancing
#' A bool, whether to apply weight balancing on the
#' binary classes 0 and 1.
#'
#' @param alpha
#' A weight balancing factor for class 1, default is `0.25` as
#' mentioned in reference [Lin et al., 2018](
#' https://arxiv.org/pdf/1708.02002.pdf). The weight for class 0 is
#' `1.0 - alpha`.
#'
#' @param gamma
#' A focusing parameter used to compute the focal factor, default is
#' `2.0` as mentioned in the reference
#' [Lin et al., 2018](https://arxiv.org/pdf/1708.02002.pdf).
#'
#' @param from_logits
#' Whether to interpret `y_pred` as a tensor of
#' [logit](https://en.wikipedia.org/wiki/Logit) values. By default, we
#' assume that `y_pred` are probabilities (i.e., values in `[0, 1]`).
#'
#' @param label_smoothing
#' Float in `[0, 1]`. When `0`, no smoothing occurs.
#' When > `0`, we compute the loss between the predicted labels
#' and a smoothed version of the true labels, where the smoothing
#' squeezes the labels towards `0.5`.
#' Larger values of `label_smoothing` correspond to heavier smoothing.
#'
#' @param axis
#' The axis along which to compute crossentropy (the features axis).
#' Defaults to `-1`.
#'
#' @param reduction
#' Type of reduction to apply to the loss. In almost all cases
#' this should be `"sum_over_batch_size"`.
#' Supported options are `"sum"`, `"sum_over_batch_size"` or `NULL`.
#'
#' @param name
#' Optional name for the loss instance.
#'
#' @param y_true
#' Ground truth values, of shape `(batch_size, d0, .. dN)`.
#'
#' @param y_pred
#' The predicted values, of shape `(batch_size, d0, .. dN)`.
#'
#' @param ...
#' For forward/backward compatability.
#'
#' @export
#' @family losses
# @seealso
# + <https://www.tensorflow.org/api_docs/python/tf/keras/losses/BinaryFocalCrossentropy>
#'
#' @tether keras.losses.BinaryFocalCrossentropy
loss_binary_focal_crossentropy <-
function (y_true, y_pred, apply_class_balancing = FALSE,
alpha = 0.25, gamma = 2, from_logits = FALSE, label_smoothing = 0,
axis = -1L, ..., reduction = "sum_over_batch_size", name = "binary_focal_crossentropy")
{
args <- capture_args(list(axis = as_axis, y_true = function (x)
if (is_py_object(x))
x
else np_array(x), y_pred = function (x)
if (is_py_object(x))
x
else np_array(x)))
callable <- if (missing(y_true) && missing(y_pred))
keras$losses$BinaryFocalCrossentropy
else keras$losses$binary_focal_crossentropy
do.call(callable, args)
}
#' Computes the crossentropy loss between the labels and predictions.
#'
#' @description
#' Use this crossentropy loss function when there are two or more label
#' classes. We expect labels to be provided in a `one_hot` representation. If
#' you want to provide labels as integers, please use
#' `SparseCategoricalCrossentropy` loss. There should be `num_classes` floating
#' point values per feature, i.e., the shape of both `y_pred` and `y_true` are
#' `[batch_size, num_classes]`.
#'
#' # Examples
#' ```{r}
#' y_true <- rbind(c(0, 1, 0), c(0, 0, 1))
#' y_pred <- rbind(c(0.05, 0.95, 0), c(0.1, 0.8, 0.1))
#' loss <- loss_categorical_crossentropy(y_true, y_pred)
#' loss
#' ```
#' Standalone usage:
#'
#' ```{r}
#' y_true <- rbind(c(0, 1, 0), c(0, 0, 1))
#' y_pred <- rbind(c(0.05, 0.95, 0), c(0.1, 0.8, 0.1))
#' # Using 'auto'/'sum_over_batch_size' reduction type.
#' cce <- loss_categorical_crossentropy()
#' cce(y_true, y_pred)
#' ```
#'
#' ```{r}
#' # Calling with 'sample_weight'.
#' cce(y_true, y_pred, sample_weight = op_array(c(0.3, 0.7)))
#' ```
#'
#' ```{r}
#' # Using 'sum' reduction type.
#' cce <- loss_categorical_crossentropy(reduction = "sum")
#' cce(y_true, y_pred)
#' ```
#'
#' ```{r}
#' # Using 'none' reduction type.
#' cce <- loss_categorical_crossentropy(reduction = NULL)
#' cce(y_true, y_pred)
#' ```
#'
#' Usage with the `compile()` API:
#'
#' ```{r, eval = FALSE}
#' model %>% compile(optimizer = 'sgd',
#' loss=loss_categorical_crossentropy())
#' ```
#'
#' @returns
#' Categorical crossentropy loss value.
#'
#' @param from_logits
#' Whether `y_pred` is expected to be a logits tensor. By
#' default, we assume that `y_pred` encodes a probability distribution.
#'
#' @param label_smoothing
#' Float in `[0, 1].` When > 0, label values are smoothed,
#' meaning the confidence on label values are relaxed. For example, if
#' `0.1`, use `0.1 / num_classes` for non-target labels and
#' `0.9 + 0.1 / num_classes` for target labels.
#'
#' @param axis
#' The axis along which to compute crossentropy (the features
#' axis). Defaults to `-1`.
#'
#' @param reduction
#' Type of reduction to apply to the loss. In almost all cases
#' this should be `"sum_over_batch_size"`.
#' Supported options are `"sum"`, `"sum_over_batch_size"` or `NULL`.
#'
#' @param name
#' Optional name for the loss instance.
#'
#' @param y_true
#' Tensor of one-hot true targets.
#'
#' @param y_pred
#' Tensor of predicted targets.
#'
#' @param ...
#' For forward/backward compatability.
#'
#' @export
#' @family losses
#' @seealso
#' + <https://keras.io/api/losses/probabilistic_losses#categoricalcrossentropy-class>
# + <https://www.tensorflow.org/api_docs/python/tf/keras/losses/CategoricalCrossentropy>
#'
#' @tether keras.losses.CategoricalCrossentropy
loss_categorical_crossentropy <-
function (y_true, y_pred, from_logits = FALSE, label_smoothing = 0,
axis = -1L, ..., reduction = "sum_over_batch_size", name = "categorical_crossentropy")
{
args <- capture_args(list(axis = as_axis, y_true = function (x)
if (is_py_object(x))
x
else np_array(x), y_pred = function (x)
if (is_py_object(x))
x
else np_array(x)))
callable <- if (missing(y_true) && missing(y_pred))
keras$losses$CategoricalCrossentropy
else keras$losses$categorical_crossentropy
do.call(callable, args)
}
#' Computes the alpha balanced focal crossentropy loss.
#'
#' @description
#' Use this crossentropy loss function when there are two or more label
#' classes and if you want to handle class imbalance without using
#' `class_weights`. We expect labels to be provided in a `one_hot`
#' representation.
#'
#' According to [Lin et al., 2018](https://arxiv.org/pdf/1708.02002.pdf), it
#' helps to apply a focal factor to down-weight easy examples and focus more on
#' hard examples. The general formula for the focal loss (FL)
#' is as follows:
#'
#' `FL(p_t) = (1 - p_t)^gamma * log(p_t)`
#'
#' where `p_t` is defined as follows:
#' `p_t = output if y_true == 1, else 1 - output`
#'
#' `(1 - p_t)^gamma` is the `modulating_factor`, where `gamma` is a focusing
#' parameter. When `gamma` = 0, there is no focal effect on the cross entropy.
#' `gamma` reduces the importance given to simple examples in a smooth manner.
#'
#' The authors use alpha-balanced variant of focal loss (FL) in the paper:
#' `FL(p_t) = -alpha * (1 - p_t)^gamma * log(p_t)`
#'
#' where `alpha` is the weight factor for the classes. If `alpha` = 1, the
#' loss won't be able to handle class imbalance properly as all
#' classes will have the same weight. This can be a constant or a list of
#' constants. If alpha is a list, it must have the same length as the number
#' of classes.
#'
#' The formula above can be generalized to:
#' `FL(p_t) = alpha * (1 - p_t)^gamma * CrossEntropy(y_true, y_pred)`
#'
#' where minus comes from `CrossEntropy(y_true, y_pred)` (CE).
#'
#' Extending this to multi-class case is straightforward:
#' `FL(p_t) = alpha * (1 - p_t) ** gamma * CategoricalCE(y_true, y_pred)`
#'
#' In the snippet below, there is `num_classes` floating pointing values per
#' example. The shape of both `y_pred` and `y_true` are
#' `(batch_size, num_classes)`.
#'
#' # Examples
#' ```{r}
#' y_true <- rbind(c(0, 1, 0), c(0, 0, 1))
#' y_pred <- rbind(c(0.05, 0.95, 0), c(0.1, 0.8, 0.1))
#' loss <- loss_categorical_focal_crossentropy(y_true, y_pred)
#' loss
#' ```
#' Standalone usage:
#'
#' ```{r}
#' y_true <- rbind(c(0, 1, 0), c(0, 0, 1))
#' y_pred <- rbind(c(0.05, 0.95, 0), c(0.1, 0.8, 0.1))
#' # Using 'auto'/'sum_over_batch_size' reduction type.
#' cce <- loss_categorical_focal_crossentropy()
#' cce(y_true, y_pred)
#' ```
#'
#' ```{r}
#' # Calling with 'sample_weight'.
#' cce(y_true, y_pred, sample_weight = op_array(c(0.3, 0.7)))
#' ```
#'
#' ```{r}
#' # Using 'sum' reduction type.
#' cce <- loss_categorical_focal_crossentropy(reduction = "sum")
#' cce(y_true, y_pred)
#' ```
#'
#' ```{r}
#' # Using 'none' reduction type.
#' cce <- loss_categorical_focal_crossentropy(reduction = NULL)
#' cce(y_true, y_pred)
#' ```
#'
#' Usage with the `compile()` API:
#'
#' ```{r, eval = FALSE}
#' model %>% compile(
#' optimizer = 'adam',
#' loss = loss_categorical_focal_crossentropy())
#' ```
#'
#' @returns
#' Categorical focal crossentropy loss value.
#'
#' @param alpha
#' A weight balancing factor for all classes, default is `0.25` as
#' mentioned in the reference. It can be a list of floats or a scalar.
#' In the multi-class case, alpha may be set by inverse class
#' frequency by using `compute_class_weight` from `sklearn.utils`.
#'
#' @param gamma
#' A focusing parameter, default is `2.0` as mentioned in the
#' reference. It helps to gradually reduce the importance given to
#' simple examples in a smooth manner. When `gamma` = 0, there is
#' no focal effect on the categorical crossentropy.
#'
#' @param from_logits
#' Whether `output` is expected to be a logits tensor. By
#' default, we consider that `output` encodes a probability
#' distribution.
#'
#' @param label_smoothing
#' Float in `[0, 1].` When > 0, label values are smoothed,
#' meaning the confidence on label values are relaxed. For example, if
#' `0.1`, use `0.1 / num_classes` for non-target labels and
#' `0.9 + 0.1 / num_classes` for target labels.
#'
#' @param axis
#' The axis along which to compute crossentropy (the features
#' axis). Defaults to `-1`.
#'
#' @param reduction
#' Type of reduction to apply to the loss. In almost all cases
#' this should be `"sum_over_batch_size"`.
#' Supported options are `"sum"`, `"sum_over_batch_size"` or `NULL`.
#'
#' @param name
#' Optional name for the loss instance.
#'
#' @param y_true
#' Tensor of one-hot true targets.
#'
#' @param y_pred
#' Tensor of predicted targets.
#'
#' @param ...
#' For forward/backward compatability.
#'
#' @export
#' @family losses
# @seealso
# + <https://www.tensorflow.org/api_docs/python/tf/keras/losses/CategoricalFocalCrossentropy>
#'
#' @tether keras.losses.CategoricalFocalCrossentropy
loss_categorical_focal_crossentropy <-
function (y_true, y_pred, alpha = 0.25, gamma = 2,
from_logits = FALSE, label_smoothing = 0, axis = -1L, ...,
reduction = "sum_over_batch_size", name = "categorical_focal_crossentropy")
{
args <- capture_args(list(axis = as_axis, y_true = function (x)
if (is_py_object(x))
x
else np_array(x), y_pred = function (x)
if (is_py_object(x))
x
else np_array(x)))
callable <- if (missing(y_true) && missing(y_pred))
keras$losses$CategoricalFocalCrossentropy
else keras$losses$categorical_focal_crossentropy
do.call(callable, args)
}
#' Computes the categorical hinge loss between `y_true` & `y_pred`.
#'
#' @description
#' Formula:
#'
#' ```{r, eval = FALSE}
#' loss <- maximum(neg - pos + 1, 0)
#' ```
#'
#' where `neg=maximum((1-y_true)*y_pred)` and `pos=sum(y_true*y_pred)`
#'
#' # Examples
#' ```{r}
#' y_true <- rbind(c(0, 1), c(0, 0))
#' y_pred <- rbind(c(0.6, 0.4), c(0.4, 0.6))
#' loss <- loss_categorical_hinge(y_true, y_pred)
#' ```
#'
#' @returns
#' Categorical hinge loss values with shape = `[batch_size, d0, .. dN-1]`.
#'
#' @param reduction
#' Type of reduction to apply to the loss. In almost all cases
#' this should be `"sum_over_batch_size"`.
#' Supported options are `"sum"`, `"sum_over_batch_size"` or `NULL`.
#'
#' @param name
#' Optional name for the loss instance.
#'
#' @param y_true
#' The ground truth values. `y_true` values are expected to be
#' either `{-1, +1}` or `{0, 1}` (i.e. a one-hot-encoded tensor) with
#' shape <- `[batch_size, d0, .. dN]`.
#'
#' @param y_pred
#' The predicted values with shape = `[batch_size, d0, .. dN]`.
#'
#' @param ...
#' For forward/backward compatability.
#'
#' @export
#' @family losses
#' @seealso
#' + <https://keras.io/api/losses/hinge_losses#categoricalhinge-class>
# + <https://www.tensorflow.org/api_docs/python/tf/keras/losses/CategoricalHinge>
#'
#' @tether keras.losses.CategoricalHinge
loss_categorical_hinge <-
function (y_true, y_pred, ..., reduction = "sum_over_batch_size",
name = "categorical_hinge")
{
args <- capture_args(list(y_true = function (x)
if (is_py_object(x))
x
else np_array(x), y_pred = function (x)
if (is_py_object(x))
x
else np_array(x)))
callable <- if (missing(y_true) && missing(y_pred))
keras$losses$CategoricalHinge
else keras$losses$categorical_hinge
do.call(callable, args)
}
#' Computes the cosine similarity between `y_true` & `y_pred`.
#'
#' @description
#' Formula:
#' ```{r, eval = FALSE}
#' loss <- -sum(l2_norm(y_true) * l2_norm(y_pred))
#' ```
#'
#' Note that it is a number between -1 and 1. When it is a negative number
#' between -1 and 0, 0 indicates orthogonality and values closer to -1
#' indicate greater similarity. This makes it usable as a loss function in a
#' setting where you try to maximize the proximity between predictions and
#' targets. If either `y_true` or `y_pred` is a zero vector, cosine
#' similarity will be 0 regardless of the proximity between predictions
#' and targets.
#'
#' # Examples
#' ```{r}
#' y_true <- rbind(c(0., 1.), c(1., 1.), c(1., 1.))
#' y_pred <- rbind(c(1., 0.), c(1., 1.), c(-1., -1.))
#' loss <- loss_cosine_similarity(y_true, y_pred, axis=-1)
#' loss
#' ```
#'
#' @returns
#' Cosine similarity tensor.
#'
#' @param axis
#' The axis along which the cosine similarity is computed
#' (the features axis). Defaults to `-1`.
#'
#' @param reduction
#' Type of reduction to apply to the loss. In almost all cases
#' this should be `"sum_over_batch_size"`.
#' Supported options are `"sum"`, `"sum_over_batch_size"` or `NULL`.
#'
#' @param name
#' Optional name for the loss instance.
#'
#' @param y_true
#' Tensor of true targets.
#'
#' @param y_pred
#' Tensor of predicted targets.
#'
#' @param ...
#' For forward/backward compatability.
#'
#' @export
#' @family losses
#' @seealso
#' + <https://keras.io/api/losses/regression_losses#cosinesimilarity-class>
# + <https://www.tensorflow.org/api_docs/python/tf/keras/losses/CosineSimilarity>
#'
#' @tether keras.losses.CosineSimilarity
loss_cosine_similarity <-
function (y_true, y_pred, axis = -1L, ..., reduction = "sum_over_batch_size",
name = "cosine_similarity")
{
args <- capture_args(list(axis = as_axis, y_true = function (x)
if (is_py_object(x))
x
else np_array(x), y_pred = function (x)
if (is_py_object(x))
x
else np_array(x)))
callable <- if (missing(y_true) && missing(y_pred))
keras$losses$CosineSimilarity
else keras$losses$cosine_similarity
do.call(callable, args)
}
#' Computes the Dice loss value between `y_true` and `y_pred`.
#'
#' @description
#' Formula:
#' ```python
#' loss = 1 - (2 * sum(y_true * y_pred)) / (sum(y_true) + sum(y_pred))
#' ```
#'
#' Formula:
#' ```python
#' loss = 1 - (2 * sum(y_true * y_pred)) / (sum(y_true) + sum(y_pred))
#' ```
#'
#' @returns
#' if `y_true` and `y_pred` are provided, Dice loss value. Otherwise,
#' a `Loss()` instance.
#'
#' @param y_true
#' tensor of true targets.
#'
#' @param y_pred
#' tensor of predicted targets.
#'
#' @param reduction
#' Type of reduction to apply to the loss. In almost all cases
#' this should be `"sum_over_batch_size"`.
#' Supported options are `"sum"`, `"sum_over_batch_size"` or `NULL`.
#'
#' @param name
#' String, name for the object
#'
#' @param ...
#' For forward/backward compatability.
#'
#' @export
#' @family losses
#' @tether keras.losses.Dice
loss_dice <-
function (y_true, y_pred, ..., reduction = "sum_over_batch_size", name = "dice")
{
args <- capture_args(list(y_true = as_py_array, y_pred = as_py_array))
callable <- if (missing(y_true) && missing(y_pred))
keras$losses$Dice
else keras$losses$dice
do.call(callable, args)
}
#' Computes the hinge loss between `y_true` & `y_pred`.
#'
#' @description
#' Formula:
#'
#' ```{r, eval = FALSE}
#' loss <- mean(maximum(1 - y_true * y_pred, 0), axis=-1)
#' ```
#'
#' `y_true` values are expected to be -1 or 1. If binary (0 or 1) labels are
#' provided we will convert them to -1 or 1.
#'
#' # Examples
#' ```{r}
#' y_true <- array(sample(c(-1,1), 6, replace = TRUE), dim = c(2, 3))
#' y_pred <- random_uniform(c(2, 3))
#' loss <- loss_hinge(y_true, y_pred)
#' loss
#' ```
#'
#' @returns
#' Hinge loss values with shape = `[batch_size, d0, .. dN-1]`.
#'
#' @param reduction
#' Type of reduction to apply to the loss. In almost all cases
#' this should be `"sum_over_batch_size"`.
#' Supported options are `"sum"`, `"sum_over_batch_size"` or `NULL`.
#'
#' @param name
#' Optional name for the loss instance.
#'
#' @param y_true
#' The ground truth values. `y_true` values are expected to be -1
#' or 1. If binary (0 or 1) labels are provided they will be converted
#' to -1 or 1 with shape = `[batch_size, d0, .. dN]`.
#'
#' @param y_pred
#' The predicted values with shape = `[batch_size, d0, .. dN]`.
#'
#' @param ...
#' For forward/backward compatability.
#'
#' @export
#' @family losses
#' @seealso
#' + <https://keras.io/api/losses/hinge_losses#hinge-class>
# + <https://www.tensorflow.org/api_docs/python/tf/keras/losses/Hinge>
#'
#' @tether keras.losses.Hinge
loss_hinge <-
function (y_true, y_pred, ..., reduction = "sum_over_batch_size",
name = "hinge")
{
args <- capture_args(list(y_true = function (x)
if (is_py_object(x))
x
else np_array(x), y_pred = function (x)
if (is_py_object(x))
x
else np_array(x)))
callable <- if (missing(y_true) && missing(y_pred))
keras$losses$Hinge
else keras$losses$hinge
do.call(callable, args)
}
#' Computes the Huber loss between `y_true` & `y_pred`.
#'
#' @description
#' Formula:
#' ```{r, eval = FALSE}
#' for (x in error) {
#' if (abs(x) <= delta){
#' loss <- c(loss, (0.5 * x^2))
#' } else if (abs(x) > delta) {
#' loss <- c(loss, (delta * abs(x) - 0.5 * delta^2))
#' }
#' }
#' loss <- mean(loss)
#' ```
#' See: [Huber loss](https://en.wikipedia.org/wiki/Huber_loss).
#'
#' # Examples
#' ```{r}
#' y_true <- rbind(c(0, 1), c(0, 0))
#' y_pred <- rbind(c(0.6, 0.4), c(0.4, 0.6))
#' loss <- loss_huber(y_true, y_pred)
#' ```
#'
#' @returns
#' Tensor with one scalar loss entry per sample.
#'
#' @param delta
#' A float, the point where the Huber loss function changes from a
#' quadratic to linear. Defaults to `1.0`.
#'
#' @param reduction
#' Type of reduction to apply to loss. Options are `"sum"`,
#' `"sum_over_batch_size"` or `NULL`. Defaults to
#' `"sum_over_batch_size"`.
#'
#' @param name
#' Optional name for the instance.
#'
#' @param y_true
#' tensor of true targets.
#'
#' @param y_pred
#' tensor of predicted targets.
#'
#' @param ...
#' For forward/backward compatability.
#'
#' @export
#' @family losses
#' @seealso
#' + <https://keras.io/api/losses/regression_losses#huber-class>
# + <https://www.tensorflow.org/api_docs/python/tf/keras/losses/Huber>
#'
#' @tether keras.losses.Huber
loss_huber <-
function (y_true, y_pred, delta = 1, ..., reduction = "sum_over_batch_size",
name = "huber_loss")
{
args <- capture_args(list(y_true = function (x)
if (is_py_object(x))
x
else np_array(x), y_pred = function (x)
if (is_py_object(x))
x
else np_array(x)))
callable <- if (missing(y_true) && missing(y_pred))
keras$losses$Huber
else keras$losses$huber
do.call(callable, args)
}
#' Computes Kullback-Leibler divergence loss between `y_true` & `y_pred`.
#'
#' @description
#' Formula:
#'
#' ```{r, eval=FALSE}
#' loss <- y_true * log(y_true / y_pred)
#' ```
#'
#' `y_true` and `y_pred` are expected to be probability
#' distributions, with values between 0 and 1. They will get
#' clipped to the `[0, 1]` range.
#'
#' # Examples
#' ```{r}
#' y_true <- random_uniform(c(2, 3), 0, 2)
#' y_pred <- random_uniform(c(2,3))
#' loss <- loss_kl_divergence(y_true, y_pred)
#' loss
#' ```
#'
#' @returns
#' KL Divergence loss values with shape = `[batch_size, d0, .. dN-1]`.
#'
#' @param reduction
#' Type of reduction to apply to the loss. In almost all cases
#' this should be `"sum_over_batch_size"`.
#' Supported options are `"sum"`, `"sum_over_batch_size"` or `NULL`.
#'
#' @param name
#' Optional name for the loss instance.
#'
#' @param y_true
#' Tensor of true targets.
#'
#' @param y_pred
#' Tensor of predicted targets.
#'
#' @param ...
#' For forward/backward compatability.
#'
#' @export
#' @family losses
#' @seealso
#' + <https://keras.io/api/losses/probabilistic_losses#kldivergence-class>
# + <https://www.tensorflow.org/api_docs/python/tf/keras/losses/KLDivergence>
#'
#' @tether keras.losses.KLDivergence
loss_kl_divergence <-
function (y_true, y_pred, ..., reduction = "sum_over_batch_size",
name = "kl_divergence")
{
args <- capture_args(list(y_true = function (x)
if (is_py_object(x))
x
else np_array(x), y_pred = function (x)
if (is_py_object(x))
x
else np_array(x)))
callable <- if (missing(y_true) && missing(y_pred))
keras$losses$KLDivergence
else keras$losses$kl_divergence
do.call(callable, args)