Keras loss函数剖析


Posted in Python onJuly 06, 2020

我就废话不多说了,大家还是直接看代码吧~

'''
Created on 2018-4-16
'''
def compile(
self,
optimizer, #优化器
loss, #损失函数,可以为已经定义好的loss函数名称,也可以为自己写的loss函数
metrics=None, #
sample_weight_mode=None, #如果你需要按时间步为样本赋权(2D权矩阵),将该值设为“temporal”。默认为“None”,代表按样本赋权(1D权),和fit中sample_weight在赋值样本权重中配合使用
weighted_metrics=None, 
target_tensors=None,
**kwargs #这里的设定的参数可以和后端交互。
)

实质调用的是Keras\engine\training.py 中的class Model中的def compile
一般使用model.compile(loss='categorical_crossentropy',optimizer='sgd',metrics=['accuracy'])

# keras所有定义好的损失函数loss:
# keras\losses.py
# 有些loss函数可以使用简称:
# 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
# 使用到的数学方法:
# mean:求均值
# sum:求和
# square:平方
# abs:绝对值
# clip:[裁剪替换](https://blog.csdn.net/qq1483661204/article/details)
# epsilon:1e-7
# log:以e为底
# maximum(x,y):x与 y逐位比较取其大者
# reduce_sum(x,axis):沿着某个维度求和
# l2_normalize:l2正则化
# softplus:softplus函数
# 
# import cntk as C
# 1.mean_squared_error:
#  return K.mean(K.square(y_pred - y_true), axis=-1) 
# 2.mean_absolute_error:
#  return K.mean(K.abs(y_pred - y_true), axis=-1)
# 3.mean_absolute_percentage_error:
#  diff = K.abs((y_true - y_pred) / K.clip(K.abs(y_true),K.epsilon(),None))
#  return 100. * K.mean(diff, axis=-1)
# 4.mean_squared_logarithmic_error:
#  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)
# 5.squared_hinge:
#  return K.mean(K.square(K.maximum(1. - y_true * y_pred, 0.)), axis=-1)
# 6.hinge(SVM损失函数):
#  return K.mean(K.maximum(1. - y_true * y_pred, 0.), axis=-1)
# 7.categorical_hinge:
#  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.)
# 8.logcosh:
#  def _logcosh(x):
#   return x + K.softplus(-2. * x) - K.log(2.)
#  return K.mean(_logcosh(y_pred - y_true), axis=-1)
# 9.categorical_crossentropy:
#  output /= C.reduce_sum(output, axis=-1)
#  output = C.clip(output, epsilon(), 1.0 - epsilon())
#  return -sum(target * C.log(output), axis=-1)
# 10.sparse_categorical_crossentropy:
#  target = C.one_hot(target, output.shape[-1])
#  target = C.reshape(target, output.shape)
#  return categorical_crossentropy(target, output, from_logits)
# 11.binary_crossentropy:
#  return K.mean(K.binary_crossentropy(y_true, y_pred), axis=-1)
# 12.kullback_leibler_divergence:
#  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)
# 13.poisson:
#  return K.mean(y_pred - y_true * K.log(y_pred + K.epsilon()), axis=-1)
# 14.cosine_proximity:
#  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)

补充知识:一文总结Keras的loss函数和metrics函数

Loss函数

定义:

keras.losses.mean_squared_error(y_true, y_pred)

用法很简单,就是计算均方误差平均值,例如

loss_fn = keras.losses.mean_squared_error
a1 = tf.constant([1,1,1,1])
a2 = tf.constant([2,2,2,2])
loss_fn(a1,a2)
<tf.Tensor: id=718367, shape=(), dtype=int32, numpy=1>

Metrics函数

Metrics函数也用于计算误差,但是功能比Loss函数要复杂。

定义

tf.keras.metrics.Mean(
  name='mean', dtype=None
)

这个定义过于简单,举例说明

mean_loss([1, 3, 5, 7])
mean_loss([1, 3, 5, 7])
mean_loss([1, 1, 1, 1])
mean_loss([2,2])

输出结果

<tf.Tensor: id=718929, shape=(), dtype=float32, numpy=2.857143>

这个结果等价于

np.mean([1, 3, 5, 7, 1, 3, 5, 7, 1, 1, 1, 1, 2, 2])

这是因为Metrics函数是状态函数,在神经网络训练过程中会持续不断地更新状态,是有记忆的。因为Metrics函数还带有下面几个Methods

reset_states()
Resets all of the metric state variables.
This function is called between epochs/steps, when a metric is evaluated during training.

result()
Computes and returns the metric value tensor.
Result computation is an idempotent operation that simply calculates the metric value using the state variables

update_state(
  values, sample_weight=None
)
Accumulates statistics for computing the reduction metric.

