categorical.py 13.1 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
# 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 numpy as np
16

17
import paddle
18
from paddle.distribution import distribution
19
from paddle.fluid.data_feeder import check_type, convert_dtype
20
from paddle.fluid.layers import tensor
21
from paddle.framework import in_dynamic_mode
22
from paddle.tensor import multinomial
23 24


25
class Categorical(distribution.Distribution):
26
    r"""
27 28 29
    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
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
    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:
        logits(list|tuple|numpy.ndarray|Tensor): The logits input of categorical distribution. The data type is float32 or float64.
        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

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

            >>> paddle.seed(100) # on CPU device
            >>> x = paddle.rand([6])
            >>> print(x)
            Tensor(shape=[6], dtype=float32, place=Place(cpu), stop_gradient=True,
            [0.55355281, 0.20714243, 0.01162981, 0.51577556, 0.36369765, 0.26091650])

            >>> paddle.seed(200) # on CPU device
            >>> y = paddle.rand([6])
            >>> print(y)
            Tensor(shape=[6], dtype=float32, place=Place(cpu), stop_gradient=True,
            [0.77663314, 0.90824795, 0.15685187, 0.04279523, 0.34468332, 0.79557180])

            >>> cat = Categorical(x)
            >>> cat2 = Categorical(y)

            >>> # doctest: +SKIP
            >>> paddle.seed(1000) # on CPU device
            >>> print(cat.sample([2,3]))
            Tensor(shape=[2, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
            [[0, 1, 5],
            [3, 4, 5]])

            >>> # doctest: -SKIP
            >>> print(cat.entropy())
            Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
            1.77528250)

            >>> print(cat.kl_divergence(cat2))
            Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=True,
            [0.07195196])

            >>> value = paddle.to_tensor([2,1,3])
            >>> print(cat.probs(value))
            Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
            [0.00608027, 0.10829761, 0.26965630])

            >>> print(cat.log_prob(value))
            Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
            [-5.10270691, -2.22287226, -1.31060708])
91 92 93 94 95 96 97 98
    """

    def __init__(self, logits, name=None):
        """
        Args:
            logits(list|tuple|numpy.ndarray|Tensor): The logits input of categorical distribution. The data type is float32 or float64.
            name(str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
        """
99
        if not in_dynamic_mode():
100 101 102 103 104 105
            check_type(
                logits,
                'logits',
                (np.ndarray, tensor.Variable, list, tuple),
                'Categorical',
            )
106 107 108 109 110 111 112 113

        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:
114 115 116 117
            if isinstance(logits, np.ndarray) and str(logits.dtype) in [
                'float32',
                'float64',
            ]:
118 119 120
                self.dtype = logits.dtype
            self.logits = self._to_tensor(logits)[0]
            if self.dtype != convert_dtype(self.logits.dtype):
121
                self.logits = paddle.cast(self.logits, dtype=self.dtype)
122 123
        dist_sum = paddle.sum(self.logits, axis=-1, keepdim=True)
        self._prob = self.logits / dist_sum
124 125 126 127 128 129 130 131 132

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

        Args:
            shape (list): Shape of the generated samples.

        Returns:
            Tensor: A tensor with prepended dimensions shape.
133

134 135 136
        Examples:
            .. code-block:: python

137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
                >>> import paddle
                >>> from paddle.distribution import Categorical

                >>> paddle.seed(100) # on CPU device
                >>> x = paddle.rand([6])
                >>> print(x)
                Tensor(shape=[6], dtype=float32, place=Place(cpu), stop_gradient=True,
                [0.55355281, 0.20714243, 0.01162981, 0.51577556, 0.36369765, 0.26091650])

                >>> # doctest: +SKIP
                >>> cat = Categorical(x)
                >>> paddle.seed(1000) # on CPU device
                >>> print(cat.sample([2,3]))
                Tensor(shape=[2, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
                [[0, 1, 5],
                [3, 4, 5]])
153 154
        """
        name = self.name + '_sample'
155
        if not in_dynamic_mode():
156 157 158 159 160 161 162
            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]
163
            logits = paddle.reshape(
164 165
                self.logits, [np.prod(logits_shape[:-1]), logits_shape[-1]]
            )
166 167 168 169
        else:
            sample_shape = shape
            logits = self.logits

170 171 172
        sample_index = multinomial(
            self._logits_to_probs(logits), num_samples, True
        )
173 174 175 176 177 178 179 180

        # multinomial sample shape is (logits.shape[:-1], num_samples), need to
        # tanspose to (num_samples, logits.shape[:-1])
        permute = list(range(sample_index.dim()))
        permute.insert(0, permute.pop(-1))
        sample_index = sample_index.transpose(permute)

        return paddle.reshape(sample_index, sample_shape, name=name)
181 182 183 184 185 186 187 188 189

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

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

        Returns:
            Tensor: kl-divergence between two Categorical distributions.
190

191 192 193
        Examples:
            .. code-block:: python

194 195
                >>> import paddle
                >>> from paddle.distribution import Categorical
196

197 198 199 200 201
                >>> paddle.seed(100) # on CPU device
                >>> x = paddle.rand([6])
                >>> print(x)
                Tensor(shape=[6], dtype=float32, place=Place(cpu), stop_gradient=True,
                [0.55355281, 0.20714243, 0.01162981, 0.51577556, 0.36369765, 0.26091650])
202

203 204 205 206 207
                >>> paddle.seed(200) # on CPU device
                >>> y = paddle.rand([6])
                >>> print(y)
                Tensor(shape=[6], dtype=float32, place=Place(cpu), stop_gradient=True,
                [0.77663314, 0.90824795, 0.15685187, 0.04279523, 0.34468332, 0.79557180])
208

209 210
                >>> cat = Categorical(x)
                >>> cat2 = Categorical(y)
211

212 213 214
                >>> print(cat.kl_divergence(cat2))
                Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=True,
                [0.07195196])
215 216
        """
        name = self.name + '_kl_divergence'
217
        if not in_dynamic_mode():
218 219
            check_type(other, 'other', Categorical, 'kl_divergence')

220
        logits = self.logits - paddle.max(self.logits, axis=-1, keepdim=True)
221
        other_logits = other.logits - paddle.max(
222 223
            other.logits, axis=-1, keepdim=True
        )
224 225
        e_logits = paddle.exp(logits)
        other_e_logits = paddle.exp(other_logits)
226 227
        z = paddle.sum(e_logits, axis=-1, keepdim=True)
        other_z = paddle.sum(other_e_logits, axis=-1, keepdim=True)
228
        prob = e_logits / z
229
        kl = paddle.sum(
230 231
            prob
            * (logits - paddle.log(z) - other_logits + paddle.log(other_z)),
232 233
            axis=-1,
            keepdim=True,
234 235
            name=name,
        )
236 237 238 239 240 241 242 243

        return kl

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

        Returns:
            Tensor: Shannon entropy of Categorical distribution. The data type is float32.
244

245 246 247
        Examples:
            .. code-block:: python

248 249
                >>> import paddle
                >>> from paddle.distribution import Categorical
250

251 252 253 254 255
                >>> paddle.seed(100) # on CPU device
                >>> x = paddle.rand([6])
                >>> print(x)
                Tensor(shape=[6], dtype=float32, place=Place(cpu), stop_gradient=True,
                [0.55355281, 0.20714243, 0.01162981, 0.51577556, 0.36369765, 0.26091650])
256

257
                >>> cat = Categorical(x)
258

259 260 261
                >>> print(cat.entropy())
                Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
                1.77528250)
