Advanced level · Module 1: Neural Networks for NLP · Lesson 1 of 3
From Text to Tensors
Learners build a vocabulary, map tokens to integer ids, handle unknown words, and pad and batch variable-length texts for PyTorch.
In this lesson you will
- Build a vocabulary with special tokens
- Create padded batches of token ids
Key concepts
vocabulary<pad> and <unk> tokenstoken idspadding and truncationDataLoader with collate_fn
The lesson
Neural models take numbers. Build a vocabulary from training tokens (keeping words that appear at least twice), reserve id 0 for <pad> and id 1 for <unk>, and map every token to its id. Unknown tokens at prediction time become <unk>.
Texts have different lengths. A batch is padded to the longest text (or truncated at a maximum length) so that it forms a rectangle. A collate_fn passed to torch.utils.data.DataLoader does the padding and also returns the true lengths.
Choices here matter for low-resource text: a vocabulary built from English news will turn most Juba Arabic words into <unk>. Character-level or subword vocabularies, covered later, reduce this problem.
Step by step
- Build a vocabulary from the training texts with min frequency 2.
- Encode five texts as id lists and decode them back.
- Write a collate_fn that pads and returns lengths.
- Measure the share of <unk> tokens in English and local-sample texts.
Practice activity
Write the data-loading code for a neural text classifier and report <unk> rates by language.
Expected result: Working batches with correct padding and an <unk>-rate table that exposes the vocabulary problem for local text.
Check your understanding
-
Why reserve special ids for <pad> and <unk>?
Show answer
To fill short texts in a batch and to represent words not in the vocabulary.
-
What does a collate_fn do?
Show answer
It combines individual examples into a padded batch.
Further learning
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.