import torch


def macro_f1(logits, targets, th=0.5):
    """
    pytorch implementation
    :param logits: Tensor of shape (B, num_class)
    :param targets: Tensor of shape (B, num_class)
    :param th: Float threshold
    :return: Float
    """
    preds = (logits.sigmoid() > th).float()
    targets = targets.float()
    score = 2.0 * torch.sum(preds * targets, dim=0) / torch.sum(preds + targets, dim=0)
    return score.mean().item()