Training Paradigms, Loss Objectives, and Embeddings

Medium · Machine Learning · Software Engineer · Technical Screen

Prompt

In a machine learning technical screen, walk through the core concepts below clearly and illustrate each with concrete examples:

  1. Supervised learning: Define how supervised training works, what typical feature-target pairs look like, and the primary task categories it addresses.
  2. Unsupervised learning: Define learning without ground-truth targets and describe the main problem classes it solves.
  3. Self-supervised learning: Explain how self-supervision constructs training signals from raw inputs and how it differs from both supervised and unsupervised methods.
  4. Loss objectives: Explain the role a loss objective plays during optimization, why smooth losses are needed alongside evaluation metrics, and several widely used loss formulations.
  5. Vector embeddings: Explain what a dense embedding represents geometrically, how embedding spaces are trained, and how embeddings are queried at serving time.
  6. Production applications: Describe practical deployments of embeddings in real-world products, focusing on semantic retrieval and personalized recommendations.

Scope & Expectations

  • Contrast supervised, unsupervised, and self-supervised paradigms by where training signals originate, what objectives they optimize, and when to combine pretraining with fine-tuning.
  • Connect mathematical properties of common regression, classification, and contrastive losses (smooth gradients, outlier sensitivity, probability calibration) to model behavior.
  • Explain end-to-end embedding workflows from training objectives (lookup tables, encoders, dual-tower contrastive setups) through low-latency approximate nearest-neighbor serving, cold-start handling, and version consistency.

