aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/contrib/distributions/python/kernel_tests/bijectors/sinh_arcsinh_bijector_test.py
blob: 45760a29ee42835da69ef63803ccec7ce82a5a8f (plain)
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
# Copyright 2017 The TensorFlow 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 SinhArcsinh Bijector."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np

# pylint: disable=g-importing-member
from tensorflow.contrib.distributions.python.ops.bijectors.sinh_arcsinh import SinhArcsinh
from tensorflow.python.ops.distributions.bijector_test_util import assert_bijective_and_finite
from tensorflow.python.ops.distributions.bijector_test_util import assert_scalar_congruency
from tensorflow.python.platform import test

# pylint: enable=g-importing-member


class SinhArcsinhBijectorTest(test.TestCase):
  """Tests correctness of the power transformation."""

  def testBijectorVersusNumpyRewriteOfBasicFunctions(self):
    with self.test_session():
      skewness = 0.2
      tailweight = 2.0
      bijector = SinhArcsinh(
          skewness=skewness,
          tailweight=tailweight,
          validate_args=True)
      self.assertEqual("SinhArcsinh", bijector.name)
      x = np.array([[[-2.01], [2.], [1e-4]]]).astype(np.float32)
      y = np.sinh((np.arcsinh(x) + skewness) * tailweight)
      self.assertAllClose(y, bijector.forward(x).eval())
      self.assertAllClose(x, bijector.inverse(y).eval())
      self.assertAllClose(
          np.sum(
              np.log(np.cosh(np.arcsinh(y) / tailweight - skewness)) -
              np.log(tailweight) - np.log(np.sqrt(y**2 + 1)),
              axis=-1),
          bijector.inverse_log_det_jacobian(y, event_ndims=1).eval())
      self.assertAllClose(
          -bijector.inverse_log_det_jacobian(y, event_ndims=1).eval(),
          bijector.forward_log_det_jacobian(x, event_ndims=1).eval(),
          rtol=1e-4,
          atol=0.)

  def testLargerTailWeightPutsMoreWeightInTails(self):
    with self.test_session():
      # Will broadcast together to shape [3, 2].
      x = [-1., 1.]
      tailweight = [[0.5], [1.0], [2.0]]
      bijector = SinhArcsinh(tailweight=tailweight, validate_args=True)
      y = bijector.forward(x).eval()

      # x = -1, 1 should be mapped to points symmetric about 0
      self.assertAllClose(y[:, 0], -1. * y[:, 1])

      # forward(1) should increase as tailweight increases, since higher
      # tailweight should map 1 to a larger number.
      forward_1 = y[:, 1]  # The positive values of y.
      self.assertLess(forward_1[0], forward_1[1])
      self.assertLess(forward_1[1], forward_1[2])

  def testSkew(self):
    with self.test_session():
      # Will broadcast together to shape [3, 2].
      x = [-1., 1.]
      skewness = [[-1.], [0.], [1.]]
      bijector = SinhArcsinh(skewness=skewness, validate_args=True)
      y = bijector.forward(x).eval()

      # For skew < 0, |forward(-1)| > |forward(1)|
      self.assertGreater(np.abs(y[0, 0]), np.abs(y[0, 1]))

      # For skew = 0, |forward(-1)| = |forward(1)|
      self.assertAllClose(np.abs(y[1, 0]), np.abs(y[1, 1]))

      # For skew > 0, |forward(-1)| < |forward(1)|
      self.assertLess(np.abs(y[2, 0]), np.abs(y[2, 1]))

  def testScalarCongruencySkewness1Tailweight0p5(self):
    with self.test_session():
      bijector = SinhArcsinh(skewness=1.0, tailweight=0.5, validate_args=True)
      assert_scalar_congruency(bijector, lower_x=-2., upper_x=2.0, rtol=0.05)

  def testScalarCongruencySkewnessNeg1Tailweight1p5(self):
    with self.test_session():
      bijector = SinhArcsinh(skewness=-1.0, tailweight=1.5, validate_args=True)
      assert_scalar_congruency(bijector, lower_x=-2., upper_x=2.0, rtol=0.05)

  def testBijectiveAndFiniteSkewnessNeg1Tailweight0p5(self):
    with self.test_session():
      bijector = SinhArcsinh(skewness=-1., tailweight=0.5, validate_args=True)
      x = np.concatenate((-np.logspace(-2, 10, 1000), [0], np.logspace(
          -2, 10, 1000))).astype(np.float32)
      assert_bijective_and_finite(bijector, x, x, event_ndims=0, rtol=1e-3)

  def testBijectiveAndFiniteSkewness1Tailweight3(self):
    with self.test_session():
      bijector = SinhArcsinh(skewness=1., tailweight=3., validate_args=True)
      x = np.concatenate((-np.logspace(-2, 5, 1000), [0], np.logspace(
          -2, 5, 1000))).astype(np.float32)
      assert_bijective_and_finite(
          bijector, x, x, event_ndims=0, rtol=1e-3)

  def testBijectorEndpoints(self):
    with self.test_session():
      for dtype in (np.float32, np.float64):
        bijector = SinhArcsinh(
            skewness=dtype(0.), tailweight=dtype(1.), validate_args=True)
        bounds = np.array(
            [np.finfo(dtype).min, np.finfo(dtype).max], dtype=dtype)
        # Note that the above bijector is the identity bijector. Hence, the
        # log_det_jacobian will be 0. Because of this we use atol.
        assert_bijective_and_finite(
            bijector, bounds, bounds, event_ndims=0, atol=2e-6)

  def testBijectorOverRange(self):
    with self.test_session():
      for dtype in (np.float32, np.float64):
        skewness = np.array([1.2, 5.], dtype=dtype)
        tailweight = np.array([2., 10.], dtype=dtype)
        # The inverse will be defined up to where sinh is valid, which is
        # arcsinh(np.finfo(dtype).max).
        log_boundary = np.log(
            np.sinh(np.arcsinh(np.finfo(dtype).max) / tailweight - skewness))
        x = np.array([
            np.logspace(-2, log_boundary[0], base=np.e, num=1000),
            np.logspace(-2, log_boundary[1], base=np.e, num=1000)
        ], dtype=dtype)
        # Ensure broadcasting works.
        x = np.swapaxes(x, 0, 1)

        y = np.sinh((np.arcsinh(x) + skewness) * tailweight)
        bijector = SinhArcsinh(
            skewness=skewness, tailweight=tailweight, validate_args=True)

        self.assertAllClose(y, bijector.forward(x).eval(), rtol=1e-4, atol=0.)
        self.assertAllClose(x, bijector.inverse(y).eval(), rtol=1e-4, atol=0.)

        # Do the numpy calculation in float128 to avoid inf/nan.
        y_float128 = np.float128(y)
        self.assertAllClose(
            np.log(np.cosh(
                np.arcsinh(y_float128) / tailweight - skewness) / np.sqrt(
                    y_float128**2 + 1)) -
            np.log(tailweight),
            bijector.inverse_log_det_jacobian(y, event_ndims=0).eval(),
            rtol=1e-4,
            atol=0.)
        self.assertAllClose(
            -bijector.inverse_log_det_jacobian(y, event_ndims=0).eval(),
            bijector.forward_log_det_jacobian(x, event_ndims=0).eval(),
            rtol=1e-4,
            atol=0.)

  def testZeroTailweightRaises(self):
    with self.test_session():
      with self.assertRaisesOpError("not positive"):
        SinhArcsinh(tailweight=0., validate_args=True).forward(1.0).eval()

  def testDefaultDtypeIsFloat32(self):
    with self.test_session():
      bijector = SinhArcsinh()
      self.assertEqual(bijector.tailweight.dtype, np.float32)
      self.assertEqual(bijector.skewness.dtype, np.float32)


if __name__ == "__main__":
  test.main()