keras损失函数详解
以下信息均来自官网
------------------------------------------------------------------------------------------------------------
损失函数的使用
损失函数(或称目标函数、优化评分函数)是编译模型时所需的两个参数之一:
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)
预测误差的双曲余弦的对数。
对于小的 x,log(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损失函数详解的更多相关文章
- 官网实例详解-目录和实例简介-keras学习笔记四
官网实例详解-目录和实例简介-keras学习笔记四 2018-06-11 10:36:18 wyx100 阅读数 4193更多 分类专栏: 人工智能 python 深度学习 keras 版权声明: ...
- 深度学习基础系列(十一)| Keras中图像增强技术详解
在深度学习中,数据短缺是我们经常面临的一个问题,虽然现在有不少公开数据集,但跟大公司掌握的海量数据集相比,数量上仍然偏少,而某些特定领域的数据采集更是非常困难.根据之前的学习可知,数据量少带来的最直接 ...
- 【小白学PyTorch】21 Keras的API详解(上)卷积、激活、初始化、正则
[新闻]:机器学习炼丹术的粉丝的人工智能交流群已经建立,目前有目标检测.医学图像.时间序列等多个目标为技术学习的分群和水群唠嗑答疑解惑的总群,欢迎大家加炼丹兄为好友,加入炼丹协会.微信:cyx6450 ...
- 小白如何学习PyTorch】25 Keras的API详解(下)缓存激活,内存输出,并发解决
[新闻]:机器学习炼丹术的粉丝的人工智能交流群已经建立,目前有目标检测.医学图像.时间序列等多个目标为技术学习的分群和水群唠嗑答疑解惑的总群,欢迎大家加炼丹兄为好友,加入炼丹协会.微信:cyx6450 ...
- SENet详解及Keras复现代码
转: SENet详解及Keras复现代码 论文地址:https://arxiv.org/pdf/1709.01507.pdf 代码地址:https://github.com/hujie-frank/S ...
- yolo3各部分代码详解(超详细)
0.摘要 最近一段时间在学习yolo3,看了很多博客,理解了一些理论知识,但是学起来还是有些吃力,之后看了源码,才有了更进一步的理解.在这里,我不在赘述网络方面的代码,网络方面的代码比较容易理解,下面 ...
- 谱聚类(Spectral Clustering)详解
谱聚类(Spectral Clustering)详解 谱聚类(Spectral Clustering, SC)是一种基于图论的聚类方法——将带权无向图划分为两个或两个以上的最优子图,使子图内部尽量相似 ...
- 基于双向BiLstm神经网络的中文分词详解及源码
基于双向BiLstm神经网络的中文分词详解及源码 基于双向BiLstm神经网络的中文分词详解及源码 1 标注序列 2 训练网络 3 Viterbi算法求解最优路径 4 keras代码讲解 最后 源代码 ...
- softmax函数详解
答案来自专栏:机器学习算法与自然语言处理 详解softmax函数以及相关求导过程 这几天学习了一下softmax激活函数,以及它的梯度求导过程,整理一下便于分享和交流. softmax函数 softm ...
随机推荐
- 三行代码CSS竖向居中
.element{ position:relative; top:50%; transform:translateY(-50%); } 这里无需设置高度或者父元素的position属性.(IE9可用) ...
- VSCode前端文件(html文件)如何以服务器模式打开?
方法1: VSCode前端文件(html文件)如何以服务器模式打开?比如工程下有一个A.html文件,想在VSCode里面直接操作,就想Webstorm一样,以http://localhost/xxx ...
- 使用WebSocket实现服务端和客户端的通信
开发中经常会有这样的使用场景.如某个用户在一个数据上做了xx操作, 与该数据相关的用户在线上的话,需要实时接收到一条信息. 这种可以使用WebSocket来实现. 另外,对于消息,可以定义一个类进行固 ...
- DNN在推荐系统中的应用参考资料
参考资料 DSSM算法计算文本相似度:https://www.cnblogs.com/wmx24/p/10157154.html Deep Neural Network for YouTube Rec ...
- Main property in package.json defines package entry point
I know my project's dependencies are installed under node_modules directory. But when I do require(' ...
- 如何计算一个C/C++程序运行时间
前两天要计算一个用C++实现的算法运行时间,就用了clock()这个函数.程序大体上如下: clock_t start,end; start = clock(); /*my code*/ end = ...
- 网络中的tarpit/tar pit
最近看haproxy源码,里面有个TARPIT的概念不能理解,找了很久才找到对应的意思.特此记录. tarpit 本意是“沼泽地.地洼地”,这里显然把它引申为“捕获或者困住某个物体”. 在网络语义中提 ...
- 阶段5 3.微服务项目【学成在线】_day09 课程预览 Eureka Feign_13-课程预览功能开发-CMS页面预览接口测试
5.2 CMS页面预览测试 CMS已经提供了页面预览功能,课程预览功能要使用CMS页面预览接口实现,下边通过cms页面预览接口测试课 程预览的效果. 1.向cms_page表插入一条页面记录或者从cm ...
- 自定义string类
#include <iostream> #include <cstring> using namespace std; class String; class Data{ // ...
- 浏览器最小显示12px字体的解决方法
今天做打印标签,发现浏览器最小字体限制了12px,标签那么小,12px随便几个字就给占满了: 最后通过 transform:scale(1,0.8) 搞定: 这个属性允许将元素移动.压缩.旋转:这里 ...