【问题标题】:Calculate Hits At metric in Theano在 Theano 中计算 Hits At 指标
【发布时间】: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


    【解决方案1】:

    与 N 无关,损失函数的可能值的数量是有限的。因此,它不能以合理的张量方式进行微分,并且您不能将其用作 Keras / Theano 中的损失函数。您可以尝试对前 N 个家伙使用 theano log loss。

    更新:

    在 Keras 中 - 您可以编写自己的损失函数。他们有一个表格声明:

    def loss_function(y_pred, y_true):
    

    y_truey_pred 都是 numpy 数组,因此您可以轻松获得一个向量 v,当给定的示例在前 500 名时为 1,否则为 0。然后您可以将其转换为 theano 张量常数向量并以某种方式应用它:

    return theano.tensor.net.binary_crossentropy(y_pred * v, y_true * v)
    

    这应该可以正常工作。

    更新 2:

    对数损失与 binary_crossentropy 相同。

    【讨论】:

    • 我目前正在使用 categorical_crossentropy;我不熟悉“前 N 的日志丢失”。是否以某种方式扩展deeplearning.net/tutorial/logreg.html#the-model
    • Hrm,看来y_pred 和y_true 实际上是张量,而不是numpy 数组。这有点复杂,因为找到域并对其进行迭代比对 numpy 数组执行相同操作更复杂。
    • 这超出了我的编码能力。然而,这个逻辑很好地回答了这个问题,所以我很高兴接受它是正确的。
    • 我在处理我的一个工作项目时遇到了类似的问题。它有效 - 但它适用于旧版本的 Keras。我也会在最近的将来使用类似的东西,所以我会分享我的研究结果:)谢谢:)
    • 如果你能想到的话,那对你很有帮助;谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-08
    • 2017-03-31
    • 2015-10-24
    • 2016-04-01
    • 1970-01-01
    • 2015-09-16
    相关资源
    最近更新 更多