Sub topic 1
The task: assigning labels to documents
Prerequisites
This chapter assumes you can write basic Python, read NumPy and pandas code, and understand training and test sets in supervised learning. You do not need the later chapters' material yet.
Framing the problem
Text classification assigns one label from a fixed set to each document. Examples include marking an email as spam or not spam, or tagging a news story by topic. Each training document has a known label, so this is a supervised learning problem. You fit a model on labeled documents and then predict labels for new ones.
A model cannot read text the way a person does. It needs numbers, so the first job is to turn each document into a numeric vector.
From raw text to tokens
A token is a unit of text that the model counts, usually a word. A simple tokenizer lowercases the text and splits it on non-letter characters. This keeps capitalization and punctuation from changing the counts.
import re
text = "The Cat sat on the mat. The cat was happy!"
tokens = re.findall(r"[a-z]+", text.lower())
print(tokens)The output is ['the', 'cat', 'sat', 'on', 'the', 'mat', 'the', 'cat', 'was', 'happy'].
Bag-of-words and the document-term matrix
A bag-of-words model counts how often each token appears in a document and ignores word order. The vocabulary is the set of all tokens seen in training. Stacking one count vector per document gives a document-term matrix, with one row per document and one column per vocabulary term. Most cells are zero, so libraries store the matrix as a sparse matrix.
Because word order is discarded, "dog bites man" and "man bites dog" produce identical rows.
TF-IDF: weighting terms by how informative they are
Raw counts give a common word such as "the" the same weight as a rare, telling word such as "tariff". TF-IDF (term frequency times inverse document frequency) corrects this. Term frequency is the count of a term in one document. Inverse document frequency drops as the number of documents containing the term rises. Scikit-learn then scales each row to unit length.
from sklearn.feature_extraction.text import TfidfVectorizer
docs = [
"the cat sat on the mat",
"the dog sat on the log",
"cats and dogs are pets",
]
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(docs)
print(X.shape)
print(vectorizer.get_feature_names_out())
print(X.toarray().round(2))The matrix has three rows and twelve columns, one for each distinct term.
Exercise
In the three-document example, which term appears in two documents, "sat" or "pets", and how does that affect its IDF?
Show answer
"sat" appears in two documents, so its document frequency is 2. "pets" appears in one document. The IDF of "sat" is therefore lower than the IDF of "pets".