text
stringlengths
1
93.6k
train_criterion = cls_criterion
elif task_type == 'multiclass classification':
train_criterion = multicls_criterion
else:
train_criterion = reg_criterion
y = batch.y
if task_type == 'multiclass classification':
y = y.view(-1, )
else:
y = y.to(torch.float32)
is_labeled = y == y
pred = model(batch)
optimizer.zero_grad()
## ignore nan targets (unlabeled) when computing training loss.
loss = train_criterion()(pred.to(torch.float32)[is_labeled],
y[is_labeled])
loss.backward()
optimizer.step()
total_loss += loss.item() * y.shape[0]
return total_loss / len(loader.dataset)
@torch.no_grad()
def eval(model, device, loader, evaluator, return_loss=False,
task_type=None, checkpoints=[None]):
model.eval()
Y_loss = []
Y_pred = []
for checkpoint in checkpoints:
if checkpoint:
model.load_state_dict(torch.load(checkpoint))
y_true = []
y_pred = []
y_loss = []
for step, batch in enumerate(tqdm(loader, desc="Iteration", ncols=70)):
if type(batch) == dict:
batch = {key: data_.to(device) for key, data_ in batch.items()}
skip_epoch = batch[args.h[0]].x.shape[0] == 1
else:
batch = batch.to(device)
skip_epoch = batch.x.shape[0] == 1
if skip_epoch:
pass
else:
with torch.no_grad():
pred = model(batch)
y = batch.y
if task_type == 'multiclass classification':
y = y.view(-1, )
else:
y = y.view(pred.shape).to(torch.float32)
y_true.append(y.detach().cpu())
y_pred.append(pred.detach().cpu())
if return_loss:
if task_type == 'binary classification':
train_criterion = cls_criterion
elif task_type == 'multiclass classification':
train_criterion = multicls_criterion
else:
train_criterion = reg_criterion
loss = train_criterion(reduction='none')(pred.to(torch.float32),
y)
loss[torch.isnan(loss)] = 0
y_loss.append(loss.sum(1).cpu())
if return_loss:
y_loss = torch.cat(y_loss, dim=0).numpy()
Y_loss.append(y_loss)
y_true = torch.cat(y_true, dim=0).numpy()
y_pred = torch.cat(y_pred, dim=0).numpy()
Y_pred.append(y_pred)
if return_loss:
y_loss = np.stack(Y_loss).mean(0)
return y_loss
y_pred = np.stack(Y_pred).mean(0)
if task_type == 'multiclass classification':
y_pred = np.argmax(y_pred, 1).reshape([-1, 1])
y_true = y_true.reshape([-1, 1])
input_dict = {"y_true": y_true, "y_pred": y_pred}
res = evaluator.eval(input_dict)
return res