forked from BUPT-GAMMA/OpenHGNN
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDMGI_trainer.py
223 lines (170 loc) · 7.91 KB
/
DMGI_trainer.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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
import torch
from sklearn.metrics import f1_score
import torch.nn.functional as F
from tqdm import tqdm
import numpy as np
import torch.nn as nn
from openhgnn.models import build_model
from openhgnn.models.DMGI import LogReg
from openhgnn.trainerflow import register_flow, BaseFlow
from openhgnn.utils import EarlyStopping
@register_flow("DMGI_trainer")
class DMGI_trainer(BaseFlow):
def __init__(self, args):
super(DMGI_trainer, self).__init__(args)
# get category
self.args.category = self.task.dataset.category
self.category = self.args.category
if hasattr(self.task.dataset, 'in_dim'):
self.args.in_dim = self.task.dataset.in_dim
else:
self.args.in_dim = self.hg.ndata['h'][self.category].shape[1]
# get category num_classes
self.num_classes = self.task.dataset.num_classes
self.args.num_classes = self.task.dataset.num_classes
self.model = build_model(self.model).build_model_from_args(self.args, self.hg)
self.model = self.model.to(self.device)
self.optimizer = self.candidate_optimizer[args.optimizer](self.model.parameters(),
lr=args.lr, weight_decay=args.weight_decay)
self.train_idx, self.val_idx, self.test_idx = self.task.get_split()
# get label
self.labels = self.task.get_labels().to(self.device)
# get category's numbers
self.num_nodes = self.hg.num_nodes(self.category)
self.isSemi = args.isSemi
# a coefficient to Calculate semi
self.sup_coef = args.sup_coef
def preprocess(self):
pass
def train(self):
stopper = EarlyStopping(self.patience)
model = self.model
epoch_iter = tqdm(range(self.max_epoch))
for epoch in epoch_iter:
'''use earlyStopping'''
loss = self._full_train_setp()
early_stop = stopper.loss_step(loss, model)
self.logger.train_info(f"Epoch: {epoch:03d}, Loss: {loss:.4f}")
if early_stop:
self.logger.train_info(f'Early Stop!\tEpoch:{epoch}')
break
# Evaluation
stopper.load_model(self.model)
model.eval()
self.evaluate(model.H.data.detach(),)
def _full_train_setp(self):
self.model.train()
self.optimizer.zero_grad()
lbl_1 = torch.ones(1, self.num_nodes)
lbl_2 = torch.zeros(1, self.num_nodes)
lbl = torch.cat((lbl_1, lbl_2), 1).to(self.args.device)
result = self.model(self.hg)
loss = self.calculate_J(result, lbl)
loss.backward()
self.optimizer.step()
loss = loss.cpu()
loss = loss.detach().numpy()
return loss
def _test_step(self, split=None, logits=None):
pass
def _mini_train_step(self, ):
pass
def loss_calculation(self, positive_graph, negative_graph, embedding):
pass
def calculate_J(self, result, lbl):
r"""
Two formulas to calculate the final objective :math:`\mathcal{J}`
If isSemi = Ture, introduce a semi-supervised module into our framework that predicts the labels of labeled nodes from
the consensus embedding Z. More precisely, we minimize the cross-entropy error over the labeled nodes:
.. math::
\begin{equation}
\mathcal{J}_{\text {semi }}=\sum_{r \in \mathcal{R}} \mathcal{L}^{(r)}+\alpha \ell_{\mathrm{cs}}+\beta\|\Theta\|+\gamma \ell_{\text {sup }}
\end{equation}
Where :math:`\gamma` is the coefficient of the semi-supervised module, the way to calculate :math:`\ell_{\text {sup }}` :
.. math::
\begin{equation}
\ell_{\text {sup }}=-\frac{1}{\left|\mathcal{Y}_{L}\right|} \sum_{l \in \mathcal{Y}_{L}} \sum_{i=1}^{c} Y_{l i} \ln \hat{Y}_{l i}
\end{equation}
If isSemi = False:
.. math::
\begin{equation}
\mathcal{J}=\sum_{r \in \mathcal{R}} \mathcal{L}^{(r)}+\alpha \ell_{\mathrm{cs}}+\beta\|\Theta\|^{2}
\end{equation}
Where :math:`\alpha` controls the importance of the consensus regularization,
:math:`mathcal{L}^{(r)}` is cross entropy.
"""
logits = result['logits']
xent = nn.CrossEntropyLoss()
b_xent = nn.BCEWithLogitsLoss()
xent_loss = None
for idx, logit in enumerate(logits):
logit = logit.unsqueeze(0)
if xent_loss is None:
xent_loss = b_xent(logit, lbl)
else:
xent_loss += b_xent(logit, lbl)
loss = xent_loss
reg_loss = result['reg_loss']
loss += self.args.reg_coef * reg_loss
if self.isSemi:
sup = result['semi']
semi_loss = xent(sup[self.train_idx], self.labels[self.train_idx])
loss += self.sup_coef * semi_loss
return loss
def evaluate(self, embeds):
hid_units = embeds.shape[2]
xent = F.cross_entropy
train_embs = embeds[0, self.train_idx]
val_embs = embeds[0, self.val_idx]
test_embs = embeds[0, self.test_idx]
train_lbls = self.labels[self.train_idx]
val_lbls = self.labels[self.val_idx]
test_lbls = self.labels[self.test_idx]
val_accs = [];test_accs = []
val_micro_f1s = [];test_micro_f1s = []
val_macro_f1s = [];test_macro_f1s = []
for _ in range(50):
log = LogReg(hid_units, self.num_classes)
opt = torch.optim.Adam(log.parameters(), lr=0.01, weight_decay=0.0)
log.to(self.device)
accs = []
micro_f1s = []
macro_f1s = []
macro_f1s_val = [] ##
for iter_ in range(50):
# train
log.train()
opt.zero_grad()
logits = log(train_embs)
loss = xent(logits, train_lbls)
loss.backward()
opt.step()
# val
logits = log(val_embs)
preds = torch.argmax(logits, dim=1)
val_acc = torch.sum(preds == val_lbls).float() / val_lbls.shape[0]
val_f1_macro = f1_score(val_lbls.cpu(), preds.cpu(), average='macro')
val_f1_micro = f1_score(val_lbls.cpu(), preds.cpu(), average='micro')
val_accs.append(val_acc.item())
val_macro_f1s.append(val_f1_macro)
val_micro_f1s.append(val_f1_micro)
# test
logits = log(test_embs)
preds = torch.argmax(logits, dim=1)
test_acc = torch.sum(preds == test_lbls).float() / test_lbls.shape[0]
test_f1_macro = f1_score(test_lbls.cpu(), preds.cpu(), average='macro')
test_f1_micro = f1_score(test_lbls.cpu(), preds.cpu(), average='micro')
test_accs.append(test_acc.item())
test_macro_f1s.append(test_f1_macro)
test_micro_f1s.append(test_f1_micro)
max_iter = val_accs.index(max(val_accs))
accs.append(test_accs[max_iter])
max_iter = val_macro_f1s.index(max(val_macro_f1s))
macro_f1s.append(test_macro_f1s[max_iter])
macro_f1s_val.append(val_macro_f1s[max_iter]) ###
max_iter = val_micro_f1s.index(max(val_micro_f1s))
micro_f1s.append(test_micro_f1s[max_iter])
self.logger.train_info("\t[Classification] Macro-F1: {:.4f} ({:.4f}) | Micro-F1: {:.4f} ({:.4f})".format(np.mean(macro_f1s),
np.std(macro_f1s),
np.mean(micro_f1s),
np.std(micro_f1s)))