-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
cumsum.py
117 lines (97 loc) · 3.46 KB
/
cumsum.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
# Copyright 2018 The TensorFlow Probability 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.
# ============================================================================
"""Cumsum bijector."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow.compat.v2 as tf
from tensorflow_probability.python.bijectors import bijector
from tensorflow_probability.python.internal import prefer_static
__all__ = [
'Cumsum',
]
class Cumsum(bijector.Bijector):
"""Computes the cumulative sum of a tensor along a specified axis.
If `axis` is not provided, the default uses the rightmost dimension, i.e.,
axis=-1.
#### Example
```python
x = tfb.Cumsum()
x.forward([[1., 1.],
[2., 2.],
[3., 3.]])
# ==> [[1., 2.],
[2., 4.],
[3., 6.]]
x = tfb.Cumsum(axis=-2)
x.forward([[1., 1.],
[2., 2.],
[3., 3.]])
# ==> [[1., 1.],
[3., 3.],
[6., 6.]]
```
"""
def __init__(self, axis=-1, validate_args=False, name='cumsum'):
"""Instantiates the `Cumsum` bijector.
Args:
axis: Negative Python `int` indicating the axis along which to compute the
cumulative sum. Note that positive (and zero) values are not supported.
validate_args: Python `bool` indicating whether arguments should be
checked for correctness.
name: Python `str` name given to ops managed by this object.
Raises:
TypeError: if `axis` is not an `int`.
ValueError: if `axis` is not negative.
"""
parameters = dict(locals())
with tf.name_scope(name) as name:
if not isinstance(axis, int):
raise TypeError(
'Argument `axis` is not an `int` type; got {}'.format(axis))
if axis >= 0:
raise ValueError(
'Argument `axis` must be negative; got {}'.format(axis))
self._axis = axis
super(Cumsum, self).__init__(
is_constant_jacobian=True,
# Positive because we verify `axis < 0`.
forward_min_event_ndims=-axis,
validate_args=validate_args,
parameters=parameters,
name=name)
@property
def axis(self):
"""Returns the axis over which this `Bijector` computes the cumsum."""
return self._axis
def _forward(self, x):
return tf.cumsum(x, axis=self.axis)
def _inverse(self, y):
ndims = prefer_static.rank(y)
shifted_y = tf.pad(
tf.slice(
y, tf.zeros(ndims, dtype=tf.int32),
prefer_static.shape(y) -
tf.one_hot(ndims + self.axis, ndims, dtype=tf.int32)
), # Remove the last entry of y in the chosen dimension.
paddings=tf.one_hot(
tf.one_hot(ndims + self.axis, ndims, on_value=0, off_value=-1),
2,
dtype=tf.int32
) # Insert zeros at the beginning of the chosen dimension.
)
return y - shifted_y
def _forward_log_det_jacobian(self, x):
return tf.constant(0., x.dtype)