Step-by-step walkthrough

  1. Supervised learning: learning from input-answer pairs

    Supervised learning trains a model on pairs (x, y), where x is the input (features, such as user activity numbers, pixel values, or text) and y is the desired answer (label or target). During training, the model adjusts its internal parameters (trainable numbers called weights w and bias b) so its function f(x) predicts y accurately on brand-new inputs drawn from the same underlying distribution.

    Typical tasks:

    • Classification (y is a discrete category): spam vs. not spam, fraud vs. legitimate transaction, or which category a product belongs to.
    • Regression (y is a continuous number): home sale price, package delivery minutes, or next week's electricity demand.
    • Structured and ranking outputs: a part-of-speech or entity tag per word, bounding boxes for objects in an image, or an ordered list of search results trained from user clicks.

    Where labels come from: Either human annotators (accurate, but slow and costly) or logged system outcomes such as clicks, purchases, and confirmed record merges. Logged labels are abundant and cheap, but they carry selection bias (a distortion caused by only observing user feedback on items the previous system chose to show near the top).

    To see how one training update actually works, trace logistic regression on a single binary example. It computes a weighted score z = w · x + b and squashes z into [0, 1] using the sigmoid function sigmoid(z) = 1 / (1 + e^(-z)) to predict probability p. Then it computes the gradient (the vector of partial derivatives showing which parameter direction increases the error fastest) and nudges the parameters in the opposite direction:

    Given:  input x = [1.0, 2.0],  true label y = 1
    Start:  weights w = [2.0, -1.0],  bias b = 0.5,  learning rate lr = 0.1
    
    1. Forward pass (predict probability):
       z    = 2.0*1.0 + (-1.0)*2.0 + 0.5 = 0.5
       p    = 1 / (1 + exp(-0.5))        = 0.6225
    
    2. Measure error (binary log loss = -ln(p) when y = 1):
       loss = -ln(0.6225)                = 0.4741
    
    3. Backward pass (compute gradient of loss with respect to w and b):
       dL/dz = p - y                     = 0.6225 - 1.0 = -0.3775
       dL/dw = (p - y) * x               = [-0.3775, -0.7551]
       dL/db = p - y                     = -0.3775
    
    4. Parameter update (w_new = w - lr * dL/dw):
       w_new = [2.0 - 0.1*(-0.3775), -1.0 - 0.1*(-0.7551)] = [2.0378, -0.9245]
       b_new = 0.5 - 0.1*(-0.3775)                         = 0.5378
    
    5. Check the same example after the update:
       z_new    = 2.0378*1.0 + (-0.9245)*2.0 + 0.5378 = 0.7266
       p_new    = 1 / (1 + exp(-0.7266))              = 0.6741   (up from 0.6225)
       loss_new = -ln(0.6741)                         = 0.3944   (down from 0.4741)
    

    One label told the model it was under-confident, and one gradient step moved p closer to 1. Supervised training simply repeats this loop across millions of examples.

  2. Unsupervised learning: discovering structure without labels

    Unsupervised learning receives only raw inputs x with no target y. Instead of predicting an external answer, the model uncovers hidden organization inside the data itself: natural groups, compact summaries, or rare outliers.

    Core problems it solves:

    • Clustering: grouping customers with similar buying habits or grouping news articles covering the same story (for example, k-means, Gaussian mixture models, DBSCAN).
    • Dimensionality reduction: compressing 1,000 correlated columns into 20 informative axes using PCA (Principal Component Analysis, which keeps the directions of largest variance), or projecting high-dimensional data to 2D for visual inspection (t-SNE, UMAP).
    • Density estimation and anomaly detection: modeling what "normal" traffic or card spend looks like so unusual points stand out immediately.
    • Representation learning: training an autoencoder (a neural network that squeezes x through a narrow bottleneck vector and tries to reconstruct x on the other side).

    Here is a complete trace of k-means clustering (k = 2) on four 1D numbers [1, 2, 9, 10], minimizing the sum of squared distances from each point to its assigned group center (centroid):

    Points: [1, 2, 9, 10]
    Initialize centroids: C1 = 1.0, C2 = 2.0
    
    Iteration 1:
      Assign each point to nearer centroid:
        1  -> |1 - 1.0| = 0.0 vs |1 - 2.0| = 1.0  => Group 1: {1}
        2  -> |2 - 1.0| = 1.0 vs |2 - 2.0| = 0.0  => Group 2: {2}
        9  -> |9 - 1.0| = 8.0 vs |9 - 2.0| = 7.0  => Group 2: {2, 9}
        10 -> |10- 1.0| = 9.0 vs |10- 2.0| = 8.0  => Group 2: {2, 9, 10}
      Recompute centroids as group means:
        C1 = 1.0,   C2 = (2 + 9 + 10) / 3 = 7.0
    
    Iteration 2:
      Assign each point to nearer centroid (1.0 vs 7.0):
        1  -> dist 0.0 vs 6.0  => Group 1
        2  -> dist 1.0 vs 5.0  => Group 1: {1, 2}
        9  -> dist 8.0 vs 2.0  => Group 2
        10 -> dist 9.0 vs 3.0  => Group 2: {9, 10}
      Recompute centroids:
        C1 = (1 + 2) / 2 = 1.5,   C2 = (9 + 10) / 2 = 9.5
    
    Iteration 3:
      Assignments stay {1, 2} and {9, 10} -> converged!
      Objective = (1 - 1.5)^2 + (2 - 1.5)^2 + (9 - 9.5)^2 + (10 - 9.5)^2
                = 0.25 + 0.25 + 0.25 + 0.25 = 1.0
    

    Because there is no ground-truth label sheet, evaluating unsupervised models is harder: teams rely on geometric proxies such as silhouette score (how tight each cluster is compared with distance to the next-nearest cluster), stability across random seeds, or whether the clusters boost a downstream business metric.

  3. Self-supervised learning: turning raw data into its own labels

    Human labels are scarce, while unlabeled text, images, and audio are massive. Self-supervised learning bridges this gap by inventing a pretext task where part of the raw input is hidden or transformed and the model must predict what is missing or match two views of the same item. Mechanically, training still uses (input, target) pairs and a supervised loss—the difference is that the data generates its own targets for free.

    Three workhorse pretext tasks:

    • Next-token prediction (autoregressive language models like GPT): given "the cat sat on the", predict "mat". Every token position in a 1-billion-token corpus automatically becomes a training target.
    • Masked prediction (BERT for text; Masked Autoencoders for vision): replace ~15% of words ("the cat [MASK] on the mat") or most image patches with a blank token and predict the original content from bidirectional context.
    • Contrastive learning (SimCLR for images): create two random augmentations (crops, color shifts) of the same photo and train the encoder to pull their output vectors together while pushing vectors of different photos apart. (Models like CLIP pair web images with their existing alt-text captions; because captions are noisy external annotations rather than carved out of the pixels alone, CLIP is often described as weakly supervised or multimodal contrastive learning.)
    Paradigm          Where targets come from    Training signal               Typical goal
    ----------------  -------------------------  ----------------------------  ----------------------------------
    Supervised        Humans or logged outcomes  Predict label y from x        Solve a specific end task directly
    Unsupervised      None                       Cluster spread, density,      Discover groups, anomalies, or
                                                 or input reconstruction       low-dimensional summaries
    Self-supervised   Carved out of raw x itself Predict hidden part or match  Pretrain rich general features,
                                                 augmented views               then fine-tune with few labels
    

    In modern ML, the standard recipe is self-supervised pretraining on huge unlabeled corpora followed by supervised fine-tuning on a small labeled dataset—cutting the human labels needed from millions down to thousands or even hundreds.

  4. Loss functions: turning mistakes into a smooth compass

    A loss function L(y, y_hat) assigns a single non-negative penalty to a prediction y_hat compared against target y: 0 when the prediction is ideal, larger as it gets worse. Training minimizes the average loss across examples, often plus a regularization penalty (an extra term like lambda * ||w||^2 that discourages overly large weights so the model does not memorize noise).

    Why we cannot just optimize our business metric directly: Metrics like classification accuracy or search recall@10 change in sudden jumps. Nudging a weight by 0.0001 changes predicted probabilities slightly without flipping any class decision, so accuracy stays flat and its derivative is 0 almost everywhere—leaving gradient descent blind. We therefore optimize a smooth, differentiable surrogate loss (like log loss) during training and evaluate on the business metric afterward.

    Common losses and what their math rewards:

    1. Regression on y = [3.0, -0.5, 2.0],  pred = [2.5, 0.0, 2.1]
       Errors (pred - y) = [-0.5, +0.5, +0.1]
       MSE (Mean Squared Error)  = (0.25 + 0.25 + 0.01) / 3 = 0.1700
       MAE (Mean Absolute Error) = (0.50 + 0.50 + 0.10) / 3 = 0.3667
    
       Outlier sensitivity on targets [1, 2, 3, 100]:
       - Single constant minimizing MSE is the mean   (26.5) -> pulled hard by 100
       - Single constant minimizing MAE is the median (any value in [2, 3]) -> ignores 100's magnitude
       - Huber loss blends both: squared near 0 (smooth gradient) and linear in the tails (outlier-safe)
    
    2. Binary classification: log loss = -ln(p_true), where p_true is predicted probability of true class
       p_true = 0.90 -> loss = 0.105      (confident and right: tiny penalty)
       p_true = 0.50 -> loss = 0.693      (coin flip)
       p_true = 0.10 -> loss = 2.303
       p_true = 0.01 -> loss = 4.605      (confident and wrong: steep penalty!)
    
    3. Multi-class cross-entropy on raw scores (logits) = [2.0, 1.0, 0.1], true class = 0
       Softmax probabilities p_i = exp(z_i) / sum_j exp(z_j) = [0.6590, 0.2424, 0.0986]
       Cross-entropy loss        = -ln(p_0) = -ln(0.6590)    = 0.4170
    
    4. Margin and embedding losses:
       Hinge loss (SVM, y in {-1, +1}): max(0, 1 - y * score) -> y = +1, score = 0.3 gives 0.7
       Triplet loss: max(0, dist(anchor, positive) - dist(anchor, negative) + margin)
       InfoNCE: multi-class cross-entropy asking "out of 1 true match and K negatives, which one matches?"
    

    Notice in Python how we subtract np.max(logits) before np.exp (max-shifting, a numerical stability trick that keeps exp from overflowing to inf on large scores without changing the ratio):

    import numpy as np
    
    y = np.array([3.0, -0.5, 2.0])
    pred = np.array([2.5, 0.0, 2.1])
    mse = np.mean((pred - y) ** 2)        # 0.17
    mae = np.mean(np.abs(pred - y))       # 0.366666...
    
    logits = np.array([2.0, 1.0, 0.1])
    # Subtract max(logits) first so exp() never overflows on large scores
    shifted = logits - np.max(logits)
    probs = np.exp(shifted) / np.sum(np.exp(shifted))
    cross_entropy = -np.log(probs[0])     # 0.41703...
    
  5. Embeddings: representing items as coordinates of meaning

    An embedding is a fixed-length dense vector of real numbers (commonly 64 to 1,536 floats) representing a discrete item—a word, search query, product, user, or photo—such that geometric closeness in vector space reflects task-relevant similarity.

    Why not represent V = 50,000 catalog products with one-hot encoding (a length-50,000 vector of all 0s except a single 1 at the item's index)? Because every pair of distinct one-hot vectors has dot product 0 and Euclidean distance sqrt(2): "running shoes" is just as far from "trail sneakers" as it is from "dishwasher detergent", so the model cannot generalize across related items.

    One-hot vectors (V = 50,000, sparse, every pair orthogonal):
      running_shoes   = [1, 0, 0, ..., 0]
      trail_sneakers  = [0, 1, 0, ..., 0]   -> dot product = 0 (zero shared information)
      detergent       = [0, 0, 1, ..., 0]   -> dot product = 0
    
    Dense embeddings (d = 3 mini-example, learned table E of shape V x d):
      running_shoes   = [ 0.82,  0.51, -0.10]
      trail_sneakers  = [ 0.79,  0.48, -0.14]  -> point in nearly the same direction!
      detergent       = [-0.60,  0.12,  0.75]  -> points away
    

    Mechanically, an ID embedding layer is simply a trainable lookup matrix E of shape (V, d) (50,000 × 256 = 12.8M float parameters): looking up row i is mathematically identical to multiplying one-hot vector i by E, without doing 49,999 multiplications by zero.

    To compare two embeddings q and v, systems compute either their dot product q · v = sum(q_k * v_k) or their cosine similarity cos(q, v) = (q · v) / (||q|| * ||v||), which divides out vector lengths so only the angle between directions matters (+1 identical direction, 0 perpendicular, -1 opposite):

    Query q = [1, 0, 1]      -> ||q|| = sqrt(1^2 + 0^2 + 1^2) = sqrt(2) = 1.4142
    Item  A = [1, 1, 1]      -> ||A|| = sqrt(1^2 + 1^2 + 1^2) = sqrt(3) = 1.7321
    Item  B = [0, 1, 0]      -> ||B|| = sqrt(0^2 + 1^2 + 0^2) = 1.0000
    
    q · A = 1*1 + 0*1 + 1*1 = 2   =>  cos(q, A) = 2 / (1.4142 * 1.7321) = 0.8165  (strong match)
    q · B = 1*0 + 0*1 + 1*0 = 0   =>  cos(q, B) = 0 / (1.4142 * 1.0000) = 0.0000  (unrelated)
    

    Individual coordinates (dimension 17) rarely have a standalone human label; meaning lives in the relative distances and directions across all d numbers together.

  6. How embeddings are learned from training tasks

    Embeddings are never hand-crafted; they emerge automatically when backpropagation updates encoder weights or lookup rows to lower a training loss. Crucially, the training objective defines what "similar" means: training on co-clicks puts complementary items together, while training on text paraphrases puts synonyms together.

    Four common ways embeddings are learned:

    • Supervised end-to-end lookup tables: Assign each categorical ID (user, merchant, city) a row in E and train a neural network to predict clicks or fraud. Two cities with similar fraud patterns receive similar gradients and drift together.
    • Self-supervised text or vision encoders: Word2Vec predicts neighboring words; BERT and vision transformers train on masked or contrastive objectives, and a pooled hidden state becomes a general-purpose text or image embedding.
    • Matrix factorization: Factor an incomplete users × items interaction grid into U @ V^T so user_vec · item_vec approximates ratings or watch time.
    • Two-tower (dual-encoder) contrastive training: One neural network ("query/user tower") maps the query to vector u, and a second network ("item tower") maps each item to vector v. Using in-batch negatives (treating the other B - 1 positive items inside the mini-batch as negative candidates), InfoNCE loss divides cosine similarities by a temperature tau (a small scaling constant like 0.1 that sharpens score gaps) and applies cross-entropy:
    Suppose temperature tau = 0.1, true match is index 0:
    
    Case 1 — Easy random negatives: similarities = [0.90, 0.20, -0.10]
      Logits (sim / tau) = [9.0, 2.0, -1.0]
      Softmax probs      = [0.9990, 0.0009, 0.00005]
      Loss = -ln(0.9990) = 0.0010   -> model already wins easily; gradient is nearly 0!
    
    Case 2 — Hard negatives (plausible near-misses): similarities = [0.50, 0.45, 0.40]
      Logits (sim / tau) = [5.0, 4.5, 4.0]
      Softmax probs      = [0.5065, 0.3072, 0.1863]
      Loss = -ln(0.5065) = 0.6803   -> large gradient teaches fine-grained distinctions!
    

    That contrast explains why production search teams mine hard negatives (items that look superficially similar to the query but were skipped): easy random negatives stop teaching the towers very early in training.

  7. Using embeddings at inference time

    At serving time, embeddings turn "find the best items among millions" into fast geometry:

    OFFLINE (batch job):
      10M catalog items --> [Item Encoder v3] --> L2-normalize --> [ANN Vector Index v3]
    
    ONLINE (per user request, < 15 ms):
      User query text   --> [Query Encoder v3] -> L2-normalize -> q
                         --> ANN search over Index v3 (top 200) --> Heavy Re-ranker --> Top 10 UI
    

    Key operational rules at inference time:

    • Table lookup vs. content encoder: For known entity IDs, serving is an O(1) array row read, but brand-new users or items have no row (cold start). Content encoders run a neural forward pass on title, description, or image pixels, giving new items a valid embedding on minute one.
    • Approximate Nearest Neighbor (ANN) indexing: Scanning 10,000,000 vectors of dimension 256 takes 2.56 billion multiply-adds per query. Production systems store precomputed item vectors in an ANN index—a data structure such as HNSW (Hierarchical Navigable Small World, a multi-layer proximity graph) or IVF-PQ (inverted-file buckets with compressed vectors)—to retrieve 95–99% of the true top-k neighbors while touching less than 1% of the catalog.
    • Version lockstep: Retraining a model from scratch can rotate or permute its vector space arbitrarily. Query embeddings from Model v4 are meaningless against an item index built by Model v3, so item indexes must be rebuilt and swapped atomically alongside the query encoder.
    import numpy as np
    
    
    def top_k_by_cosine(query: np.ndarray, items: np.ndarray, k: int) -> list[int]:
        """Return row indices of the k items with highest cosine similarity to query."""
        # Normalize query and item rows to unit length so dot product equals cosine similarity
        query_unit = query / np.linalg.norm(query)
        items_unit = items / np.linalg.norm(items, axis=1, keepdims=True)
        scores = items_unit @ query_unit
        return np.argsort(-scores)[:k].tolist()
    
    
    catalog = np.array([[1.0, 1.0, 1.0], [0.0, 1.0, 0.0], [2.0, 0.0, 1.9]])
    # cosines with [1, 0, 1]: item 0 -> 0.8165, item 1 -> 0.0, item 2 -> 0.9997
    print(top_k_by_cosine(np.array([1.0, 0.0, 1.0]), catalog, k=2))  # [2, 0]
    
  8. Real-world use cases in search and personalization

    Embeddings power the retrieval and personalization layer across modern consumer and enterprise products:

    • Semantic and hybrid search: A query for "cheap flights to Rome" retrieves "budget airfare to Italy" even with zero overlapping keywords. Production search usually blends dense embedding scores with BM25 (classic exact-keyword term-frequency scoring) so rare part numbers and proper nouns still match accurately.
    • Two-stage recommendation funnel: A two-tower model narrows 50 million videos or products down to 500 candidates in milliseconds via ANN search; a heavier cross-feature ranking model then scores only those 500 items with rich real-time context (time of day, cart total, device).
    • Real-time user personalization: Averaging (or recency-weighting) the embeddings of the last 20 items a user clicked gives an instant user interest vector without retraining any model weights.
    • Entity resolution and historical record linkage: Fuzzy duplicates with spelling drift, nicknames, or OCR noise—such as "Jon Smith, b. 1850, York" and "John Smyth, born 1850, Yorkshire"—land in the same neighborhood of embedding space, turning an impossible O(N^2) all-pairs comparison into a fast k-nearest-neighbor blocking step before running a precision matcher.
    • Cold-start recommendations and "more like this": Newly uploaded listings or articles immediately appear as neighbors of existing items via their text/image embeddings before accumulating a single click.
    • Cross-modal search and RAG: Multimodal encoders (CLIP-style) map text queries and photos into one shared space, while RAG (Retrieval-Augmented Generation) embeds document chunks, retrieves the top passages matching a user's question, and feeds them into an LLM prompt for grounded answers.

Intuition & how it works

Think of machine learning as training an apprentice librarian to organize and retrieve millions of items. Learning paradigms describe where the practice answer key comes from: in supervised learning, a teacher hands over explicit (question, answer) flashcards; in unsupervised learning, there is no teacher and the apprentice groups books purely by shared patterns; in self-supervised learning, the apprentice covers up one word on every page and practices guessing the hidden word from surrounding context. The loss function acts as a smooth "warmer or colder" dial that converts each guess into a single penalty score with a gradient (a directional slope telling each model weight whether to move up or down), and embeddings are the learned map coordinates on the library floor where items useful for the same task end up parked right next to each other.

Relying on naive choices breaks down at every layer of that pipeline. Requiring human annotators for every example is far too slow and expensive at web scale, while training directly on discrete business metrics like accuracy fails because tiny weight nudges do not flip right/wrong counts—leaving a flat surface with zero slope to guide updates. Likewise, representing 50,000 catalog items with one-hot vectors (sparse vectors of 49,999 zeros and a single 1) places "running shoes" and "trail sneakers" at right angles with zero overlap, forcing the model to relearn everything separately for each item ID.

Walk through how these pieces connect on a tiny three-item search system: 1. Self-supervised pretraining: A text encoder first trains on millions of raw sentences using masked-word prediction and cross-entropy loss (-ln(p_true), the negative log of the probability assigned to the true word), learning general language structure without human labels. 2. Supervised contrastive fine-tuning: Given logged search pairs like query q = "cheap Rome flight" -> clicked item A = "budget Italy airfare" alongside negative B = "toaster oven", a two-tower model (separate query and item encoders) computes cosine similarities [0.50, 0.45], scales them by temperature tau = 0.1 to [5.0, 4.5], and minimizes InfoNCE loss (-ln(0.6225) = 0.4741) so q and A move closer while B is pushed away. 3. Offline indexing: All catalog items are encoded once into normalized 256-float vectors and stored in an ANN index (Approximate Nearest Neighbor index, a graph or bucketed data structure that finds close vectors without scanning every row). 4. Online serving: When a user searches "affordable tickets to Milan", the query tower encodes the text in a few milliseconds and retrieves the closest item coordinates—surfacing relevant flights even when zero keywords match.

Key points

  • Supervised learning: Learns f(x) -> y from labeled pairs for classification (categories), regression (numbers), or ranking; watch out for selection bias (skew caused when logged clicks only exist for items the old ranker chose to display).
  • Unsupervised learning: Takes unlabeled inputs x to perform clustering (k-means, DBSCAN), dimensionality reduction (PCA, which projects data onto axes of maximal variance), and anomaly detection; evaluated via silhouette score (cluster tightness vs. separation) or downstream task lift.
  • Self-supervised learning: Generates supervisory targets directly from raw data (next-token prediction, masked tokens/patches, augmented image views) and trains with standard supervised losses—forming the foundation of modern pretrain-then-fine-tune workflows.
  • Loss vs. evaluation metric: Evaluation metrics (accuracy, recall@k, revenue) measure business success; the loss function is a smooth surrogate (a differentiable stand-in) whose gradient guides weight updates, often paired with regularization (a weight penalty such as lambda * ||w||^2 that curbs overfitting).
  • Loss geometry shapes predictions: MSE (Mean Squared Error) penalizes large errors quadratically and pulls predictions toward the conditional mean; MAE (Mean Absolute Error) penalizes linearly and pulls toward the median; log loss / cross-entropy heavily punishes confident wrong probabilities (4.605 at p = 0.01 vs. 0.105 at p = 0.90).
  • Embeddings encode task-specific similarity: An embedding is a compact float vector learned via lookup tables, self-supervised encoders, matrix factorization, or two-tower models, where hard negatives (plausible near-misses) supply most of the informative gradient.
  • Serving discipline: Use content encoders to solve cold start (scoring brand-new items with zero interaction history), serve large catalogs through ANN indexes (such as HNSW graphs or product quantization), and rebuild the item index whenever you deploy a newly retrained encoder version.

Common mistakes

  • Claiming self-supervised learning has no targets or loss: It uses explicit targets and supervised-style losses (cross-entropy or InfoNCE); the difference is simply that targets are extracted automatically from raw inputs rather than labeled by humans.
  • Confusing the training loss with the reporting metric: Trying to run gradient descent directly on accuracy or top-k recall fails because step functions have zero derivative almost everywhere.
  • Using MSE on classification probabilities: Squared error on [0, 1] probabilities is bounded by 1.0 and flattens out when sigmoid saturates, whereas log loss grows unboundedly (-ln(0.01) = 4.605) and produces clean linear gradients (p - y).
  • Saying individual embedding dimensions are human-interpretable features: Unless explicitly constrained during training, single axes do not mean "price" or "genre"; only relative distances and angles across the full vector carry meaning.
  • Mixing embeddings from two model runs in one vector index: Independent training runs rotate the coordinate space arbitrarily, so querying a v1 item index with a v2 query encoder returns garbage neighbors.
  • Using an unnormalized dot-product index for cosine-trained vectors: Cosine similarity divides out vector length while dot product scales with length; always L2-normalize vectors at index and query time if the model was trained with cosine similarity.

Follow-up questions

  • How do you evaluate embedding quality both offline before launch and online afterward? Offline, hold out ground-truth pairs (such as query -> purchased item or confirmed duplicate records) and compute retrieval metrics like recall@k (the fraction of queries whose true match appears in the top k retrieved neighbors) and MRR (Mean Reciprocal Rank, the average of 1 / rank of the first relevant hit). Pair that with downstream model lift—measuring NDCG (Normalized Discounted Cumulative Gain, a ranking score that rewards placing highly relevant items near rank 1) when embeddings are fed into the ranker—plus manual inspection of nearest neighbors on tail queries to catch obvious failure modes. Finally, validate with an online A/B test on live user engagement, since offline historical logs always favor behaviors similar to the previous production ranker.

  • When should a retrieval system score candidates with cosine similarity instead of a raw dot product? Cosine similarity measures only the angle between two vectors ((q · v) / (||q|| * ||v||)), whereas dot product (q · v) multiplies that cosine by both vector lengths. For query q = [1, 0] against specific niche item A = [0.9, 0.1] and broadly popular item B = [3.0, 3.0], cosine prefers A (0.994 vs. 0.707) while dot product prefers B (3.0 vs. 0.9) because B's larger norm encodes global popularity or confidence. Always match serving to your training objective—and if you trained with cosine, L2-normalize every vector once (v / ||v||) so fast inner-product ANN kernels compute exact cosine rankings.

  • How do you choose the embedding dimensionality for a production catalog? Treat dimensionality d as an empirical trade-off between expressiveness, overfitting, memory, and latency by sweeping powers of two (such as 64, 128, 256, 512) and plotting recall@k against serving cost. Memory scales linearly with d: 10 million items at d = 256 in float32 (4 bytes) consume 10.24 GB of RAM before graph overhead, whereas d = 64 takes 2.56 GB. Too few dimensions force unrelated concepts to collide, while too many dimensions let rare IDs memorize noise and slow down distance calculations; techniques like Matryoshka representation learning (training nested prefixes d = 64, 128, 256 simultaneously) or float16 / int8 quantization (storing numbers with fewer bits) preserve most recall at a fraction of the memory footprint.

Follow-up questions

Similar questions

More Ancestry interview questions

All 1 Ancestry questions →