MCPcopy
hub / github.com/thunlp/OpenKE / NegativeSampling

Class NegativeSampling

openke/module/strategy/NegativeSampling.py:3–32  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1from .Strategy import Strategy
2
3class NegativeSampling(Strategy):
4
5 def __init__(self, model = None, loss = None, batch_size = 256, regul_rate = 0.0, l3_regul_rate = 0.0):
6 super(NegativeSampling, self).__init__()
7 self.model = model
8 self.loss = loss
9 self.batch_size = batch_size
10 self.regul_rate = regul_rate
11 self.l3_regul_rate = l3_regul_rate
12
13 def _get_positive_score(self, score):
14 positive_score = score[:self.batch_size]
15 positive_score = positive_score.view(-1, self.batch_size).permute(1, 0)
16 return positive_score
17
18 def _get_negative_score(self, score):
19 negative_score = score[self.batch_size:]
20 negative_score = negative_score.view(-1, self.batch_size).permute(1, 0)
21 return negative_score
22
23 def forward(self, data):
24 score = self.model(data)
25 p_score = self._get_positive_score(score)
26 n_score = self._get_negative_score(score)
27 loss_res = self.loss(p_score, n_score)
28 if self.regul_rate != 0:
29 loss_res += self.regul_rate * self.model.regularization(data)
30 if self.l3_regul_rate != 0:
31 loss_res += self.l3_regul_rate * self.model.l3_regularization()
32 return loss_res

Calls

no outgoing calls

Tested by

no test coverage detected