python计算mAP

mAP(mean Average Precision)是信息检索和推荐系统领域评估算法性能的重要指标。

If you have an algorithm that is returning a ranked ordering of items, each item is either hit or miss (like relevant vs. irrelevant search results) and items further down in the list are less likely to be used (like search results at the bottom of the page), then maybe MAP is the metric for you!

我用python实现了如下形式的mAP :

具体代码如下:

# 计算mAP指标
def get_mAP(y_trues, y_preds, m, n, digts):
    """
    :param y_trues:1-D list
    :param y_preds:2-D list
    :param m:number of labels of each sample
    :param n: number of samples
    :param digts: decimal places
    :return: a float number
    """
    k = len(y_preds[0])     # 每个测试样本的预测标签数量
    y_trues = [[y_trues[i]]*k for i in range(len(y_trues))]
    avg_precisions = []      # 存放每个样本的average precision的列表
    for j in range(len(y_trues)):
        y_true = y_trues[j]     # 举例:真实标签列表,[1, 1, 1]
        y_pred = y_preds[j]     # 举例:预测标签列表,[0, 0, 1]
        cur_hit_num = 0     # 当前命中数量
        hit_list = [int(y_true[s] == y_pred[s]) for s in range(k)]  # 举例:[0, 1, 1]
        print('hit_list:', hit_list)
        precision_k = []
        k_index = 0  # 元素对应索引
        for o in hit_list:
            k_index += 1
            if o == 1:
                cur_hit_num += 1  # 遍历到目前为止命中元素数量
                # precision@k
                precision_k.append(float(cur_hit_num) / k_index)
            else:
                cur_hit_num += 0
                # precision@k
                precision_k.append(float(cur_hit_num) / k_index)
        print('precision_k:', precision_k)

        try:
            avg_precision = (1 / m) * sum([hit_list[s] * precision_k[s] for s in range(k)])
        except ZeroDivisionError:
            avg_precision = 0.0
        print('avg_precision:', avg_precision)
        avg_precisions.append(avg_precision)
    print('avg_precisions:', avg_precisions)
    mAP = round(sum(avg_precisions) / n, digts)
    return mAP


if __name__ == '__main__':
    # 注意输入格式
    y_tures = [1, 2, 3]
    y_preds = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
    map = get_mAP(y_tures, y_preds, m=1, n=3, digts=3)
    print('mAP:', map)

效果如下图所示:

 

编程过程参考了

Mean Average Precision (MAP) For Recommender Systems

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值