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

作者:鹊踏枝 时间:2023-09-24 12:12:15 

在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)

来源:https://blog.csdn.net/u011501388/article/details/84030578

标签:Keras,自定义,损失,loss
0
投稿

猜你喜欢

  • 在vscode中配置python环境过程解析

    2021-10-08 20:28:15
  • ThinkPHP3.1.3版本新特性概述

    2023-09-28 15:25:11
  • python GUI库图形界面开发之PyQt5控件数据拖曳Drag与Drop详细使用方法与实例

    2022-04-19 04:22:39
  • Python实现Const详解

    2021-06-24 16:18:40
  • 仿QQ和MSN消息提示的效果代码

    2010-03-16 12:17:00
  • Django restframework 框架认证、权限、限流用法示例

    2023-01-17 15:51:20
  • python3.7 打包成exe程序方式(只需两行命令)

    2023-01-26 14:29:34
  • 解决Django数据库makemigrations有变化但是migrate时未变动问题

    2024-01-15 16:55:39
  • python构造icmp echo请求和实现网络探测器功能代码分享

    2023-07-14 15:53:43
  • Asp WinHttp.WinHttpRequest.5.1 对象使用详解

    2012-05-02 10:15:27
  • 举例讲解Python中的死锁、可重入锁和互斥锁

    2023-12-21 07:35:03
  • python使用 cx_Oracle 模块进行查询操作示例

    2022-06-17 05:55:24
  • 用ASP实现远程批量文件改名

    2007-09-12 12:23:00
  • Python向Excel中插入图片的简单实现方法

    2022-09-27 21:41:59
  • 带你快速搞定Mysql优化

    2024-01-26 19:25:37
  • Python实现聚类K-means算法详解

    2023-04-22 07:48:36
  • RS.GETROWS使用详解

    2008-01-16 13:21:00
  • 跟老齐学Python之赋值,简单也不简单

    2021-03-09 22:44:14
  • mysql中模糊查询的四种用法介绍

    2024-01-23 17:03:02
  • requests在python中发送请求的实例讲解

    2022-06-26 09:04:07
  • asp之家 网络编程 m.aspxhome.com