Bag of Words and TF-IDF: Build Text Feature Vectors by Hand
Turn three short documents into numbers by hand. Build one fixed vocabulary, count Bag of Words features, calculate unsmoothed IDF, and compare the final vectors.
KnowledgeGate Team
Exam prep & CS education

A model cannot calculate directly with sentences. Every document must become a fixed-length numeric vector.
The same three documents produce a Bag of Words matrix and then TF-IDF weights, starting with cleaned tokens. The arithmetic uses raw term frequency and natural-log IDF throughout, so the convention does not change halfway through the example.
What Bag of Words and TF-IDF turn text into
A corpus is the full text collection. Each text is a document, and each cleaned unit is a token. The distinct tokens form a vocabulary, whose terms become positions in a feature vector.
Bag of Words records how many times each vocabulary term occurs in a document. TF-IDF keeps the same columns, but reduces the influence of terms that appear in many documents.
Both representations are matrices: rows are documents, columns are terms, and every row follows one column order. Unigram Bag of Words loses word order, so data uses science and science uses data have identical counts.
This calculation fits the broader Coding & Skills path. Afterwards, try the Introduction to Natural Language Processing MCQs as a concept check.
Freeze the preprocessing rules and construct the vocabulary
Use these three source documents:
D1:
Data science uses data.D2:
Machine learning uses data.D3:
Machine learning learns patterns.
Apply only lowercasing and punctuation removal. Do not remove stop words, stem, or lemmatise. The tokens are:
D1 =
[data, science, uses, data]D2 =
[machine, learning, uses, data]D3 =
[machine, learning, learns, patterns]
learning and learns remain separate because lemmatisation is not selected.
Deduplicate the combined tokens and freeze this required seven-term feature order:
V = [data, learns, learning, machine, patterns, science, uses]
Every vector and table uses that exact order.

Build the Bag of Words matrix by hand
Count every occurrence, not only presence. Thus data has count 2 in D1.
Document | data | learns | learning | machine | patterns | science | uses |
|---|---|---|---|---|---|---|---|
D1 | 2 | 0 | 0 | 0 | 0 | 1 | 1 |
D2 | 1 | 0 | 1 | 1 | 0 | 0 | 1 |
D3 | 0 | 1 | 1 | 1 | 1 | 0 | 0 |
Reading each row in the locked vocabulary order gives:
D1 =
[2, 0, 0, 0, 0, 1, 1]D2 =
[1, 0, 1, 1, 0, 0, 1]D3 =
[0, 1, 1, 1, 1, 0, 0]
Each row sums to 4, matching its source tokens. Three rows and seven columns give shape 3 x 7.
The vectors are interpretable and sparse, but preserve neither order nor meaning. Synonyms stay separate unless preprocessing maps them together.
Calculate document frequency and inverse document frequency
State the formula before calculating:
TF(t,d) = raw count of term t in document ddf(t) = number of documents containing term tN = 3IDF(t) = ln(N / df(t))
Use the natural logarithm and round only displayed final values to four decimals. Document frequency measures presence, so data has df = 2 although its corpus count is 3.
Term | df | IDF calculation | IDF |
|---|---|---|---|
data | 2 |
| 0.4055 |
learns | 1 |
| 1.0986 |
learning | 2 |
| 0.4055 |
machine | 2 |
| 0.4055 |
patterns | 1 |
| 1.0986 |
science | 1 |
| 1.0986 |
uses | 2 |
| 0.4055 |
learns, patterns, and science get the larger weight because each appears in one document. Under this unsmoothed convention, a term in all three would get ln(3/3) = 0.
Multiply TF by IDF and read the weighted vectors
TF-IDF is the raw count multiplied by the term's IDF. Work D1 in full with unrounded IDF values:
data = 2 x ln(3/2) = 0.8109science = 1 x ln(3/1) = 1.0986uses = 1 x ln(3/2) = 0.4055
Every absent term remains zero. Applying the same multiplication to all rows gives:
Document | data | learns | learning | machine | patterns | science | uses |
|---|---|---|---|---|---|---|---|
D1 | 0.8109 | 0 | 0 | 0 | 0 | 1.0986 | 0.4055 |
D2 | 0.4055 | 0 | 0.4055 | 0.4055 | 0 | 0 | 0.4055 |
D3 | 0 | 1.0986 | 0.4055 | 0.4055 | 1.0986 | 0 | 0 |
In D1, one science weighs 1.0986, more than two data occurrences at 0.8109. In D3, learns and patterns outrank shared machine and learning.
For an optional check, D1 and D2 have Bag of Words cosine similarity 3 / (sqrt(6) x 2) = 0.6124. Their TF-IDF cosine similarity is approximately 0.4270. Downweighting shared, less distinctive terms reduces measured similarity.
This sparse baseline is transparent. Contrast it with later learned representations through the Artificial Neural Networks MCQs.

Avoid the mistakes that silently change the answer
Several small choices can produce a different matrix:
Changing vocabulary order makes rows incomparable. Freeze one order and reuse it.
Using corpus frequency instead of document frequency changes IDF. Count documents containing the term.
Rounding 0.4055 before every multiplication creates drift. Keep full precision internally and round for display.
Mixing
ln(N/df)with a library's smoothed formula produces different weights. State the convention first.
Fitting vocabulary or IDF on validation or test text leaks information. Stop-word removal can delete context. Stemming or lemmatisation changes features, unigrams lose order, and a growing vocabulary creates high-dimensional sparse matrices.
For new text Data learns quickly, the fixed vocabulary gives [1, 1, 0, 0, 0, 0, 0]. The unseen quickly is ignored, and IDF is not recomputed. N-grams, hashing, or an unknown-token policy are possible remedies.
How exams and interviews test the idea
Use these short prompts to check whether the calculation is genuinely clear:
Why is the vocabulary size 7?
Why does D1's Bag of Words row sum to 4?
Which terms have the maximum IDF of 1.0986?
Why do
learningandlearnsoccupy different columns?
These classroom, viva, and interview checks follow directly from the preprocessing rules, matrix order, and formula.
To verify in code, create the same strings, request the locked vocabulary order, and inspect the count matrix. Configure TF-IDF for raw TF and unsmoothed IDF before comparing values. Python, from concepts to coding questions is a practical implementation path.
The short version
Bag of Words turns documents into count vectors. TF-IDF multiplies those counts by corpus-level distinctiveness. Both representations depend on one fixed preprocessing and vocabulary contract.
Build the matrix once by hand before trusting library defaults. To move from this baseline to tokenisation, embeddings, transformers, and applied machine learning, continue with Artificial Intelligence, including tokenisation and embeddings.
Keep learning
Natural Language Processing Explained: Pipeline, TF-IDF Worked Example and Exam Patterns
Start from raw text, build BoW and TF-IDF vectors, compute cosine similarity, examine ambiguity, and finish with evaluation and exam-style checks.
Logical Sequence of Words: Step-by-Step Method, Shortcuts and Solved Examples
Learn to identify the relation and direction in word-sequencing questions, join forced pairs, and verify every link through four worked patterns.
Random Forests: Bootstrap Sampling, Feature Subsets, and a 3-Tree Worked Example
See exactly where randomness enters a random forest by building three shallow trees, tracing their votes, and calculating a toy out-of-bag score.
Covariance and Correlation for Machine Learning: Read Feature Relationships Correctly
Calculate covariance and Pearson correlation by hand, then see how units, influential points and nonlinear patterns change what the numbers mean.





