以下信息均来自官网

------------------------------------------------------------------------------------------------------------

损失函数的使用

损失函数(或称目标函数、优化评分函数)是编译模型时所需的两个参数之一:

model.compile(loss='mean_squared_error', optimizer='sgd')
from keras import losses model.compile(loss=losses.mean_squared_error, optimizer='sgd')

你可以传递一个现有的损失函数名,或者一个 TensorFlow/Theano 符号函数。 该符号函数为每个数据点返回一个标量,有以下两个参数:

  • y_true: 真实标签。TensorFlow/Theano 张量。
  • y_pred: 预测值。TensorFlow/Theano 张量,其 shape 与 y_true 相同。

实际的优化目标是所有数据点的输出数组的平均值。

可用损失函数

mean_squared_error

mean_squared_error(y_true, y_pred)

mean_absolute_error

mean_absolute_error(y_true, y_pred)

mean_absolute_percentage_error

mean_absolute_percentage_error(y_true, y_pred)

mean_squared_logarithmic_error

mean_squared_logarithmic_error(y_true, y_pred)

squared_hinge

squared_hinge(y_true, y_pred)

hinge

hinge(y_true, y_pred)

categorical_hinge

categorical_hinge(y_true, y_pred)

logcosh

logcosh(y_true, y_pred)

预测误差的双曲余弦的对数。

对于小的 xlog(cosh(x)) 近似等于 (x ** 2) / 2。对于大的 x,近似于 abs(x) - log(2)。这表示 'logcosh' 与均方误差大致相同,但是不会受到偶尔疯狂的错误预测的强烈影响。

参数

  • y_true: 目标真实值的张量。
  • y_pred: 目标预测值的张量。

返回

每个样本都有一个标量损失的张量。


categorical_crossentropy

categorical_crossentropy(y_true, y_pred)

sparse_categorical_crossentropy

sparse_categorical_crossentropy(y_true, y_pred)

binary_crossentropy

binary_crossentropy(y_true, y_pred)

kullback_leibler_divergence

kullback_leibler_divergence(y_true, y_pred)

poisson

poisson(y_true, y_pred)

cosine_proximity

cosine_proximity(y_true, y_pred)

注意: 当使用 categorical_crossentropy 损失时,你的目标值应该是分类格式 (即,如果你有 10 个类,每个样本的目标值应该是一个 10 维的向量,这个向量除了表示类别的那个索引为 1,其他均为 0)。 为了将 整数目标值 转换为 分类目标值,你可以使用 Keras 实用函数 to_categorical

from keras.utils.np_utils import to_categorical

categorical_labels = to_categorical(int_labels, num_classes=None)

