Skip to content
class

Categorical

extendsDistribution
Categorical(probs: Tensor | None = None, logits: Tensor | None = None, validate_args: bool | None = None)

Categorical distribution — a discrete distribution over K labelled outcomes.

Categorical(probs=p) or Categorical(logits=l) defines a distribution over the integer set {0,1,…,K−1}\{0, 1, \ldots, K-1\} where KK is the number of categories. Exactly one of probs or logits must be given.

Parameters

probsTensor | None= None
Non-negative probability vector (or batch of vectors) of shape (..., K). Rows are automatically normalised to sum to 1. Mutually exclusive with logits.
logitsTensor | None= None
Unnormalised log-probabilities of shape (..., K). The distribution uses softmax\text{softmax} internally to convert to normalised probabilities. Mutually exclusive with probs.
validate_argsbool | None= None
If True, validate parameter constraints at construction time.

Attributes

probsTensor
Normalised probability vector of shape (..., K) — stored when given, otherwise softmax(logits), derived on access.
logitsTensor
Log-probability vector of shape (..., K) — as given (unnormalised), otherwise log(probs), derived on access.

Notes

PMF:

P(X=k)=pk,k∈{0,1,…,K−1},∑kpk=1P(X = k) = p_k, \quad k \in \{0, 1, \ldots, K-1\}, \quad \sum_{k} p_k = 1

Parameterisations are related by:

pk=elk∑jelj,lk=log⁡pk  (up to additive constant)p_k = \frac{e^{l_k}}{\sum_j e^{l_j}}, \qquad l_k = \log p_k \;(\text{up to additive constant})

Entropy:

H[X]=−∑k=0K−1pklog⁡pkH[X] = -\sum_{k=0}^{K-1} p_k \log p_k

Mean is not well-defined for a general Categorical (the labels have no canonical metric), so mean returns a NaN tensor of the batch shape.

Sampling uses the Gumbel-max trick: add i.i.d. Gumbel⁡(0,1)\operatorname{Gumbel}(0, 1) noise to the log-probabilities and take the argmax. This is equivalent to ancestral sampling and avoids cumulative-sum + binary-search.

The batch dimensions of the input correspond to independent distributions. For example, probs of shape (B, K) yields a batch of BB Categorical distributions.

Examples

>>> import lucid
>>> from lucid.distributions import Categorical
>>> # Uniform over 4 categories
>>> dist = Categorical(probs=lucid.tensor([0.25, 0.25, 0.25, 0.25]))
>>> samples = dist.sample((10,))
>>> # Batch of 2 distributions
>>> dist_b = Categorical(logits=lucid.zeros(2, 5))
>>> dist_b.batch_shape, dist_b.event_shape
((2,), ())

Used by 4

Constructors

1
dunder

__init__

→None
__init__(probs: Tensor | None = None, logits: Tensor | None = None, validate_args: bool | None = None)

Initialise a Categorical distribution.

Parameters

probsTensor | None= None
Non-negative probability vector of shape (..., K). Rows are automatically normalised to sum to 1. Mutually exclusive with logits.
logitsTensor | None= None
Unnormalised log-probabilities of shape (..., K). Stored shifted by their logsumexp (so logits holds log-probabilities), as in the reference framework; a row with no such shift — all -inf, or holding +inf — is refused under validation. Mutually exclusive with probs.
validate_argsbool | None= None
If True, validate parameter constraints at construction time.

Raises

ValueError
If both or neither of probs and logits are provided.

Properties

5
prop

mean

→Tensor
mean: Tensor

Mean of the Categorical distribution (undefined — returns NaN).

The Categorical distribution assigns labels with no inherent ordering or metric, so the mean is not well-defined. This property returns a NaN tensor of the batch shape to match expected behaviour.

Returns

Tensor

Tensor of float('nan') values with shape batch_shape.

prop

mode

→Tensor
mode: Tensor

Mode of the Categorical distribution: the most probable category.

Returns

Tensor

Integer category indices of shape batch_shape; the first one on a tie.

prop

stddev

→Tensor
stddev: Tensor

Standard deviation of the Categorical distribution (NaN).

The square root of variance, which is NaN for the reason given there.

Returns

Tensor

Tensor of float('nan') with shape batch_shape.

prop

support

→Constraint
support: Constraint

Support of the distribution: integer interval {0,…,K−1}\{0, \ldots, K-1\}.

Returns

Constraint

An integer_interval constraint from 0 to K - 1.

prop

variance

→Tensor
variance: Tensor

Variance of the Categorical distribution (undefined — NaN).

A variance is a squared distance, and the labels this distribution assigns have no metric to measure one with — the same reason mean is NaN. Returned rather than raised so the moment composes with the rest of the API the way the reference framework's does; a caller who wants an error can test for NaN.

Returns

Tensor

Tensor of float('nan') with shape batch_shape.

Instance methods

7
fn

entropy

→Tensor
entropy()

Shannon entropy of the Categorical distribution.

H[X]=−∑k=0K−1pklog⁡pkH[X] = -\sum_{k=0}^{K-1} p_k \log p_k

with 0log⁡0=00 \log 0 = 0: a category of probability zero — a zero in probs, or a logit of -inf masking an action out — contributes nothing rather than 0 · (-inf) = NaN.

Returns

Tensor

Entropy values of shape batch_shape (nats).

Examples

>>> import lucid
>>> from lucid.distributions import Categorical
>>> Categorical(probs=lucid.tensor([0.0, 0.5, 0.5])).entropy()
tensor(0.6931)
>>> Categorical(logits=lucid.tensor([float("-inf"), 0.0, 0.0])).entropy()
tensor(0.6931)
fn

enumerate_support

→Tensor
enumerate_support(expand: bool = True)

Category indices 0,…,K−10, \ldots, K - 1 along axis 0, in int64.

fn

expand

→Self
expand(batch_shape: Sequence[int], _instance: Self | None = None)

Return a new Categorical with batch dimensions expanded to batch_shape.

fn

log_prob

→Tensor
log_prob(value: Tensor)

Log-probability of the given category indices.

For a one-hot index kk, the log-probability is:

log⁡P(X=k)=log⁡pk\log P(X = k) = \log p_k

Parameters

valueTensor
Integer tensor of category indices with shape compatible with batch_shape. Values must be in {0,…,K−1}\{0, \ldots, K-1\}.

Returns

Tensor

Log-probabilities of shape batch_shape.

fn

logits

→Tensor
logits()

Log-probabilities — as given (shifted by their logsumexp), or derived from probs on access.

Derived as log(probs) with probs clamped one epsilon inside [0, 1], as the reference framework derives it, so a category of probability zero gets a large negative logit rather than -inf.

fn

probs

→Tensor
probs()

Normalised probabilities — as given, or softmax(logits).

fn

sample

→Tensor
sample(sample_shape: tuple[int, ...] = ())

Draw samples from the Categorical distribution.

Uses the Gumbel-max trick: add i.i.d. Gumbel⁡(0,1)\operatorname{Gumbel}(0, 1) noise to the log-probabilities and take the argmax, which is equivalent to ancestral sampling but avoids cumulative-sum and binary search.

Parameters

sample_shapetuple[int, ...]= ()
Leading shape of the output sample batch.

Returns

Tensor

Integer tensor of shape (*sample_shape, *batch_shape) with values in {0,1,…,K−1}\{0, 1, \ldots, K-1\}. The result is detached (no gradients flow through discrete samples).