Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Text analytics: bag of words and TF-IDF

Notes on Bag-of-Words (BoW) and TF‑IDF: definitions, assumptions, formulas, step-by-step numerical example, and a runnable Python implementation that computes raw and L2‑normalized TF‑IDF vectors.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Text data (documents, tweets, logs) must be converted to numeric vectors before most machine learning or visualization. The Bag-of-Words and TF‑IDF (term-frequency × inverse-document-frequency) are simple, widely used ways to convert text into vectors for classification, clustering, search, and feature engineering in systems an engineer builds.

Key ideas

  • Bag-of-Words (BoW) representation: the exact statement used in exams is: a Bag-of-Words representation of a document d is a vector v ∈ ℤ_{≥0}^{|V|} where v_i = count of token i in d. Assumptions: word order and grammar are ignored, only token multiplicities are kept. Diagram to draw for an answer: draw three short documents, list vocabulary horizontally, and draw a table with rows per document and columns per vocabulary token showing integer counts.

  • Term Frequency (TF): several definitions exist. Exact common ones universities accept:

    • Raw count TF: TF(t, d) = number of times term t appears in document d.
    • Normalized TF: TF_norm(t, d) = TF(t, d) / (total tokens in d), to correct for document length.
    • Log-scaled TF: TF_log(t, d) = 1 + log(TF(t, d)) for TF(t,d)>0, else 0. State which TF variant you use when answering a question.
  • Document Frequency (df): df(t) = number of documents in the corpus that contain term t at least once. Assume binary presence for df.

  • Inverse Document Frequency (IDF): the exact common exam definition: IDF(t) = log(N / df(t)) where N is the total number of documents. Assumptions: natural logarithm usually used (log base e); other variants add smoothing: IDF_smooth(t) = log((N + 1)/(df(t) + 1)) + 1; scikit‑learn's default uses this (smooth_idf=True). Always state the variant. IDF down-weights frequent tokens across the corpus (stop words) and up-weights rare but potentially more informative tokens.

  • TF‑IDF weight: TFIDF(t, d) = TF_variant(t, d) × IDF_variant(t). Typical combination: raw TF × log(N/df).

  • Normalization and similarity: After computing TF‑IDF vectors, it is common to L2-normalize each document vector (divide by its Euclidean norm) so that inner-product equals cosine similarity. Draw a small vector and show normalization by length.

  • Use-cases and limitations: BoW/TF‑IDF are simple and fast; they ignore word order, syntax and semantics (no phrases, polysemy or context). They work as baseline features for classification and retrieval, and as inputs to visualization methods described elsewhere in the course (e.g., Document visualisation, Text and document visualisation, and Naive Bayes for text classification).

Formulas

V = {w_1, w_2, ..., w_|V|} — vocabulary (dimensionless)

TF(t,d) = count of term t in document d — count, dimensionless; applies to raw-count TF.

TF_norm(t,d) = TF(t,d) / (total tokens in d) — fraction (dimensionless); applies for length-normalised TF.

TF_log(t,d) = { 1 + log(TF(t,d)) if TF(t,d) > 0; 0 otherwise } — log-scaled TF (dimensionless); applies when diminishing returns for multiple occurrences are desired.

df(t) = |{d in corpus : TF(t,d) > 0}| — number of documents containing term t (dimensionless).

IDF(t) = log(N / df(t)) — inverse document frequency (dimensionless); N = total number of documents; applies when no smoothing is used and df(t) ≥ 1. If df(t)=N then IDF=0.

IDF_smooth(t) = log((N + 1)/(df(t) + 1)) + 1 — a common smoothed IDF (used by scikit‑learn; dimensionless).

TFIDF(t,d) = TF_variant(t,d) × IDF_variant(t) — TF‑IDF weight for term t in document d (dimensionless).

||v||_2 = sqrt(sum_i v_i^2) — L2 norm of vector v (dimensionless); used to normalize document vectors.

v_normalized = v / ||v||_2 — L2-normalized vector; dimensionless; used before cosine similarity.

cosine(u,v) = (u · v) / (||u||_2 ||v||_2) — cosine similarity (dimensionless); equals dot product if u and v are L2-normalized.

Note: units are not physical — all quantities are dimensionless counts or ratios.

Worked examples

