-
Notifications
You must be signed in to change notification settings - Fork 0
/
evaluate_embedding.py
300 lines (242 loc) · 10.2 KB
/
evaluate_embedding.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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
import torch
import torch.nn as nn
import numpy as np
import pandas as pd
import os
import torch.nn.functional as F
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import GridSearchCV, KFold, StratifiedKFold
from sklearn.svm import SVC, LinearSVC
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.neural_network import MLPClassifier
from sklearn import preprocessing
from sklearn.metrics import accuracy_score
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
def draw_plot(datadir, DS, embeddings, fname, max_nodes=None):
return
graphs = read_graphfile(datadir, DS, max_nodes=max_nodes)
labels = [graph.graph['label'] for graph in graphs]
labels = preprocessing.LabelEncoder().fit_transform(labels)
x, y = np.array(embeddings), np.array(labels)
print('fitting TSNE ...')
x = TSNE(n_components=2).fit_transform(x)
plt.close()
df = pd.DataFrame(columns=['x0', 'x1', 'Y'])
df['x0'], df['x1'], df['Y'] = x[:,0], x[:,1], y
sns.pairplot(x_vars=['x0'], y_vars=['x1'], data=df, hue="Y", size=5)
plt.legend()
plt.savefig(fname)
class LogReg(nn.Module):
def __init__(self, ft_in, nb_classes):
super(LogReg, self).__init__()
self.fc = nn.Linear(ft_in, nb_classes)
for m in self.modules():
self.weights_init(m)
def weights_init(self, m):
if isinstance(m, nn.Linear):
torch.nn.init.xavier_uniform_(m.weight.data)
if m.bias is not None:
m.bias.data.fill_(0.0)
def forward(self, seq):
ret = self.fc(seq)
return ret
def logistic_classify(x, y, x_test, y_test, args=None):
nb_classes = np.unique(y).shape[0]
xent = nn.CrossEntropyLoss()
hid_units = x.shape[1]
accs = []
accs_val = []
kf = StratifiedKFold(n_splits=10, shuffle=True, random_state=None)
# for train_index, test_index in kf.split(x, y):
# test
train_embs, test_embs = x, x_test
train_lbls, test_lbls= y, y_test
train_embs, train_lbls = torch.from_numpy(train_embs).cuda(), torch.from_numpy(train_lbls).cuda()
test_embs, test_lbls= torch.from_numpy(test_embs).cuda(), torch.from_numpy(test_lbls).cuda()
log = LogReg(hid_units, nb_classes)
log.cuda()
opt = torch.optim.Adam(log.parameters(), lr=0.01, weight_decay=0.0)
best_val = 0
test_acc = None
for it in range(100):
log.train()
opt.zero_grad()
logits = log(train_embs)
loss = xent(logits, train_lbls)
loss.backward()
opt.step()
logits = log(test_embs)
preds = torch.argmax(logits, dim=1)
# acc = torch.sum(preds == test_lbls[:200]).float() / test_lbls.shape[0]
acc = torch.sum(preds[:120] == test_lbls[:120]).float()/ 120
accs.append(acc.item())
# val
# val_size = len(test_index)
# print(len(test_index))
# test_index = np.random.choice(test_index, val_size, replace=False).tolist()
# train_index = [i for i in train_index if not i in test_index]
train_embs, test_embs = x, x_test
train_lbls, test_lbls= y, y_test
train_embs, train_lbls = torch.from_numpy(train_embs).cuda(), torch.from_numpy(train_lbls).cuda()
test_embs, test_lbls= torch.from_numpy(test_embs).cuda(), torch.from_numpy(test_lbls).cuda()
log = LogReg(hid_units, nb_classes)
log.cuda()
opt = torch.optim.Adam(log.parameters(), lr=0.01, weight_decay=0.0)
best_val = 0
test_acc = None
for it in range(100):
log.train()
opt.zero_grad()
logits = log(train_embs)
loss = xent(logits, train_lbls)
loss.backward()
opt.step()
logits = log(test_embs)
logits_train = log(train_embs)
# logs,_ = torch.max(F.softmax(logits, dim=1), dim=1)
# logmax_save = logs.cpu().detach().numpy()
# if args is not None:
# np.savetxt(str(args.DS_pair) + '_logmax.txt', logmax_save, fmt='%.4f', delimiter='\t')
logmax_save = logits.cpu().detach().numpy()
logmax_train_save = logits_train.cpu().detach().numpy()
# if args is not None:
# np.savetxt(str(args.DS_pair) + '_logits_test.txt', logmax_save, fmt='%.4f', delimiter='\t')
# np.savetxt(str(args.DS_pair) + '_logits_train.txt', logmax_train_save, fmt='%.4f', delimiter='\t')
preds = torch.argmax(logits, dim=1)
# acc = torch.sum(preds == test_lbls).float() / test_lbls.shape[0]
acc = torch.sum(preds[:200] == test_lbls[:200]).float() / 200
accs_val.append(acc.item())
return np.mean(accs_val), np.mean(accs)
def svc_classify(x, y, search):
kf = StratifiedKFold(n_splits=10, shuffle=True, random_state=None)
accuracies = []
accuracies_val = []
for train_index, test_index in kf.split(x, y):
# test
x_train, x_test = x[train_index], x[test_index]
y_train, y_test = y[train_index], y[test_index]
# x_train, x_val, y_train, y_val = train_test_split(x_train, y_train, test_size=0.1)
if search:
params = {'C':[0.001, 0.01,0.1,1,10,100,1000]}
classifier = GridSearchCV(SVC(), params, cv=5, scoring='accuracy', verbose=0)
else:
classifier = SVC(C=10)
classifier.fit(x_train, y_train)
accuracies.append(accuracy_score(y_test, classifier.predict(x_test)))
# val
val_size = len(test_index)
test_index = np.random.choice(train_index, val_size, replace=False).tolist()
train_index = [i for i in train_index if not i in test_index]
x_train, x_test = x[train_index], x[test_index]
y_train, y_test = y[train_index], y[test_index]
# x_train, x_val, y_train, y_val = train_test_split(x_train, y_train, test_size=0.1)
if search:
params = {'C':[0.001, 0.01,0.1,1,10,100,1000]}
classifier = GridSearchCV(SVC(), params, cv=5, scoring='accuracy', verbose=0)
else:
classifier = SVC(C=10)
classifier.fit(x_train, y_train)
accuracies_val.append(accuracy_score(y_test, classifier.predict(x_test)))
return np.mean(accuracies_val), np.mean(accuracies)
def randomforest_classify(x, y, search):
kf = StratifiedKFold(n_splits=10, shuffle=True, random_state=None)
accuracies = []
accuracies_val = []
for train_index, test_index in kf.split(x, y):
# test
x_train, x_test = x[train_index], x[test_index]
y_train, y_test = y[train_index], y[test_index]
if search:
params = {'n_estimators': [100, 200, 500, 1000]}
classifier = GridSearchCV(RandomForestClassifier(), params, cv=5, scoring='accuracy', verbose=0)
else:
classifier = RandomForestClassifier()
classifier.fit(x_train, y_train)
accuracies.append(accuracy_score(y_test, classifier.predict(x_test)))
# val
val_size = len(test_index)
test_index = np.random.choice(test_index, val_size, replace=False).tolist()
train_index = [i for i in train_index if not i in test_index]
x_train, x_test = x[train_index], x[test_index]
y_train, y_test = y[train_index], y[test_index]
if search:
params = {'n_estimators': [100, 200, 500, 1000]}
classifier = GridSearchCV(RandomForestClassifier(), params, cv=5, scoring='accuracy', verbose=0)
else:
classifier = RandomForestClassifier()
classifier.fit(x_train, y_train)
accuracies_val.append(accuracy_score(y_test, classifier.predict(x_test)))
ret = np.mean(accuracies)
return np.mean(accuracies_val), ret
def linearsvc_classify(x, y, search):
kf = StratifiedKFold(n_splits=10, shuffle=True, random_state=None)
accuracies = []
accuracies_val = []
for train_index, test_index in kf.split(x, y):
# test
x_train, x_test = x[train_index], x[test_index]
y_train, y_test = y[train_index], y[test_index]
if search:
params = {'C':[0.001, 0.01,0.1,1,10,100,1000]}
classifier = GridSearchCV(LinearSVC(), params, cv=5, scoring='accuracy', verbose=0)
else:
classifier = LinearSVC(C=10)
with warnings.catch_warnings():
warnings.simplefilter('ignore')
classifier.fit(x_train, y_train)
accuracies.append(accuracy_score(y_test, classifier.predict(x_test)))
# val
val_size = len(test_index)
test_index = np.random.choice(train_index, val_size, replace=False).tolist()
train_index = [i for i in train_index if not i in test_index]
x_train, x_test = x[train_index], x[test_index]
y_train, y_test = y[train_index], y[test_index]
if search:
params = {'C':[0.001, 0.01,0.1,1,10,100,1000]}
classifier = GridSearchCV(LinearSVC(), params, cv=5, scoring='accuracy', verbose=0)
else:
classifier = LinearSVC(C=10)
with warnings.catch_warnings():
warnings.simplefilter('ignore')
classifier.fit(x_train, y_train)
accuracies_val.append(accuracy_score(y_test, classifier.predict(x_test)))
return np.mean(accuracies_val), np.mean(accuracies)
def evaluate_embedding(embeddings, labels, emb_test, labels_test, search=True, args=None):
labels = preprocessing.LabelEncoder().fit_transform(labels)
x, y = np.array(embeddings), np.array(labels)
labels_test = preprocessing.LabelEncoder().fit_transform(labels_test)
x_test, y_test = np.array(emb_test), np.array(labels_test)
acc = 0
acc_val = 0
'''
_acc_val, _acc = logistic_classify(x, y, x_test, y_test, args)
if _acc_val > acc_val:
acc_val = _acc_val
acc = _acc
'''
_acc_val, _acc = svc_classify(x,y, search)
if _acc_val > acc_val:
acc_val = _acc_val
acc = _acc
"""
_acc_val, _acc = linearsvc_classify(x, y, search)
if _acc_val > acc_val:
acc_val = _acc_val
acc = _acc
"""
'''
_acc_val, _acc = randomforest_classify(x, y, search)
if _acc_val > acc_val:
acc_val = _acc_val
acc = _acc
'''
print(acc_val, acc)
return acc_val, acc
'''
if __name__ == '__main__':
evaluate_embedding('./data', 'ENZYMES', np.load('tmp/emb.npy'))
'''