Measure a nearest neighbor in embedding space

Read a complete operation before typing its result. · 155 words

An embedding represents an item as a vector of numbers, so geometric distance can stand for similarity. Euclidean distance is d(q,x)=sqrt(sum_i(q_i-x_i)^2). The square root can be omitted for ranking because it preserves order. For example, a museum app receives query [1,2]. Exhibit A is [2,2], and Exhibit B is [4,4]. Their squared distances are 1 and 13, so A is nearer and becomes the nearest neighbor, meaning the closest item under the chosen metric.

A different task may use cosine distance, which measures angle rather than raw length. In a library search, query q=[1,1], Book A has a=[2,2], and Book B has b=[2,0]. Cosine similarity is the dot product divided by the two vector lengths. The similarities are 4/(sqrt(2)sqrt(8))=1 and 2/(sqrt(2)sqrt(4))=0.707. A is more similar and therefore nearer in cosine distance. Metrics should fit the data: Euclidean rewards absolute closeness, while cosine similarity stays constant when either nonzero vector is multiplied by a positive number.

Check your recall

For query [1,2], which is nearest by squared Euclidean distance, [2,2] or [4,4], and what are the two squared distances?

Check your answer

[2,2] is nearest. Its squared distance is (1-2)^2+(2-2)^2=1; [4,4] has squared distance (1-4)^2+(2-4)^2=13.

Sources and credits

Original KeyTouch lesson. Background reading · Google · Neural networks.