另外注意,Loss函数和Metrics函数的调用形式,

loss_fn = keras.losses.mean_squared_error mean_loss = keras.metrics.Mean()

mean_loss(1)等价于keras.metrics.Mean()(1),而不是keras.metrics.Mean(1),这个从keras.metrics.Mean函数的定义可以看出。

但是必须先令生成一个实例mean_loss=keras.metrics.Mean(),而不能直接使用keras.metrics.Mean()本身。

以上这篇Keras loss函数剖析就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Flask框架学习笔记(一)安装篇(windows安装与centos安装)
Jun 25 Python
使用Python的Flask框架来搭建第一个Web应用程序
Jun 04 Python
放弃 Python 转向 Go语言有人给出了 9 大理由
Oct 20 Python
Python基于动态规划算法解决01背包问题实例
Dec 06 Python
python自动发邮件库yagmail的示例代码
Feb 23 Python
Python 操作mysql数据库查询之fetchone(), fetchmany(), fetchall()用法示例
Oct 17 Python
使用Python和百度语音识别生成视频字幕的实现
Apr 09 Python
Python类及获取对象属性方法解析
Jun 15 Python
PyTorch: Softmax多分类实战操作
Jul 07 Python
Python模拟登录requests.Session应用详解
Nov 17 Python
Python+Matplotlib图像上指定坐标的位置添加文本标签与注释
Apr 11 Python
python读取mat文件生成h5文件的实现
Jul 15 Python
keras 模型参数,模型保存,中间结果输出操作
Jul 06 #Python
Python自省及反射原理实例详解
Jul 06 #Python
如何通过命令行进入python
Jul 06 #Python
解决TensorFlow调用Keras库函数存在的问题
Jul 06 #Python
python else语句在循环中的运用详解
Jul 06 #Python
Keras模型转成tensorflow的.pb操作
Jul 06 #Python
python如何进入交互模式
Jul 06 #Python
You might like
php中strstr、strrchr、substr、stristr四个函数的区别总结
2014/09/22 PHP
深入浅析Yii admin的权限控制
2016/08/31 PHP
php基于Redis消息队列实现的消息推送的方法
2018/11/28 PHP
tp5(thinkPHP5框架)时间查询操作实例分析
2019/05/29 PHP
JavaScript浏览器选项卡效果
2010/08/25 Javascript
JavaScript高级程序设计 阅读笔记(十八) js跨平台的事件
2012/08/14 Javascript
原生js仿jq判断当前浏览器是否为ie,精确到ie6~8
2014/08/30 Javascript
jquery中trigger()无法触发hover事件的解决方法
2015/05/07 Javascript
jQuery实现鼠标经过图片变亮其他变暗效果
2015/05/08 Javascript
微信小程序 require机制详解及实例代码
2016/12/14 Javascript
jQuery.cookie.js实现记录最近浏览过的商品功能示例
2017/01/23 Javascript
分享一个精简的vue.js 图片lazyload插件实例
2017/03/13 Javascript
详解vue mint-ui源码解析之loadmore组件
2017/10/11 Javascript
用Node编写RESTful API接口的示例代码
2018/07/04 Javascript
微信小程序倒计时功能实例代码
2018/07/17 Javascript
EasyUI 数据表格datagrid列自适应内容宽度的实现
2019/07/18 Javascript
Vue.directive 实现元素scroll逻辑复用
2019/11/29 Javascript
angularjs模态框的使用代码实例
2019/12/20 Javascript
详解vue 中 scoped 样式作用域的规则
2020/09/14 Javascript
Python线性方程组求解运算示例
2018/01/17 Python
Python3+OpenCV2实现图像的几何变换(平移、镜像、缩放、旋转、仿射)
2019/05/13 Python
python Pandas如何对数据集随机抽样
2019/07/29 Python
Python文件时间操作步骤代码详解
2020/04/13 Python
JupyterNotebook 输出窗口的显示效果调整方法
2020/04/13 Python
纯CSS和jQuery实现的在页面顶部显示的进度条效果2例(仿手机浏览器进度条效果)
2014/04/16 HTML / CSS
使用HTML5做个画图板的方法介绍
2013/05/03 HTML / CSS
新秀丽拉杆箱美国官方网站:Samsonite美国
2016/07/25 全球购物
美国猫狗药物和用品网站:PetCareRx
2017/01/05 全球购物
导师就业推荐信范文
2014/05/22 职场文书
学校领导班子对照检查材料
2014/08/28 职场文书
要账委托书范本
2014/09/15 职场文书
培训计划通知
2015/07/15 职场文书
2015国庆节感想
2015/08/04 职场文书
消防演习感想
2015/08/10 职场文书
2016年暑假学生家长评语
2015/12/01 职场文书
Java spring单点登录系统
2021/09/04 Java/Android