Sub topic 5
Bag of Words: Counting Terms
Prerequisites and the basic idea
This chapter assumes that you know basic Python, NumPy arrays, and the general idea of fitting a machine-learning model. It also assumes that you understand that a vector is a list of numbers.
Machine-learning models cannot use raw sentences directly. A bag-of-words model represents each document as numbers that record which terms appear and how often they appear. It is called a “bag” because it ignores word order.
A document can be a sentence, paragraph, email, or any other text unit. A term is usually a token such as a word. The model first tokenizes each document, then builds one shared vocabulary.
Building a vocabulary
Consider these documents:
the cat satthe dog satthe cat slept
After tokenization, the vocabulary contains each distinct term. If terms are sorted alphabetically, the vocabulary is:
| Column | Term |
|---|---|
| 0 | cat |
| 1 | dog |
| 2 | sat |
| 3 | slept |
| 4 | the |
The model creates one row for each document and one column for each vocabulary term. Each cell contains the number of times that term occurs in that document.
The resulting document-term matrix is:
| Document | cat | dog | sat | slept | the |
|---|---|---|---|---|---|
| `the cat sat` | 1 | 0 | 1 | 0 | 1 |
| `the dog sat` | 0 | 1 | 1 | 0 | 1 |
| `the cat slept` | 1 | 0 | 0 | 1 | 1 |
Repeated terms receive larger counts. For example, the cat cat would have a count of 2 in the cat column.
Creating counts with scikit-learn
CountVectorizer performs tokenization, vocabulary construction, and counting:
from sklearn.feature_extraction.text import CountVectorizer
docs = [
"cats chase mice",
"dogs chase cats",
]
vectorizer = CountVectorizer()
matrix = vectorizer.fit_transform(docs)
print(vectorizer.get_feature_names_out())
print(matrix.toarray())The vocabulary is ['cats', 'chase', 'dogs', 'mice'], so the matrix is:
[[1 1 0 1]
[1 1 1 0]]fit_transform learns the vocabulary from docs and immediately converts the documents into rows of counts. The result is usually a sparse matrix, which stores only nonzero entries. This saves memory when the vocabulary is large and most terms do not occur in each document.
> Note > The vocabulary defines the meaning of every column. Save the fitted vectorizer with the model so that future text uses the same columns.
What bag of words preserves and loses
Bag of words preserves term presence and frequency. It loses word order and most grammatical structure. Therefore, dog bites man and man bites dog can produce identical counts. It also treats related words such as run and running as different terms unless you add preprocessing such as stemming or lemmatization.
Exercise
Using the vocabulary [blue, green, red], what vector represents the document "red red blue"?
Show answer
[1, 0, 2]. The document contains one blue term, no green terms, and two red terms.