PyTorch from Zero: Building a Luganda & English Intent Classifier
Train your first deep learning text classifier in PyTorch with mathematical intuition, clean tokenized batches, and practical Ugandan bilingual examples.
Why this tutorial matters: Most introductory PyTorch guides classify movie reviews in English. Real products in Kampala handle code-switching between Luganda and English—like mobile money queries, clinic triage, or agritech support.
1. The Mathematical Core: Softmax & Cross-Entropy
Given an input sentence converted into a dense representation vector , a linear classification head projects into class logits . We turn logits into probabilities with Softmax:
To train the weights and , we minimize the Cross-Entropy Loss between the true label and predicted distribution :
PyTorch fuses LogSoftmax and negative log-likelihood into nn.CrossEntropyLoss() for numerical stability.
2. Minimal Bilingual Dataset (Luganda + English)
Let’s define a compact intent-classification task with three real-world intents: agri_help (0), health_info (1), and fintech_support (2):
import torch
import torch.nn as nn
samples = [
("Ebikoola bya muwogo birina amabala agakyenvu", 0), # Cassava leaves have yellow spots
("My banana plantation shows wilting leaves", 0),
("Omwana alina omusujja era takyayagala kulya", 1), # Child has fever and won't eat
("Where is the nearest immunization clinic in Kampala?", 1),
("Sente zange ku mobile money tezinnatuuka", 2), # My mobile money hasn't arrived
("How do I reverse a wrong transfer?", 2),
]
vocab = {"<pad>": 0, "<unk>": 1}
for text, _ in samples:
for tok in text.lower().split():
if tok not in vocab:
vocab[tok] = len(vocab)
def encode(text: str, max_len: int = 12) -> list[int]:
ids = [vocab.get(tok, 1) for tok in text.lower().split()][:max_len]
return ids + [0] * (max_len - len(ids))
3. Mean-Pooled Embedding Classifier in PyTorch
Notice how compact this architecture is—under 100 KB, fast enough to run on CPU or even convert to ONNX for Cloudflare Workers / mobile edge devices:
class UgaIntentNet(nn.Module):
def __init__(self, vocab_size: int, embed_dim: int = 64, num_classes: int = 3):
super().__init__()
self.embedding = nn.Embedding(vocab_size, embed_dim, padding_idx=0)
self.net = nn.Sequential(
nn.Linear(embed_dim, 64),
nn.GELU(),
nn.Dropout(0.15),
nn.Linear(64, num_classes),
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
mask = (x != 0).unsqueeze(-1).float()
emb = self.embedding(x) * mask
pooled = emb.sum(dim=1) / mask.sum(dim=1).clamp(min=1.0)
return self.net(pooled)
model = UgaIntentNet(vocab_size=len(vocab))
optimizer = torch.optim.AdamW(model.parameters(), lr=3e-3, weight_decay=1e-2)
criterion = nn.CrossEntropyLoss()
X = torch.tensor([encode(t) for t, _ in samples])
y = torch.tensor([label for _, label in samples])
for epoch in range(80):
optimizer.zero_grad()
logits = model(X)
loss = criterion(logits, y)
loss.backward()
optimizer.step()
print(f"Final training loss: {loss.item():.4f}")
4. Scaling to Production in Uganda
To move beyond a toy vocabulary and handle rich agglutinative morphology in Luganda, Runyankole, and Acholi:
- Swap whitespace splitting for subword BPE / SentencePiece trained on the open Sunbird SALT corpus.
- Fine-tune multilingual pretrained encoders (like AfroXLM-R or compact distilled Gemma/Qwen backbones) using LoRA on a single free Google Colab T4 GPU.
- Evaluate separately on code-switched sentences (e.g., “Nkusaba balance yange”) rather than clean English-only validation splits.