google-research
60 строк · 2.2 Кб
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 the sinkhorn module."""
17
18from __future__ import absolute_import
19from __future__ import division
20from __future__ import print_function
21
22from absl.testing import absltest
23import jax.numpy as np
24
25from soft_sort.jax import sinkhorn
26
27
28class SinkhornTestCase(absltest.TestCase):
29"""Test case for Sinkhorn1D."""
30
31def setUp(self):
32super(SinkhornTestCase, self).setUp()
33self.no_decay = dict(
34epsilon_0=1e-3, epsilon_decay=1.00, max_iterations=5000)
35self.decay = dict(
36epsilon_0=1e-1, epsilon_decay=0.95, max_iterations=5000)
37self.x = np.array([[0.2, -0.5, 0.4, 0.44, -0.9, 0.9]])
38self.y = 1 / self.x.shape[1] * np.cumsum(np.ones(self.x.shape), axis=-1)
39self.a = 1.0 / self.x.shape[1] * np.ones(self.x.shape)
40self.b = 1.0 / self.y.shape[1] * np.ones(self.y.shape)
41
42def test_sinkhorn(self):
43"""Tests that the __call__ methods returns transport maps."""
44f, g, eps, cost, _, iterations = sinkhorn.sinkhorn_iterations(
45self.x, self.y, self.a, self.b, **self.decay)
46p = sinkhorn.transport(cost, f, g, eps)
47self.assertTupleEqual(p.shape, self.x.shape + (self.y.shape[1],))
48self.assertLessEqual(iterations, self.decay['max_iterations'])
49
50def test_decay(self):
51"""Tests that applying the epsilon decay scheme speeds up convergence."""
52decay_iterations = sinkhorn.sinkhorn_iterations(
53self.x, self.y, self.a, self.b, **self.decay)[-1]
54no_decay_iterations = sinkhorn.sinkhorn_iterations(
55self.x, self.y, self.a, self.b, **self.no_decay)[-1]
56self.assertLess(decay_iterations, no_decay_iterations)
57
58
59if __name__ == '__main__':
60absltest.main()
61