Last active
September 16, 2021 04:54
-
-
Save e96031413/b499b300526c6822a010de6037bfe7f6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def testing(UnNormalize, writer, val_loader, model, criterion, args, size_val_df, y_pred, y_true): | |
batch_time = AverageMeter('Time', ':6.3f') | |
losses = AverageMeter('Loss', ':.4e') | |
top1 = AverageMeter('Acc@1', ':6.2f') | |
top5 = AverageMeter('Acc@5', ':6.2f') | |
progress = ProgressMeter( | |
len(val_loader), | |
[batch_time, losses, top1, top5], | |
prefix='Test: ') | |
model.eval() | |
val_running_loss = 0.0 | |
val_running_accuracy = 0 | |
with torch.no_grad(): | |
end = time.time() | |
for i, (images, target, path) in enumerate(val_loader): | |
if args.gpu is not None: | |
images = images.cuda(args.gpu, non_blocking=True) | |
if torch.cuda.is_available(): | |
target = target.cuda(args.gpu, non_blocking=True) | |
# compute output | |
output = model(images) | |
_, preds = torch.max(output, 1) | |
loss = criterion(output, target) | |
preds = torch.tensor([(lambda i: 1 if i > 1 else i)(i) for i in preds]).cuda() | |
target = torch.tensor([(lambda i: 1 if i > 1 else i)(i) for i in target]).cuda() | |
y_pred.extend(preds.view(-1).detach().cpu().numpy()) | |
y_true.extend(target.view(-1).detach().cpu().numpy()) | |
# measure accuracy and record loss | |
acc1, acc5 = accuracy(output, target, topk=(1, 5)) | |
losses.update(loss.item(), images.size(0)) | |
top1.update(acc1[0], images.size(0)) | |
top5.update(acc5[0], images.size(0)) | |
val_running_loss += loss.item() * images.size(0) | |
val_running_accuracy += torch.sum(preds == target.data) | |
# measure elapsed time | |
batch_time.update(time.time() - end) | |
end = time.time() | |
test_data_recorder(UnNormalize, i, pred_index, writer, target, images, output, i, val_loader) | |
if i % args.print_freq == 0: | |
progress.display(i) | |
print(' * Acc@1 {top1.avg:.3f} Acc@5 {top5.avg:.3f}' | |
.format(top1=top1, top5=top5)) | |
return top1.avg, y_pred, y_true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment