distribution.py 33.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#   Copyright (c) 2020 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.

# TODO: define the distribution functions 
# __all__ = ['Categorical',
#            'MultivariateNormalDiag',
#            'Normal',
#            'sampling_id',
#            'Uniform']
21 22 23 24 25 26 27

from __future__ import print_function

from .fluid.layers import control_flow
from .fluid.layers import tensor
from .fluid.layers import ops
from .fluid.layers import nn
28
from .fluid.layers import elementwise_mul, elementwise_div, elementwise_add, elementwise_sub
29
from .fluid import core
30
from .fluid.framework import in_dygraph_mode
P
pangyoki 已提交
31
from .tensor import arange, gather_nd, concat, multinomial
32 33 34 35 36
import math
import numpy as np
import warnings

from .fluid.data_feeder import convert_dtype, check_variable_and_dtype, check_type, check_dtype
W
wanghuancoder 已提交
37
from paddle import _C_ops
38

P
pangyoki 已提交
39
__all__ = ['Distribution', 'Uniform', 'Normal', 'Categorical']
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


class Distribution(object):
    """
    The abstract base class for probability distributions. Functions are 
    implemented in specific distributions.
    """

    def __init__(self):
        super(Distribution, self).__init__()

    def sample(self):
        """Sampling from the distribution."""
        raise NotImplementedError

    def entropy(self):
        """The entropy of the distribution."""
        raise NotImplementedError

    def kl_divergence(self, other):
        """The KL-divergence between self distributions and other."""
        raise NotImplementedError

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

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

    def _validate_args(self, *args):
        """
        Argument validation for distribution args
        Args:
            value (float, list, numpy.ndarray, Tensor)
        Raises
            ValueError: if one argument is Tensor, all arguments should be Tensor
        """
        is_variable = False
        is_number = False
        for arg in args:
            if isinstance(arg, tensor.Variable):
                is_variable = True
            else:
                is_number = True

        if is_variable and is_number:
            raise ValueError(
                'if one argument is Tensor, all arguments should be Tensor')

        return is_variable

93
    def _to_tensor(self, *args):
94 95 96 97 98 99 100 101 102 103 104 105 106 107
        """
        Argument convert args to Tensor

        Args:
            value (float, list, numpy.ndarray, Tensor)
        Returns:
            Tensor of args.
        """
        numpy_args = []
        variable_args = []
        tmp = 0.

        for arg in args:
            if isinstance(arg, float):
108
                arg = [arg]
109
            if not isinstance(arg, (list, tuple, np.ndarray, tensor.Variable)):
110 111 112 113
                raise TypeError(
                    "Type of input args must be float, list, numpy.ndarray or Tensor, but received type {}".
                    format(type(arg)))

114 115
            arg_np = np.array(arg)
            arg_dtype = arg_np.dtype
116 117 118 119 120 121 122
            if str(arg_dtype) != 'float32':
                if str(arg_dtype) != 'float64':
                    # "assign" op doesn't support float64. if dtype is float64, float32 variable will be generated
                    #  and converted to float64 later using "cast".
                    warnings.warn(
                        "data type of argument only support float32 and float64, your argument will be convert to float32."
                    )
123
                arg_np = arg_np.astype('float32')
124
            # tmp is used to support broadcast, it summarizes shapes of all the args and get the mixed shape.
125 126 127 128 129 130 131 132 133 134 135 136
            tmp = tmp + arg_np
            numpy_args.append(arg_np)

        dtype = tmp.dtype
        for arg in numpy_args:
            arg_broadcasted, _ = np.broadcast_arrays(arg, tmp)
            arg_variable = tensor.create_tensor(dtype=dtype)
            tensor.assign(arg_broadcasted, arg_variable)
            variable_args.append(arg_variable)

        return tuple(variable_args)

137 138 139 140 141 142
    def _check_values_dtype_in_probs(self, param, value):
        """
        Log_prob and probs methods have input ``value``, if value's dtype is different from param,
        convert value's dtype to be consistent with param's dtype.

        Args:
143
            param (Tensor): low and high in Uniform class, loc and scale in Normal class.
144 145 146 147 148 149 150 151 152 153 154
            value (Tensor): The input tensor.

        Returns:
            value (Tensor): Change value's dtype if value's dtype is different from param.
        """
        if in_dygraph_mode():
            if value.dtype != param.dtype and convert_dtype(
                    value.dtype) in ['float32', 'float64']:
                warnings.warn(
                    "dtype of input 'value' needs to be the same as parameters of distribution class. dtype of 'value' will be converted."
                )
