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 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
| import codecs import random import math import numpy as np import copy import time
entity2id = {} relation2id = {}
def data_loader(file): file1 = file + "train.txt" file2 = file + "entity2id.txt" file3 = file + "relation2id.txt"
with open(file2, 'r') as f1, open(file3, 'r') as f2: lines1 = f1.readlines() lines2 = f2.readlines() for line in lines1: line = line.strip().split('\t') if len(line) != 2: continue entity2id[line[0]] = line[1]
for line in lines2: line = line.strip().split('\t') if len(line) != 2: continue relation2id[line[0]] = line[1]
entity_set = set() relation_set = set() triple_list = []
with codecs.open(file1, 'r') as f: content = f.readlines() for line in content: triple = line.strip().split("\t") if len(triple) != 3: continue
h_ = entity2id[triple[0]] t_ = entity2id[triple[1]] r_ = relation2id[triple[2]]
triple_list.append([h_, t_, r_])
entity_set.add(h_) entity_set.add(t_) relation_set.add(r_)
return entity_set, relation_set, triple_list
def distanceL2(h, r, t): return np.sum(np.square(h + r - t))
def distanceL1(h, r, t): return np.sum(np.fabs(h + r - t))
class TransE: def __init__(self, entity_set, relation_set, triple_list, embedding_dim=100, learning_rate=0.01, margin=1, L1=True): self.embedding_dim = embedding_dim self.learning_rate = learning_rate self.margin = margin self.entity = entity_set self.relation = relation_set self.triple_list = triple_list self.L1 = L1
self.loss = 0
def emb_initialize(self): relation_dict = {} entity_dict = {}
for relation in self.relation: r_emb_temp = np.random.uniform(-6 / math.sqrt(self.embedding_dim), 6 / math.sqrt(self.embedding_dim), self.embedding_dim) relation_dict[relation] = r_emb_temp / np.linalg.norm(r_emb_temp, ord=2)
for entity in self.entity: e_emb_temp = np.random.uniform(-6 / math.sqrt(self.embedding_dim), 6 / math.sqrt(self.embedding_dim), self.embedding_dim) entity_dict[entity] = e_emb_temp / np.linalg.norm(e_emb_temp, ord=2)
self.relation = relation_dict self.entity = entity_dict
def train(self, epochs): nbatches = 400 batch_size = len(self.triple_list) // nbatches print("batch size: ", batch_size) for epoch in range(epochs): start = time.time() self.loss = 0
for k in range(nbatches): Sbatch = random.sample(self.triple_list, batch_size) Tbatch = []
for triple in Sbatch: corrupted_triple = self.Corrupt(triple) if (triple, corrupted_triple) not in Tbatch: Tbatch.append((triple, corrupted_triple)) self.update_embeddings(Tbatch)
end = time.time() print("epoch: ", epoch, "cost time: %s" % (round((end - start), 3))) print("loss: ", self.loss)
if epoch % 20 == 0: with codecs.open("entity_temp", "w") as f_e: for e in self.entity.keys(): f_e.write(e + "\t") f_e.write(str(list(self.entity[e]))) f_e.write("\n") with codecs.open("relation_temp", "w") as f_r: for r in self.relation.keys(): f_r.write(r + "\t") f_r.write(str(list(self.relation[r]))) f_r.write("\n")
print("写入文件...") with codecs.open("entity_50dim_batch400", "w") as f1: for e in self.entity.keys(): f1.write(e + "\t") f1.write(str(list(self.entity[e]))) f1.write("\n")
with codecs.open("relation50dim_batch400", "w") as f2: for r in self.relation.keys(): f2.write(r + "\t") f2.write(str(list(self.relation[r]))) f2.write("\n") print("写入完成")
def Corrupt(self, triple): corrupted_triple = copy.deepcopy(triple) seed = random.random() if seed > 0.5: rand_head = triple[0] while rand_head == triple[0]: rand_head = random.sample(self.entity.keys(), 1)[0] corrupted_triple[0] = rand_head
else: rand_tail = triple[1] while rand_tail == triple[1]: rand_tail = random.sample(self.entity.keys(), 1)[0] corrupted_triple[1] = rand_tail return corrupted_triple
def update_embeddings(self, Tbatch): copy_entity = copy.deepcopy(self.entity) copy_relation = copy.deepcopy(self.relation)
for triple, corrupted_triple in Tbatch: h_correct_update = copy_entity[triple[0]] t_correct_update = copy_entity[triple[1]] relation_update = copy_relation[triple[2]]
h_corrupt_update = copy_entity[corrupted_triple[0]] t_corrupt_update = copy_entity[corrupted_triple[1]]
h_correct = self.entity[triple[0]] t_correct = self.entity[triple[1]] relation = self.relation[triple[2]]
h_corrupt = self.entity[corrupted_triple[0]] t_corrupt = self.entity[corrupted_triple[1]]
if self.L1: dist_correct = distanceL1(h_correct, relation, t_correct) dist_corrupt = distanceL1(h_corrupt, relation, t_corrupt) else: dist_correct = distanceL2(h_correct, relation, t_correct) dist_corrupt = distanceL2(h_corrupt, relation, t_corrupt)
err = self.hinge_loss(dist_correct, dist_corrupt)
if err > 0: self.loss += err
grad_pos = 2 * (h_correct + relation - t_correct) grad_neg = 2 * (h_corrupt + relation - t_corrupt)
if self.L1: for i in range(len(grad_pos)): if grad_pos[i] > 0: grad_pos[i] = 1 else: grad_pos[i] = -1
for i in range(len(grad_neg)): if grad_neg[i] > 0: grad_neg[i] = 1 else: grad_neg[i] = -1
h_correct_update -= self.learning_rate * grad_pos t_correct_update -= (-1) * self.learning_rate * grad_pos
if triple[0] == corrupted_triple[0]: h_correct_update -= (-1) * self.learning_rate * grad_neg t_corrupt_update -= self.learning_rate * grad_neg
elif triple[1] == corrupted_triple[1]: h_corrupt_update -= (-1) * self.learning_rate * grad_neg t_correct_update -= self.learning_rate * grad_neg
relation_update -= self.learning_rate * grad_pos relation_update -= (-1) * self.learning_rate * grad_neg
for i in copy_entity.keys(): copy_entity[i] /= np.linalg.norm(copy_entity[i]) for i in copy_relation.keys(): copy_relation[i] /= np.linalg.norm(copy_relation[i])
self.entity = copy_entity self.relation = copy_relation
def hinge_loss(self, dist_correct, dist_corrupt): return max(0, dist_correct - dist_corrupt + self.margin)
if __name__ == '__main__': file1 = "./FB15k/" entity_set, relation_set, triple_list = data_loader(file1) print("load file...") print("Complete load. entity : %d , relation : %d , triple : %d" % ( len(entity_set), len(relation_set), len(triple_list)))
transE = TransE(entity_set, relation_set, triple_list, embedding_dim=50, learning_rate=0.01, margin=1, L1=True) transE.emb_initialize() transE.train(epochs=1001)
|