def topk_accuracy(outputs, labels, recalls=(1, 5)):
    """Return @recall accuracies for the given recalls."""

    _, num_classes = outputs.size()
    maxk = min(max(recalls), num_classes)

    _, pred = outputs.topk(maxk, dim=1, largest=True, sorted=True)
    correct = (pred == labels[:,None].expand_as(pred)).float()

    topk_accuracy = []
    for recall in recalls:
        topk_accuracy.append(100 * correct[:, :recall].sum(1).mean())
    return topk_accuracy