Keras自定义Loss函数

Keras本身提供了很多常用的loss函数(即目标函数),但这些损失函数都是比较基本的、通用的。有时候我们需要根据自己所做的任务来自定义损失函数,虽然Keras是一个很高级的封装,自定义loss还是比较简单的。
第一种方式:自定义函数
进入keras/keras/losses.py文件中,我们可以看到很多keras自带loss的实现代码,比如最简单的均方误差损失函数

def mean_squared_error(y_true,y_pred):
	return K.mean(K.square(y_pred-y_true),axis=-1)

其中y_true为网络给出的预测值,y_true即是标签,两者均为tensor。在loss中直接操作这两个变量即可实现自己想要的loss。例如,我们将其改为四次方的平均值来作为新的loss:

def mean_squared_error2(y_true, y_pred):
	return K.mean(K.square(K.square(y_pred-y_true)),axis=-1)

model编译阶段将loss指定为我们自定义的函数

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

!!!第二种方式:自定义一个层次!!!
在Keras自带的examples中又发现了另外一种定义loss函数的例子,该例子将新的损失函数定义为一个层次来使用。在keras/examples/variational_autoencoder.py文件中

# Custom loss layer
class CustomVariationalLayer(Layer):
    def __init__(self, **kwargs):
        self.is_placeholder = True
        super(CustomVariationalLayer, self).__init__(**kwargs)

    def vae_loss(self, x, x_decoded_mean):
        xent_loss = original_dim * metrics.binary_crossentropy(x, x_decoded_mean)#Square Loss
        kl_loss = - 0.5 * K.sum(1 + z_log_var - K.square(z_mean) - K.exp(z_log_var), axis=-1)# KL-Divergence Loss
        return K.mean(xent_loss + kl_loss)

    def call(self, inputs):
        x = inputs[0]
        x_decoded_mean = inputs[1]
        loss = self.vae_loss(x, x_decoded_mean)
        self.add_loss(loss, inputs=inputs)
        # We won't actually use the output.
        return x

该自定义层次的使用如下:

y = CustomVariationalLayer()[x,x_decoded_mean])
vae = Model(x,y)
vae.compile(optimizer='rmsprop',loss=None)

第一句代码中的x为输入数据,x_decoded_mean为网络的输出数据(除开网络的最后一层)。
compile函数中指定’loss’为None,表示loss已经作为一个层次在网络中了,不需要这里指定loss。
这里定义CustomVariationalLayer类别的对应内容可以视为
y = CustomVariationalLayer()[inputs,outputs]

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值