python - 如何在 Keras 中定义具有相同形状张量的变量?
问题描述
我想在 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)
解决方案
您可以像这样定义损失函数:
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]])}))