import torch
import torch.nn.functional as F

Examples

Test yourself by expanding the output of each code to see it in action.

# i - Bigram context: one-hot encode a single character 'e' (index 5) in a 27-char vocab
ix = 5                                          # 'e'
xenc = F.one_hot(torch.tensor(ix), num_classes=27).float()
print(xenc)
print(xenc.shape)                               # (27,) — one 1 at position 5
tensor([0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0.])
torch.Size([27])
# i - Bigram context: one-hot encode a sequence of characters spelling "cat."
stoi = {'.':0,'a':1,'b':2,'c':3,'d':4,'t':20}  # simplified
word = "cat."
indices = torch.tensor([stoi[c] for c in word]) # [3, 1, 20, 0]
xenc = F.one_hot(indices, num_classes=27).float()
print(xenc)
print(xenc.shape)                               # (4, 27) — one row per character
tensor([[0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
         0., 0., 0., 0., 0., 0., 0., 0., 0.],
        [0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
         0., 0., 0., 0., 0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
         0., 0., 1., 0., 0., 0., 0., 0., 0.],
        [1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
         0., 0., 0., 0., 0., 0., 0., 0., 0.]])
torch.Size([4, 27])
# i - Sentiment: one-hot encode labels [positive, negative, neutral] for a batch of 5 reviews
labels = torch.tensor([0, 1, 2, 0, 1])          # 0=pos, 1=neg, 2=neutral
xenc = F.one_hot(labels, num_classes=3).float()
print(xenc)
print(xenc.shape)                               # (5, 3)
tensor([[1., 0., 0.],
        [0., 1., 0.],
        [0., 0., 1.],
        [1., 0., 0.],
        [0., 1., 0.]])
torch.Size([5, 3])
# i - Dice roll: one-hot encode outcomes of 8 dice rolls (faces 1-6, mapped to 0-5)
rolls = torch.tensor([0, 2, 5, 1, 3, 5, 0, 4]) # 0=roll of 1, 5=roll of 6
xenc = F.one_hot(rolls, num_classes=6).float()
print(xenc)
print(xenc.shape)                               # (8, 6)
tensor([[1., 0., 0., 0., 0., 0.],
        [0., 0., 1., 0., 0., 0.],
        [0., 0., 0., 0., 0., 1.],
        [0., 1., 0., 0., 0., 0.],
        [0., 0., 0., 1., 0., 0.],
        [0., 0., 0., 0., 0., 1.],
        [1., 0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 1., 0.]])
torch.Size([8, 6])
# i - Days of week: one-hot encode a week's worth of days (0=Mon, 6=Sun)
days = torch.tensor([0, 1, 2, 3, 4, 5, 6])
xenc = F.one_hot(days, num_classes=7).float()
print(xenc)
print(xenc.shape)                               # (7, 7) — identity matrix
tensor([[1., 0., 0., 0., 0., 0., 0.],
        [0., 1., 0., 0., 0., 0., 0.],
        [0., 0., 1., 0., 0., 0., 0.],
        [0., 0., 0., 1., 0., 0., 0.],
        [0., 0., 0., 0., 1., 0., 0.],
        [0., 0., 0., 0., 0., 1., 0.],
        [0., 0., 0., 0., 0., 0., 1.]])
torch.Size([7, 7])