Blog→Embeddings and vectors
Artificial intelligenceProgrammingFor beginners

What is an embedding: how AI turns meaning into numbers

27 Aug 2026 · 15 min read

When you type “AI course for beginners” into a search, you also expect results titled “introduction to artificial intelligence”. The words don’t match, the meaning does. An embedding converts text, an image or another object into a numeric vector in which such semantic similarity can be computed.

The article in 30 seconds

Three things worth knowing

  • 1An embedding is a list of numbers produced by a model, not a hand-built dictionary of meanings.
  • 2Similar objects have similar vectors in a specific vector space — according to what the model learned to consider similar.
  • 3Embeddings enable semantic search and RAG, but by themselves they don’t guarantee truth, safety or a correct answer.

Embedding: text, image and audio are converted into vectors and similar meanings lie close together in the space

What an embedding is

An embedding, also called a vector representation, is a mapping of an object into a space of numbers. The input can be a word, a sentence, a whole document, a photograph, audio, a product, a user or, say, a graph node. The output is an ordered list of numbers of fixed length:

The value 0.18 alone usually doesn’t mean “artificial intelligence” and −0.42 doesn’t mean “beginner”. The information is carried only by the whole vector and its position relative to other vectors produced by the same model.

The key property is: objects that the model, according to its training, considers similar end up close to each other. The embedding of the sentence “Python basics” may therefore be closer to “Python programming for beginners” than to “caring for fruit trees”. It is not, however, a general definition of meaning. It is a representation learned from the data and objective of a specific model.

Why AI needs vectors

A neural network doesn’t work directly with words or images. Its layers multiply matrices, add numbers and apply non-linear functions. The input must therefore take a numeric form. The simplest option for words is one-hot encoding: each word has a long vector full of zeros and a single one at its own position.

Such encoding distinguishes words but doesn’t capture their relationship. The vectors of the words “dog” and “puppy” are as far apart as “dog” and “database”. Moreover, they have as many dimensions as there are items in the vocabulary and most values are zero.

An embedding, by contrast, is a dense vector: it has considerably fewer dimensions and almost all values carry part of the information. The model learns its coordinates so that they are useful for the chosen task. For text this often means that expressions used in similar contexts get similar representations.

An embedding is not “understanding” in the human sense

A vector captures the statistical structure learned from data. That can be extremely useful for search and classification, but it doesn’t mean the model understands experience, intent or truth the way a human does.

How an embedding is created

The exact procedure depends on the architecture and training. For a modern text embedding model, four steps can be described in simplified form:

  1. Tokenisation. The text is split into tokens — whole words, parts of words, punctuation or other units. A Czech word can form one or several tokens.
  2. Initial representation. Each token gets an input vector from a learned embedding table. Information about order or position is added.
  3. Contextualisation. Transformer layers transform the representation of each token according to the surrounding text. The word “lock” can therefore have one contextual state in a sentence about doors and another in a sentence about a canal.
  4. Merging into a single vector. The model uses pooling or a special learned output to create a fixed-length vector from text of variable length. A model intended for similarity is trained specifically for this step.

The last point matters. Not every language model automatically produces a quality embedding of whole sentences. For example, simply averaging arbitrary hidden states of a Transformer need not give a space suitable for semantic comparison. The model should be trained or fine-tuned precisely for retrieval, similarity or another intended task.

What the model learns during training

The older word2vec learned to predict a word from its surrounding context, or conversely the context from a given word. Modern embedding models often use contrastive learning: they get pairs that belong together and hard negative examples that look similar but are not the correct answer. The goal is to bring relevant pairs closer and push irrelevant ones apart.

For search, a positive pair can be a question and the paragraph with the answer. A negative example is a paragraph on a similar topic that doesn’t answer the question, however. The choice of training pairs therefore directly affects what “close” will later mean.

The vector space as a map of meanings

Every embedding can be understood as a point in a multi-dimensional space. The two-dimensional map below is only an illustration: a real model may use hundreds or thousands of dimensions and part of the relationships is lost when projecting into two dimensions.

Python Programming Java car train transport puppy dog
Illustrative 2D projection: distance expresses similarity learned by a specific model, not a universal and fixed map of meaning.