W
wanghuancoder 已提交
155 156
                return _C_ops.cast(value, 'in_dtype', value.dtype, 'out_dtype',
                                   param.dtype)
157
            return value
158 159 160 161 162 163 164 165 166 167

        check_variable_and_dtype(value, 'value', ['float32', 'float64'],
                                 'log_prob')
        if value.dtype != param.dtype:
            warnings.warn(
                "dtype of input 'value' needs to be the same as parameters of distribution class. dtype of 'value' will be converted."
            )
            return tensor.cast(value, dtype=param.dtype)
        return value

168 169

class Uniform(Distribution):
170
    r"""Uniform distribution with `low` and `high` parameters.
171 172 173

    Mathematical Details

174
    The probability density function (pdf) is
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193

    .. math::

        pdf(x; a, b) = \\frac{1}{Z}, \ a <=x <b

    .. math::

        Z = b - a

    In the above equation:

    * :math:`low = a`,
    * :math:`high = b`,
    * :math:`Z`: is the normalizing constant.

    The parameters `low` and `high` must be shaped in a way that supports
    [broadcasting](https://www.paddlepaddle.org.cn/documentation/docs/en/develop/beginners_guide/basic_concept/broadcasting_en.html) (e.g., `high - low` is a valid operation).

    Args:
194 195
        low(int|float|list|tuple|numpy.ndarray|Tensor): The lower boundary of uniform distribution.The data type is int, float, list, numpy.ndarray or Tensor
        high(int|float|list|tuple|numpy.ndarray|Tensor): The higher boundary of uniform distribution.The data type is int, float, list, numpy.ndarray or Tensor
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
        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

          import paddle
          from paddle.distribution import Uniform

          # Without broadcasting, a single uniform distribution [3, 4]:
          u1 = Uniform(low=3.0, high=4.0)
          # 2 distributions [1, 3], [2, 4]
          u2 = Uniform(low=[1.0, 2.0], high=[3.0, 4.0])
          # 4 distributions
          u3 = Uniform(low=[[1.0, 2.0], [3.0, 4.0]],
                    high=[[1.5, 2.5], [3.5, 4.5]])

          # With broadcasting:
          u4 = Uniform(low=3.0, high=[5.0, 6.0, 7.0])

          # Complete example
216
          value_tensor = paddle.to_tensor([0.8], dtype="float32")
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232

          uniform = Uniform([0.], [2.])

          sample = uniform.sample([2])
          # a random tensor created by uniform distribution with shape: [2, 1]
          entropy = uniform.entropy()
          # [0.6931472] with shape: [1]
          lp = uniform.log_prob(value_tensor)
          # [-0.6931472] with shape: [1]
          p = uniform.probs(value_tensor)
          # [0.5] with shape: [1]
    """

    def __init__(self, low, high, name=None):
        if not in_dygraph_mode():
            check_type(low, 'low',
233
                       (int, float, np.ndarray, tensor.Variable, list, tuple),
234 235
                       'Uniform')
            check_type(high, 'high',
236
                       (int, float, np.ndarray, tensor.Variable, list, tuple),
237 238 239 240 241
                       'Uniform')

        self.all_arg_is_float = False
        self.batch_size_unknown = False
        self.name = name if name is not None else 'Uniform'
242
        self.dtype = 'float32'
243 244 245 246 247 248 249 250 251 252

        if isinstance(low, int):
            low = float(low)
        if isinstance(high, int):
            high = float(high)

        if self._validate_args(low, high):
            self.batch_size_unknown = True
            self.low = low
            self.high = high
253
            self.dtype = convert_dtype(low.dtype)
254 255 256
        else:
            if isinstance(low, float) and isinstance(high, float):
                self.all_arg_is_float = True
257 258 259 260 261 262 263 264
            if isinstance(
                    low,
                    np.ndarray) and str(low.dtype) in ['float32', 'float64']:
                self.dtype = low.dtype
            elif isinstance(
                    high,
                    np.ndarray) and str(high.dtype) in ['float32', 'float64']:
                self.dtype = high.dtype
265
            self.low, self.high = self._to_tensor(low, high)
