最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

對Keras自帶Loss Function的深入研究

 更新時間:2021年05月25日 09:15:48   作者:Forskamse  
這篇文章主要介紹了對Keras自帶Loss Function的深入研究,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

本文研究Keras自帶的幾個常用的Loss Function。

1. categorical_crossentropy VS. sparse_categorical_crossentropy

注意到二者的主要差別在于輸入是否為integer tensor。在文檔中,我們還可以找到關于二者如何選擇的描述:

解釋一下這里的Integer target 與 Categorical target,實際上Integer target經(jīng)過獨熱編碼就變成了Categorical target,舉例說明:

(類別數(shù)5)
Integer target: [1,2,4]
Categorical target: [[0. 1. 0. 0. 0.]
					 [0. 0. 1. 0. 0.]
					 [0. 0. 0. 0. 1.]]

在Keras中提供了to_categorical方法來實現(xiàn)二者的轉化:

from keras.utils import to_categorical
categorical_labels = to_categorical(int_labels, num_classes=None)

注意categorical_crossentropy和sparse_categorical_crossentropy的輸入?yún)?shù)output,都是softmax輸出的tensor。我們都知道softmax的輸出服從多項分布,

因此categorical_crossentropy和sparse_categorical_crossentropy應當應用于多分類問題。

我們再看看這兩個的源碼,來驗證一下:

https://github.com/tensorflow/tensorflow/blob/r1.13/tensorflow/python/keras/backend.py
--------------------------------------------------------------------------------------------------------------------
def categorical_crossentropy(target, output, from_logits=False, axis=-1):
  """Categorical crossentropy between an output tensor and a target tensor.
  Arguments:
      target: A tensor of the same shape as `output`.
      output: A tensor resulting from a softmax
          (unless `from_logits` is True, in which
          case `output` is expected to be the logits).
      from_logits: Boolean, whether `output` is the
          result of a softmax, or is a tensor of logits.
      axis: Int specifying the channels axis. `axis=-1` corresponds to data
          format `channels_last', and `axis=1` corresponds to data format
          `channels_first`.
  Returns:
      Output tensor.
  Raises:
      ValueError: if `axis` is neither -1 nor one of the axes of `output`.
  """
  rank = len(output.shape)
  axis = axis % rank
  # Note: nn.softmax_cross_entropy_with_logits_v2
  # expects logits, Keras expects probabilities.
  if not from_logits:
    # scale preds so that the class probas of each sample sum to 1
    output = output / math_ops.reduce_sum(output, axis, True)
    # manual computation of crossentropy
    epsilon_ = _to_tensor(epsilon(), output.dtype.base_dtype)
    output = clip_ops.clip_by_value(output, epsilon_, 1. - epsilon_)
    return -math_ops.reduce_sum(target * math_ops.log(output), axis)
  else:
    return nn.softmax_cross_entropy_with_logits_v2(labels=target, logits=output)
--------------------------------------------------------------------------------------------------------------------
def sparse_categorical_crossentropy(target, output, from_logits=False, axis=-1):
  """Categorical crossentropy with integer targets.
  Arguments:
      target: An integer tensor.
      output: A tensor resulting from a softmax
          (unless `from_logits` is True, in which
          case `output` is expected to be the logits).
      from_logits: Boolean, whether `output` is the
          result of a softmax, or is a tensor of logits.
      axis: Int specifying the channels axis. `axis=-1` corresponds to data
          format `channels_last', and `axis=1` corresponds to data format
          `channels_first`.
  Returns:
      Output tensor.
  Raises:
      ValueError: if `axis` is neither -1 nor one of the axes of `output`.
  """
  rank = len(output.shape)
  axis = axis % rank
  if axis != rank - 1:
    permutation = list(range(axis)) + list(range(axis + 1, rank)) + [axis]
    output = array_ops.transpose(output, perm=permutation)
  # Note: nn.sparse_softmax_cross_entropy_with_logits
  # expects logits, Keras expects probabilities.
  if not from_logits:
    epsilon_ = _to_tensor(epsilon(), output.dtype.base_dtype)
    output = clip_ops.clip_by_value(output, epsilon_, 1 - epsilon_)
    output = math_ops.log(output)
  output_shape = output.shape
  targets = cast(flatten(target), 'int64')
  logits = array_ops.reshape(output, [-1, int(output_shape[-1])])
  res = nn.sparse_softmax_cross_entropy_with_logits(
      labels=targets, logits=logits)
  if len(output_shape) >= 3:
    # If our output includes timesteps or spatial dimensions we need to reshape
    return array_ops.reshape(res, array_ops.shape(output)[:-1])
  else:
    return res

