Sub topic 1
Why Models Need Text as Numbers
Prerequisites
You should know basic Python, including lists and functions. Familiarity with NumPy arrays helps. You should also understand the idea of a classifier that learns with fit and predicts with predict.
Why models need text as numbers
A model computes with numbers. It cannot use the string "the cat sat" directly. We convert each document into a vector, a fixed-length list of numbers. Each position in the vector must always refer to the same word, so the conversion is consistent across documents.
Splitting text into tokens
A token is one unit of text, usually a word. The tokenizer decides where one token ends and the next begins. scikit-learn's default tokenizer splits on word boundaries and keeps only tokens of two or more letters or digits. That is why the single letter "a" disappears.
Lowercasing and stop words
CountVectorizer lowercases text by default, so "The" and "the" become one token. A stop word is a very common word, such as "the", "on", or "and", that often adds little signal. Setting stop_words="english" removes a built-in list of these words.
Building a vocabulary
The vocabulary is the sorted list of every distinct token in the training documents. Each token gets a column index. Calling fit builds the vocabulary, and the vocabulary should come from training data only.
Bag of words: counting terms
Bag of words represents each document by counting how often each vocabulary term appears. It discards word order, so "dog bites man" and "man bites dog" produce identical counts.
The document-term matrix
Stack the count vectors row by row. Each row is a document and each column is a term.
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.toarray())['cat' 'chased' 'dog' 'log' 'mat' 'on' 'sat' 'the']
[[1 0 0 0 1 1 1 2]
[0 0 1 1 0 1 1 2]
[1 1 1 0 0 0 0 2]]Exercise
In the matrix above, how many columns does it have, and why is the count of "the" in the first document equal to 2?
Show answer
It has 8 columns, one for each vocabulary term. The first document is "the cat sat on the mat", which contains "the" twice.