def average_precision_score(y_true, y_score, k=10):
    'Average precision at rank k\n    Parameters\n    ----------\n    y_true : array-like, shape = [n_samples]\n        Ground truth (true relevance labels).\n    y_score : array-like, shape = [n_samples]\n        Predicted scores.\n    k : int\n        Rank.\n    Returns\n    -------\n    average precision @k : float\n    '
    unique_y = np.unique(y_true)
    if (len(unique_y) == 1):
        return ValueError('The score cannot be approximated.')
    elif (len(unique_y) > 2):
        raise ValueError('Only supported for two relevance levels.')
    pos_label = unique_y[1]
    n_pos = np.sum((y_true == pos_label))
    order = np.argsort(y_score)[::(- 1)][:min(n_pos, k)]
    y_true = np.asarray(y_true)[order]
    score = 0
    for i in range(len(y_true)):
        if (y_true[i] == pos_label):
            prec = 0
            for j in range(0, (i + 1)):
                if (y_true[j] == pos_label):
                    prec += 1.0
            prec /= (i + 1.0)
            score += prec
    if (n_pos == 0):
        return 0
    return (score / n_pos)
Average precision at rank k
Parameters
----------
y_true : array-like, shape = [n_samples]
    Ground truth (true relevance labels).
y_score : array-like, shape = [n_samples]
    Predicted scores.
k : int
    Rank.
Returns
-------
average precision @k : float
def average_precision_score(y_true, y_score, k=10):
    'Average precision at rank k\n    Parameters\n    ----------\n    y_true : array-like, shape = [n_samples]\n        Ground truth (true relevance labels).\n    y_score : array-like, shape = [n_samples]\n        Predicted scores.\n    k : int\n        Rank.\n    Returns\n    -------\n    average precision @k : float\n    '
    unique_y = np.unique(y_true)
    if (len(unique_y) == 1):
        return ValueError('The score cannot be approximated.')
    elif (len(unique_y) > 2):
        raise ValueError('Only supported for two relevance levels.')
    pos_label = unique_y[1]
    n_pos = np.sum((y_true == pos_label))
    order = np.argsort(y_score)[::(- 1)][:min(n_pos, k)]
    y_true = np.asarray(y_true)[order]
    score = 0
    for i in range(len(y_true)):
        if (y_true[i] == pos_label):
            prec = 0
            for j in range(0, (i + 1)):
                if (y_true[j] == pos_label):
                    prec += 1.0
            prec /= (i + 1.0)
            score += prec
    if (n_pos == 0):
        return 0
    return (score / n_pos)