forked from tensorflow/models
-
Notifications
You must be signed in to change notification settings - Fork 2
/
loss_layers_test.py
1379 lines (1197 loc) · 55.8 KB
/
loss_layers_test.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 2018 The TensorFlow Global Objectives Authors. All Rights Reserved.
#
# 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.
# ==============================================================================
"""Tests for global objectives loss layers."""
# Dependency imports
from absl.testing import parameterized
import numpy
import tensorflow as tf
from global_objectives import loss_layers
from global_objectives import util
# TODO: Include weights in the lagrange multiplier update tests.
class PrecisionRecallAUCLossTest(parameterized.TestCase, tf.test.TestCase):
@parameterized.named_parameters(
('_xent', 'xent', 0.7),
('_hinge', 'hinge', 0.7),
('_hinge_2', 'hinge', 0.5)
)
def testSinglePointAUC(self, surrogate_type, target_precision):
# Tests a case with only one anchor point, where the loss should equal
# recall_at_precision_loss
batch_shape = [10, 2]
logits = tf.Variable(tf.random_normal(batch_shape))
labels = tf.Variable(
tf.to_float(tf.greater(tf.random_uniform(batch_shape), 0.4)))
auc_loss, _ = loss_layers.precision_recall_auc_loss(
labels,
logits,
precision_range=(target_precision - 0.01, target_precision + 0.01),
num_anchors=1,
surrogate_type=surrogate_type)
point_loss, _ = loss_layers.recall_at_precision_loss(
labels, logits, target_precision=target_precision,
surrogate_type=surrogate_type)
with self.test_session():
tf.global_variables_initializer().run()
self.assertAllClose(auc_loss.eval(), point_loss.eval())
def testThreePointAUC(self):
# Tests a case with three anchor points against a weighted sum of recall
# at precision losses.
batch_shape = [11, 3]
logits = tf.Variable(tf.random_normal(batch_shape))
labels = tf.Variable(
tf.to_float(tf.greater(tf.random_uniform(batch_shape), 0.4)))
# TODO: Place the hing/xent loss in a for loop.
auc_loss, _ = loss_layers.precision_recall_auc_loss(
labels, logits, num_anchors=1)
first_point_loss, _ = loss_layers.recall_at_precision_loss(
labels, logits, target_precision=0.25)
second_point_loss, _ = loss_layers.recall_at_precision_loss(
labels, logits, target_precision=0.5)
third_point_loss, _ = loss_layers.recall_at_precision_loss(
labels, logits, target_precision=0.75)
expected_loss = (first_point_loss + second_point_loss +
third_point_loss) / 3
auc_loss_hinge, _ = loss_layers.precision_recall_auc_loss(
labels, logits, num_anchors=1, surrogate_type='hinge')
first_point_hinge, _ = loss_layers.recall_at_precision_loss(
labels, logits, target_precision=0.25, surrogate_type='hinge')
second_point_hinge, _ = loss_layers.recall_at_precision_loss(
labels, logits, target_precision=0.5, surrogate_type='hinge')
third_point_hinge, _ = loss_layers.recall_at_precision_loss(
labels, logits, target_precision=0.75, surrogate_type='hinge')
expected_hinge = (first_point_hinge + second_point_hinge +
third_point_hinge) / 3
with self.test_session():
tf.global_variables_initializer().run()
self.assertAllClose(auc_loss.eval(), expected_loss.eval())
self.assertAllClose(auc_loss_hinge.eval(), expected_hinge.eval())
def testLagrangeMultiplierUpdateDirection(self):
for target_precision in [0.35, 0.65]:
precision_range = (target_precision - 0.01, target_precision + 0.01)
for surrogate_type in ['xent', 'hinge']:
kwargs = {'precision_range': precision_range,
'num_anchors': 1,
'surrogate_type': surrogate_type,
'scope': 'pr-auc_{}_{}'.format(target_precision,
surrogate_type)}
run_lagrange_multiplier_test(
global_objective=loss_layers.precision_recall_auc_loss,
objective_kwargs=kwargs,
data_builder=_multilabel_data,
test_object=self)
kwargs['scope'] = 'other-' + kwargs['scope']
run_lagrange_multiplier_test(
global_objective=loss_layers.precision_recall_auc_loss,
objective_kwargs=kwargs,
data_builder=_other_multilabel_data(surrogate_type),
test_object=self)
class ROCAUCLossTest(parameterized.TestCase, tf.test.TestCase):
def testSimpleScores(self):
# Tests the loss on data with only one negative example with score zero.
# In this case, the loss should equal the surrogate loss on the scores with
# positive labels.
num_positives = 10
scores_positives = tf.constant(3.0 * numpy.random.randn(num_positives),
shape=[num_positives, 1])
labels = tf.constant([0.0] + [1.0] * num_positives,
shape=[num_positives + 1, 1])
scores = tf.concat([[[0.0]], scores_positives], 0)
loss = tf.reduce_sum(
loss_layers.roc_auc_loss(labels, scores, surrogate_type='hinge')[0])
expected_loss = tf.reduce_sum(
tf.maximum(1.0 - scores_positives, 0)) / (num_positives + 1)
with self.test_session():
self.assertAllClose(expected_loss.eval(), loss.eval())
def testRandomROCLoss(self):
# Checks that random Bernoulli scores and labels has ~25% swaps.
shape = [1000, 30]
scores = tf.constant(
numpy.random.randint(0, 2, size=shape), shape=shape, dtype=tf.float32)
labels = tf.constant(
numpy.random.randint(0, 2, size=shape), shape=shape, dtype=tf.float32)
loss = tf.reduce_mean(loss_layers.roc_auc_loss(
labels, scores, surrogate_type='hinge')[0])
with self.test_session():
self.assertAllClose(0.25, loss.eval(), 1e-2)
@parameterized.named_parameters(
('_zero_hinge', 'xent',
[0.0, 0.0, 0.0, 1.0, 1.0, 1.0],
[-5.0, -7.0, -9.0, 8.0, 10.0, 14.0],
0.0),
('_zero_xent', 'hinge',
[0.0, 0.0, 0.0, 1.0, 1.0, 1.0],
[-0.2, 0, -0.1, 1.0, 1.1, 1.0],
0.0),
('_xent', 'xent',
[0.0, 0.0, 0.0, 1.0, 1.0, 1.0],
[0.0, -17.0, -19.0, 1.0, 14.0, 14.0],
numpy.log(1.0 + numpy.exp(-1.0)) / 6),
('_hinge', 'hinge',
[0.0, 0.0, 0.0, 1.0, 1.0, 1.0],
[-0.2, -0.05, 0.0, 0.95, 0.8, 1.0],
0.4 / 6)
)
def testManualROCLoss(self, surrogate_type, labels, logits, expected_value):
labels = tf.constant(labels)
logits = tf.constant(logits)
loss, _ = loss_layers.roc_auc_loss(
labels=labels, logits=logits, surrogate_type=surrogate_type)
with self.test_session():
self.assertAllClose(expected_value, tf.reduce_sum(loss).eval())
def testMultiLabelROCLoss(self):
# Tests the loss on multi-label data against manually computed loss.
targets = numpy.array([[0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 1.0, 1.0]])
scores = numpy.array([[0.1, 1.0, 1.1, 1.0], [1.0, 0.0, 1.3, 1.1]])
class_1_auc = tf.reduce_sum(
loss_layers.roc_auc_loss(targets[0], scores[0])[0])
class_2_auc = tf.reduce_sum(
loss_layers.roc_auc_loss(targets[1], scores[1])[0])
total_auc = tf.reduce_sum(loss_layers.roc_auc_loss(
targets.transpose(), scores.transpose())[0])
with self.test_session():
self.assertAllClose(total_auc.eval(),
class_1_auc.eval() + class_2_auc.eval())
def testWeights(self):
# Test the loss with per-example weights.
# The logits_negatives below are repeated, so that setting half their
# weights to 2 and the other half to 0 should leave the loss unchanged.
logits_positives = tf.constant([2.54321, -0.26, 3.334334], shape=[3, 1])
logits_negatives = tf.constant([-0.6, 1, -1.3, -1.3, -0.6, 1], shape=[6, 1])
logits = tf.concat([logits_positives, logits_negatives], 0)
targets = tf.constant([1, 1, 1, 0, 0, 0, 0, 0, 0],
shape=[9, 1], dtype=tf.float32)
weights = tf.constant([1, 1, 1, 0, 0, 0, 2, 2, 2],
shape=[9, 1], dtype=tf.float32)
loss = tf.reduce_sum(loss_layers.roc_auc_loss(targets, logits)[0])
weighted_loss = tf.reduce_sum(
loss_layers.roc_auc_loss(targets, logits, weights)[0])
with self.test_session():
self.assertAllClose(loss.eval(), weighted_loss.eval())
class RecallAtPrecisionTest(tf.test.TestCase):
def testEqualWeightLoss(self):
# Tests a special case where the loss should equal cross entropy loss.
target_precision = 1.0
num_labels = 5
batch_shape = [20, num_labels]
logits = tf.Variable(tf.random_normal(batch_shape))
targets = tf.Variable(
tf.to_float(tf.greater(tf.random_uniform(batch_shape), 0.7)))
label_priors = tf.constant(0.34, shape=[num_labels])
loss, _ = loss_layers.recall_at_precision_loss(
targets, logits, target_precision, label_priors=label_priors)
expected_loss = (
tf.contrib.nn.deprecated_flipped_sigmoid_cross_entropy_with_logits(
logits, targets))
with self.test_session() as session:
tf.global_variables_initializer().run()
loss_val, expected_val = session.run([loss, expected_loss])
self.assertAllClose(loss_val, expected_val)
def testEqualWeightLossWithMultiplePrecisions(self):
"""Tests a case where the loss equals xent loss with multiple precisions."""
target_precision = [1.0, 1.0]
num_labels = 2
batch_size = 20
target_shape = [batch_size, num_labels]
logits = tf.Variable(tf.random_normal(target_shape))
targets = tf.Variable(
tf.to_float(tf.greater(tf.random_uniform(target_shape), 0.7)))
label_priors = tf.constant([0.34], shape=[num_labels])
loss, _ = loss_layers.recall_at_precision_loss(
targets,
logits,
target_precision,
label_priors=label_priors,
surrogate_type='xent',
)
expected_loss = (
tf.contrib.nn.deprecated_flipped_sigmoid_cross_entropy_with_logits(
logits, targets))
with self.test_session() as session:
tf.global_variables_initializer().run()
loss_val, expected_val = session.run([loss, expected_loss])
self.assertAllClose(loss_val, expected_val)
def testPositivesOnlyLoss(self):
# Tests a special case where the loss should equal cross entropy loss
# on the negatives only.
target_precision = 1.0
num_labels = 3
batch_shape = [30, num_labels]
logits = tf.Variable(tf.random_normal(batch_shape))
targets = tf.Variable(
tf.to_float(tf.greater(tf.random_uniform(batch_shape), 0.4)))
label_priors = tf.constant(0.45, shape=[num_labels])
loss, _ = loss_layers.recall_at_precision_loss(
targets, logits, target_precision, label_priors=label_priors,
lambdas_initializer=tf.zeros_initializer())
expected_loss = util.weighted_sigmoid_cross_entropy_with_logits(
targets,
logits,
positive_weights=1.0,
negative_weights=0.0)
with self.test_session() as session:
tf.global_variables_initializer().run()
loss_val, expected_val = session.run([loss, expected_loss])
self.assertAllClose(loss_val, expected_val)
def testEquivalenceBetweenSingleAndMultiplePrecisions(self):
"""Checks recall at precision with different precision values.
Runs recall at precision with multiple precision values, and runs each label
seperately with its own precision value as a scalar. Validates that the
returned loss values are the same.
"""
target_precision = [0.2, 0.9, 0.4]
num_labels = 3
batch_shape = [30, num_labels]
logits = tf.Variable(tf.random_normal(batch_shape))
targets = tf.Variable(
tf.to_float(tf.greater(tf.random_uniform(batch_shape), 0.4)))
label_priors = tf.constant([0.45, 0.8, 0.3], shape=[num_labels])
multi_label_loss, _ = loss_layers.recall_at_precision_loss(
targets, logits, target_precision, label_priors=label_priors,
)
single_label_losses = [
loss_layers.recall_at_precision_loss(
tf.expand_dims(targets[:, i], -1),
tf.expand_dims(logits[:, i], -1),
target_precision[i],
label_priors=label_priors[i])[0]
for i in range(num_labels)
]
single_label_losses = tf.concat(single_label_losses, 1)
with self.test_session() as session:
tf.global_variables_initializer().run()
multi_label_loss_val, single_label_loss_val = session.run(
[multi_label_loss, single_label_losses])
self.assertAllClose(multi_label_loss_val, single_label_loss_val)
def testEquivalenceBetweenSingleAndEqualMultiplePrecisions(self):
"""Compares single and multiple target precisions with the same value.
Checks that using a single target precision and multiple target precisions
with the same value would result in the same loss value.
"""
num_labels = 2
target_shape = [20, num_labels]
logits = tf.Variable(tf.random_normal(target_shape))
targets = tf.Variable(
tf.to_float(tf.greater(tf.random_uniform(target_shape), 0.7)))
label_priors = tf.constant([0.34], shape=[num_labels])
multi_precision_loss, _ = loss_layers.recall_at_precision_loss(
targets,
logits,
[0.75, 0.75],
label_priors=label_priors,
surrogate_type='xent',
)
single_precision_loss, _ = loss_layers.recall_at_precision_loss(
targets,
logits,
0.75,
label_priors=label_priors,
surrogate_type='xent',
)
with self.test_session() as session:
tf.global_variables_initializer().run()
multi_precision_loss_val, single_precision_loss_val = session.run(
[multi_precision_loss, single_precision_loss])
self.assertAllClose(multi_precision_loss_val, single_precision_loss_val)
def testLagrangeMultiplierUpdateDirection(self):
for target_precision in [0.35, 0.65]:
for surrogate_type in ['xent', 'hinge']:
kwargs = {'target_precision': target_precision,
'surrogate_type': surrogate_type,
'scope': 'r-at-p_{}_{}'.format(target_precision,
surrogate_type)}
run_lagrange_multiplier_test(
global_objective=loss_layers.recall_at_precision_loss,
objective_kwargs=kwargs,
data_builder=_multilabel_data,
test_object=self)
kwargs['scope'] = 'other-' + kwargs['scope']
run_lagrange_multiplier_test(
global_objective=loss_layers.recall_at_precision_loss,
objective_kwargs=kwargs,
data_builder=_other_multilabel_data(surrogate_type),
test_object=self)
def testLagrangeMultiplierUpdateDirectionWithMultiplePrecisions(self):
"""Runs Lagrange multiplier test with multiple precision values."""
target_precision = [0.65, 0.35]
for surrogate_type in ['xent', 'hinge']:
scope_str = 'r-at-p_{}_{}'.format(
'_'.join([str(precision) for precision in target_precision]),
surrogate_type)
kwargs = {
'target_precision': target_precision,
'surrogate_type': surrogate_type,
'scope': scope_str,
}
run_lagrange_multiplier_test(
global_objective=loss_layers.recall_at_precision_loss,
objective_kwargs=kwargs,
data_builder=_multilabel_data,
test_object=self)
kwargs['scope'] = 'other-' + kwargs['scope']
run_lagrange_multiplier_test(
global_objective=loss_layers.recall_at_precision_loss,
objective_kwargs=kwargs,
data_builder=_other_multilabel_data(surrogate_type),
test_object=self)
class PrecisionAtRecallTest(tf.test.TestCase):
def testCrossEntropyEquivalence(self):
# Checks a special case where the loss should equal cross-entropy loss.
target_recall = 1.0
num_labels = 3
batch_shape = [10, num_labels]
logits = tf.Variable(tf.random_normal(batch_shape))
targets = tf.Variable(
tf.to_float(tf.greater(tf.random_uniform(batch_shape), 0.4)))
loss, _ = loss_layers.precision_at_recall_loss(
targets, logits, target_recall,
lambdas_initializer=tf.constant_initializer(1.0))
expected_loss = util.weighted_sigmoid_cross_entropy_with_logits(
targets, logits)
with self.test_session():
tf.global_variables_initializer().run()
self.assertAllClose(loss.eval(), expected_loss.eval())
def testNegativesOnlyLoss(self):
# Checks a special case where the loss should equal the loss on
# the negative examples only.
target_recall = 0.61828
num_labels = 4
batch_shape = [8, num_labels]
logits = tf.Variable(tf.random_normal(batch_shape))
targets = tf.Variable(
tf.to_float(tf.greater(tf.random_uniform(batch_shape), 0.6)))
loss, _ = loss_layers.precision_at_recall_loss(
targets,
logits,
target_recall,
surrogate_type='hinge',
lambdas_initializer=tf.constant_initializer(0.0),
scope='negatives_only_test')
expected_loss = util.weighted_hinge_loss(
targets, logits, positive_weights=0.0, negative_weights=1.0)
with self.test_session():
tf.global_variables_initializer().run()
self.assertAllClose(expected_loss.eval(), loss.eval())
def testLagrangeMultiplierUpdateDirection(self):
for target_recall in [0.34, 0.66]:
for surrogate_type in ['xent', 'hinge']:
kwargs = {'target_recall': target_recall,
'dual_rate_factor': 1.0,
'surrogate_type': surrogate_type,
'scope': 'p-at-r_{}_{}'.format(target_recall, surrogate_type)}
run_lagrange_multiplier_test(
global_objective=loss_layers.precision_at_recall_loss,
objective_kwargs=kwargs,
data_builder=_multilabel_data,
test_object=self)
kwargs['scope'] = 'other-' + kwargs['scope']
run_lagrange_multiplier_test(
global_objective=loss_layers.precision_at_recall_loss,
objective_kwargs=kwargs,
data_builder=_other_multilabel_data(surrogate_type),
test_object=self)
def testCrossEntropyEquivalenceWithMultipleRecalls(self):
"""Checks a case where the loss equals xent loss with multiple recalls."""
num_labels = 3
target_recall = [1.0] * num_labels
batch_shape = [10, num_labels]
logits = tf.Variable(tf.random_normal(batch_shape))
targets = tf.Variable(
tf.to_float(tf.greater(tf.random_uniform(batch_shape), 0.4)))
loss, _ = loss_layers.precision_at_recall_loss(
targets, logits, target_recall,
lambdas_initializer=tf.constant_initializer(1.0))
expected_loss = util.weighted_sigmoid_cross_entropy_with_logits(
targets, logits)
with self.test_session():
tf.global_variables_initializer().run()
self.assertAllClose(loss.eval(), expected_loss.eval())
def testNegativesOnlyLossWithMultipleRecalls(self):
"""Tests a case where the loss equals the loss on the negative examples.
Checks this special case using multiple target recall values.
"""
num_labels = 4
target_recall = [0.61828] * num_labels
batch_shape = [8, num_labels]
logits = tf.Variable(tf.random_normal(batch_shape))
targets = tf.Variable(
tf.to_float(tf.greater(tf.random_uniform(batch_shape), 0.6)))
loss, _ = loss_layers.precision_at_recall_loss(
targets,
logits,
target_recall,
surrogate_type='hinge',
lambdas_initializer=tf.constant_initializer(0.0),
scope='negatives_only_test')
expected_loss = util.weighted_hinge_loss(
targets, logits, positive_weights=0.0, negative_weights=1.0)
with self.test_session():
tf.global_variables_initializer().run()
self.assertAllClose(expected_loss.eval(), loss.eval())
def testLagrangeMultiplierUpdateDirectionWithMultipleRecalls(self):
"""Runs Lagrange multiplier test with multiple recall values."""
target_recall = [0.34, 0.66]
for surrogate_type in ['xent', 'hinge']:
scope_str = 'p-at-r_{}_{}'.format(
'_'.join([str(recall) for recall in target_recall]),
surrogate_type)
kwargs = {'target_recall': target_recall,
'dual_rate_factor': 1.0,
'surrogate_type': surrogate_type,
'scope': scope_str}
run_lagrange_multiplier_test(
global_objective=loss_layers.precision_at_recall_loss,
objective_kwargs=kwargs,
data_builder=_multilabel_data,
test_object=self)
kwargs['scope'] = 'other-' + kwargs['scope']
run_lagrange_multiplier_test(
global_objective=loss_layers.precision_at_recall_loss,
objective_kwargs=kwargs,
data_builder=_other_multilabel_data(surrogate_type),
test_object=self)
def testEquivalenceBetweenSingleAndMultipleRecalls(self):
"""Checks precision at recall with multiple different recall values.
Runs precision at recall with multiple recall values, and runs each label
seperately with its own recall value as a scalar. Validates that the
returned loss values are the same.
"""
target_precision = [0.7, 0.9, 0.4]
num_labels = 3
batch_shape = [30, num_labels]
logits = tf.Variable(tf.random_normal(batch_shape))
targets = tf.Variable(
tf.to_float(tf.greater(tf.random_uniform(batch_shape), 0.4)))
label_priors = tf.constant(0.45, shape=[num_labels])
multi_label_loss, _ = loss_layers.precision_at_recall_loss(
targets, logits, target_precision, label_priors=label_priors
)
single_label_losses = [
loss_layers.precision_at_recall_loss(
tf.expand_dims(targets[:, i], -1),
tf.expand_dims(logits[:, i], -1),
target_precision[i],
label_priors=label_priors[i])[0]
for i in range(num_labels)
]
single_label_losses = tf.concat(single_label_losses, 1)
with self.test_session() as session:
tf.global_variables_initializer().run()
multi_label_loss_val, single_label_loss_val = session.run(
[multi_label_loss, single_label_losses])
self.assertAllClose(multi_label_loss_val, single_label_loss_val)
def testEquivalenceBetweenSingleAndEqualMultipleRecalls(self):
"""Compares single and multiple target recalls of the same value.
Checks that using a single target recall and multiple recalls with the
same value would result in the same loss value.
"""
num_labels = 2
target_shape = [20, num_labels]
logits = tf.Variable(tf.random_normal(target_shape))
targets = tf.Variable(
tf.to_float(tf.greater(tf.random_uniform(target_shape), 0.7)))
label_priors = tf.constant([0.34], shape=[num_labels])
multi_precision_loss, _ = loss_layers.precision_at_recall_loss(
targets,
logits,
[0.75, 0.75],
label_priors=label_priors,
surrogate_type='xent',
)
single_precision_loss, _ = loss_layers.precision_at_recall_loss(
targets,
logits,
0.75,
label_priors=label_priors,
surrogate_type='xent',
)
with self.test_session() as session:
tf.global_variables_initializer().run()
multi_precision_loss_val, single_precision_loss_val = session.run(
[multi_precision_loss, single_precision_loss])
self.assertAllClose(multi_precision_loss_val, single_precision_loss_val)
class FalsePositiveRateAtTruePositiveRateTest(tf.test.TestCase):
def testNegativesOnlyLoss(self):
# Checks a special case where the loss returned should be the loss on the
# negative examples.
target_recall = 0.6
num_labels = 3
batch_shape = [3, num_labels]
logits = tf.Variable(tf.random_normal(batch_shape))
targets = tf.Variable(
tf.to_float(tf.greater(tf.random_uniform(batch_shape), 0.4)))
label_priors = tf.constant(numpy.random.uniform(size=[num_labels]),
dtype=tf.float32)
xent_loss, _ = loss_layers.false_positive_rate_at_true_positive_rate_loss(
targets, logits, target_recall, label_priors=label_priors,
lambdas_initializer=tf.constant_initializer(0.0))
xent_expected = util.weighted_sigmoid_cross_entropy_with_logits(
targets,
logits,
positive_weights=0.0,
negative_weights=1.0)
hinge_loss, _ = loss_layers.false_positive_rate_at_true_positive_rate_loss(
targets, logits, target_recall, label_priors=label_priors,
lambdas_initializer=tf.constant_initializer(0.0),
surrogate_type='hinge')
hinge_expected = util.weighted_hinge_loss(
targets,
logits,
positive_weights=0.0,
negative_weights=1.0)
with self.test_session() as session:
tf.global_variables_initializer().run()
xent_val, xent_expected = session.run([xent_loss, xent_expected])
self.assertAllClose(xent_val, xent_expected)
hinge_val, hinge_expected = session.run([hinge_loss, hinge_expected])
self.assertAllClose(hinge_val, hinge_expected)
def testPositivesOnlyLoss(self):
# Checks a special case where the loss returned should be the loss on the
# positive examples only.
target_recall = 1.0
num_labels = 5
batch_shape = [5, num_labels]
logits = tf.Variable(tf.random_normal(batch_shape))
targets = tf.ones_like(logits)
label_priors = tf.constant(numpy.random.uniform(size=[num_labels]),
dtype=tf.float32)
loss, _ = loss_layers.false_positive_rate_at_true_positive_rate_loss(
targets, logits, target_recall, label_priors=label_priors)
expected_loss = tf.nn.sigmoid_cross_entropy_with_logits(
labels=targets, logits=logits)
hinge_loss, _ = loss_layers.false_positive_rate_at_true_positive_rate_loss(
targets, logits, target_recall, label_priors=label_priors,
surrogate_type='hinge')
expected_hinge = util.weighted_hinge_loss(
targets, logits)
with self.test_session():
tf.global_variables_initializer().run()
self.assertAllClose(loss.eval(), expected_loss.eval())
self.assertAllClose(hinge_loss.eval(), expected_hinge.eval())
def testEqualWeightLoss(self):
# Checks a special case where the loss returned should be proportional to
# the ordinary loss.
target_recall = 1.0
num_labels = 4
batch_shape = [40, num_labels]
logits = tf.Variable(tf.random_normal(batch_shape))
targets = tf.Variable(
tf.to_float(tf.greater(tf.random_uniform(batch_shape), 0.6)))
label_priors = tf.constant(0.5, shape=[num_labels])
loss, _ = loss_layers.false_positive_rate_at_true_positive_rate_loss(
targets, logits, target_recall, label_priors=label_priors)
expected_loss = tf.nn.sigmoid_cross_entropy_with_logits(
labels=targets, logits=logits)
with self.test_session():
tf.global_variables_initializer().run()
self.assertAllClose(loss.eval(), expected_loss.eval())
def testLagrangeMultiplierUpdateDirection(self):
for target_rate in [0.35, 0.65]:
for surrogate_type in ['xent', 'hinge']:
kwargs = {'target_rate': target_rate,
'surrogate_type': surrogate_type,
'scope': 'fpr-at-tpr_{}_{}'.format(target_rate,
surrogate_type)}
# True positive rate is a synonym for recall, so we use the
# recall constraint data.
run_lagrange_multiplier_test(
global_objective=(
loss_layers.false_positive_rate_at_true_positive_rate_loss),
objective_kwargs=kwargs,
data_builder=_multilabel_data,
test_object=self)
kwargs['scope'] = 'other-' + kwargs['scope']
run_lagrange_multiplier_test(
global_objective=(
loss_layers.false_positive_rate_at_true_positive_rate_loss),
objective_kwargs=kwargs,
data_builder=_other_multilabel_data(surrogate_type),
test_object=self)
def testLagrangeMultiplierUpdateDirectionWithMultipleRates(self):
"""Runs Lagrange multiplier test with multiple target rates."""
target_rate = [0.35, 0.65]
for surrogate_type in ['xent', 'hinge']:
kwargs = {'target_rate': target_rate,
'surrogate_type': surrogate_type,
'scope': 'fpr-at-tpr_{}_{}'.format(
'_'.join([str(target) for target in target_rate]),
surrogate_type)}
# True positive rate is a synonym for recall, so we use the
# recall constraint data.
run_lagrange_multiplier_test(
global_objective=(
loss_layers.false_positive_rate_at_true_positive_rate_loss),
objective_kwargs=kwargs,
data_builder=_multilabel_data,
test_object=self)
kwargs['scope'] = 'other-' + kwargs['scope']
run_lagrange_multiplier_test(
global_objective=(
loss_layers.false_positive_rate_at_true_positive_rate_loss),
objective_kwargs=kwargs,
data_builder=_other_multilabel_data(surrogate_type),
test_object=self)
def testEquivalenceBetweenSingleAndEqualMultipleRates(self):
"""Compares single and multiple target rates of the same value.
Checks that using a single target rate and multiple rates with the
same value would result in the same loss value.
"""
num_labels = 2
target_shape = [20, num_labels]
logits = tf.Variable(tf.random_normal(target_shape))
targets = tf.Variable(
tf.to_float(tf.greater(tf.random_uniform(target_shape), 0.7)))
label_priors = tf.constant([0.34], shape=[num_labels])
multi_label_loss, _ = (
loss_layers.false_positive_rate_at_true_positive_rate_loss(
targets, logits, [0.75, 0.75], label_priors=label_priors))
single_label_loss, _ = (
loss_layers.false_positive_rate_at_true_positive_rate_loss(
targets, logits, 0.75, label_priors=label_priors))
with self.test_session() as session:
tf.global_variables_initializer().run()
multi_label_loss_val, single_label_loss_val = session.run(
[multi_label_loss, single_label_loss])
self.assertAllClose(multi_label_loss_val, single_label_loss_val)
def testEquivalenceBetweenSingleAndMultipleRates(self):
"""Compares single and multiple target rates of different values.
Runs false_positive_rate_at_true_positive_rate_loss with multiple target
rates, and runs each label seperately with its own target rate as a
scalar. Validates that the returned loss values are the same.
"""
target_precision = [0.7, 0.9, 0.4]
num_labels = 3
batch_shape = [30, num_labels]
logits = tf.Variable(tf.random_normal(batch_shape))
targets = tf.Variable(
tf.to_float(tf.greater(tf.random_uniform(batch_shape), 0.4)))
label_priors = tf.constant(0.45, shape=[num_labels])
multi_label_loss, _ = (
loss_layers.false_positive_rate_at_true_positive_rate_loss(
targets, logits, target_precision, label_priors=label_priors))
single_label_losses = [
loss_layers.false_positive_rate_at_true_positive_rate_loss(
tf.expand_dims(targets[:, i], -1),
tf.expand_dims(logits[:, i], -1),
target_precision[i],
label_priors=label_priors[i])[0]
for i in range(num_labels)
]
single_label_losses = tf.concat(single_label_losses, 1)
with self.test_session() as session:
tf.global_variables_initializer().run()
multi_label_loss_val, single_label_loss_val = session.run(
[multi_label_loss, single_label_losses])
self.assertAllClose(multi_label_loss_val, single_label_loss_val)
class TruePositiveRateAtFalsePositiveRateTest(tf.test.TestCase):
def testPositivesOnlyLoss(self):
# A special case where the loss should equal the loss on the positive
# examples.
target_rate = numpy.random.uniform()
num_labels = 3
batch_shape = [20, num_labels]
logits = tf.Variable(tf.random_normal(batch_shape))
targets = tf.Variable(
tf.to_float(tf.greater(tf.random_uniform(batch_shape), 0.6)))
label_priors = tf.constant(numpy.random.uniform(size=[num_labels]),
dtype=tf.float32)
xent_loss, _ = loss_layers.true_positive_rate_at_false_positive_rate_loss(
targets, logits, target_rate, label_priors=label_priors,
lambdas_initializer=tf.constant_initializer(0.0))
xent_expected = util.weighted_sigmoid_cross_entropy_with_logits(
targets,
logits,
positive_weights=1.0,
negative_weights=0.0)
hinge_loss, _ = loss_layers.true_positive_rate_at_false_positive_rate_loss(
targets, logits, target_rate, label_priors=label_priors,
lambdas_initializer=tf.constant_initializer(0.0),
surrogate_type='hinge')
hinge_expected = util.weighted_hinge_loss(
targets,
logits,
positive_weights=1.0,
negative_weights=0.0)
with self.test_session():
tf.global_variables_initializer().run()
self.assertAllClose(xent_expected.eval(), xent_loss.eval())
self.assertAllClose(hinge_expected.eval(), hinge_loss.eval())
def testNegativesOnlyLoss(self):
# A special case where the loss should equal the loss on the negative
# examples, minus target_rate * (1 - label_priors) * maybe_log2.
target_rate = numpy.random.uniform()
num_labels = 3
batch_shape = [25, num_labels]
logits = tf.Variable(tf.random_normal(batch_shape))
targets = tf.zeros_like(logits)
label_priors = tf.constant(numpy.random.uniform(size=[num_labels]),
dtype=tf.float32)
xent_loss, _ = loss_layers.true_positive_rate_at_false_positive_rate_loss(
targets, logits, target_rate, label_priors=label_priors)
xent_expected = tf.subtract(
util.weighted_sigmoid_cross_entropy_with_logits(targets,
logits,
positive_weights=0.0,
negative_weights=1.0),
target_rate * (1.0 - label_priors) * numpy.log(2))
hinge_loss, _ = loss_layers.true_positive_rate_at_false_positive_rate_loss(
targets, logits, target_rate, label_priors=label_priors,
surrogate_type='hinge')
hinge_expected = util.weighted_hinge_loss(
targets, logits) - target_rate * (1.0 - label_priors)
with self.test_session():
tf.global_variables_initializer().run()
self.assertAllClose(xent_expected.eval(), xent_loss.eval())
self.assertAllClose(hinge_expected.eval(), hinge_loss.eval())
def testLagrangeMultiplierUpdateDirection(self):
for target_rate in [0.35, 0.65]:
for surrogate_type in ['xent', 'hinge']:
kwargs = {'target_rate': target_rate,
'surrogate_type': surrogate_type,
'scope': 'tpr-at-fpr_{}_{}'.format(target_rate,
surrogate_type)}
run_lagrange_multiplier_test(
global_objective=(
loss_layers.true_positive_rate_at_false_positive_rate_loss),
objective_kwargs=kwargs,
data_builder=_multilabel_data,
test_object=self)
kwargs['scope'] = 'other-' + kwargs['scope']
run_lagrange_multiplier_test(
global_objective=(
loss_layers.true_positive_rate_at_false_positive_rate_loss),
objective_kwargs=kwargs,
data_builder=_other_multilabel_data(surrogate_type),
test_object=self)
def testLagrangeMultiplierUpdateDirectionWithMultipleRates(self):
"""Runs Lagrange multiplier test with multiple target rates."""
target_rate = [0.35, 0.65]
for surrogate_type in ['xent', 'hinge']:
kwargs = {'target_rate': target_rate,
'surrogate_type': surrogate_type,
'scope': 'tpr-at-fpr_{}_{}'.format(
'_'.join([str(target) for target in target_rate]),
surrogate_type)}
run_lagrange_multiplier_test(
global_objective=(
loss_layers.true_positive_rate_at_false_positive_rate_loss),
objective_kwargs=kwargs,
data_builder=_multilabel_data,
test_object=self)
kwargs['scope'] = 'other-' + kwargs['scope']
run_lagrange_multiplier_test(
global_objective=(
loss_layers.true_positive_rate_at_false_positive_rate_loss),
objective_kwargs=kwargs,
data_builder=_other_multilabel_data(surrogate_type),
test_object=self)
def testEquivalenceBetweenSingleAndEqualMultipleRates(self):
"""Compares single and multiple target rates of the same value.
Checks that using a single target rate and multiple rates with the
same value would result in the same loss value.
"""
num_labels = 2
target_shape = [20, num_labels]
logits = tf.Variable(tf.random_normal(target_shape))
targets = tf.Variable(
tf.to_float(tf.greater(tf.random_uniform(target_shape), 0.7)))
label_priors = tf.constant([0.34], shape=[num_labels])
multi_label_loss, _ = (
loss_layers.true_positive_rate_at_false_positive_rate_loss(
targets, logits, [0.75, 0.75], label_priors=label_priors))
single_label_loss, _ = (
loss_layers.true_positive_rate_at_false_positive_rate_loss(
targets, logits, 0.75, label_priors=label_priors))
with self.test_session() as session:
tf.global_variables_initializer().run()
multi_label_loss_val, single_label_loss_val = session.run(
[multi_label_loss, single_label_loss])
self.assertAllClose(multi_label_loss_val, single_label_loss_val)
def testEquivalenceBetweenSingleAndMultipleRates(self):
"""Compares single and multiple target rates of different values.
Runs true_positive_rate_at_false_positive_rate_loss with multiple target
rates, and runs each label seperately with its own target rate as a
scalar. Validates that the returned loss values are the same.
"""
target_precision = [0.7, 0.9, 0.4]
num_labels = 3
batch_shape = [30, num_labels]
logits = tf.Variable(tf.random_normal(batch_shape))
targets = tf.Variable(
tf.to_float(tf.greater(tf.random_uniform(batch_shape), 0.4)))
label_priors = tf.constant(0.45, shape=[num_labels])
multi_label_loss, _ = (
loss_layers.true_positive_rate_at_false_positive_rate_loss(
targets, logits, target_precision, label_priors=label_priors))
single_label_losses = [
loss_layers.true_positive_rate_at_false_positive_rate_loss(
tf.expand_dims(targets[:, i], -1),
tf.expand_dims(logits[:, i], -1),
target_precision[i],
label_priors=label_priors[i])[0]
for i in range(num_labels)
]
single_label_losses = tf.concat(single_label_losses, 1)
with self.test_session() as session:
tf.global_variables_initializer().run()
multi_label_loss_val, single_label_loss_val = session.run(
[multi_label_loss, single_label_losses])
self.assertAllClose(multi_label_loss_val, single_label_loss_val)
class UtilityFunctionsTest(tf.test.TestCase):
def testTrainableDualVariable(self):
# Confirm correct behavior of a trainable dual variable.
x = tf.get_variable('primal', dtype=tf.float32, initializer=2.0)
y_value, y = loss_layers._create_dual_variable(
'dual', shape=None, dtype=tf.float32, initializer=1.0, collections=None,
trainable=True, dual_rate_factor=0.3)
optimizer = tf.train.GradientDescentOptimizer(learning_rate=1.0)
update = optimizer.minimize(0.5 * tf.square(x - y_value))
with self.test_session():
tf.global_variables_initializer().run()
update.run()
self.assertAllClose(0.7, y.eval())
def testUntrainableDualVariable(self):
# Confirm correct behavior of dual variable which is not trainable.
x = tf.get_variable('primal', dtype=tf.float32, initializer=-2.0)
y_value, y = loss_layers._create_dual_variable(
'dual', shape=None, dtype=tf.float32, initializer=1.0, collections=None,
trainable=False, dual_rate_factor=0.8)