Lesson 3 of 12
Step 2: Convert Text to Features
Machine learning models work with numbers, not raw text. This step converts our email texts into numerical feature vectors using CountVectorizer.
What is CountVectorizer?
CountVectorizer converts a collection of text documents to a matrix of word counts.
For each email:
- Build a vocabulary of all unique words across all emails
- For each email, count how many times each vocabulary word appears
- The result is a number array for each email: one count per vocabulary word
This is called the Bag-of-Words representation. It ignores word order but captures which words are present and how often.
Diagram
Loading diagram…
Educational visual guide for step 2 convert text to features.
CountVectorizer in Action
CountVectorizer in Action
# Converting text to numerical features with CountVectorizer
from sklearn.feature_extraction.text import CountVectorizer
import pandas as pd
# Small example to understand what CountVectorizer does
sample_texts = [
"free prize win now",
"meeting scheduled thursday confirm",
"free money win big prize",
"project report attached review",
]
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(sample_texts)
# Show the vocabulary
print("Vocabulary (unique words found):")
vocab = vectorizer.get_feature_names_out()
print(f" {list(vocab)}")
print()
# Show the feature matrix
import numpy as np
feature_matrix = X.toarray()
print("Feature matrix (rows=emails, columns=word counts):")
print(f"{'Email':>6}", end="")
for word in vocab:
print(f" {word:>10}", end="")
print()
for i, (text, row) in enumerate(zip(sample_texts, feature_matrix)):
short = text[:25] + "..." if len(text) > 25 else text
print(f" {i+1}: {short:28}", end="")
for count in row:
print(f" {count:>10}", end="")
print()
print()
print(f"Shape: {feature_matrix.shape} ({feature_matrix.shape[0]} emails, {feature_matrix.shape[1]} features)")Try It Yourself
Try It YourselfHTML
HTML Editor
✓ ValidTab = 2 spaces
HTML|20 lines|561 chars|✓ Valid syntax
UTF-8
Finished this lesson?
0 of 12 in Module 11