Lexical features and semantic tasks
From token sequences to numerical features
A bag-of-words vector has one coordinate per vocabulary term. Its value is usually the number of occurrences of that term in the document. With vocabulary [bike, blue, red], red bike red maps to [1, 0, 2]. The vector ignores ordering, so rearranged text can have identical features even when meaning changes. Vocabulary order must remain fixed between training and prediction. A bag of n-grams preserves some local order at the cost of more features.
Fit vocabulary and inverse document frequency
TF-IDF combines term frequency (TF) with inverse document frequency (IDF). In this example TF is the raw count, document frequency df is the number of training documents containing the term at least once, and smoothed IDF is 1 + ln((1 + N)/(1 + df)), where N is the training document count. Multiply TF by IDF coordinate by coordinate. A term in every document has IDF 1; rarer terms have higher values. Other TF-IDF definitions exist. The example deliberately omits final vector normalization; scikit-learn normally applies L2 normalization by default. Fit vocabulary and IDF on training documents only for supervised evaluation, and freeze both before transforming held-out text. For search, the indexed corpus defines the vocabulary; the query does not refit it.
from math import log
def fit_vocab(documents): return sorted({word for doc in documents for word in doc})
def counts(doc, vocab): return [doc.count(word) for word in vocab]
def fit_idf(documents, vocab): if not documents: raise ValueError("Need at least one document") return [1 + log((1+len(documents)) / (1+sum(word in doc for doc in documents))) for word in vocab]
training = ["red bike red".split(), "blue bike".split()]vocab = fit_vocab(training)idf = fit_idf(training, vocab)held_out = "red scooter".split()print(vocab)print(counts(training[0], vocab))print([round(w, 3) for w in idf])print([round(c*w, 3) for c,w in zip(counts(held_out, vocab), idf)])Interpret the vector
Bike occurs in both training documents, so its IDF is 1. Blue and red each appear in one of two documents, so both have IDF approximately 1.405. Repeated red does not increase document frequency. The held-out word scooter is not in the training vocabulary and contributes no coordinate; red receives weight 1.405. A document consisting only of unseen terms becomes a zero vector. Rounding is for display only. Real vectorizers use sparse representations when vocabularies are large. Never fit on validation or test data to avoid leakage.
Lexical retrieval and zero overlap
Cosine similarity compares the angle between vectors: dot product divided by the product of their Euclidean norms. It is undefined if either vector has zero norm. This example uses nonnegative raw count vectors for search, not TF-IDF. Scores are not probabilities. It returns only positive-overlap documents, sorted by decreasing similarity then increasing zero-based document ID. For these nonnegative integer count vectors, ranking by the exact fraction dot² / squared document norm is equivalent to ranking by cosine: the query norm is constant and squaring preserves positive order. This avoids floating-point rounding breaking a mathematical tie; document ID resolves exact ties. A query with no known terms yields no match, rather than a fabricated relevant result.
from math import sqrtfrom fractions import Fraction
def cosine(a, b): if len(a) != len(b): raise ValueError("Different vector dimensions") na = sum(x*x for x in a) nb = sum(x*x for x in b) if na == 0 or nb == 0: return None return sum(x*y for x,y in zip(a,b)) / sqrt(na*nb)
def retrieve(query, documents): # Vocabulary and document coordinates belong to this fixed index. vocab = sorted({word for doc in documents for word in doc}) q = [query.count(word) for word in vocab] scored = [] for i, doc in enumerate(documents): d = [doc.count(word) for word in vocab] score = cosine(q, d) if score is not None and score > 0: dot = sum(x*y for x,y in zip(q,d)) rank_key = Fraction(dot*dot, sum(y*y for y in d)) scored.append((i, score, rank_key)) scored.sort(key=lambda row: (-row[2], row[0])) return [(i, score) for i, score, _ in scored]
docs = ["repair bicycle".split(), "fix bike".split(), "paint wall".split()]print([(i, round(s, 3)) for i,s in retrieve("repair bicycle".split(), docs)])print(retrieve(["scooter"], docs))What the lexical search misses
The query retrieves document 0 with cosine 1.0. Document 1 says fix bike, which may be relevant even though it has no word in common with repair bicycle. A lexical score of zero is not proof of irrelevance. A semantic embedding is a dense learned representation that can capture some relationships between different strings. It may also miss negation, rare terminology or language-specific distinctions; semantic similarity is not factual correctness. Use the same compatible embedding model and preprocessing for index and query. Combine lexical and semantic retrieval only if evaluation supports it. The example does not produce or test actual learned embeddings.
Choose the NLP task and evaluate it
Text classification assigns labels to documents (such as repair request versus billing request); sequence labeling attaches labels to tokens or spans (such as part-number entities); retrieval ranks existing documents; generation produces new text. They have distinct output contracts and evaluations. For classification, use held-out labels and precision/recall where suitable; for sequence labeling, verify exact spans after normalization; for retrieval, compare top-k results with relevance judgments; for generation, evaluate factual accuracy and task completion with human review as appropriate. Use separate evaluation data, include spelling, synonyms, negation and language-specific error slices, and never assume a tokenizer performs equally across scripts. For example, inspect false matches for not repaired versus repaired. The next chapter applies analogous representation choices to images.
Practice
Build the tiny search audit in the project. Predict which query returns an empty list, then propose a way to improve recall without pretending synonym matching guarantees correctness. Explain why frozen vocabulary prevents held-out leakage and why adding a bigram is useful for not working.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Lexical features and semantic tasks quiz
Apply the representation and evaluation concepts.
With vocabulary [bike, blue, red], what is the count vector for "red red bike"?
Under IDF = 1 + ln((1+N)/(1+df)), what is IDF for a term present in all N training documents?
Why freeze a fitted vocabulary before transforming held-out supervised evaluation documents?
Why can the lesson’s count-vector retrieval miss "fix bike" for the query "repair bicycle"?
Which task assigns a label to each relevant token or span?