-
Notifications
You must be signed in to change notification settings - Fork 1
/
datasets.py
271 lines (214 loc) · 8.94 KB
/
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
import os.path as osp
import torch
import numpy as np
from torch_geometric.data import InMemoryDataset, Data
from torch_geometric.io import read_txt_array
import torch.nn.functional as F
import scipy
import pickle as pkl
import csv
import json
import warnings
warnings.filterwarnings('ignore', category=DeprecationWarning)
class CitationDataset(InMemoryDataset):
def __init__(self,
root,
name,
transform=None,
pre_transform=None,
pre_filter=None):
self.name = name
self.root = root
super(CitationDataset, self).__init__(root, transform, pre_transform, pre_filter)
self.data, self.slices = torch.load(self.processed_paths[0])
@property
def raw_file_names(self):
return ["docs.txt", "edgelist.txt", "labels.txt"]
@property
def processed_file_names(self):
return ['data.pt']
def download(self):
pass
def process(self):
edge_path = osp.join(self.raw_dir, '{}_edgelist.txt'.format(self.name))
edge_index = read_txt_array(edge_path, sep=',', dtype=torch.long).t()
docs_path = osp.join(self.raw_dir, '{}_docs.txt'.format(self.name))
f = open(docs_path, 'rb')
content_list = []
for line in f.readlines():
line = str(line, encoding="utf-8")
content_list.append(line.split(","))
x = np.array(content_list, dtype=float)
x = torch.from_numpy(x).to(torch.float)
label_path = osp.join(self.raw_dir, '{}_labels.txt'.format(self.name))
f = open(label_path, 'rb')
content_list = []
for line in f.readlines():
line = str(line, encoding="utf-8")
line = line.replace("\r", "").replace("\n", "")
content_list.append(line)
y = np.array(content_list, dtype=int)
y = torch.from_numpy(y).to(torch.int64)
data_list = []
data = Data(edge_index=edge_index, x=x, y=y)
random_node_indices = np.random.permutation(y.shape[0])
training_size = int(len(random_node_indices) * 0.8)
val_size = int(len(random_node_indices) * 0.1)
train_node_indices = random_node_indices[:training_size]
val_node_indices = random_node_indices[training_size:training_size + val_size]
test_node_indices = random_node_indices[training_size + val_size:]
train_masks = torch.zeros([y.shape[0]], dtype=torch.bool)
train_masks[train_node_indices] = 1
val_masks = torch.zeros([y.shape[0]], dtype=torch.bool)
val_masks[val_node_indices] = 1
test_masks = torch.zeros([y.shape[0]], dtype=torch.bool)
test_masks[test_node_indices] = 1
data.train_mask = train_masks
data.val_mask = val_masks
data.test_mask = test_masks
if self.pre_transform is not None:
data = self.pre_transform(data)
data_list.append(data)
data, slices = self.collate([data])
torch.save((data, slices), self.processed_paths[0])
class EllipticDataset(InMemoryDataset):
def __init__(self,
root,
name,
transform=None,
pre_transform=None,
pre_filter=None):
self.name = name
self.root = root
super(EllipticDataset, self).__init__(root, transform, pre_transform, pre_filter)
self.data, self.slices = torch.load(self.processed_paths[0])
@property
def raw_file_names(self):
return [".pkl"]
@property
def processed_file_names(self):
return ['data.pt']
def download(self):
pass
def process(self):
path = osp.join(self.raw_dir, '{}.pkl'.format(self.name))
result = pkl.load(open(path, 'rb'))
A, label, features = result
label = label + 1
edge_index = torch.tensor(np.array(A.nonzero()), dtype=torch.long)
features = np.array(features)
x = torch.from_numpy(features).to(torch.float)
y = torch.tensor(label).to(torch.int64)
data_list = []
data = Data(edge_index=edge_index, x=x, y=y)
random_node_indices = np.random.permutation(y.shape[0])
training_size = int(len(random_node_indices) * 0.8)
val_size = int(len(random_node_indices) * 0.1)
train_node_indices = random_node_indices[:training_size]
val_node_indices = random_node_indices[training_size:training_size + val_size]
test_node_indices = random_node_indices[training_size + val_size:]
train_masks = torch.zeros([y.shape[0]], dtype=torch.bool)
train_masks[train_node_indices] = 1
val_masks = torch.zeros([y.shape[0]], dtype=torch.bool)
val_masks[val_node_indices] = 1
test_masks = torch.zeros([y.shape[0]], dtype=torch.bool)
test_masks[test_node_indices] = 1
data.train_mask = train_masks
data.val_mask = val_masks
data.test_mask = test_masks
if self.pre_transform is not None:
data = self.pre_transform(data)
data_list.append(data)
data, slices = self.collate([data])
torch.save((data, slices), self.processed_paths[0])
class TwitchDataset(InMemoryDataset):
def __init__(self,
root,
name,
transform=None,
pre_transform=None,
pre_filter=None):
self.name = name
self.root = root
super(TwitchDataset, self).__init__(root, transform, pre_transform, pre_filter)
self.data, self.slices = torch.load(self.processed_paths[0])
@property
def raw_file_names(self):
return ["edges.csv, features.json, target.csv"]
@property
def processed_file_names(self):
return ['data.pt']
def download(self):
pass
def load_twitch(self, lang):
assert lang in ('DE', 'EN', 'FR'), 'Invalid dataset'
filepath = self.raw_dir
label = []
node_ids = []
src = []
targ = []
uniq_ids = set()
with open(f"{filepath}/musae_{lang}_target.csv", 'r') as f:
reader = csv.reader(f)
next(reader)
for row in reader:
node_id = int(row[5])
# handle FR case of non-unique rows
if node_id not in uniq_ids:
uniq_ids.add(node_id)
label.append(int(row[2]=="True"))
node_ids.append(int(row[5]))
node_ids = np.array(node_ids, dtype=np.int32)
with open(f"{filepath}/musae_{lang}_edges.csv", 'r') as f:
reader = csv.reader(f)
next(reader)
for row in reader:
src.append(int(row[0]))
targ.append(int(row[1]))
with open(f"{filepath}/musae_{lang}_features.json", 'r') as f:
j = json.load(f)
src = np.array(src)
targ = np.array(targ)
label = np.array(label)
inv_node_ids = {node_id:idx for (idx, node_id) in enumerate(node_ids)}
reorder_node_ids = np.zeros_like(node_ids)
for i in range(label.shape[0]):
reorder_node_ids[i] = inv_node_ids[i]
n = label.shape[0]
A = scipy.sparse.csr_matrix((np.ones(len(src)), (np.array(src), np.array(targ))), shape=(n,n))
features = np.zeros((n,3170))
for node, feats in j.items():
if int(node) >= n:
continue
features[int(node), np.array(feats, dtype=int)] = 1
new_label = label[reorder_node_ids]
label = new_label
return A, label, features
def process(self):
A, label, features = self.load_twitch(self.name)
edge_index = torch.tensor(np.array(A.nonzero()), dtype=torch.long)
features = np.array(features)
x = torch.from_numpy(features).to(torch.float)
y = torch.from_numpy(label).to(torch.int64)
data_list = []
data = Data(edge_index=edge_index, x=x, y=y)
random_node_indices = np.random.permutation(y.shape[0])
training_size = int(len(random_node_indices) * 0.8)
val_size = int(len(random_node_indices) * 0.1)
train_node_indices = random_node_indices[:training_size]
val_node_indices = random_node_indices[training_size:training_size + val_size]
test_node_indices = random_node_indices[training_size + val_size:]
train_masks = torch.zeros([y.shape[0]], dtype=torch.bool)
train_masks[train_node_indices] = 1
val_masks = torch.zeros([y.shape[0]], dtype=torch.bool)
val_masks[val_node_indices] = 1
test_masks = torch.zeros([y.shape[0]], dtype=torch.bool)
test_masks[test_node_indices] = 1
data.train_mask = train_masks
data.val_mask = val_masks
data.test_mask = test_masks
if self.pre_transform is not None:
data = self.pre_transform(data)
data_list.append(data)
data, slices = self.collate([data])
torch.save((data, slices), self.processed_paths[0])