Example 1 — numerical, step-by-step (university exam style): Corpus (N = 3 documents): Doc1: "the cat sat on the mat" Doc2: "the dog sat on the log" Doc3: "the cat chased the dog"

Step 1 — build vocabulary in order of first appearance: V = [the, cat, sat, on, mat, dog, log, chased].

Step 2 — raw term counts (BoW table):

  • Doc1 counts: the=2, cat=1, sat=1, on=1, mat=1, dog=0, log=0, chased=0.
  • Doc2 counts: the=2, dog=1, sat=1, on=1, log=1, cat=0, mat=0, chased=0.
  • Doc3 counts: the=2, cat=1, chased=1, dog=1, sat=0, on=0, mat=0, log=0.

Step 3 — document frequencies df(t):

  • df(the)=3; df(cat)=2; df(sat)=2; df(on)=2; df(mat)=1; df(dog)=2; df(log)=1; df(chased)=1.

Step 4 — IDF using natural log: IDF(t) = ln(N / df(t)), N=3:

  • IDF(the) = ln(3/3) = ln(1) = 0.000000
  • IDF(cat) = ln(3/2) ≈ 0.405465
  • IDF(sat) = ln(3/2) ≈ 0.405465
  • IDF(on) = ln(3/2) ≈ 0.405465
  • IDF(mat) = ln(3/1) ≈ 1.098612
  • IDF(dog) = ln(3/2) ≈ 0.405465
  • IDF(log) = ln(3/1) ≈ 1.098612
  • IDF(chased) = ln(3/1) ≈ 1.098612

Step 5 — raw TF‑IDF = TF × IDF for each document (showing nonzero terms):

  • Doc1 TF‑IDF: the: 2×0 = 0; cat: 1×0.405465 = 0.405465; sat: 0.405465; on: 0.405465; mat: 1.098612.
  • Doc2 TF‑IDF: the: 0; dog: 0.405465; sat: 0.405465; on: 0.405465; log: 1.098612.
  • Doc3 TF‑IDF: the: 0; cat: 0.405465; dog: 0.405465; chased: 1.098612.

Step 6 — L2-normalize each TF‑IDF vector (compute norm and divide):

  • Doc1 vector (nonzero entries): [cat=0.405465, sat=0.405465, on=0.405465, mat=1.098612]. Norm = sqrt(0.405465^2 *3 + 1.098612^2) ≈ sqrt(1.700155) ≈ 1.303136. Normalized values: cat ≈ 0.405465/1.303133 ≈ 0.311; sat ≈ 0.311; on ≈ 0.311; mat ≈ 1.098612/1.303133 ≈ 0.843. Final (rounded): [cat=0.311, sat=0.311, on=0.311, mat=0.843].

  • Doc2 same pattern (replace mat by log): [dog=0.311, sat=0.311, on=0.311, log=0.843].

  • Doc3 vector [cat=0.405465, dog=0.405465, chased=1.098612]. Norm = sqrt(0.405465^2*2 + 1.098612^2) ≈ sqrt(1.535753) ≈ 1.239251. Normalized: cat ≈ 0.405465/1.239251 ≈ 0.327; dog ≈ 0.327; chased ≈ 1.098612/1.239251 ≈ 0.887. Final (rounded): [cat=0.327, dog=0.327, chased=0.887].

These normalized TF‑IDF vectors are often used for cosine-similarity computations or as input features to classifiers.

Example 2 — Python program (manual TF‑IDF computation, runnable):

# tfidf_manual.py - compute raw and L2-normalized TF-IDF
import math

corpus = [
    "the cat sat on the mat",
    "the dog sat on the log",
    "the cat chased the dog"
]

# Build vocabulary in order of first occurrence
vocab = []
for doc in corpus:
    for token in doc.split():
        if token not in vocab:
            vocab.append(token)

N = len(corpus)

# Term counts per document
counts = []
for doc in corpus:
    tokens = doc.split()
    dcount = {w: 0 for w in vocab}
    for t in tokens:
        dcount[t] += 1
    counts.append(dcount)

# Document frequencies
df = {w: 0 for w in vocab}
for w in vocab:
    for d in counts:
        if d[w] > 0:
            df[w] += 1

# IDF (natural log, no smoothing)
idf = {w: math.log(N / df[w]) for w in vocab}

# Compute TF-IDF (raw TF x IDF) and then L2 normalize
tfidf_raw = []
for d in counts:
    vec = [d[w] * idf[w] for w in vocab]
    tfidf_raw.append(vec)

