Tensorflow Keras自定义度量

Tensorflow Keras自定义度量,tensorflow,deep-learning,keras,Tensorflow,Deep Learning,Keras,我如何创建一个自定义指标,不仅当预测类别和真实类别相同时,而且当预测类别是真实类别的相邻类别时,在分类问题上接受正确的预测?如果您认为“只有一个类别”应该被输出,那么这个答案是有效的 def neighbourMetric(yTrue,yPred): #these make this function not differntiable, but since you asked for "metric" it's ok trueIndices = K.argmax(yTrue)

我如何创建一个自定义指标,不仅当预测类别和真实类别相同时,而且当预测类别是真实类别的相邻类别时,在分类问题上接受正确的预测?

如果您认为“只有一个类别”应该被输出,那么这个答案是有效的

def neighbourMetric(yTrue,yPred):

    #these make this function not differntiable, but since you asked for "metric" it's ok
    trueIndices = K.argmax(yTrue)
    predIndices = K.argmax(yPred)

    minAccepted = trueIndices - 1
    maxAccepted = trueIndices + 1


    satisfiesMin = K.cast(K.greater_equal(predIndices,minAccepted),K.floatx())
    satisfiesMax = K.cast(K.less_equal(predIndices,maxAccepted),K.floatx())

    satisfiesBoth = satisfiesMin * satisfiesMax

    return K.mean(satisfiesBoth)

我是这样解决的:

def one_off(y_true, y_pred):
    return K.cast(K.abs(K.argmax(y_true, axis=-1) -  K.argmax(y_pred, axis=-1)) < 2, K.floatx())
def one_off(y_true,y_pred):
返回K.cast(K.abs(K.argmax(y_-true,axis=-1)-K.argmax(y_-pred,axis=-1))<2,K.floatx()