Bag of Words with CountVectorizer: Turn Text into Word Counts
A model only does maths, so text has to become numbers first. Clean a review, count its words with CountVectorizer, read the document-term matrix, see why it is sparse, and add word pairs with n-grams. Shown on 2,000 movie reviews.
What you will learn
- Explain why a model cannot fit on raw text
- Clean text with lower-casing, tokenising and stop words using CountVectorizer
- Build and read a document-term matrix and its sparse form
- Keep a little word order with n-grams using ngram_range
Before you start
- Basic Python
- Reading a CSV with pandas
Imagine a postbox full of letters. Letter one says "great movie, great cast". Letter two says "boring movie". Letter three says "great story".
Open letter one and count each word: great two times, movie once, cast once. Letter two has boring once and movie once. Letter three has great once and story once. Notice something? The order of the words is forgotten, as if we shook them in a bag. Every letter becomes a row of word counts, and that's a bag of words.
That's exactly how we'll turn movie reviews into numbers a model can learn from.
The data: 2,000 movie reviews
The file movie_review.csv has one sentence per row. We glue the sentences back together, review by review:
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.linear_model import LogisticRegression
sents = pd.read_csv("movie_review.csv")
grouped = sents.groupby(["cv_tag", "tag"])["text"]
reviews = grouped.apply(" ".join).reset_index()
print(reviews.shape)
print(reviews["tag"].value_counts().to_dict())
print(reviews["text"][0][:44])
(2000, 3)
{'neg': 1000, 'pos': 1000}
plot : two teen couples go to a church party
2,000 reviews, 1,000 positive and 1,000 negative. The first one starts "plot : two teen couples".
A model cannot read text
What happens if we hand the text column straight to a logistic regression and call fit?
try:
model = LogisticRegression()
model.fit(reviews[["text"]], reviews["tag"])
except ValueError as err:
print("ValueError:", str(err).split(":")[0])
ValueError: could not convert string to float
Boom. A model only does maths on numbers, so it can't use a sentence. We need a step that turns each review into a row of numbers first.
Clean the text: lower-case, tokens, stop words
Before we count, we clean. Three things happen:
- Lower-case everything, so "GREAT" and "great" are the same word.
- Tokenise: split the text into words. Each word is a token.
- Drop the stop words. Words like "the" and "was" are everywhere, so they tell us very little. They're the small talk of a sentence.
CountVectorizer does all three for us. stop_words="english" asks it to drop the filler words, and build_analyzer() hands us its cleaning function so we can try it on one sentence:
vec = CountVectorizer(stop_words="english")
analyze = vec.build_analyzer()
print(analyze("The movie was GREAT, really great!"))
['movie', 'great', 'really', 'great']
Lower-case, split, and "the" and "was" are gone. The punctuation is gone too. What's left are the words that matter.
The document-term matrix
Now four tiny reviews:
corpus = [
"The movie was great and the acting was great",
"The movie was boring",
"Great story, boring ending",
"I loved the movie",
]
X = vec.fit_transform(corpus)
terms = vec.get_feature_names_out()
pd.DataFrame(X.toarray(), columns=terms)
acting boring ending great loved movie story
0 1 0 0 2 0 1 0
1 0 1 0 0 0 1 0
2 0 1 1 1 0 0 1
3 0 0 0 0 1 1 0
fit_transform does two jobs:
- fit learns the words. Seven are left after cleaning: acting, boring, ending, great, loved, movie, story.
- transform counts them, review by review.
So there's one row per review, which we call a document, and one column per word, which we call a term. That's the document-term matrix. Look at row 0: great is 2, because the review says "great" twice.
All 2,000 reviews: almost all zeros
Now the same on every review. This time we keep every word (no stop-word list), just to see how big the matrix gets:
texts = reviews["text"]
X_all = CountVectorizer().fit_transform(texts)
print(X_all.shape)
print("stored numbers:", X_all.nnz)
total = 2000 * X_all.shape[1]
share = 100 * X_all.nnz / total
print("filled:", round(share, 2), "%")
(2000, 39659)
stored numbers: 666842
filled: 0.84 %
2,000 rows and 39,659 columns, one for every different word. That's about 79 million cells, but only 666,842 of them are not zero. Fewer than one cell in a hundred holds a count, because each review uses only a tiny slice of all the words.
So scikit-learn returns a sparse matrix. It stores just the non-zero numbers and where they sit, not the millions of zeros. Your laptop will thank you. (.toarray() turns it back into a full table, which is fine for four tiny reviews and a bad idea for 2,000.)
This cell fits on all 2,000 reviews only to measure the matrix. When you train a model, split first and fit the vectorizer on the training reviews only, as in Train-Test Split and Data Leakage. The text classifier article does exactly that.
N-grams: pairs of words keep a little order
Forgetting the order has a cost. A bag of words can't tell "good" from "not good". Take two reviews:
- "the movie was good"
- "the movie was not good"
Counted as single words, they look almost the same. So we also count pairs of neighbouring words: "the movie", "movie was", and so on. A run of n neighbouring words is called an n-gram, and ngram_range=(1, 2) asks for single words and pairs. Here we keep every word, so "not" stays in:
a, b = "the movie was good", "the movie was not good"
bi = CountVectorizer(ngram_range=(1, 2))
counts = bi.fit_transform([a, b]).toarray()
names = bi.get_feature_names_out()
pd.DataFrame(counts, columns=names).T
0 1
good 1 1
movie 1 1
movie was 1 1
not 0 1
not good 0 1
the 1 1
the movie 1 1
was 1 1
was good 1 0
was not 0 1
Ten columns, shown flipped with .T so each row is one word or pair. Look at not good: 0 for review 0 and 1 for review 1. Now the two reviews look different.
ngram_range=(1, 2), "not good" becomes a column of its own, and only review 1 fills it.Pairs bring back a little of the order. The price is more columns: 10 here instead of 5 single words.
Common mistakes
- Passing raw text to a model. You get
could not convert string to float. Vectorize first. - Calling
.toarray()on a big matrix. 2,000 x 39,659 is fine sparse and wasteful dense. Keep it sparse; the text models in the text classifier article (MultinomialNB and LinearSVC) take the vectorizer's output directly. - Dropping stop words when you need n-grams like "not good". Check what your stop-word list removes before you rely on negation pairs.
- Fitting the vectorizer before the split. The vocabulary is learned from the data, so fit it on the training text only.
Recap
| Step | What it does | In code |
|---|---|---|
| Tokenise | Lower-case and split the text into words | build_analyzer() |
| Stop words | Drop the filler words | stop_words="english" |
| Bag of words | Count each word; every review becomes a row | CountVectorizer().fit_transform() |
| Sparse matrix | Store only the non-zero counts | X_all.nnz |
| N-grams | Count word pairs to keep a little order | ngram_range=(1, 2) |
Plain counts treat every word the same, though, and words like "film" fill every movie review. The next step, TF-IDF, lets the rare words count for more.
Try it yourself
Add a fifth review, "Boring, boring, boring", to corpus and run fit_transform again. Which column changes, and to what number? The notebook and the dataset for this lesson are in the community, free to join.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Recommender Systems: Item-Based Collaborative Filtering with Cosine Similarity
Next →TF-IDF with TfidfVectorizer: Common Words Fade, Rare Words Speak
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
TF-IDF with TfidfVectorizer: Common Words Fade, Rare Words Speak
Plain word counts treat every word the same. TF-IDF multiplies each count by how rare the word is, then scales each row to length 1. Worked by hand on four restaurant reviews, then on 2,000 movie reviews.
Build a Text Classifier with TF-IDF and a Pipeline: Naive Bayes vs LinearSVC
Train a movie-review sentiment classifier: split first, put TF-IDF and the model in one Pipeline, compare MultinomialNB (F1 0.801) with LinearSVC (F1 0.857), read the confusion matrix and predict new reviews from raw text.