Beginner level · Module 5: Introduction to Text Classification · Lesson 1 of 3
Bag of Words: Turning Text into Numbers
Learners see how CountVectorizer builds a vocabulary and turns each message into a row of word counts, the simplest representation that classifiers can use.
In this lesson you will
- Explain the bag-of-words representation
- Create a document-term matrix with CountVectorizer
Key concepts
vocabularydocument-term matrixCountVectorizersparse matrixword order lost
The lesson
A classifier needs numbers. The bag-of-words idea counts how many times each vocabulary word appears in each text. Every message becomes a row, every word a column, and most cells are zero.
CountVectorizer from scikit-learn does this in two steps: fit learns the vocabulary from the training texts; transform turns texts into count rows. Its default settings lowercase the text and keep tokens of two or more letters or digits.
Bag of words ignores word order, so 'fees not paid' and 'not fees paid' look the same. Despite this, it works well for many classification tasks and is fast on modest computers.
Step by step
- Fit a CountVectorizer on five short messages.
- Print get_feature_names_out() and the count matrix with toarray().
- Transform a new message containing an unknown word and explain the result.
- Write one limitation of ignoring word order.
Practice activity
Build and interpret a document-term matrix for ten project messages.
Expected result: A correct matrix with an explanation of the vocabulary, unknown words and word-order loss.
Check your understanding
-
What happens to a word not seen during fit?
Show answer
It is ignored, because it is not in the vocabulary.
-
What information does bag of words lose?
Show answer
Word order.
Further learning
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.