Что такое векторные эмбеддинги
Поймите, как нейронные сети отображают текст в плотные векторы многомерного пространства, почему семантически похожие тексты дают близкие векторы и что измеряет косинусное сходство.
«Что такое векторные эмбеддинги» — бесплатный урок AI Engineering Academy на CoddyKit. Это урок 1 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения AI Engineering Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс AI Engineering Academy содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
The Meaning Behind Numbers
A vector embedding is a list of numbers (a vector) that represents the meaning of a piece of text. Instead of storing words as raw strings, neural networks learn to encode semantic meaning into dense numerical arrays. Two texts with similar meaning will produce vectors that are close together in this high-dimensional space.
High-Dimensional Vector Space
Modern embeddings typically have 768 to 3072 dimensions. Each dimension captures some latent feature of meaning — topics, sentiment, style, and relationships — without being explicitly programmed. The result is a rich geometric space where semantic relationships become measurable distances.
For example, text-embedding-3-small produces 1536-dimensional vectors, while text-embedding-3-large produces 3072-dimensional vectors.
How Neural Networks Learn Embeddings
Embedding models are trained on massive text corpora to predict missing words (masked language modeling) or to distinguish semantically similar from dissimilar pairs. During training, the network adjusts millions of weights until similar texts naturally cluster together in the learned vector space.
This is why embeddings are called dense representations — every dimension carries information, unlike sparse one-hot encodings where most values are zero.
Cosine Similarity: Measuring Closeness
Cosine similarity measures the angle between two vectors, returning a value between -1 and 1. A score of 1 means the vectors point in exactly the same direction (identical meaning), 0 means orthogonal (unrelated), and -1 means opposite directions.
It is preferred over Euclidean distance for text because it ignores vector magnitude and focuses purely on direction, making it robust to differences in text length.
import numpy as np
def cosine_similarity(vec_a, vec_b):
dot_product = np.dot(vec_a, vec_b)
norm_a = np.linalg.norm(vec_a)
norm_b = np.linalg.norm(vec_b)
return dot_product / (norm_a * norm_b)
# Example with tiny 3D vectors
v1 = np.array([0.8, 0.2, 0.5])
v2 = np.array([0.9, 0.1, 0.4])
print(cosine_similarity(v1, v2)) # Close to 1.0Why Semantic Similarity Matters
Traditional keyword search breaks when users paraphrase: searching for automobile misses documents about cars. Vector embeddings solve this because semantically equivalent texts map to nearby vectors regardless of the exact words used.
This enables semantic search, where you find the most relevant result based on meaning rather than word overlap — a fundamental capability needed for RAG systems.
The Embedding Vector Visualized
Imagine plotting sentences in a 2D map (a simplified analogy). Sentences about machine learning cluster in one region, sentences about cooking cluster in another, and sentences about sports form a third cluster. Vector embeddings create this map in thousands of dimensions.
Famous relationships like king - man + woman ≈ queen are real arithmetic in this space — vector operations encode semantic analogies.
Generating a Simple Embedding
The OpenAI embeddings API accepts text and returns a list of floats. A single API call can embed one sentence or an entire paragraph. The returned vector has a fixed dimension regardless of input length.
Important: longer inputs do not produce larger vectors — they still produce the same fixed-size vector, but very long texts may lose fine-grained detail because the model compresses everything into that fixed space.
from openai import OpenAI
client = OpenAI() # uses OPENAI_API_KEY from environment
response = client.embeddings.create(
model='text-embedding-3-small',
input='Vector embeddings capture semantic meaning.'
)
embedding = response.data[0].embedding
print(f'Dimensions: {len(embedding)}') # 1536
print(f'First 5 values: {embedding[:5]}')Embedding Multiple Texts at Once
You can embed multiple strings in a single API call by passing a list to the input parameter. This is much more efficient than making one request per text because it reduces network round-trips and lets the API batch the computation.
The response contains one embedding object per input, in the same order, so you can zip them together with your original texts.
from openai import OpenAI
client = OpenAI()
texts = [
'Python is a programming language.',
'Snakes are reptiles.',
'Machine learning requires data.'
]
response = client.embeddings.create(
model='text-embedding-3-small',
input=texts
)
for text, result in zip(texts, response.data):
print(f'{text[:30]}... -> {len(result.embedding)}D vector')Dot Product vs Cosine Similarity
If your embeddings are L2-normalized (unit vectors with magnitude 1), the dot product equals cosine similarity. OpenAI's embedding models return normalized vectors, so you can use either metric — dot product is slightly faster to compute.
However, when combining embeddings from different models or sources that may not be normalized, always compute cosine similarity explicitly to avoid misleading results.
import numpy as np
def normalize(vec):
return vec / np.linalg.norm(vec)
v1 = normalize(np.array([3.0, 4.0, 0.0]))
v2 = normalize(np.array([4.0, 3.0, 0.0]))
# For unit vectors: dot product == cosine similarity
dot = np.dot(v1, v2)
print(f'Dot product: {dot:.4f}') # same as cosine simEmbeddings vs One-Hot Encoding
One-hot encoding represents each word as a vector with exactly one 1 and all other values 0. A vocabulary of 50,000 words produces 50,000-dimensional vectors that are almost entirely zeros — very inefficient.
Dense embeddings use 768-3072 dimensions but every dimension carries real information. The space is 10-20x smaller yet captures far more nuance, including synonyms, analogies, and compositional meaning that one-hot encoding completely misses.
Common Use Cases for Embeddings
Beyond semantic search, embeddings power many practical applications:
- Semantic search — find documents by meaning, not keywords
- Recommendation systems — suggest items similar to ones the user liked
- Clustering — group documents by topic automatically
- Classification — feed embeddings to a linear classifier
- Deduplication — detect near-duplicate content
All RAG systems depend on embeddings to match user queries with relevant document chunks.
Quick Check
Test your understanding of AI Engineering concepts from this lesson.
Lesson Recap
In this lesson you learned: vector embeddings encode semantic meaning as dense numerical arrays, cosine similarity measures semantic closeness by comparing vector directions, and OpenAI's embedding API converts text to fixed-size vectors in a single call. Next up we explore how to generate and compare embeddings using the OpenAI models in practice.
Часто задаваемые вопросы
Урок «Что такое векторные эмбеддинги» бесплатный?
Да — полный текст урока «Что такое векторные эмбеддинги» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс AI Engineering Academy, подпишись на CoddyKit PRO. Курс AI Engineering Academy содержит 4 уроков всего.
Чему я научусь в уроке «Что такое векторные эмбеддинги»?
Поймите, как нейронные сети отображают текст в плотные векторы многомерного пространства, почему семантически похожие тексты дают близкие векторы и что измеряет косинусное сходство. Ты практикуешь AI Engineering Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать AI Engineering Academy?
Предыдущий опыт не требуется. AI Engineering Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 1 из 4.
Сколько времени занимает урок «Что такое векторные эмбеддинги»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке AI Engineering Academy?
Да. Каждый урок AI Engineering Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Что такое векторные эмбеддинги
- Создание эмбеддингов с помощью OpenAI
- Семантический поиск с NumPy
- Кластеризация и визуализация эмбеддингов