如何为具有tensorflow的角膜更正此自定义损失函数? [英] How to correct this custom loss function for keras with tensorflow?

查看:72
本文介绍了如何为具有tensorflow的角膜更正此自定义损失函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to write a custom loss function that would penalize underestimation of positive target values with weights. It would work like mean square error, with the only difference that square errors in said case would get multiplied with a weight greater than 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

但是,当我将其提供给keras中以tensorflow作为后端的Sequential模型时:

However, when I supply it to my Sequential model in keras with tensorflow as backend:

model.compile(loss=wmse,optimizer='rmsprop')

我收到以下错误:

 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.

回溯指向wmse中的此行:

weights[np.logical_and(predictions < ground_truth, np.sign(ground_truth) > 0)] =  100

到目前为止,我从未使用过kerastensorflow,因此,如果有人帮助我将此损失函数调整为keras/tensorflow框架,我将不胜感激.我尝试将np.logical_and替换为tensorflow.logical_and,但无济于事,该错误仍然存​​在.

I have never worked with keras nor tensorflow until now, so I'd appreciate if someone helped me to adapt this loss function to keras/tensorflow framework. I tried to replace np.logical_and with tensorflow.logical_and, but to no avail, the error is still there.

推荐答案

如@nuric所述,您必须仅使用带有衍生工具的Keras/Tensorflow操作来实现损失,因为这些框架将无法反向传播其他操作(例如numpy的操作).

As @nuric mentioned, you have to implement your loss using only Keras / Tensorflow operations with derivatives, as these frameworks won't be able to back-propagate through other operations (like numpy ones).

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

A Keras only implementation could look like this:

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

这篇关于如何为具有tensorflow的角膜更正此自定义损失函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