import torch


def validate_model(model, valid_loader, criterion, device):
    """Validate the accuracy of the model during training

    Arguments:
        model -- The model to validate
        valid_loader -- Valdation data loader
        criterion -- Loss function used by the model
        device -- If it is to train on the cpu or gpu

    Returns:
        The actual loss and accuracy of the model W.R.T. the validation data
    """
    valid_loss = 0  # Running loss of the validation batch
    accuracy = 0  # Accuracy of the classifier

    for inputs, labels in valid_loader:  # for each batch of data / label

        inputs, labels = inputs.to(device), labels.to(device)
        output = model.forward(inputs)  # feed forward
        loss = criterion(output, labels)  # calculate the loss

        # Exponential because the output is the log of prob. distribution
        probabilities = torch.exp(output)
        # Compare the class label with the most probable classification class
        # from our classifier. dim=1 because dim=0 is the batch size
        # [1] because max returns the max probability value on [0] and the
        # index (our classes) on [1]
        equality = (labels.data == probabilities.max(dim=1)[1])
        # the average of right classifications
        accuracy += equality.type(torch.FloatTensor).mean()

        valid_loss += loss.item()

    return valid_loss, accuracy