Sub topic 2
Generating Embeddings with a Pretrained Model
Assume you know basic Python, arrays, dot products, and keyword search. An embedding model converts text into a fixed-length numeric vector. Texts with similar meanings tend to produce nearby vectors.
Generate embeddings
A pretrained model already learned language patterns from large text collections. You can use it to encode both documents and queries. all-MiniLM-L6-v2 produces 384-dimensional vectors.
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("all-MiniLM-L6-v2")
texts = [
"How do I reset my password?",
"Steps to recover access to your account",
"The weather is sunny today",
]
embeddings = model.encode(texts, normalize_embeddings=True)
print(embeddings.shape) # (3, 384)normalize_embeddings=True scales every vector to length 1. This makes the dot product equal to cosine similarity.
Embed, index, query, and rank
A semantic search pipeline follows this sequence:
First, encode documents and store their vectors with document identifiers. For each query, encode the query with the same model. Search the index for the most similar document vectors, then return the corresponding text.
Exact top-k search
For a small collection, compare the query with every document. If normalized document vectors form a matrix D and the normalized query is q, D @ q computes all cosine similarities at once.
import numpy as np
documents = [
"Recover access through the account security settings.",
"The office is open from 9 to 5.",
"Change your login credentials in the security settings.",
]
doc_vectors = np.array([
[0.8, 0.2],
[0.1, 0.9],
[0.7, 0.3],
])
query_vector = np.array([0.75, 0.25])
scores = doc_vectors @ query_vector
top_ids = np.argsort(-scores)[:2]
for i in top_ids:
print(f"{scores[i]:.3f} {documents[i]}")Exact search is simple and gives the true ranking, but its cost grows with the number of vectors.
Chunk long documents
Embedding models have input limits. Split long documents into overlapping chunks so important context is less likely to fall across a boundary.
def chunk_words(text, chunk_size=200, overlap=40):
if overlap >= chunk_size:
raise ValueError("overlap must be smaller than chunk_size")
words = text.split()
step = chunk_size - overlap
chunks = []
for start in range(0, len(words), step):
chunks.append(" ".join(words[start:start + chunk_size]))
if start + chunk_size >= len(words):
break
return chunksStore each chunk as a separate searchable item, together with its source document and position.
Exercise
Why normalize vectors before using a dot product for semantic search?
Show answer
Normalization makes every vector unit length, so the dot product measures cosine similarity instead of mixing direction with vector magnitude.