Sub topic 1
Why Models Need Text as Numbers
Prerequisites
This chapter assumes you can:
- Write basic Python with lists, dictionaries and functions.
- Read NumPy arrays and understand a vector as an ordered list of numbers.
- Describe a classifier as something you call
fiton with examples and labels, then callpredicton with new inputs. - Read a logarithm at a high-school level. Logarithms matter from a later chapter on, not here.
You do not need prior NLP experience. This chapter sets up the problem that the rest of the tutorial solves.
The problem: models compute on numbers
Most machine learning models are arithmetic. A linear model multiplies each input by a weight and adds the results. A nearest-neighbor model measures distances. A neural network multiplies matrices. None of these operations is defined for the string "great movie". You cannot multiply a word by 0.7.
A model therefore needs every example to be a fixed-length list of numbers, called a feature vector. A dataset becomes a matrix X with one row per example and one column per feature. Labels, if you have them, go in a separate array y.
For text, the job is to choose a function that maps a string of any length to a vector of one fixed length. This tutorial covers one family of such functions: bag of words and its reweighted variant, TF-IDF.
What makes text awkward
Text differs from a table of measurements in four ways. Each one constrains how you design the mapping.
- Variable length. One review has 5 words and another has 500. The vector length must still be the same for both.
- Discrete symbols. Words are not points on a scale. "Cat" is not halfway between "bat" and "dog".
- Huge feature space. A realistic corpus has tens of thousands of distinct words, so vectors are wide.
- Unseen words. New text will contain words that never appeared in your training data. The mapping must still produce a valid vector.
Why not just give each word an ID?
The obvious first idea is to assign every word an integer and feed the integers to the model. Suppose the vocabulary is cat=0, chased=1, dog=2. A linear model would then treat dog as twice chased and as "more" than cat. Those relationships come from the arbitrary order of assignment, not from the language. Reassigning the IDs would change the model's behavior without changing the data.
The fix is to give each word its own column. A column holds a count (or later a weight) for that word, and zero means the word is absent. No word is "larger" than another, and the columns do not interact until the model learns weights for them.
The core idea: one column per vocabulary word
The approach has three steps.
- Split each document into pieces called tokens, usually words.
- Collect all distinct tokens in the training documents into a vocabulary and give each one a fixed column position.
- Represent each document as a vector whose entry in column
jis how often wordjappears in that document.
The later chapters take these steps one at a time: tokenization, normalization, vocabulary construction, and then counting. First, build the whole thing in plain Python so there is nothing hidden.
A minimal implementation
The code below uses a deliberately naive tokenizer, str.split, and a vocabulary built in sorted order so the column positions are reproducible.
docs = [
"the cat sat on the mat",
"the dog sat on the log",
"the cat chased the dog",
]
# Step 1 and 2: tokenize and build a vocabulary with a fixed column per word
vocab = sorted({word for doc in docs for word in doc.split()})
index = {word: i for i, word in enumerate(vocab)}
def to_vector(text):
vector = [0] * len(vocab)
for word in text.split():
if word in index: # words outside the vocabulary are ignored
vector[index[word]] += 1
return vector
print(vocab)
print(to_vector(docs[0]))
print(to_vector("the bird sat"))The output is:
['cat', 'chased', 'dog', 'log', 'mat', 'on', 'sat', 'the']
[1, 0, 0, 0, 1, 1, 1, 2]
[0, 0, 0, 0, 0, 0, 1, 1]Three points follow from this output.
- Every vector has length 8, the size of the vocabulary, no matter how long the document is.
- The first document has a 2 in the
thecolumn because "the" occurs twice. - The unseen word
birdis dropped silently. The model never sees it, so it contributes nothing.
The same thing in scikit-learn
In practice you do not write this yourself. CountVectorizer does the same work and stores the result efficiently.
from sklearn.feature_extraction.text import CountVectorizer
docs = [
"the cat sat on the mat",
"the dog sat on the log",
"the cat chased the dog",
]
vec = CountVectorizer()
X = vec.fit_transform(docs)
print(vec.get_feature_names_out())
print(X.shape)
print(X.toarray())It prints the alphabetical vocabulary cat, chased, dog, log, mat, on, sat, the, a shape of (3, 8), and a first row of [1 0 0 0 1 1 1 2]. This matches the hand-built version. The result X is a SciPy sparse matrix, and toarray() converts it to a dense array for display only. On a real corpus, call toarray() rarely, because a dense matrix of 100,000 documents by 50,000 words would need tens of gigabytes. A later chapter explains the sparse storage.
What you gain and what you give up
Reading documents as rows of a matrix lets every standard tool apply: logistic regression, naive Bayes, clustering, nearest-neighbor search. That is the gain.
The cost is information. A count vector keeps which words occurred and how often, and it discards everything else.
| Kept | Lost |
|---|---|
| Which words appear | Word order |
| How many times each appears | Grammar and sentence structure |
| A fixed length for any document | Meaning shared between different words |
Consider "the dog chased the cat" and "the cat chased the dog". Their count vectors are identical, yet the sentences describe opposite events. Likewise "film" and "movie" occupy unrelated columns, so the model has no built-in notion that they are similar. These limits are why the name is "bag" of words: you shake out the words and count them, and the order is gone. The final chapter returns to them with alternatives.
Common mistakes at this stage
- Building the vocabulary from all data, including the test set. This leaks information from the test set into your features. A later chapter covers the correct approach, which is to fit only on training data.
- Expecting the same columns from two separate vectorizers. If you fit a new vectorizer on new data, its vocabulary and column order will differ. Reuse the fitted one with
transform. - Treating a zero as "unknown". A zero means the word is absent from this document. It does not mean the model lacks information about that word.
- Converting to a dense array on big data. This can exhaust memory without warning.
Summary of the design
You now have the shape of the whole tutorial. Text becomes tokens, tokens become a vocabulary, and a vocabulary defines the columns of a matrix. Each cell holds a number that says something about one word in one document. Everything that follows is a choice about how to tokenize, which words to keep, and what number to put in each cell.
Exercise
Using the vocabulary ['cat', 'chased', 'dog', 'log', 'mat', 'on', 'sat', 'the'], write the count vector for the text "the dog chased the cat". Then explain why the text "the cat chased the dog" produces exactly the same vector, and what that shows about this representation.
Show answer
The vector is [1, 1, 1, 0, 0, 0, 0, 2]: one each of cat, chased and dog, and two of "the". The reversed sentence contains the same words with the same counts, so its vector is identical. This shows that a bag-of-words vector discards word order, so two sentences with opposite meanings can be indistinguishable to the model.
Exercise
A teammate encodes each word as an integer ID (cat=0, chased=1, dog=2) and feeds the IDs to a linear model. Give one reason this is a poor encoding, and name the encoding this chapter uses instead.
Show answer
The integers impose an arbitrary order and spacing, so the model treats dog as "twice" chased and larger than cat, and changing the ID assignment would change predictions without changing the data. The chapter's encoding gives each vocabulary word its own column, with a count in that column, so no word is ranked above another.