我想在keras中定义自己的损失函数,并将bce_loss
与变量W
相乘。实际上,W
与张量bce_loss
的形状相同。
如果我打印张量bce_loss
,也许可以显示如下:
Tensor("loss_8/activation_14_loss/logistic_loss:0", shape=(?, 3), dtype=float32)
现在我不知道如何获得bce_loss
的形状,并使变量W
具有与bce_loss
相同的形状。
我的代码:
def myLoss(y_true, y_pred):
bce_loss = K.binary_crossentropy(y_true, y_pred)
# want to get a variable W with the same shape of bce_loss
# And W is initialized with normal distribution.
val = np.random.normal(0, 0.05, size= bce_loss.size())
W = keras.variable( val )
return K.mean(self.W*bce_loss, axis = -1)
答案 0 :(得分:2)
您可以这样定义损失函数:
from keras import backend as K
import numpy as np
def myLoss(y_true, y_pred):
bce_loss = K.binary_crossentropy(y_true, y_pred)
w = K.random_normal(K.shape(bce_loss), 0, 0.05)
return K.mean(w * bce_loss, axis=-1)
y_t = K.placeholder((1,2))
y_p = K.placeholder((1,2))
loss = myLoss(y_t, y_p)
print(K.get_session().run(loss, {y_t: np.array([[1,1]]), y_p: np.array([[0.5, 0.2]])}))