本文介绍了Keras自定义功能:实现Jaccard的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Tensorflow作为后端,在Keras LSTM中将Jaccard系数用作自定义损失函数.

I am trying to apply the Jaccard coefficient as customised loss function in a Keras LSTM, using Tensorflow as backend.

我知道我必须打以下电话:

I know the I have to call the following:

model.compile(optimizer='rmsprop', loss=[jaccard_similarity])

其中jaccard_similarity函数应为以下的keras.backend实现:

where jaccard_similarity function should be the keras.backend implementation of the below:

def jaccard_similarity(doc1, doc2):
   intersection =set(doc1).intersection(set(doc2))
   union = set(doc1).union(set(doc2))
   return len(intersection)/len(union)

问题是我找不到使用tensorflow作为后端在张量上实现交集和并集函数的方法.

The problem is that I cannot find methods to implement intersection and union functions on tensors using tensorflow as backend.

有什么建议吗?

推荐答案

我已经使用jaccard距离来训练keras中的语义分割网络.我使用的损失函数与.我将其粘贴在这里:

I've used the jaccard distance to train a semantic segmentation network in keras. The loss function I used is identidical to this one. I'll paste it here:

from keras import backend as K
def jaccard_distance(y_true, y_pred, smooth=100):
    intersection = K.sum(K.abs(y_true * y_pred), axis=-1)
    sum_ = K.sum(K.abs(y_true) + K.abs(y_pred), axis=-1)
    jac = (intersection + smooth) / (sum_ - intersection + smooth)
    return (1 - jac) * smooth

请注意,这要减去jaccard相似度(您要使其最大化).实际上,它是jaccard距离的连续近似值,因此其导数得到了很好的定义.

Notice that this one minus the jaccard similarity (which you want to maximize). In fact, it's a continuous approximation of the jaccard distance, so it's derivative is well defined.

这篇关于Keras自定义功能:实现Jaccard的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!