What the dimension of an embedding is

The dimension is the number of numbers in the vector. A vector of length 384 has 384 dimensions. More dimensions can give the model more capacity, but don’t automatically mean better results. They also increase storage size, the amount of transferred data and the cost of comparison.

A rough estimate for uncompressed float32 values is number of vectors × dimension × 4 bytes. A million vectors of 768 dimensions takes approximately 3.1 GB for the coordinates alone. Metadata, the database index, replication and operational overhead come on top.

Don’t directly compare vectors from different models. Each model creates its own coordinate system. When changing the model, it is usually necessary to recreate the embeddings of all documents and queries.

How embedding similarity is measured

Once we have two vectors, we need a number expressing their closeness. Most often cosine similarity, the dot product or Euclidean distance is used. The right choice depends on how the model was trained and what its documentation recommends.

Cosine similarity

cos(a,b) = a·b / (||a|| ||b||)

Compares the angle between vectors. It ignores their magnitude and is often used for semantic similarity of text.

Dot product

a·b = Σ aᵢbᵢ

Takes into account both direction and length of the vectors. For vectors normalised to length one it is identical to cosine similarity.

Euclidean distance

||a−b||₂

Measures the straight-line distance between endpoints. The smaller the result, the closer the vectors are.

With cosine similarity, 1 is usually maximum agreement of direction, 0 orthogonality and −1 opposite direction. In practice, however, there is no universal threshold like “above 0.8 the text is relevant”. The distribution of scores depends on the model, language, data and type of query. The threshold must be derived from your own test set, or you work with the ranking of the best top-k results.

A simplified numeric example

Imagine only three dimensions. The query has the normalised vector q = [0.8, 0.6, 0]. Document A has a = [0.75, 0.66, 0] and document B b = [0.1, 0.2, 0.97]. The dot product of the query with A is considerably higher, so A ends up before B. A real model does the same kind of calculation in hundreds of dimensions; the numbers in the example are not the output of a specific model.

What types of embeddings exist

Text

Static word embeddings

Each word has one vector regardless of the sentence. These include word2vec, GloVe or FastText. They are fast and illustrative, but handle ambiguity and context poorly.

Text

Contextual token embeddings

The representation of a token changes according to the surrounding words. A “mouse” next to a computer can thus have a different state from a “mouse” in a biology text.

Retrieval

Sentence and document embeddings

They convert text of varying length into a fixed-length vector. They are used for search, clustering, deduplication and classification.

Multiple modalities

Multimodal embeddings

Text and images can be mapped into a shared space. A text query can then be used to find photographs or to compare an image with a description.

Recommendation

User and product embeddings

Similarity need not mean the same topic. It can express similar behaviour: products bought by the same people or videos watched by a similar audience.

Structures

Graph and entity embeddings

Nodes and relationships can be converted into vectors according to their neighbourhood and roles in the graph. Useful for recommendation, anomaly detection or working with knowledge graphs.

Symmetric and asymmetric search

In symmetric similarity we compare objects of the same type, for example two paraphrases. In asymmetric retrieval a short question is compared with a longer paragraph containing the answer. Some models require a different prefix or a separate encoding method for the query and the document. Ignoring this instruction can significantly reduce quality.

Practical example: semantic search in Python

The following small example uses a local multilingual model from Sentence Transformers. We normalise both documents and query, so matrix multiplication corresponds to cosine similarity. The model is suitable for an illustrative demo; for production, compare several models on your own data.

Python
from sentence_transformers import SentenceTransformer
import numpy as np

model = SentenceTransformer(
    "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2"
)

dokumenty = [
    "Kurz vysvětluje základy Pythonu úplným začátečníkům.",
    "Neuronové sítě se učí z trénovacích dat.",
    "Fakturu pošleme po přijetí objednávky.",
    "Do umělé inteligence můžete vstoupit i bez předchozí praxe.",
]

vektory = model.encode(
    dokumenty,
    normalize_embeddings=True,
)

dotaz = "Jak začít s AI, když nemám zkušenosti?"
vektor_dotazu = model.encode(
    dotaz,
    normalize_embeddings=True,
)

