normal.py 11.6 KB
Newer Older
1
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
2
#
3 4 5
# 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
6
#
7
#     http://www.apache.org/licenses/LICENSE-2.0
8
#
9 10 11 12 13 14 15 16 17 18
# 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
import warnings

import numpy as np
19
import paddle
20
from paddle import _C_ops, _legacy_C_ops
21 22 23 24 25 26 27 28
from paddle.distribution import distribution
from paddle.fluid import core
from paddle.fluid.data_feeder import (check_dtype, check_type,
                                      check_variable_and_dtype, convert_dtype)
from paddle.fluid.framework import _non_static_mode, in_dygraph_mode
from paddle.fluid.layers import (control_flow, elementwise_add, elementwise_div,
                                 elementwise_mul, elementwise_sub, nn, ops,
                                 tensor)
29 30 31 32
try:
    from collections.abc import Iterable
except:
    from collections import Iterable
33 34


35
class Normal(distribution.Distribution):
36 37 38 39 40 41 42 43
    r"""The Normal distribution with location `loc` and `scale` parameters.

    Mathematical details

    The probability density function (pdf) is

    .. math::

44
        pdf(x; \mu, \sigma) = \frac{1}{Z}e^{\frac {-0.5 (x - \mu)^2}  {\sigma^2} }
45 46 47 48 49 50 51 52 53 54 55 56

    .. math::

        Z = (2 \pi \sigma^2)^{0.5}

    In the above equation:

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

    Args:
57 58
        loc(int|float|list|tuple|numpy.ndarray|Tensor): The mean of normal distribution.The data type is float32 and float64.
        scale(int|float|list|tuple|numpy.ndarray|Tensor): The std of normal distribution.The data type is float32 and float64.
59 60 61 62
        name(str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.

    Examples:
        .. code-block:: python
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
            import paddle
            from paddle.distribution import Normal

            # Define a single scalar Normal distribution.
            dist = Normal(loc=0., scale=3.)
            # Define a batch of two scalar valued Normals.
            # The first has mean 1 and standard deviation 11, the second 2 and 22.
            dist = Normal(loc=[1., 2.], scale=[11., 22.])
            # Get 3 samples, returning a 3 x 2 tensor.
            dist.sample([3])

            # Define a batch of two scalar valued Normals.
            # Both have mean 1, but different standard deviations.
            dist = Normal(loc=1., scale=[11., 22.])

            # Complete example
            value_tensor = paddle.to_tensor([0.8], dtype="float32")

            normal_a = Normal([0.], [1.])
            normal_b = Normal([0.5], [2.])
            sample = normal_a.sample([2])
            # a random tensor created by normal distribution with shape: [2, 1]
            entropy = normal_a.entropy()
            # [1.4189385] with shape: [1]
            lp = normal_a.log_prob(value_tensor)
            # [-1.2389386] with shape: [1]
            p = normal_a.probs(value_tensor)
            # [0.28969154] with shape: [1]
            kl = normal_a.kl_divergence(normal_b)
            # [0.34939718] with shape: [1]
94 95 96
    """

    def __init__(self, loc, scale, name=None):
J
Jiabin Yang 已提交
97
        if not _non_static_mode():
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
            check_type(loc, 'loc',
                       (int, float, np.ndarray, tensor.Variable, list, tuple),
                       'Normal')
            check_type(scale, 'scale',
                       (int, float, np.ndarray, tensor.Variable, list, tuple),
                       'Normal')

        self.batch_size_unknown = False
        self.all_arg_is_float = False
        self.name = name if name is not None else 'Normal'
        self.dtype = 'float32'

        if isinstance(loc, int):
            loc = float(loc)
        if isinstance(scale, int):
            scale = float(scale)

        if self._validate_args(loc, scale):
            self.batch_size_unknown = True
            self.loc = loc
            self.scale = scale
            self.dtype = convert_dtype(loc.dtype)
        else:
            if isinstance(loc, float) and isinstance(scale, float):
                self.all_arg_is_float = True
123 124
            if isinstance(loc, np.ndarray) and str(
                    loc.dtype) in ['float32', 'float64']:
125
                self.dtype = loc.dtype
126 127
            elif isinstance(scale, np.ndarray) and str(
                    scale.dtype) in ['float32', 'float64']:
128 129 130 131 132 133
                self.dtype = scale.dtype
            # pylint: disable=unbalanced-tuple-unpacking
            self.loc, self.scale = self._to_tensor(loc, scale)
            if self.dtype != convert_dtype(self.loc.dtype):
                self.loc = tensor.cast(self.loc, dtype=self.dtype)
                self.scale = tensor.cast(self.scale, dtype=self.dtype)
134
        super(Normal, self).__init__(self.loc.shape)
135

136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
    @property
    def mean(self):
        """Mean of multinomial distribuion.

        Returns:
            Tensor: mean value.
        """
        return self.loc

    @property
    def variance(self):
        """Variance of lognormal distribution.

        Returns:
            Tensor: variance value.
        """
        return self.scale.pow(2)

    def sample(self, shape=(), seed=0):
155 156 157
        """Generate samples of the specified shape.

        Args:
158
            shape (Sequence[int], optional): Shape of the generated samples.
159
            seed (int): Python integer number.
160 161

        Returns:
162
            Tensor, A tensor with prepended dimensions shape.The data type is float32.
163 164

        """
165 166 167
        if not isinstance(shape, Iterable):
            raise TypeError('sample shape must be Iterable object.')

J
Jiabin Yang 已提交
168
        if not _non_static_mode():
