-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathutils.py
55 lines (47 loc) · 1.88 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
import torch
import torch.nn as nn
import os, shutil
import numpy as np
from torch_geometric.datasets import Planetoid, CoraFull, Amazon, Coauthor
import scipy.sparse as sp
def load_dataset(name):
if name in ["Cora", "CiteSeer", "PubMed"]:
dataset = Planetoid(root='./data/'+name, name=name)
elif name == "CoraFull":
dataset = CoraFull(root='./data/'+name)
elif name in ["Computers", "Photo"]:
dataset = Amazon(root='./data/'+name, name=name)
elif name in ["CS", "Physics"]:
dataset = Coauthor(root='./data/'+name, name=name)
else:
exit("wrong dataset")
return dataset
def normalize_features(mx):
"""Row-normalize sparse matrix"""
rowsum = mx.sum(1)
r_inv = torch.pow(rowsum, -1).flatten()
r_inv[torch.isinf(r_inv)] = 0.
r_mat_inv = torch.diag(r_inv)
mx = torch.mm(r_mat_inv, mx)
return mx
def create_exp_dir(path, scripts_to_save=None):
path_split = path.split("/")
path_i = "."
for one_path in path_split:
path_i += "/" + one_path
if not os.path.exists(path_i):
os.mkdir(path_i)
print('Experiment dir : {}'.format(path_i))
if scripts_to_save is not None:
os.mkdir(os.path.join(path, 'scripts'))
for script in scripts_to_save:
dst_file = os.path.join(path, 'scripts', os.path.basename(script))
shutil.copyfile(script, dst_file)
def save_checkpoint(model, optimizer, epoch, path, finetune=False):
if finetune:
torch.save(model, os.path.join(path, 'finetune_model.pt'))
torch.save(optimizer.state_dict(), os.path.join(path, 'finetune_optimizer.pt'))
else:
torch.save(model, os.path.join(path, 'model.pt'))
torch.save(optimizer.state_dict(), os.path.join(path, 'optimizer.pt'))
torch.save({'epoch': epoch+1}, os.path.join(path, 'misc.pt'))