Keras loss函数剖析
作者:姚贤贤 发布时间:2021-01-24 05:25:27
标签: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()本身。
来源:https://blog.csdn.net/u011311291/article/details/79956195


猜你喜欢
- 爬取流程(美食区最热标签下的三个视频)在首页获取视频的编号和名字拼接成正确的url保存视频思路1.从网页中获取视频的url发现视频的url在
- 使用mysql二进制方式启动连接您可以使用MySQL二进制方式进入到mysql命令提示符下来连接MySQL数据库。实例以下是从命令行中连接m
- Microsoft SQL Server 2008通过与Microsoft Office的深度集成,为所有人提供了可用的商业智能,以合适的价
- 阅读上一篇:FrontPage XP设计教程5——表单的设计 在制作出图文并茂的网页之后,很多读者朋友还想让自己的网页能够播放音乐、视频等多
- 随笔:(1) 命名空间  
- 本文实例讲述了Python实现获取命令行输出结果的方法。分享给大家供大家参考,具体如下:Python获取命令行输出结果,并对结果进行过滤找到
- 今天我们来学习字符串数据类型相关知识,将讨论如何声明字符串数据类型,字符串数据类型与 ASCII 表的关系,字符串数据类型的属性,以及一些重
- 如下:数据文件:上海机场 (sh600009)24.113.58东风汽车 (sh600006)74.251.74中国国贸 (sh600007
- 一般说来,你会把模板以文件的方式存储在文件系统中,但是你也可以使用自定义的 template loaders 从其他来源加载模板。Djang
- Python 格式化输出字符串(输出字符串+数字的几种方法)1. 介绍字符串格式化输出是python非常重要的基础语法。格式化输出:内容按照
- 一、远程过程调用RPC XML-RPC is a Remote Procedure Call method that uses XML pa
- 假设我们已经安装好了tensorflow。一般在安装好tensorflow后,都会跑它的demo,而最常见的demo就是手写数字识别的dem
- 概要不要以为 Python 有自动垃圾回收就不会内存泄漏,本着它有“垃圾回收”我有“垃圾代码”的精神,现在总结一下三种常见的内存泄漏场景。无
- 本地虚拟环境开发完成之后,上线过程中需要一一安装依赖包,做个记录如下:CentOS 安装python3.5.3wget https://ww
- 日常工作生活中,事情一多,就会忘记一些该做未做的事情。即使有时候把事情记录在了小本本上或者手机、电脑端备忘录上,也总会有查看不及时,导致错过
- 本文实例讲述了Python反转序列的方法。分享给大家供大家参考,具体如下:序列是python中最基本的数据结构,序列中每个元素都有一个跟位置
- 1.导入模块import cv2 as cvimport numpy as np 2.OpenCV绘图大致步骤OpenCV 图形绘制步骤(1
- #!/usr/bin/env python# coding: utf-8### show time in console#import sy
- 分布式编程的难点在于:1.服务器之间的通信,主节点如何了解从节点的执行进度,并在从节点之间进行负载均衡和任务调度;2.如何让多个服务器上的进
- 要实现的SQL查询很原始:要求从第一个表进行查询得到第二个表格式的数据,上网查询之后竟然能写出下面的SQL:代码如下:select * fr