def average_precision(truth, recommend):
    """Average Precision (AP).

    Args:
        truth (numpy 1d array): Set of truth samples.
        recommend (numpy 1d array): Ordered set of recommended samples.

    Returns:
        float: AP.

    """
    if len(truth) == 0:
        if len(recommend) == 0:
            return 1.
        return 0.

    tp = accum = 0.
    for n in range(recommend.size):
        if recommend[n] in truth:
            tp += 1.
            accum += (tp / (n + 1.))
    return accum / truth.size
Average Precision (AP).

    Args:
        truth (numpy 1d array): Set of truth samples.
        recommend (numpy 1d array): Ordered set of recommended samples.

    Returns:
        float: AP.