Knowledge graph embeddings: can a score tell direction?
知识图谱嵌入
Train DistMult and ComplEx on a directional counterexample and check their gradients.
knowledge-graph-embeddingsMore dimensions cannot fix every scoring rule
Suppose a relation means “earlier than.” If A is earlier than B, the reverse statement should not receive the same positive judgment. A model whose score is unchanged when its endpoints are swapped cannot represent that distinction, even with many embedding dimensions.
Knowledge graph embeddings assign vectors to entities and parameters to relations, then score triples. The scoring operator determines which patterns are easy or impossible to represent. Yang and colleagues examine a diagonal bilinear model, commonly called DistMult; Trouillon and colleagues use complex-valued embeddings and conjugation in ComplEx. Diagonal model, PDF 4 Equations 9–11, PDF 4
We derive their scores, train both on an authored directional counterexample and inspect the result. This is a comparison of a specific expressivity restriction, not a claim that one model wins on every knowledge graph.
A diagonal product is symmetric
DistMult uses a real k-dimensional entity vector and a diagonal relation operator. Writing its diagonal as r gives:
The matrix notation becomes a componentwise product because all off-diagonal entries are zero. This reduces relation parameters from k² to k. With shared entity vectors for head and tail, real multiplication commutes:
No training schedule or larger k removes this identity. It does not mean every use of DistMult fails: symmetric relations fit this bias, and a particular evaluation may not demand opposing scores for swapped endpoints. Different candidate restrictions can also hide the restriction. The diagonal operator itself is described by Yang and colleagues. PDF 4
ComplEx changes the representation and conjugates the tail. Its real-valued score is:
To compute this without special complex differentiation, write head=a+ib, tail=c+id and relation=u+iv, with all six component vectors real. Expanding the product gives:
The u part is symmetric under endpoint exchange. The v part changes sign. A purely real relation produces a symmetric score; a purely imaginary relation produces an antisymmetric score. This is score-matrix antisymmetry, not a claim that every logical property follows automatically. PDF 4 For example, head 1, tail i and relation i give real score 1; swapping the endpoints gives−1.
For training, our authored dataset labels all six ordered pairs among three entities. Forward order has y=+1 and reverse order y=−1. We minimize regularized logistic loss over the real parameter components Θ:
This is our explicitly labeled, full-batch teaching objective. It is not Yang’s margin-training protocol or a reproduction of either paper’s benchmark. Negative labels here are authored opposite directions, not unknown edges sampled from a real knowledge base.
For one example, the loss derivative with respect to its score and the head-component derivatives of the ComplEx score are:
Apply the chain rule, add λ times each real parameter, and accumulate both endpoint contributions when an entity repeats. Tail and relation derivatives follow from the same four real products. The code implements all of them; finite differences check every component, including a self-loop. A separate test evaluates the score with native complex multiplication and conjugation.
For a symmetric scorer, each opposing pair must share a score s. Its average data loss has a lower bound:
with equality at s=0. One proof multiplies the log arguments: (1+e⁻ˢ)(1+eˢ)=2+eˢ+e⁻ˢ≥4. Thus DistMult cannot drive this directional dataset’s average data loss below ln 2. The argument is structural, independent of random seed and dimension.
Train both models on the same contradiction
Use Python 3.12 and NumPy 1.26.4. Seed 43, dimension 2, learning rate 0.4 and 1200 steps are fixed. DistMult has 8 real parameters; ComplEx has 16 because it stores real and imaginary parts. The comparison is not parameter-count matched. The mathematical symmetry obstruction nevertheless applies to DistMult at any dimension.
"""Train DistMult and ComplEx scorers on opposite directed labels.
Full-batch regularized logistic teaching experiment, not either paper benchmark.
"""
import json
import numpy as np
def scores(E, R, triples, complex_model):
q = np.asarray(triples, dtype=int)
h, t = E[q[:, 0]], E[q[:, 2]]
r = R[q[:, 1]]
if not complex_model:
return np.sum(h*r*t, axis=1)
a, b = h[:, 0], h[:, 1]
c, d = t[:, 0], t[:, 1]
e, f = r[:, 0], r[:, 1]
return np.sum(e*(a*c+b*d)+f*(a*d-b*c), axis=1)
def loss_grad(E, R, triples, labels, complex_model, ridge=0.01):
q, y = np.asarray(triples, dtype=int), np.asarray(labels, dtype=float)
if q.ndim != 2 or q.shape[1] != 3 or y.shape != (len(q),) or not len(q) or not np.isin(y, [-1, 1]).all():
raise ValueError("Nonempty triples with signed labels required")
if not np.isfinite(ridge) or ridge < 0 or not np.isfinite(E).all() or not np.isfinite(R).all():
raise ValueError("Finite parameters and nonnegative ridge 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")
s = scores(E, R, q, complex_model)
coefficient = -y*np.exp(-np.logaddexp(0, y*s))/len(y)
dE, dR = ridge*E, ridge*R
h, t, r = E[q[:, 0]], E[q[:, 2]], R[q[:, 1]]
if complex_model:
a, b = h[:, 0], h[:, 1]; c, d = t[:, 0], t[:, 1]; e, f = r[:, 0], r[:, 1]
gh = np.stack([e*c+f*d, e*d-f*c], axis=1)
gt = np.stack([e*a-f*b, e*b+f*a], axis=1)
gr = np.stack([a*c+b*d, a*d-b*c], axis=1)
coefficient = coefficient[:, None, None]
else:
gh, gt, gr = r*t, r*h, h*t
coefficient = coefficient[:, None]
np.add.at(dE, q[:, 0], coefficient*gh)
np.add.at(dE, q[:, 2], coefficient*gt)
np.add.at(dR, q[:, 1], coefficient*gr)
loss = np.logaddexp(0, -y*s).mean()+ridge/2*(np.sum(E*E)+np.sum(R*R))
return float(loss), dE, dR
def train_model(complex_model, seed=43, steps=1200, dimension=2):
if steps < 0 or dimension < 1:
raise ValueError("Invalid training parameters")
triples = [(h, 0, t) for h in range(3) for t in range(3) if h != t]
labels = np.array([1. if h < t else -1. for h, _, t in triples])
rng = np.random.default_rng(seed)
suffix = (2, dimension) if complex_model else (dimension,)
E, R = rng.normal(0, .3, (3, *suffix)), rng.normal(0, .3, (1, *suffix))
initial = loss_grad(E, R, triples, labels, complex_model)[0]
for _ in range(steps):
_, dE, dR = loss_grad(E, R, triples, labels, complex_model)
E -= .4*dE; R -= .4*dR
return E, R, triples, labels, initial
def demo():
output = {}
for complex_model in [False, True]:
E, R, q, y, initial = train_model(complex_model)
values = scores(E, R, q, complex_model)
reverse = scores(E, R, [(t, r, h) for h, r, t in q], complex_model)
output["complex" if complex_model else "distmult"] = dict(
parameters=E.size+R.size, initial_loss=initial,
final_loss=loss_grad(E, R, q, y, complex_model)[0],
data_loss=float(np.logaddexp(0, -y*values).mean()),
signed_accuracy=float(np.mean(y*values > 0)),
scores=values.tolist(), maximum_direction_gap=float(np.max(np.abs(values-reverse))))
return output
if __name__ == "__main__":
print(json.dumps(demo(), indent=2))
DistMult’s final data loss is ln 2≈0.69314718056, while its regularized loss is slightly higher. Its scores approach zero and swapped scores agree within floating-point error. The strict sign accuracy of 0.5 is based on tiny nonzero numerical scores and should not be interpreted as confidence.
ComplEx’s final data loss is about 0.00861696885, regularized loss 0.0697456491 and training sign accuracy 1. Its forward and reverse scores are approximately±4.74971. These six labels were used for training; the example has no held-out edges and establishes no generalization performance.
For n entities, r relations and dimension k, DistMult stores (n+r)k real values and ComplEx stores twice that. Both score one triple in O(k) time. A vectorized full-batch step over M triples costs O(Mk+(n+r)k), including regularization, with O(Mk) working arrays in this implementation. Stable logaddexp calculations avoid explicitly exponentiating a large positive logistic argument.
Expressivity is one part of learning
An operator may represent a pattern without finding it from limited data. Dimension, regularization, initialization, negative construction and evaluation splits remain consequential. Pure imaginary relation weights allow antisymmetric scores but do not impose transitivity. Nor do unconstrained relation vectors certify an ontology’s consistency.
Other families make different choices: TransE uses translation distance, full bilinear models use relation matrices, and nonlinear or graph-based encoders add further structure. These choices trade parameters, computation and inductive biases. Comparing them requires the same completion protocol, including candidate and filtering rules.
Look for an algebraic obstruction
- Does increasing DistMult’s dimension remove endpoint symmetry? Answer: No. Every added real component is another commutative product, so their sum remains symmetric.
- Take head 1, tail i and relation i. What are the forward and reverse ComplEx scores? Answer: Forward Re(i×1×conj(i))=1. Reverse Re(i×i×conj(1))=−1. Conjugation makes the distinction possible.
- A symmetric scorer assigns s=0 to an opposing positive/negative pair. What is its mean logistic data loss? Answer: ln 2. Moving s away from zero helps one label while hurting the other; their mean cannot be smaller.
- ComplEx fits all six labels. Has it learned a general “earlier than” relation? Answer: That has not been established. It fits this training set. New entities, held-out edges and properties such as transitivity require separate evidence and an appropriate evaluation design.
Use an equation to choose the next experiment
The original papers supply the diagonal and complex scoring operators. This article’s labels, full-batch optimizer, real-gradient code and counterexample are original; upstream experiment code is not copied. The ComplEx paper discusses a much broader representation theory, which this small experiment does not prove. An informative next experiment adds symmetric and directional relations together, then holds out edges while keeping their identities and evaluation protocol fixed.
Make a prediction, then check
With shared entity vectors, can DistMult assign different scores to (a,r,b) and (b,r,a)?
Learning objectives
- Derive DistMult symmetry and the real expansion of ComplEx, then test the consequence on opposite labels.
- Prove the symmetric logistic-loss lower bound and check real-component gradients against numerical and complex arithmetic.
Prerequisites & connections
Explore related knowledge →References
- Embedding Entities and Relations for Learning and Inference in Knowledge Bases — arXiv v4
Bishan Yang; Wen-tau Yih; Xiaodong He; Jianfeng Gao; Li Deng · 2015 - 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/version date and PDF3–4 text; viewed PDF4. Bilinear/diagonal scoring and margin training. Tutorial instead uses explicit labeled logistic training for a symmetry counterexample. No paper benchmark or rule-mining 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 DistMult/ComplEx gradients, native complex arithmetic, endpoint symmetry and imaginary antisymmetry, the ln2 lower bound, self-loop accumulation and stable logistic loss. Six authored directional labels,8/16 real parameters; no held-out or universal-expressivity proof.
- Checked all DistMult/ComplEx gradients, native complex arithmetic, endpoint symmetry and imaginary antisymmetry, the ln2 lower bound, self-loop accumulation and stable logistic loss. Six authored directional labels,8/16 real parameters; no held-out or universal-expressivity proof.
- 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:
- Embedding Entities and Relations for Learning and Inference in Knowledge Bases — arXiv v4 · Read PDF1 identity/version date and PDF3–4 text; viewed PDF4. Bilinear/diagonal scoring and margin training. Tutorial instead uses explicit labeled logistic training for a symmetry counterexample. No paper benchmark or rule-mining 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