Keras 라이브러리와 함께 제공되는 대신 자체 binary_crossentropy를 사용하고 싶습니다.theano 함수를 사용하여 keras에서 사용자 정의 손실 함수
sgd = SGD(lr=0.001)
model.compile(loss = custom_objective, optimizer = sgd)
내가이 오류를 얻을 : I 모델 컴파일 할 때
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)
하지만, :
--------------------------------------------------------------------------- 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'
을 나는 인라인 함수와 elementwise_multiply 교체 할 때 여기 내 사용자 지정 기능입니다 :
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)
모델은 손실 값이 유모 않고 컴파일 :
이Epoch 1/1 945/945 [==============================] - 62s - loss: nan - acc: 0.0011 - val_loss: nan - val_acc: 0.0000e+00
누군가가 이것 좀 도와 줘요 수 없습니다!
감사합니다.
오류 메시지가이 두 기능은 같은'결과 = second_log + first_log'되는 오류를 나타내는 것으로 보인다. 'K.log'의 출력을 확인 했습니까? –
@ M.T 예, K.log의 출력은 "Elemwise {log, no_inplace} .0"입니다. 방금 질문을 업데이트했습니다 (모델이 컴파일되지만 손실이없는 시나리오가 추가됨) – Nejla