Deep learning and neural networksLoading progress…

Embeddings

Compare learned embeddings, transfer learning, fine-tuning and contrastive training objectives.

Items as points in a space

An embedding turns an item (a word, an image, a user) into a vector of numbers. The numbers are learned so that items that behave alike end up close together. Similarity is usually measured by the cosine of the angle between two vectors: 1 for the same direction, 0 for unrelated, −1 for opposite. It ignores length.

nearest to
catdogcartruck
wordvectorcosine with cat
cat[1, 0.2]1
dog[0.9, 0.3]0.992
car[0, 1]0.196
truck[0.1, 0.9]0.303

Rotating all vectors changes every coordinate but no cosine. What an embedding means is in the relationships, not in "the first coordinate".

Four words in two dimensions. Pick a word to rank the others. Then rotate the whole space.

Predict first. Must the first coordinate always mean the same human concept across two separately trained models?

E = table[ids]                                   # an embedding layer is just row lookup
cos = (a @ b) / (np.linalg.norm(a) * np.linalg.norm(b))
Chapter context

A representation is useful when its structure supports a downstream task. Learning a representation changes which examples appear similar, but those similarities inherit assumptions from training data and objectives.

Chapter reference: math, worked example & code

This section belongs to the whole chapter, so it is the same on every lesson in it and may cover a different lesson's topic. The code for the experiment you just ran is inside the experiment itself.

Math and notation

One contrastive loss for an anchor a and positive p is

L=−log⁡exp⁡(s(a,p)/τ)∑j∈Cexp⁡(s(a,j)/τ).L=-\log\frac{\exp(s(a,p)/\tau)}{\sum_{j\in\mathcal C}\exp(s(a,j)/\tau)}.

The candidate set includes the designated positive; other candidate definitions depend on the method. Temperature tau is positive and controls concentration.

Worked example

For a candidate set with positive logit ln 2 and one alternative logit 0, exponentiated weights are 2 and 1. The positive probability is 2/3 and loss is −ln(2/3)≈0.405465. This demonstrates the normalization; actual contrastive batches usually contain many more candidates.

Reference code

The following example uses the Python standard library and does not call a remote service.

from math import log, exp, isclose
logits=[log(2),0]
prob=exp(logits[0])/sum(exp(v) for v in logits)
assert isclose(prob,2/3)
assert isclose(-log(prob),.40546510810816444)

Python examples are provided for study and local execution; this page does not execute Python.

Common mistakes

Embedding proximity is task-dependent. Frozen parameters can coexist with a trainable head. Parameter-efficient tuning still requires evaluation for forgetting and task failures.