fn

one_hot

Tensor
one_hot(tensor: Tensor, num_classes: int = -1)
source

One-hot encode an integer class index tensor.

Maps each integer entry into a one-hot vector along a new trailing axis of size num_classes:

out[,c]={1if tensor[]=c0otherwise\mathrm{out}[\ldots, c] = \begin{cases} 1 & \text{if } \mathrm{tensor}[\ldots] = c \\ 0 & \text{otherwise} \end{cases}

Parameters

tensorTensor
Integer tensor of arbitrary shape (*) whose entries are class indices in [0, num_classes).
num_classesint= -1
Total number of classes CC. If -1 (the default), it is inferred as tensor.max() + 1; supplying an explicit value avoids a host round-trip and is preferred in hot loops.

Returns

Tensor

One-hot encoded tensor of shape (*, num_classes) and integer dtype. Cast to a floating dtype if it will participate in gradient-based computation.

Notes

For loss functions like cross-entropy, prefer passing raw integer targets to the loss directly — one-hot encoding then immediately contracting against a softmax wastes memory and breaks the log-sum-exp fused path.

Examples

>>> import lucid
>>> from lucid.nn.functional import one_hot
>>> idx = lucid.tensor([0, 2, 1, 2], dtype=lucid.int64)
>>> one_hot(idx, num_classes=3)
Tensor([[1, 0, 0],
        [0, 0, 1],
        [0, 1, 0],
        [0, 0, 1]])