-
Notifications
You must be signed in to change notification settings - Fork 2
/
load_datasets.py
453 lines (362 loc) · 18.2 KB
/
load_datasets.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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
import os
import glob
import json
import torch
import pickle
import shutil
import numpy as np
import os.path as osp
from torch_geometric.datasets import MoleculeNet
from torch_geometric.utils import dense_to_sparse
from torch.utils.data import random_split, Subset
from torch_geometric.data import Data, InMemoryDataset, download_url, extract_zip
from torch_geometric.loader import DataLoader
def undirected_graph(data):
data.edge_index = torch.cat([torch.stack([data.edge_index[1], data.edge_index[0]], dim=0),
data.edge_index], dim=1)
return data
def split(data, batch):
# i-th contains elements from slice[i] to slice[i+1]
node_slice = torch.cumsum(torch.from_numpy(np.bincount(batch)), 0)
node_slice = torch.cat([torch.tensor([0]), node_slice])
row, _ = data.edge_index
edge_slice = torch.cumsum(torch.from_numpy(np.bincount(batch[row])), 0)
edge_slice = torch.cat([torch.tensor([0]), edge_slice])
# Edge indices should start at zero for every graph.
data.edge_index -= node_slice[batch[row]].unsqueeze(0)
data.__num_nodes__ = np.bincount(batch).tolist()
slices = dict()
slices['x'] = node_slice
slices['edge_index'] = edge_slice
slices['y'] = torch.arange(0, batch[-1] + 2, dtype=torch.long)
return data, slices
def read_file(folder, prefix, name):
file_path = osp.join(folder, prefix + f'_{name}.txt')
return np.genfromtxt(file_path, dtype=np.int64)
def read_sentigraph_data(folder: str, prefix: str):
txt_files = glob.glob(os.path.join(folder, "{}_*.txt".format(prefix)))
json_files = glob.glob(os.path.join(folder, "{}_*.json".format(prefix)))
txt_names = [f.split(os.sep)[-1][len(prefix) + 1:-4] for f in txt_files]
json_names = [f.split(os.sep)[-1][len(prefix) + 1:-5] for f in json_files]
names = txt_names + json_names
with open(os.path.join(folder, prefix+"_node_features.pkl"), 'rb') as f:
x: np.array = pickle.load(f)
x: torch.FloatTensor = torch.from_numpy(x)
edge_index: np.array = read_file(folder, prefix, 'edge_index')
edge_index: torch.tensor = torch.tensor(edge_index, dtype=torch.long).T
batch: np.array = read_file(folder, prefix, 'node_indicator') - 1 # from zero
y: np.array = read_file(folder, prefix, 'graph_labels')
y: torch.tensor = torch.tensor(y, dtype=torch.long)
supplement = dict()
if 'split_indices' in names:
split_indices: np.array = read_file(folder, prefix, 'split_indices')
split_indices = torch.tensor(split_indices, dtype=torch.long)
supplement['split_indices'] = split_indices
if 'sentence_tokens' in names:
with open(os.path.join(folder, prefix + '_sentence_tokens.json')) as f:
sentence_tokens: dict = json.load(f)
supplement['sentence_tokens'] = sentence_tokens
data = Data(x=x, edge_index=edge_index, y=y)
data, slices = split(data, batch)
return data, slices, supplement
def read_syn_data(folder: str, prefix):
with open(os.path.join(folder, f"{prefix}.pkl"), 'rb') as f:
adj, features, y_train, y_val, y_test, train_mask, val_mask, test_mask, edge_label_matrix = pickle.load(f)
x = torch.from_numpy(features).float()
y = train_mask.reshape(-1, 1) * y_train + val_mask.reshape(-1, 1) * y_val + test_mask.reshape(-1, 1) * y_test
y = torch.from_numpy(np.where(y)[1])
edge_index = dense_to_sparse(torch.from_numpy(adj))[0]
data = Data(x=x, y=y, edge_index=edge_index)
data.train_mask = torch.from_numpy(train_mask)
data.val_mask = torch.from_numpy(val_mask)
data.test_mask = torch.from_numpy(test_mask)
return data
def read_ba2motif_data(folder: str, prefix):
with open(os.path.join(folder, f"{prefix}.pkl"), 'rb') as f:
dense_edges, node_features, graph_labels = pickle.load(f)
data_list = []
for graph_idx in range(dense_edges.shape[0]):
data_list.append(Data(x=torch.from_numpy(node_features[graph_idx]).float(),
edge_index=dense_to_sparse(torch.from_numpy(dense_edges[graph_idx]))[0],
y=torch.from_numpy(np.where(graph_labels[graph_idx])[0])))
return data_list
def get_dataset(dataset_dir, dataset_name, task=None):
sync_dataset_dict = {
'BA_2Motifs'.lower(): 'BA_2Motifs',
'BA_Shapes'.lower(): 'BA_shapes',
'BA_Community'.lower(): 'BA_Community',
'Tree_Cycle'.lower(): 'Tree_Cycle',
'Tree_Grids'.lower(): 'Tree_Grids',
'BA_LRP'.lower(): 'ba_lrp'
}
sentigraph_names = ['Graph_SST2', 'Graph_Twitter', 'Graph_SST5']
sentigraph_names = [name.lower() for name in sentigraph_names]
molecule_net_dataset_names = [name.lower() for name in MoleculeNet.names.keys()]
if dataset_name.lower() == 'Mutagenicity'.lower():
return load_MUTAG(dataset_dir, 'mutagenicity')
elif dataset_name.lower() in sync_dataset_dict.keys():
sync_dataset_filename = sync_dataset_dict[dataset_name.lower()]
return load_syn_data(dataset_dir, sync_dataset_filename)
elif dataset_name.lower() in molecule_net_dataset_names:
return load_MolecueNet(dataset_dir, dataset_name, task)
elif dataset_name.lower() in sentigraph_names:
return load_SeniGraph(dataset_dir, dataset_name)
else:
raise NotImplementedError
class MUTAGDataset(InMemoryDataset):
def __init__(self, root, name, transform=None, pre_transform=None):
self.root = root
self.name = name.lower()
super(MUTAGDataset, self).__init__(root, transform, pre_transform)
self.data, self.slices = torch.load(self.processed_paths[0])
def __len__(self):
return len(self.slices['x']) - 1
@property
def raw_dir(self):
return os.path.join(self.root, self.name, 'raw')
@property
def raw_file_names(self):
return ['Mutagenicity_A', 'Mutagenicity_graph_labels', 'Mutagenicity_graph_indicator', 'Mutagenicity_node_labels']
@property
def processed_dir(self):
return os.path.join(self.root, self.name, 'processed')
@property
def processed_file_names(self):
return ['data.pt']
def download(self):
url = 'https://www.chrsmrrs.com/graphkerneldatasets'
folder = osp.join(self.root, self.name)
path = download_url(f'{url}/{self.name}.zip', folder)
extract_zip(path, folder)
os.unlink(path)
shutil.rmtree(self.raw_dir)
os.rename(osp.join(folder, self.name), self.raw_dir)
def process(self):
r"""Processes the dataset to the :obj:`self.processed_dir` folder."""
with open(os.path.join(self.raw_dir, 'Mutagenicity_node_labels.txt'), 'r') as f:
nodes_all_temp = f.read().splitlines()
nodes_all = [int(i) for i in nodes_all_temp]
adj_all = np.zeros((len(nodes_all), len(nodes_all)))
with open(os.path.join(self.raw_dir, 'Mutagenicity_A.txt'), 'r') as f:
adj_list = f.read().splitlines()
for item in adj_list:
lr = item.split(', ')
l = int(lr[0])
r = int(lr[1])
adj_all[l - 1, r - 1] = 1
with open(os.path.join(self.raw_dir, 'Mutagenicity_graph_indicator.txt'), 'r') as f:
graph_indicator_temp = f.read().splitlines()
graph_indicator = [int(i) for i in graph_indicator_temp]
graph_indicator = np.array(graph_indicator)
with open(os.path.join(self.raw_dir, 'Mutagenicity_graph_labels.txt'), 'r') as f:
graph_labels_temp = f.read().splitlines()
graph_labels = [int(i) for i in graph_labels_temp]
data_list = []
for i in range(1, 4338):
idx = np.where(graph_indicator == i)
graph_len = len(idx[0])
adj = adj_all[idx[0][0]:idx[0][0] + graph_len, idx[0][0]:idx[0][0] + graph_len]
label = int(graph_labels[i - 1] == 1)
feature = nodes_all[idx[0][0]:idx[0][0] + graph_len]
nb_clss = 14
targets = np.array(feature).reshape(-1)
one_hot_feature = np.eye(nb_clss)[targets]
data_example = Data(x=torch.from_numpy(one_hot_feature).float(),
edge_index=dense_to_sparse(torch.from_numpy(adj))[0],
y=label)
data_list.append(data_example)
torch.save(self.collate(data_list), self.processed_paths[0])
class SentiGraphDataset(InMemoryDataset):
def __init__(self, root, name, transform=None, pre_transform=undirected_graph):
self.name = name
super(SentiGraphDataset, self).__init__(root, transform, pre_transform)
self.data, self.slices, self.supplement = torch.load(self.processed_paths[0])
@property
def raw_dir(self):
return osp.join(self.root, self.name, 'raw')
@property
def processed_dir(self):
return osp.join(self.root, self.name, 'processed')
@property
def raw_file_names(self):
return ['node_features', 'node_indicator', 'sentence_tokens', 'edge_index',
'graph_labels', 'split_indices']
@property
def processed_file_names(self):
return ['data.pt']
def process(self):
# Read data into huge `Data` list.
self.data, self.slices, self.supplement \
= read_sentigraph_data(self.raw_dir, self.name)
if self.pre_filter is not None:
data_list = [self.get(idx) for idx in range(len(self))]
data_list = [data for data in data_list if self.pre_filter(data)]
self.data, self.slices = self.collate(data_list)
if self.pre_transform is not None:
data_list = [self.get(idx) for idx in range(len(self))]
data_list = [self.pre_transform(data) for data in data_list]
self.data, self.slices = self.collate(data_list)
torch.save((self.data, self.slices, self.supplement), self.processed_paths[0])
class SynGraphDataset(InMemoryDataset):
def __init__(self, root, name, transform=None, pre_transform=None):
self.name = name
super(SynGraphDataset, self).__init__(root, transform, pre_transform)
self.data, self.slices = torch.load(self.processed_paths[0])
@property
def raw_dir(self):
return osp.join(self.root, self.name, 'raw')
@property
def processed_dir(self):
return osp.join(self.root, self.name, 'processed')
@property
def raw_file_names(self):
return [f"{self.name}.pkl"]
@property
def processed_file_names(self):
return ['data.pt']
def process(self):
# Read data into huge `Data` list.
data = read_syn_data(self.raw_dir, self.name)
data = data if self.pre_transform is None else self.pre_transform(data)
torch.save(self.collate([data]), self.processed_paths[0])
class BA2MotifDataset(InMemoryDataset):
def __init__(self, root, name, transform=None, pre_transform=None):
self.name = name
super(BA2MotifDataset, self).__init__(root, transform, pre_transform)
self.data, self.slices = torch.load(self.processed_paths[0])
@property
def raw_dir(self):
return osp.join(self.root, self.name, 'raw')
@property
def processed_dir(self):
return osp.join(self.root, self.name, 'processed')
@property
def raw_file_names(self):
return [f"{self.name}.pkl"]
@property
def processed_file_names(self):
return ['data.pt']
def process(self):
# Read data into huge `Data` list.
data_list = read_ba2motif_data(self.raw_dir, self.name)
if self.pre_filter is not None:
data_list = [self.get(idx) for idx in range(len(self))]
data_list = [data for data in data_list if self.pre_filter(data)]
self.data, self.slices = self.collate(data_list)
if self.pre_transform is not None:
data_list = [self.get(idx) for idx in range(len(self))]
data_list = [self.pre_transform(data) for data in data_list]
self.data, self.slices = self.collate(data_list)
torch.save(self.collate(data_list), self.processed_paths[0])
def load_MUTAG(dataset_dir, dataset_name):
""" 188 molecules where label = 1 denotes mutagenic effect """
dataset = MUTAGDataset(root=dataset_dir, name=dataset_name)
return dataset
class BA_LRP(InMemoryDataset):
def __init__(self, root, num_per_class, transform=None, pre_transform=None):
self.num_per_class = num_per_class
super().__init__(root, transform, pre_transform)
self.data, self.slices = torch.load(self.processed_paths[0])
@property
def processed_file_names(self):
return [f'data{self.num_per_class}.pt']
def gen_class1(self):
x = torch.tensor([[1], [1]], dtype=torch.float)
edge_index = torch.tensor([[0, 1], [1, 0]], dtype=torch.long)
data = Data(x=x, edge_index=edge_index, y=torch.tensor([[0]], dtype=torch.float))
for i in range(2, 20):
data.x = torch.cat([data.x, torch.tensor([[1]], dtype=torch.float)], dim=0)
deg = torch.stack([(data.edge_index[0] == node_idx).float().sum() for node_idx in range(i)], dim=0)
sum_deg = deg.sum(dim=0, keepdim=True)
probs = (deg / sum_deg).unsqueeze(0)
prob_dist = torch.distributions.Categorical(probs)
node_pick = prob_dist.sample().squeeze()
data.edge_index = torch.cat([data.edge_index,
torch.tensor([[node_pick, i], [i, node_pick]], dtype=torch.long)], dim=1)
return data
def gen_class2(self):
x = torch.tensor([[1], [1]], dtype=torch.float)
edge_index = torch.tensor([[0, 1], [1, 0]], dtype=torch.long)
data = Data(x=x, edge_index=edge_index, y=torch.tensor([[1]], dtype=torch.float))
epsilon = 1e-30
for i in range(2, 20):
data.x = torch.cat([data.x, torch.tensor([[1]], dtype=torch.float)], dim=0)
deg_reciprocal = torch.stack([1 / ((data.edge_index[0] == node_idx).float().sum() + epsilon) for node_idx in range(i)], dim=0)
sum_deg_reciprocal = deg_reciprocal.sum(dim=0, keepdim=True)
probs = (deg_reciprocal / sum_deg_reciprocal).unsqueeze(0)
prob_dist = torch.distributions.Categorical(probs)
node_pick = -1
for _ in range(1 if i % 5 != 4 else 2):
new_node_pick = prob_dist.sample().squeeze()
while new_node_pick == node_pick:
new_node_pick = prob_dist.sample().squeeze()
node_pick = new_node_pick
data.edge_index = torch.cat([data.edge_index,
torch.tensor([[node_pick, i], [i, node_pick]], dtype=torch.long)], dim=1)
return data
def process(self):
data_list = []
for i in range(self.num_per_class):
data_list.append(self.gen_class1())
data_list.append(self.gen_class2())
data, slices = self.collate(data_list)
torch.save((data, slices), self.processed_paths[0])
def load_syn_data(dataset_dir, dataset_name):
""" The synthetic dataset """
if dataset_name.lower() == 'BA_2Motifs'.lower():
dataset = BA2MotifDataset(root=dataset_dir, name=dataset_name)
elif dataset_name.lower() == 'BA_LRP'.lower():
dataset = BA_LRP(root=os.path.join(dataset_dir, 'ba_lrp'), num_per_class=10000)
else:
dataset = SynGraphDataset(root=dataset_dir, name=dataset_name)
dataset.node_type_dict = {k: v for k, v in enumerate(range(dataset.num_classes))}
dataset.node_color = None
return dataset
def load_MolecueNet(dataset_dir, dataset_name, task=None):
""" Attention the multi-task problems not solved yet """
molecule_net_dataset_names = {name.lower(): name for name in MoleculeNet.names.keys()}
dataset = MoleculeNet(root=dataset_dir, name=molecule_net_dataset_names[dataset_name.lower()])
dataset.data.x = dataset.data.x.float()
if task is None:
dataset.data.y = dataset.data.y.squeeze().long()
else:
dataset.data.y = dataset.data.y[task].long()
dataset.node_type_dict = None
dataset.node_color = None
return dataset
def load_SeniGraph(dataset_dir, dataset_name):
dataset = SentiGraphDataset(root=dataset_dir, name=dataset_name)
return dataset
def get_dataloader(dataset, batch_size, random_split_flag=True, data_split_ratio=None, seed=2):
"""
Args:
dataset:
batch_size: int
random_split_flag: bool
data_split_ratio: list, training, validation and testing ratio
seed: random seed to split the dataset randomly
Returns:
a dictionary of training, validation, and testing dataLoader
"""
if not random_split_flag and hasattr(dataset, 'supplement'):
assert 'split_indices' in dataset.supplement.keys(), "split idx"
split_indices = dataset.supplement['split_indices']
train_indices = torch.where(split_indices == 0)[0].numpy().tolist()
dev_indices = torch.where(split_indices == 1)[0].numpy().tolist()
test_indices = torch.where(split_indices == 2)[0].numpy().tolist()
train = Subset(dataset, train_indices)
eval = Subset(dataset, dev_indices)
test = Subset(dataset, test_indices)
else:
num_train = int(data_split_ratio[0] * len(dataset))
num_eval = int(data_split_ratio[1] * len(dataset))
num_test = len(dataset) - num_train - num_eval
train, eval, test = random_split(dataset, lengths=[num_train, num_eval, num_test],
generator=torch.Generator().manual_seed(seed))
dataloader = dict()
dataloader['train'] = DataLoader(train, batch_size=batch_size, shuffle=True)
dataloader['eval'] = DataLoader(eval, batch_size=batch_size, shuffle=False)
dataloader['test'] = DataLoader(test, batch_size=batch_size, shuffle=False)
return dataloader
if __name__ == '__main__':
get_dataset(dataset_dir='./datasets', dataset_name='bbbp')