eval.py 1.85 KB
import os
import fire
import json
from pprint import pprint

import torch
import torch.nn as nn
import torchvision.transforms as transforms
from torch.utils.tensorboard import SummaryWriter

from utils import *

# command
# python eval.py --model_path='logs/April_16_00:26:10__resnet50__None/'

def eval(model_path):
    print('\n[+] Parse arguments')
    kwargs_path = os.path.join(model_path, 'kwargs.json')
    kwargs = json.loads(open(kwargs_path).read())
    args, kwargs = parse_args(kwargs)
    pprint(args)
    device = torch.device('cuda' if args.use_cuda else 'cpu')
    

    print('\n[+] Create network')
    model = select_model(args)
    optimizer = select_optimizer(args, model)
    criterion = nn.CrossEntropyLoss()
    if args.use_cuda:
        model = model.cuda()
        criterion = criterion.cuda()

    print('\n[+] Load model')
    weight_path = os.path.join(model_path, 'model', 'model.pt')
    model.load_state_dict(torch.load(weight_path))

    print('\n[+] Load dataset')
    transform = transforms.Compose([
            transforms.Resize([240, 240]),
            transforms.ToTensor() 
    ])
    test_dataset = get_dataset(args, transform, 'test') 

   
    test_loader = iter(get_dataloader(args, test_dataset)) ###

    print('\n[+] Start testing')
    os.makedirs(os.path.join(model_path, 'test'))
    writer = SummaryWriter(log_dir=os.path.join(model_path, 'test'))
    _test_res = validate(args, model, criterion, test_loader, step=0)

    print('\n[+] Valid results')
    print('  Acc@1 : {:.3f}%'.format(_test_res[0].data.cpu().numpy()[0]*100))
    print('  Loss : {:.3f}'.format(_test_res[1].data))
    print('  Infer Time(per image) : {:.3f}ms'.format(_test_res[2]*1000 / len(test_dataset)))

    writer.add_scalar('test/acc1', _test_res[0])
    writer.add_scalar('test/loss', _test_res[1])

    writer.close()

if __name__ == '__main__':
    fire.Fire(eval)