File size: 7,386 Bytes
c91d7b1 | 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 | import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
from copy import deepcopy
from deeprobust.graph import utils
import torch
class BaseModel(nn.Module):
def __init__(self):
super(BaseModel, self).__init__()
pass
def fit(self, pyg_data, train_iters=1000, initialize=True, verbose=False, patience=100, **kwargs):
if initialize:
self.initialize()
# self.data = pyg_data[0].to(self.device)
self.data = pyg_data.to(self.device)
# By default, it is trained with early stopping on validation
self.train_with_early_stopping(train_iters, patience, verbose)
def finetune(self, edge_index, edge_weight, feat=None, train_iters=10, verbose=True):
if verbose:
print(f'=== finetuning {self.name} model ===')
optimizer = optim.Adam(self.parameters(), lr=self.lr, weight_decay=self.weight_decay)
labels = self.data.y
if feat is None:
x = self.data.x
else:
x = feat
train_mask, val_mask = self.data.train_mask, self.data.val_mask
best_loss_val = 100
best_acc_val = 0
for i in range(train_iters):
self.train()
optimizer.zero_grad()
output = self.forward(x, edge_index, edge_weight)
loss_train = F.nll_loss(output[train_mask], labels[train_mask])
loss_train.backward()
optimizer.step()
if verbose and i % 50 == 0:
print('Epoch {}, training loss: {}'.format(i, loss_train.item()))
self.eval()
with torch.no_grad():
output = self.forward(x, edge_index)
loss_val = F.nll_loss(output[val_mask], labels[val_mask])
acc_val = utils.accuracy(output[val_mask], labels[val_mask])
# if best_loss_val > loss_val:
# best_loss_val = loss_val
# best_output = output
# weights = deepcopy(self.state_dict())
if best_acc_val < acc_val:
best_acc_val = acc_val
best_output = output
weights = deepcopy(self.state_dict())
print('best_acc_val:', best_acc_val.item())
self.load_state_dict(weights)
return best_output
def _fit_with_val(self, pyg_data, train_iters=1000, initialize=True, verbose=False, **kwargs):
if initialize:
self.initialize()
# self.data = pyg_data[0].to(self.device)
self.data = pyg_data.to(self.device)
if verbose:
print(f'=== training {self.name} model ===')
optimizer = optim.Adam(self.parameters(), lr=self.lr, weight_decay=self.weight_decay)
labels = self.data.y
train_mask, val_mask = self.data.train_mask, self.data.val_mask
x, edge_index = self.data.x, self.data.edge_index
for i in range(train_iters):
self.train()
optimizer.zero_grad()
output = self.forward(x, edge_index)
loss_train = F.nll_loss(output[train_mask+val_mask], labels[train_mask+val_mask])
loss_train.backward()
optimizer.step()
if verbose and i % 50 == 0:
print('Epoch {}, training loss: {}'.format(i, loss_train.item()))
def fit_with_val(self, pyg_data, train_iters=1000, initialize=True, patience=100, verbose=False, **kwargs):
if initialize:
self.initialize()
self.data = pyg_data.to(self.device)
self.data.train_mask = self.data.train_mask + self.data.val1_mask
self.data.val_mask = self.data.val2_mask
self.train_with_early_stopping(train_iters, patience, verbose)
def train_with_early_stopping(self, train_iters, patience, verbose):
"""early stopping based on the validation loss
"""
if verbose:
print(f'=== training {self.name} model ===')
optimizer = optim.Adam(self.parameters(), lr=self.lr, weight_decay=self.weight_decay)
labels = self.data.y
train_mask, val_mask = self.data.train_mask, self.data.val_mask
early_stopping = patience
best_loss_val = 100
best_acc_val = 0
best_epoch = 0
x, edge_index = self.data.x, self.data.edge_index
for i in range(train_iters):
self.train()
optimizer.zero_grad()
output = self.forward(x, edge_index)
loss_train = F.nll_loss(output[train_mask], labels[train_mask])
loss_train.backward()
optimizer.step()
if verbose and i % 50 == 0:
print('Epoch {}, training loss: {}'.format(i, loss_train.item()))
self.eval()
output = self.forward(x, edge_index)
loss_val = F.nll_loss(output[val_mask], labels[val_mask])
acc_val = utils.accuracy(output[val_mask], labels[val_mask])
# print(acc)
# if best_loss_val > loss_val:
# best_loss_val = loss_val
# self.output = output
# weights = deepcopy(self.state_dict())
# patience = early_stopping
# best_epoch = i
# else:
# patience -= 1
if best_acc_val < acc_val:
best_acc_val = acc_val
self.output = output
weights = deepcopy(self.state_dict())
patience = early_stopping
best_epoch = i
else:
patience -= 1
if i > early_stopping and patience <= 0:
break
if verbose:
# print('=== early stopping at {0}, loss_val = {1} ==='.format(best_epoch, best_loss_val) )
print('=== early stopping at {0}, acc_val = {1} ==='.format(best_epoch, best_acc_val) )
self.load_state_dict(weights)
def test(self):
"""Evaluate model performance on test set.
Parameters
----------
idx_test :
node testing indices
"""
self.eval()
test_mask = self.data.test_mask
labels = self.data.y
output = self.forward(self.data.x, self.data.edge_index)
# output = self.output
loss_test = F.nll_loss(output[test_mask], labels[test_mask])
acc_test = utils.accuracy(output[test_mask], labels[test_mask])
print("Test set results:",
"loss= {:.4f}".format(loss_test.item()),
"accuracy= {:.4f}".format(acc_test.item()))
return acc_test.item()
def predict(self, x=None, edge_index=None, edge_weight=None):
"""
Returns
-------
torch.FloatTensor
output (log probabilities)
"""
self.eval()
if x is None or edge_index is None:
x, edge_index = self.data.x, self.data.edge_index
return self.forward(x, edge_index, edge_weight)
def _ensure_contiguousness(self,
x,
edge_idx,
edge_weight):
if not x.is_sparse:
x = x.contiguous()
if hasattr(edge_idx, 'contiguous'):
edge_idx = edge_idx.contiguous()
if edge_weight is not None:
edge_weight = edge_weight.contiguous()
return x, edge_idx, edge_weight
|