266 267 268
            if self.dtype != convert_dtype(self.low.dtype):
                self.low = tensor.cast(self.low, dtype=self.dtype)
                self.high = tensor.cast(self.high, dtype=self.dtype)
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289

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

        Args:
          shape (list): 1D `int32`. Shape of the generated samples.
          seed (int): Python integer number.

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

        """
        if not in_dygraph_mode():
            check_type(shape, 'shape', (list), 'sample')
            check_type(seed, 'seed', (int), 'sample')

        name = self.name + '_sample'
        batch_shape = list((self.low + self.high).shape)
        if self.batch_size_unknown:
            output_shape = shape + batch_shape
            zero_tmp = tensor.fill_constant_batch_size_like(
290
                self.low + self.high, batch_shape + shape, self.dtype, 0.)
291
            uniform_random_tmp = nn.uniform_random_batch_size_like(
292 293
                zero_tmp,
                zero_tmp.shape,
294
                dtype=self.dtype,
295 296 297 298 299 300 301 302 303 304
                min=0.,
                max=1.,
                seed=seed)
            zero_tmp_reshape = nn.reshape(zero_tmp, output_shape)
            uniform_random_tmp_reshape = nn.reshape(uniform_random_tmp,
                                                    output_shape)
            output = uniform_random_tmp_reshape * (
                zero_tmp_reshape + self.high - self.low)
            output = elementwise_add(output, self.low, name=name)
            return output
305 306 307
        else:
            output_shape = shape + batch_shape
            output = nn.uniform_random(
P
pangyoki 已提交
308 309
                output_shape, dtype=self.dtype, min=0., max=1.,
                seed=seed) * (tensor.zeros(
310
                    output_shape, dtype=self.dtype) + (self.high - self.low))
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
            output = elementwise_add(output, self.low, name=name)
            if self.all_arg_is_float:
                return nn.reshape(output, shape, name=name)
            else:
                return output

    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.

        """
327
        value = self._check_values_dtype_in_probs(self.low, value)
328
        if in_dygraph_mode():
329
            # ensure value in [low, high]
330 331
            lb_bool = self.low < value
            ub_bool = value < self.high
332

W
wanghuancoder 已提交
333 334 335 336
            lb = _C_ops.cast(lb_bool, 'in_dtype', lb_bool.dtype, 'out_dtype',
                             value.dtype)
            ub = _C_ops.cast(ub_bool, 'in_dtype', ub_bool.dtype, 'out_dtype',
                             value.dtype)
337
            return nn.log(lb * ub) - nn.log(self.high - self.low)
338

339
        name = self.name + '_log_prob'
340 341
        lb_bool = self.low < value
        ub_bool = value < self.high
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
        lb = tensor.cast(lb_bool, dtype=value.dtype)
        ub = tensor.cast(ub_bool, dtype=value.dtype)
        return elementwise_sub(
            nn.log(lb * ub), nn.log(self.high - self.low), name=name)

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

        Args:
          value (Tensor): The input tensor.

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

        """
357
        value = self._check_values_dtype_in_probs(self.low, value)
358 359 360
        if in_dygraph_mode():
            lb_bool = self.low < value
            ub_bool = value < self.high
361

W
wanghuancoder 已提交
362 363 364 365
            lb = _C_ops.cast(lb_bool, 'in_dtype', lb_bool.dtype, 'out_dtype',
                             value.dtype)
            ub = _C_ops.cast(ub_bool, 'in_dtype', ub_bool.dtype, 'out_dtype',
                             value.dtype)
366
            return (lb * ub) / (self.high - self.low)
367

368
        name = self.name + '_probs'
369 370
        lb_bool = self.low < value
        ub_bool = value < self.high
371 372 373 374 375
        lb = tensor.cast(lb_bool, dtype=value.dtype)
        ub = tensor.cast(ub_bool, dtype=value.dtype)
        return elementwise_div((lb * ub), (self.high - self.low), name=name)

    def entropy(self):
376
        r"""Shannon entropy in nats.
377

378 379 380 381 382 383
        The entropy is

        .. math::

            entropy(low, high) = \\log (high - low)

384 385 386 387 388 389 390 391 392
        Returns:
          Tensor: Shannon entropy of uniform distribution.The data type is float32.

        """
        name = self.name + '_entropy'
        return nn.log(self.high - self.low, name=name)


class Normal(Distribution):
393
    r"""The Normal distribution with location `loc` and `scale` parameters.
394 395 396

    Mathematical details

