3

我的目标是了解 AveragePrecision at KRecall at K. 我有两个列表,一个是预测的,另一个是实际的(基本事实)

让我们将这两个列表称为预测的和实际的。现在我想做precision@kand recall@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 个字符串,顺序如下: predicted = ['b','c','a','e','d'] andactual = ['a','b','e'] since we are doing @k would the precision@k is same asrecall@k ? If not how would I dorecall@k`

如果我想做f-measure (f-score)上述列表的最佳途径是什么?

4

1 回答 1

8

我猜,你已经检查过wiki了。根据它的公式,第三个和最大的一个(在“这个有限和等于:”这个词之后),让我们看看每次迭代的例子:

  1. 我=1 p = 1
  2. 我=2 相对= 0
  3. i=3 p = 2/3
  4. i=4 p = 3/4
  5. 我=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
于 2015-02-26T20:48:48.743 回答