forked from uma-pi1/kge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcomplex.py
62 lines (49 loc) · 2.19 KB
/
complex.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import torch
from kge import Config, Dataset
from kge.model.kge_model import RelationalScorer, KgeModel
class ComplExScorer(RelationalScorer):
r"""Implementation of the ComplEx KGE scorer.
Reference: Théo Trouillon, Johannes Welbl, Sebastian Riedel, Éric Gaussier and
Guillaume Bouchard: Complex Embeddings for Simple Link Prediction. ICML 2016.
`<http://proceedings.mlr.press/v48/trouillon16.pdf>`_
"""
def __init__(self, config: Config, dataset: Dataset, configuration_key=None):
super().__init__(config, dataset, configuration_key)
def score_emb(self, s_emb, p_emb, o_emb, combine: str):
n = p_emb.size(0)
# Here we use a fast implementation of computing the ComplEx scores using
# Hadamard products, as in Eq. (11) of paper.
#
# Split the relation and object embeddings into real part (first half) and
# imaginary part (second half).
p_emb_re, p_emb_im = (t.contiguous() for t in p_emb.chunk(2, dim=1))
o_emb_re, o_emb_im = (t.contiguous() for t in o_emb.chunk(2, dim=1))
# combine them again to create a column block for each required combination
s_all = torch.cat((s_emb, s_emb), dim=1) # re, im, re, im
r_all = torch.cat((p_emb_re, p_emb, -p_emb_im), dim=1) # re, re, im, -im
o_all = torch.cat((o_emb, o_emb_im, o_emb_re), dim=1) # re, im, im, re
if combine == "spo":
out = (s_all * o_all * r_all).sum(dim=1)
elif combine == "sp_":
out = (s_all * r_all).mm(o_all.transpose(0, 1))
elif combine == "_po":
out = (r_all * o_all).mm(s_all.transpose(0, 1))
else:
return super().score_emb(s_emb, p_emb, o_emb, combine)
return out.view(n, -1)
class ComplEx(KgeModel):
r"""Implementation of the ComplEx KGE model."""
def __init__(
self,
config: Config,
dataset: Dataset,
configuration_key=None,
init_for_load_only=False,
):
super().__init__(
config=config,
dataset=dataset,
scorer=ComplExScorer,
configuration_key=configuration_key,
init_for_load_only=init_for_load_only,
)