262 263
        """
        name = self.name + '_entropy'
264
        logits = self.logits - paddle.max(self.logits, axis=-1, keepdim=True)
265
        e_logits = paddle.exp(logits)
266
        z = paddle.sum(e_logits, axis=-1, keepdim=True)
267 268
        prob = e_logits / z

269 270
        neg_entropy = paddle.sum(prob * (logits - paddle.log(z)), axis=-1)
        entropy = paddle.scale(neg_entropy, scale=-1.0, name=name)
271 272 273 274 275
        return entropy

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

276
        If ``logits`` is 2-D or higher dimension, the last dimension will be regarded as
277
        category, and the others represents the different distributions.
278
        At the same time, if ``vlaue`` is 1-D Tensor, ``value`` will be broadcast to the
279 280 281 282 283 284 285 286 287
        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:
            value (Tensor): The input tensor represents the selected category index.

        Returns:
            Tensor: probability according to the category index.
288

289 290 291
        Examples:
            .. code-block:: python

292 293
                >>> import paddle
                >>> from paddle.distribution import Categorical
294

295 296 297 298 299
                >>> paddle.seed(100) # on CPU device
                >>> x = paddle.rand([6])
                >>> print(x)
                Tensor(shape=[6], dtype=float32, place=Place(cpu), stop_gradient=True,
                [0.55355281, 0.20714243, 0.01162981, 0.51577556, 0.36369765, 0.26091650])
300

301
                >>> cat = Categorical(x)
302

303 304 305 306
                >>> value = paddle.to_tensor([2,1,3])
                >>> print(cat.probs(value))
                Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
                [0.00608027, 0.10829761, 0.26965630])
307 308
        """
        name = self.name + '_probs'
309
        if len(self._prob.shape) == 1:  # batch_shape is empty
310 311 312
            return paddle.gather(
                self._prob, value.reshape([-1], name=name), name=name
            ).reshape(value.shape, name=name)
313
        else:
314 315 316
            if len(value.shape) == 1:
                return paddle.take_along_axis(
                    self._prob,
317 318 319 320 321 322 323
                    paddle.reshape(
                        value,
                        (len(self._prob.shape) - 1) * [1] + [-1],
                        name=name,
                    ),
                    axis=-1,
                )
324 325
            else:
                return paddle.take_along_axis(self._prob, value, axis=-1)
326 327 328 329 330 331 332 333 334

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

        Args:
            value (Tensor): The input tensor represents the selected category index.

        Returns:
            Tensor: Log probability.
335

336 337 338
        Examples:
            .. code-block:: python

339 340
                >>> import paddle
                >>> from paddle.distribution import Categorical
341

342 343 344 345 346
                >>> paddle.seed(100) # on CPU device
                >>> x = paddle.rand([6])
                >>> print(x)
                Tensor(shape=[6], dtype=float32, place=Place(cpu), stop_gradient=True,
                [0.55355281, 0.20714243, 0.01162981, 0.51577556, 0.36369765, 0.26091650])
347

348
                >>> cat = Categorical(x)
349

350 351 352 353
                >>> value = paddle.to_tensor([2,1,3])
                >>> print(cat.log_prob(value))
                Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
                [-5.10270691, -2.22287226, -1.31060708])
354 355 356
        """
        name = self.name + '_log_prob'

357
        return paddle.log(self.probs(value), name=name)