-
Notifications
You must be signed in to change notification settings - Fork 4
/
data.py
342 lines (273 loc) · 11.4 KB
/
data.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
# Inspired by https://github.com/deepfindr/gnn-project
# dataset classes and load function
import torch
from torch_geometric.data import Dataset, Data
from torch_geometric.datasets import TUDataset
from torch.nn.functional import one_hot
import os
import shutil
class Mutagenicity(Dataset):
def __init__(self, root, transform=None, pre_transform=None):
"""
root = Where the dataset should be stored. This folder is split
into raw_dir (downloaded dataset) and processed_dir (processed data).
"""
self.root = root
self.graph_count = 4308
super(Mutagenicity, self).__init__(root, transform, pre_transform)
@property
def raw_file_names(self):
""" If this file exists in raw_dir, the download is not triggered.
(The download func. is not implemented here)
"""
return []
@property
def processed_file_names(self):
""" If these files are found in processed_dir, processing is skipped"""
return [f'data_{i}.pt' for i in range(self.graph_count)]
def download(self):
pass
def process(self):
graphs = TUDataset(root=os.path.join(self.root, 'tudataset'), name='Mutagenicity')
# we remove graphs if they include node classes which has frequency less than or equal to 50.
x_all = []
for graph in graphs:
x_all.append(graph.x.sum(dim=0))
x_all = torch.stack(x_all).sum(dim=0)
atoms_to_keep = torch.where(x_all > 50)[0]
print(f'There are {len(atoms_to_keep)} valid number of labels!')
count = 0
for i, graph in enumerate(graphs):
# Create data object
if graph.x.sum() == graph.x[:, atoms_to_keep].sum():
# Create data
x = graph.x[:, atoms_to_keep]
data = Data(edge_index=graph.edge_index.clone(),
y=torch.tensor(graph.y.item()), # 0 is mutagenetic, which is undesired for drug discovery.
# node_labels=self.label_from_one_hot(x),
x=x.clone(),
num_nodes=graph.num_nodes
)
torch.save(data, os.path.join(self.processed_dir, f'data_{count}.pt'))
count += 1
print(f"There are {count} graphs!")
# Delete TUDataset.
del i, graph, graphs
shutil.rmtree(os.path.join(self.root, 'tudataset'))
def len(self):
return self.graph_count
def get(self, idx):
""" - Equivalent to __getitem__ in pytorch
- Is not needed for PyG's InMemoryDataset
"""
data = torch.load(os.path.join(self.processed_dir,
f'data_{idx}.pt'))
return data
@staticmethod
def one_hot_from_label(labels):
return one_hot(labels, num_classes=10)
@staticmethod
def label_from_one_hot(one_hot):
return torch.argmax(one_hot, dim=1)
@staticmethod
def num_classes():
return 10
class AIDS(Dataset):
def __init__(self, root, transform=None, pre_transform=None):
"""
root = Where the dataset should be stored. This folder is split
into raw_dir (downloaded dataset) and processed_dir (processed data).
"""
self.root = root
self.graph_count = 1837
super(AIDS, self).__init__(root, transform, pre_transform)
@property
def raw_file_names(self):
""" If this file exists in raw_dir, the download is not triggered.
(The download func. is not implemented here)
"""
return []
@property
def processed_file_names(self):
""" If these files are found in processed_dir, processing is skipped"""
return [f'data_{i}.pt' for i in range(self.graph_count)]
def download(self):
pass
def process(self):
graphs = TUDataset(root=os.path.join(self.root, 'tudataset'), name='AIDS')
# we remove graphs if they include node classes which has frequency less than or equal to 50.
x_all = []
for graph in graphs:
x_all.append(graph.x.sum(dim=0))
x_all = torch.stack(x_all).sum(dim=0)
atoms_to_keep = torch.where(x_all > 50)[0]
print(f'There are {len(atoms_to_keep)} valid number of labels!')
count = 0
for i, graph in enumerate(graphs):
if graph.x.sum() == graph.x[:, atoms_to_keep].sum():
# Create data
x = graph.x[:, atoms_to_keep]
data = Data(edge_index=graph.edge_index.clone(),
edge_attr=torch.argmax(graph.edge_attr, dim=1).clone(),
y=torch.tensor(0) if graph.y.item() else torch.tensor(1), # Note that original graph label 0 means active against aids, which is desired. So we swap the order.
# node_labels=self.label_from_one_hot(x),
x=x.clone(),
num_nodes=graph.num_nodes,
)
torch.save(data, os.path.join(self.processed_dir, f'data_{count}.pt'))
count += 1
print(f"There are {count} graphs!")
# Delete TUDataset.
del i, graph, graphs
shutil.rmtree(os.path.join(self.root, 'tudataset'))
def len(self):
return self.graph_count
def get(self, idx):
""" - Equivalent to __getitem__ in pytorch
- Is not needed for PyG's InMemoryDataset
"""
data = torch.load(os.path.join(self.processed_dir,
f'data_{idx}.pt'))
return data
@staticmethod
def one_hot_from_label(labels):
return one_hot(labels, num_classes=9)
@staticmethod
def label_from_one_hot(one_hot):
return torch.argmax(one_hot, dim=1)
@staticmethod
def num_classes():
# return 38
return 9
class NCI1(Dataset):
def __init__(self, root, transform=None, pre_transform=None):
"""
root = Where the dataset should be stored. This folder is split
into raw_dir (downloaded dataset) and processed_dir (processed data).
"""
self.root = root
self.graph_count = 3978
super(NCI1, self).__init__(root, transform, pre_transform)
@property
def raw_file_names(self):
""" If this file exists in raw_dir, the download is not triggered.
(The download func. is not implemented here)
"""
return []
@property
def processed_file_names(self):
""" If these files are found in processed_dir, processing is skipped"""
return [f'data_{i}.pt' for i in range(self.graph_count)]
def download(self):
pass
def process(self):
graphs = TUDataset(root=os.path.join(self.root, 'tudataset'), name='NCI1')
# we remove graphs if they include node classes which has frequency less than or equal to 50.
x_all = []
for graph in graphs:
x_all.append(graph.x.sum(dim=0))
x_all = torch.stack(x_all).sum(dim=0)
atoms_to_keep = torch.where(x_all > 50)[0]
print(f'There are {len(atoms_to_keep)} valid number of labels!')
count = 0
for i, graph in enumerate(graphs):
# Create data object
if graph.x.sum() == graph.x[:, atoms_to_keep].sum():
x = graph.x[:, atoms_to_keep]
data = Data(edge_index=graph.edge_index.clone(),
y=torch.tensor(0) if graph.y.item() else torch.tensor(1), # Note that original graph label 0 means active against cancer, which is desired. So we swap the order.
# node_labels=self.label_from_one_hot(x),
x=x.clone(),
num_nodes=graph.num_nodes
)
torch.save(data, os.path.join(self.processed_dir, f'data_{count}.pt'))
count += 1
print(f"There are {count} graphs!")
# Delete TUDataset.
del i, graph, graphs
shutil.rmtree(os.path.join(self.root, 'tudataset'))
def len(self):
return self.graph_count
def get(self, idx):
""" - Equivalent to __getitem__ in pytorch
- Is not needed for PyG's InMemoryDataset
"""
data = torch.load(os.path.join(self.processed_dir,
f'data_{idx}.pt'))
return data
@staticmethod
def one_hot_from_label(labels):
return one_hot(labels, num_classes=10)
@staticmethod
def label_from_one_hot(one_hot):
return torch.argmax(one_hot, dim=1)
@staticmethod
def num_classes():
# return 37
return 10
class PROTEINS(Dataset):
def __init__(self, root, transform=None, pre_transform=None):
"""
root = Where the dataset should be stored. This folder is split
into raw_dir (downloaded dataset) and processed_dir (processed data).
"""
self.root = root
self.graph_count = 1113
super(PROTEINS, self).__init__(root, transform, pre_transform)
@property
def raw_file_names(self):
""" If this file exists in raw_dir, the download is not triggered.
(The download func. is not implemented here)
"""
return []
@property
def processed_file_names(self):
""" If these files are found in processed_dir, processing is skipped"""
return [f'data_{i}.pt' for i in range(self.graph_count)]
def download(self):
pass
def process(self):
graphs = TUDataset(root=os.path.join(self.root, 'tudataset'), name='PROTEINS')
for i, graph in enumerate(graphs):
# Create data object
# assert torch.abs(torch.sum(graph.x, axis=1) - torch.ones(size=torch.sum(graph.x, axis=1).size())).sum().item() == 0
data = Data(edge_index=graph.edge_index.clone(),
y=torch.tensor(0) if graph.y.item() else torch.tensor(1), # Note that original graph label 0 means enzyme, which is desired. So we swap the order.
# node_labels=self.label_from_one_hot(graph.x),
x=graph.x.clone(),
num_nodes=graph.num_nodes
)
torch.save(data, os.path.join(self.processed_dir, f'data_{i}.pt'))
# Delete TUDataset.
del i, graph, graphs
shutil.rmtree(os.path.join(self.root, 'tudataset'))
def len(self):
return self.graph_count
def get(self, idx):
""" - Equivalent to __getitem__ in pytorch
- Is not needed for PyG's InMemoryDataset
"""
data = torch.load(os.path.join(self.processed_dir,
f'data_{idx}.pt'))
return data
@staticmethod
def one_hot_from_label(labels):
return one_hot(labels, num_classes=3)
@staticmethod
def label_from_one_hot(one_hot):
return torch.argmax(one_hot, dim=1)
@staticmethod
def num_classes():
return 3
def load_dataset(dataset_name):
if dataset_name == 'mutagenicity':
dataset = Mutagenicity('data/mutagenicity')
elif dataset_name == 'aids':
dataset = AIDS('data/aids')
elif dataset_name == 'nci1':
dataset = NCI1('data/nci1')
elif dataset_name == 'proteins':
dataset = PROTEINS('data/proteins')
else:
raise ValueError(f'Dataset {dataset_name} not supported. ')
return dataset