Week 04 · Word embeddings and similarity

Compare a sparse context vector with a compressed representation.

← Week 3 · Subject contents · Week 5 →

Compare a sparse context vector with a compressed representation.

Work through the problem

A word’s context counts form a vector. Cosine similarity normalizes away magnitude: cos(u,v)=u·v/(‖u‖‖v‖). Compress the count matrix with SVD and use the first two components as dense word coordinates. Compression can preserve broad associations while erasing a distinction needed for a specific task.

The context columns below roughly describe finance, rivers, and public places. A single vector for bank combines its two senses. Even a good cosine score does not establish that two words are substitutable in a sentence.

Five words in two context dimensions. Second component by first component. Groups: bank, loan, shore, market, park.

Five words in two context dimensions.

Run the Python lab

import numpy as np
words = ["bank","loan","shore","market","park"]
counts = np.array([[5,5,0],[6,0,0],[0,6,1],[4,0,2],[0,2,6]],float)
u,s,v = np.linalg.svd(counts,full_matrices=False)
dense = u[:,:2]*s[:2]
for name, matrix in [("Counts",counts),("Two dimensions",dense)]:
    norms = np.linalg.norm(matrix,axis=1)
    similarity = (matrix@matrix[0])/(norms*norms[0])
    print(name,dict(zip(words,similarity.round(3).tolist())))

Output from the lab

Counts {'bank': 1.0, 'loan': 0.707, 'shore': 0.697, 'market': 0.632, 'park': 0.224}
Two dimensions {'bank': 1.0, 'loan': 0.788, 'shore': 0.666, 'market': 0.93, 'park': 0.519}

Practice

  1. Why can bank be similar to both loan and shore?

Check your reasoning

  1. The count vector aggregates examples from multiple meanings into a single representation.

← Week 3 · Subject contents · Week 5 →

Further reading · Jurafsky and Martin · Speech and Language Processing