16
votes

I want to use the various loss function defined in keras for calculating the loss value manually. For example:

from keras.losses import binary_crossentropy
error=binary_crossentropy([1,2,3,4],[6,7,8,9])

gives me error

AttributeError: 'list' object has no attribute 'dtype'.

Similar way I want to use other keras loss function. I have my y_pred and y_true lists/arrays.

1
use numpy arrays instead of lists - Skyy2010
Done that, converted my list to numpy array but I get this AttributeError: 'numpy.dtype' object has no attribute 'base_dtype'. ​ - Bhaskar Dhariyal

1 Answers

24
votes

You can use K.variable() to wrap the inputs and use K.eval() to get the value.

from keras.losses import binary_crossentropy
from keras import backend as K
y_true = K.variable(np.array([[1], [0], [1], [1]]))
y_pred = K.variable(np.array([[0.5], [0.6], [0.7], [0.8]]))
error = K.eval(binary_crossentropy(y_true, y_pred))

print(error)
[ 0.69314718  0.91629082  0.35667494  0.22314353]