Skip to main content

Warm-up embeddings · vectors

How alike are two words

Words become arrows, and the angle between them says how related they are.

Models store each word as a list of numbers called a vector. Two words point the same way when their vectors line up, and cosine similarity measures that: 1 means same direction, 0 means unrelated, -1 means opposite.

Write cosine(a, b): a and b are arrays of numbers with the same length. Return the dot product (multiply matching items and add them up) divided by the length of a times the length of b. The length of a vector is the square root of the sum of its squares. If either vector is all zeros, return 0.

Call show(products) with the array of matching-item products and the stage draws them as bars.

Example: cosine([1, 0], [0, 1]) returns 0.

Tests you can see

  • cosine([1,0], [0,1])0
  • cosine([1,2,3], [2,4,6])1
  • cosine([1,2], [2,1])0.7999999999999998

More tests are hidden. The server runs them all before a time counts.

The idea behind this, in a two-minute live page

Call show() while your code works and the run plays back here.

javascriptcosine()

Tab indents · Cmd/Ctrl+Enter runs