python - 评估列表 : AvgP@K and R@K are they same?

标签 python algorithm machine-learning precision-recall

我的目标是了解平均K 时的精度K 时的召回率。我有两个列表,一个是预测的,另一个是实际的(ground truth)

让我们称这两个列表为预测的和实际的。现在我想做 precision@krecall@k

我使用 python 在 K 处实现了 Avg 精度,如下所示:

def apk(actual, predicted, k=10):
    """
    Computes the average precision at k.

    This function computes the average precision at k between two lists of items.

    Parameters
    ----------
    actual: list
            A list of elements that are to be predicted (order doesn't matter)
    predicted : list
            A list of predicted elements (order does matter)
    k: int, optional

    Returns
    -------
    score : double
            The average precision at k over the input lists

    """
    if len(predicted) > k:
        predicted = predicted[:k]

    score = 0.0
    num_hits = 0.0

    for i,p in enumerate(predicted):
        if p in actual and p not in predicted[:i]:
            num_hits += 1.0
            score += num_hits / (i + 1.0)

    if not actual:
        return 1.0
    if min(len(actual), k) == 0:
        return 0.0
    else:
        return score / min(len(actual), k)

假设我们的预测有 5 个字符串,顺序如下: 预测 = ['b','c','a','e','d'] 和实际 = ['a','b','e']因为我们正在做@k precision@k 是否与recall@k 相同?如果不是我该怎么做recall@k`

如果我想做f-measure (f-score),对于上面提到的列表,最好的方法是什么?

最佳答案

我想,您已经检查过 wiki .根据它的公式,第三个也是最大的一个(在“这个有限和等于:”一词之后),让我们看看每次迭代的示例:

  1. i=1 p = 1
  2. i=2 rel = 0
  3. i=3 p = 2/3
  4. i=4 p = 3/4
  5. i=5 相对 = 0

因此,avp@4 = avp@5 = (1 + 0.66 + 0.75)/3 = 0.805; avp@3 = (1 + 0.66)/3 等等。

召回@5 = 召回@4 = 3/3 = 1;召回@3 = 2/3;召回@2 =召回@1 = 1/3

下面是precision@k 和recall@k 的代码。我保留了您的符号,虽然使用 actual 表示观察值/返回值和使用 expected 表示基本事实似乎更常见(例如,参见 JUnit 默认值)。

def precision(actual, predicted, k):
    act_set = set(actual)
    pred_set = set(predicted[:k])
    result = len(act_set & pred_set) / float(k)
    return result

def recall(actual, predicted, k):
    act_set = set(actual)
    pred_set = set(predicted[:k])
    result = len(act_set & pred_set) / float(len(act_set))
    return result

关于python - 评估列表 : AvgP@K and R@K are they same?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28734607/

相关文章:

python - 将 sframe 列转换为列表

python - 在 Python 中连接两个 SQL 字符串列表

c++ - AVX2 中排序数组的高效稳定总和

python - split() 缺少 1 个必需的位置参数 : 'y'

python - 如何在 Python 中构建玩游戏的神经网络?

python - XGBoost CV 和最佳迭代

python - 当我们尝试将巨大的 Pandas 数据帧(40-5000 万行)转换为 Spark 2.0 数据帧时如何提高性能

python - 为什么我在使用 Python 时会遇到文件权限错误

algorithm - 如何找到图循环中的顶点

python - 合并迭代器产生模糊的结果