-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmodel_dropout_bn.py
69 lines (53 loc) · 2.16 KB
/
model_dropout_bn.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
63
64
65
66
67
68
69
import numpy as np
import torch
from torch.nn.init import xavier_normal_
class TuckER(torch.nn.Module):
def __init__(self, d, d1, d2, **kwargs):
super(TuckER, self).__init__()
self.d1 = d1
self.d2 = d2
self.E = torch.nn.Embedding(len(d.entities), d1, padding_idx=0)
self.R = torch.nn.Embedding(len(d.relations), d2, padding_idx=0)
self.W = torch.nn.Parameter(torch.tensor(np.random.uniform(-1, 1, (d2, d1, d1)),
dtype=torch.float, device="cuda", requires_grad=True))
self.input_dropout = torch.nn.Dropout(kwargs["input_dropout"])
self.hidden_dropout1 = torch.nn.Dropout(kwargs["hidden_dropout1"])
self.hidden_dropout2 = torch.nn.Dropout(kwargs["hidden_dropout2"])
self.loss = torch.nn.BCELoss()
self.bn0 = torch.nn.BatchNorm1d(d1)
self.bn1 = torch.nn.BatchNorm1d(d1)
def init(self):
xavier_normal_(self.E.weight.data)
xavier_normal_(self.R.weight.data)
def forward(self, e1_idx, e2_idx):
e1 = self.E(e1_idx)
x = self.bn0(e1)
x = self.input_dropout(x)
x = x.view(-1, 1, e1.size(1))
e2 = self.E(e2_idx)
W_mat = torch.mm(e2, self.W.view(e2.size(1), -1))
W_mat = W_mat.view(-1, e1.size(1), self.d2)
W_mat = self.hidden_dropout1(W_mat)
x = torch.bmm(x, W_mat)
x = x.view(-1, self.d2)
x = self.bn1(x)
x = self.hidden_dropout2(x)
x = torch.mm(x, self.R.weight.transpose(1,0))
pred = torch.sigmoid(x)
return pred
def forward_lp(self, e1_idx, r_idx):
e1 = self.E(e1_idx)
x = self.bn0(e1)
x = self.input_dropout(x)
x = x.view(-1, 1, e1.size(1))
r = self.R(r_idx)
W_mat = torch.mm(r, self.W.view(r.size(1), -1))
W_mat = W_mat.view(-1, e1.size(1), e1.size(1))
W_mat = self.hidden_dropout1(W_mat)
x = torch.bmm(x, W_mat)
x = x.view(-1, e1.size(1))
x = self.bn1(x)
x = self.hidden_dropout2(x)
x = torch.mm(x, self.E.weight.transpose(1,0))
pred = torch.sigmoid(x)
return pred