Guide to AI and Data Courses · Lecture Notes

Chapter 28: Information Retrieval and Recommender Systems

When we type two words into a search box the answer arrives in milliseconds, although millions of documents stand behind it and reading them one by one would be impossible. A video platform, meanwhile, suggests the next video without our typing anything. Both systems produce a ranked list, and the hard part is getting the first few lines of that list right. These notes introduce the course and work through its three core ideas with small examples you can compute by hand: the inverted index that makes finding documents fast, the ranking metrics that measure a list, and the collaborative filtering that recommends from past behavior.

Learning outcomes

Inverted index
Build the inverted index of a small collection and answer a two-term Boolean query by intersecting lists.
Scoring
Score and rank documents with term frequency and inverse document frequency.
Ranking metrics
Compute P@k, recall, AP and NDCG for a ranked list by hand.
Recommendation
Make a neighborhood-based prediction from a user-item rating table and carry out one gradient step of matrix factorization.
Place of the course
State what separates information retrieval from data mining, natural language processing, machine learning and social network analysis.

28.1What question does the course ask?

How are the most relevant documents or products picked from millions of candidates?

Information retrieval studies systems that find the documents most relevant to a query among millions and rank them. Recommender systems do the same job without a query: they predict what a user will like from past behavior. Both return a ranked list, not an answer.

In information retrieval we have a collection of documents and a need in the user's mind. The need is usually expressed as a query of a few words and it is ambiguous: does the person typing "jaguar" want the animal or the car? So the system produces not "the right answer" but an order that puts the documents most likely to be relevant at the top. Success is measured by how close to the top of the list the relevant documents stand.

The first half of the course works on the two components of this problem. Speed: to reach only the documents that contain the query terms without scanning millions of them, an inverted index is built. Order: the documents found are scored (TF-IDF, BM25) and arranged by estimated relevance. In the second half the query disappears; a recommender system tries to guess what a user will want from past behavior.

28.1.1Why this is not a machine learning course

In machine learning, success is mostly predicting individual examples correctly. Here it is not the individual prediction but the order of the list that matters: a user looks at the first three results and never at the hundredth. That is why rank-aware metrics are used instead of accuracy. Learning methods certainly appear in the course (learning to rank, matrix factorization), but what defines the problem is the need to produce a ranked list.

28.1.2At a glance

CriterionInformation Retrieval and Recommender Systems
Approachmatching and ranking
Inputquery, documents, user history
Outputranked result list
Success measureprecision, recall, NDCG
Math loadmedium: vector spaces
Data needslots of interaction data

28.2A short history

YearMilestone
1972Spärck Jones proposes inverse document frequency (IDF): a rare term says more.
1975Salton and colleagues publish the vector space model: documents and queries are term vectors.
1992Xerox PARC's Tapestry system coins the term "collaborative filtering".
1998Brin and Page introduce the Google search engine, built on PageRank.
2006The Netflix Prize begins; matrix factorization stands out in the winning solutions.
2020Dense vector retrieval and retrieval-augmented generation (RAG) begin to spread.

28.3Core concepts

The rest of the course is built on the concepts below. The following sections work through the most important ones with examples.

ConceptMeaning
Inverted indexFor each term, a list of the documents containing it.
TF-IDF and BM25Scoring documents by term frequency and rarity.
Vector space modelMeasuring similarity by the cosine of the angle.
Precision, recallShare of results that are relevant; share of relevant ones found.
Ranking metricsMAP, MRR, NDCG: position in the list matters.
Collaborative filteringRecommending from what similar users liked.
Matrix factorizationSplitting the user-item table into latent factors.
Cold startNew users or items with no history.

28.4The inverted index and scoring

It is impossible to read every document from start to finish for each query. An inverted index is like the index at the back of a book: for every term in the dictionary, the numbers of the documents that contain it are kept in a sorted list, the postings list. When a query arrives, only the lists of the query terms are consulted.

Definition 28.1 (Boolean query and list intersection)

For the query "A and B" the two postings lists are scanned together. The pointer at the smaller number is advanced; when the numbers are equal the document goes into the result. The two lists are scanned in a number of steps equal to the sum of their lengths, independent of the number of documents.

Example 28.1: An index of four documents