skore = vektory @ vektor_dotazu
poradi = np.argsort(skore)[::-1]

for index in poradi[:3]:
    print(f"{skore[index]:.3f}  {dokumenty[index]}")

The output sorts the texts by similarity to the query. The exact scores may change with the version of the model and library. What matters is the order: the sentence about getting into AI should rank higher than the sentence about an invoice, even though the query doesn’t use the same wording.

For a few thousand items, similarity can be computed directly in NumPy. For millions of vectors, a specialised index for approximate nearest neighbour search is used.

From embedding to semantic search

A vector database stores the embedding together with the identifier of the original text and metadata, for example language, document type, date or user permission. For a query it returns the nearest vectors. The original content is usually loaded by the stored identifier.

For fast search in a large collection, Approximate Nearest Neighbor (ANN) indexes are used. A well-known example is HNSW, which organises vectors into a multi-layer graph. The search need not visit every point, but the price for speed is the possibility of missing some truly nearest neighbour. Index parameters therefore balance speed, memory and recall.

A more detailed look at storage, metadata and indexing is in the article What is a vector database and how AI agents use it.

When embeddings alone are not enough

Semantic search can overlook an exact product code, a contract number, an unusual abbreviation or a new proper name. Full-text search, by contrast, is strong in exact word matching. Production systems therefore often use hybrid search: they combine a lexical score, for example BM25, with vector similarity and re-rank the results.

The next step is a reranker. A cheap embedding index quickly selects, say, 50 candidates and a more accurate model that sees the query together with each candidate builds the final ranking from them. This separates fast candidate retrieval from the more expensive relevance assessment.

How embeddings work in RAG

RAG, or Retrieval-Augmented Generation, connects search with a generative model. In it, embeddings often handle the first part — retrieval:

  1. Documents are split into smaller excerpts, or chunks.
  2. Each chunk gets an embedding and is stored in the index.
  3. The user query is converted into a vector by the same model.
  4. The system finds relevant chunks, optionally filters and re-ranks them.
  5. The selected texts are inserted into the language model’s context.
  6. The model produces an answer and ideally cites sources.

So the embedding doesn’t generate the answer. It helps decide which material the generative model should receive. If retrieval selects the wrong documents, even a strong language model won’t produce a reliable answer from them.

Chunking: how much text to put into one vector

A whole long manual can technically be converted into a single vector only with a model that accepts such a length. For search, however, this tends to be bad: several topics merge into one representation and the returned document is too long. Excerpts that are too small, on the other hand, lose context.

  • Split by structure. Headings, paragraphs, lists and sections often give better boundaries than a fixed number of characters.
  • Preserve identity. Add the document title, parent heading, URL and version to the chunk.
  • Use overlap sparingly. It can protect sentences at the boundary, but it creates duplicates and increases costs.
  • Filter metadata before searching when it is a security condition. A user must not get someone else’s document just because it is semantically similar.

The RAG variants from simple search to GraphRAG and agentic control are compared in the article Types of RAG: from basic retrieval to GraphRAG and AI agents.

Where embeddings are used

  • Semantic search: finds content by meaning, not just by word match.
  • Recommender systems: connect users with similar products, films, music or courses.
  • Clustering: reveals topics in customer queries, reviews or documents without hand-prepared categories.
  • Classification: the embedding serves as input for a simpler model, or a new text is assigned to the nearest known examples.
  • Deduplication and paraphrase detection: reveals nearly identical content even when rephrased.
  • Anomaly detection: unusually distant points can signal a new type of request or an error in the data.
  • AI agents: embeddings help search memory, documentation and the tool catalogue. They don’t create agency itself, though; the article What is an AI agent and how does it work explains more.

Limitations and common mistakes

Similarity is not truth The nearest paragraph may be topically related but outdated, wrong or without an answer to the question.
One model is not the best everywhere A model strong in English need not work equally well with Czech, code, legal texts or short product names.
Bad chunking hides the answer Excerpts that are too long mix topics; too short ones lose conditions, exceptions and references.
There is no universal threshold A score of 0.75 can be excellent in one system and weak in another. Thresholds are calibrated on representative queries.
Changing the model requires migration Old and new vectors don’t live in the same space. Reindexing must be controlled, versioned and ideally without downtime.
A vector is not anonymisation An embedding can carry information about sensitive input and can be abused. Protect it as derived sensitive data.
Permissions belong before retrieval Filtering out a secret document only after retrieval can lead to leaks via logs, cache or intermediate results.
Retrieval doesn’t solve prompt injection A retrieved document can contain malicious instructions. Separate data from instructions and limit the actions of the downstream model.

