DeepGraphLearning / KnowledgeGraphEmbedding

MIT License
1.24k stars 264 forks source link

How to use embedding to compute triplet score #17

Closed zhongpeixiang closed 4 years ago

zhongpeixiang commented 4 years ago

I don't quite understand your training script about head-batch. Anyway, I have pretrained ent and rel embeddings without understanding it.

Now I want to figure out that given a triplet: h [x1, ..., x200], r=[r1, ..., r100] and t=[y1, ..., y200], how to compute its score?

A detailed description will be much appreciated.

Edward-Sun commented 4 years ago

Hi, Peixiang,

For RotatE, you can first transform relation embedding into phases like:

https://github.com/DeepGraphLearning/KnowledgeGraphEmbedding/blob/2442e8b9bb1a40e44edabcb3cc4f145ac24b1c7b/codes/model.py#L208

where self.embedding_range.item() is model-dependent. Then you can calculate the score by either head-batch mode or tail-batch mode, they are equivalent for a single triplet.

For example, in head-batch mode, you can write something like:

re_head, im_head = torch.chunk(head, 2, dim=2) re_tail, im_tail = torch.chunk(tail, 2, dim=2) re_relation = torch.cos(phase_relation) im_relation = torch.sin(phase_relation) re_score = re_relation re_tail + im_relation im_tail - re_head im_score = re_relation im_tail - im_relation re_tail - im_head score = torch.stack([re_score, im_score], dim = 0) score = score.norm(dim = 0) score = - score.sum(dim = 2)