← Lesson
Embedding Geometry
Joeven
Run
Reset
Python loads on first run
def dot(u, v): return sum(a * b for a, b in zip(u, v)) def mag(v): return sum(x * x for x in v) ** 0.5 def cosine(u, v): return dot(u, v) / (mag(u) * mag(v)) def topk(query, store, k=2): scored = [(cosine(query, vec), text, label) for text, label, vec in store] scored.sort(reverse=True) return scored[:k] store2d = [ ("refunds 5-7 days", "billing", [0.9, 0.1]), ("invoice PDF in /billing", "billing", [0.8, 0.2]), ("reset password via email", "auth", [0.1, 0.9]), ("SSO is SAML", "auth", [0.2, 0.8]), ("runner OOM last night", "infra", [-0.7, 0.2]), ("scale the worker pool", "infra", [-0.6, 0.1]), ] q_bill = [0.85, 0.15] print("2d billing query:") for row in topk(q_bill, store2d, 2): print(" ", round(row[0], 3), row[1], row[2]) store3d = [ ("refunds 5-7 days", "billing", [0.9, 0.1, 0.0]), ("invoice PDF in /billing", "billing", [0.8, 0.2, 0.05]), ("reset password via email", "auth", [0.1, 0.9, 0.0]), ("SSO is SAML", "auth", [0.2, 0.8, 0.1]), ("runner OOM last night", "infra", [0.1, 0.1, 0.95]), ("scale the worker pool", "infra", [0.0, 0.2, 0.9]), ] q_infra = [0.05, 0.05, 0.9] print("3d infra query:") for row in topk(q_infra, store3d, 2): print(" ", round(row[0], 3), row[1], row[2]) q_far = [0.4, 0.4, 0.4] print("3d vague query (still top-2):") for row in topk(q_far, store3d, 2): print(" ", round(row[0], 3), row[1], row[2])
Run to execute this in your browser. Nothing is sent to a server.