-
Notifications
You must be signed in to change notification settings - Fork 0
/
train.py
153 lines (139 loc) · 7.36 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
from model import Model_Layer
import numpy as np
import networkx as nx
from utils import *
import random
import torch
from tqdm import tqdm_notebook as tqdm
import time
import scipy.sparse as sparse
from sklearn.preprocessing import normalize
class Train_Model():
def __init__(self, args):
self.args = args
self.graph, self.dic_id2feature, self.dic_id2label, self.id_train, self.id_valid, self.id_test, num_labels = load_data2(self.args.dataset,True)
self.sample_batch_size = 256
print('train walk')
self.walks_train = pre_sample(self.args.time, self.graph, self.id_train, self.sample_batch_size, 'train',self.args.way,self.args.do_walk)
print('valid walk')
self.walks_valid = pre_sample(self.args.time, self.graph, self.id_valid, self.sample_batch_size,'valid',self.args.way,self.args.do_walk)
self.nor_graph = sparse.csr_matrix(self.graph.cpu().detach().numpy())
self.nor_graph.setdiag(1.0)
#self.nor_graph = normalize(self.nor_graph, norm='l1', axis=1)
self.nor_graph = sparse_mx_to_torch_sparse_tensor(normalize(self.nor_graph, norm='l1', axis=1)).to_dense().cuda()
self.args.feature_dim = self.dic_id2feature.shape[1]
self.args.num_nodes = self.dic_id2feature.shape[0]
self.args.num_labels = num_labels
self.model = Model_Layer(self.args).cuda()
self.lstm_h_0 = torch.zeros(1, self.args.batch_size, self.args.hidden).cuda()
self.lstm_c_0 = torch.zeros(1, self.args.batch_size, self.args.hidden).cuda()
print('cuda ready')
#self.model = torch.nn.DataParallel(Model_Layer(self.args),device_ids=[0,1,2,3])
self.logs = create_logs(self.args)
self.best_loss = 1000
self.best_acc = 0
self.best_loss_both = 1000
self.best_acc_both = 0
self.stop_count = 0
self.best_loss_epoch = -1
self.best_both_epoch = -1
self.best_acc_epoch = -1
self.epoch_idx = 0
self.total_time = 0.0
def fit(self):
print("\nTraining started.\n")
self.optimizer = torch.optim.Adam(self.model.parameters(), lr = self.args.learning_rate, weight_decay = self.args.weight_decay)
self.optimizer.zero_grad()
batches = create_batches_forWalk(self.walks_train , self.args.batch_size)
valid_batch = create_batches_forWalk(self.walks_valid , self.args.batch_size)
self.id_train = list(self.id_train)
ave_epoch_time = 0
ave_batch_time = 0
total_start = time.time()
for epoch in tqdm(range(self.args.epochs)):
self.model.train()
self.epoch_loss = 0.0
self.acc_score = 0.0
self.nodes_processed = 0.0
batch_range = len(batches)
batch_time = 0
epoch_start = time.time()
for batch in range(batch_range):
label = torch.index_select(self.dic_id2label, 0, batches[batch][:,0].view(-1))
start = time.time()
self.epoch_loss = self.epoch_loss + self.process_batch(label, batches[batch])
batch_time += time.time() - start
epoch_end = time.time()
ave_epoch_time += epoch_end - epoch_start
batch_time = batch_time / batch_range
ave_batch_time += batch_time
self.model.eval()
valid_loss = 0.0
valid_acc = 0.0
for batch in valid_batch:
label = torch.index_select(self.dic_id2label, 0, batch[:,0].view(-1))
loss_node, acc, label_predict = self.process_node(label, batch)
valid_loss += loss_node.item()
valid_acc += acc.item()
valid_loss = round(valid_loss*1000/len(self.id_valid), 4)
valid_acc = round(valid_acc/len(self.id_valid), 4)
self.acc_score = round(self.acc_score/len(self.id_train), 4)
loss_score = round(self.epoch_loss*1000/len(self.id_train), 4)
if epoch % 1 == 0:
print("epoch",epoch,"loss_train:",loss_score,"acc_train:",self.acc_score,'||',"loss_valid:",valid_loss,"acc_valid:",valid_acc, '|| batch time:', round(batch_time, 4), '||epoch time:', round(epoch_end - epoch_start, 4))
if (valid_loss < self.best_loss or valid_acc > self.best_acc) :
if valid_loss < self.best_loss:
self.best_loss = valid_loss
torch.save(self.model.state_dict(),self.args.save_path_loss+"best_model.pt")
stop_count = 0
self.best_loss_epoch = epoch
if valid_acc > self.best_acc :
self.best_acc = valid_acc
torch.save(self.model.state_dict(),self.args.save_path_acc+"best_model.pt")
stop_count = 0
self.best_acc_epoch = epoch
else:
stop_count += 1
if stop_count == self.args.patience:
print(self.args.patience, "times no decrease")
#print(self.total_time / (epoch+1))
return round(ave_epoch_time/(epoch+1), 4), round(ave_batch_time / (epoch+1), 4), time.time()-total_start
print('Max epoches reaches!')
return round(ave_epoch_time/(epoch+1), 4), round(ave_batch_time / (epoch+1), 4), time.time()-total_start
def evaluation(self):
loss_result = torch.zeros(len(self.id_test), self.args.eva_times, dtype=torch.long)
acc_result = torch.zeros(len(self.id_test), self.args.eva_times, dtype=torch.long)
loss_acc = 0.0
acc_acc = 0.0
#print('test walk')
self.walks_test = pre_sample(self.args.time, self.graph, self.id_test, self.sample_batch_size,'test', self.args.way,True)
test_batch = create_batches_forWalk(self.walks_test, self.args.batch_size)
self.model.eval()
self.model.load_state_dict(torch.load(self.args.save_path_loss+"best_model.pt"))
for batch in test_batch:
label = torch.index_select(self.dic_id2label, 0, batch[:,0].view(-1))
loss_node, acc, label_predict = self.process_node(label, batch)
loss_acc += acc.item()
self.model.load_state_dict(torch.load(self.args.save_path_acc+"best_model.pt"))
batchID = 0
for batch in test_batch:
label = torch.index_select(self.dic_id2label, 0, batch[:,0].view(-1))
loss_node, acc, label_predict = self.process_node(label, batch)
acc_acc += acc.item()
acc_acc = round(acc_acc/len(self.id_test), 4)
loss_acc = round(loss_acc/len(self.id_test), 4)
print("loss acc:", loss_acc, 'load epoch:', self.best_loss_epoch)
print("acc acc:", acc_acc, 'load epoch:', self.best_acc_epoch)
return loss_acc, acc_acc
def process_node(self,label, node):
prediction = self.model(node, self.nor_graph, self.dic_id2feature)
prediction_loss = calculate_predictive_loss(label, prediction)
acc, label_pre = calculate_reward(label, prediction)
return prediction_loss, acc, label_pre
def process_batch(self,label,batch):
self.optimizer.zero_grad()
batch_loss, acc, label_pre = self.process_node(label, batch)
self.acc_score += acc.item()
batch_loss.backward()
self.optimizer.step()
return batch_loss.item()