169 170
            check_type(seed, 'seed', (int), 'sample')

171
        shape = list(shape)
172 173 174 175 176 177 178 179 180
        batch_shape = list((self.loc + self.scale).shape)
        name = self.name + '_sample'

        if self.batch_size_unknown:
            output_shape = shape + batch_shape
            zero_tmp = tensor.fill_constant_batch_size_like(
                self.loc + self.scale, batch_shape + shape, self.dtype, 0.)
            zero_tmp_reshape = nn.reshape(zero_tmp, output_shape)
            zero_tmp_shape = nn.shape(zero_tmp_reshape)
181 182 183 184 185
            normal_random_tmp = nn.gaussian_random(zero_tmp_shape,
                                                   mean=0.,
                                                   std=1.,
                                                   seed=seed,
                                                   dtype=self.dtype)
186 187 188 189 190
            output = normal_random_tmp * (zero_tmp_reshape + self.scale)
            output = elementwise_add(output, self.loc, name=name)
            return output
        else:
            output_shape = shape + batch_shape
191 192 193
            output = nn.gaussian_random(
                output_shape, mean=0., std=1., seed=seed, dtype=self.dtype) * (
                    tensor.zeros(output_shape, dtype=self.dtype) + self.scale)
194 195 196 197 198 199
            output = elementwise_add(output, self.loc, name=name)
            if self.all_arg_is_float:
                return nn.reshape(output, shape, name=name)
            else:
                return output

200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
    def rsample(self, shape=()):
        """Generate reparameterized samples of the specified shape.

        Args:
          shape (Sequence[int], optional): Shape of the generated samples.

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

        """
        if not isinstance(shape, Iterable):
            raise TypeError('sample shape must be Iterable object.')

        shape = self._extend_shape(tuple(shape))
        eps = paddle.normal(shape=shape)
        return (self.loc + eps * self.scale)

217 218 219 220 221 222 223
    def entropy(self):
        r"""Shannon entropy in nats.

        The entropy is

        .. math::

224
            entropy(\sigma) = 0.5 \log (2 \pi e \sigma^2)
225 226 227 228 229 230

        In the above equation:

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

        Returns:
231
            Tensor, Shannon entropy of normal distribution.The data type is float32.
232 233 234 235

        """
        name = self.name + '_entropy'
        batch_shape = list((self.loc + self.scale).shape)
236 237 238 239 240 241 242
        zero_tmp = tensor.fill_constant_batch_size_like(self.loc + self.scale,
                                                        batch_shape, self.dtype,
                                                        0.)
        return elementwise_add(0.5 + zero_tmp,
                               0.5 * math.log(2 * math.pi) + nn.log(
                                   (self.scale + zero_tmp)),
                               name=name)
243 244 245 246 247 248 249 250

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

        Args:
          value (Tensor): The input tensor.

        Returns:
251
          Tensor: log probability.The data type is same with :attr:`value` .
252 253 254 255 256 257 258

        """
        name = self.name + '_log_prob'
        value = self._check_values_dtype_in_probs(self.loc, value)

        var = self.scale * self.scale
        log_scale = nn.log(self.scale)
259 260 261 262
        return elementwise_sub(-1. * ((value - self.loc) * (value - self.loc)) /
                               (2. * var),
                               log_scale + math.log(math.sqrt(2. * math.pi)),
                               name=name)
263 264 265 266 267

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

        Args:
268
            value (Tensor): The input tensor.
269 270

        Returns:
271
            Tensor, probability. The data type is same with :attr:`value` .
272 273 274 275 276 277

        """
        name = self.name + '_probs'
        value = self._check_values_dtype_in_probs(self.loc, value)

        var = self.scale * self.scale
278 279 280 281
        return elementwise_div(ops.exp(-1. * ((value - self.loc) *
                                              (value - self.loc)) / (2. * var)),
                               (math.sqrt(2 * math.pi) * self.scale),
                               name=name)
282 283 284 285 286 287 288 289

    def kl_divergence(self, other):
        r"""The KL-divergence between two normal distributions.

        The probability density function (pdf) is

        .. math::

290
            KL\_divergence(\mu_0, \sigma_0; \mu_1, \sigma_1) = 0.5 (ratio^2 + (\frac{diff}{\sigma_1})^2 - 1 - 2 \ln {ratio})
291 292 293

        .. math::

294
            ratio = \frac{\sigma_0}{\sigma_1}
295

296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
        .. math::

            diff = \mu_1 - \mu_0

        In the above equation:

        * :math:`loc = \mu_0`: is the mean of current Normal distribution.
        * :math:`scale = \sigma_0`: is the std of current Normal distribution.
        * :math:`loc = \mu_1`: is the mean of other Normal distribution.
        * :math:`scale = \sigma_1`: is the std of other Normal distribution.
        * :math:`ratio`: is the ratio of scales.
        * :math:`diff`: is the difference between means.

        Args:
            other (Normal): instance of Normal.

        Returns:
313
            Tensor, kl-divergence between two normal distributions.The data type is float32.
314 315

        """
J
Jiabin Yang 已提交
316
        if not _non_static_mode():
317 318 319 320 321 322 323
            check_type(other, 'other', Normal, 'kl_divergence')

        name = self.name + '_kl_divergence'
        var_ratio = self.scale / other.scale
        var_ratio = (var_ratio * var_ratio)
        t1 = (self.loc - other.loc) / other.scale
        t1 = (t1 * t1)
324 325 326
        return elementwise_add(0.5 * var_ratio,
                               0.5 * (t1 - 1. - nn.log(var_ratio)),
                               name=name)