如果还不明白,请看下面的源码
 """Built-in loss functions.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function import six
from . import backend as K
from .utils.generic_utils import deserialize_keras_object
from .utils.generic_utils import serialize_keras_object def mean_squared_error(y_true, y_pred):
return K.mean(K.square(y_pred - y_true), axis=-1) def mean_absolute_error(y_true, y_pred):
return K.mean(K.abs(y_pred - y_true), axis=-1) def mean_absolute_percentage_error(y_true, y_pred):
diff = K.abs((y_true - y_pred) / K.clip(K.abs(y_true),
K.epsilon(),
None))
return 100. * K.mean(diff, axis=-1) def mean_squared_logarithmic_error(y_true, y_pred):
first_log = K.log(K.clip(y_pred, K.epsilon(), None) + 1.)
second_log = K.log(K.clip(y_true, K.epsilon(), None) + 1.)
return K.mean(K.square(first_log - second_log), axis=-1) def squared_hinge(y_true, y_pred):
return K.mean(K.square(K.maximum(1. - y_true * y_pred, 0.)), axis=-1) def hinge(y_true, y_pred):
return K.mean(K.maximum(1. - y_true * y_pred, 0.), axis=-1) def categorical_hinge(y_true, y_pred):
pos = K.sum(y_true * y_pred, axis=-1)
neg = K.max((1. - y_true) * y_pred, axis=-1)
return K.maximum(0., neg - pos + 1.) def logcosh(y_true, y_pred):
"""Logarithm of the hyperbolic cosine of the prediction error.
`log(cosh(x))` is approximately equal to `(x ** 2) / 2` for small `x` and
to `abs(x) - log(2)` for large `x`. This means that 'logcosh' works mostly
like the mean squared error, but will not be so strongly affected by the
occasional wildly incorrect prediction.
# Arguments
y_true: tensor of true targets.
y_pred: tensor of predicted targets.
# Returns
Tensor with one scalar loss entry per sample.
"""
def _logcosh(x):
return x + K.softplus(-2. * x) - K.log(2.)
return K.mean(_logcosh(y_pred - y_true), axis=-1) def categorical_crossentropy(y_true, y_pred):
return K.categorical_crossentropy(y_true, y_pred) def sparse_categorical_crossentropy(y_true, y_pred):
return K.sparse_categorical_crossentropy(y_true, y_pred) def binary_crossentropy(y_true, y_pred):
return K.mean(K.binary_crossentropy(y_true, y_pred), axis=-1) def kullback_leibler_divergence(y_true, y_pred):
y_true = K.clip(y_true, K.epsilon(), 1)
y_pred = K.clip(y_pred, K.epsilon(), 1)
return K.sum(y_true * K.log(y_true / y_pred), axis=-1) def poisson(y_true, y_pred):
return K.mean(y_pred - y_true * K.log(y_pred + K.epsilon()), axis=-1) def cosine_proximity(y_true, y_pred):
y_true = K.l2_normalize(y_true, axis=-1)
y_pred = K.l2_normalize(y_pred, axis=-1)
return -K.sum(y_true * y_pred, 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
kld = KLD = kullback_leibler_divergence
cosine = cosine_proximity def serialize(loss):
return serialize_keras_object(loss) def deserialize(name, custom_objects=None):
return deserialize_keras_object(name,
module_objects=globals(),
custom_objects=custom_objects,
printable_module_name='loss function') def get(identifier):
"""Get the `identifier` loss function.
# Arguments
identifier: None or str, name of the function.
# Returns
The loss function or None if `identifier` is None.
# Raises
ValueError if unknown identifier.
"""
if identifier is None:
return None
if isinstance(identifier, six.string_types):
identifier = str(identifier)
return deserialize(identifier)
if isinstance(identifier, dict):
return deserialize(identifier)
elif callable(identifier):
return identifier
else:
raise ValueError('Could not interpret '
'loss function identifier:', identifier)
 

keras损失函数详解的更多相关文章

  1. 官网实例详解-目录和实例简介-keras学习笔记四

    官网实例详解-目录和实例简介-keras学习笔记四 2018-06-11 10:36:18 wyx100 阅读数 4193更多 分类专栏: 人工智能 python 深度学习 keras   版权声明: ...

  2. 深度学习基础系列(十一)| Keras中图像增强技术详解

    在深度学习中,数据短缺是我们经常面临的一个问题,虽然现在有不少公开数据集,但跟大公司掌握的海量数据集相比,数量上仍然偏少,而某些特定领域的数据采集更是非常困难.根据之前的学习可知,数据量少带来的最直接 ...

  3. 【小白学PyTorch】21 Keras的API详解(上)卷积、激活、初始化、正则

    [新闻]:机器学习炼丹术的粉丝的人工智能交流群已经建立,目前有目标检测.医学图像.时间序列等多个目标为技术学习的分群和水群唠嗑答疑解惑的总群,欢迎大家加炼丹兄为好友,加入炼丹协会.微信:cyx6450 ...

  4. 小白如何学习PyTorch】25 Keras的API详解(下)缓存激活,内存输出,并发解决

    [新闻]:机器学习炼丹术的粉丝的人工智能交流群已经建立,目前有目标检测.医学图像.时间序列等多个目标为技术学习的分群和水群唠嗑答疑解惑的总群,欢迎大家加炼丹兄为好友,加入炼丹协会.微信:cyx6450 ...

  5. SENet详解及Keras复现代码

    转: SENet详解及Keras复现代码 论文地址:https://arxiv.org/pdf/1709.01507.pdf 代码地址:https://github.com/hujie-frank/S ...

  6. yolo3各部分代码详解(超详细)

    0.摘要 最近一段时间在学习yolo3,看了很多博客,理解了一些理论知识,但是学起来还是有些吃力,之后看了源码,才有了更进一步的理解.在这里,我不在赘述网络方面的代码,网络方面的代码比较容易理解,下面 ...

  7. 谱聚类(Spectral Clustering)详解

    谱聚类(Spectral Clustering)详解 谱聚类(Spectral Clustering, SC)是一种基于图论的聚类方法——将带权无向图划分为两个或两个以上的最优子图,使子图内部尽量相似 ...

  8. 基于双向BiLstm神经网络的中文分词详解及源码

    基于双向BiLstm神经网络的中文分词详解及源码 基于双向BiLstm神经网络的中文分词详解及源码 1 标注序列 2 训练网络 3 Viterbi算法求解最优路径 4 keras代码讲解 最后 源代码 ...

  9. softmax函数详解

    答案来自专栏:机器学习算法与自然语言处理 详解softmax函数以及相关求导过程 这几天学习了一下softmax激活函数,以及它的梯度求导过程,整理一下便于分享和交流. softmax函数 softm ...

随机推荐

  1. Hadoop界的Hello World!

    Hadoop界的Hello World! 2019-05-20  19:50:09 应用平台:Eclipse+ubantu+hadoop包 注:例分析的形式给宝宝们解释一下,详细运行过程省略. 实例: ...

  2. Oracle plsql 触发器 查询/启用/停止

    在PLSQL中查询某个表的触发器脚本 select * from user_triggers where table_name='xxx' oracle触发器的启用和停用 1.禁用 table_nam ...

  3. Windows下的apache maven安装与配置

    去到官网http://maven.apache.org/download.cgi下载压缩包我选择的是二进制zip压缩文件. 解压并配置压缩文件的目录到MAVEN_HOME环境变量,添加解压文件下的bi ...

  4. Oracle sql 复习题目总结

    sql 题目一 表结构 1.表名:g_cardapply 字段(字段名/类型/长度): apply_no varchar8; //申请单号(关键字) apply_date date; //申请日期 s ...

  5. How can I get a Netty server to reload a TLS certificate when it is renewed?

    java - How can I get a Netty server to reload a TLS certificate when it is renewed? - Stack Overflow ...

  6. java匿名内部类new(){}

    匿名内部类:顾名思义,没有名字的内部类.表面上看起来它们似乎有名字,实际那不是它们的名字.当程序中使用匿名内部类时,在定义匿名内部类的地方往往直接创建该类的一个对象.匿名内部类的声明格式如下:new ...

  7. PorterDuffXfermode之PorterDuff.Mode.SRC_IN

    package com.loaderman.customviewdemo.view; import android.content.Context; import android.graphics.B ...

  8. nVidia GPGPU vs AMD Radeon HD Graphics执行模式对比

    大家做高性能计算的朋友,想必对CPU的执行模式已经非常熟悉了吧.当代高级些的CPU一般采用超标量流水线,使得毗邻几条相互独立的指令能够并行执行——这称为指令集并行(ILP,Instruction-Le ...

  9. GoogleNet-ILSVRC-2014冠军

    Going deeper with convolutions-22层 https://my.oschina.net/u/876354/blog/1637819 那么,GoogLeNet是如何进一步提升 ...

  10. 41 Flutter 仿京东商城项目签名验证 增加收货地址、显示收货地址 事件广播

    加群452892873 下载对应41课文件,运行方法,建好项目,直接替换lib目录 AddressAdd.dart import 'package:dio/dio.dart'; import 'pac ...