Bag of Words

What Is Bag of Words?

Bag of Words is a simple way to represent text for a machine learning model. It turns text into numbers by counting how often words appear.

Simple Idea

Text → Split into words → Count the words → Create a numerical representation

Example Text: I love dogs. I love cats.

Word Counts: I = 2 · love = 2 · dogs = 1 · cats = 1

Why Bag of Words Matters

Machine learning models cannot directly understand raw text. They need numbers. Bag of Words turns words into numerical features.

Common Uses
  • Spam detection
  • Sentiment analysis
  • Topic classification
  • Search systems
  • Document classification
  • Simple text classification tasks

Key Idea: Word counts can help a model recognize patterns in text.

Bag of Words Is a Text Representation

A text representation is a way to turn text into a format a model can use. Bag of Words represents text using word counts.

Example

Document 1: I love AI → Vector: 1, 1, 1, 0

Document 2: I love coding → Vector: 1, 1, 0, 1

Vocabulary: I · love · AI · coding

Each number shows whether the word appears or how often it appears.

Vocabulary

A vocabulary is the list of unique words used by the Bag of Words model.

Example

Document 1: cats are cute

Document 2: dogs are loyal

Vocabulary: cats · are · cute · dogs · loyal

Important: Each document is represented using this vocabulary.

Document Vector

A document vector is a list of numbers that represents a document. Each position in the vector matches a word in the vocabulary.

Example

Vocabulary: cat · dog · fish

Document: cat dog cat

Vector: 2, 1, 0

cat appears 2 times · dog appears 1 time · fish appears 0 times

Bag of Words Step by Step

  1. 1Collect text documents
  2. 2Clean the text if needed
  3. 3Tokenize the text into words
  4. 4Build a vocabulary of unique words
  5. 5Count how often each word appears in each document
  6. 6Turn each document into a vector
  7. 7Use the vectors in a machine learning model

Example Dataset

This example shows how three short documents can be converted into Bag of Words vectors.

Example

Document 1: I love cats → Vector: 1, 1, 1, 0, 0

Document 2: I love dogs → Vector: 1, 1, 0, 1, 0

Document 3: Dogs love food → Vector: 0, 1, 0, 1, 1

Vocabulary: I · love · cats · dogs · food

Word Counts

Bag of Words usually counts how often each word appears.

Example

Text: spam spam offer now

Vocabulary: spam · offer · now

Vector: 2, 1, 1

spam appears twice · offer appears once · now appears once

Binary Bag of Words

Binary Bag of Words only records whether a word appears or does not appear.

Example

Text: spam spam offer now

Vocabulary: spam · offer · now

Count Vector: 2, 1, 1

Binary Vector: 1, 1, 1

Meaning: Each word appeared at least once.

Bag of Words for Spam Detection

Bag of Words can help detect spam emails by learning which words often appear in spam messages.

Example

Spam-like Words: win · money · click · offer · free · now

Email: Win a free prize now → Possible Prediction: Spam

Email: Can we meet after class? → Possible Prediction: Not Spam

Bag of Words for Sentiment Analysis

Bag of Words can help detect whether text sounds positive, negative, or neutral.

Example

Positive Words: great · amazing · love · helpful · excellent

Negative Words: bad · terrible · hate · broken · confusing

Text: I love this app. It is amazing.

Possible Sentiment: Positive

Bag of Words for Topic Classification

Bag of Words can help classify documents by topic based on common words.

Example

Sports Words: team · score · game · player · season

Technology Words: software · computer · AI · model · data

Health Words: doctor · patient · medicine · hospital · treatment

Goal: Use word patterns to predict the topic.

Bag of Words for Search

Search systems can use word matching to find documents related to a query.

Example

Query: machine learning basics

Document 1: Machine learning models learn from data.

Document 2: Pizza recipes use cheese and dough.

Likely Better Match: Document 1 — it shares more words with the query.

Bag of Words Ignores Word Order

The biggest limitation of Bag of Words is that it ignores word order.

