google-research
54 строки · 1.8 Кб
1# coding=utf-8
2# Copyright 2024 The Google Research Authors.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16"""Tests for uq_utils."""
17
18from __future__ import absolute_import19from __future__ import division20from __future__ import print_function21
22import numpy as np23import scipy.special24import tensorflow.compat.v2 as tf25
26from uq_benchmark_2019 import uq_utils27
28
29class UqUtilsTest(tf.test.TestCase):30
31def test_np_inverse_softmax(self):32batch_size, nclasses = [4, 3]33logits_orig = np.random.rand(batch_size, nclasses)34probs_orig = scipy.special.softmax(logits_orig, axis=-1)35logits_new = uq_utils.np_inverse_softmax(probs_orig)36probs_new = scipy.special.softmax(logits_new, axis=-1)37self.assertAllClose(probs_orig, probs_new)38
39def test_np_soften_probabilities(self):40shape = [12, 5]41logits = np.random.uniform(0, 1, size=shape)42probs = scipy.special.softmax(logits, axis=-1)43probs[0] = 044probs[0, 0] = 145soft_probs = uq_utils.np_soften_probabilities(probs, epsilon=1e-8)46self.assertAllClose(probs[1:], soft_probs[1:])47self.assertAllLess(soft_probs, 1)48self.assertAllGreater(soft_probs, 0)49self.assertAllClose(np.ones(shape[0]), soft_probs.sum(1), atol=1e-10)50
51
52if __name__ == '__main__':53tf.enable_v2_behavior()54tf.test.main()55