Embeddings and sequence classification
Quick answer
An embedding maps a token ID to a dense learned vector. A sequence classifier aggregates token representations or uses a recurrent or attention encoder to predict a document label. Examples are static Python snippets tested locally on CPU; scikit-learn or PyTorch is required for selected examples. ByteMind execution is unverified.
Native embedding lookup
import torche=torch.nn.Embedding(4,2,padding_idx=0)with torch.no_grad(): e.weight.copy_(torch.tensor([[0.,0.],[1.,1.],[2.,4.],[4.,2.]]))x=e(torch.tensor([[2,3,0]]))print(list(x.shape),x[0,:2].mean(0).tolist())Expected output (locally tested): [1, 3, 2] [3.0, 3.0]. Pool only valid positions.
How it works
For vocabulary size V and dimension d, an embedding table has shape (V,d); indexing IDs of shape (batch,time) returns (batch,time,d). Reserve PAD and UNK independently. PyTorch nn.Embedding padding_idx prevents that row from receiving ordinary embedding gradients; it does not automatically mask downstream pooling. A masked mean divides the sum of valid vectors by valid-token count. For an empty document, explicitly reject or use a designated fallback; the exercise uses zeros. Mean pooling loses order; RNNs or attention preserve more contextual information, and contextual embeddings differ by occurrence. The output head maps the representation to class logits; fit with cross-entropy on labeled training data. A pretrained representation may carry language/domain bias and requires provenance and evaluation; no external weights are used here. Evaluate by document rather than token and inspect per-language performance. Keep all chunks from an original document in the same split.
Padding gradients and masks
import torche=torch.nn.Embedding(3,2,padding_idx=0)e(torch.tensor([0,1,1])).sum().backward()print(e.weight.grad.tolist())Expected output (locally tested): [[0.0, 0.0], [2.0, 2.0], [0.0, 0.0]]. The padding row does not receive lookup gradients.
Common mistakes
Do not average padding into the representation, treat an embedding as a probability distribution, or claim a mean-pooled model understands word order.
Practice and next steps
Compute a masked mean for two valid tokens and a padding row. Swap token order and observe the same pooled result.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Embeddings and sequence classification — knowledge check
Apply embeddings and sequence classification to small examples and debugging scenarios.
What is embedding table shape?
Does padding_idx automatically mask mean pooling?
What does mean pooling lose?
What is a contextual embedding?
How should document chunks be split?