-
Notifications
You must be signed in to change notification settings - Fork 17
/
utils.py
137 lines (120 loc) · 5.16 KB
/
utils.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
import numpy as np
import scipy.sparse as sp
import torch
import sys
import pickle as pkl
import networkx as nx
from normalization import fetch_normalization, row_normalize
from time import perf_counter
def parse_index_file(filename):
"""Parse index file."""
index = []
for line in open(filename):
index.append(int(line.strip()))
return index
def preprocess_citation(adj, features, normalization="FirstOrderGCN"):
adj_normalizer = fetch_normalization(normalization)
#features, Droot = row_normalize(features,adj)
features = row_normalize(features)
adj = adj_normalizer(adj)
return adj, features
def sparse_mx_to_torch_sparse_tensor(sparse_mx):
"""Convert a scipy sparse matrix to a torch sparse tensor."""
sparse_mx = sparse_mx.tocoo().astype(np.float32)
indices = torch.from_numpy(
np.vstack((sparse_mx.row, sparse_mx.col)).astype(np.int64))
values = torch.from_numpy(sparse_mx.data)
shape = torch.Size(sparse_mx.shape)
return torch.sparse.FloatTensor(indices, values, shape)
def load_citation(dataset_str="cora", normalization="NormAdj", cuda=True):
"""
Load Citation Networks Datasets.
"""
names = ['x', 'y', 'tx', 'ty', 'allx', 'ally', 'graph']
objects = []
for i in range(len(names)):
with open("data/ind.{}.{}".format(dataset_str.lower(), names[i]), '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_reorder = parse_index_file("data/ind.{}.test.index".format(dataset_str))
test_idx_range = np.sort(test_idx_reorder)
if dataset_str == 'citeseer':
# Fix citeseer dataset (there are some isolated nodes in the graph)
# Find isolated nodes, add them as zero-vecs into the right position
test_idx_range_full = range(min(test_idx_reorder), max(test_idx_reorder)+1)
tx_extended = sp.lil_matrix((len(test_idx_range_full), x.shape[1]))
tx_extended[test_idx_range-min(test_idx_range), :] = tx
tx = tx_extended
ty_extended = np.zeros((len(test_idx_range_full), y.shape[1]))
ty_extended[test_idx_range-min(test_idx_range), :] = ty
ty = ty_extended
features = sp.vstack((allx, tx)).tolil()
features[test_idx_reorder, :] = features[test_idx_range, :]
adj = nx.adjacency_matrix(nx.from_dict_of_lists(graph))
adj = adj + adj.T.multiply(adj.T > adj) - adj.multiply(adj.T > adj)
labels = np.vstack((ally, ty))
labels[test_idx_reorder, :] = labels[test_idx_range, :]
idx_test = test_idx_range.tolist()
idx_train = range(len(y))
idx_val = range(len(y), len(y)+500)
adj, features = preprocess_citation(adj, features, normalization)
# porting to pytorch
features = torch.FloatTensor(np.array(features.todense())).float()
labels = torch.LongTensor(labels)
labels = torch.max(labels, dim=1)[1]
adj = sparse_mx_to_torch_sparse_tensor(adj).float()
idx_train = torch.LongTensor(idx_train)
idx_val = torch.LongTensor(idx_val)
idx_test = torch.LongTensor(idx_test)
if cuda:
features = features.cuda()
adj = adj.cuda()
labels = labels.cuda()
idx_train = idx_train.cuda()
idx_val = idx_val.cuda()
idx_test = idx_test.cuda()
return adj, features, labels, idx_train, idx_val, idx_test
def sgc_precompute(features, adj, degree, alpha):
t = perf_counter()
ori_features = features
emb = features
for i in range(degree):
features = (1-alpha) * torch.spmm(adj, features)
emb += features
emb /= degree
emb = emb + alpha * ori_features
precompute_time = perf_counter()-t
return emb, precompute_time
def set_seed(seed, cuda):
np.random.seed(seed)
torch.manual_seed(seed)
if cuda: torch.cuda.manual_seed(seed)
def loadRedditFromNPZ(dataset_dir):
adj = sp.load_npz(dataset_dir+"reddit_adj.npz")
data = np.load(dataset_dir+"reddit.npz")
return adj, data['feats'], data['y_train'], data['y_val'], data['y_test'], data['train_index'], data['val_index'], data['test_index']
def load_reddit_data(data_path="data/", normalization="AugNormAdj", cuda=True):
adj, features, y_train, y_val, y_test, train_index, val_index, test_index = loadRedditFromNPZ("data/")
labels = np.zeros(adj.shape[0])
labels[train_index] = y_train
labels[val_index] = y_val
labels[test_index] = y_test
adj = adj + adj.T + sp.eye(adj.shape[0])
train_adj = adj[train_index, :][:, train_index]
features = torch.FloatTensor(np.array(features))
features = (features-features.mean(dim=0))/features.std(dim=0)
adj_normalizer = fetch_normalization(normalization)
adj = adj_normalizer(adj)
adj = sparse_mx_to_torch_sparse_tensor(adj).float()
train_adj = adj_normalizer(train_adj)
train_adj = sparse_mx_to_torch_sparse_tensor(train_adj).float()
labels = torch.LongTensor(labels)
if cuda:
adj = adj.cuda()
train_adj = train_adj.cuda()
features = features.cuda()
labels = labels.cuda()
return adj, train_adj, features, labels, train_index, val_index, test_index