TransE: train relations as translations
TransE
Optimize a margin loss, normalize entities and measure the geometric cost of two different tails.
transeMove the head toward the tail
Place entities as points in a vector space. For a relation such as hasCapital, assign an arrow. A useful arrow should move each country point toward its capital point. The arrow is shared across all triples with that relation, so the model cannot give each pair an unrelated answer.
TransE represents relations as translations and learns entity and relation vectors from positive triples and corrupted competitors. Its original formulation uses an L1 or L2 norm distance, a margin ranking loss and unit-norm entity embeddings. PDF 2–3 This article trains an L2-norm version on three authored pairs and then examines the geometric cost of making one head point to two distinct tails.
The loss compares two distances
Let E contain one k-dimensional vector per entity and R one per relation. For a triple (h,r,t), write its vectors as e_h, r and e_t. A lower energy means a better fit:
The norm is not squared in this implementation. A displacement (3,4) has energy 5, not 25. The same entity uses the same vector whether it appears as head or tail. A corrupted triple replaces one endpoint; our finite training pool excludes known training positives. Unknown true edges can still be competitors, as discussed in graph completion.
Let P contain positive–negative pairs, and let γ be a positive margin. Our full-pair objective averages hinge losses:
An active pair asks the positive distance to be smaller and the negative distance larger. Once the gap is at least γ, that pair contributes zero. A small positive energy alone is insufficient: a negative can be equally close. The paper uses the same margin principle with stochastic batches; our averaging and full finite pool are explicit teaching choices. Equation 1 and algorithm 1, PDF 3
Without constraints, scaling can enlarge an already favorable gap without improving its geometry. The original method normalizes entity vectors, while relation vectors are normalized initially but have no continuing unit-norm constraint:
For displacement Δ=e_h+r−e_t, the derivative of its Euclidean norm is its unit direction when nonzero. At zero the norm is nondifferentiable; the program selects the zero subgradient:
For one active pair, let u⁺ and u⁻ be these directions. Before averaging over P, the entity-gradient contribution for entity a and the relation-gradient contribution are:
An entity may occupy several roles in a pair; its contributions must add. Assigning into an array without accumulation would silently lose terms. Inactive pairs contribute zero, and the implementation chooses zero hinge subgradient at the margin boundary.
With learning rate η, take a gradient step and project each nonzero entity vector back to the unit sphere. Relations receive an ordinary unconstrained step:
The program rejects zero vectors during normalization. It projects after each step, so the returned model also satisfies the constraint. It runs a fixed number of steps; the original algorithm uses validation performance for stopping. Training-loss convergence alone does not choose a model for deployment.
The shared translation creates a specific one-to-many pressure. If the same head and relation should reach two tails t₁ and t₂, the triangle inequality gives:
If both errors are at most ε, the tails must lie within 2ε. Exact zero errors collapse the two tail vectors. This does not prove that every one-to-many dataset is impossible to rank correctly: finite error and other triples change the optimization. It identifies an inductive bias that alternative relation operators can change. ComplEx’s model comparison illustrates different scoring families. Table 1, PDF 3
Train the vectors and inspect the constraint
Use Python 3.12 with NumPy 1.26.4. The authored graph contains three disjoint positive pairs sharing one relation. Seed 41, dimension 8, margin 0.5, learning rate 0.2 and 600 steps are fixed so the result is reproducible. All head/tail corruptions outside the training positives are enumerated rather than sampled.
"""Original NumPy TransE experiment: L2 norm, full corruption pairs, projection.
Not the paper's stochastic sampling/validation protocol. Training fit only.
"""
import json
import numpy as np
def energy(E, R, triples):
q = np.asarray(triples, dtype=int)
if q.ndim != 2 or q.shape[1] != 3 or len(q) == 0:
raise ValueError("Nonempty triples required")
if (q < 0).any() or (q[:, [0, 2]] >= len(E)).any() or (q[:, 1] >= len(R)).any():
raise ValueError("Triple index out of range")
return np.linalg.norm(E[q[:, 0]]+R[q[:, 1]]-E[q[:, 2]], axis=1)
def pairs_for(train, n):
known = set(map(tuple, train))
pairs = []
for h, r, t in sorted(known):
negatives = ({(e, r, t) for e in range(n)} | {(h, r, e) for e in range(n)}) - known
pairs.extend([((h, r, t), neg) for neg in sorted(negatives)])
if not pairs:
raise ValueError("No corruption pairs")
return np.asarray(pairs, dtype=int)
def loss_grad(E, R, pairs, margin=0.5):
if not np.isfinite(margin) or margin <= 0 or len(pairs) == 0:
raise ValueError("Positive margin and nonempty pairs required")
positive, negative = pairs[:, 0], pairs[:, 1]
dp, dn = energy(E, R, positive), energy(E, R, negative)
z = margin + dp-dn
active = z > 0
dE, dR = np.zeros_like(E), np.zeros_like(R)
for sign, q, distances in [(1, positive, dp), (-1, negative, dn)]:
delta = E[q[:, 0]]+R[q[:, 1]]-E[q[:, 2]]
unit = np.divide(delta, distances[:, None], out=np.zeros_like(delta), where=distances[:, None] > 0)
g = sign*unit*active[:, None]/len(pairs)
np.add.at(dE, q[:, 0], g)
np.add.at(dR, q[:, 1], g)
np.add.at(dE, q[:, 2], -g)
return float(np.maximum(z, 0).mean()), dE, dR
def normalize(E):
lengths = np.linalg.norm(E, axis=1)
if np.any(lengths == 0) or not np.isfinite(E).all():
raise ValueError("Cannot normalize zero or nonfinite vectors")
return E/lengths[:, None]
def train_model(seed=41, steps=600, dimension=8, rate=0.2):
if steps < 0 or dimension < 1 or not np.isfinite(rate) or rate <= 0:
raise ValueError("Invalid training parameters")
train = [(0, 0, 1), (2, 0, 3), (4, 0, 5)]
rng = np.random.default_rng(seed)
width = 6/np.sqrt(dimension)
E = normalize(rng.uniform(-width, width, (6, dimension)))
R = normalize(rng.uniform(-width, width, (1, dimension)))
pairs = pairs_for(train, len(E))
initial = loss_grad(E, R, pairs)[0]
for _ in range(steps):
_, dE, dR = loss_grad(E, R, pairs)
E = normalize(E-rate*dE)
R = R-rate*dR
return E, R, train, pairs, initial
def demo():
E, R, train, pairs, initial = train_model()
ranks = []
for h, r, t in train:
values = energy(E, R, [(h, r, e) for e in range(len(E))])
ranks.append(int(1+np.sum(values < values[t])))
midpoint = np.array([1., 0.]); left = np.array([1., 1.]); right = np.array([1., -1.])
return dict(initial_loss=initial, final_loss=loss_grad(E, R, pairs)[0],
corruption_pairs=len(pairs), training_tail_ranks=ranks,
entity_norms=np.linalg.norm(E, axis=1).tolist(), relation_norm=float(np.linalg.norm(R)),
two_tail_gap=float(np.linalg.norm(left-right)),
sum_translation_errors=float(np.linalg.norm(midpoint-left)+np.linalg.norm(midpoint-right)))
if __name__ == "__main__":
print(json.dumps(demo(), indent=2))
There are 30 positive–negative pairs. Mean training loss falls from 0.5978610453 to 0, and all three training tail targets have rank 1. Entity norms are 1; the relation norm is about 1.069982. These are fitting and constraint checks, not held-out prediction results. The separate two-tail construction has tail separation 2 and total translation error 2, attaining the triangle bound; it is a geometric illustration, not the normalized training data.
For n entities, r relation types, dimension k and P stored pairs, parameters require O((n+r)k) space. A full gradient step costs O(Pk+nk), including projection, with vectorized working arrays O(Pk). Enumerating corruptions can store O(mn) pairs for m positive triples. This exhaustive strategy is suitable for the tiny example; sampled competitors reduce its cost at scale. The tests compare every parameter gradient with finite differences away from nondifferentiable points and separately check zero-distance behavior.
A good translation is still a restricted model
Unknown entities lack learned vectors. Relation meaning can vary by context, and one shared arrow may be too restrictive. Negative choices, entity normalization, loss scale and evaluation filtering all affect results. A zero training hinge loss is neither a probability estimate nor proof that all missing edges are correct.
Do not compare this three-pair example with WordNet or Freebase scores from the paper. A meaningful extension holds out edges, keeps a fixed candidate roster, tunes on validation data and evaluates with the declared protocol. A different scoring family may address a structural limitation, but only evidence on the intended task establishes whether it helps.
Predict the gradient and the geometry
- Does TransE prefer a larger or smaller distance for a plausible triple? Answer: Smaller. Its energy is the distance between the translated head and the tail; an implementation using scores can negate this energy.
- With γ=0.5, positive distance 0.2 and negative distance 0.4, what is the pair loss? Answer: max(0,0.5+0.2−0.4)=0.3. Merely placing the positive slightly closer has not met the margin.
- Both translations have error at most 0.1. Can the two tail vectors be distance 1 apart? Answer: No. The triangle bound limits their separation to 0.2. This is a bound on the vectors, not a declaration that the real entities are identical.
- Training loss is zero. What is missing before claiming useful completion? Answer: Held-out evaluation, a stated candidate and filtering protocol, validation-based choices and checks for shortcuts or leakage. Training fit alone establishes none of those.
Change the operator, then inspect what changes
TransE’s paper supplies the translation model, norm constraint and ranking objective. The code here is original, uses an exhaustive finite corruption pool and does not reproduce the paper’s optimization schedule or benchmark. The next embedding comparison uses DistMult and ComplEx to test a different restriction: whether exchanging head and tail must preserve the score.
Make a prediction, then check
Can the same vector h+r equal two distinct tail vectors exactly?
Learning objectives
- Derive the norm-distance gradient and one-to-many limitation; distinguish training fit from prediction evidence.
- Run norm-distance margin training, accumulate repeated entity roles and check the entity constraint after updates.
Prerequisites & connections
Explore related knowledge →References
- Translating Embeddings for Modeling Multi-relational Data
Antoine Bordes; Nicolas Usunier; Alberto Garcia-Durán; Jason Weston; Oksana Yakhnenko · 2013 - Complex Embeddings for Simple Link Prediction
Théo Trouillon; Johannes Welbl; Sebastian Riedel; Éric Gaussier; Guillaume Bouchard · 2016
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-23 · Single AI author. Scoped reading: Read PDF1 identity and PDF2–3/5 text; viewed PDF3. Translation, L1/L2 norm, margin loss, head-or-tail corruption, unit entity constraint and raw/filtered evaluation. Original full-pair deterministic program differs from paper sampling/validation; no benchmark reproduction. Read PDF1 identity and PDF3–4 text; viewed PDF4. Complex conjugation, real score expansion (9–11), symmetric/antisymmetric components and model comparison table. No proof audit of universality, original benchmark reproduction or source-code reuse. 7 paired equations and four explained exercises. Checked all parameter gradients by finite differences, L2 norm rather than squared distance, shared-role accumulation, unit entity projection and the two-tail triangle bound. Full corruption-pair training with fixed steps; reported fit is training-only.
- Checked all parameter gradients by finite differences, L2 norm rather than squared distance, shared-role accumulation, unit entity projection and the two-tail triangle bound. Full corruption-pair training with fixed steps; reported fit is training-only.
- Four computed SVG variants per topic;14 numeric/geometry tests and36 responsive cases passed. Twelve selected current captures visually checked: seven identical to previously viewed images and five re-viewed final captures; TransE arrow revision retained. Full article acceptance recorded separately.
Source locations checked:
- Translating Embeddings for Modeling Multi-relational Data · Read PDF1 identity and PDF2–3/5 text; viewed PDF3. Translation, L1/L2 norm, margin loss, head-or-tail corruption, unit entity constraint and raw/filtered evaluation. Original full-pair deterministic program differs from paper sampling/validation; no benchmark reproduction.
- Complex Embeddings for Simple Link Prediction · Read PDF1 identity and PDF3–4 text; viewed PDF4. Complex conjugation, real score expansion (9–11), symmetric/antisymmetric components and model comparison table. No proof audit of universality, original benchmark reproduction or source-code reuse.
Related topics