Example

Sentence 1: Dog bites man.

Sentence 2: Man bites dog.

Same Words: dog · bites · man

Problem: The meanings are different, but Bag of Words may represent them similarly.

Bag of Words Ignores Grammar

Bag of Words does not deeply understand grammar or how words interact in a sentence.

Example

Sentence: The student did not pass.

Important Meaning: not pass

Problem: A simple word-count model may not fully understand how "not" changes the meaning.

Bag of Words Ignores Context

Bag of Words does not understand context well. The same word can have different meanings in different sentences.

Example

Sentence 1: The bank approved my loan.

Sentence 2: The bank was covered in river water.

Problem: The word "bank" has different meanings, but Bag of Words sees the same word.

Sparse Vectors

Bag of Words often creates sparse vectors. A sparse vector has many zeros.

Example

Vocabulary Size: 10,000 words

Document: Uses only 50 unique words

Vector: Most positions are 0

Problem: Sparse vectors can be large and inefficient.

Vocabulary Size Problem

The vocabulary can become very large if the text is messy or not normalized.

Example

Example Variations: hello · Hello · HELLO · hello! · helloo · hellooo

Problem: These may become separate vocabulary entries.

Result: The vocabulary grows too much, making models slower and harder to train.

Preprocessing Helps Bag of Words

Text preprocessing can reduce noise and make Bag of Words more useful.

Helpful Preprocessing Steps
  • Lowercasing
  • Removing punctuation
  • Tokenization
  • Stopword removal
  • Stemming
  • Lemmatization

Before: The cats were running quickly!

After: cat run quick

Lowercasing with Bag of Words

Lowercasing helps treat the same word consistently.

Example

Before Lowercasing: AI · ai · Ai

After Lowercasing: ai · ai · ai

Benefit: Reduces duplicate word forms.

Removing Punctuation with Bag of Words

Removing punctuation can simplify word counts, but punctuation should not always be removed.

Example

Before: hello · hello! · hello!!!

After Punctuation Removal: hello · hello · hello

Benefit: The words are counted together.

Warning: Punctuation can carry emotion or meaning.

Stopword Removal with Bag of Words

Stopword removal can help focus on more meaningful words, but it should be used carefully.

Example

Before: The article is about machine learning.

After: article machine learning

Risk: Removing a word like "not" can change meaning.

Example: "not good" → "good" — that is a serious problem for sentiment analysis.

Stemming with Bag of Words

Stemming helps Bag of Words treat related words as similar.

Example

Words: running · runs · runner

Possible Stem: run

Benefit: Related word forms can be counted together.

Limitation: Stemming can create unnatural forms. Example: studies → studi

Lemmatization with Bag of Words

Lemmatization can group related words while keeping cleaner dictionary forms.

Examples

running → run

better → good

mice → mouse

Benefit: Cleaner than stemming in many cases. Useful when word meaning matters more.

Bag of Words Table Example

Each row represents one document, and each column represents one word in the vocabulary.

Documentcatslikemilkdogsbonesandplay
cats like milk1110000
dogs like bones0101100
cats and dogs play1001011

Bag of Words and Machine Learning

After text is converted into Bag of Words vectors, a machine learning model can use those vectors to learn patterns.

Common Models
  • Logistic regression
  • Naive Bayes
  • Support vector machines
  • Decision trees
  • Random forests

Example: If words like "free", "win", and "click" appear often, the model may predict spam.

Naive Bayes and Bag of Words

Naive Bayes is often used with Bag of Words for simple text classification tasks.

Spam Detection Example

Words Common in Spam: win · free · offer · click

Words Common in Normal Emails: meeting · class · schedule · project

Naive Bayes: Uses word frequencies to estimate the likely class.

CountVectorizer

In many machine learning libraries, Bag of Words is created using a tool often called CountVectorizer.

CountVectorizer Usually
  • Builds a vocabulary
  • Counts word appearances
  • Creates document vectors

Example Documents: I love AI · I love coding

