Skip to content
BIASED

Bag of words

Block 1 of 6~2 min

From a protocol to count vectors

Corpora and evaluation fixed the fitting and measurement boundaries. We can now inspect a complete count-based representation inside those boundaries.

Four equipment-desk messages are enough to build a complete text representation by hand. We can count their words, rank them for a query, and fit a small classifier. The same calculation also reveals exactly what this representation cannot distinguish.

Baseline: counting tokens

Fix a vocabulary with VV entries and an order for those entries. For document dd, let xdjx_{dj} be the number of occurrences of vocabulary token jj. The vector xd∈RVx_d\in\mathbb R^V is a bag-of-words representation: it retains multiplicities and discards order. The word bag distinguishes counts from a set, which records presence only.

The vocabulary is fitted on permitted training text. At prediction time, its order remains fixed. A token absent from the vocabulary contributes no coordinate under the simple policy used here. A document containing only unknown tokens therefore becomes a zero vector. Record this case rather than pretending that zero means an ordinary average document.

Our complete constructed collection is:

Document Text
1 desk lamp lamp pickup
2 desk lamp return
3 desk tripod return
4 desk tripod tripod pickup

We use whitespace tokens and the vocabulary order desk, lamp, pickup, return, tripod. The count matrix is

X=(12100110101001110102).X=\begin{pmatrix} 1&2&1&0&0\\ 1&1&0&1&0\\ 1&0&0&1&1\\ 1&0&1&0&2 \end{pmatrix}.

Rows are documents and columns are vocabulary entries. Twelve of the twenty cells are nonzero. Larger vocabularies often make each document sparse because one document contains only a subset of all possible tokens. Sparse storage records the occupied coordinates rather than allocating every zero. Its benefit depends on the number of nonzeros and indexing overhead; a tiny dense matrix like ours does not demonstrate a storage benchmark.

Answers are saved on the server and tied to this browser until you sign in.

Go deeper — optional

Code and labs do not count toward the main percentage or the certificate.

  • Reproduce the count-based modeloptional

    Inspect the full fictional inputs, rerun the standard-library calculations, and check the stated invariants. Optional desktop practice.

    ~15 min · easier on a computer

    Self-check in the notebook — not part of mastery or the certificate.