How Vector Embeddings Work: A Practical Code Guide

A vector embedding is a list of numbers that represents a piece of text. The numbers are chosen so that texts with similar meaning get similar lists. Once text is in that form, your code can do something string matching never could: find things that mean the same thing even when they share no words at all.

This guide builds that idea from the ground up. We start with why naive approaches fail, implement the core math in plain NumPy, then build a working semantic search and connect the dots to the embedding models you actually use in production.

Why string matching is not enough

Say you are building search over support tickets. A user types “my password reset email never arrived” and the knowledge base contains an article titled “Didn’t receive your password reset link?” A keyword search for “email” might miss the article entirely. Stemming and synonyms help, but they are maintenance-heavy: every synonym list is a hand-written approximation of meaning.

The deeper problem is structural. Strings give you exact-match semantics. Two strings are either equal or they are not. There is no notion of “close.” Embeddings fix this by mapping text into a continuous space where closeness has meaning.

From one-hot vectors to dense vectors

The simplest vector representation is a one-hot vector. Build a vocabulary of every word you have ever seen, then represent a word as a vector that is 1 at its own index and 0 everywhere else:

vocab = ["king", "queen", "man", "woman", "apple"]
# one-hot for "king"
king = [1, 0, 0, 0, 0]

This fails twice. First, the vectors are enormous: one dimension per vocabulary word, so 50,000 dimensions for a modest vocabulary. Second, the geometry is useless. Every pair of distinct words is at the same distance from each other, because one-hot vectors are mutually orthogonal. “King” is as far from “queen” as it is from “apple.” No meaning survives.

Dense embeddings solve both problems at once. Instead of one dimension per word, you use a fixed, much smaller number of dimensions (a few hundred to a few thousand), and every entry is a learned real number:

king   = [0.21, -0.83, 0.44, 0.12, ...]   # 384 numbers
queen  = [0.19, -0.79, 0.41, 0.15, ...]
apple  = [-0.52, 0.31, -0.09, 0.66, ...]

Now the geometry carries information. “King” and “queen” sit near each other; “apple” sits elsewhere. Individual dimensions are not labeled (“dimension 42 is royalty”), but the relative positions of points encode semantic relationships. That is the whole trick: meaning becomes position in space.

Where the numbers come from: the distributional hypothesis

The working assumption behind every embedding model is old: “you shall know a word by the company it keeps.” Words that appear in similar contexts tend to mean similar things. A model trained to predict a word from its neighbors (or neighbors from a word) is forced to place words with similar contexts near each other, because that arrangement makes the prediction task easier.

Early models like word2vec trained exactly this way on raw text, with no human labels. Modern sentence embeddings use transformer models trained on pairs of sentences: pairs labeled as similar get pulled together, pairs labeled as different get pushed apart. The training objective differs, but the result is the same kind of artifact: a function that maps text to a point in a high-dimensional space.

You do not need to train these models yourself. Pre-trained models are the standard, and you treat them as functions: text in, vector out. What you do need to understand is the math that happens after the vector comes out, because that is where your application logic lives.

The core operation: cosine similarity

Comparing two embeddings almost always means computing cosine similarity: the cosine of the angle between the two vectors.

import numpy as np

def cosine_similarity(a: np.ndarray, b: np.ndarray) -> float:
    return float(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)))

a = np.array([1.0, 2.0, 3.0])
b = np.array([1.0, 2.0, 3.0])
print(cosine_similarity(a, b))  # 1.0: identical direction

The result is 1.0 for vectors pointing the same way, 0.0 for perpendicular vectors, and -1.0 for opposite directions. Text embeddings from most models live in a region where scores typically fall between about 0 and 1, with higher meaning more similar.

Why angles and not distances? Cosine similarity ignores magnitude. Two vectors pointing the same direction are treated as identical even if one is twice as long. For text, this is usually what you want: a longer sentence should not be “farther” from its paraphrase just because the model emitted a longer vector. That said, the choice is a modeling decision, not a law of physics. Euclidean distance works when magnitude carries information (some retrieval setups use it), and dot product is popular in maximum-inner-product search where vectors are pre-normalized so that dot product and cosine similarity agree.

Many production embedding models output normalized vectors (length 1) precisely so that the cheaper dot product can stand in for cosine similarity:

def normalize(v: np.ndarray) -> np.ndarray:
    return v / np.linalg.norm(v)

# For unit vectors, dot product == cosine similarity
a_n, b_n = normalize(a), normalize(b)
print(float(np.dot(a_n, b_n)))  # same as cosine_similarity(a, b)

If your model’s docs say outputs are normalized, use the dot product and skip the division. If they do not say, normalize defensively. Mixing normalized and unnormalized vectors in one index silently corrupts your rankings.

Building semantic search in NumPy

With embeddings and cosine similarity, semantic search is a loop: embed the corpus once, embed each query, rank by similarity.

import numpy as np

def embed(text: str) -> np.ndarray:
    """Placeholder: in practice, call your embedding model here."""
    rng = np.random.default_rng(abs(hash(text)) % (2**32))
    return rng.normal(size=384)

corpus = [
    "How to reset your account password",
    "Refund policy for annual subscriptions",
    "Configuring two-factor authentication",
    "Troubleshooting login error 401",
    "Changing your billing email address",
]

# Embed the corpus once, upfront
doc_vectors = np.array([embed(doc) for doc in corpus])
doc_vectors = doc_vectors / np.linalg.norm(doc_vectors, axis=1, keepdims=True)