397
    The probability density function (pdf) is
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413

    .. math::

        pdf(x; \mu, \sigma) = \\frac{1}{Z}e^{\\frac {-0.5 (x - \mu)^2}  {\sigma^2} }

    .. 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:
414 415
        loc(int|float|list|tuple|numpy.ndarray|Tensor): The mean of normal distribution.The data type is int, float, list, numpy.ndarray or Tensor.
        scale(int|float|list|tuple|numpy.ndarray|Tensor): The std of normal distribution.The data type is int, float, list, numpy.ndarray or Tensor.
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
        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
          
          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
437
          value_tensor = paddle.to_tensor([0.8], dtype="float32")
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455

          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]
    """

    def __init__(self, loc, scale, name=None):
        if not in_dygraph_mode():
            check_type(loc, 'loc',
456
                       (int, float, np.ndarray, tensor.Variable, list, tuple),
457 458
                       'Normal')
            check_type(scale, 'scale',
459
                       (int, float, np.ndarray, tensor.Variable, list, tuple),
460 461 462 463 464
                       'Normal')

        self.batch_size_unknown = False
        self.all_arg_is_float = False
        self.name = name if name is not None else 'Normal'
465
        self.dtype = 'float32'
466 467 468 469 470 471 472 473 474 475

        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
476
            self.dtype = convert_dtype(loc.dtype)
477 478 479
        else:
            if isinstance(loc, float) and isinstance(scale, float):
                self.all_arg_is_float = True
480 481 482 483 484 485 486 487
            if isinstance(
                    loc,
                    np.ndarray) and str(loc.dtype) in ['float32', 'float64']:
                self.dtype = loc.dtype
            elif isinstance(
                    scale,
                    np.ndarray) and str(scale.dtype) in ['float32', 'float64']:
                self.dtype = scale.dtype
488
            self.loc, self.scale = self._to_tensor(loc, scale)
489 490 491
            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)
492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513

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

        Args:
          shape (list): 1D `int32`. Shape of the generated samples.
          seed (int): Python integer number.

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

        """
        if not in_dygraph_mode():
            check_type(shape, 'shape', (list), 'sample')
            check_type(seed, 'seed', (int), 'sample')

        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(
514
                self.loc + self.scale, batch_shape + shape, self.dtype, 0.)
515 516
            zero_tmp_reshape = nn.reshape(zero_tmp, output_shape)
            zero_tmp_shape = nn.shape(zero_tmp_reshape)
517
            normal_random_tmp = nn.gaussian_random(
518
                zero_tmp_shape, mean=0., std=1., seed=seed, dtype=self.dtype)
519 520 521
            output = normal_random_tmp * (zero_tmp_reshape + self.scale)
            output = elementwise_add(output, self.loc, name=name)
            return output
522 523
        else:
            output_shape = shape + batch_shape
524 525
            output = nn.gaussian_random(output_shape, mean=0., std=1., seed=seed, dtype=self.dtype) * \
                     (tensor.zeros(output_shape, dtype=self.dtype) + self.scale)
526 527 528 529 530 531 532
            output = elementwise_add(output, self.loc, name=name)
            if self.all_arg_is_float:
                return nn.reshape(output, shape, name=name)
            else:
                return output

    def entropy(self):
533
        r"""Shannon entropy in nats.
534

535 536 537 538 539 540 541 542 543 544
        The entropy is

        .. math::

            entropy(\sigma) = 0.5 \\log (2 \pi e \sigma^2)

        In the above equation:

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

545 546 547 548 549 550 551
        Returns:
          Tensor: Shannon entropy of normal distribution.The data type is float32.

        """
        name = self.name + '_entropy'
        batch_shape = list((self.loc + self.scale).shape)
        zero_tmp = tensor.fill_constant_batch_size_like(
552
            self.loc + self.scale, batch_shape, self.dtype, 0.)
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
        return elementwise_add(
            0.5 + zero_tmp,
            0.5 * math.log(2 * math.pi) + nn.log((self.scale + zero_tmp)),
            name=name)

    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.

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

571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
        var = self.scale * self.scale
        log_scale = nn.log(self.scale)
        return elementwise_sub(
            -1. * ((value - self.loc) * (value - self.loc)) / (2. * var),
            log_scale + math.log(math.sqrt(2. * math.pi)),
            name=name)

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

        Args:
          value (Tensor): The input tensor.

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

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

