按公制计算命中率

2024-09-29 21:58:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用keras来构建推荐者模型。因为项集相当大,我想计算Hits @ N metric作为精度的度量。也就是说,如果观察到的项目在预测的前N位,则视为相关建议。在

我能够使用numpy在N处构建hits函数。但当我试图将它移植到keras的自定义损失函数中时,我遇到了张量的问题。具体来说,在张量上枚举是不同的。当我在语法中寻找等价的东西时,我开始质疑整个方法。它草率而缓慢,反映了我对python的熟悉程度。在

def hits_at(y_true, y_pred): #numpy version
    a=y_pred.argsort(axis=1) #ascending, sort by row, return index
    a = np.fliplr(a) #reverse to get descending
    a = a[:,0:10] #return only the first 10 columns of each row
    Ybool = [] #initialze 2D arrray
    for t, idx in enumerate(a):
        ybool = np.zeros(num_items +1) #zero fill; 0 index is reserved
        ybool[idx] = 1 #flip the recommended item from 0 to 1
        Ybool.append(ybool)
    A = map(lambda t: list(t), Ybool)
    right_sum = (A * y_true).max(axis=1) #element-wise multiplication, then find the max
    right_sum = right_sum.sum() #how many times did we score a hit?
    return right_sum/len(y_true) #fraction of observations where we scored a hit

我应该如何以一种更紧凑、更友好张量的方式来处理这个问题?在

更新:

我可以让一个版本的Top1工作。我松散地基于GRU4Rec描述

^{pr2}$

我只需要比较前1个预测的数组和实际元素的数组。而Theano有一个eq()函数来实现这一点。在


Tags: the函数rightnumpytrueindexreturnkeras
1条回答
网友
1楼 · 发布于 2024-09-29 21:58:28

与N无关,损失函数的可能值是有限的。因此,它不可能在一个有意义的张量方式下是可微的,你不能用它作为Keras/Theano中的损失函数。你可以试着在前N名球员中使用“无日志丢失”。在

更新:

在Keras中,您可以编写自己的损失函数。它们有一种形式的声明:

def loss_function(y_pred, y_true):

y_truey_pred都是numpy数组,所以你可以很容易地得到一个向量{},当给定的例子在前500名时为1,否则为0。然后,您可以将其转换为无张量常量向量,并按以下方式应用:

^{pr2}$

这应该可以正常工作。在

更新2:

对数损失和二进制熵是一样的。在

相关问题 更多 >

    热门问题