forked from chennnM/GBP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
citation.py
140 lines (112 loc) · 4.19 KB
/
citation.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
from __future__ import division
from __future__ import print_function
from utils import load_citation,muticlass_f1
import time
import random
import argparse
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.utils.data as Data
from model import GnnBP
import uuid
# Training settings
parser = argparse.ArgumentParser()
parser.add_argument('--seed', type=int, default=20159, help='random seed.')
parser.add_argument('--epochs', type=int, default=1000, help='number of epochs.')
parser.add_argument('--lr', type=float, default=0.01, help='learning rate.')
parser.add_argument('--weight_decay', type=float, default=5e-4, help='weight decay.')
parser.add_argument('--layer', type=int, default=2, help='number of layers.')
parser.add_argument('--hidden', type=int, default=64, help='hidden dimensions.')
parser.add_argument('--dropout', type=float, default=0.5, help='dropout rate.')
parser.add_argument('--patience', type=int, default=100, help='patience')
parser.add_argument('--data', default='cora', help='dateset')
parser.add_argument('--dev', type=int, default=0, help='device id')
parser.add_argument('--alpha', type=float, default=0.1, help='decay factor')
parser.add_argument('--rmax', type=float, default=1e-5, help='threshold.')
parser.add_argument('--rrz', type=float, default=0.0, help='r.')
parser.add_argument('--bias', default='none', help='bias.')
parser.add_argument('--batch', type=int, default=64, help='batch size')
args = parser.parse_args()
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
torch.cuda.manual_seed(args.seed)
print("--------------------------")
print(args)
features,labels,idx_train,idx_val,idx_test = load_citation(args.data,args.alpha,args.rmax,args.rrz)
checkpt_file = 'pretrained/'+uuid.uuid4().hex+'.pt'
model = GnnBP(nfeat=features.shape[1],
nlayers=args.layer,
nhidden=args.hidden,
nclass=int(labels.max()) + 1,
dropout=args.dropout,
bias = args.bias).cuda(args.dev)
optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.weight_decay)
loss_fn = nn.CrossEntropyLoss()
features = features.cuda(args.dev)
labels = labels.cuda(args.dev)
torch_dataset = Data.TensorDataset(features[idx_train], labels[idx_train])
loader = Data.DataLoader(dataset=torch_dataset,
batch_size=args.batch,
shuffle=True,
num_workers=0)
def train():
model.train()
loss_list = []
time_epoch = 0
for step, (batch_x, batch_y) in enumerate(loader):
# batch_x = batch_x.cuda(args.dev)
# batch_y = batch_y.cuda(args.dev)
t1 = time.time()
optimizer.zero_grad()
output = model(batch_x)
loss_train = loss_fn(output, batch_y)
loss_train.backward()
optimizer.step()
time_epoch+=(time.time()-t1)
loss_list.append(loss_train.item())
return np.mean(loss_list),time_epoch
def validate():
model.eval()
with torch.no_grad():
output = model(features[idx_val])
micro_val = muticlass_f1(output, labels[idx_val])
return micro_val.item()
def test():
model.load_state_dict(torch.load(checkpt_file))
model.eval()
with torch.no_grad():
output = model(features[idx_test])
micro_test = muticlass_f1(output, labels[idx_test])
return micro_test.item()
train_time = 0
bad_counter = 0
best = 0
best_epoch = 0
for epoch in range(args.epochs):
loss_tra,train_ep = train()
f1_val = validate()
train_time+=train_ep
if(epoch+1)%10 == 0:
print('Epoch:{:04d}'.format(epoch+1),
'train',
'loss:{:.3f}'.format(loss_tra),
'| val',
'acc:{:.3f}'.format(f1_val),
'| cost{:.3f}'.format(train_time))
if f1_val > best:
best = f1_val
best_epoch = epoch
torch.save(model.state_dict(), checkpt_file)
bad_counter = 0
else:
bad_counter += 1
if bad_counter == args.patience:
break
f1_test = test()
print("Train cost: {:.4f}s".format(train_time))
print('Load {}th epoch'.format(best_epoch))
print("Test f1:{:.3f}".format(f1_test))
print("--------------------------")