Four short documents: D1 = "cat drinks milk, loves milk"; D2 = "dog eats bone"; D3 = "cat plays with dog"; D4 = "cat likes milk and fish". The query is "cat milk".

  1. Index. cat → {1, 3, 4}; milk → {1, 4}; dog → {2, 3}.
  2. Boolean AND. Intersect {1, 3, 4} with {1, 4}: 1 = 1 add; 3 < 4, skip 3; 4 = 4 add. Result {1, 4}.
  3. Inverse document frequency. N = 4 documents. idf = log10(N / df): for cat log10(4/3) ≈ 0.125, for milk log10(4/2) ≈ 0.301. The rarer "milk" carries more weight.
  4. Term weight. w = (1 + log10 tf) · idf. In D1 "milk" occurs twice: 1 + log10 2 ≈ 1.301.
  5. Scores. D1: 0.125 · 1 + 0.301 · 1.301 ≈ 0.517; D4: 0.125 + 0.301 ≈ 0.426; D3 (cat only): 0.125; D2: 0.

The order is D1, D4, D3, D2. The Boolean query treated D1 and D4 as equal; scoring put D1 first because it mentions "milk" more often. D2 contains no query term, so it was never even seen in the postings lists.

Real systems have the same two steps: the inverted index narrows the candidate set very quickly, and scoring ranks the candidates. BM25 is the probabilistic form of this scoring that saturates term frequency (a repeated term's contribution does not grow without bound) and corrects for document length; the sum above uses the same skeleton.

Common mistake

Assuming every word is worth the same. If a term occurs in all the documents of the collection, idf = log10(N/N) = 0 and it does not separate documents. Had the example index contained a word in every document, adding it to the query would not have changed the ranking at all. Dropping words like "the" and "a" (stop words) is the practical consequence of this observation.

28.5Evaluating a ranking

Is a search system good? To say so we need queries, documents, and human judgments saying whether each document is relevant (the Cranfield collection is the classic of this approach). The system returns a ranked list for a query; the metric compares that list with the judgments. Because order matters, the precision and recall of machine learning are not enough; we need metrics that weight the front of the list.

Definition 28.2 (The main ranking metrics)

P@k: the share of the first k results that are relevant. Recall@k: the share of the collection's relevant documents found in the first k. AP (average precision): the sum of the P@k values computed at the rank of each relevant document, divided by the total number of relevant documents in the collection. NDCG: for graded relevance, the gain discounted by position, DCG = Σ gi / log2(i + 1), divided by the DCG of the perfect ranking.

Example 28.2: Four metrics on one list

In the first five results of a query the relevant (1) and non-relevant (0) documents are, in order, 1, 0, 1, 1, 0. The collection holds 4 relevant documents for this query in total.

  1. P@5. 3 of the 5 results are relevant: 3/5 = 0.6.
  2. Recall@5. 3 of the 4 relevant documents were retrieved: 3/4 = 0.75.
  3. AP. The relevant documents are at ranks 1, 3 and 4. P@1 = 1/1, P@3 = 2/3, P@4 = 3/4. AP = (1 + 0.667 + 0.75) / 4 ≈ 0.604. The divisor is 4, not 3: the relevant document that was not retrieved lowers the score.
  4. NDCG@5. Let the graded judgments (3 highly relevant, 0 irrelevant) be 3, 2, 3, 0, 1 in order. DCG = 3/1 + 2/1.585 + 3/2 + 0/2.322 + 1/2.585 ≈ 3 + 1.262 + 1.5 + 0 + 0.387 ≈ 6.15. The perfect order is 3, 3, 2, 1, 0: 3 + 1.893 + 1 + 0.431 + 0 ≈ 6.32. NDCG ≈ 6.15 / 6.32 ≈ 0.97.

(The judgments in the last step are illustrative; the log base is 2 and the gain is the grade itself. Some sources write the gain as 2g − 1.)

On a single query a metric is noisy, so values are averaged over tens or hundreds of queries: the mean of AP is called MAP. When only the position of the first relevant result matters (for example "I want a single answer"), the reciprocal rank is used: if the first relevant document is at rank 2, the query scores 1/2.

Common mistake

Forgetting that P@k ignores order inside the first k. Whether the two relevant documents are at ranks 1 and 2 or at ranks 4 and 5, P@5 = 0.4. AP gives (1 + 1)/2 = 1 in the first case and (1/4 + 2/5)/2 = 0.325 in the second, and shows the difference.

28.6Collaborative filtering and matrix factorization

A recommender system has no query; what we have are the ratings users gave to items (or views, or clicks). The data form a user × item table in which most cells are empty. Collaborative filtering rests on one assumption: users who showed similar tastes in the past will show similar tastes in the future. There are two common ways to fill an empty cell: average the ratings of similar users (neighborhood-based) or split the table into latent factors (matrix factorization).

Example 28.3: A neighborhood-based prediction

Users rate four items (i1–i4): A = (5, 4, ?, 1), B = (5, 5, 4, 1), C = (1, 2, 5, 4). We predict the rating A would give to i3.

  1. Common items. A and B have both rated i1, i2, i4: A = (5, 4, 1), B = (5, 5, 1), C = (1, 2, 4).
  2. Cosine similarity A–B. (25 + 20 + 1) / (√42 · √51) = 46 / (6.481 · 7.141) ≈ 0.994.
  3. Cosine similarity A–C. (5 + 8 + 4) / (√42 · √21) = 17 / (6.481 · 4.583) ≈ 0.572.
  4. Weighted average. B gave i3 a 4, C a 5: (0.994 · 4 + 0.572 · 5) / (0.994 + 0.572) ≈ 4.37.

Item i3 would be recommended to A with a high rating. The prediction sits closer to B's rating because B is more similar to A.

Common mistake

Forgetting that cosine on raw ratings makes all users look alike. Above, A and C have opposite tastes and still came out 0.57 similar, because every rating is positive. In practice each user's mean rating is subtracted first (the Pearson correlation or centered cosine), so that "above or below one's own average" is what gets compared.

28.6.1Matrix factorization

In matrix factorization every user gets a vector pu and every item a vector qi (latent factors: say "amount of action", "sentimentality"). The prediction is the dot product r̂ = pu · qi. The vectors are learned by minimizing the squared error on the known ratings. This idea, which stood out in the Netflix Prize, is trained with gradient descent in the same way as in a machine learning course.

Example 28.4: One gradient step

User vector p = (1, 0.5), item vector q = (2, 1), true rating r = 4, learning rate η = 0.1 (no regularization).

  1. Prediction. r̂ = 1 · 2 + 0.5 · 1 = 2.5; error e = r − r̂ = 1.5.
  2. Update. p ← p + η e q = (1 + 0.3, 0.5 + 0.15) = (1.3, 0.65); q ← q + η e p = (2 + 0.15, 1 + 0.075) = (2.15, 1.075) (both computed from the old values).
  3. New prediction. 1.3 · 2.15 + 0.65 · 1.075 ≈ 3.49: the error fell from 1.5 to 0.51.

This step is repeated many times over all the known ratings. After training, the prediction for an empty cell is again a dot product; items are sorted by their predictions and the first few are shown as recommendations. A new user or item with no ratings gets no learned vector: this is the cold-start problem.

28.7How is the course taught?

28.7.1A typical workflow

Collectcrawls,interaction logsIndexinverted index,vector indexRetrievethousands offast candidatesRanklearnedrankerEvaluateNDCG,A/B test
Figure 28.1: A typical workflow in Information Retrieval and Recommender Systems

A video platform collects watch logs, indexes videos as vectors, retrieves a few hundred candidates from millions, ranks them by probability of being watched, and compares the new ranker with the old one in an A/B test.

28.7.2Topics over the semester

  1. Boolean retrieval and the inverted index
  2. Index construction, compression and dictionaries
  3. Text preprocessing: tokenization, stemming
  4. Scoring: TF-IDF and the vector space model
  5. Probabilistic retrieval and BM25
  6. Evaluating retrieval: precision, MAP, NDCG
  7. Link analysis: PageRank and HITS
  8. Learning to rank
  9. Dense retrieval and approximate nearest neighbors
  10. Content-based recommendation
  11. Collaborative filtering and matrix factorization
  12. Evaluating recommenders: offline metrics, A/B tests

This is a typical semester; the order and coverage vary between universities.

28.7.3Skills you will gain

  • building a search index in Elasticsearch
  • BM25 experiments with Pyserini
  • vector search with FAISS
  • training recommenders with Surprise
  • measuring rankings with NDCG and MAP

28.7.4Try it yourself

The Try It: Searching a Help Center slide in the presentation lets you solve a typical problem of this course yourself: A shopping site's help center has nine articles, and customers type questions in their own words. Pick a sample question or type your own; articles are ranked by TF-IDF weights and cosine similarity.

28.8Are you ready for this course?

28.8.1Prerequisites

CourseWhy it is needed
Linear Algebravector space model, matrix factorization
Data Structureshash tables, trees and priority queues: the index and the top k results
Algorithmssorting, merging and complexity: speed on large indexes

28.8.2Ask yourself

For every "no", the right-hand column shows where to start. If you can say "yes" to most of them, you are ready.

QuestionIf not, start with
Can you compute and interpret the cosine similarity of two vectors?Linear Algebra
Can you explain why lookup in a hash table takes constant time?A data structures course: hash tables and trees
Can you compute precision and recall from a confusion matrix?Machine Learning
Can you split a text into words and count word frequencies?Natural Language Processing and Text Mining

28.9Neighboring courses

NLPData MiningLinear AlgebraSocial Network AnalysisIR & Recommenders
subfieldbuilds onshares methodsapplication
Figure 28.2: Neighbors of Information Retrieval and Recommender Systems and the kind of relation

28.9.1Where it overlaps

RelationCourseShared ground
builds onThis course builds on Linear Algebravector space model, matrix factorization
shares methodsShares methods with Natural Language Processing and Text Miningtext representation, TF-IDF, semantic search
shares methodsShares methods with Data Miningassociation, collaborative filtering
shares methodsShares methods with Social Network AnalysisPageRank, link analysis

28.9.2Where it differs

  • Data Mining: Data mining discovers patterns in data; this course turns discovery into a ranked list for one user's current need.
  • Natural Language Processing and Text Mining: NLP analyzes the structure and meaning of language; this course represents text only to score and rank relevance.
  • Machine Learning: ML tries to predict individual examples correctly; this course cares about list order, above all the top few results.
  • Social Network Analysis: Social network analysis studies the structure of ties; this course uses that structure (e.g. PageRank) only as a ranking signal.

28.10In practice

28.10.1Applications

AreaWhat is done
Web searchRanking the pages most relevant to a query.
E-commerceCustomers who bought this also bought...
Video and musicPersonal feeds and playlists.
Enterprise searchSearching company documents and e-mail.
News feedsRanking posts by relevance.
RAGFetching the right documents for a language model.

28.10.2Risks and ethics

RiskExplanation
Filter bubblesAlways showing more of what a user liked narrows the range of views; polarization from news and video feeds is debated.
Popularity biasPopular items get recommended more, so they get clicked more; new and small producers stay invisible.
Query logs can identify peopleFrom search logs that AOL anonymized and released in 2006, journalists identified some of the users.
Ranking manipulationLink farms, fake reviews and keyword stuffing distort rankings; the system must be designed against adversaries.

These issues are discussed in depth in Explainable AI and AI Ethics.

28.10.3Tools and datasets

Tools: Apache Lucene, Elasticsearch, FAISS, Pyserini, Surprise, scikit-learn.

Well-known datasets: MovieLens, Netflix Prize, MS MARCO, TREC collections, Cranfield collection, Amazon product reviews.

28.11Common misconceptions

Common mistake

A search engine just finds the words in the query.

The real work is ranking thousands of matches; users rarely look past the first page.

Common mistake

Recommending the top-rated items is enough.

The same list for everyone is not personalization; diversity and novelty are measured too.

Common mistake

High accuracy means good recommendations.

A model with low rating error can still rank badly; rank metrics such as NDCG are needed.

Common mistake

Dense vectors have made classic search obsolete.

BM25 is still a strong baseline; many systems combine the two.

28.12Summary

  • Information retrieval and recommender systems produce a ranked list, not a single answer; success is how close to the top the relevant documents stand.
  • The inverted index maps each term to the documents containing it; a Boolean query is answered by list intersection, ranking by a TF-IDF or BM25 score.
  • A term's weight grows with its frequency in the document and falls with its commonness in the collection: idf = log(N/df).
  • P@k, recall, AP and NDCG measure a ranked list; AP and NDCG are rank-aware, P@k is not.
  • Collaborative filtering fills empty cells from similar users or from latent factors (matrix factorization); a user or item with no history raises the cold-start problem.

28.13Test Yourself

  1. The postings list of "tree" is {2, 5, 9, 14} and that of "forest" is {1, 2, 9, 10, 14, 20}. What is the result of "tree AND forest"?

    Answer

    Intersect the lists: compare 2 with 1, skip 1; 2 = 2 (add); 5 < 9, skip 5; 9 = 9 (add); 14 > 10, skip 10; 14 = 14 (add). The result is {2, 9, 14}.

  2. In a collection of N = 1000 documents one term occurs in 10 documents and another in all 1000. Compute the inverse document frequency of each (log base 10). What do the results show?

    Answer

    log10(1000/10) = log10 100 = 2 and log10(1000/1000) = 0. A term in every document does not discriminate; its contribution to ranking is zero.

  3. In a list the relevance judgments are, in order, 0, 1, 1, 0, 1; the collection holds 3 relevant documents in total. Find P@5, AP and the reciprocal rank.

    Answer

    P@5 = 3/5 = 0.6. The relevant documents are at ranks 2, 3 and 5: P@2 = 1/2, P@3 = 2/3, P@5 = 3/5. AP = (0.5 + 0.667 + 0.6) / 3 ≈ 0.589. The first relevant document is at rank 2: reciprocal rank = 1/2.

  4. With graded judgments a system's order is 2, 0, 1. The perfect order is 2, 1, 0. What is NDCG@3? (gain = grade, log base 2)

    Answer

    DCG = 2/1 + 0/1.585 + 1/2 = 2.5. IDCG = 2/1 + 1/1.585 + 0 ≈ 2.631. NDCG ≈ 2.5/2.631 ≈ 0.95.

  5. In matrix factorization p = (1, 1), q = (2, 1), the true rating is 5 and η = 0.1. What is the prediction after one gradient step?

    Answer

    The first prediction is 3, the error 2. p ← (1 + 0.4, 1 + 0.2) = (1.4, 1.2), q ← (2 + 0.2, 1 + 0.2) = (2.2, 1.2). New prediction 1.4 · 2.2 + 1.2 · 1.2 = 3.08 + 1.44 = 4.52.

  6. Why can collaborative filtering not give good recommendations to a user who has just joined a new movie site? What can be tried?

    Answer

    The user has no ratings, so no similar users or latent vector can be found (cold start). Options: ask for a few genres or movies at sign-up, switch to content-based recommendation (movie features), show popular items at first, and move to the collaborative model as behavior accumulates.

28.14After this course

After this course you can move on to semantic search with natural language processing, link-based ranking with social network analysis, and indexing billions of documents with big data systems. Retrieval-augmented generation connects this course directly to large language models.

Related careers: Search engineer, Recommender systems engineer, Data scientist, Ranking researcher.

28.15Further reading

  • C. D. Manning, P. Raghavan and H. Schütze, Introduction to Information Retrieval (2008): covers the inverted index, scoring and evaluation at textbook level; freely available on the authors' site.
  • C. C. Aggarwal, Recommender Systems: The Textbook (2016): gathers neighborhood methods, matrix factorization and evaluation in a single book.
  • Y. Koren, R. Bell and C. Volinsky, "Matrix Factorization Techniques for Recommender Systems" (2009): a short article showing what objective the gradient step used in these notes trains toward, and why.

28.16References

  1. Manning, Raghavan and Schütze, Introduction to Information Retrieval, Cambridge University Press, 2008.
  2. Baeza-Yates and Ribeiro-Neto, Modern Information Retrieval, 2nd ed., Addison-Wesley, 2011.
  3. Aggarwal, Recommender Systems: The Textbook, Springer, 2016.
  4. Koren, Bell and Volinsky, "Matrix Factorization Techniques for Recommender Systems", IEEE Computer 42(8), 2009.

Related pages: Slides · Slides (PDF) · Course page