def ndcg_from_ranking(y_true, ranking):
    'Normalized discounted cumulative gain (NDCG) at rank k\n    Parameters\n    ----------\n    y_true : array-like, shape = [n_samples]\n        Ground truth (true relevance labels).\n    ranking : array-like, shape = [k]\n        Document indices, i.e.,\n            ranking[0] is the index of top-ranked document,\n            ranking[1] is the index of second-ranked document,\n            ...\n    k : int\n        Rank.\n    Returns\n    -------\n    NDCG @k : float\n    '
    k = len(ranking)
    best_ranking = np.argsort(y_true)[::(- 1)]
    best = dcg_from_ranking(y_true, best_ranking[:k])
    return (dcg_from_ranking(y_true, ranking) / best)
Normalized discounted cumulative gain (NDCG) at rank k
Parameters
----------
y_true : array-like, shape = [n_samples]
    Ground truth (true relevance labels).
ranking : array-like, shape = [k]
    Document indices, i.e.,
        ranking[0] is the index of top-ranked document,
        ranking[1] is the index of second-ranked document,
        ...
k : int
    Rank.
Returns
-------
NDCG @k : float
def ndcg_from_ranking(y_true, ranking):
    'Normalized discounted cumulative gain (NDCG) at rank k\n    Parameters\n    ----------\n    y_true : array-like, shape = [n_samples]\n        Ground truth (true relevance labels).\n    ranking : array-like, shape = [k]\n        Document indices, i.e.,\n            ranking[0] is the index of top-ranked document,\n            ranking[1] is the index of second-ranked document,\n            ...\n    k : int\n        Rank.\n    Returns\n    -------\n    NDCG @k : float\n    '
    k = len(ranking)
    best_ranking = np.argsort(y_true)[::(- 1)]
    best = dcg_from_ranking(y_true, best_ranking[:k])
    return (dcg_from_ranking(y_true, ranking) / best)