【发布时间】:2018-09-08 01:58:47
【问题描述】:
我正在尝试在 Keras 中实现一个自定义损失函数,其中每个单独的示例(不是类)具有不同的权重。
确切地说,考虑到通常的 y_true(例如 )和 y_pred(例如 ),我我正在尝试创建权重(例如)并将它们与binary_crossentropy损失函数一起使用。我试过了:
import numpy as np
from keras import backend as K
def my_binary_crossentropy(y_true, y_pred):
base_factor = 0.9
num_examples = K.int_shape(y_true)[0]
out = [ K.pow(base_factor, num_examples - i - 1) for i in range(num_examples) ]
forgetting_factors = K.stack(out)
return K.mean(
forgetting_factors * K.binary_crossentropy(y_true, y_pred),
axis=-1
)
在这个简单的例子中效果很好:
y_true = K.variable( np.array([1,1,0]) )
y_pred = K.variable( np.array([1,0.2,0.8]) )
print K.eval(my_binary_crossentropy(y_true, y_pred))
但是,当我将它与 model.compile(loss=my_binary_crossentropy, ...) 一起使用时,我收到以下错误:TypeError: range() integer end argument expected, got NoneType。
我已经尝试了一些东西。我用 K_shape 替换了 K.int_shape 现在得到:TypeError: range() integer end argument expected, got Tensor. 我进一步用 K.arange() 替换了 range() 现在得到:TypeError: Tensor objects are not iterable when eager execution is not enabled. To iterate over this tensor use tf.map_fn。
谁能帮帮我?我错过了什么?非常感谢!
【问题讨论】:
标签: python tensorflow keras loss-function