/
losses.py
1634 lines (1323 loc) · 52.7 KB
/
losses.py
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
# Copyright 2023 The TensorFlow Ranking Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Keras losses in TF-Ranking."""
from typing import Any, Dict, List, Optional
import tensorflow.compat.v2 as tf
from tensorflow_ranking.python import losses_impl
from tensorflow_ranking.python.keras import utils
class RankingLossKey(object):
"""Ranking loss key strings."""
# Names for the ranking based loss functions.
PAIRWISE_HINGE_LOSS = 'pairwise_hinge_loss'
PAIRWISE_LOGISTIC_LOSS = 'pairwise_logistic_loss'
PAIRWISE_SOFT_ZERO_ONE_LOSS = 'pairwise_soft_zero_one_loss'
PAIRWISE_MSE_LOSS = 'pairwise_mse_loss'
YETI_LOGISTIC_LOSS = 'yeti_logistic_loss'
SOFTMAX_LOSS = 'softmax_loss'
UNIQUE_SOFTMAX_LOSS = 'unique_softmax_loss'
SIGMOID_CROSS_ENTROPY_LOSS = 'sigmoid_cross_entropy_loss'
MEAN_SQUARED_LOSS = 'mean_squared_loss'
ORDINAL_LOSS = 'ordinal_loss'
LIST_MLE_LOSS = 'list_mle_loss'
APPROX_NDCG_LOSS = 'approx_ndcg_loss'
APPROX_MRR_LOSS = 'approx_mrr_loss'
GUMBEL_APPROX_NDCG_LOSS = 'gumbel_approx_ndcg_loss'
COUPLED_RANKDISTIL_LOSS = 'coupled_rankdistil_loss'
# TODO: Add support for circle loss and neural sort losses.
@classmethod
def all_keys(cls) -> List[str]:
return [v for k, v in vars(cls).items() if k.isupper()]
def get(loss: str,
reduction: tf.losses.Reduction = tf.losses.Reduction.AUTO,
lambda_weight: Optional[losses_impl._LambdaWeight] = None,
name: Optional[str] = None,
**kwargs) -> tf.keras.losses.Loss:
"""Factory method to get a ranking loss class.
Args:
loss: (str) An attribute of `RankingLossKey`, defining which loss object to
return.
reduction: (enum) An enum of strings indicating the loss reduction type.
See type definition in the `tf.compat.v2.losses.Reduction`.
lambda_weight: (losses_impl._LambdaWeight) A lambda object for ranking
metric optimization.
name: (optional) (str) Name of loss.
**kwargs: Keyword arguments for the loss object.
Returns:
A ranking loss instance. See `_RankingLoss` signature for more details.
Raises:
ValueError: If loss_key is unsupported.
"""
loss_kwargs = {'reduction': reduction, 'name': name}
if kwargs:
loss_kwargs.update(kwargs)
loss_kwargs_with_lambda_weights = {'lambda_weight': lambda_weight}
loss_kwargs_with_lambda_weights.update(loss_kwargs)
key_to_cls = {
RankingLossKey.SIGMOID_CROSS_ENTROPY_LOSS: SigmoidCrossEntropyLoss,
RankingLossKey.MEAN_SQUARED_LOSS: MeanSquaredLoss,
RankingLossKey.ORDINAL_LOSS: OrdinalLoss,
RankingLossKey.APPROX_NDCG_LOSS: ApproxNDCGLoss,
RankingLossKey.APPROX_MRR_LOSS: ApproxMRRLoss,
RankingLossKey.GUMBEL_APPROX_NDCG_LOSS: GumbelApproxNDCGLoss,
RankingLossKey.COUPLED_RANKDISTIL_LOSS: CoupledRankDistilLoss,
}
key_to_cls_with_lambda_weights = {
RankingLossKey.LIST_MLE_LOSS: ListMLELoss,
RankingLossKey.PAIRWISE_HINGE_LOSS: PairwiseHingeLoss,
RankingLossKey.PAIRWISE_LOGISTIC_LOSS: PairwiseLogisticLoss,
RankingLossKey.PAIRWISE_SOFT_ZERO_ONE_LOSS: PairwiseSoftZeroOneLoss,
RankingLossKey.PAIRWISE_MSE_LOSS: PairwiseMSELoss,
RankingLossKey.YETI_LOGISTIC_LOSS: YetiLogisticLoss,
RankingLossKey.SOFTMAX_LOSS: SoftmaxLoss,
RankingLossKey.UNIQUE_SOFTMAX_LOSS: UniqueSoftmaxLoss,
}
if loss in key_to_cls:
loss_cls = key_to_cls[loss]
loss_obj = loss_cls(**loss_kwargs)
elif loss in key_to_cls_with_lambda_weights:
loss_cls = key_to_cls_with_lambda_weights[loss]
loss_obj = loss_cls(**loss_kwargs_with_lambda_weights)
else:
raise ValueError('unsupported loss: {}'.format(loss))
return loss_obj
@tf.keras.utils.register_keras_serializable(package='tensorflow_ranking')
class LabelDiffLambdaWeight(losses_impl.LabelDiffLambdaWeight):
"""Keras serializable class for LabelDiffLambdaWeight."""
def __init__(self, **kwargs):
super().__init__()
def get_config(self) -> Dict[str, Any]:
return {}
@tf.keras.utils.register_keras_serializable(package='tensorflow_ranking')
class DCGLambdaWeight(losses_impl.DCGLambdaWeight):
"""Keras serializable class for DCG."""
def __init__(self,
topn: Optional[int] = None,
gain_fn: Optional[utils.GainFunction] = None,
rank_discount_fn: Optional[utils.RankDiscountFunction] = None,
normalized: bool = False,
smooth_fraction: float = 0.,
**kwargs):
gain_fn = gain_fn or utils.identity
rank_discount_fn = rank_discount_fn or utils.inverse
super().__init__(topn, gain_fn, rank_discount_fn, normalized,
smooth_fraction)
def get_config(self) -> Dict[str, Any]:
return {
'topn': self._topn,
'gain_fn': self._gain_fn,
'rank_discount_fn': self._rank_discount_fn,
'normalized': self._normalized,
'smooth_fraction': self._smooth_fraction,
}
@tf.keras.utils.register_keras_serializable(package='tensorflow_ranking')
class NDCGLambdaWeightV2(losses_impl.DCGLambdaWeightV2):
"""Keras serializable class for NDCG LambdaWeight V2 for topn."""
def __init__(self,
topn: Optional[int] = None,
gain_fn: Optional[utils.GainFunction] = None,
rank_discount_fn: Optional[utils.RankDiscountFunction] = None,
**kwargs):
gain_fn = gain_fn or utils.pow_minus_1
rank_discount_fn = rank_discount_fn or utils.log2_inverse
super().__init__(topn, gain_fn, rank_discount_fn, normalized=True)
def get_config(self) -> Dict[str, Any]:
return {
'topn': self._topn,
'gain_fn': self._gain_fn,
'rank_discount_fn': self._rank_discount_fn,
}
@tf.keras.utils.register_keras_serializable(package='tensorflow_ranking')
class YetiDCGLambdaWeight(losses_impl.YetiDCGLambdaWeight):
"""Keras serializable class for YetiDCGLambdaWeight."""
def __init__(
self,
topn: Optional[int] = None,
gain_fn: Optional[utils.GainFunction] = None,
rank_discount_fn: Optional[utils.RankDiscountFunction] = None,
normalized: bool = False,
**kwargs
):
gain_fn = gain_fn or utils.pow_minus_1
rank_discount_fn = rank_discount_fn or utils.log2_inverse
super().__init__(topn, gain_fn, rank_discount_fn, normalized=normalized)
def get_config(self) -> Dict[str, Any]:
return {
'topn': self._topn,
'gain_fn': self._gain_fn,
'rank_discount_fn': self._rank_discount_fn,
'normalized': self._normalized,
}
@tf.keras.utils.register_keras_serializable(package='tensorflow_ranking')
class NDCGLambdaWeight(DCGLambdaWeight):
"""Keras serializable class for NDCG."""
def __init__(self,
topn: Optional[int] = None,
gain_fn: Optional[utils.GainFunction] = None,
rank_discount_fn: Optional[utils.RankDiscountFunction] = None,
smooth_fraction: float = 0.,
**kwargs):
super().__init__(
topn,
gain_fn or utils.pow_minus_1,
rank_discount_fn or utils.log2_inverse,
normalized=True,
smooth_fraction=smooth_fraction)
@tf.keras.utils.register_keras_serializable(package='tensorflow_ranking')
class PrecisionLambdaWeight(losses_impl.PrecisionLambdaWeight):
"""Keras serializable class for Precision."""
def __init__(self,
topn: Optional[int] = None,
positive_fn: Optional[utils.PositiveFunction] = None,
**kwargs):
positive_fn = positive_fn or utils.is_greater_equal_1
super().__init__(topn, positive_fn)
def get_config(self) -> Dict[str, Any]:
return {
'topn': self._topn,
'positive_fn': self._positive_fn,
}
@tf.keras.utils.register_keras_serializable(package='tensorflow_ranking')
class ListMLELambdaWeight(losses_impl.ListMLELambdaWeight):
def __init__(self,
rank_discount_fn: Optional[utils.RankDiscountFunction] = None,
**kwargs):
super().__init__(rank_discount_fn)
def get_config(self) -> Dict[str, Any]:
return {
'rank_discount_fn': self._rank_discount_fn,
}
class _RankingLoss(tf.keras.losses.Loss):
"""Base class for all ranking losses.
Please see tf.keras.losses.Loss for more information about such a class and
https://www.tensorflow.org/tutorials/distribute/custom_training on how to do
customized training.
"""
def __init__(self,
reduction: tf.losses.Reduction = tf.losses.Reduction.AUTO,
name: Optional[str] = None,
ragged: bool = False):
super().__init__(reduction, name)
# An instance of loss in `losses_impl`. Overwrite this in subclasses.
self._loss = None
self._ragged = ragged
def __call__(self,
y_true: utils.TensorLike,
y_pred: utils.TensorLike,
sample_weight: Optional[utils.TensorLike] = None) -> tf.Tensor:
"""See tf.keras.losses.Loss."""
if self._loss is None:
raise ValueError('self._loss is not defined. Please use a subclass.')
sample_weight = self._loss.normalize_weights(y_true, sample_weight)
return super().__call__(y_true, y_pred, sample_weight)
def call(self, y_true: utils.TensorLike,
y_pred: utils.TensorLike) -> tf.Tensor:
"""See tf.keras.losses.Loss."""
y_pred = self._loss.get_logits(y_pred)
losses, weights = self._loss.compute_unreduced_loss(
labels=y_true, logits=y_pred)
return tf.multiply(losses, weights)
def get_config(self) -> Dict[str, Any]:
config = super().get_config()
config.update({'ragged': self._ragged})
return config
class _PairwiseLoss(_RankingLoss):
"""Base class for pairwise ranking losses."""
def __init__(self,
reduction: tf.losses.Reduction = tf.losses.Reduction.AUTO,
name: Optional[str] = None,
lambda_weight: Optional[losses_impl._LambdaWeight] = None,
temperature: float = 1.0,
ragged: bool = False,
**kwargs):
super().__init__(reduction, name, ragged)
self._lambda_weight = lambda_weight
self._temperature = temperature
def get_config(self) -> Dict[str, Any]:
config = super().get_config()
config.update({
'lambda_weight': utils.serialize_keras_object(
self._lambda_weight
),
'temperature': self._temperature,
})
return config
@classmethod
def from_config(cls, config, custom_objects=None):
config = config.copy()
config.update(
{
'lambda_weight': utils.deserialize_keras_object(
config['lambda_weight']
),
}
)
return cls(**config)
def call(self, y_true: utils.TensorLike,
y_pred: utils.TensorLike) -> tf.Tensor:
"""See _RankingLoss."""
losses, weights = self._loss.compute_unreduced_loss(
labels=y_true, logits=y_pred)
losses = tf.multiply(losses, weights)
# [batch_size, list_size, list_size]
losses.get_shape().assert_has_rank(3)
# Reduce the loss along the last dim so that weights ([batch_size, 1] or
# [batch_size, list_size] can be applied in __call__.
return tf.reduce_sum(losses, axis=2)
@tf.keras.utils.register_keras_serializable(package='tensorflow_ranking')
class PairwiseHingeLoss(_PairwiseLoss):
r"""Computes pairwise hinge loss between `y_true` and `y_pred`.
For each list of scores `s` in `y_pred` and list of labels `y` in `y_true`:
```
loss = sum_i sum_j I[y_i > y_j] * max(0, 1 - (s_i - s_j))
```
Standalone usage:
>>> y_true = [[1., 0.]]
>>> y_pred = [[0.6, 0.8]]
>>> loss = tfr.keras.losses.PairwiseHingeLoss()
>>> loss(y_true, y_pred).numpy()
0.6
>>> # Using ragged tensors
>>> y_true = tf.ragged.constant([[1., 0.], [0., 1., 0.]])
>>> y_pred = tf.ragged.constant([[0.6, 0.8], [0.5, 0.8, 0.4]])
>>> loss = tfr.keras.losses.PairwiseHingeLoss(ragged=True)
>>> loss(y_true, y_pred).numpy()
0.41666666
Usage with the `compile()` API:
```python
model.compile(optimizer='sgd', loss=tfr.keras.losses.PairwiseHingeLoss())
```
Definition:
$$
\mathcal{L}(\{y\}, \{s\}) =
\sum_i \sum_j I[y_i > y_j] \max(0, 1 - (s_i - s_j))
$$
"""
def __init__(self,
reduction: tf.losses.Reduction = tf.losses.Reduction.AUTO,
name: Optional[str] = None,
lambda_weight: Optional[losses_impl._LambdaWeight] = None,
temperature: float = 1.0,
ragged: bool = False):
"""Pairwise hinge loss.
Args:
reduction: (Optional) The `tf.keras.losses.Reduction` to use (see
`tf.keras.losses.Loss`).
name: (Optional) The name for the op.
lambda_weight: (Optional) A lambdaweight to apply to the loss. Can be one
of `tfr.keras.losses.DCGLambdaWeight`,
`tfr.keras.losses.NDCGLambdaWeight`, or,
`tfr.keras.losses.PrecisionLambdaWeight`.
temperature: (Optional) The temperature to use for scaling the logits.
ragged: (Optional) If True, this loss will accept ragged tensors. If
False, this loss will accept dense tensors.
"""
super().__init__(reduction, name, lambda_weight, temperature, ragged)
self._loss = losses_impl.PairwiseHingeLoss(
name='{}_impl'.format(name) if name else None,
lambda_weight=lambda_weight,
temperature=temperature,
ragged=ragged)
@tf.keras.utils.register_keras_serializable(package='tensorflow_ranking')
class PairwiseLogisticLoss(_PairwiseLoss):
r"""Computes pairwise logistic loss between `y_true` and `y_pred`.
For each list of scores `s` in `y_pred` and list of labels `y` in `y_true`:
```
loss = sum_i sum_j I[y_i > y_j] * log(1 + exp(-(s_i - s_j)))
```
Standalone usage:
>>> y_true = [[1., 0.]]
>>> y_pred = [[0.6, 0.8]]
>>> loss = tfr.keras.losses.PairwiseLogisticLoss()
>>> loss(y_true, y_pred).numpy()
0.39906943
>>> # Using ragged tensors
>>> y_true = tf.ragged.constant([[1., 0.], [0., 1., 0.]])
>>> y_pred = tf.ragged.constant([[0.6, 0.8], [0.5, 0.8, 0.4]])
>>> loss = tfr.keras.losses.PairwiseLogisticLoss(ragged=True)
>>> loss(y_true, y_pred).numpy()
0.3109182
Usage with the `compile()` API:
```python
model.compile(optimizer='sgd', loss=tfr.keras.losses.PairwiseLogisticLoss())
```
Definition:
$$
\mathcal{L}(\{y\}, \{s\}) =
\sum_i \sum_j I[y_i > y_j] \log(1 + \exp(-(s_i - s_j)))
$$
"""
def __init__(self,
reduction: tf.losses.Reduction = tf.losses.Reduction.AUTO,
name: Optional[str] = None,
lambda_weight: Optional[losses_impl._LambdaWeight] = None,
temperature: float = 1.0,
ragged: bool = False):
"""Pairwise logistic loss.
Args:
reduction: (Optional) The `tf.keras.losses.Reduction` to use (see
`tf.keras.losses.Loss`).
name: (Optional) The name for the op.
lambda_weight: (Optional) A lambdaweight to apply to the loss. Can be one
of `tfr.keras.losses.DCGLambdaWeight`,
`tfr.keras.losses.NDCGLambdaWeight`, or,
`tfr.keras.losses.PrecisionLambdaWeight`.
temperature: (Optional) The temperature to use for scaling the logits.
ragged: (Optional) If True, this loss will accept ragged tensors. If
False, this loss will accept dense tensors.
"""
super().__init__(reduction, name, lambda_weight, temperature, ragged)
self._loss = losses_impl.PairwiseLogisticLoss(
name='{}_impl'.format(name) if name else None,
lambda_weight=lambda_weight,
temperature=temperature,
ragged=ragged)
@tf.keras.utils.register_keras_serializable(package='tensorflow_ranking')
class PairwiseSoftZeroOneLoss(_PairwiseLoss):
r"""Computes pairwise soft zero-one loss between `y_true` and `y_pred`.
For each list of scores `s` in `y_pred` and list of labels `y` in `y_true`:
```
loss = sum_i sum_j I[y_i > y_j] * (1 - sigmoid(s_i - s_j))
```
Standalone usage:
>>> y_true = [[1., 0.]]
>>> y_pred = [[0.6, 0.8]]
>>> loss = tfr.keras.losses.PairwiseSoftZeroOneLoss()
>>> loss(y_true, y_pred).numpy()
0.274917
>>> # Using ragged tensors
>>> y_true = tf.ragged.constant([[1., 0.], [0., 1., 0.]])
>>> y_pred = tf.ragged.constant([[0.6, 0.8], [0.5, 0.8, 0.4]])
>>> loss = tfr.keras.losses.PairwiseSoftZeroOneLoss(ragged=True)
>>> loss(y_true, y_pred).numpy()
0.22945064
Usage with the `compile()` API:
```python
model.compile(optimizer='sgd',
loss=tfr.keras.losses.PairwiseSoftZeroOneLoss())
```
Definition:
$$
\mathcal{L}(\{y\}, \{s\}) =
\sum_i \sum_j I[y_i > y_j] (1 - \text{sigmoid}(s_i - s_j))
$$
"""
def __init__(self,
reduction: tf.losses.Reduction = tf.losses.Reduction.AUTO,
name: Optional[str] = None,
lambda_weight: Optional[losses_impl._LambdaWeight] = None,
temperature: float = 1.0,
ragged: bool = False):
"""Pairwise soft zero one loss.
Args:
reduction: (Optional) The `tf.keras.losses.Reduction` to use (see
`tf.keras.losses.Loss`).
name: (Optional) The name for the op.
lambda_weight: (Optional) A lambdaweight to apply to the loss. Can be one
of `tfr.keras.losses.DCGLambdaWeight`,
`tfr.keras.losses.NDCGLambdaWeight`, or,
`tfr.keras.losses.PrecisionLambdaWeight`.
temperature: (Optional) The temperature to use for scaling the logits.
ragged: (Optional) If True, this loss will accept ragged tensors. If
False, this loss will accept dense tensors.
"""
super().__init__(reduction, name, lambda_weight, temperature, ragged)
self._loss = losses_impl.PairwiseSoftZeroOneLoss(
name='{}_impl'.format(name) if name else None,
lambda_weight=lambda_weight,
temperature=temperature,
ragged=ragged)
@tf.keras.utils.register_keras_serializable(package='tensorflow_ranking')
class PairwiseMSELoss(_PairwiseLoss):
r"""Computes pairwise mean squared error loss between `y_true` and `y_pred`.
For each list of scores `s` in `y_pred` and list of labels `y` in `y_true`:
```
loss = sum_{i \neq j} ((s_i - s_j) - (y_i - y_j))**2
```
Standalone usage:
>>> y_true = [[1., 0.]]
>>> y_pred = [[0.6, 0.8]]
>>> loss = tfr.keras.losses.PairwiseMSELoss()
>>> loss(y_true, y_pred).numpy()
1.44
>>> # Using ragged tensors
>>> y_true = tf.ragged.constant([[1., 0.], [0., 1., 0.]])
>>> y_pred = tf.ragged.constant([[0.6, 0.8], [0.5, 0.8, 0.4]])
>>> loss = tfr.keras.losses.PairwiseMSELoss(ragged=True)
>>> loss(y_true, y_pred).numpy()
0.7666667
Usage with the `compile()` API:
```python
model.compile(optimizer='sgd',
loss=tfr.keras.losses.PairwiseMSELoss())
```
Definition:
$$
\mathcal{L}(\{y\}, \{s\}) =
\sum_{i \neq j}((s_i - s_j) - (y_i - y_j))^2
$$
"""
def __init__(self,
reduction: tf.losses.Reduction = tf.losses.Reduction.AUTO,
name: Optional[str] = None,
lambda_weight: Optional[losses_impl._LambdaWeight] = None,
temperature: float = 1.0,
ragged: bool = False):
"""Pairwise Mean Squared Error loss.
Args:
reduction: (Optional) The `tf.keras.losses.Reduction` to use (see
`tf.keras.losses.Loss`).
name: (Optional) The name for the op.
lambda_weight: (Optional) A lambdaweight to apply to the loss. Can be one
of `tfr.keras.losses.DCGLambdaWeight`,
`tfr.keras.losses.NDCGLambdaWeight`, or,
`tfr.keras.losses.PrecisionLambdaWeight`.
temperature: (Optional) The temperature to use for scaling the logits.
ragged: (Optional) If True, this loss will accept ragged tensors. If
False, this loss will accept dense tensors.
"""
super().__init__(reduction, name, lambda_weight, temperature, ragged)
self._loss = losses_impl.PairwiseMSELoss(
name='{}_impl'.format(name) if name else None,
lambda_weight=lambda_weight,
temperature=temperature,
ragged=ragged)
@tf.keras.utils.register_keras_serializable(package='tensorflow_ranking')
class YetiLogisticLoss(_PairwiseLoss):
r"""Computes Yeti logistic loss between `y_true` and `y_pred`.
Adapted to neural network models from the Yeti loss implemenation for GBDT in
([Lyzhin et al, 2022][lyzhin2022]).
In this code base, we support Yeti loss with the DCG lambda weight option.
The default uses the YetiDCGLambdaWeight with default settings. To customize,
please set the lambda_weight to YetiDCGLambdaWeight.
For each list of scores `s` in `y_pred` and list of labels `y` in `y_true`:
```
loss = sum_a sum_i I[y_i > y_{i\pm 1}] * log(1 + exp(-(s^a_i - s^a_{i\pm 1})))
```
where
```
s^a_i = s_i + gumbel(0, 1)^a
```
Standalone usage:
>>> y_true = [[1., 0.]]
>>> y_pred = [[0.6, 0.8]]
>>> loss = tfr.keras.losses.YetiLogisticLoss(sample_size=2, seed=1)
>>> loss(y_true, y_pred).numpy()
0.90761846
>>> # Using ragged tensors
>>> y_true = tf.ragged.constant([[1., 0.], [0., 1., 0.]])
>>> y_pred = tf.ragged.constant([[0.6, 0.8], [0.5, 0.8, 0.4]])
>>> loss = tfr.keras.losses.YetiLogisticLoss(seed=1, ragged=True)
>>> loss(y_true, y_pred).numpy()
0.43420443
Usage with the `compile()` API:
```python
model.compile(optimizer='sgd', loss=tfr.keras.losses.YetiLogisticLoss())
```
Definition:
$$
\mathcal{L}(\{y\}, \{s\}) =
\sum_a \sum_i \sum_{j=i\pm 1}I[y_i > y_j] \log(1 + \exp(-(s^a_i - s^a_j)))
$$
References:
- [Which Tricks are Important for Learning to Rank?, Lyzhin et al,
2022][lyzhin2022]
[lyzhin2022]: https://arxiv.org/abs/2204.01500
""" # pylint: disable=g-line-too-long
def __init__(
self,
reduction: tf.losses.Reduction = tf.losses.Reduction.AUTO,
name: Optional[str] = None,
lambda_weight: Optional[YetiDCGLambdaWeight] = None,
temperature: float = 0.1,
sample_size: int = 8,
gumbel_temperature: float = 1.0,
seed: Optional[int] = None,
ragged: bool = False,
):
lambda_weight = lambda_weight or YetiDCGLambdaWeight()
super().__init__(
reduction, name, lambda_weight, temperature=temperature, ragged=ragged
)
self._loss = losses_impl.PairwiseLogisticLoss(
name='{}_impl'.format(name) if name else None,
lambda_weight=lambda_weight,
temperature=temperature,
ragged=ragged,
)
self._sample_size = sample_size
self._gumbel_temperature = gumbel_temperature
self._seed = seed
self._gumbel_sampler = losses_impl.GumbelSampler(
name=name,
sample_size=sample_size,
temperature=gumbel_temperature,
seed=seed,
ragged=ragged,
)
def get_config(self) -> Dict[str, Any]:
config = super().get_config()
config.update({
'sample_size': self._sample_size,
'gumbel_temperature': self._gumbel_temperature,
'seed': self._seed,
})
return config
def __call__(
self,
y_true: utils.TensorLike,
y_pred: utils.TensorLike,
sample_weight: Optional[utils.TensorLike] = None,
) -> tf.Tensor:
"""See _RankingLoss."""
# For Yeti losses, the logits are sampled from Gumbel distribution
# and then sorted.
gbl_labels, gbl_logits, gbl_weights = self._gumbel_sampler.sample(
y_true, y_pred, weights=sample_weight
)
return super().__call__(gbl_labels, gbl_logits, gbl_weights)
class _ListwiseLoss(_RankingLoss):
"""Base class for listwise ranking losses."""
def __init__(self,
reduction: tf.losses.Reduction = tf.losses.Reduction.AUTO,
name: Optional[str] = None,
lambda_weight: Optional[losses_impl._LambdaWeight] = None,
temperature: float = 1.0,
ragged: bool = False,
**kwargs):
super().__init__(reduction, name, ragged)
self._lambda_weight = lambda_weight
self._temperature = temperature
def get_config(self) -> Dict[str, Any]:
config = super().get_config()
config.update({
'lambda_weight': utils.serialize_keras_object(
self._lambda_weight
),
'temperature': self._temperature,
})
return config
@classmethod
def from_config(cls, config, custom_objects=None):
config = config.copy()
config.update(
{
'lambda_weight': utils.deserialize_keras_object(
config['lambda_weight']
),
}
)
return cls(**config)
@tf.keras.utils.register_keras_serializable(package='tensorflow_ranking')
class SoftmaxLoss(_ListwiseLoss):
r"""Computes Softmax cross-entropy loss between `y_true` and `y_pred`.
For each list of scores `s` in `y_pred` and list of labels `y` in `y_true`:
```
loss = - sum_i y_i * log(softmax(s_i))
```
Standalone usage:
>>> y_true = [[1., 0.]]
>>> y_pred = [[0.6, 0.8]]
>>> loss = tfr.keras.losses.SoftmaxLoss()
>>> loss(y_true, y_pred).numpy()
0.7981389
>>> # Using ragged tensors
>>> y_true = tf.ragged.constant([[1., 0.], [0., 1., 0.]])
>>> y_pred = tf.ragged.constant([[0.6, 0.8], [0.5, 0.8, 0.4]])
>>> loss = tfr.keras.losses.SoftmaxLoss(ragged=True)
>>> loss(y_true, y_pred).numpy()
0.83911896
Usage with the `compile()` API:
```python
model.compile(optimizer='sgd', loss=tfr.keras.losses.SoftmaxLoss())
```
Definition:
$$
\mathcal{L}(\{y\}, \{s\}) = - \sum_i y_i
\log\left(\frac{\exp(s_i)}{\sum_j \exp(s_j)}\right)
$$
"""
def __init__(self,
reduction: tf.losses.Reduction = tf.losses.Reduction.AUTO,
name: Optional[str] = None,
lambda_weight: Optional[losses_impl._LambdaWeight] = None,
temperature: float = 1.0,
ragged: bool = False):
"""Softmax cross-entropy loss.
Args:
reduction: (Optional) The `tf.keras.losses.Reduction` to use (see
`tf.keras.losses.Loss`).
name: (Optional) The name for the op.
lambda_weight: (Optional) A lambdaweight to apply to the loss. Can be one
of `tfr.keras.losses.DCGLambdaWeight`,
`tfr.keras.losses.NDCGLambdaWeight`, or,
`tfr.keras.losses.PrecisionLambdaWeight`.
temperature: (Optional) The temperature to use for scaling the logits.
ragged: (Optional) If True, this loss will accept ragged tensors. If
False, this loss will accept dense tensors.
"""
super().__init__(reduction, name, lambda_weight, temperature, ragged)
self._loss = losses_impl.SoftmaxLoss(
name='{}_impl'.format(name) if name else None,
lambda_weight=lambda_weight,
temperature=temperature,
ragged=ragged)
def __call__(self,
y_true: utils.TensorLike,
y_pred: utils.TensorLike,
sample_weight: Optional[utils.TensorLike] = None) -> tf.Tensor:
"""See _RankingLoss."""
losses, sample_weight = self._loss.compute_per_list(y_true, y_pred,
sample_weight)
return tf.keras.__internal__.losses.compute_weighted_loss(
losses, sample_weight, reduction=self._get_reduction())
@tf.keras.utils.register_keras_serializable(package='tensorflow_ranking')
class UniqueSoftmaxLoss(_ListwiseLoss):
r"""Computes unique softmax cross-entropy loss between `y_true` and `y_pred`.
Implements unique rating softmax loss ([Zhu et al, 2020][zhu2020]).
For each list of scores `s` in `y_pred` and list of labels `y` in `y_true`:
```
loss = - sum_i (2^{y_i} - 1) *
log(exp(s_i) / sum_j I(y_i > y_j) exp(s_j) + exp(s_i))
```
Standalone usage:
>>> y_true = [[1., 0.]]
>>> y_pred = [[0.6, 0.8]]
>>> loss = tfr.keras.losses.UniqueSoftmaxLoss()
>>> loss(y_true, y_pred).numpy()
0.7981389
>>> # Using ragged tensors
>>> y_true = tf.ragged.constant([[1., 0.], [0., 1., 0.]])
>>> y_pred = tf.ragged.constant([[0.6, 0.8], [0.5, 0.8, 0.4]])
>>> loss = tfr.keras.losses.UniqueSoftmaxLoss(ragged=True)
>>> loss(y_true, y_pred).numpy()
0.83911896
Usage with the `compile()` API:
```python
model.compile(optimizer='sgd', loss=tfr.keras.losses.UniqueSoftmaxLoss())
```
Definition:
$$
\mathcal{L}(\{y\}, \{s\}) = - \sum_i (2^{y_i} - 1)
\log\left(\frac{\exp(s_i)}{\sum_j I_{y_i > y_j} \exp(s_j) + \exp(s_i)}\right)
$$
References:
- [Listwise Learning to Rank by Exploring Unique Ratings, Zhu et al,
2020][zhu2020]
[zhu2020]: https://arxiv.org/abs/2001.01828
"""
def __init__(self,
reduction: tf.losses.Reduction = tf.losses.Reduction.AUTO,
name: Optional[str] = None,
lambda_weight: Optional[losses_impl._LambdaWeight] = None,
temperature: float = 1.0,
ragged: bool = False):
super().__init__(reduction, name, lambda_weight, temperature, ragged)
self._loss = losses_impl.UniqueSoftmaxLoss(
name='{}_impl'.format(name) if name else None,
lambda_weight=lambda_weight,
temperature=temperature,
ragged=ragged)
@tf.keras.utils.register_keras_serializable(package='tensorflow_ranking')
class ListMLELoss(_ListwiseLoss):
r"""Computes ListMLE loss between `y_true` and `y_pred`.
Implements ListMLE loss ([Xia et al, 2008][xia2008]). For each list of scores
`s` in `y_pred` and list of labels `y` in `y_true`:
```
loss = - log P(permutation_y | s)
P(permutation_y | s) = Plackett-Luce probability of permutation_y given s
permutation_y = permutation of items sorted by labels y.
```
NOTE: This loss is stochastic and may return different values for identical
inputs.
Standalone usage:
>>> tf.random.set_seed(42)
>>> y_true = [[1., 0.]]
>>> y_pred = [[0.6, 0.8]]
>>> loss = tfr.keras.losses.ListMLELoss()
>>> loss(y_true, y_pred).numpy()
0.7981389
>>> # Using ragged tensors
>>> tf.random.set_seed(42)
>>> y_true = tf.ragged.constant([[1., 0.], [0., 1., 0.]])
>>> y_pred = tf.ragged.constant([[0.6, 0.8], [0.5, 0.8, 0.4]])
>>> loss = tfr.keras.losses.ListMLELoss(ragged=True)
>>> loss(y_true, y_pred).numpy()
1.1613163
Usage with the `compile()` API:
```python
model.compile(optimizer='sgd', loss=tfr.keras.losses.ListMLELoss())
```
Definition:
$$
\mathcal{L}(\{y\}, \{s\}) = - \log(P(\pi_y | s))
$$
where $P(\pi_y | s)$ is the Plackett-Luce probability of a permutation
$\pi_y$ conditioned on scores $s$. Here $\pi_y$ represents a permutation
of items ordered by the relevance labels $y$ where ties are broken randomly.
References:
- [Listwise approach to learning to rank: theory and algorithm, Xia et al,
2008][xia2008]
[xia2008]: https://dl.acm.org/doi/10.1145/1390156.1390306
"""
def __init__(self,
reduction: tf.losses.Reduction = tf.losses.Reduction.AUTO,
name: Optional[str] = None,
lambda_weight: Optional[losses_impl._LambdaWeight] = None,
temperature: float = 1.0,
ragged: bool = False):
"""ListMLE loss.
Args:
reduction: (Optional) The `tf.keras.losses.Reduction` to use (see
`tf.keras.losses.Loss`).
name: (Optional) The name for the op.
lambda_weight: (Optional) A lambdaweight to apply to the loss. Can be one
of `tfr.keras.losses.DCGLambdaWeight`,
`tfr.keras.losses.NDCGLambdaWeight`,
`tfr.keras.losses.PrecisionLambdaWeight`, or,
`tfr.keras.losses.ListMLELambdaWeight`.
temperature: (Optional) The temperature to use for scaling the logits.
ragged: (Optional) If True, this loss will accept ragged tensors. If
False, this loss will accept dense tensors.
"""
super().__init__(reduction, name, lambda_weight, temperature, ragged)
self._loss = losses_impl.ListMLELoss(
name='{}_impl'.format(name) if name else None,
lambda_weight=lambda_weight,
temperature=temperature,
ragged=ragged)
@tf.keras.utils.register_keras_serializable(package='tensorflow_ranking')
class ApproxMRRLoss(_ListwiseLoss):
r"""Computes approximate MRR loss between `y_true` and `y_pred`.
Implementation of ApproxMRR loss ([Qin et al, 2008][qin2008]). This loss is
an approximation for `tfr.keras.metrics.MRRMetric`. It replaces the
non-differentiable ranking function in MRR with a differentiable approximation
based on the logistic function.
For each list of scores `s` in `y_pred` and list of labels `y` in `y_true`:
```
loss = sum_i (1 / approxrank(s_i)) * y_i
approxrank(s_i) = 1 + sum_j (1 / (1 + exp(-(s_j - s_i) / temperature)))
```
Standalone usage:
>>> y_true = [[1., 0.]]
>>> y_pred = [[0.6, 0.8]]
>>> loss = tfr.keras.losses.ApproxMRRLoss()
>>> loss(y_true, y_pred).numpy()