591 592 593 594 595 596 597
        var = self.scale * self.scale
        return elementwise_div(
            ops.exp(-1. * ((value - self.loc) * (value - self.loc)) /
                    (2. * var)), (math.sqrt(2 * math.pi) * self.scale),
            name=name)

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

600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
        The probability density function (pdf) is

        .. math::

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

        .. math::

            ratio = \\frac{\sigma_0}{\sigma_1}
        
        .. 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.

623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
        Args:
            other (Normal): instance of Normal.

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

        """
        if not in_dygraph_mode():
            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)
        return elementwise_add(
            0.5 * var_ratio, 0.5 * (t1 - 1. - nn.log(var_ratio)), name=name)
P
pangyoki 已提交
640 641 642


class Categorical(Distribution):
643
    r"""
P
pangyoki 已提交
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
    Categorical distribution is a discrete probability distribution that 
    describes the possible results of a random variable that can take on 
    one of K possible categories, with the probability of each category 
    separately specified.

    The probability mass function (pmf) is:

    .. math::

        pmf(k; p_i) = \prod_{i=1}^{k} p_i^{[x=i]}

    In the above equation:

    * :math:`[x=i]` : it evaluates to 1 if :math:`x==i` , 0 otherwise.

    Args:
660
        logits(list|tuple|numpy.ndarray|Tensor): The logits input of categorical distribution. The data type is float32 or float64.
