How AI Language Models Work ยท Text 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.
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)math module, for functions like math.exp and math.sqrt.a changes from 0.9 to 0.7. f changes from 0.1 to 0.3.similarity points to.a changes from 0.7 to 0.1. f changes from 0.3 to 0.9.similarity points to.a changes from 0.1 to 0.2. f changes from 0.9 to 0.8.similarity points to.for a, f in zip(animal, food).