7

What's the threshold value of binary_accuracy in keras Metrices is used to predicted one sample as positive and negative cases? is that threshold value 0.5? how to adjust it? I want to set the threshold value 0.80, if the predicted value is 0.79, then it is considered a negative sample,otherwise,if the predicted value is 0.81, then it is considered a positive sample.

1

3 Answers 3

6

binary_accuracy don't have threshold param but you can easily define one yourself.

import keras
from keras import backend as K

def threshold_binary_accuracy(y_true, y_pred):
    threshold = 0.80
    if K.backend() == 'tensorflow':
        return K.mean(K.equal(y_true, K.tf.cast(K.lesser(y_pred,threshold), y_true.dtype)))
    else:
        return K.mean(K.equal(y_true, K.lesser(y_pred,threshold)))

a_pred = K.variable([.1, .2, .6, .79, .8, .9])
a_true = K.variable([0., 0., 0.,  0., 1., 1.])

print K.eval(keras.metrics.binary_accuracy(a_true, a_pred))
print K.eval(threshold_binary_accuracy(a_true, a_pred))

Now you can use it as metrics=[threshold_binary_accuracy]

3
  • So, if one were to set threshold=0.5, they should get the same value as if they just used the default "accuracy" metric, right? I'm getting wildly different values when I do this... Aug 28, 2017 at 3:37
  • def binary_accuracy(y_true, y_pred, threshold=0.5): threshold = math_ops.cast(threshold, y_pred.dtype) y_pred = math_ops.cast(y_pred > threshold, y_pred.dtype) return K.mean(math_ops.equal(y_true, y_pred), axis=-1) Seems standard in Tensorflow but not in Keras. This function works exactly like the normal binary accuracy in Keras. Encountered the same problem as you, there is definitely something wrong with the suggested method.
    – Axl
    Mar 1, 2019 at 9:17
  • @MonicaHeddneck any luck with this issue ?
    – ace
    Jun 5, 2019 at 12:14
6

To answer the initial question, keras uses the round function to assign classes, so the threshold is 0.5.

https://github.com/fchollet/keras/blob/master/keras/metrics.py

def binary_accuracy(y_true, y_pred):
    return K.mean(K.equal(y_true, K.round(y_pred)))
2

Even faster, if you use tf 2 you can use: tf.keras.metrics.BinaryAccuracy() which has an internal threshold argument that you can set

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.