# L2 normalization
def l2_norm(v):
    s = sum(x*x for x in v)
    return math.sqrt(s) if s > 0 else 1.0

tfidf_norm = []
for vec in tfidf_raw:
    norm = l2_norm(vec)
    tfidf_norm.append([x / norm for x in vec])

# Print results
print('vocab =', vocab)
print('\nIDF:')
for w in vocab:
    print(f"  {w}: {idf[w]:.6f}")

print('\nTF-IDF (raw):')
for i, vec in enumerate(tfidf_raw, 1):
    print(f"Doc{i}:", ['{:.6f}'.format(x) for x in vec])

print('\nTF-IDF (L2-normalized):')
for i, vec in enumerate(tfidf_norm, 1):
    print(f"Doc{i}:", ['{:.6f}'.format(x) for x in vec])

Sample input: the program uses the corpus defined inside the file (no stdin). Exact output when run (values rounded to 6 decimals): vocab = ['the', 'cat', 'sat', 'on', 'mat', 'dog', 'log', 'chased']

IDF: the: 0.000000 cat: 0.405465 sat: 0.405465 on: 0.405465 mat: 1.098612 dog: 0.405465 log: 1.098612 chased: 1.098612

TF-IDF (raw): Doc1: ['0.000000', '0.405465', '0.405465', '0.405465', '1.098612', '0.000000', '0.000000', '0.000000'] Doc2: ['0.000000', '0.000000', '0.405465', '0.405465', '0.000000', '0.405465', '1.098612', '0.000000'] Doc3: ['0.000000', '0.405465', '0.000000', '0.000000', '0.000000', '0.405465', '0.000000', '1.098612']

TF-IDF (L2-normalized): Doc1: ['0.000000', '0.311104', '0.311104', '0.311104', '0.842683', '0.000000', '0.000000', '0.000000'] Doc2: ['0.000000', '0.000000', '0.311104', '0.311104', '0.000000', '0.311104', '0.842683', '0.000000'] Doc3: ['0.000000', '0.327127', '0.000000', '0.000000', '0.000000', '0.327127', '0.000000', '0.886818']

(These numeric values match the manual worked example up to rounding.)

Common mistakes

  • Failing to L2-normalize when the question asks for cosine similarity — forgetting that raw TF‑IDF dot product is not cosine unless normalized.
  • Building vocabulary inconsistently (different order across answers) — for vector listings, fix an order and state it.
  • Confusing document frequency df(t) with term frequency TF(t,d).
  • Using sklearn's default TF‑IDF (which uses smoothing and adds 1) without noting the difference in formula and numeric results.

For your exam

Kinds of questions you will get:

  • Definitions: define Bag-of-Words, TF, DF, IDF, TF‑IDF, and normalization.
  • Short notes: explain advantages/disadvantages of BoW and TF‑IDF and where used in an engineering pipeline (feature extraction for Naive Bayes, clustering, search ranking).
  • Derivations: show step-by-step computation of TF‑IDF for a small corpus (draw the BoW table and compute DF, IDF, TF‑IDF, normalization). Show the diagram (table) as described in Key ideas.
  • Numericals: compute TF‑IDF raw and normalized vectors (carry units: dimensionless counts) and compute cosine similarity between two documents.
  • Programs: write code to compute TF‑IDF (manual or using sklearn). A full-marks program answer should show: building vocab deterministically, computing df, computing chosen IDF formula, computing TF‑IDF, and showing normalization. Include sample outputs.

What a full-marks answer includes: clear statement of definitions and chosen variants, the BoW table, computed df and IDF values with the log base specified, TF‑IDF calculation steps, norm and normalized vectors, and comments on effects (e.g., stop-words getting low IDF).

Quick check

  1. Define Bag-of-Words in one sentence.
  2. Give the formula for IDF (unsmoothed) and say what happens when a term appears in every document.
  3. Why normalize TF‑IDF vectors before cosine similarity?

Answers: 1) A Bag-of-Words is a vector representation of a document where each component is the count of a vocabulary term, ignoring word order and grammar. 2) IDF(t)=ln(N/df(t)); if df(t)=N then IDF(t)=0 (term gives no discriminating weight). 3) Normalization (L2) makes vector length 1 so dot product equals cosine similarity and removes document-length bias.

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?