How AI Language Models Work ยท Text as Numbers

Embeddings: Meaning as Numbers

Give every word a vector, and words with similar meanings end up pointing the same way. Find the word closest to "kitten" with cosine similarity.

embeddings.py

import math

# Each word gets a vector: a list of numbers that describes its meaning.
# Real models learn hundreds of numbers per word. Here there are two: how animal-like, how food-like.
words = ["cat", "dog", "apple", "bread"]
kinds = ["animal", "animal", "food", "food"]
animal = [0.9, 0.7, 0.1, 0.2]
food = [0.1, 0.3, 0.9, 0.8]

# A new word, "kitten". Which known word means the most similar thing?
qa, qf = 0.8, 0.1

similarity = []
for a, f in zip(animal, food):
    # Cosine similarity: 1 when two vectors point the same way, 0 when they have nothing in common.
    cos = (a * qa + f * qf) / (math.sqrt(a * a + f * f) * math.sqrt(qa * qa + qf * qf))
    similarity.append(round(cos, 3))

closest = words[similarity.index(max(similarity))]
print("kitten is closest to", closest)

Step by step

  1. This brings in Python's built-in math module, for functions like math.exp and math.sqrt.
  2. Four words the model knows.
  3. Two are animals and two are food. The model is never told this; it is here only to colour the chart.
  4. The first number of each word's vector: how animal-like it is.
  5. The second number: how food-like. Each word is now a point on the chart: animals bottom right, food top left.
  6. A new word, "kitten": very animal-like, barely food-like. It is the star on the chart.
  7. An empty list for one similarity score per word.
  8. Compare kitten with each word in turn, starting with cat.
  9. Cosine similarity: the dot product of the two vectors divided by their lengths. Cat and kitten point almost exactly the same way: 1.0.
  10. Save it, rounded.
  11. a changes from 0.9 to 0.7. f changes from 0.1 to 0.3.
  12. Dog: 0.961. Also very close; dogs are animals too.
  13. 0.961 is added to the end of the list that similarity points to.
  14. a changes from 0.7 to 0.1. f changes from 0.3 to 0.9.
  15. Apple: 0.233. It points a very different way.
  16. 0.233 is added to the end of the list that similarity points to.
  17. a changes from 0.1 to 0.2. f changes from 0.9 to 0.8.
  18. Bread: 0.361. Low.
  19. 0.361 is added to the end of the list that similarity points to.
  20. Python moves to the next item of the loop: for a, f in zip(animal, food).
  21. The closest meaning is the word with the highest similarity: cat.
  22. Kitten is closest to cat. Nobody wrote a rule saying kittens are cats: closeness of the vectors is the meaning. Real embeddings have hundreds of numbers, but the comparison is exactly this.