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

(0)

相关推荐

  • keras做CNN的训练误差loss的下降操作

    采用二值判断如果确认是噪声,用该点上面一个灰度进行替换. 噪声点处理:对原点周围的八个点进行扫描,比较.当该点像素值与周围8个点的值小于N时,此点为噪点 . 处理后的文件大小只有原文件小的三分之一,前后的图片内容肉眼几乎无法察觉. 但是这样处理后图片放入CNN中在其他条件不变的情况下,模型loss无法下降,二分类图片,loss一直在8-9之间.准确率维持在0.5,同时,测试集的训练误差持续下降,但是准确率也在0.5徘徊.大概真是需要误差,让优化方法从局部最优跳出来. 使用的activation

  • keras中epoch,batch,loss,val_loss用法说明

    1.epoch Keras官方文档中给出的解释是:"简单说,epochs指的就是训练过程接中数据将被"轮"多少次" (1)释义: 训练过程中当一个完整的数据集通过了神经网络一次并且返回了一次,这个过程称为一个epoch,网络会在每个epoch结束时报告关于模型学习进度的调试信息. (2)为什么要训练多个epoch,即数据要被"轮"多次 在神经网络中传递完整的数据集一次是不够的,对于有限的数据集(是在批梯度下降情况下),使用一个迭代过程,更新权重一

  • 浅谈keras中loss与val_loss的关系

    loss函数如何接受输入值 keras封装的比较厉害,官网给的例子写的云里雾里, 在stackoverflow找到了答案 You can wrap the loss function as a inner function and pass your input tensor to it (as commonly done when passing additional arguments to the loss function). def custom_loss_wrapper(input_

  • 使用keras框架cnn+ctc_loss识别不定长字符图片操作

    我就废话不多说了,大家还是直接看代码吧~ # -*- coding: utf-8 -*- #keras==2.0.5 #tensorflow==1.1.0 import os,sys,string import sys import logging import multiprocessing import time import json import cv2 import numpy as np from sklearn.model_selection import train_test_s

  • keras 自定义loss model.add_loss的使用详解

    一点见解,不断学习,欢迎指正 1.自定义loss层作为网络一层加进model,同时该loss的输出作为网络优化的目标函数 from keras.models import Model import keras.layers as KL import keras.backend as K import numpy as np from keras.utils.vis_utils import plot_model x_train=np.random.normal(1,1,(100,784)) x_

  • keras 自定义loss层+接受输入实例

    loss函数如何接受输入值 keras封装的比较厉害,官网给的例子写的云里雾里, 在stackoverflow找到了答案 You can wrap the loss function as a inner function and pass your input tensor to it (as commonly done when passing additional arguments to the loss function). def custom_loss_wrapper(input_

  • 解决keras GAN训练是loss不发生变化,accuracy一直为0.5的问题

    1.Binary Cross Entropy 常用于二分类问题,当然也可以用于多分类问题,通常需要在网络的最后一层添加sigmoid进行配合使用,其期望输出值(target)需要进行one hot编码,另外BCELoss还可以用于多分类问题Multi-label classification. 定义: For brevity, let x = output, z = target. The binary cross entropy loss is loss(x, z) = - sum_i (x[

  • Keras loss函数剖析

    我就废话不多说了,大家还是直接看代码吧~ ''' Created on 2018-4-16 ''' def compile( self, optimizer, #优化器 loss, #损失函数,可以为已经定义好的loss函数名称,也可以为自己写的loss函数 metrics=None, # sample_weight_mode=None, #如果你需要按时间步为样本赋权(2D权矩阵),将该值设为"temporal".默认为"None",代表按样本赋权(1D权),和f

  • Keras之自定义损失(loss)函数用法说明

    在Keras中可以自定义损失函数,在自定义损失函数的过程中需要注意的一点是,损失函数的参数形式,这一点在Keras中是固定的,须如下形式: def my_loss(y_true, y_pred): # y_true: True labels. TensorFlow/Theano tensor # y_pred: Predictions. TensorFlow/Theano tensor of the same shape as y_true . . . return scalar #返回一个标量

  • keras 回调函数Callbacks 断点ModelCheckpoint教程

    整理自keras:https://keras-cn.readthedocs.io/en/latest/other/callbacks/ 回调函数Callbacks 回调函数是一个函数的合集,会在训练的阶段中所使用.你可以使用回调函数来查看训练模型的内在状态和统计.你可以传递一个列表的回调函数(作为 callbacks 关键字参数)到 Sequential 或 Model 类型的 .fit() 方法.在训练时,相应的回调函数的方法就会被在各自的阶段被调用. Callback keras.callb

  • keras回调函数的使用

    目录 回调函数 fit()方法中使用callbacks参数 模型的保存和加载 通过对Callback类子类化来创建自定义回调函数 [其他]模型的定义 和 数据加载 回调函数 回调函数是一个对象(实现了特定方法的类实例),它在调用fit()时被传入模型,并在训练过程中的不同时间点被模型调用 可以访问关于模型状态与模型性能的所有可用数据 模型检查点(model checkpointing):在训练过程中的不同时间点保存模型的当前状态. 提前终止(early stopping):如果验证损失不再改善,

  • Pytorch中的backward()多个loss函数用法

    Pytorch的backward()函数 假若有多个loss函数,如何进行反向传播和更新呢? x = torch.tensor(2.0, requires_grad=True) y = x**2 z = x # 反向传播 y.backward() x.grad tensor(4.) z.backward() x.grad tensor(5.) ## 累加 补充:Pytorch中torch.autograd ---backward函数的使用方法详细解析,具体例子分析 backward函数 官方定义

  • Keras在mnist上的CNN实践,并且自定义loss函数曲线图操作

    使用keras实现CNN,直接上代码: from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten from keras.layers import Convolution2D, MaxPooling2D from keras.utils import np_utils from keras imp

  • keras中的loss、optimizer、metrics用法

    用keras搭好模型架构之后的下一步,就是执行编译操作.在编译时,经常需要指定三个参数 loss optimizer metrics 这三个参数有两类选择: 使用字符串 使用标识符,如keras.losses,keras.optimizers,metrics包下面的函数 例如: sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True) model.compile(loss='categorical_crossentropy', opt

  • 基于keras中的回调函数用法说明

    keras训练 fit( self, x, y, batch_size=32, nb_epoch=10, verbose=1, callbacks=[], validation_split=0.0, validation_data=None, shuffle=True, class_weight=None, sample_weight=None ) 1. x:输入数据.如果模型只有一个输入,那么x的类型是numpy array,如果模型有多个输入,那么x的类型应当为list,list的元素是对应

随机推荐