import torch


def binary_accuracy(output, target, threshold=0.0):
    """
    Computes the accuracy based on a real-valued output tensor and a corresponding
    target matrix of the same size with valuesin [0, 1].

    An optional threshold for positive classification can be specified (default = 0).
    """

    # assertions:
    assert torch.is_tensor(output)
    assert torch.is_tensor(target)
    assert output.size() == target.size()

    # compute accuracy:
    correct = output.ge(threshold).type_as(target).eq_(target).long()
    return correct.sum().item() * 100.0 / float(target.nelement())