Keras之自定义损失(loss)函数用法说明

 更新时间:2020年06月10日 08:41:51   作者:鹊踏枝  
这篇文章主要介绍了Keras之自定义损失(loss)函数用法说明,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

在Keras中可以自定义损失函数,在自定义损失函数的过程中需要注意的一点是,损失函数的参数形式,这一点在Keras中是固定的,须如下形式:

def my_loss(y_true, y_pred):
# y_true: True labels. TensorFlow/Theano tensor
# y_pred: Predictions. TensorFlow/Theano tensor of the same shape as y_true
 .
 .
 .
 return scalar #返回一个标量值

然后在model.compile中指定即可,如:

model.compile(loss=my_loss, optimizer='sgd')

具体参考Keras官方metrics的定义keras/metrics.py

"""Built-in metrics.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
 
import six
from . import backend as K
from .losses import mean_squared_error
from .losses import mean_absolute_error
from .losses import mean_absolute_percentage_error
from .losses import mean_squared_logarithmic_error
from .losses import hinge
from .losses import logcosh
from .losses import squared_hinge
from .losses import categorical_crossentropy
from .losses import sparse_categorical_crossentropy
from .losses import binary_crossentropy
from .losses import kullback_leibler_divergence
from .losses import poisson
from .losses import cosine_proximity
from .utils.generic_utils import deserialize_keras_object
from .utils.generic_utils import serialize_keras_object
 
def binary_accuracy(y_true, y_pred):
 return K.mean(K.equal(y_true, K.round(y_pred)), axis=-1)
 
 
def categorical_accuracy(y_true, y_pred):
 return K.cast(K.equal(K.argmax(y_true, axis=-1),
       K.argmax(y_pred, axis=-1)),
     K.floatx())
 
def sparse_categorical_accuracy(y_true, y_pred):
 # reshape in case it's in shape (num_samples, 1) instead of (num_samples,)
 if K.ndim(y_true) == K.ndim(y_pred):
  y_true = K.squeeze(y_true, -1)
 # convert dense predictions to labels
 y_pred_labels = K.argmax(y_pred, axis=-1)
 y_pred_labels = K.cast(y_pred_labels, K.floatx())
 return K.cast(K.equal(y_true, y_pred_labels), K.floatx())
 
def top_k_categorical_accuracy(y_true, y_pred, k=5):
 return K.mean(K.in_top_k(y_pred, K.argmax(y_true, axis=-1), k), axis=-1)
 
def sparse_top_k_categorical_accuracy(y_true, y_pred, k=5):
 # If the shape of y_true is (num_samples, 1), flatten to (num_samples,)
 return K.mean(K.in_top_k(y_pred, K.cast(K.flatten(y_true), 'int32'), k),
     axis=-1)
 
# Aliases
 
mse = MSE = mean_squared_error
mae = MAE = mean_absolute_error
mape = MAPE = mean_absolute_percentage_error
msle = MSLE = mean_squared_logarithmic_error
cosine = cosine_proximity
 
def serialize(metric):
 return serialize_keras_object(metric)
 
def deserialize(config, custom_objects=None):
 return deserialize_keras_object(config,
         module_objects=globals(),
         custom_objects=custom_objects,
         printable_module_name='metric function')
 
def get(identifier):
 if isinstance(identifier, dict):
  config = {'class_name': str(identifier), 'config': {}}
  return deserialize(config)
 elif isinstance(identifier, six.string_types):
  return deserialize(str(identifier))
 elif callable(identifier):
  return identifier
 else:
  raise ValueError('Could not interpret '
       'metric function identifier:', identifier)

以上这篇Keras之自定义损失(loss)函数用法说明就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • Python语言的自我介绍一起来看看

    Python语言的自我介绍一起来看看

    这篇文章主要为大家详细介绍了Python语言的自我介绍,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
    2022-02-02
  • python+opencv轮廓检测代码解析

    python+opencv轮廓检测代码解析

    这篇文章主要介绍了python+opencv轮廓检测代码解析,本文实例实现对图片的简单处理,比如图片的读取,灰度显示等相关内容,具有一定借鉴价值,需要的朋友可以参考下
    2018-01-01
  • Python利用matplotlib生成图片背景及图例透明的效果

    Python利用matplotlib生成图片背景及图例透明的效果

    这篇文章主要给大家介绍了Python利用matplotlib生成图片背景及图例透明效果的相关资料,文中给出了详细的示例代码,相信对大家具有一定的参考家价值,需要的朋友们下面来一起学习学习吧。
    2017-04-04
  • 简单了解python中的f.b.u.r函数

    简单了解python中的f.b.u.r函数

    这篇文章主要介绍了简单了解python中的f.b.u.r函数,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-11-11
  • python3使用diagrams绘制架构图的步骤

    python3使用diagrams绘制架构图的步骤

    这篇文章主要介绍了python3使用diagrams生成架构图的步骤,帮助大家更好的理解和学习使用python,感兴趣的朋友可以了解下
    2021-04-04
  • python2与python3的print及字符串格式化小结

    python2与python3的print及字符串格式化小结

    最近一直在用python写程序,对于python的print一直很恼火,老是不按照预期输出。今天特来总结一样print和format,也希望能帮助大家彻底理解它们
    2018-11-11
  • 基于Python实现自动抠图小程序

    基于Python实现自动抠图小程序

    这篇文章主要为了大家利用用Python制作一款界面化的抠图小程序,文中的示例代码讲解详细,对我们学习Python有一定的帮助,感兴趣的可以学习一下
    2022-01-01
  • python中 chr unichr ord函数的实例详解

    python中 chr unichr ord函数的实例详解

    这篇文章主要介绍了python中 chr unichr ord函数的实例详解的相关资料,需要的朋友可以参考下
    2017-08-08
  • python多行字符串拼接使用小括号的方法

    python多行字符串拼接使用小括号的方法

    今天小编就为大家分享一篇python多行字符串拼接使用小括号的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-07-07
  • python运行脚本文件的三种方法实例

    python运行脚本文件的三种方法实例

    在计算中,脚本一词用于指代包含订单逻辑序列的文件或批处理文件,下面这篇文章主要给大家介绍了关于python运行脚本文件的三种方法,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2022-06-06

最新评论