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.

Vector space model and cosine ranking

Vector space model represents documents and queries as vectors in a common term space and ranks documents by the cosine of the angle between their vectors (cosine similarity).

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

Engineers use the vector space model when building search features: it converts text (documents and queries) into numeric vectors so the system can compute similarity and return ranked results. Cosine ranking is a simple, fast, and interpretable way to order results and is the basis for many practical retrieval systems and learning-to-rank methods.

Key ideas

  • Term: a distinct word or token from preprocessing steps (tokenisation, stemming, stopword removal). We assume terms are known and fixed; this defines the dimensionality t of the space.

  • Document-term matrix: a matrix D of size (number_of_documents) × t where entry D[d,t] is the weight of term t in document d.

  • Term frequency (TF): the (possibly transformed) count of times a term appears in a document. Bold definition: term frequency is the raw count of occurrences of a given term in one document, often denoted tf_{t,d}.

  • Inverse document frequency (IDF): Bold definition: inverse document frequency measures how rare a term is across the whole collection. A common form is idf_t = log(N / df_t), where N is number of documents and df_t is the number of documents containing term t. IDF downweights very common terms.

  • TF–IDF weight: Bold definition: TF–IDF for term t in document d is a product w_{t,d} = tf_{t,d} · idf_t (variants include log-scaling for tf and idf). This is the most common weighting that balances term importance inside a document and across the collection.

  • Vector representation: If vocabulary has t terms, a document d is a vector v_d = (w_{1,d}, w_{2,d}, ..., w_{t,d}). A query is also represented as a vector in the same t-dimensional space.

  • Dot product (inner product): Bold definition: dot product of two vectors x and y is x · y = sum_i x_i y_i. For text vectors, the dot product measures raw overlap in weighted terms.

  • Euclidean norm (length): Bold definition: the Euclidean norm of vector x is ||x|| = sqrt(x · x).

  • Cosine similarity: Bold definition: cosine similarity between vectors x and y is cos(θ) = (x · y) / (||x||·||y||). Cosine similarity measures the angle between vectors and is independent of vector lengths (document lengths); values range from -1 to 1 (for non-negative TF–IDF, 0..1). If either vector has zero length (all weights zero), the cosine is undefined; practical systems drop such vectors or apply smoothing.

Assumptions behind the model (important to state in exam answers):

  • Terms are treated as independent dimensions (no term-term correlation unless you add latent methods such as LSI).
  • Basis vectors are conceptually orthogonal: a document with only one term has nonzero component in that single dimension.
  • Weighting scheme (tf, idf, normalization) strongly affects ranking; there is no single universally correct choice.

Derivation universities commonly ask for (cosine from dot product):

  1. Represent documents and queries as vectors v and q.
  2. Dot product v·q = sum_i v_i q_i measures overlap in terms.
  3. To remove bias from document length, divide by product of lengths: cos(θ) = (v·q) / (||v||·||q||). This is the cosine of the angle θ between v and q (by Euclidean geometry). The ranking by decreasing cos(θ) is equivalent to ranking by decreasing projection of one vector onto the other when lengths are fixed. If you L2-normalize all vectors to unit length, cosine similarity equals the dot product of the normalized vectors.

Diagram to draw (exam instruction):

  • Draw a 2D coordinate system with axes labelled term1 on x-axis and term2 on y-axis (each axis represents weight for a term).
  • Plot two vectors: one for the query q and one for a document d.
  • Draw the angle θ between them and label the projection of q onto d.
  • Label ||q||, ||d||, and show that q·d = ||q||·||d||·cos(θ).

Formulas

v_d = (w_{1,d}, w_{2,d}, ..., w_{t,d})

  • v_d: document vector for document d, dimensionless, applies after you compute term weights for the chosen vocabulary.

tf_{t,d} = count(term t in document d)

  • tf_{t,d}: term frequency (count, dimensionless), applies when using raw counts.

idf_t = log(N / df_t)

  • idf_t: inverse document frequency, dimensionless, where N is total number of documents, df_t is number of documents containing term t; log base unspecified (common choices: natural log or base 10); applies when using classic idf weighting.

w_{t,d} = tf_{t,d} * idf_t (TF–IDF weight)

  • w_{t,d}: weight of term t in document d, dimensionless, applies with multiplicative TF–IDF weighting. Variants: w = (1 + log(tf)) * idf or w = (tf / max_tf_in_doc) * idf.

x · y = sum_{i=1..t} x_i * y_i

  • Dot product, dimensionless, applies to any two vectors in same space.

||x|| = sqrt(x · x)

  • Euclidean norm (length) of vector x, dimensionless, applies in Euclidean geometry.

cos(theta) = (x · y) / (||x|| * ||y||)

  • Cosine similarity; theta is the angle between x and y, dimensionless (value in [-1,1]); for non-negative weights normally in [0,1]. Applies when comparing documents and queries represented as vectors.

Worked examples

Example 1 — numerical TF–IDF and cosine ranking (model exam question)

