Keras loss函数剖析

 更新时间:2020年07月06日 16:38:03   作者:姚贤贤  
这篇文章主要介绍了Keras loss函数剖析,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

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

'''
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函数剖析就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • python3线程池ThreadPoolExecutor处理csv文件数据

    python3线程池ThreadPoolExecutor处理csv文件数据

    这篇文章主要为大家介绍了python3线程池ThreadPoolExecutor处理csv文件数据实现的实例过程,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-06-06
  • numpy.insert用法及内插插0的方法

    numpy.insert用法及内插插0的方法

    本文主要介绍了numpy.insert用法及内插插0的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-03-03
  • python中的os.path.join使用方法详解

    python中的os.path.join使用方法详解

    这篇文章主要介绍了python中的os.path.join使用方法详解,os.path.join用于将多个路径拼接为一个完整路径,经常使用,但没了解过细节,直到今天遇到一个令人疑惑的问题,最后发现是os.path.join的问题,借此机会,记录下os.path.join的用法,需要的朋友可以参考下
    2023-11-11
  • Python函数中闭包和延迟绑定详情

    Python函数中闭包和延迟绑定详情

    这篇文章主要介绍了Python函数中闭包和延迟绑定详情,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的小伙伴可以参考一下
    2022-05-05
  • 简单理解Python中基于生成器的状态机

    简单理解Python中基于生成器的状态机

    这篇文章主要介绍了简单理解Python中基于生成器的状态机,来自于IBM官方技术文档,需要的朋友可以参考下
    2015-04-04
  • flask使用session保存登录状态及拦截未登录请求代码

    flask使用session保存登录状态及拦截未登录请求代码

    这篇文章主要介绍了flask使用session保存登录状态及拦截未登录请求代码,具有一定借鉴价值,需要的朋友可以参考下
    2018-01-01
  • python 容器总结整理

    python 容器总结整理

    这篇文章主要介绍了python 容器总结整理的相关资料,需要的朋友可以参考下
    2017-04-04
  • python实现电子产品商店

    python实现电子产品商店

    这篇文章主要为大家详细介绍了python实现电子产品商店,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-02-02
  • Python帮你解决手机qq微信内存占用太多问题

    Python帮你解决手机qq微信内存占用太多问题

    你有没有发现以前16G内存也可以装几个游戏玩,现在128G的却日常使用都不够了?更不用说装什么游戏,这其实是软件内存占用过多导致的,今天我们用python来清理下
    2022-02-02
  • Python批量发送post请求的实现代码

    Python批量发送post请求的实现代码

    昨天学了一天的Python(我的生产语言是java,也可以写一些shell脚本,算有一点点基础),今天有一个应用场景,就正好练手了
    2018-05-05

最新评论