Classroom Activity: Word Embeddings and Cosine Similarity

Four 4-dimensional word embeddings:

\[ A = \begin{bmatrix} 0.8 \\ 0.4 \\ -0.4 \\ 0.2 \end{bmatrix} \qquad B = \begin{bmatrix} 0.15 \\ -0.3 \\ 0.25 \\ 0.35 \end{bmatrix} \qquad C = \begin{bmatrix} 0.8 \\ 0.4 \\ -0.2 \\ 0.4 \end{bmatrix} \qquad D = \begin{bmatrix} 1.6 \\ 0.9 \\ -0.7 \\ 0.5 \end{bmatrix} \]

These represent trout, bass, donut, and guitar, in some unknown order.

Student questions

  1. Compute the Euclidean norm of each vector.
  2. Normalize all these vectors.
  3. How many pairs of vectors are there to compare similarity between?
  4. Calculate the cosine similarity between all these pairs.
  5. Which vector most likely represents donut? Why?

Solutions

1. Euclidean norms

Vector Sum of squares Euclidean norm Already normalized?
A 1.00 1.0000 Yes
B 0.2975 0.5454 No
C 1.00 1.0000 Yes
D 4.11 2.0273 No

2. Normalized vectors

\[ A = \begin{bmatrix} 0.8000 \\ 0.4000 \\ -0.4000 \\ 0.2000 \end{bmatrix} \qquad B = \begin{bmatrix} 0.2750 \\ -0.5500 \\ 0.4583 \\ 0.6417 \end{bmatrix} \qquad C = \begin{bmatrix} 0.8000 \\ 0.4000 \\ -0.2000 \\ 0.4000 \end{bmatrix} \qquad D = \begin{bmatrix} 0.7892 \\ 0.4439 \\ -0.3453 \\ 0.2466 \end{bmatrix} \]

3. How many pairs?

\[ \binom{4}{2} = 6. \]

4. Pairwise cosine similarities

Pair Cosine similarity Cosine distance
A, B −0.0550 1.0550
A, C 0.9600 0.0400
A, D 0.9964 0.0036
B, C 0.1650 0.8350
B, D −0.0271 1.0271
C, D 0.9767 0.0233

Here, cosine distance = 1 − cosine similarity.

5. Correct answer: B = donut

The three vectors A, C, and D are extremely close together in cosine similarity:

Meanwhile, B has very low cosine similarity with all three. Since trout and bass will have a lot of semantic overlap (fishing), and bass and guitar will have a lot of overlap (rock music) whereas donut doesn’t have any particular relationship to the other words, vector B is almost certainly donut’s embedding.