categorical_crossentropy計算交叉熵時使用的是nn.softmax_cross_entropy_with_logits_v2( labels=targets, logits=logits),而sparse_categorical_crossentropy使用的是nn.sparse_softmax_cross_entropy_with_logits( labels=targets, logits=logits),二者本質(zhì)并無區(qū)別,只是對輸入?yún)?shù)logits的要求不同,v2要求的是logits與labels格式相同(即元素也是獨熱的),而sparse則要求logits的元素是個數(shù)值,與上面Integer format和Categorical format的對比含義類似。

綜上所述,categorical_crossentropy和sparse_categorical_crossentropy只不過是輸入?yún)?shù)target類型上的區(qū)別,其loss的計算在本質(zhì)上沒有區(qū)別,就是交叉熵;二者是針對多分類(Multi-class)任務的。

2. Binary_crossentropy

二元交叉熵,從名字中我們可以看出,這個loss function可能是適用于二分類的。文檔中并沒有詳細說明,那么直接看看源碼吧:

https://github.com/tensorflow/tensorflow/blob/r1.13/tensorflow/python/keras/backend.py
--------------------------------------------------------------------------------------------------------------------
def binary_crossentropy(target, output, from_logits=False):
  """Binary crossentropy between an output tensor and a target tensor.
  Arguments:
      target: A tensor with the same shape as `output`.
      output: A tensor.
      from_logits: Whether `output` is expected to be a logits tensor.
          By default, we consider that `output`
          encodes a probability distribution.
  Returns:
      A tensor.
  """
  # Note: nn.sigmoid_cross_entropy_with_logits
  # expects logits, Keras expects probabilities.
  if not from_logits:
    # transform back to logits
    epsilon_ = _to_tensor(epsilon(), output.dtype.base_dtype)
    output = clip_ops.clip_by_value(output, epsilon_, 1 - epsilon_)
    output = math_ops.log(output / (1 - output))
  return nn.sigmoid_cross_entropy_with_logits(labels=target, logits=output)

可以看到源碼中計算使用了nn.sigmoid_cross_entropy_with_logits,熟悉tensorflow的應該比較熟悉這個損失函數(shù)了,它可以用于簡單的二分類,也可以用于多標簽任務,而且應用廣泛,在樣本合理的情況下(如不存在類別不均衡等問題)的情況下,通??梢灾苯邮褂谩?/p>

補充:keras自定義loss function的簡單方法

首先看一下Keras中我們常用到的目標函數(shù)(如mse,mae等)是如何定義的

from keras import backend as K
def mean_squared_error(y_true, y_pred):
    return K.mean(K.square(y_pred - y_true), axis=-1)
def mean_absolute_error(y_true, y_pred):
    return K.mean(K.abs(y_pred - y_true), axis=-1)
def mean_absolute_percentage_error(y_true, y_pred):
    diff = K.abs((y_true - y_pred) / K.clip(K.abs(y_true), K.epsilon(), np.inf))
    return 100. * K.mean(diff, axis=-1)
def categorical_crossentropy(y_true, y_pred):
    '''Expects a binary class matrix instead of a vector of scalar classes.
    '''
    return K.categorical_crossentropy(y_pred, y_true)
def sparse_categorical_crossentropy(y_true, y_pred):
    '''expects an array of integer classes.
    Note: labels shape must have the same number of dimensions as output shape.
    If you get a shape error, add a length-1 dimension to labels.
    '''
    return K.sparse_categorical_crossentropy(y_pred, y_true)
def binary_crossentropy(y_true, y_pred):
    return K.mean(K.binary_crossentropy(y_pred, y_true), axis=-1)
def kullback_leibler_divergence(y_true, y_pred):
    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)
def poisson(y_true, y_pred):
    return K.mean(y_pred - y_true * K.log(y_pred + K.epsilon()), axis=-1)
