【发布时间】:2016-08-10 07:45:15
【问题描述】:
我正在使用keras 构建推荐模型。因为项目集非常大,我想计算Hits @ N metric 作为准确度的衡量标准。也就是说,如果观察到的项目在预测的前 N 个中,则视为相关推荐。
我能够使用numpy 在 N 函数处构建命中。但是当我试图将它移植到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
我应该如何以更紧凑、对张量友好的方式来处理这个问题?
更新:
我能够获得 Top 1 的一个版本。我大致基于GRU4Rec 描述
def custom_objective(y_true, y_pred):
y_pred_idx_sort = T.argsort(-y_pred, axis=1)[:,0] #returns the first element, which is the index of the row with the largest value
y_act_idx = T.argmax(y_true, axis=1)#returns an array of indexes with the top value
return T.cast(-T.mean(T.nnet.sigmoid((T.eq(y_pred_idx_sort,y_act_idx)))), theano.config.floatX)`
我只需将前 1 个预测的数组与实际元素的数组进行比较。 Theano 有一个 eq() 函数可以做到这一点。
【问题讨论】:
标签: python machine-learning keras deep-learning theano