【问题标题】:How to access y_true values in custom cost function?如何在自定义成本函数中访问 y_true 值?
【发布时间】:2020-08-02 07:16:52
【问题描述】:

我想编写一个自定义成本函数,我想在其中访问 y_true 和 y_pred 的值。 就像在这个例子中一样,他们直接使用 y_pred - y_true 但我想访问这些元素以进行其他操作。

def custom_loss(layer):
    def loss(y_true,y_pred):
        return K.mean(K.square(y_pred - y_true) + K.square(layer), axis=-1)
    return loss

那么我该如何使用这些元素呢?

【问题讨论】:

    标签: tensorflow machine-learning keras deep-learning data-science


    【解决方案1】:

    您可以像操作 numpy 数组一样使用它们,尽管这次 y_truey_pred 是张量,而不是 numpy 数组。

    看这个例子:

    def triplet_loss(y_true, y_pred, cosine=True, alpha=0.2, embedding_size=128):
        ind = int(embedding_size * 2)
        print('Shape of y pred is:', y_pred.shape)
        a_pred = y_pred[:, :embedding_size]
        p_pred = y_pred[:, embedding_size:ind]
        n_pred = y_pred[:, ind:]
    
        if cosine:
            positive_distance = 1 - K.sum((a_pred * p_pred), axis=-1)
            negative_distance = 1 - K.sum((a_pred * n_pred), axis=-1)
        else:
            positive_distance = K.sqrt(K.sum(K.square(a_pred - p_pred), axis=-1))
            negative_distance = K.sqrt(K.sum(K.square(a_pred - n_pred), axis=-1))
        loss = K.maximum(0.0, positive_distance - negative_distance + alpha)
        return loss
    

    这实际上是 Siamese Networks 中特定问题的损失函数;但要点是y_pred是通过切片来操作的。

    因此,您可以根据需要对y_truey_pred 的某些部分进行切片/选择。

    【讨论】:

    • 实际上我的问题是 y_true 并且 y_pred 是多标签,我需要找到在 t 迭代中计算损失函数时它预测的类是什么,所以我需要获取那些并且还需要找到那里的嵌入.所以当我在做 np.where(y_true) 时,它给了我一个错误,这没关系,因为它是一个张量,我们使用的是一个数组。那么我们能做些什么呢。
    • 我有一个字典 {"Class_labels" : "embeddings"} ,在损失函数中,我需要在每次迭代中找到 y_pred 类,并且还需要获取相应的嵌入,然后需要用实际类的嵌入,因此可以减少它们之间的差异。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-12
    • 2020-07-16
    • 2020-09-27
    • 2019-01-15
    • 2020-01-19
    • 1970-01-01
    相关资源
    最近更新 更多