微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 keras 进行 RNN 的三重网络

如何解决使用 keras 进行 RNN 的三重网络

我正在尝试为三元组损失编写一个自定义损失函数(使用 keras),它需要 3 个参数锚点,正负。三元组使用 gru 层生成,model.fit 的参数通过数据生成器提供。

我面临的问题是训练时:

TypeError: Cannot convert a symbolic Keras input/output to a numpy array. 
This error may indicate that you're trying to pass a symbolic value to a NumPy 
call,which is not supported. Or,you may be trying to pass Keras symbolic 
inputs/outputs to a TF API that does not register dispatching,preventing Keras from automatically 
converting the API call to a lambda layer in the Functional Model.

损失函数的实现

def batch_hard_triplet_loss(self,anchor_embeddings,pos_embeddings,neg_embeddings,margin):
    def loss(y_true,y_pred):
        '''print(anchor_embeddings)
        print(pos_embeddings)
        print(neg_embeddings)'''
        # distance between the anchor and the positive
        pos_dist = K.sum(K.square(anchor_embeddings - pos_embeddings),axis=-1)
        max_pos_dist = K.max(pos_dist)
        # distance between the anchor and the negative
        neg_dist = K.sum(K.square(anchor_embeddings - neg_embeddings),axis=-1)
        max_neg_dist = K.min(neg_dist)
        # compute loss
        basic_loss = max_pos_dist - max_neg_dist + margin
        tr_loss = K.maximum(basic_loss,0.0)
        return tr_loss
    #return triplet_loss

    return loss

这可能是因为 keras 期望数组作为返回损失,但我提供的是标量值吗?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。