TensorPlay
latest (dev)
Copy
View Markdown

Latest development documentation · Updated 2026-10-08

Categorical

class tensorplay.distributions.Categorical(probs: Tensor | None = None, logits: Tensor | None = None, validate_args: bool | None = None)[source]

Creates a categorical distribution parameterized by either probs or logits (but not both).

Note

It is equivalent to the distribution that tensorplay.multinomial() samples from.

Samples are integers from {0,…,K−1}\{0, \ldots, K-1\} where K is probs.size(-1).

If probs is 1-dimensional with length-K, each element is the relative probability of sampling the class at that index.

If probs is N-dimensional, the first N-1 dimensions are treated as a batch of relative probability vectors.

Note

The probs argument must be non-negative, finite and have a non-zero sum, and it will be normalized to sum to 1 along the last dimension. probs will return this normalized value. The logits argument will be interpreted as unnormalized log probabilities and can therefore be any real number. It will likewise be normalized so that the resulting probabilities sum to 1 along the last dimension. logits will return this normalized value.

See also: tensorplay.multinomial()

Example:

>>> # xdoctest: +IGNORE_WANT("non-deterministic")
>>> m = Categorical(tensorplay.tensor([ 0.25, 0.25, 0.25, 0.25 ]))
>>> m.sample()  # equal probability of 0, 1, 2, 3
tensor(3)
Parameters:
  • probs (Tensor) – event probabilities

  • logits (Tensor) – event log probabilities (unnormalized)

property batch_shape: Size

Returns the shape over which parameters are batched.

cdf(value: Tensor) → Tensor

Returns the cumulative density/mass function evaluated at value.

Parameters:

value (Tensor)

property event_shape: Size

Returns the shape of a single sample (without batching).

icdf(value: Tensor) → Tensor

Returns the inverse cumulative density/mass function evaluated at value.

Parameters:

value (Tensor)

perplexity() → Tensor

Returns perplexity of distribution, batched over batch_shape.

Returns:

Tensor of shape batch_shape.

rsample(sample_shape: Size | Sequence[int] = ()) → Tensor

Generates a sample_shape shaped reparameterized sample or sample_shape shaped batch of reparameterized samples if the distribution parameters are batched.

sample_n(n: int) → Tensor

Generates n samples or n batches of samples if the distribution parameters are batched.

static set_default_validate_args(value: bool) → None

Sets whether validation is enabled or disabled.

The default behavior mimics Python’s assert statement: validation is on by default, but is disabled if Python is run in optimized mode (via python -O). Validation may be expensive, so you may want to disable it once a model is working.

Parameters:

value (bool) – Whether to enable validation.

property stddev: Tensor

Returns the standard deviation of the distribution.

On this page

Ask DeepWiki