知识图谱嵌入:评分能分清方向吗?
Knowledge graph embeddings
在方向性反例上训练DistMult与ComplEx,并核对梯度。
knowledge-graph-embeddings不是每种评分规则都能靠加维度修好
假设关系表示“早于”。A早于B时,反过来的陈述不应获得同样的正面判断。如果一种模型交换端点后分数始终不变,那么即使嵌入维度很多,也无法表达这个区别。
知识图谱嵌入给实体分配向量,给关系分配参数,再为三元组评分。评分算子决定哪些模式容易表达、哪些根本表达不了。Yang等研究了通常称为DistMult的对角双线性模型;Trouillon等则在ComplEx中使用复数嵌入和共轭。对角模型,PDF第4页 式9—11,PDF第4页
下面推导两种评分,在原创方向反例上实际训练,再检查结果。这是在比较一种具体的表达限制,不是在宣布某个模型对所有知识图谱都更好。
对角乘积具有对称性
DistMult使用实数k维实体向量和对角关系算子。把对角元素写成r,评分为:
非对角元素全为零,矩阵式便化为逐分量乘积,关系参数从k²降到k。头尾共享实体向量时,实数乘法可交换:
任何训练日程或更大的k都不能消除这个恒等式。这不表示DistMult处处失效:对称关系符合这种偏置,特定评测也未必要求交换端点后给出相反分数。候选限制还可能掩盖这个限制。Yang等描述了这种对角算子。PDF第4页
ComplEx改变表示,并对尾实体取共轭,得到实数评分:
为了不依赖特殊的复数求导,把头写成a+ib、尾写成c+id、关系写成u+iv,六个分量向量都为实数。展开乘积得到:
u部分在交换端点后不变,v部分则变号。纯实关系产生对称评分,纯虚关系产生反对称评分。这里说的是分数矩阵的反对称性,不表示所有逻辑性质都会自动成立。PDF第4页例如头为1、尾为i、关系为i时,实评分为1;交换端点后变为−1。
训练数据给三个实体之间的全部六个有序配对标注标签:顺序方向为y=+1,反向为y=−1。对实参数分量Θ,最小化正则化逻辑损失:
这是明确标签、全批次的原创教学目标,不是Yang的间隔训练协议,也没有复现两篇论文的基准。这里的负标签是自建的相反方向,不是从现实知识库抽出的未知边。
单个样本的损失对分数的导数,以及ComplEx分数对头实体实虚分量的导数为:
应用链式法则,为每个实参数加上λ倍参数值;同一实体重复出现时,要累加两个端点的贡献。尾实体和关系的导数也可以从那四项实乘积推出。代码实现了全部导数,有限差分逐分量检查,还覆盖了自环。另一项测试用原生复数乘法和共轭独立计算分数。
对称评分器必须给一对相反标签同一个分数s。这对标签的平均数据损失存在下界:
s=0时取等号。证明可以把两个对数的参数相乘:(1+e⁻ˢ)(1+eˢ)=2+eˢ+e⁻ˢ≥4。因此DistMult无法把这组方向数据的平均数据损失降到ln2以下。这个结论来自结构,与随机种子和维度无关。
让两个模型面对同一个矛盾
使用Python3.12、NumPy1.26.4,固定种子43、维度2、学习率0.4和1200步。DistMult有8个实参数,ComplEx保存实部和虚部,共16个。本比较没有匹配参数总数,但DistMult的数学对称障碍在任何维度都成立。
"""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最终数据损失为ln2≈0.69314718056,带正则项的损失略高。分数趋近零,交换端点后的差异仅在浮点误差范围内。严格符号准确率0.5来自极小的非零数值,不应解读为置信程度。
ComplEx最终数据损失约0.00861696885,带正则项的损失0.0697456491,训练符号准确率1;正反向分数约为±4.74971。这六个标签都用于训练,例子没有留出边,不能证明泛化表现。
设n个实体、r种关系、维度k,DistMult存储(n+r)k个实数,ComplEx是它的两倍。两者为一个三元组评分都需O(k)时间。含正则化的M三元组向量化全批更新耗时O(Mk+(n+r)k),本实现工作数组占O(Mk)。稳定的logaddexp计算避免直接对很大的正逻辑损失参数取指数。
能表达,只是学习问题的一部分
某个算子能表达一种模式,不表示它能从有限数据中找到这种模式。维度、正则化、初始化、负例构造和评估划分仍有影响。纯虚关系权重允许反对称评分,却不强制传递性;无约束的关系向量也不能证明本体一致。
其他家族有不同选择:TransE用平移距离,完整双线性模型使用关系矩阵,非线性或基于图的编码器再加入其他结构。它们在参数、计算和归纳偏置之间取舍。比较时需要相同的补全协议,包括候选和过滤规则。
寻找代数上的障碍
- 增大DistMult维度能消除端点对称性吗?答案:不能。新增的每个实数分量仍是可交换乘积,它们求和后依然对称。
- 头为1、尾为i、关系为i,正反向ComplEx评分分别是多少?答案:正向Re(i×1×conj(i))=1,反向Re(i×i×conj(1))=−1。共轭使这种区别成为可能。
- 对称评分器给一对正负相反标签都打s=0,平均逻辑数据损失是多少?答案:ln2。s偏离零会帮助一个标签、伤害另一个,二者平均不能更小。
- ComplEx拟合了全部六个标签,就学会了一般的“早于”关系吗?答案:尚未证明。它拟合的是这份训练集。新实体、留出边以及传递性等性质,需要单独证据与合适的评估设计。
用方程选择下一项实验
原论文提供了对角和复数评分算子;本文标签、全批优化器、实数梯度代码和反例均为原创,没有复制上游实验代码。ComplEx论文还讨论了更广的表示理论,这个小实验不能证明那些结论。下一步可以同时加入对称关系和方向关系,在固定实体与评估协议的条件下留出部分边再测试。
先判断,再看解释
共享实体向量时,DistMult能给(a,r,b)和(b,r,a)不同评分吗?
学习目标
- 推导DistMult对称性及ComplEx实数展开,用相反标签检验后果。
- 证明对称评分的逻辑损失下界,用数值差分和复数运算核对实分量梯度。
先修与延伸
查看知识关联图 →参考文献
- 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
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(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.
- 核DistMult/ComplEx全部梯度、原生复数运算、端点对称/纯虚反对称、ln2下界、自环累加和稳定逻辑损失;六个原创方向标签、8/16实参数,无留出成绩或通用表达定理证明。
- 每题四张计算SVG,14数值/几何与36响应式组合通过;12张当前选定图实看,其中7张与此前所看字节相同、5张最终图重新实看,TransE箭头修订已保全,完整页面验收另记。
核对的来源位置:
- 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.
相关主题