Given 3 documents (N = 3) and vocabulary of three terms: information, retrieval, vector. The document term counts are:

  • Doc1: information=3, retrieval=0, vector=1
  • Doc2: information=0, retrieval=2, vector=1
  • Doc3: information=1, retrieval=1, vector=0 Query: "information vector" (counts: information=1, retrieval=0, vector=1)

Step 1 — compute df and idf (use natural log):

  • df_information = 2 => idf_information = ln(3/2) = 0.405 (dimensionless)
  • df_retrieval = 2 => idf_retrieval = ln(3/2) = 0.405
  • df_vector = 2 => idf_vector = ln(3/2) = 0.405

Step 2 — compute TF–IDF weights w_{t,d} = tf * idf

  • Doc1 vector v1 = [30.405, 00.405, 1*0.405] = [1.215, 0.000, 0.405]
  • Doc2 vector v2 = [00.405, 20.405, 1*0.405] = [0.000, 0.810, 0.405]
  • Doc3 vector v3 = [10.405, 10.405, 0*0.405] = [0.405, 0.405, 0.000]
  • Query q = [10.405, 00.405, 1*0.405] = [0.405, 0.000, 0.405]

Step 3 — compute norms

  • ||q|| = sqrt(0.405^2 + 0.405^2) = sqrt(0.1640 + 0.1640) = sqrt(0.3280) = 0.573
  • ||v1|| = sqrt(1.215^2 + 0.405^2) = sqrt(1.4762 + 0.1640) = sqrt(1.6402) = 1.281
  • ||v2|| = sqrt(0.810^2 + 0.405^2) = sqrt(0.6561 + 0.1640) = sqrt(0.8201) = 0.906
  • ||v3|| = sqrt(0.405^2 + 0.405^2) = 0.573

Step 4 — dot products and cosine similarities

  • q · v1 = 0.4051.215 + 0.4050.405 = 0.4921 + 0.1640 = 0.6561 -> cos(q,v1) = 0.6561 / (0.573 * 1.281) = 0.6561 / 0.734 ≈ 0.893

  • q · v2 = 0.4050 + 0.4050.405 = 0.1640 -> cos(q,v2) = 0.1640 / (0.573 * 0.906) = 0.1640 / 0.519 ≈ 0.316

  • q · v3 = 0.4050.405 + 0.4050 = 0.1640 -> cos(q,v3) = 0.1640 / (0.573 * 0.573) = 0.1640 / 0.328 = 0.500

Final ranking by cosine (highest first): Doc1 (≈0.893), Doc3 (0.500), Doc2 (≈0.316). Bold result: Doc1, Doc3, Doc2.

(Explain: Doc1 ranks highest because it contains both query terms; Doc3 and Doc2 each share only one query term, and both terms have the same nonzero idf in this collection.)

Example 2 — short model answer (theory question)

Question: "Explain why cosine similarity reduces length bias and show one drawback of the vector space model."

Model answer (short): Cosine similarity divides the dot product by the product of vector lengths: cos(θ) = (v·q)/(||v||·||q||). If a document is a scaled-up copy of another (same term proportions but longer), the cosine between those two documents equals 1; moreover, for any fixed query q, cos(q,d) is unchanged by scaling d, so ranking does not prefer longer documents — thus cosine removes length bias. A drawback is the independence assumption: terms are orthogonal dimensions, so synonyms and word order are ignored; semantic connections are not captured unless expanded by techniques like LSI or query expansion.

Common mistakes

  • Mixing different TF variants without stating which one is used (raw tf vs log-tf vs normalised tf).
  • Confusing Euclidean distance with cosine similarity: smaller Euclidean distance is not the same as larger cosine similarity unless vectors are normalised.
  • Using log base without specifying (exam answers should say which log and use it consistently).
  • Treating negative cosine as meaningful in standard TF–IDF (weights are non-negative so cosine is normally 0..1).

For your exam

Kinds of questions you will see:

  • Definitions: define vector space model, TF, IDF, TF–IDF, cosine similarity. (Short precise definitions required.)
  • Short notes: explain advantages/limitations, show effect of normalization. (Give assumptions and one example.)
  • Derivations: derive cosine similarity from dot product and show algebraic steps for normalization. (Show vector algebra and geometry.)
  • Numericals: compute TF–IDF weights and cosine similarity for small collections. (Show arithmetic steps and rounding.)
  • Diagram: draw vectors in 2D and label angle θ and projections. (Draw axes labelled by two terms and two vectors.)

What a full-marks answer includes:

  • Clear definitions with bolding of terms (in written exams state the term and its mathematical symbol).
  • Statement of assumptions (term independence, weighting choices).
  • Correct formulas with symbols defined and units (dimensionless).
  • For numericals: all steps, intermediate values, norms, dot products, and final ranking with numeric cosine values.
  • For theory: at least one practical limitation and one real-world use.

Quick check

  1. What does IDF measure in one sentence?
  2. Write the formula for cosine similarity between vectors x and y.
  3. If two document vectors are scalar multiples of each other, what is their cosine similarity?

Answers: 1) IDF measures how rare (informative) a term is across the document collection (inverse of document frequency). 2) cos(θ) = (x · y) / (||x|| * ||y||). 3) Cosine similarity = 1 (they point in the same direction).

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

Stuck on something here?