-
Notifications
You must be signed in to change notification settings - Fork 2
/
run.py
274 lines (214 loc) · 9.98 KB
/
run.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
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
from config import *
import warnings
warnings.filterwarnings('ignore')
import os
import torch
import keras
import numpy as np
from utils import *
from tqdm import *
from keras.layers import *
import tensorflow.compat.v1 as tf
import keras.backend as K
from layer import NR_GraphAttention
from os.path import join as pjoin
import sparse_eval
import pickle
from os.path import join as pjoin
from sinkhorn import matrix_sinkhorn
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
tf.logging.set_verbosity(tf.compat.v1.logging.ERROR)
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
sess = tf.Session(config=config)
seed = 12306
np.random.seed(seed)
tf.compat.v1.set_random_seed(seed)
'''
----------------------- data information -------------------------
name | explain | type
___________________________________________________________________
dev_pair | test pair | [(1, 100), (2,103)]
adj_matrix | (h,r,t) adj[h,t] = adj[t,h] = 1
r_index 有反向边 [[count, r], [count, r]] count = different (h, t) len(r_index) = num_triple
r_val 1/degree
adj_features norm(adj+I)
rel_features norm(rel_in || rel_out)
'''
dataset = args.dataset
source_dataset, target_dataset = dataset.split('-')
# load side modalities from ./data/dataset/MSP_results folder
side_modalities = {}
for filename in os.listdir(pjoin('./data', dataset, 'MSP_results')):
# load the .npy file
if filename.endswith('.npy'):
side_modalities[filename.split('.')[0]] = np.load(pjoin('./data', dataset, 'MSP_results', filename))
print('there are {} side modalities'.format(len(side_modalities)))
print('they are: {}'.format(side_modalities.keys()))
train_pair, dev_pair, adj_matrix, r_index, r_val, adj_features, rel_features = load_data("data/" + dataset + '/', train_ratio=0.20)
adj_matrix = np.stack(adj_matrix.nonzero(), axis=1)
print(adj_matrix)
rel_matrix, rel_val = np.stack(rel_features.nonzero(), axis=1), rel_features.data
ent_matrix, ent_val = np.stack(adj_features.nonzero(), axis=1), adj_features.data
print(rel_matrix)
print(rel_val)
node_size = adj_features.shape[0]
rel_size = rel_features.shape[1]
triple_size = len(adj_matrix)
node_hidden = 128
rel_hidden = 128
batch_size = 1024
dropout_rate = 0.3
lr = 0.005
gamma = 1
depth = 2
def get_embedding(index_a, index_b, vec=None):
if vec is None:
inputs = [adj_matrix, r_index, r_val, rel_matrix, ent_matrix]
inputs = [np.expand_dims(item, axis=0) for item in inputs]
vec = get_emb.predict_on_batch(inputs)
Lvec = np.array([vec[e] for e in index_a])
Rvec = np.array([vec[e] for e in index_b])
Lvec = Lvec / (np.linalg.norm(Lvec, axis=-1, keepdims=True) + 1e-5)
Rvec = Rvec / (np.linalg.norm(Rvec, axis=-1, keepdims=True) + 1e-5)
return Lvec, Rvec
class TokenEmbedding(keras.layers.Embedding):
"""Embedding layer with weights returned."""
def compute_output_shape(self, input_shape):
return self.input_dim, self.output_dim
def compute_mask(self, inputs, mask=None):
return None
def call(self, inputs):
return self.embeddings
def get_trgat(node_hidden, rel_hidden, triple_size=triple_size, node_size=node_size, rel_size=rel_size, dropout_rate=0,
gamma=3, lr=0.005, depth=2):
adj_input = Input(shape=(None, 2))
index_input = Input(shape=(None, 2), dtype='int64')
val_input = Input(shape=(None,))
rel_adj = Input(shape=(None, 2))
ent_adj = Input(shape=(None, 2))
ent_emb = TokenEmbedding(node_size, node_hidden, trainable=True)(val_input)
rel_emb = TokenEmbedding(rel_size, node_hidden, trainable=True)(val_input)
def avg(tensor, size):
adj = K.cast(K.squeeze(tensor[0], axis=0), dtype="int64")
adj = tf.SparseTensor(indices=adj, values=tf.ones_like(adj[:, 0], dtype='float32'),
dense_shape=(node_size, size))
adj = tf.sparse_softmax(adj)
return tf.sparse_tensor_dense_matmul(adj, tensor[1])
opt = [rel_emb, adj_input, index_input, val_input]
ent_feature = Lambda(avg, arguments={'size': node_size})([ent_adj, ent_emb])
rel_feature = Lambda(avg, arguments={'size': rel_size})([rel_adj, rel_emb])
e_encoder = NR_GraphAttention(node_size, activation="tanh",
rel_size=rel_size,
use_bias=True,
depth=depth,
triple_size=triple_size)
r_encoder = NR_GraphAttention(node_size, activation="tanh",
rel_size=rel_size,
use_bias=True,
depth=depth,
triple_size=triple_size)
out_feature = Concatenate(-1)([e_encoder([ent_feature] + opt), r_encoder([rel_feature] + opt)])
out_feature = Dropout(dropout_rate)(out_feature)
alignment_input = Input(shape=(None, 2))
def align_loss(tensor):
def squared_dist(x):
A, B = x
row_norms_A = tf.reduce_sum(tf.square(A), axis=1)
row_norms_A = tf.reshape(row_norms_A, [-1, 1]) # Column vector.
row_norms_B = tf.reduce_sum(tf.square(B), axis=1)
row_norms_B = tf.reshape(row_norms_B, [1, -1]) # Row vector.
return row_norms_A + row_norms_B - 2 * tf.matmul(A, B, transpose_b=True)
emb = tensor[1]
l, r = K.cast(tensor[0][0, :, 0], 'int32'), K.cast(tensor[0][0, :, 1], 'int32')
l_emb, r_emb = K.gather(reference=emb, indices=l), K.gather(reference=emb, indices=r)
pos_dis = K.sum(K.square(l_emb - r_emb), axis=-1, keepdims=True)
r_neg_dis = squared_dist([r_emb, emb])
l_neg_dis = squared_dist([l_emb, emb])
l_loss = pos_dis - l_neg_dis + gamma
l_loss = l_loss * (
1 - K.one_hot(indices=l, num_classes=node_size) - K.one_hot(indices=r, num_classes=node_size))
r_loss = pos_dis - r_neg_dis + gamma
r_loss = r_loss * (
1 - K.one_hot(indices=l, num_classes=node_size) - K.one_hot(indices=r, num_classes=node_size))
r_loss = (r_loss - K.stop_gradient(K.mean(r_loss, axis=-1, keepdims=True))) / K.stop_gradient(
K.std(r_loss, axis=-1, keepdims=True))
l_loss = (l_loss - K.stop_gradient(K.mean(l_loss, axis=-1, keepdims=True))) / K.stop_gradient(
K.std(l_loss, axis=-1, keepdims=True))
lamb, tau = 30, 10
l_loss = tf.reduce_logsumexp(lamb * l_loss + tau, axis=-1)
r_loss = tf.reduce_logsumexp(lamb * r_loss + tau, axis=-1)
final_loss = K.mean(l_loss + r_loss)
print(final_loss)
return final_loss
loss = Lambda(align_loss)([alignment_input, out_feature])
inputs = [adj_input, index_input, val_input, rel_adj, ent_adj]
train_model = keras.Model(inputs=inputs + [alignment_input], outputs=loss)
train_model.compile(loss=lambda y_true, y_pred: y_pred, optimizer=keras.optimizers.RMSprop(lr))
feature_model = keras.Model(inputs=inputs, outputs=out_feature)
return train_model, feature_model
model,get_emb = get_trgat(dropout_rate=dropout_rate,
node_size=node_size,
rel_size=rel_size,
depth=depth,
gamma=gamma,
node_hidden=node_hidden,
rel_hidden=rel_hidden,
lr=lr)
model.summary()
rest_set_1 = [e1 for e1, e2 in dev_pair]
rest_set_2 = [e2 for e1, e2 in dev_pair]
sourceId2Index = {e1: i for i, e1 in enumerate(rest_set_1)}
targetId2Index = {e2: i for i, e2 in enumerate(rest_set_2)}
np.random.shuffle(rest_set_1)
np.random.shuffle(rest_set_2)
epoch = 20
for turn in range(3):
for i in trange(epoch):
np.random.shuffle(train_pair)
for pairs in [train_pair[i * batch_size:(i + 1) * batch_size] for i in
range(len(train_pair) // batch_size + 1)]:
if len(pairs) == 0:
continue
inputs = [adj_matrix, r_index, r_val, rel_matrix, ent_matrix, pairs]
inputs = [np.expand_dims(item, axis=0) for item in inputs]
output = model.train_on_batch(inputs, np.zeros((1, 1)))
print(output)
if i%5==4 :
Lvec, Rvec = get_embedding(dev_pair[:, 0], dev_pair[:, 1])
# get score matrix for dev_pair
scores = torch.Tensor(Lvec.dot(Rvec.T))
# add side modalities scores
for _, side_score in side_modalities.items():
scores += torch.Tensor(side_score)
scores = matrix_sinkhorn(1 - scores)
sparse_eval.evaluate_sim_matrix(link = torch.stack([torch.arange(len(dev_pair)),
torch.arange(len(dev_pair))], dim=0),
sim_x2y=scores,
no_csls=True)
new_pair = []
Lvec, Rvec = get_embedding(rest_set_1, rest_set_2)
side_scores_now = {}
for side_name, side_score in side_modalities.items():
side_scores_now[side_name] = np.zeros((len(rest_set_1), len(rest_set_2)), dtype=np.float32)
for i, e1 in enumerate(rest_set_1):
for j, e2 in enumerate(rest_set_2):
source_index = sourceId2Index[e1]
target_index = targetId2Index[e2]
side_scores_now[side_name][i, j] = side_score[source_index, target_index]
scores = Lvec.dot(Rvec.T)
for _, side_score in side_scores_now.items():
scores += side_score
A, B = scores.argmax(axis=0), scores.argmax(axis=1)
for i, j in enumerate(A):
if B[j] == i:
new_pair.append([rest_set_1[j], rest_set_2[i]])
train_pair = np.concatenate([train_pair, np.array(new_pair)], axis=0)
for e1, e2 in new_pair:
if e1 in rest_set_1:
rest_set_1.remove(e1)
for e1, e2 in new_pair:
if e2 in rest_set_2:
rest_set_2.remove(e2)
epoch = 5