Pytorch achieve Top1 accuracy and accuracy Top5

Top5 Top1 has been unclear before and what is, in fact, very simple to figure out, is both measures indicators, which, Top1 is an ordinary Accuracy, Top5 measure more than Top1 "stringent"

Specifically, such a total of 10 points required class, each output sorter 10 are probability values ​​add up to 1, which is ten values ​​of Top1 maximum probability value corresponding to that classification exactly the correct frequency, the Top5 probability value is ten in descending order out of the top five, and then see if there is the correct classification of these top five categories, and then calculate the frequency. Pytorch achieve the following:

def evaluteTop1(model, loader):
    model.eval()
    
    correct = 0
    total = len(loader.dataset)

    for x,y in loader:
        x,y = x.to(device), y.to(device)
        with torch.no_grad():
            logits = model(x)
            pred = logits.argmax(dim=1)
            correct += torch.eq(pred, y).sum().float().item()
        #correct += torch.eq(pred, y).sum().item()
    return correct / total

def evaluteTop5(model, loader):
    model.eval()
    correct = 0
    total = len(loader.dataset)
    for x, y in loader:
        x,y = x.to(device),y.to(device)
        with torch.no_grad():
            logits = model(x)
            maxk = max((1,5))
            _, pred = logits.topk(maxk, 1, True, True)
            correct += torch.eq(pred, y).sum().float().item()
    return correct / total

function of the specific use topk see https://blog.csdn.net/u014264373/article/details/86525621

Guess you like

Origin www.cnblogs.com/yqpy/p/11391972.html