def search(query: str, top_k: int = 3):
    q = embed(query)
    q = q / np.linalg.norm(q)
    scores = doc_vectors @ q          # dot product == cosine for unit vectors
    ranked = np.argsort(scores)[::-1][:top_k]
    return [(corpus[i], float(scores[i])) for i in ranked]

for doc, score in search("I can't log in to my account"):
    print(f"{score:.3f}  {doc}")

The random-vector embed() above is a stand-in so the code runs anywhere; the interesting part is the pipeline shape. In production you replace embed() with a real model call and this exact ranking loop still works. Note two things the code makes explicit:

  1. Embeddings are computed once per document. At query time you only embed the query and run one matrix-vector multiply. For 100k documents at 768 dimensions that multiply is milliseconds on a CPU.
  2. Similarity is relative, not absolute. A score of 0.82 means nothing on its own. What matters is the ranking: which documents score highest for this query. Thresholds like “only return results above 0.75” are fragile because the score distribution shifts with the model and the corpus.

What real embedding models add

The NumPy code above shows the consumer side. The producer side, the model, is where the quality comes from, and it is worth knowing what you are buying when you pick one.

Training data and objective. General-purpose models are trained on web text, Q&A pairs, and search logs. A model fine-tuned on question-answer pairs will rank FAQ-style retrieval better than one trained only on raw prose. Match the training objective to your task: retrieval, clustering, and classification each favor slightly different models.

Context limits. Embedding models have a maximum input length, commonly 512 tokens for older models and up to 8k for newer ones. Text longer than the limit gets truncated silently. If you embed whole documents, you are effectively embedding their beginnings. The standard fix is chunking: split documents into passages, embed each passage, and retrieve at passage granularity.

Dimensionality. Common sizes are 384, 768, 1024, and 3072. More dimensions are not automatically better; a well-trained 384-dimension model routinely beats a sloppy 1024-dimension one on retrieval benchmarks. Dimensions cost you twice: once in storage (vectors per document times dimensions times bytes per float) and once in search latency. Some newer models support Matryoshka-style truncation, where you can cut the vector short at query time and keep most of the quality, which makes the trade-off adjustable rather than fixed.

Pooling and normalization. Sentence embedding models typically average the token vectors (mean pooling) and then normalize. If you ever roll your own pooling over a base transformer, forgetting the normalization step is the classic bug: your cosine similarities will silently degrade into magnitude comparisons.

In practice, most developers reach for a library rather than raw transformers. The sentence-transformers package is the common starting point:

from sentence_transformers import SentenceTransformer

model = SentenceTransformer("all-MiniLM-L6-v2")  # 384 dimensions, fast baseline
vectors = model.encode(corpus, normalize_embeddings=True)

query_vec = model.encode("I can't log in to my account", normalize_embeddings=True)
scores = vectors @ query_vec

This is the same pipeline as the NumPy version, with a real encoder swapped in. Everything said about ranking, thresholds, and normalization still applies.

Practical gotchas worth knowing early

Embeddings reflect their training data. A model trained mostly on English web text will produce worse vectors for Indonesian legal documents or medical notes. If your domain is specialized, test retrieval quality on your own queries before committing to a model. A quick evaluation set of 50 query-to-expected-document pairs, scored by hand, beats any public benchmark for your decision.

Similar scores do not mean identical meaning. Embeddings capture topical relatedness more than precise semantics. “How to cancel my subscription” and “How to renew my subscription” can score uncomfortably close because they share nearly all their context words. If your application needs fine distinctions (cancellation vs. renewal, install vs. uninstall), plan for a reranking step or a classifier on top of retrieval rather than trusting raw similarity.

Anisotropy is real but manageable. In many models, all embeddings cluster in a narrow cone of the space rather than spreading evenly. This compresses the dynamic range of cosine scores, which is one reason absolute thresholds are unreliable. Normalization and model choice mitigate it; you do not need to fix the geometry yourself.

Changing models means re-embedding everything. Vectors from different models live in different spaces and cannot be compared. If you switch from model A to model B, every stored vector must be regenerated. Keep the source text alongside your vectors so a model migration is a batch job, not a data loss event.

Mind the cost model of APIs. Hosted embedding APIs charge per token. Re-embedding a large corpus on every deploy is a line item. Cache vectors, version your embedding pipeline (model name plus chunking config), and only re-embed documents whose source text or pipeline version changed.

Where to go from here

Once the basics are in place, the natural next steps are:

  • Vector databases (Qdrant, Weaviate, pgvector) for when brute-force NumPy search outgrows memory or latency budgets. They implement approximate nearest neighbor search, trading a small accuracy loss for large speedups.
  • Hybrid search, combining embedding similarity with classic keyword scoring (BM25), which fixes the cases where exact terms matter, like product codes or names.
  • Rerankers: small models that score query-document pairs jointly and reorder your top-k results. They cost more per query than embeddings but fix the cancel-vs-renew problem.
  • Evaluation: build that 50-query test set before you need it. Retrieval quality is the metric your users actually feel.

Embeddings are not magic. They are a coordinate system for meaning, learned from text, consumed with linear algebra. The developers who get the most out of them are the ones who understand the two or three operations that matter, cosine similarity, normalization, and ranking, and who test on their own data instead of trusting defaults.

Ditulis oleh

Firdaus Safari Putra

Founder, PT FirKaizen Digital Solutions

Firdaus Safari Putra adalah founder PT FirKaizen Digital Solutions. Ia membangun dan mengoperasikan infrastruktur server di balik panduan ini, dan menulis berdasarkan apa yang benar-benar ia jalankan, uji, dan ukur — bukan teori.