Technical details that are easy to overlook

  • Respect the model’s maximum input length and monitor the actual token count.
  • Use exactly the same preprocessing, model version and recommended input format for documents and queries.
  • Store the model identifier, dimension, chunking version and a hash of the source text. Without them the index is hard to reproduce.
  • After a document changes, regenerate all affected chunks and remove the old vectors. Otherwise the system will return outdated content.
  • Don’t confuse similarity with the final ranking. Language, freshness, source authority and permissions can carry the same or greater weight.

How to tell that embedding search works

Five convincing demos are not enough. You need a test set of real queries and, for each of them, labelled relevant documents. Ideally it includes short and long queries, text without diacritics, exact identifiers, synonyms, vague questions and cases for which no correct document exists.

Create a gold set For each query, determine one or more relevant chunks and the cases with no answer.
Measure retrieval separately Recall@k says whether the relevant chunk made it into the top k results. MRR favours the situation where the first correct result is high.
Compare variants Test the model, chunk size, hybrid search, metadata and reranker with the same set.
Measure the whole RAG system Track answer correctness, grounding in sources, citations, latency and price. Good retrieval still doesn’t guarantee good generation.
Analyse errors Split failures into missing data, bad chunking, weak embedding, unsuitable filter, reranking and generative model error.

In production, add anonymised feedback and regularly sample failed queries. The distribution of queries changes and an index that worked at launch may lag behind after months.

Frequently asked questions about embeddings

Is an embedding the same as a vector?

An embedding is a vector used as a learned representation of some object. So every embedding is a vector, but not every arbitrary vector is an embedding.

Do I always need a vector database?

No. For a small collection you can hold all vectors in memory and compare directly. A specialised database starts to make sense because of volume, speed, metadata, filters, updates, replication and operational management.

Can an embedding be converted back into the original text?

There is no common exact inverse function, because many inputs can have similar representations. But that doesn’t make an embedding safe anonymisation. Models and attacks can reveal properties of the input, so protect sensitive data.

Does the same text always get the same embedding?

With the same model, version and preprocessing, inference tends to be deterministic. The result can change, however, after a service update or a change of prefix, tokenisation or normalisation. So store the version together with the vector.

Does an embedding understand negation?

Sometimes yes, but not always sufficiently. The sentences “the course is suitable for beginners” and “the course is not suitable for beginners” share most words and can end up dangerously close. Such minimal pairs belong in the test set.

Is a higher dimension always better?

No. Training, data and the target task decide. A higher dimension costs more memory and compute. Verify the choice by measuring quality, latency and total cost.

Key takeaways

  • An embedding converts text, an image or another object into a fixed-length vector.
  • Closeness of vectors expresses similarity learned by a specific model.
  • Vectors can be compared by cosine similarity, dot product or distance according to the model’s recommendation.
  • Embeddings power semantic search, recommendation, classification, clustering and retrieval in RAG.
  • System quality is determined not only by the model but also by chunking, metadata, hybrid search, reranking, permissions and evaluation.
  • Similarity is not truth and an embedding is neither encryption nor a security boundary.

Want to plug embeddings into a real AI application?

In the AI Agent Developer course we connect language models with documents, tools and application logic. You will learn to design retrieval, RAG and agentic workflows so that they work not only in a demo but also in practice.

See the AI agents course →

Sources and further reading

Zdeněk Vais

About the author

Zdeněk Vais

Founder · Senior Principal Software Engineer, Oracle

Zdeněk has been programming since high school. Since then he has gone from programmer through team leader to architect, building large financial systems, scientific applications and IoT solutions for aircraft along the way. He currently works as a senior principal software engineer at Oracle, where he builds the cloud for media services.

Meet our team

← Back to the blog