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 相关文章推荐
python设置windows桌面壁纸的实现代码
Jan 28 Python
一道python走迷宫算法题
Jan 22 Python
python代码 输入数字使其反向输出的方法
Dec 22 Python
使用Python自动化破解自定义字体混淆信息的方法实例
Feb 13 Python
Python设置matplotlib.plot的坐标轴刻度间隔以及刻度范围
Jun 25 Python
pytorch模型预测结果与ndarray互转方式
Jan 15 Python
tensorflow入门:tfrecord 和tf.data.TFRecordDataset的使用
Jan 20 Python
Python 时间戳之获取整点凌晨时间戳的操作方法
Jan 28 Python
基于virtualenv创建python虚拟环境过程图解
Mar 30 Python
为什么说python适合写爬虫
Jun 11 Python
pycharm中leetcode插件使用图文详解
Dec 07 Python
Python实现拼音转换
Jun 07 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
Win2000+Apache+MySql+PHP4+PERL安装使用小结
2006/10/09 PHP
phpfans留言版用到的数据操作类和分页类
2007/01/04 PHP
PHP提交表单失败后如何保留已经填写的信息
2014/06/20 PHP
phpmyadmin提示The mbstring extension is missing的解决方法
2014/12/17 PHP
PHP基于swoole多进程操作示例
2019/08/12 PHP
基于PHP实现生成随机水印图片
2020/12/09 PHP
一个JavaScript继承的实现
2006/10/24 Javascript
jQuery图片滚动图片的效果(另类实现)
2013/06/02 Javascript
得到form下的所有的input的js代码
2013/11/07 Javascript
基于socket.io+express实现多房间聊天
2016/03/17 Javascript
js实现图片上传并预览功能
2018/08/06 Javascript
layui文件上传控件带更改后数据传值的方法
2019/09/23 Javascript
使用axios请求时,发送formData请求的示例
2019/10/29 Javascript
Vuex的API文档说明详解
2020/02/05 Javascript
jquery插件实现轮播图效果
2020/10/19 jQuery
Vue 数据绑定的原理分析
2020/11/16 Javascript
Python数据库的连接实现方法与注意事项
2016/02/27 Python
浅谈Python数据类型之间的转换
2016/06/08 Python
Python使用matplotlib简单绘图示例
2018/02/01 Python
PyQt5显示GIF图片的方法
2019/06/17 Python
PyTorch的深度学习入门教程之构建神经网络
2019/06/27 Python
python实现读取excel文件中所有sheet操作示例
2019/08/09 Python
Django Session和Cookie分别实现记住用户登录状态操作
2020/07/02 Python
python使用布隆过滤器的实现示例
2020/08/20 Python
利用Python实现Json序列化库的方法步骤
2020/09/09 Python
Python更改pip镜像源的方法示例
2020/12/01 Python
python中count函数知识点浅析
2020/12/17 Python
CSS3教程:新增加的结构伪类
2009/04/02 HTML / CSS
英国户外服装、鞋类和设备的领先零售商:Millets
2020/10/12 全球购物
2014年计算机专业个人自我评价
2014/01/19 职场文书
经验丰富大学生村干部自我鉴定
2014/01/22 职场文书
保密工作目标责任书
2014/07/28 职场文书
搞笑婚庆主持词
2015/06/29 职场文书
导游词之云南-元阳梯田
2019/10/08 职场文书
Java面试题冲刺第十七天--基础篇3
2021/08/07 面试题
ajax请求前端跨域问题原因及解决方案
2021/10/16 Javascript