/
train_eval.py
181 lines (134 loc) · 5.62 KB
/
train_eval.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
from __future__ import division
import time
import torch
import torch.nn.functional as F
from torch import tensor
from torch.optim import Adam
import numpy as np
from torch_geometric.utils import *
import networkx as nx
from tqdm import tqdm
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def index_to_mask(index, size):
mask = torch.zeros(size, dtype=torch.bool, device=index.device)
mask[index] = 1
return mask
def random_planetoid_splits(data, num_classes, lcc_mask):
# Set new random planetoid splits:
# * 20 * num_classes labels for training
# * 500 labels for validation
# * 1000 labels for testing
indices = []
if lcc_mask is not None:
for i in range(num_classes):
index = (data.y[lcc_mask] == i).nonzero().view(-1)
index = index[torch.randperm(index.size(0))]
indices.append(index)
else:
for i in range(num_classes):
index = (data.y == i).nonzero().view(-1)
index = index[torch.randperm(index.size(0))]
indices.append(index)
train_index = torch.cat([i[:20] for i in indices], dim=0)
rest_index = torch.cat([i[20:] for i in indices], dim=0)
rest_index = rest_index[torch.randperm(rest_index.size(0))]
data.train_mask = index_to_mask(train_index, size=data.num_nodes)
data.val_mask = index_to_mask(rest_index[:500], size=data.num_nodes)
data.test_mask = index_to_mask(rest_index[500:1500], size=data.num_nodes)
return data
def random_coauthor_amazon_splits(data, num_classes, lcc_mask):
# Set random coauthor/co-purchase splits:
# * 20 * num_classes labels for training
# * 30 * num_classes labels for validation
# rest labels for testing
indices = []
if lcc_mask is not None:
for i in range(num_classes):
index = (data.y[lcc_mask] == i).nonzero().view(-1)
index = index[torch.randperm(index.size(0))]
indices.append(index)
else:
for i in range(num_classes):
index = (data.y == i).nonzero().view(-1)
index = index[torch.randperm(index.size(0))]
indices.append(index)
train_index = torch.cat([i[:20] for i in indices], dim=0)
val_index = torch.cat([i[20:50] for i in indices], dim=0)
rest_index = torch.cat([i[50:] for i in indices], dim=0)
rest_index = rest_index[torch.randperm(rest_index.size(0))]
data.train_mask = index_to_mask(train_index, size=data.num_nodes)
data.val_mask = index_to_mask(val_index, size=data.num_nodes)
data.test_mask = index_to_mask(rest_index, size=data.num_nodes)
return data
def run(dataset, model, runs, epochs, lr, weight_decay, early_stopping,
permute_masks=None, logger=None, lcc=False, save_path=None):
val_losses, accs, durations = [], [], []
lcc_mask = None
if lcc: # select largest connected component
data_ori = dataset[0]
data_nx = to_networkx(data_ori)
data_nx = data_nx.to_undirected()
print("Original #nodes:", data_nx.number_of_nodes())
data_nx = data_nx.subgraph(max(nx.connected_components(data_nx), key=len))
print("#Nodes after lcc:", data_nx.number_of_nodes())
lcc_mask = list(data_nx.nodes)
data = dataset[0]
pbar = tqdm(range(runs), unit='run')
for _ in pbar:
if permute_masks is not None:
data = permute_masks(data, dataset.num_classes, lcc_mask)
data = data.to(device)
model.to(device).reset_parameters()
optimizer = Adam(model.parameters(), lr=lr, weight_decay=weight_decay)
if torch.cuda.is_available():
torch.cuda.synchronize()
t_start = time.perf_counter()
best_val_loss = float('inf')
test_acc = 0
val_loss_history = []
for epoch in range(1, epochs + 1):
out = train(model, optimizer, data)
eval_info = evaluate(model, data)
eval_info['epoch'] = epoch
if logger is not None:
logger(eval_info)
if eval_info['val_loss'] < best_val_loss:
best_val_loss = eval_info['val_loss']
test_acc = eval_info['test_acc']
val_loss_history.append(eval_info['val_loss'])
if early_stopping > 0 and epoch > epochs // 2:
tmp = tensor(val_loss_history[-(early_stopping + 1):-1])
if eval_info['val_loss'] > tmp.mean().item():
break
if torch.cuda.is_available():
torch.cuda.synchronize()
t_end = time.perf_counter()
val_losses.append(best_val_loss)
accs.append(test_acc)
durations.append(t_end - t_start)
loss, acc, duration = tensor(val_losses), tensor(accs), tensor(durations)
print('Val Loss: {:.4f}, Test Accuracy: {:.3f} ± {:.3f}, Duration: {:.3f}'.
format(loss.mean().item(),
acc.mean().item(),
acc.std().item(),
duration.mean().item()))
def train(model, optimizer, data):
model.train()
optimizer.zero_grad()
out = model(data)
loss = F.nll_loss(out[data.train_mask], data.y[data.train_mask])
loss.backward()
optimizer.step()
def evaluate(model, data):
model.eval()
with torch.no_grad():
logits = model(data)
outs = {}
for key in ['train', 'val', 'test']:
mask = data['{}_mask'.format(key)]
loss = F.nll_loss(logits[mask], data.y[mask]).item()
pred = logits[mask].max(1)[1]
acc = pred.eq(data.y[mask]).sum().item() / mask.sum().item()
outs['{}_loss'.format(key)] = loss
outs['{}_acc'.format(key)] = acc
return outs