Velamuvi AIAcademy
Embeddings

Lesson 3 of 8 · Meaning as Vectors

Creating Embeddings

How embedding models learn, creating embeddings with an API or an open-source model in Python, query vs document embeddings, batching and a mini model to run.

  • 7 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • How embedding models learn, in plain terms
  • How to create embeddings with an API or an open model
  • Why older word-count vectors miss meaning
  • Practical habits: batching, query versus document, storing vectors

From text to vector

An embedding model takes text and returns a vector of fixed length, for example 384, 768, 1,024 or 3,072 numbers, whatever the length of the text.

How they learn

Most text embedding models are trained with contrastive learning:

  1. Collect huge numbers of pairs that belong together: a question and its answer, a title and its article, two paraphrases of the same sentence.
  2. Train the model so each pair's vectors are pulled closer together, while vectors of unrelated texts are pushed apart.

After billions of such examples, the model has learned that "cheap flights" and "low-cost airline tickets" should land in the same place, even though they share no words.

A model you can see inside

Real models have millions of learned parameters, so you can't see why a vector has its values. The program below is a deliberately tiny "embedding model" built from a word list: each dimension is a topic, and each known word adds to its topics. It is far too simple for real use, but it behaves like a real model in the way that matters: synonyms land together.

Try it yourselfPython
import math

# A tiny, hand-made "embedding model". Each dimension is a topic.
# A real model learns thousands of dimensions from data; ours uses a word list
# so you can see exactly where the numbers come from.
TOPICS = ["travel", "food", "money", "tech", "health", "weather"]
LEXICON = {
    "flight": {"travel": 1}, "flights": {"travel": 1}, "airline": {"travel": 1},
    "plane": {"travel": 1}, "airport": {"travel": 1}, "trip": {"travel": 1},
    "holiday": {"travel": 1}, "hotel": {"travel": 1, "money": 0.3},
    "train": {"travel": 1}, "tickets": {"travel": 0.8, "money": 0.5},
    "recipe": {"food": 1}, "cook": {"food": 1}, "dinner": {"food": 1},
    "pasta": {"food": 1}, "rice": {"food": 1}, "curry": {"food": 1},
    "vegetarian": {"food": 1, "health": 0.3}, "restaurant": {"food": 1, "travel": 0.3},
    "cheap": {"money": 1}, "budget": {"money": 1}, "low-cost": {"money": 1},
    "price": {"money": 1}, "save": {"money": 1}, "salary": {"money": 1},
    "bank": {"money": 1}, "loan": {"money": 1}, "expensive": {"money": 1},
    "laptop": {"tech": 1}, "phone": {"tech": 1}, "app": {"tech": 1},
    "battery": {"tech": 1}, "wifi": {"tech": 1}, "password": {"tech": 1},
    "python": {"tech": 1}, "doctor": {"health": 1}, "sleep": {"health": 1},
    "exercise": {"health": 1}, "fever": {"health": 1}, "headache": {"health": 1},
    "diet": {"health": 1, "food": 0.5}, "rain": {"weather": 1},
    "sunny": {"weather": 1}, "forecast": {"weather": 1}, "storm": {"weather": 1},
    "umbrella": {"weather": 1}, "snow": {"weather": 1, "travel": 0.2},
}

def embed(text):
    vector = [0.0] * len(TOPICS)
    for word in text.lower().replace(",", " ").replace(".", " ").replace("?", " ").split():
        for topic, weight in LEXICON.get(word, {}).items():
            vector[TOPICS.index(topic)] += weight
    length = math.sqrt(sum(v * v for v in vector))
    if length == 0:
        return vector
    return [v / length for v in vector]          # unit length, so dot product = cosine

def cosine(a, b):
    return sum(x * y for x, y in zip(a, b))

for text in ["cheap flights to Goa", "low-cost airline tickets", "an easy pasta recipe",
             "will it rain tomorrow?", "my laptop battery dies fast"]:
    vector = embed(text)
    rounded = []
    for value in vector:
        rounded.append(round(value, 2) + 0.0)
    print(f"{text:30} {rounded}")

print()
a, b = embed("cheap flights to Goa"), embed("low-cost airline tickets")
print("cheap flights vs low-cost airline tickets:", round(cosine(a, b), 3))
print("cheap flights vs pasta recipe:          ", round(cosine(a, embed("an easy pasta recipe")), 3))

"cheap flights to Goa" and "low-cost airline tickets" share no words, yet their vectors are almost identical (similarity 0.996), because both are about travel and money. A pasta recipe points somewhere else entirely.

Why word counts aren't enough

Before neural embeddings, a common approach was to count words (a "bag of words", or the weighted version called TF-IDF). It works when queries and documents use the same words, and fails when they don't: "cheap flights" and "low-cost airline tickets" would get a similarity of zero. You will build one in the exercise below. Neural embeddings fixed exactly this weakness.

Creating real embeddings

These run on your own computer. With an API (here OpenAI's Python SDK, one of several providers):

from openai import OpenAI

client = OpenAI()
response = client.embeddings.create(
    model="text-embedding-3-small",          # check the provider's current models
    input=["cheap flights to Goa", "low-cost airline tickets"],
)
vectors = [item.embedding for item in response.data]
print(len(vectors), "vectors of", len(vectors[0]), "numbers")

With an open model on your own machine, using the sentence-transformers library:

from sentence_transformers import SentenceTransformer

model = SentenceTransformer("all-MiniLM-L6-v2")   # a small, popular open model
vectors = model.encode(
    ["cheap flights to Goa", "low-cost airline tickets"],
    normalize_embeddings=True,                     # unit length, so dot product = cosine
)
print(vectors.shape)                               # (2, 384)

Practical habits

  • Batch your requests: most APIs accept many texts per call, which is faster and cheaper.
  • Query versus document: some models want to know whether a text is a search query or a document (an "input type" setting, or a prefix such as "query:"). Follow the model's instructions; it improves search quality.
  • Store the text with the vector, plus the model name and version.
  • Re-embed everything if you change models: old and new vectors can't be compared.
  • Mind the input limit: embedding models have a maximum input length; longer text is cut off or rejected, which is one reason to chunk.

Common mistakes

Practice exercise

Build the simplest possible text vector: word counts. It works for exact words but knows nothing about meaning.

Your solutionPython
vocabulary = ["cheap", "flight", "hotel", "pasta"]
text = "cheap flight and a cheap hotel"

# Make a "bag of words" vector: for each word in vocabulary, count how many
# times it appears in text. Print the list. Expected: [2, 1, 1, 0]
Knowledge check

How are most text embedding models trained to place similar texts close together?

Summary

  • An embedding model turns any text into a fixed-length vector.
  • Models learn with contrastive learning on pairs that belong together.
  • Unlike word counts, neural embeddings place synonyms and paraphrases together.
  • Create embeddings with an API or an open model; batch requests and store text, vectors and model name together.
  • Use one model (and its documented settings) for queries and documents, and re-embed if you switch.

Next: choosing an embedding model.

Finished reading? Tick it off to track your progress.