Text Preprocessing and Representations
From bag-of-words and TF-IDF to subword tokenizers and dense embeddings: the ways text becomes model input.
Intermediate · about 8 hours · difficulty 2/5
Learn first: Logistic Regression and Linear Classifiers, Feature Engineering
Models only consume numbers, so every NLP system starts by deciding how text becomes vectors. The choice shapes what the model can learn and how well it handles words it never saw.
Classical representations
- Normalization: lowercasing, Unicode handling, removing markup. Stemming and lemmatization matter for classical models but rarely for transformers.
- Bag-of-words and n-grams: count which words appear, ignoring order.
- TF-IDF down-weights words that appear everywhere. TF-IDF plus logistic regression is a strong, fast baseline for classification that you should always try first.
Tokenization
Modern models split text into subword tokens using algorithms such as BPE, WordPiece or SentencePiece. Rare words break into pieces (unbelievable might become un, believ, able), so there are no unknown words and the vocabulary stays manageable. Learn to inspect token ids, special tokens, padding, truncation and attention masks, because many bugs live here.
Embeddings
- Word embeddings (word2vec, GloVe) map each word to a dense vector where similar words sit close together.
- Contextual embeddings from transformers give the same word different vectors depending on the sentence (river bank versus savings bank).
- Sentence embeddings (for example sentence-transformers models) power semantic search, clustering and deduplication using cosine similarity.
Good enough to move on when you can build a TF-IDF baseline, tokenize text with a pretrained tokenizer and explain every field it returns, and run a semantic similarity search with sentence embeddings.
Key concepts
- Text normalization
- Bag-of-words and n-grams
- TF-IDF baselines
- Subword tokenization (BPE, WordPiece)
- Word embeddings (word2vec, GloVe)
- Sentence embeddings
- Stemming and lemmatization
Mini project
Build a news or review classifier with TF-IDF and logistic regression, then a semantic search over the same corpus using sentence embeddings, and compare what each approach gets right.
Check yourself
Why do subword tokenizers avoid the unknown-word problem, and what is the attention mask used for when batching sequences of different lengths?
Free resources
- Hugging Face Learn (Hugging Face)
- scikit-learn: working with text data (scikit-learn)
- Sentence Transformers documentation (SBERT)