What you will build
- 1.1 Explore word embeddings: see a word as 50 numbers and do "word maths" (king − man + woman = ?)
- 1.2 A small web app that finds the documents closest in meaning to a question (Top-K search)
- 1.3 The same app with a second step, reranking, the way real search and RAG systems do it
Time: about 50 minutes · API key needed: No (everything in this module runs on your laptop)
How to do these exercises
- Finish the setup first: 11-rag-setup/Setup_Guide_for_Learners.html.
- Open the folder 1_GIVE_FIRST_Starter_Code. Every file has blanks marked
# ----- TODO n: ... -----. - Replace the placeholder line under each TODO (for example
scores = [] # replace with your code) with your own code. - Stuck for more than 5 minutes? Open the hint under the TODO on this page. Still stuck? Ask your instructor.
- Check your work with the "You are done when" box at the end of each exercise.
Exercise 1.1 downloads a 66 MB word model. Exercises 1.2 and 1.3 download two small models (about 90 MB each). After the first time they load from your laptop.
Exercise 1.1 — Word embeddings notebook
File: 1_GIVE_FIRST_Starter_Code/1_word_embeddings.ipynb
Story: A computer cannot read the word king. It only works with numbers. An embedding is a list of numbers that stands for a word, and words with similar meanings get similar lists. Your job is to look at these numbers and use them.
Run the cells from top to bottom. Fill in these blanks:
Expected: the shape is (50,), which means 50 numbers.
Need a hint?
- The model works like a dictionary:
model["some_word"] - A numpy array has a .shape attribute
Do the analogy king − man + woman. Which word comes back?
Need a hint?
model.most_similar(positive=[words to add], negative=[words to subtract], topn=1)
Paris is to France as ? is to India.
Need a hint?
- Same pattern as TODO 2. Words to add: paris, india. Word to subtract: france
Formula: cosine(a, b) = (a · b) / (|a| × |b|). Your numbers must match gensim's numbers.
Need a hint?
np.dot(a, b)gives a · bnp.linalg.norm(a) gives |a|
- TODO 2 prints
queenand TODO 3 prints an Indian city - In TODO 4, "my answer" and "gensim" show the same three numbers
- king vs queen scores clearly higher than king vs banana
Exercise 1.2 — Similarity search app (Top-K) web app
File: 1_GIVE_FIRST_Starter_Code/2_similarity_search_app.py
Story: You have a pile of sentences (documents). A user types a question. Show the K sentences whose meaning is closest to the question, even if they share no words with it. This is the R (Retrieval) in RAG.
Need a hint?
cosine(a, b) = (a · b) / (|a| × |b|)np.dot(a, b) and np.linalg.norm(a)are all you need
Need a hint?
model.encode(list_of_texts)returns one vector per text- Encode the query as a list with one item, then take
[0]
Need a hint?
- Build a list of
(doc, score)pairs withzip(docs, doc_embeddings) list.sort(key=lambda pair: pair[1], reverse=True)puts the highest score first
Run it:
python 2_similarity_search_app.py
Open the link shown in the terminal (usually http://127.0.0.1:7860). The sample documents and query are already filled in. Click Retrieve Top K.
- For the query fruit and nutrition, the two fruit sentences (bananas, apples and oranges) are the top 2 rows
- Changing the query to share prices falling puts the stock market and Sensex sentences on top
- Moving the K slider changes how many rows you get
Exercise 1.3 — Retrieve, then Rerank web app
File: 1_GIVE_FIRST_Starter_Code/3_reranking_app.py
Story: Fast search (Exercise 1.2) is good at finding roughly related text, but it can be fooled by sentences that just repeat the question's words. A reranker (a cross-encoder) reads the question and each document together and gives a sharper relevance score. Real systems do both: retrieve many quickly, then rerank the few that came back.
This is the same idea as Exercise 1.2, written with scikit-learn's cosine_similarity, which scores all documents in one call.
Need a hint?
bi_encoder.encode(documents) -> matrix (one row per document)bi_encoder.encode([query]) ->matrix with ONE rowcosine_similarity(query_matrix, doc_matrix)[0] ->one score per document
Need a hint?
- Build pairs like
[(query, doc1), (query, doc2), ...] cross_encoder.predict(pairs) ->one score per pair(higher = more relevant)
Run it: python 3_reranking_app.py, open the link, click 1) Retrieve Top K, then 2) Rerank.
- Both tables show all 8 documents with a score
- The order in the "Reranked" table is different from the "Top-K" table
- Write down: which sentence is #1 before reranking, and which is #1 after?
Think about it (answer in 1–2 lines each)
- In Exercise 1.1, when we search with the raw vector for king − man + woman, the top word is king itself. Why?
- Why do we compare embeddings with cosine similarity (the angle) and not just by subtracting the numbers?
- A cross-encoder gives better scores. So why don't we run it on all one million documents in a real system?
- Exercise 1.3 has a document saying COVID-19 causes memory loss and confusion. That is not a common COVID symptom. Did the reranker push it down? What does that tell you about what a reranker checks?
- If you set K = 2 in Exercise 1.3, can the reranker still find the best document? Why or why not?
Your instructor will discuss the answers after the exercise.
Stretch challenges (if you finish early)
- 1.1: Try your own analogies, for example
positive=["dosa","italy"], negative=["india"]. Which ones work? Which fail? - 1.2: Add 5 sentences about cricket and 5 about cooking. Does the search still keep topics apart?
- 1.3: Add a column to the reranked table that shows each document's old position, so you can see how far it moved.