自定义损失函数Keras Tensorflow [英] Custom Loss function Keras Tensorflow

查看:383
本文介绍了自定义损失函数Keras Tensorflow的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要自定义加权MSE损失函数.我在keras.backend

I need a custom weighted MSE loss function. I defined it in keras.backend

from keras import backend as K
def weighted_loss(y_true, y_pred):
    return K.mean( K.square(y_pred - y_true) *
    K.exp(-K.log(1.7) * (K.log(1. + K.exp((y_true - 3)/5 ))))      
    ,axis=-1  )

但是,测试运行会返回

    weighted_loss(1,2)
ValueError: Tensor conversion requested dtype int32 for Tensor with dtype float32: 'Tensor("Exp_37:0", shape=(), dtype=float32)'  

    weighted_loss(1.,2.)
ZeroDivisionError: integer division or modulo by zero   

我想知道我在这里犯了什么错误.

I wonder what mistakes am I making here.

推荐答案

您使用的是Tensorflow还是Theano与您的问题无关.如果该术语使您感到困惑,则Google会使用张量"的含义.

Whether you are using Tensorflow or Theano is irrelevant for your question. Google the meaning of 'tensor' if the term confuses you.

看看Keras自己的损失函数测试是如何实现的

Take a look at how Keras own loss function tests have been implemented here:

def test_metrics():
    y_a = K.variable(np.random.random((6, 7)))
    y_b = K.variable(np.random.random((6, 7)))
    for metric in all_metrics:
        output = metric(y_a, y_b)
        print(metric.__name__)
        assert K.eval(output).shape == (6,)

您不能简单地将浮点数或整数输入张量计算.还要注意使用K.eval来获得您想要的结果.

You can't simply feed a float or int into tensor calculations. Note also the use of K.eval to obtain the result you're looking for.

因此,请尝试使用与您的功能相似的内容:

So try something similar with your function:

from keras import backend as K
import numpy as np

y_a = K.variable(np.random.random((6, 7)))
y_b = K.variable(np.random.random((6, 7)))
output = weighted_loss(y_a,y_b)
result = K.eval(output)

也无需在keras.backend中定义您的自定义函数-如果您以后决定更新Keras,该怎么办?

There is also no need to define your custom function in keras.backend - what if you decide to update Keras later on?

相反,您可以在自己的代码中执行以下操作:定义一个返回损失函数的函数

Instead you could do the following in your own code: define a function that returns your loss function

def weighted_loss(y_true, y_pred):
        return K.mean( K.square(y_pred - y_true) * K.exp(-K.log(1.7) * (K.log(1. + K.exp((y_true - 3)/5 )))),axis=-1  )

然后,当您要使用损失函数编译模型时,可以执行以下操作:

Then when you want to compile your model with your loss function, you can do:

model.compile(loss = weighted_loss)

如果要定义一个更通用的损失函数,其中权重取决于某些输入,则需要包装该函数.例如:

In case you want to define a more general loss function, where the weighting depends on some input, you'll need to wrap the function. So for example:

def get_weighted_loss(my_input):
    def weighted_loss(y_true, y_pred):
        return K.mean( K.square(y_pred - y_true) * K.exp(-K.log(1.7) * (K.log(1. + K.exp((y_true - 3)/my_input )))),axis=-1  )
    return weighted_loss

然后,当您要使用损失函数编译模型时,可以执行以下操作:

Then when you want to compile your model with your loss function, you can do:

model.compile(loss = get_weighted_loss(5))

这篇关于自定义损失函数Keras Tensorflow的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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