661
        name(str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
P
pangyoki 已提交
662 663 664 665

    Examples:
        .. code-block:: python

666 667
            import paddle
            from paddle.distribution import Categorical
P
pangyoki 已提交
668

C
cnn 已提交
669
            paddle.seed(100) # on CPU device
670
            x = paddle.rand([6])
671
            print(x)
672 673
            # [0.5535528  0.20714243 0.01162981
            #  0.51577556 0.36369765 0.2609165 ]
P
pangyoki 已提交
674

C
cnn 已提交
675
            paddle.seed(200) # on CPU device
676
            y = paddle.rand([6])
677
            print(y)
678 679
            # [0.77663314 0.90824795 0.15685187
            #  0.04279523 0.34468332 0.7955718 ]
P
pangyoki 已提交
680

681 682
            cat = Categorical(x)
            cat2 = Categorical(y)
P
pangyoki 已提交
683

C
cnn 已提交
684
            paddle.seed(1000) # on CPU device
685 686 687
            cat.sample([2,3])
            # [[0, 0, 5],
            #  [3, 4, 5]]
P
pangyoki 已提交
688

689 690
            cat.entropy()
            # [1.77528]
P
pangyoki 已提交
691

692 693
            cat.kl_divergence(cat2)
            # [0.071952]
P
pangyoki 已提交
694

695 696 697 698 699 700
            value = paddle.to_tensor([2,1,3])
            cat.probs(value)
            # [0.00608027 0.108298 0.269656]

            cat.log_prob(value)
            # [-5.10271 -2.22287 -1.31061]
P
pangyoki 已提交
701 702 703 704 705 706

    """

    def __init__(self, logits, name=None):
        """
        Args:
707
            logits(list|tuple|numpy.ndarray|Tensor): The logits input of categorical distribution. The data type is float32 or float64.
708
            name(str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
P
pangyoki 已提交
709 710
        """
        if not in_dygraph_mode():
711 712
            check_type(logits, 'logits',
                       (np.ndarray, tensor.Variable, list, tuple),
P
pangyoki 已提交
713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
                       'Categorical')

        self.name = name if name is not None else 'Categorical'
        self.dtype = 'float32'

        if self._validate_args(logits):
            self.logits = logits
            self.dtype = convert_dtype(logits.dtype)
        else:
            if isinstance(logits, np.ndarray) and str(
                    logits.dtype) in ['float32', 'float64']:
                self.dtype = logits.dtype
            self.logits = self._to_tensor(logits)[0]
            if self.dtype != convert_dtype(self.logits.dtype):
                self.logits = tensor.cast(self.logits, dtype=self.dtype)

    def sample(self, shape):
        """Generate samples of the specified shape.

        Args:
733
            shape (list): Shape of the generated samples.
P
pangyoki 已提交
734 735

        Returns:
736
            Tensor: A tensor with prepended dimensions shape.
P
pangyoki 已提交
737 738
        
        Examples:
739
            .. code-block:: python
P
pangyoki 已提交
740

741 742
                import paddle
                from paddle.distribution import Categorical
P
pangyoki 已提交
743

C
cnn 已提交
744
                paddle.seed(100) # on CPU device
745
                x = paddle.rand([6])
746
                print(x)
747 748
                # [0.5535528  0.20714243 0.01162981
                #  0.51577556 0.36369765 0.2609165 ]
P
pangyoki 已提交
749

750
                cat = Categorical(x)
P
pangyoki 已提交
751

C
cnn 已提交
752
                paddle.seed(1000) # on CPU device
753 754 755
                cat.sample([2,3])
                # [[0, 0, 5],
                #  [3, 4, 5]]
P
pangyoki 已提交
756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782

        """
        name = self.name + '_sample'
        if not in_dygraph_mode():
            check_type(shape, 'shape', (list), 'sample')

        num_samples = np.prod(np.array(shape))

        logits_shape = list(self.logits.shape)
        if len(logits_shape) > 1:
            sample_shape = shape + logits_shape[:-1]
            logits = nn.reshape(self.logits,
                                [np.prod(logits_shape[:-1]), logits_shape[-1]])
        else:
            sample_shape = shape
            logits = self.logits

        sample_index = multinomial(logits, num_samples, True)
        return nn.reshape(sample_index, sample_shape, name=name)

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

        Args:
            other (Categorical): instance of Categorical. The data type is float32.

        Returns:
783
            Tensor: kl-divergence between two Categorical distributions.
P
pangyoki 已提交
784 785
        
        Examples:
786
            .. code-block:: python
P
pangyoki 已提交
787

788 789 790
                import paddle
                from paddle.distribution import Categorical

C
cnn 已提交
791
                paddle.seed(100) # on CPU device
792
                x = paddle.rand([6])
793
                print(x)
794 795
                # [0.5535528  0.20714243 0.01162981
                #  0.51577556 0.36369765 0.2609165 ]
P
pangyoki 已提交
796

C
cnn 已提交
797
                paddle.seed(200) # on CPU device
798
                y = paddle.rand([6])
799
                print(y)
800 801
                # [0.77663314 0.90824795 0.15685187
                #  0.04279523 0.34468332 0.7955718 ]
P
pangyoki 已提交
802

803 804
                cat = Categorical(x)
                cat2 = Categorical(y)
P
pangyoki 已提交
805

806 807
                cat.kl_divergence(cat2)
                # [0.071952]
P
pangyoki 已提交
808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833

        """
        name = self.name + '_kl_divergence'
        if not in_dygraph_mode():
            check_type(other, 'other', Categorical, 'kl_divergence')

        logits = self.logits - nn.reduce_max(self.logits, dim=-1, keep_dim=True)
        other_logits = other.logits - nn.reduce_max(
            other.logits, dim=-1, keep_dim=True)
        e_logits = ops.exp(logits)
        other_e_logits = ops.exp(other_logits)
        z = nn.reduce_sum(e_logits, dim=-1, keep_dim=True)
        other_z = nn.reduce_sum(other_e_logits, dim=-1, keep_dim=True)
        prob = e_logits / z
        kl = nn.reduce_sum(
            prob * (logits - nn.log(z) - other_logits + nn.log(other_z)),
            dim=-1,
            keep_dim=True,
            name=name)

        return kl

    def entropy(self):
        """Shannon entropy in nats.

        Returns:
834
            Tensor: Shannon entropy of Categorical distribution. The data type is float32.
P
pangyoki 已提交
835 836
        
        Examples:
837
            .. code-block:: python
P
pangyoki 已提交
838

839 840
                import paddle
                from paddle.distribution import Categorical
P
pangyoki 已提交
841

C
cnn 已提交
842
                paddle.seed(100) # on CPU device
843
                x = paddle.rand([6])
844
                print(x)
845 846
                # [0.5535528  0.20714243 0.01162981
                #  0.51577556 0.36369765 0.2609165 ]
P
pangyoki 已提交
847

848
                cat = Categorical(x)
P
pangyoki 已提交
849

850 851
                cat.entropy()
                # [1.77528]
P
pangyoki 已提交
852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875

        """
        name = self.name + '_entropy'
        logits = self.logits - nn.reduce_max(self.logits, dim=-1, keep_dim=True)
        e_logits = ops.exp(logits)
        z = nn.reduce_sum(e_logits, dim=-1, keep_dim=True)
        prob = e_logits / z

        neg_entropy = nn.reduce_sum(
            prob * (logits - nn.log(z)), dim=-1, keep_dim=True)
        entropy = nn.scale(neg_entropy, scale=-1.0, name=name)
        return entropy

    def probs(self, value):
        """Probabilities of the given category (``value``).

        If ``logits`` is 2-D or higher dimension, the last dimension will be regarded as 
        category, and the others represents the different distributions.
        At the same time, if ``vlaue`` is 1-D Tensor, ``value`` will be broadcast to the 
        same number of distributions as ``logits``.
        If ``value`` is not 1-D Tensor, ``value`` should have the same number distributions
        with ``logits. That is, ``value[:-1] = logits[:-1]``.

        Args:
876
            value (Tensor): The input tensor represents the selected category index.
P
pangyoki 已提交
877 878

        Returns:
879
            Tensor: probability according to the category index.
P
pangyoki 已提交
880 881
        
        Examples:
882
            .. code-block:: python
P
pangyoki 已提交
883

884 885
                import paddle
                from paddle.distribution import Categorical
P
pangyoki 已提交
886

C
cnn 已提交
887
                paddle.seed(100) # on CPU device
888
                x = paddle.rand([6])
889
                print(x)
890 891
                # [0.5535528  0.20714243 0.01162981
                #  0.51577556 0.36369765 0.2609165 ]
P
pangyoki 已提交
892

893
                cat = Categorical(x)
P
pangyoki 已提交
894

895 896 897
                value = paddle.to_tensor([2,1,3])
                cat.probs(value)
                # [0.00608027 0.108298 0.269656]
P
pangyoki 已提交
898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941

        """
        name = self.name + '_probs'

        dist_sum = nn.reduce_sum(self.logits, dim=-1, keep_dim=True)
        prob = self.logits / dist_sum

        shape = list(prob.shape)
        value_shape = list(value.shape)
        if len(shape) == 1:
            num_value_in_one_dist = np.prod(value_shape)
            index_value = nn.reshape(value, [num_value_in_one_dist, 1])
            index = index_value
        else:
            num_dist = np.prod(shape[:-1])
            num_value_in_one_dist = value_shape[-1]
            prob = nn.reshape(prob, [num_dist, shape[-1]])
            if len(value_shape) == 1:
                value = nn.expand(value, [num_dist])
                value_shape = shape[:-1] + value_shape
            index_value = nn.reshape(value, [num_dist, -1, 1])
            if shape[:-1] != value_shape[:-1]:
                raise ValueError(
                    "shape of value {} must match shape of logits {}".format(
                        str(value_shape[:-1]), str(shape[:-1])))

            index_prefix = nn.unsqueeze(
                arange(
                    num_dist, dtype=index_value.dtype), axes=-1)
            index_prefix = nn.expand(index_prefix, [1, num_value_in_one_dist])
            index_prefix = nn.unsqueeze(index_prefix, axes=-1)

            if index_value.dtype != index_prefix.dtype:
                tensor.cast(index_prefix, dtype=index_value.dtype)
            index = concat([index_prefix, index_value], axis=-1)

        # value is the category index to search for the corresponding probability.
        select_prob = gather_nd(prob, index)
        return nn.reshape(select_prob, value_shape, name=name)

    def log_prob(self, value):
        """Log probabilities of the given category. Refer to ``probs`` method.

        Args:
942
            value (Tensor): The input tensor represents the selected category index.
P
pangyoki 已提交
943 944

        Returns:
945
            Tensor: Log probability.
P
pangyoki 已提交
946 947
        
        Examples:
948
            .. code-block:: python
P
pangyoki 已提交
949

950 951
                import paddle
                from paddle.distribution import Categorical
P
pangyoki 已提交
952

C
cnn 已提交
953
                paddle.seed(100) # on CPU device
954
                x = paddle.rand([6])
955
                print(x)
956 957
                # [0.5535528  0.20714243 0.01162981
                #  0.51577556 0.36369765 0.2609165 ]
P
pangyoki 已提交
958

959
                cat = Categorical(x)
P
pangyoki 已提交
960

961 962 963
                value = paddle.to_tensor([2,1,3])
                cat.log_prob(value)
                # [-5.10271 -2.22287 -1.31061]
P
pangyoki 已提交
964 965 966 967 968

        """
        name = self.name + '_log_prob'

        return nn.log(self.probs(value), name=name)