-
Notifications
You must be signed in to change notification settings - Fork 12
/
dataset.py
195 lines (159 loc) · 7.34 KB
/
dataset.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
import numpy as np
import scipy.sparse as sp
import os.path as osp
import os
import urllib.request
import sys
import pickle as pkl
import networkx as nx
from utils import get_train_val_test
class Dataset():
"""Dataset class contains four citation network datasets "cora", "cora-ml", "citeseer" and "pubmed",
and one blog dataset "Polblogs".
The 'cora', 'cora-ml', 'poblogs' and 'citeseer' are downloaded from https://github.com/danielzuegner/gnn-meta-attack/tree/master/data, and 'pubmed' is from https://github.com/tkipf/gcn/tree/master/gcn/data.
Parameters
----------
root :
root directory where the dataset should be saved.
name :
dataset name, it can be choosen from ['cora', 'citeseer', 'cora_ml', 'polblogs', 'pubmed']
seed :
random seed for splitting training/validation/test.
--------
We can first create an instance of the Dataset class and then take out its attributes.
>>> from deeprobust.graph.data import Dataset
>>> data = Dataset(root='/tmp/', name='cora')
>>> adj, features, labels = data.adj, data.features, data.labels
>>> idx_train, idx_val, idx_test = data.idx_train, data.idx_val, data.idx_test
"""
def __init__(self, root, name, seed=None):
self.name = name.lower()
assert self.name in ['cora', 'citeseer', 'cora_ml', 'polblogs', 'pubmed'], \
'Currently only support cora, citeseer, cora_ml, polblogs, pubmed'
self.seed = seed
self.url = 'https://raw.githubusercontent.com/danielzuegner/gnn-meta-attack/master/data/%s.npz' % self.name
self.root = osp.expanduser(osp.normpath(root))
self.data_folder = osp.join(root, self.name)
self.data_filename = self.data_folder + '.npz'
self.adj, self.features, self.labels = self.load_data()
self.idx_train, self.idx_val, self.idx_test = self.get_train_val_test()
def get_train_val_test(self):
"""Get training, validation, test splits
"""
return get_train_val_test(nnodes=self.adj.shape[0], val_size=0.1, test_size=0.8, stratify=self.labels, seed=self.seed)
def load_data(self):
print('Loading {} dataset...'.format(self.name))
if self.name == 'pubmed':
return self.load_pubmed()
if not osp.exists(self.data_filename):
self.download_npz()
adj, features, labels = self.get_adj()
return adj, features, labels
def download_npz(self):
"""Download adjacen matrix npz file from self.url.
"""
print('Dowloading from {} to {}'.format(self.url, self.data_filename))
try:
urllib.request.urlretrieve(self.url, self.data_filename)
except:
raise Exception('''Download failed! Make sure you have stable Internet connection and enter the right name''')
def download_pubmed(self, name):
url = 'https://raw.githubusercontent.com/tkipf/gcn/master/gcn/data/'
try:
urllib.request.urlretrieve(url + name, osp.join(self.root, name))
except:
raise Exception('''Download failed! Make sure you have stable Internet connection and enter the right name''')
def load_pubmed(self):
dataset = 'pubmed'
names = ['x', 'y', 'tx', 'ty', 'allx', 'ally', 'graph']
objects = []
for i in range(len(names)):
name = "ind.{}.{}".format(dataset, names[i])
data_filename = osp.join(self.root, name)
if not osp.exists(data_filename):
self.download_pubmed(name)
with open(data_filename, 'rb') as f:
if sys.version_info > (3, 0):
objects.append(pkl.load(f, encoding='latin1'))
else:
objects.append(pkl.load(f))
x, y, tx, ty, allx, ally, graph = tuple(objects)
test_idx_file = "ind.{}.test.index".format(dataset)
if not osp.exists(osp.join(self.root, test_idx_file)):
self.download_pubmed(test_idx_file)
test_idx_reorder = parse_index_file(osp.join(self.root, test_idx_file))
test_idx_range = np.sort(test_idx_reorder)
features = sp.vstack((allx, tx)).tolil()
features[test_idx_reorder, :] = features[test_idx_range, :]
adj = nx.adjacency_matrix(nx.from_dict_of_lists(graph))
labels = np.vstack((ally, ty))
labels[test_idx_reorder, :] = labels[test_idx_range, :]
labels = np.where(labels)[1]
return adj, features, labels
def get_adj(self):
adj, features, labels = self.load_npz(self.data_filename)
adj = adj + adj.T
adj = adj.tolil()
adj[adj > 1] = 1
lcc = self.largest_connected_components(adj)
adj = adj[lcc][:, lcc]
features = features[lcc]
labels = labels[lcc]
assert adj.sum(0).A1.min() > 0, "Graph contains singleton nodes"
# whether to set diag=0?
adj.setdiag(0)
adj = adj.astype("float32").tocsr()
adj.eliminate_zeros()
assert np.abs(adj - adj.T).sum() == 0, "Input graph is not symmetric"
assert adj.max() == 1 and len(np.unique(adj[adj.nonzero()].A1)) == 1, "Graph must be unweighted"
return adj, features, labels
def load_npz(self, file_name, is_sparse=True):
with np.load(file_name) as loader:
# loader = dict(loader)
if is_sparse:
adj = sp.csr_matrix((loader['adj_data'], loader['adj_indices'],
loader['adj_indptr']), shape=loader['adj_shape'])
if 'attr_data' in loader:
features = sp.csr_matrix((loader['attr_data'], loader['attr_indices'],
loader['attr_indptr']), shape=loader['attr_shape'])
else:
features = None
labels = loader.get('labels')
else:
adj = loader['adj_data']
if 'attr_data' in loader:
features = loader['attr_data']
else:
features = None
labels = loader.get('labels')
if features is None:
features = np.eye(adj.shape[0])
features = sp.csr_matrix(features, dtype=np.float32)
return adj, features, labels
def largest_connected_components(self, adj, n_components=1):
"""Select k largest connected components.
Parameters
----------
adj : scipy.sparse.csr_matrix
input adjacency matrix
n_components : int
n largest connected components we want to select
"""
_, component_indices = sp.csgraph.connected_components(adj)
component_sizes = np.bincount(component_indices)
components_to_keep = np.argsort(component_sizes)[::-1][:n_components] # reverse order to sort descending
nodes_to_keep = [
idx for (idx, component) in enumerate(component_indices) if component in components_to_keep]
print("Selecting {0} largest connected components".format(n_components))
return nodes_to_keep
def __repr__(self):
return '{0}(adj_shape={1}, feature_shape={2})'.format(self.name, self.adj.shape, self.features.shape)
def onehot(self, labels):
eye = np.identity(labels.max() + 1)
onehot_mx = eye[labels]
return onehot_mx
def parse_index_file(filename):
index = []
for line in open(filename):
index.append(int(line.strip()))
return index