Logo
Section 1 / 4

基于翻译的方法

了解基于翻译的知识图谱嵌入方法。

导入

基于翻译的方法

了解基于翻译的知识图谱嵌入方法。

...
TransE

如果考虑三元组 (h,r,t)(h,r,t),TransE 算法尝试为所有实体和关系找到嵌入表示,使得头实体向量与关系向量的组合结果近似于尾实体向量,即
h+r≈th + r ≈ t。

TransE 算法通过最小化预测向量与实际向量之间的差异来学习实体和关系的嵌入表示。为此,评分函数 (ff) 可以定义为 h+rh + r 与 tt 之间的距离(L1 或 L2 范数)。

fr(h,t)=−∣∣h+r−t∣∣f_r (h, t) = −||h + r − t||

fr(h,t)=−∣∣h⊥+r−t⊥∣∣f_r(h,t)=−||h_⊥ +r−t_⊥||

...
TransH with a hyperplane

实体 (hh 和 tt) 在空间 RdR^d 中被向量化,关系 (rr) 则位于特定于关系的空间 (RKR^K) 中。随后,实体被投影到关系空间中以计算评分函数。

...
TransR with separate spaces

hr=h∗Mrh_r = h * M_r tr=t∗Mrt_r = t * M_r fr(h,t)=∣∣hr+r−tr∣∣f_r(h, t) = ||h_r + r − t_r||

其中 hrh_r 和 trt_r 是投影后的实体,MrM_r 是关系 rr 的投影矩阵。此外,还开发了更多类似思想的翻译算法,如 TransD、TranSparse 和 TransM,它们在实现上略有不同。

1from pykeen.models import TransE 2from pykeen.triples import TriplesFactory 3from pykeen.pipeline import pipeline 4from pykeen.datasets import Nations 5import networkx as nx 6import pandas as pd 7import matplotlib.pyplot as plt 8 9df = pd.DataFrame(Nations().training.triples) 10df.columns = ['h', 'r', 't'] 11 12# create graph 13G = nx.from_pandas_edgelist(df, source='h', target='t', edge_attr='r') 14 15# Generate triples from the graph 16tf = TriplesFactory.from_labeled_triples(df.values) 17 18training, testing = tf.split([0.8, 0.2], random_state=42) 19result = pipeline( 20 training=training, 21 testing=testing, 22 model = "TransE", 23 model_kwargs=dict(embedding_dim=16), 24 optimizer = "adam", 25 training_kwargs=dict(num_epochs=10, use_tqdm_batch=False), 26 random_seed=42, 27 device='cpu', 28 negative_sampler = 'bernoulli', 29 negative_sampler_kwargs = dict(num_negs_per_pos = 3)) 30 31losses = result.losses 32plt.figure(figsize=(10, 5), dpi=300) 33plt.plot(losses) 34plt.xlabel("Epochs") 35plt.ylabel("Loss")

注意: Nations 数据集是一个小型知识图谱,描述不同国家及其政治关系。

1from pykeen.triples import TriplesFactory 2from pykeen.pipeline import pipeline 3from pykeen.datasets import Nations 4import networkx as nx 5import pandas as pd 6import matplotlib.pyplot as plt 7 8df = pd.DataFrame(Nations().training.triples) 9df.columns = ['h', 'r', 't'] 10 11# Generate triples from the graph 12tf = TriplesFactory.from_labeled_triples(df.values) 13 14training, testing = tf.split([0.8, 0.2], random_state=42) 15result = pipeline( 16 training=training, 17 testing=testing, 18 model = "TransR", 19 model_kwargs=dict(embedding_dim=16), 20 optimizer = "adam", 21 training_kwargs=dict(num_epochs=10, use_tqdm_batch=False), 22 random_seed=42, 23 device='cpu', 24 negative_sampler = 'bernoulli', 25 negative_sampler_kwargs = dict(num_negs_per_pos = 3)) 26 27losses = result.losses 28plt.figure(figsize=(10, 5), dpi=300) 29plt.plot(losses) 30plt.xlabel("Epochs") 31plt.ylabel("Loss")

图嵌入

基于分解的方法