How to find loss values ​​using keras?

I want to use the loss function defined in keras to calculate the loss value manually. For instance:

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

gives me an error

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

Similarly, I want to use another keras loss function. I have y_pred and y_true lists / arrays.

+4
source share
2 answers

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

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]
+4
source

This works fine for me:

>>> import numpy as np
>>> from keras.losses import binary_crossentropy
>>> a = np.array([1,2,3,4])
>>> b = np.array([5,6,7,8])
>>> error = binary_crossentropy(a,b)
>>> error
mean
0
source

Source: https://habr.com/ru/post/1687929/


All Articles