import torch


def accuracy4batch(model, testloader, criterion):
    """save a model checkpoint

    INPUT:
    model: pytorch nn model. 
    testloader: DataLoader. test data set
    criterion: criterion. loss criterion
    device: torch.device. device on which model/data is based

    OUTPUT: 
    accuracy: float in [0:1]. percenct proportion of correct classifications in testloader
    test_loss: float. absolute error
    """
    test_loss = 0
    accuracy = 0
    model.eval()
    with torch.no_grad():
        for inputs, labels in testloader:
            inputs, labels = inputs.to(model.device), labels.to(model.device)
            logps = model.forward(inputs)
            batch_loss = criterion(logps, labels)

            test_loss += batch_loss.item()

            # Calculate accuracy
            ps = torch.exp(logps)
            top_p, top_class = ps.topk(1, dim=1)
            equals = top_class == labels.view(*top_class.shape)
            accuracy += torch.mean(equals.type(torch.FloatTensor)).item()
    
    accuracy = accuracy/len(testloader)
    
    return accuracy, test_loss