Lesson 3 of 5 · 2 min
Approximate search
With millions of items, an index looks at only some of them. It is much faster and sometimes misses the true best. Here the vectors are grouped around a few centres and only the nearest groups are searched.
import numpy as np
rng = np.random.default_rng(1)
store = rng.normal(size=(4000, 16))
centres = store[rng.choice(len(store), 20, replace=False)]
group = np.argmax(store @ centres.T, axis=1)
def search(q, probes):
near = np.argsort(centres @ q)[::-1][:probes]
ids = np.flatnonzero(np.isin(group, near))
return ids[np.argmax(store[ids] @ q)], len(ids)
q = rng.normal(size=16)
truth = int(np.argmax(store @ q))
for probes in (1, 4, 20):
found, looked = search(q, probes)
print(f"{probes:2} groups: looked at {looked:4}, found the best: {found == truth}")
