def dcg_from_ranking(y_true, ranking):
    'Discounted cumulative gain (DCG) 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    DCG @k : float\n    '
    y_true = np.asarray(y_true)
    ranking = np.asarray(ranking)
    rel = y_true[ranking]
    gains = ((2 ** rel) - 1)
    discounts = np.log2((np.arange(len(ranking)) + 2))
    return np.sum((gains / discounts))
Discounted cumulative gain (DCG) 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
-------
DCG @k : float
def dcg_from_ranking(y_true, ranking):
    'Discounted cumulative gain (DCG) 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    DCG @k : float\n    '
    y_true = np.asarray(y_true)
    ranking = np.asarray(ranking)
    rel = y_true[ranking]
    gains = ((2 ** rel) - 1)
    discounts = np.log2((np.arange(len(ranking)) + 2))
    return np.sum((gains / discounts))