gumbel.py 7.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# Copyright (c) 2022 PaddlePaddle 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.

import math
16 17
import numbers

18 19
import numpy as np

20
import paddle
21
from paddle.distribution.transformed_distribution import TransformedDistribution
22
from paddle.fluid import framework
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


class Gumbel(TransformedDistribution):
    r"""The Gumbel distribution with location `loc` and `scale` parameters.

    Mathematical details

    The probability density function (pdf) is

    .. math::

        pdf(x; mu, sigma) = exp(-(x - mu) / sigma - exp(-(x - mu) / sigma)) / sigma


    In the above equation:

    * :math:`loc = \mu`: is the mean.
    * :math:`scale = \sigma`: is the std.

    Args:
        loc(int|float|tensor): The mean of gumbel distribution.The data type is int, float, tensor.
        scale(int|float|tensor): The std of gumbel distribution.The data type is int, float, tensor.

    Examples:
        .. code-block:: python

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
            >>> import paddle
            >>> from paddle.distribution.gumbel import Gumbel

            >>> # Gumbel distributed with loc=0, scale=1
            >>> dist = Gumbel(paddle.full([1], 0.0), paddle.full([1], 1.0))

            >>> # doctest: +SKIP
            >>> print(dist.sample([2]))
            Tensor(shape=[2, 1], dtype=float32, place=Place(cpu), stop_gradient=True,
            [[0.40484068],
            [3.19400501]])

            >>> print(dist.rsample([2]))
            Tensor(shape=[2, 1], dtype=float32, place=Place(cpu), stop_gradient=True,
            [[-0.95093185],
            [ 0.32422572]])

            >>> # doctest: -SKIP
            >>> value = paddle.full([1], 0.5)
            >>> print(dist.prob(value))
            Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=True,
            [0.33070430])

            >>> print(dist.log_prob(value))
            Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=True,
            [-1.10653067])

            >>> print(dist.cdf(value))
            Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=True,
            [0.54523921])

            >>> print(dist.entropy())
            Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=True,
            [1.57721567])
83 84 85 86 87
    """

    def __init__(self, loc, scale):
        if not isinstance(loc, (numbers.Real, framework.Variable)):
            raise TypeError(
88 89
                f"Expected type of loc is Real|Variable, but got {type(loc)}"
            )
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
        if not isinstance(scale, (numbers.Real, framework.Variable)):
            raise TypeError(
                f"Expected type of scale is Real|Variable, but got {type(scale)}"
            )

        if isinstance(loc, numbers.Real):
            loc = paddle.full(shape=(), fill_value=loc)

        if isinstance(scale, numbers.Real):
            scale = paddle.full(shape=(), fill_value=scale)

        if loc.shape != scale.shape:
            self.loc, self.scale = paddle.broadcast_tensors([loc, scale])
        else:
            self.loc, self.scale = loc, scale

        finfo = np.finfo(dtype='float32')
        self.base_dist = paddle.distribution.Uniform(
            paddle.full_like(self.loc, float(finfo.tiny)),
109 110
            paddle.full_like(self.loc, float(1 - finfo.eps)),
        )
111 112 113

        self.transforms = ()

114
        super().__init__(self.base_dist, self.transforms)
115 116 117

    @property
    def mean(self):
118
        r"""Mean of distribution
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139

        The mean is

        .. math::

            mean = \mu + \sigma * γ

        In the above equation:

        * :math:`loc = \mu`: is the location parameter.
        * :math:`scale = \sigma`: is the scale parameter.
        * :math:`γ`: is the euler's constant.

        Returns:
            Tensor: mean value.

        """
        return self.loc + self.scale * np.euler_gamma

    @property
    def variance(self):
140
        r"""Variance of distribution.
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155

        The variance is

        .. math::

            variance = \sigma^2 * \pi^2 / 6

        In the above equation:

        * :math:`scale = \sigma`: is the scale parameter.

        Returns:
            Tensor: The variance value.

        """
156 157 158 159 160
        temp = paddle.full(
            shape=self.loc.shape,
            fill_value=math.pi * math.pi,
            dtype=self.scale.dtype,
        )
161 162 163 164 165

        return paddle.pow(self.scale, 2) * temp / 6

    @property
    def stddev(self):
166
        r"""Standard deviation of distribution
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

        The standard deviation is

        .. math::

            stddev = \sqrt{\sigma^2 * \pi^2 / 6}

        In the above equation:
        * :math:`scale = \sigma`: is the scale parameter.

        Returns:
            Tensor: std value
        """
        return paddle.sqrt(self.variance)

    def prob(self, value):
        """Probability density/mass function

        Args:
            value (Tensor): The input tensor.

        Returns:
            Tensor: probability.The data type is same with value.

        """
        y = (self.loc - value) / self.scale

        return paddle.exp(y - paddle.exp(y)) / self.scale

    def log_prob(self, value):
        """Log probability density/mass function.

        Args:
            value (Tensor): The input tensor.

        Returns:
            Tensor: log probability.The data type is same with value.

        """
        return paddle.log(self.prob(value))

    def cdf(self, value):
        """Cumulative distribution function.
        Args:
            value (Tensor): value to be evaluated.

        Returns:
            Tensor: cumulative probability of value.

        """
        return paddle.exp(-paddle.exp(-(value - self.loc) / self.scale))

    def entropy(self):
        """Entropy of Gumbel distribution.

        Returns:
            Entropy of distribution.

        """
        return paddle.log(self.scale) + 1 + np.euler_gamma

    def sample(self, shape):
        """Sample from ``Gumbel``.

        Args:
            shape (Sequence[int], optional): The sample shape. Defaults to ().

        Returns:
            Tensor: A tensor with prepended dimensions shape.The data type is float32.

        """
        with paddle.no_grad():
            return self.rsample(shape)

    def rsample(self, shape):
        """reparameterized sample
        Args:
            shape (Sequence[int]): 1D `int32`. Shape of the generated samples.

        Returns:
            Tensor: A tensor with prepended dimensions shape.The data type is float32.

        """
        exp_trans = paddle.distribution.ExpTransform()
        affine_trans_1 = paddle.distribution.AffineTransform(
252 253 254 255 256
            paddle.full(
                shape=self.scale.shape, fill_value=0, dtype=self.loc.dtype
            ),
            -paddle.ones_like(self.scale),
        )
257
        affine_trans_2 = paddle.distribution.AffineTransform(
258 259
            self.loc, -self.scale
        )
260 261 262 263

        return affine_trans_2.forward(
            exp_trans.inverse(
                affine_trans_1.forward(
264 265 266 267
                    exp_trans.inverse(self._base.sample(shape))
                )
            )
        )