Learning path: Neural Networks from Scratch to Embeddings · Step 9 of 9
Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
Ask one question of a whole collection of vectors: which items are closest to this one? Normalise, score every row with one matrix multiply, keep the top k or everything above a threshold, and check it with NearestNeighbors.
What you will learn
- Normalise rows to length 1 so cosine similarity becomes a plain dot product
- Score a whole collection against one query with a single matrix multiply
- Return the top k with argsort, or only results above a threshold
- Do the same search with scikit-learn NearestNeighbors and see what brute force costs
Before you start
- Embeddings: Words as Vectors, Cosine Similarity and nn.Embedding
- NumPy arrays and the @ operator
You hand a librarian a book and say: "find me books like this one." The librarian walks along the shelf, compares your book with every single book on it, and brings back the three closest.
That's similarity search. A book is a vector, comparing gives a score, and bringing back the best three is called top k. Compare the question with every item, then keep the closest few. We use the same 20 GloVe word vectors as in Embeddings: Words as Vectors.
A collection is a matrix
import numpy as np
import pandas as pd
vec = pd.read_csv("word_vectors_small.csv", index_col=0)
words = list(vec.index)
M = vec.values
print(M.shape)
(20, 50)
Every word is one row, every row has 50 numbers. A collection is simply a matrix: N items by d numbers. The full GloVe set would be 400,000 rows, still 50 columns.
Length 1 turns cosine into a dot product
Cosine similarity is a @ b divided by the two lengths. If we divide every row by its own length first, every vector has length 1, its direction stays exactly the same, and that division does nothing any more. Cosine becomes a plain dot product, which is very cheap.
lengths = np.linalg.norm(M, axis=1, keepdims=True)
M_norm = M / lengths
print(lengths[:3].ravel().round(2))
print(np.linalg.norm(M_norm, axis=1)[:3].round(2))
[4.41 4.86 5.14]
[1. 1. 1.]
Cat, dog and horse have lengths 4.41, 4.86 and 5.14. After the division, all three are 1. Check that the two ways agree:
def cosine(a, b):
n = np.linalg.norm(a) * np.linalg.norm(b)
return float(a @ b / n)
cat, dog = words.index("cat"), words.index("dog")
print("cosine:", round(cosine(M[cat], M[dog]), 4))
print("dot: ", round(float(M_norm[cat] @ M_norm[dog]), 4))
cosine: 0.9218
dot: 0.9218
Same number, no division needed.
One query, every row, one multiply
q is the cat row: our "book like this one". M_norm @ q multiplies every row with q, all at once.
q = M_norm[words.index("cat")]
scores = M_norm @ q
print(scores.shape)
for w, s in zip(words[:5], scores[:5]):
print(f"{w:<6} {s:.2f}")
(20,)
cat 1.00
dog 0.92
horse 0.70
cow 0.65
car 0.36
One score for each of the 20 rows. One line scores the whole collection against the query.
Top k: sort the scores, keep the best
order = np.argsort(-scores)
for i in order[:4]:
print(f"{words[i]:<6} {scores[i]:.3f}")
cat 1.000
dog 0.922
boy 0.704
horse 0.702
argsort sorts from small to big, so the minus sign is the trick that puts the best first. With three decimals you can see boy (0.704) just beats horse (0.702).
One small trap: cat comes back first with a perfect 1.0, because it's the query itself. So we drop it and keep the next k. Wrapped in a helper:
def search(word, k=3):
i = words.index(word)
scores = M_norm @ M_norm[i]
order = np.argsort(-scores)
order = order[order != i] # drop the query itself
return [(words[j], round(float(scores[j]), 2)) for j in order[:k]]
for w in ("cat", "truck", "king"):
print(w, search(w))
cat [('dog', 0.92), ('boy', 0.7), ('horse', 0.7)]
truck [('car', 0.92), ('bus', 0.82), ('train', 0.74)]
king [('prince', 0.82), ('queen', 0.78), ('princess', 0.6)]
The closest words really do sit in the same neighbourhood.
A threshold: only what is close enough
Top k always returns k results, even when nothing is really close. Sometimes you want a threshold instead:
def search_above(word, t):
i = words.index(word)
scores = M_norm @ M_norm[i]
keep = [j for j in np.argsort(-scores) if j != i and scores[j] >= t]
return [(words[j], round(float(scores[j]), 2)) for j in keep]
for t in (0.7, 0.9, 0.95):
hits = search_above("cat", t)
print(t, len(hits), [w for w, s in hits])
0.7 3 ['dog', 'boy', 'horse']
0.9 1 ['dog']
0.95 0 []
At 0.7, three words are close enough. At 0.9, only dog. At 0.95, nothing comes back. "Close enough" decides, and that's exactly how a cache decides whether a new question is close enough to reuse an old answer.
The same search with scikit-learn
from sklearn.neighbors import NearestNeighbors
knn = NearestNeighbors(n_neighbors=4, metric="cosine").fit(M)
dist, idx = knn.kneighbors(vec.loc[["cat"]].values)
for d, j in zip(dist[0], idx[0]):
print(f"{words[j]:<6} distance {d:.2f} similarity {1 - d:.2f}")
cat distance 0.00 similarity 1.00
dog distance 0.08 similarity 0.92
boy distance 0.30 similarity 0.70
horse distance 0.30 similarity 0.70
NearestNeighbors gives back a distance, not a similarity: cosine distance = 1 - similarity, so dog's 0.08 + 0.92 = 1. We ask for 4 neighbours because cat itself comes back first, with distance 0. Same answer as our own code. (It's the same neighbour search that powers KNN.)
What does brute force cost?
The optional cells load all 400,000 GloVe words (needs gensim) and time a top-3 search, averaged over 20 runs:
# OPTIONAL: pip install gensim (66 MB download, once)
import gensim.downloader as api
glove = api.load("glove-wiki-gigaword-50")
big = glove.vectors
big_norm = big / np.linalg.norm(big, axis=1, keepdims=True)
print(big_norm.shape)
(400000, 50)
import time
def time_search(matrix, q, repeats=20):
start = time.perf_counter()
for _ in range(repeats):
top = np.argsort(-(matrix @ q))[:3]
return (time.perf_counter() - start) / repeats * 1000
q_big = big_norm[glove.key_to_index["cat"]]
print(f"20 rows: {time_search(M_norm, q):.3f} ms")
print(f"400,000 rows: {time_search(big_norm, q_big):.1f} ms")
top = np.argsort(-(big_norm @ q_big))[1:4]
print("closest to cat:", [glove.index_to_key[j] for j in top])
20 rows: 0.006 ms
400,000 rows: 19.7 ms
closest to cat: ['dog', 'rabbit', 'monkey']
On the lecture's PC, 20 rows took about 0.006 ms and 400,000 rows about 19.7 ms. Your times will differ, but brute force always checks every row, every time. For really big collections, a vector database keeps an index, so it doesn't check every row. This search is also the retrieve stage of a RAG pipeline.
Common mistakes
- Forgetting to normalise before using the dot product. Without length 1, longer vectors win just for being long.
- Leaving the query in the results. It always scores a perfect 1.0.
argsort(scores)without the minus. You'd get the least similar first.- Reading a distance as a similarity.
NearestNeighborsreturns 1 - similarity.
Quick recap
| Step | Code | Example (query: cat) |
|---|---|---|
| Collection as a matrix | M = vec.values | (20, 50) |
| Normalise | M / np.linalg.norm(M, axis=1, keepdims=True) | cosine = dot = 0.9218 |
| Score every row | M_norm @ q | 20 scores |
| Top k | np.argsort(-scores), drop the query | dog, boy, horse |
| Threshold | scores[j] >= t | 0.9 keeps only dog |
| scikit-learn | NearestNeighbors(metric="cosine") | distance = 1 - similarity |
Try it yourself
Search the 400,000 words for doctor with a threshold of 0.75. How many words come back? Hint: big_norm @ big_norm[glove.key_to_index["doctor"]], then count the scores >= 0.75 (leave out doctor itself).
The notebook and word_vectors_small.csv are in the StudyEasy AI Community, free to join.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Why Neural Networks: Pixels, One Neuron and Layers
Why pictures need neural networks: a handwritten digit is 784 numbers, one neuron is a weighted sum plus a bias and one small rule, and neurons stack into layers. Worked out on MNIST with NumPy.
The Forward Pass and Activation Functions: ReLU, Sigmoid, Tanh and Softmax
Follow numbers through a tiny 3-2-3 network in NumPy: one matrix product per layer, ReLU inside, softmax at the end, and a count of every weight and bias.
Loss and Backpropagation: How Wrong, and Who Is to Blame
The loss says how wrong the network was; backpropagation says how much each weight is to blame. MSE and cross-entropy, the chain rule by hand on a two-weight chain, then the same gradients from PyTorch autograd.
The Training Loop: Epochs, Mini-Batches, Learning Rate and Optimisers
How training is organised: shuffle, cut into mini-batches, take one step per batch, repeat per epoch. Real MNIST runs compare three learning rates, SGD against Adam, and show the overfitting signal in the validation loss.