如何使用张量流更正此自定义损失函数?

Mil*_*los 2 machine-learning keras tensorflow loss-function

我想编写一个自定义损失函数,该函数将权衡正目标值的低估。它将像均方误差一样工作,唯一的区别在于,在这种情况下,均方误差将乘以大于1的权重。

我这样写:

def wmse(ground_truth, predictions):
    square_errors = np.square(np.subtract(ground_truth, predictions))
    weights = np.ones_like(square_errors)
    weights[np.logical_and(predictions < ground_truth, np.sign(ground_truth) > 0)] =  100
    weighted_mse = np.mean(np.multiply(square_errors, weights))
    return weighted_mse
Run Code Online (Sandbox Code Playgroud)

然而,当我把它提供给我的顺序模型kerastensorflow作为后端:

model.compile(loss=wmse,optimizer='rmsprop')
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

 raise TypeError("Using a `tf.Tensor` as a Python `bool` is not allowed. 
TypeError: Using a `tf.Tensor` as a Python `bool` is not allowed. Use `if t is not None:` instead of `if t:` to test if a tensor is defined, and use TensorFlow ops such as tf.cond to execute subgraphs conditioned on the value of a tensor.
Run Code Online (Sandbox Code Playgroud)

追溯指向以下行wmse

weights[np.logical_and(predictions < ground_truth, np.sign(ground_truth) > 0)] =  100
Run Code Online (Sandbox Code Playgroud)

我从来没有工作过keras,也没有tensorflow到现在为止,因此,如果有人帮助我适应这个损失函数来我会很感激keras/ tensorflow框架。我试图取代np.logical_andtensorflow.logical_and,但无济于事,错误依然存在。

ben*_*che 5

就像@nuric提到的那样,您必须仅使用带有衍生工具的Keras / Tensorflow操作来实现损失,因为这些框架将无法通过其他操作(例如numpy操作)进行反向传播。

仅Keras的实现可能如下所示:

from keras import backend as K

def wmse(ground_truth, predictions):
    square_errors = (ground_truth - predictions) ** 2
    weights = K.ones_like(square_errors)
    mask = K.less(predictions, ground_truth) & K.greater(K.sign(ground_truth), 0)
    weights =  K.switch(mask, weights * 100, weights)
    weighted_mse = K.mean(square_errors * weights)
    return weighted_mse

gt = K.constant([-2, 2, 1, -1, 3], dtype="int32")
pred = K.constant([-2, 1, 1, -1, 1], dtype="int32")
weights, loss = wmse(gt, pred)

sess = K.get_session()
print(loss.eval(session=sess))
# 100
Run Code Online (Sandbox Code Playgroud)