(val_loader, model, criterion)
| 220 | |
| 221 | |
| 222 | def validate(val_loader, model, criterion): |
| 223 | batch_time = AverageMeter() |
| 224 | losses = AverageMeter() |
| 225 | top1 = AverageMeter() |
| 226 | top5 = AverageMeter() |
| 227 | |
| 228 | # switch to evaluate mode |
| 229 | model.eval() |
| 230 | softmax = nn.Softmax(dim=1).cuda() |
| 231 | end = time.time() |
| 232 | with torch.no_grad(): |
| 233 | for i, (input, target) in enumerate(val_loader): |
| 234 | if args.tencrops: |
| 235 | bs, ncrops, c, h, w = input.size() |
| 236 | input = input.view(-1, c, h, w).contiguous() |
| 237 | input_cu, target_cu = input.cuda(), target.cuda() |
| 238 | |
| 239 | output = model(input_cu) |
| 240 | if args.tencrops: |
| 241 | output_central = output.view(bs, ncrops, -1)[: , int(ncrops / 2 - 1), :] |
| 242 | output = softmax(output) |
| 243 | output = torch.squeeze(output.view(bs, ncrops, -1).mean(1)) |
| 244 | else: |
| 245 | output_central = output |
| 246 | |
| 247 | prec1, prec5 = accuracy(output.data, target_cu, topk=(1, 5)) |
| 248 | top1.update(prec1.item(), input.size(0)) |
| 249 | top5.update(prec5.item(), input.size(0)) |
| 250 | loss = criterion(output_central, target_cu) |
| 251 | losses.update(loss.item(), input.size(0)) |
| 252 | |
| 253 | # measure elapsed time |
| 254 | batch_time.update(time.time() - end) |
| 255 | end = time.time() |
| 256 | |
| 257 | logger.info('Validation: [{0}/{1}]\t' |
| 258 | 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' |
| 259 | 'Loss {loss.val:.4f} ({loss.avg:.4f})\t' |
| 260 | 'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t' |
| 261 | 'Prec@5 {top5.val:.3f} ({top5.avg:.3f})' |
| 262 | .format(i, len(val_loader), batch_time=batch_time, |
| 263 | loss=losses, top1=top1, top5=top5)) |
| 264 | |
| 265 | return top1.avg, top5.avg, losses.avg |
| 266 | |
| 267 | if __name__ == '__main__': |
| 268 | main() |
no test coverage detected