-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtrain.py
More file actions
125 lines (103 loc) · 3.23 KB
/
train.py
File metadata and controls
125 lines (103 loc) · 3.23 KB
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
import pickle
import time
import numpy as np
from utils import *
import torch
import torch.nn.functional as F
import torch.optim as optim
import scipy.sparse as sp
from models import GCN
dataset = 'watcha'
#Hyperparameter
epochs = 200
hidden = 200
num_class = 2
dropout = 0.5
lr = 0.02
weight_decay = 0
cuda = 0
early_stopping = 10
seed = 42
np.random.seed(seed)
torch.manual_seed(seed)
# Load data
with open("data/ind.{}.adj".format(dataset), 'rb') as f:
adj = pickle.load(f)
with open("data/ind.{}.data".format(dataset), 'rb') as f:
data = pickle.load(f)
num_doc = data['num_doc']
num_class = num_doc
A = np.array(adj.toarray())
features = sp.eye(A.shape[0])
labels = torch.LongTensor(np.array(data['label']))
features = torch.FloatTensor(np.array(features.todense()))
adj = sparse_mx_to_torch_sparse_tensor(adj)
idx_train = torch.LongTensor(range(0, data['train_size']))
idx_val = torch.LongTensor(range(data['train_size'], data['val_size']))
idx_test = torch.LongTensor(range(data['val_size'], data['test_size']))
print(idx_train)
print("===================================")
print(idx_val)
print("===================================")
print(idx_test)
# Model and optimizer
model = GCN(nfeat=features.shape[0],
nhid=hidden,
nclass=num_doc,
dropout=dropout)
optimizer = optim.Adam(model.parameters(),
lr=lr, weight_decay=weight_decay)
"""
if cuda:
model.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()"""
cost_val = []
def train(epoch):
t = time.time()
model.train()
optimizer.zero_grad()
output = model(features, adj)
loss_train = F.nll_loss(output[idx_train], labels[idx_train])
acc_train = accuracy(output[idx_train], labels[idx_train])
loss_train.backward()
optimizer.step()
# Evaluate validation set performance separately,
# deactivates dropout during validation run.
model.eval()
output = model(features, adj)
loss_val = F.nll_loss(output[idx_val], labels[idx_val])
acc_val = accuracy(output[idx_val], labels[idx_val])
cost_val.append(loss_val)
print('Epoch: {:04d}'.format(epoch+1),
'loss_train: {:.4f}'.format(loss_train.item()),
'acc_train: {:.4f}'.format(acc_train.item()),
'loss_val: {:.4f}'.format(loss_val.item()),
'acc_val: {:.4f}'.format(acc_val.item()),
'time: {:.4f}s'.format(time.time() - t))
if epoch > early_stopping and cost_val[-1] > torch.mean(torch.FloatTensor(cost_val[-(early_stopping + 1):-1])):
print("Early stopping...")
return False
return True
def test():
model.eval()
output = model(features, adj)
loss_test = F.nll_loss(output[idx_test], labels[idx_test])
acc_test = accuracy(output[idx_test], labels[idx_test])
print("Test set results:",
"loss= {:.4f}".format(loss_test.item()),
"accuracy= {:.4f}".format(acc_test.item()))
# Train model
t_total = time.time()
for epoch in range(epochs):
flag = train(epoch)
if flag == False :
break
print("Optimization Finished!")
print("Total time elapsed: {:.4f}s".format(time.time() - t_total))
# Testing
test()