def cosine_proximity(y_true, y_pred):
    y_true = K.l2_normalize(y_true, axis=-1)
    y_pred = K.l2_normalize(y_pred, axis=-1)
    return -K.mean(y_true * y_pred, axis=-1)

所以仿照以上的方法,可以自己定義特定任務的目標函數(shù)。比如:定義預測值與真實值的差

from keras import backend as K
def new_loss(y_true,y_pred):
    return K.mean((y_pred-y_true),axis = -1)

然后,應用你自己定義的目標函數(shù)進行編譯

from keras import backend as K
def my_loss(y_true,y_pred):
    return K.mean((y_pred-y_true),axis = -1)
model.compile(optimizer=optimizers.RMSprop(lr),loss=my_loss,
metrics=['accuracy'])

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關文章

  • pycharm 2018 激活碼及破解補丁激活方式

    pycharm 2018 激活碼及破解補丁激活方式

    這篇文章主要介紹了pycharm 2018 激活碼及破解補丁激活方式,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-05-05
  • 使用python實現(xiàn)下載我們想聽的歌曲,速度超快

    使用python實現(xiàn)下載我們想聽的歌曲,速度超快

    這篇文章主要介紹了使用python實現(xiàn)下載我們想聽的歌曲,速度超快,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-07-07
  • pytorch關于Tensor的數(shù)據(jù)類型說明

    pytorch關于Tensor的數(shù)據(jù)類型說明

    這篇文章主要介紹了pytorch關于Tensor的數(shù)據(jù)類型說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-07-07
  • Python代碼實現(xiàn)雙鏈表

    Python代碼實現(xiàn)雙鏈表

    這篇文章主要為大家詳細介紹了Python代碼實現(xiàn)雙鏈表,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-05-05
  • Python修改游戲內(nèi)存的方法

    Python修改游戲內(nèi)存的方法

    本文給大家分享一個通過Python來修改游戲內(nèi)存的方法,幫助大家更改游戲中的數(shù)據(jù),步驟很簡單,而且有視頻講解,感興趣的朋友一起看看吧
    2021-11-11
  • python如何利用paramiko執(zhí)行服務器命令

    python如何利用paramiko執(zhí)行服務器命令

    這篇文章主要介紹了python如何利用paramiko執(zhí)行服務器命令,幫助大家更好的理解和使用python,感興趣的朋友可以了解下
    2020-11-11
  • 4種非常實用的python內(nèi)置數(shù)據(jù)結構

    4種非常實用的python內(nèi)置數(shù)據(jù)結構

    這篇文章主要介紹了4種非常實用的python內(nèi)置數(shù)據(jù)結構,幫助大家更好的理解和學習使用python,感興趣的朋友可以了解下
    2021-04-04
  • Python類的定義和使用詳情

    Python類的定義和使用詳情

    這篇文章主要介紹了Python類的定義與使用,類名只要是一個合法的標識符即可,但這僅僅滿足的是?Python?的語法要求:如果從程序的可讀性方面來看,Python?的類名必須是由一個或多個有意義的單詞連綴而成的,下文基于這些基礎內(nèi)容展開介紹,需要的朋友可以參考一下
    2022-03-03
  • Python字典推導式將cookie字符串轉化為字典解析

    Python字典推導式將cookie字符串轉化為字典解析

    這篇文章主要介紹了Python字典推導式將cookie字符串轉化為字典解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2019-08-08
  • 使用Python快速實現(xiàn)鏈接轉word文檔

    使用Python快速實現(xiàn)鏈接轉word文檔

    這篇文章主要為大家詳細介紹了如何使用Python快速實現(xiàn)鏈接轉word文檔功能,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下
    2025-02-02

最新評論

邵阳县| 旺苍县| 尼勒克县| 台东市| 瑞金市| 客服| 沈阳市| 玉溪市| 台前县| 雷州市| 乳山市| 海淀区| 涟水县| 龙泉市| 马边| 繁昌县| SHOW| 漳平市| 兴安盟| 磐安县| 武定县| 玛曲县| 伊吾县| 郓城县| 乌鲁木齐县| 无锡市| 霍林郭勒市| 安仁县| 隆安县| 高安市| 高青县| 绥江县| 自治县| 开阳县| 宁国市| 白山市| 桑日县| 宁明县| 高清| 马关县| 汉川市|