Output: Numerical vectors based on word counts

Bag of Words vs One-Hot Encoding

One-hot encoding often represents one word at a time. Bag of Words represents a whole document using word counts.

Example

Vocabulary: cat · dog · fish

One-Hot for dog: 0, 1, 0

Bag of Words for "cat dog cat": 2, 1, 0

Bag of Words vs TF-IDF

Bag of Words counts word frequency. TF-IDF also considers how important a word is across many documents.

Comparison

Word: the

Bag of Words: May have a high count.

TF-IDF: Usually gives it lower importance because it appears everywhere.

Key Difference: TF-IDF adjusts for common words.

Advantages of Bag of Words

Advantages
  • Simple to understand
  • Easy to implement
  • Works well for basic text classification
  • Useful for spam detection
  • Useful for topic classification
  • Works with many traditional ML models
  • Good baseline for NLP tasks

Baseline: A simple starting model used for comparison.

Limitations of Bag of Words

Limitations
  • Ignores word order
  • Ignores grammar
  • Ignores context
  • Can create very large vectors
  • Can create sparse vectors
  • Does not understand meaning deeply
  • Struggles with sarcasm
  • Struggles with ambiguity
  • Treats similar words as unrelated unless preprocessing helps

Bag of Words vs Word Embeddings

Bag of Words uses word counts. Word embeddings use dense vectors that can capture meaning and similarity.

Comparison

Bag of Words: cat and kitten are different words.

Word Embeddings: cat and kitten may have similar vectors.

Main Difference: Embeddings can capture relationships better than simple word counts.

Bag of Words in Modern NLP

Bag of Words is still useful even though modern NLP often uses embeddings and transformers.

Bag of Words Is Useful For
  • Learning NLP basics
  • Building simple baselines
  • Fast text classification
  • Small datasets
  • Interpretable word-based models
  • Search and keyword matching

When to Use Bag of Words

Bag of Words May Be Good When
  • The task is simple
  • Word counts are useful
  • Data is not too complex
  • You need a fast baseline
  • You want interpretability
  • The dataset is small or medium-sized
  • Word order is not extremely important

Example: Classifying support tickets by topic

When Bag of Words Is Not Enough

Bag of Words May Not Be Enough When
  • Word order matters
  • Context matters
  • Meaning depends on sentence structure
  • The task involves long conversations
  • The task requires deep language understanding
  • The model needs to handle synonyms well
  • The text contains sarcasm or ambiguity

Example: Understanding a complex chatbot conversation

Common Mistakes

Common Mistakes
  • Thinking Bag of Words understands word order
  • Forgetting that Bag of Words ignores context
  • Building a vocabulary before cleaning text
  • Not handling capitalization
  • Removing important words like "not"
  • Using too many rare words
  • Forgetting that vectors can become sparse
  • Using Bag of Words for tasks that need deep meaning
  • Comparing models without using the same preprocessing
  • Assuming higher word count always means higher importance

Summary

Key Takeaways
  • Bag of Words represents text using word counts.
  • It turns documents into numerical vectors.
  • A vocabulary is the list of unique words used by the model.
  • Each document vector shows how often vocabulary words appear.
  • Bag of Words is useful for spam detection, sentiment analysis, topic classification, and search.
  • Bag of Words ignores word order, grammar, and context.
  • Preprocessing can improve Bag of Words.
  • Bag of Words often creates sparse vectors.
  • Bag of Words is simple, interpretable, and useful as a baseline.
  • More advanced methods such as TF-IDF and embeddings can capture more information.

Practice Prompt

Create a Bag of Words representation for these two documents:

Practice

Document 1: I love AI

Document 2: AI helps students

First create the vocabulary. Then create a word count vector for each document. Finally, explain one limitation of Bag of Words.

Need Help?

Ask the AI if you need help understanding Bag of Words, vocabulary, document vectors, word counts, sparse vectors, preprocessing, spam detection, topic classification, or the limitations of Bag of Words.