Skip to content
Streak:0Loading your progress…Sign in

Module 10 · Lesson 1 of 3

Embeddings & similarity

Text → vectors; nearby vectors mean similar meaning. ~25 min

Lesson notes

An embedding model maps text to a fixed-length vector (e.g. 1024 floats). Semantically similar texts land close together. Cosine similarity = dot product of the two vectors divided by the product of their lengths; it ranges -1..1. If vectors are pre-normalised to length 1, cosine similarity is just the dot product — which is why vector DBs normalise on insert.

NumPy: vectorised math instead of Python loops
import numpy as np

docs = np.array([[0.1, 0.9], [0.8, 0.2], [0.7, 0.7]])   # (n_docs, dim)
q = np.array([0.6, 0.8])

docs_n = docs / np.linalg.norm(docs, axis=1, keepdims=True)
q_n = q / np.linalg.norm(q)
scores = docs_n @ q_n          # (n_docs,) cosine similarities
top = np.argsort(-scores)[:2]  # indices of best 2

Vector stores (pgvector, Pinecone, Weaviate, Qdrant, LanceDB) do this at scale using approximate nearest-neighbour indexes (HNSW, IVF) — trading a little recall for huge speedups. For < ~100k chunks, Postgres + pgvector is usually the right first answer.

Practice

  1. 1. Cosine top-k with NumPy

    medium25 XP

    Write top_k(query, matrix, k) returning a list of (index, score) for the k most similar rows of matrix to query by cosine similarity, highest first, with scores rounded to 4 decimals. Rows with zero norm must score 0 (no division-by-zero warnings). No Python loops over rows.

    Ctrl/⌘ + Enter runs the tests · Esc then Tab leaves the editor