-
Notifications
You must be signed in to change notification settings - Fork 26
/
train.py
199 lines (162 loc) · 6.76 KB
/
train.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
import numpy
import argparse
import os.path as osp
import random
import nni
import torch
from torch_geometric.utils import dropout_adj, degree, to_undirected
from simple_param.sp import SimpleParam
from pGRACE.model import Encoder, GRACE
from pGRACE.functional import drop_feature, drop_edge_weighted, \
degree_drop_weights, \
evc_drop_weights, pr_drop_weights, \
feature_drop_weights, drop_feature_weighted_2, feature_drop_weights_dense
from pGRACE.eval import log_regression, MulticlassEvaluator
from pGRACE.utils import get_base_model, get_activation, \
generate_split, compute_pr, eigenvector_centrality
from pGRACE.dataset import get_dataset
def train():
model.train()
optimizer.zero_grad()
def drop_edge(idx: int):
global drop_weights
if param['drop_scheme'] == 'uniform':
return dropout_adj(data.edge_index, p=param[f'drop_edge_rate_{idx}'])[0]
elif param['drop_scheme'] in ['degree', 'evc', 'pr']:
return drop_edge_weighted(data.edge_index, drop_weights, p=param[f'drop_edge_rate_{idx}'], threshold=0.7)
else:
raise Exception(f'undefined drop scheme: {param["drop_scheme"]}')
edge_index_1 = drop_edge(1)
edge_index_2 = drop_edge(2)
x_1 = drop_feature(data.x, param['drop_feature_rate_1'])
x_2 = drop_feature(data.x, param['drop_feature_rate_2'])
if param['drop_scheme'] in ['pr', 'degree', 'evc']:
x_1 = drop_feature_weighted_2(data.x, feature_weights, param['drop_feature_rate_1'])
x_2 = drop_feature_weighted_2(data.x, feature_weights, param['drop_feature_rate_2'])
z1 = model(x_1, edge_index_1)
z2 = model(x_2, edge_index_2)
loss = model.loss(z1, z2, batch_size=1024 if args.dataset == 'Coauthor-Phy' else None)
loss.backward()
optimizer.step()
return loss.item()
def test(final=False):
model.eval()
z = model(data.x, data.edge_index)
evaluator = MulticlassEvaluator()
if args.dataset == 'WikiCS':
accs = []
for i in range(20):
acc = log_regression(z, dataset, evaluator, split=f'wikics:{i}', num_epochs=800)['acc']
accs.append(acc)
acc = sum(accs) / len(accs)
else:
acc = log_regression(z, dataset, evaluator, split='rand:0.1', num_epochs=3000, preload_split=split)['acc']
if final and use_nni:
nni.report_final_result(acc)
elif use_nni:
nni.report_intermediate_result(acc)
return acc
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--device', type=str, default='cuda:2')
parser.add_argument('--dataset', type=str, default='WikiCS')
parser.add_argument('--param', type=str, default='local:wikics.json')
parser.add_argument('--seed', type=int, default=39788)
parser.add_argument('--verbose', type=str, default='train,eval,final')
parser.add_argument('--save_split', type=str, nargs='?')
parser.add_argument('--load_split', type=str, nargs='?')
default_param = {
'learning_rate': 0.01,
'num_hidden': 256,
'num_proj_hidden': 32,
'activation': 'prelu',
'base_model': 'GCNConv',
'num_layers': 2,
'drop_edge_rate_1': 0.3,
'drop_edge_rate_2': 0.4,
'drop_feature_rate_1': 0.1,
'drop_feature_rate_2': 0.0,
'tau': 0.4,
'num_epochs': 3000,
'weight_decay': 1e-5,
'drop_scheme': 'degree',
}
# add hyper-parameters into parser
param_keys = default_param.keys()
for key in param_keys:
parser.add_argument(f'--{key}', type=type(default_param[key]), nargs='?')
args = parser.parse_args()
# parse param
sp = SimpleParam(default=default_param)
param = sp(source=args.param, preprocess='nni')
# merge cli arguments and parsed param
for key in param_keys:
if getattr(args, key) is not None:
param[key] = getattr(args, key)
use_nni = args.param == 'nni'
if use_nni and args.device != 'cpu':
args.device = 'cuda'
torch_seed = args.seed
torch.manual_seed(torch_seed)
random.seed(12345)
device = torch.device(args.device)
path = osp.expanduser('~/datasets')
path = osp.join(path, args.dataset)
dataset = get_dataset(path, args.dataset)
data = dataset[0]
data = data.to(device)
# generate split
split = generate_split(data.num_nodes, train_ratio=0.1, val_ratio=0.1)
if args.save_split:
torch.save(split, args.save_split)
elif args.load_split:
split = torch.load(args.load_split)
encoder = Encoder(dataset.num_features, param['num_hidden'], get_activation(param['activation']),
base_model=get_base_model(param['base_model']), k=param['num_layers']).to(device)
model = GRACE(encoder, param['num_hidden'], param['num_proj_hidden'], param['tau']).to(device)
optimizer = torch.optim.Adam(
model.parameters(),
lr=param['learning_rate'],
weight_decay=param['weight_decay']
)
if param['drop_scheme'] == 'degree':
drop_weights = degree_drop_weights(data.edge_index).to(device)
elif param['drop_scheme'] == 'pr':
drop_weights = pr_drop_weights(data.edge_index, aggr='sink', k=200).to(device)
elif param['drop_scheme'] == 'evc':
drop_weights = evc_drop_weights(data).to(device)
else:
drop_weights = None
if param['drop_scheme'] == 'degree':
edge_index_ = to_undirected(data.edge_index)
node_deg = degree(edge_index_[1])
if args.dataset == 'WikiCS':
feature_weights = feature_drop_weights_dense(data.x, node_c=node_deg).to(device)
else:
feature_weights = feature_drop_weights(data.x, node_c=node_deg).to(device)
elif param['drop_scheme'] == 'pr':
node_pr = compute_pr(data.edge_index)
if args.dataset == 'WikiCS':
feature_weights = feature_drop_weights_dense(data.x, node_c=node_pr).to(device)
else:
feature_weights = feature_drop_weights(data.x, node_c=node_pr).to(device)
elif param['drop_scheme'] == 'evc':
node_evc = eigenvector_centrality(data)
if args.dataset == 'WikiCS':
feature_weights = feature_drop_weights_dense(data.x, node_c=node_evc).to(device)
else:
feature_weights = feature_drop_weights(data.x, node_c=node_evc).to(device)
else:
feature_weights = torch.ones((data.x.size(1),)).to(device)
log = args.verbose.split(',')
for epoch in range(1, param['num_epochs'] + 1):
loss = train()
if 'train' in log:
print(f'(T) | Epoch={epoch:03d}, loss={loss:.4f}')
if epoch % 100 == 0:
acc = test()
if 'eval' in log:
print(f'(E) | Epoch={epoch:04d}, avg_acc = {acc}')
acc = test(final=True)
if 'final' in log:
print(f'{acc}')