Ich möchte meine eigene binary_crossentropy anstelle der Verwendung der Keras-Bibliothek verwenden. Hier ist meine eigene Funktion:angepasste Verlustfunktion in Keras mit derano-Funktion
import theano
from keras import backend as K
def elementwise_multiply(a, b): # a and b are tensors
c = a * b
return theano.function([a, b], c)
def custom_objective(y_true, y_pred):
first_log = K.log(y_pred)
first_log = elementwise_multiply(first_log, y_true)
second_log = K.log(1 - y_pred)
second_log = elementwise_multiply(second_log, (1 - y_true))
result = second_log + first_log
return K.mean(result, axis=-1)
note: This is for practice. I'm aware of T.nnet.binary_crossentropy(y_pred, y_true)
Aber, wenn ich das Modell kompilieren:
sgd = SGD(lr=0.001)
model.compile(loss = custom_objective, optimizer = sgd)
ich diesen Fehler:
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) in() 36 37 sgd = SGD(lr=0.001) ---> 38 model.compile(loss = custom_objective, optimizer = sgd) 39 # ==============================================
C:\Program Files (x86)\Anaconda3\lib\site-packages\keras\models.py in compile(self, optimizer, loss, class_mode) 418 else: 419 mask = None --> 420 train_loss = weighted_loss(self.y, self.y_train, self.weights, mask) 421 test_loss = weighted_loss(self.y, self.y_test, self.weights, mask) 422
C:\Program Files (x86)\Anaconda3\lib\site-packages\keras\models.py in weighted(y_true, y_pred, weights, mask) 80 ''' 81 # score_array has ndim >= 2 ---> 82 score_array = fn(y_true, y_pred) 83 if mask is not None: 84 # mask should have the same shape as score_array
in custom_objective(y_true, y_pred) 11 second_log = K.log(1 - K.clip(y_true, K.epsilon(), np.inf)) 12 second_log = elementwise_multiply(second_log, (1-y_true)) ---> 13 result = second_log + first_log 14 #result = np.multiply(result, y_pred) 15 return K.mean(result, axis=-1)
TypeError: unsupported operand type(s) for +: 'Function' and 'Function'
wenn ich elementwise_multiply mit Inline-Funktion ersetzen :
def custom_objective(y_true, y_pred):
first_log = K.log(y_pred)
first_log = first_log * y_true
second_log = K.log(1 - y_pred)
second_log = second_log * (1-y_true)
result = second_log + first_log
return K.mean(result, axis=-1)
das Modell erstellt, aber der Verlustwert ist nan:
Epoch 1/1 945/945 [==============================] - 62s - loss: nan - acc: 0.0011 - val_loss: nan - val_acc: 0.0000e+00
jemand mir bitte dabei helfen könnte ?!
Dank
Die Fehlermeldung erscheint 'result = second_log + first_log' ist, um die Fehler anzuzeigen, da diese beide Funktionen sind. Haben Sie die Ausgabe von 'K.log' überprüft? –
@ M.T ja, die Ausgabe von K.log ist "Elemwise {log, no_inplace} .0". Ich habe gerade die Frage aktualisiert (fügte ein weiteres Szenario hinzu, in dem das Modell kompiliert, aber der Verlust ist nan) – Nejla