B
    ӻdF8             	   @   s  d Z ddlZddlZddlmZ ddlmZ ddlm	Z	 ddl
mZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlm Z  ddl!m"Z" ddl!m#Z# ddl!m$Z$ ddl%m&Z& ddl'm(Z( ddl)m*Z* e(dG dd dZ+G dd  d e+Z,e(d!G d"d# d#e,Z-e(d$G d%d& d&e,Z.e(d'G d(d) d)e,Z/e(d*G d+d, d,e,Z0e(d-G d.d/ d/e,Z1e(d0G d1d2 d2e,Z2e(d3G d4d5 d5e,Z3e(d6G d7d8 d8e,Z4e(d9G d:d; d;e,Z5e(d<G d=d> d>e,Z6e(d?G d@dA dAe,Z7e(dBG dCdD dDe,Z8e(dEG dFdG dGe,Z9e(dHG dIdJ dJe,Z:e(dKdLdMdNdOdPe&j;dQdR Z<ddTdUZ=e&>e<e#j?dVdW Z@e(dXdYdZd[d\d]e&j;d^d_ ZAe&>eAe#j?d`da ZBe(dbdcdddedfdge&j;dhdi ZCe&>eCe#j?djdk ZDe(dldmdndodpdqe&j;drds ZEe&>eEe#j?dtdu ZFdvdw ZGe(dxdye&j;dzd{ ZHe(d|d}e&j;d~d ZIe(de&j;dd ZJe(dg de&j;dddZKe(dddde&j;dd ZLe(dde&j;dddZMe&>eMe#j?dddZNe(dde&j;dddZOe&>eOe#j?dddZPe(dde&j;dddZQe&>eQe#j?dddZRe(dddddddde&j;dd ZSe(dde&j;dd ZTe(ddddddgde&j;dddZUe(dG dd de,ZVeQ ZWZXe< ZYZZeA Z[Z\eC Z]Z^eE Z_Z`eS Za ZbZceLZdeKZedd Zfe(ddd Zge(ddddZhe(dddÄ Zie jjdeOdiZkdS )zBuilt-in loss functions.    N)ag_ctx)api)distribution_strategy_context)context)constant_op)ops)
smart_cond)tensor_spec)tensor_util)backend)losses_utils)tf_utils)deserialize_keras_object)serialize_keras_object)	array_ops)control_flow_ops)math_ops)nn)losses_impl)ragged_map_ops)ragged_tensor)ragged_util)dispatch)keras_export)doc_controlszkeras.losses.Lossc               @   sd   e Zd ZdZejjdfddZdd ZdddZ	e
d	d
 Zdd Zejejdd Zdd ZdS )Lossa  Loss base class.

  To be implemented by subclasses:
  * `call()`: Contains the logic for loss calculation using `y_true`, `y_pred`.

  Example subclass implementation:

  ```python
  class MeanSquaredError(Loss):

    def call(self, y_true, y_pred):
      y_pred = tf.convert_to_tensor_v2(y_pred)
      y_true = tf.cast(y_true, y_pred.dtype)
      return tf.reduce_mean(math_ops.square(y_pred - y_true), axis=-1)
  ```

  When used with `tf.distribute.Strategy`, outside of built-in training loops
  such as `tf.keras` `compile` and `fit`, please use 'SUM' or 'NONE' reduction
  types, and reduce losses explicitly in your training loop. Using 'AUTO' or
  'SUM_OVER_BATCH_SIZE' will raise an error.

  Please see this custom training [tutorial](
    https://www.tensorflow.org/tutorials/distribute/custom_training) for more
  details on this.

  You can implement 'SUM_OVER_BATCH_SIZE' using global batch size like:

  ```python
  with strategy.scope():
    loss_obj = tf.keras.losses.CategoricalCrossentropy(
        reduction=tf.keras.losses.Reduction.NONE)
    ....
    loss = (tf.reduce_sum(loss_obj(labels, predictions)) *
            (1. / global_batch_size))
  ```
  Nc             C   s*   t j| || _|| _d| _|   dS )a  Initializes `Loss` class.

    Args:
      reduction: Type of `tf.keras.losses.Reduction` to apply to
        loss. Default value is `AUTO`. `AUTO` indicates that the reduction
        option will be determined by the usage context. For almost all cases
        this defaults to `SUM_OVER_BATCH_SIZE`. When used with
        `tf.distribute.Strategy`, outside of built-in training loops such as
        `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE`
        will raise an error. Please see this custom training [tutorial](
          https://www.tensorflow.org/tutorials/distribute/custom_training) for
            more details.
      name: Optional name for the instance.
    FN)r   ReductionV2validate	reductionname_allow_sum_over_batch_size_set_name_scope)selfr   r    r#   P/var/www/html/venv/lib/python3.7/site-packages/tensorflow/python/keras/losses.py__init__W   s
    zLoss.__init__c             C   s:   | j dkr| jj| _n | j dkr(d| _n| j d| _dS )z"Creates a valid `name_scope` name.Nz<lambda>lambda_)r   	__class____name___name_scopestrip)r"   r#   r#   r$   r!   n   s
    

zLoss._set_name_scopec          
   C   sv   t |||}t| jR |B t r2| j}nt	| jt
 }|||}tj|||  dS Q R X W dQ R X dS )a  Invokes the `Loss` instance.

    Args:
      y_true: Ground truth values. shape = `[batch_size, d0, .. dN]`, except
        sparse loss functions such as sparse categorical crossentropy where
        shape = `[batch_size, d0, .. dN-1]`
      y_pred: The predicted values. shape = `[batch_size, d0, .. dN]`
      sample_weight: Optional `sample_weight` acts as a coefficient for the
        loss. If a scalar is provided, then the loss is simply scaled by the
        given value. If `sample_weight` is a tensor of size `[batch_size]`, then
        the total loss for each sample of the batch is rescaled by the
        corresponding element in the `sample_weight` vector. If the shape of
        `sample_weight` is `[batch_size, d0, .. dN-1]` (or can be broadcasted to
        this shape), then each loss element of `y_pred` is scaled
        by the corresponding value of `sample_weight`. (Note on`dN-1`: all loss
          functions reduce by 1 dimension, usually axis=-1.)

    Returns:
      Weighted loss float `Tensor`. If `reduction` is `NONE`, this has
        shape `[batch_size, d0, .. dN-1]`; otherwise, it is scalar. (Note `dN-1`
        because all loss functions reduce by 1 dimension, usually axis=-1.)

    Raises:
      ValueError: If the shape of `sample_weight` is invalid.
    )r   N)r   Z"graph_context_for_symbolic_tensorsr   Z
name_scoper*   r   Zexecuting_eagerlycall	autograph
tf_convertr   control_status_ctxr   Zcompute_weighted_loss_get_reduction)r"   y_truey_predZsample_weightZ	graph_ctxZcall_fnZlossesr#   r#   r$   __call__x   s    

zLoss.__call__c             C   s
   | f |S )zInstantiates a `Loss` from its config (output of `get_config()`).

    Args:
        config: Output of `get_config()`.

    Returns:
        A `Loss` instance.
    r#   )clsconfigr#   r#   r$   from_config   s    
zLoss.from_configc             C   s   | j | jdS )z4Returns the config dictionary for a `Loss` instance.)r   r   )r   r   )r"   r#   r#   r$   
get_config   s    zLoss.get_configc             C   s   t ddS )a  Invokes the `Loss` instance.

    Args:
      y_true: Ground truth values. shape = `[batch_size, d0, .. dN]`, except
        sparse loss functions such as sparse categorical crossentropy where
        shape = `[batch_size, d0, .. dN-1]`
      y_pred: The predicted values. shape = `[batch_size, d0, .. dN]`

    Returns:
      Loss values with the shape `[batch_size, d0, .. dN-1]`.
    z"Must be implemented in subclasses.N)NotImplementedError)r"   r1   r2   r#   r#   r$   r,      s    z	Loss.callc             C   sN   | j s2t r2| jtjjks*| jtjjkr2td| jtjjkrHtjjS | jS )z?Handles `AUTO` reduction cases and returns the reduction value.aQ  Please use `tf.keras.losses.Reduction.SUM` or `tf.keras.losses.Reduction.NONE` for loss reduction when losses are used with `tf.distribute.Strategy` outside of the built-in training loops. You can implement `tf.keras.losses.Reduction.SUM_OVER_BATCH_SIZE` using global batch size like:
```
with strategy.scope():
    loss_obj = tf.keras.losses.CategoricalCrossentropy(reduction=tf.keras.losses.Reduction.NONE)
....
    loss = tf.reduce_sum(loss_obj(labels, predictions)) * (1. / global_batch_size)
```
Please see https://www.tensorflow.org/tutorials/distribute/custom_training for more details.)	r    r   Zhas_strategyr   r   r   AUTOZSUM_OVER_BATCH_SIZE
ValueError)r"   r#   r#   r$   r0      s    zLoss._get_reduction)N)r)   
__module____qualname____doc__r   r   r9   r%   r!   r3   classmethodr6   r7   abcabstractmethodr   Zfor_subclass_implementersr,   r0   r#   r#   r#   r$   r   0   s   %

'r   c                   s>   e Zd ZdZejjdf fdd	Zdd Z fddZ	  Z
S )	LossFunctionWrapperz*Wraps a loss function in the `Loss` class.Nc                s    t  j||d || _|| _dS )ag  Initializes `LossFunctionWrapper` class.

    Args:
      fn: The loss function to wrap, with signature `fn(y_true, y_pred,
        **kwargs)`.
      reduction: Type of `tf.keras.losses.Reduction` to apply to
        loss. Default value is `AUTO`. `AUTO` indicates that the reduction
        option will be determined by the usage context. For almost all cases
        this defaults to `SUM_OVER_BATCH_SIZE`. When used with
        `tf.distribute.Strategy`, outside of built-in training loops such as
        `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE`
        will raise an error. Please see this custom training [tutorial](
          https://www.tensorflow.org/tutorials/distribute/custom_training) for
            more details.
      name: Optional name for the instance.
      **kwargs: The keyword arguments that are passed on to `fn`.
    )r   r   N)superr%   fn
_fn_kwargs)r"   rC   r   r   kwargs)r(   r#   r$   r%      s    zLossFunctionWrapper.__init__c             C   sF   t |r$t |r$t||\}}t| jt }|||f| j	S )zInvokes the `LossFunctionWrapper` instance.

    Args:
      y_true: Ground truth values.
      y_pred: The predicted values.

    Returns:
      Loss values per sample.
    )
r
   Z
is_tf_typer   Zsqueeze_or_expand_dimensionsr-   r.   rC   r   r/   rD   )r"   r1   r2   Zag_fnr#   r#   r$   r,      s    
zLossFunctionWrapper.callc                s^   i }x2| j  D ]$\}}t|r,t|n|||< qW t  }tt	| t	|  S )N)
rD   itemsr   Zis_tensor_or_variabler   evalrB   r7   dictlist)r"   r5   kvZbase_config)r(   r#   r$   r7     s
     
zLossFunctionWrapper.get_config)r)   r;   r<   r=   r   r   r9   r%   r,   r7   __classcell__r#   r#   )r(   r$   rA      s
   rA   zkeras.losses.MeanSquaredErrorc                   s*   e Zd ZdZejjdf fdd	Z  ZS )MeanSquaredErrora  Computes the mean of squares of errors between labels and predictions.

  `loss = square(y_true - y_pred)`

  Standalone usage:

  >>> y_true = [[0., 1.], [0., 0.]]
  >>> y_pred = [[1., 1.], [1., 0.]]
  >>> # Using 'auto'/'sum_over_batch_size' reduction type.
  >>> mse = tf.keras.losses.MeanSquaredError()
  >>> mse(y_true, y_pred).numpy()
  0.5

  >>> # Calling with 'sample_weight'.
  >>> mse(y_true, y_pred, sample_weight=[0.7, 0.3]).numpy()
  0.25

  >>> # Using 'sum' reduction type.
  >>> mse = tf.keras.losses.MeanSquaredError(
  ...     reduction=tf.keras.losses.Reduction.SUM)
  >>> mse(y_true, y_pred).numpy()
  1.0

  >>> # Using 'none' reduction type.
  >>> mse = tf.keras.losses.MeanSquaredError(
  ...     reduction=tf.keras.losses.Reduction.NONE)
  >>> mse(y_true, y_pred).numpy()
  array([0.5, 0.5], dtype=float32)

  Usage with the `compile()` API:

  ```python
  model.compile(optimizer='sgd', loss=tf.keras.losses.MeanSquaredError())
  ```
  mean_squared_errorc                s   t  jt||d dS )a  Initializes `MeanSquaredError` instance.

    Args:
      reduction: Type of `tf.keras.losses.Reduction` to apply to
        loss. Default value is `AUTO`. `AUTO` indicates that the reduction
        option will be determined by the usage context. For almost all cases
        this defaults to `SUM_OVER_BATCH_SIZE`. When used with
        `tf.distribute.Strategy`, outside of built-in training loops such as
        `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE`
        will raise an error. Please see this custom training [tutorial](
          https://www.tensorflow.org/tutorials/distribute/custom_training) for
            more details.
      name: Optional name for the instance. Defaults to 'mean_squared_error'.
    )r   r   N)rB   r%   rN   )r"   r   r   )r(   r#   r$   r%   3  s    zMeanSquaredError.__init__)	r)   r;   r<   r=   r   r   r9   r%   rL   r#   r#   )r(   r$   rM     s   $rM   zkeras.losses.MeanAbsoluteErrorc                   s*   e Zd ZdZejjdf fdd	Z  ZS )MeanAbsoluteErrora  Computes the mean of absolute difference between labels and predictions.

  `loss = abs(y_true - y_pred)`

  Standalone usage:

  >>> y_true = [[0., 1.], [0., 0.]]
  >>> y_pred = [[1., 1.], [1., 0.]]
  >>> # Using 'auto'/'sum_over_batch_size' reduction type.
  >>> mae = tf.keras.losses.MeanAbsoluteError()
  >>> mae(y_true, y_pred).numpy()
  0.5

  >>> # Calling with 'sample_weight'.
  >>> mae(y_true, y_pred, sample_weight=[0.7, 0.3]).numpy()
  0.25

  >>> # Using 'sum' reduction type.
  >>> mae = tf.keras.losses.MeanAbsoluteError(
  ...     reduction=tf.keras.losses.Reduction.SUM)
  >>> mae(y_true, y_pred).numpy()
  1.0

  >>> # Using 'none' reduction type.
  >>> mae = tf.keras.losses.MeanAbsoluteError(
  ...     reduction=tf.keras.losses.Reduction.NONE)
  >>> mae(y_true, y_pred).numpy()
  array([0.5, 0.5], dtype=float32)

  Usage with the `compile()` API:

  ```python
  model.compile(optimizer='sgd', loss=tf.keras.losses.MeanAbsoluteError())
  ```
  mean_absolute_errorc                s   t  jt||d dS )a  Initializes `MeanAbsoluteError` instance.

    Args:
      reduction: Type of `tf.keras.losses.Reduction` to apply to
        loss. Default value is `AUTO`. `AUTO` indicates that the reduction
        option will be determined by the usage context. For almost all cases
        this defaults to `SUM_OVER_BATCH_SIZE`. When used with
        `tf.distribute.Strategy`, outside of built-in training loops such as
        `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE`
        will raise an error. Please see this custom training [tutorial](
          https://www.tensorflow.org/tutorials/distribute/custom_training) for
            more details.
      name: Optional name for the instance. Defaults to 'mean_absolute_error'.
    )r   r   N)rB   r%   rP   )r"   r   r   )r(   r#   r$   r%   m  s    zMeanAbsoluteError.__init__)	r)   r;   r<   r=   r   r   r9   r%   rL   r#   r#   )r(   r$   rO   G  s   $rO   z(keras.losses.MeanAbsolutePercentageErrorc                   s*   e Zd ZdZejjdf fdd	Z  ZS )MeanAbsolutePercentageErrora  Computes the mean absolute percentage error between `y_true` and `y_pred`.

  `loss = 100 * abs(y_true - y_pred) / y_true`

  Standalone usage:

  >>> y_true = [[2., 1.], [2., 3.]]
  >>> y_pred = [[1., 1.], [1., 0.]]
  >>> # Using 'auto'/'sum_over_batch_size' reduction type.
  >>> mape = tf.keras.losses.MeanAbsolutePercentageError()
  >>> mape(y_true, y_pred).numpy()
  50.

  >>> # Calling with 'sample_weight'.
  >>> mape(y_true, y_pred, sample_weight=[0.7, 0.3]).numpy()
  20.

  >>> # Using 'sum' reduction type.
  >>> mape = tf.keras.losses.MeanAbsolutePercentageError(
  ...     reduction=tf.keras.losses.Reduction.SUM)
  >>> mape(y_true, y_pred).numpy()
  100.

  >>> # Using 'none' reduction type.
  >>> mape = tf.keras.losses.MeanAbsolutePercentageError(
  ...     reduction=tf.keras.losses.Reduction.NONE)
  >>> mape(y_true, y_pred).numpy()
  array([25., 75.], dtype=float32)

  Usage with the `compile()` API:

  ```python
  model.compile(optimizer='sgd',
                loss=tf.keras.losses.MeanAbsolutePercentageError())
  ```
  mean_absolute_percentage_errorc                s   t  jt||d dS )a
  Initializes `MeanAbsolutePercentageError` instance.

    Args:
      reduction: Type of `tf.keras.losses.Reduction` to apply to
        loss. Default value is `AUTO`. `AUTO` indicates that the reduction
        option will be determined by the usage context. For almost all cases
        this defaults to `SUM_OVER_BATCH_SIZE`. When used with
        `tf.distribute.Strategy`, outside of built-in training loops such as
        `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE`
        will raise an error. Please see this custom training [tutorial](
          https://www.tensorflow.org/tutorials/distribute/custom_training) for
            more details.
      name: Optional name for the instance. Defaults to
        'mean_absolute_percentage_error'.
    )r   r   N)rB   r%   rR   )r"   r   r   )r(   r#   r$   r%     s    z$MeanAbsolutePercentageError.__init__)	r)   r;   r<   r=   r   r   r9   r%   rL   r#   r#   )r(   r$   rQ     s   %rQ   z(keras.losses.MeanSquaredLogarithmicErrorc                   s*   e Zd ZdZejjdf fdd	Z  ZS )MeanSquaredLogarithmicErrora&  Computes the mean squared logarithmic error between `y_true` and `y_pred`.

  `loss = square(log(y_true + 1.) - log(y_pred + 1.))`

  Standalone usage:

  >>> y_true = [[0., 1.], [0., 0.]]
  >>> y_pred = [[1., 1.], [1., 0.]]
  >>> # Using 'auto'/'sum_over_batch_size' reduction type.
  >>> msle = tf.keras.losses.MeanSquaredLogarithmicError()
  >>> msle(y_true, y_pred).numpy()
  0.240

  >>> # Calling with 'sample_weight'.
  >>> msle(y_true, y_pred, sample_weight=[0.7, 0.3]).numpy()
  0.120

  >>> # Using 'sum' reduction type.
  >>> msle = tf.keras.losses.MeanSquaredLogarithmicError(
  ...     reduction=tf.keras.losses.Reduction.SUM)
  >>> msle(y_true, y_pred).numpy()
  0.480

  >>> # Using 'none' reduction type.
  >>> msle = tf.keras.losses.MeanSquaredLogarithmicError(
  ...     reduction=tf.keras.losses.Reduction.NONE)
  >>> msle(y_true, y_pred).numpy()
  array([0.240, 0.240], dtype=float32)

  Usage with the `compile()` API:

  ```python
  model.compile(optimizer='sgd',
                loss=tf.keras.losses.MeanSquaredLogarithmicError())
  ```
  mean_squared_logarithmic_errorc                s   t  jt||d dS )a
  Initializes `MeanSquaredLogarithmicError` instance.

    Args:
      reduction: Type of `tf.keras.losses.Reduction` to apply to
        loss. Default value is `AUTO`. `AUTO` indicates that the reduction
        option will be determined by the usage context. For almost all cases
        this defaults to `SUM_OVER_BATCH_SIZE`. When used with
        `tf.distribute.Strategy`, outside of built-in training loops such as
        `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE`
        will raise an error. Please see this custom training [tutorial](
          https://www.tensorflow.org/tutorials/distribute/custom_training) for
            more details.
      name: Optional name for the instance. Defaults to
        'mean_squared_logarithmic_error'.
    )r   r   N)rB   r%   rT   )r"   r   r   )r(   r#   r$   r%     s    z$MeanSquaredLogarithmicError.__init__)	r)   r;   r<   r=   r   r   r9   r%   rL   r#   r#   )r(   r$   rS     s   %rS   zkeras.losses.BinaryCrossentropyc                   s0   e Zd ZdZdddejjdf fdd	Z  ZS )BinaryCrossentropya  Computes the cross-entropy loss between true labels and predicted labels.

  Use this cross-entropy loss for binary (0 or 1) classification applications.
  The loss function requires the following inputs:

  - `y_true` (true label): This is either 0 or 1.
  - `y_pred` (predicted value): This is the model's prediction, i.e, a single
    floating-point value which either represents a
    [logit](https://en.wikipedia.org/wiki/Logit), (i.e, value in [-inf, inf]
    when `from_logits=True`) or a probability (i.e, value in [0., 1.] when
    `from_logits=False`).

  **Recommended Usage:** (set `from_logits=True`)

  With `tf.keras` API:

  ```python
  model.compile(
    loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
    ....
  )
  ```

  As a standalone function:

  >>> # Example 1: (batch_size = 1, number of samples = 4)
  >>> y_true = [0, 1, 0, 0]
  >>> y_pred = [-18.6, 0.51, 2.94, -12.8]
  >>> bce = tf.keras.losses.BinaryCrossentropy(from_logits=True)
  >>> bce(y_true, y_pred).numpy()
  0.865

  >>> # Example 2: (batch_size = 2, number of samples = 4)
  >>> y_true = [[0, 1], [0, 0]]
  >>> y_pred = [[-18.6, 0.51], [2.94, -12.8]]
  >>> # Using default 'auto'/'sum_over_batch_size' reduction type.
  >>> bce = tf.keras.losses.BinaryCrossentropy(from_logits=True)
  >>> bce(y_true, y_pred).numpy()
  0.865
  >>> # Using 'sample_weight' attribute
  >>> bce(y_true, y_pred, sample_weight=[0.8, 0.2]).numpy()
  0.243
  >>> # Using 'sum' reduction` type.
  >>> bce = tf.keras.losses.BinaryCrossentropy(from_logits=True,
  ...     reduction=tf.keras.losses.Reduction.SUM)
  >>> bce(y_true, y_pred).numpy()
  1.730
  >>> # Using 'none' reduction type.
  >>> bce = tf.keras.losses.BinaryCrossentropy(from_logits=True,
  ...     reduction=tf.keras.losses.Reduction.NONE)
  >>> bce(y_true, y_pred).numpy()
  array([0.235, 1.496], dtype=float32)

  **Default Usage:** (set `from_logits=False`)

  >>> # Make the following updates to the above "Recommended Usage" section
  >>> # 1. Set `from_logits=False`
  >>> tf.keras.losses.BinaryCrossentropy() # OR ...('from_logits=False')
  >>> # 2. Update `y_pred` to use probabilities instead of logits
  >>> y_pred = [0.6, 0.3, 0.2, 0.8] # OR [[0.6, 0.3], [0.2, 0.8]]
  Fr   binary_crossentropyc                s"   t  jt|||||d || _dS )a]  Initializes `BinaryCrossentropy` instance.

    Args:
      from_logits: Whether to interpret `y_pred` as a tensor of
        [logit](https://en.wikipedia.org/wiki/Logit) values. By default, we
          assume that `y_pred` contains probabilities (i.e., values in [0, 1]).
      label_smoothing: Float in [0, 1]. When 0, no smoothing occurs. When > 0,
        we compute the loss between the predicted labels and a smoothed version
        of the true labels, where the smoothing squeezes the labels towards 0.5.
        Larger values of `label_smoothing` correspond to heavier smoothing.
      axis: The axis along which to compute crossentropy (the features axis).
        Defaults to -1.
      reduction: Type of `tf.keras.losses.Reduction` to apply to
        loss. Default value is `AUTO`. `AUTO` indicates that the reduction
        option will be determined by the usage context. For almost all cases
        this defaults to `SUM_OVER_BATCH_SIZE`. When used with
        `tf.distribute.Strategy`, outside of built-in training loops such as
        `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE`
        will raise an error. Please see this custom training [tutorial](
          https://www.tensorflow.org/tutorials/distribute/custom_training) for
            more details.
      name: Name for the op. Defaults to 'binary_crossentropy'.
    )r   r   from_logitslabel_smoothingaxisN)rB   r%   rW   rX   )r"   rX   rY   rZ   r   r   )r(   r#   r$   r%   ;  s    zBinaryCrossentropy.__init__)	r)   r;   r<   r=   r   r   r9   r%   rL   r#   r#   )r(   r$   rU     s   >rU   z$keras.losses.CategoricalCrossentropyc                   s0   e Zd ZdZdddejjdf fdd	Z  ZS )CategoricalCrossentropya  Computes the crossentropy loss between the labels and predictions.

  Use this crossentropy loss function when there are two or more label classes.
  We expect labels to be provided in a `one_hot` representation. If you want to
  provide labels as integers, please use `SparseCategoricalCrossentropy` loss.
  There should be `# classes` floating point values per feature.

  In the snippet below, there is `# classes` floating pointing values per
  example. The shape of both `y_pred` and `y_true` are
  `[batch_size, num_classes]`.

  Standalone usage:

  >>> y_true = [[0, 1, 0], [0, 0, 1]]
  >>> y_pred = [[0.05, 0.95, 0], [0.1, 0.8, 0.1]]
  >>> # Using 'auto'/'sum_over_batch_size' reduction type.
  >>> cce = tf.keras.losses.CategoricalCrossentropy()
  >>> cce(y_true, y_pred).numpy()
  1.177

  >>> # Calling with 'sample_weight'.
  >>> cce(y_true, y_pred, sample_weight=tf.constant([0.3, 0.7])).numpy()
  0.814

  >>> # Using 'sum' reduction type.
  >>> cce = tf.keras.losses.CategoricalCrossentropy(
  ...     reduction=tf.keras.losses.Reduction.SUM)
  >>> cce(y_true, y_pred).numpy()
  2.354

  >>> # Using 'none' reduction type.
  >>> cce = tf.keras.losses.CategoricalCrossentropy(
  ...     reduction=tf.keras.losses.Reduction.NONE)
  >>> cce(y_true, y_pred).numpy()
  array([0.0513, 2.303], dtype=float32)

  Usage with the `compile()` API:

  ```python
  model.compile(optimizer='sgd', loss=tf.keras.losses.CategoricalCrossentropy())
  ```
  Fr   rV   categorical_crossentropyc                s   t  jt|||||d dS )a  Initializes `CategoricalCrossentropy` instance.

    Args:
      from_logits: Whether `y_pred` is expected to be a logits tensor. By
        default, we assume that `y_pred` encodes a probability distribution.
      label_smoothing: Float in [0, 1]. When > 0, label values are smoothed,
        meaning the confidence on label values are relaxed. For example, if
        `0.1`, use `0.1 / num_classes` for non-target labels and
        `0.9 + 0.1 / num_classes` for target labels.
      axis: The axis along which to compute crossentropy (the features axis).
        Defaults to -1.
      reduction: Type of `tf.keras.losses.Reduction` to apply to
        loss. Default value is `AUTO`. `AUTO` indicates that the reduction
        option will be determined by the usage context. For almost all cases
        this defaults to `SUM_OVER_BATCH_SIZE`. When used with
        `tf.distribute.Strategy`, outside of built-in training loops such as
        `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE`
        will raise an error. Please see this custom training [tutorial](
          https://www.tensorflow.org/tutorials/distribute/custom_training) for
            more details.
      name: Optional name for the instance.
        Defaults to 'categorical_crossentropy'.
    )r   r   rX   rY   rZ   N)rB   r%   r\   )r"   rX   rY   rZ   r   r   )r(   r#   r$   r%     s    z CategoricalCrossentropy.__init__)	r)   r;   r<   r=   r   r   r9   r%   rL   r#   r#   )r(   r$   r[   b  s   +r[   z*keras.losses.SparseCategoricalCrossentropyc                   s,   e Zd ZdZdejjdf fdd	Z  ZS )SparseCategoricalCrossentropyav  Computes the crossentropy loss between the labels and predictions.

  Use this crossentropy loss function when there are two or more label classes.
  We expect labels to be provided as integers. If you want to provide labels
  using `one-hot` representation, please use `CategoricalCrossentropy` loss.
  There should be `# classes` floating point values per feature for `y_pred`
  and a single floating point value per feature for `y_true`.

  In the snippet below, there is a single floating point value per example for
  `y_true` and `# classes` floating pointing values per example for `y_pred`.
  The shape of `y_true` is `[batch_size]` and the shape of `y_pred` is
  `[batch_size, num_classes]`.

  Standalone usage:

  >>> y_true = [1, 2]
  >>> y_pred = [[0.05, 0.95, 0], [0.1, 0.8, 0.1]]
  >>> # Using 'auto'/'sum_over_batch_size' reduction type.
  >>> scce = tf.keras.losses.SparseCategoricalCrossentropy()
  >>> scce(y_true, y_pred).numpy()
  1.177

  >>> # Calling with 'sample_weight'.
  >>> scce(y_true, y_pred, sample_weight=tf.constant([0.3, 0.7])).numpy()
  0.814

  >>> # Using 'sum' reduction type.
  >>> scce = tf.keras.losses.SparseCategoricalCrossentropy(
  ...     reduction=tf.keras.losses.Reduction.SUM)
  >>> scce(y_true, y_pred).numpy()
  2.354

  >>> # Using 'none' reduction type.
  >>> scce = tf.keras.losses.SparseCategoricalCrossentropy(
  ...     reduction=tf.keras.losses.Reduction.NONE)
  >>> scce(y_true, y_pred).numpy()
  array([0.0513, 2.303], dtype=float32)

  Usage with the `compile()` API:

  ```python
  model.compile(optimizer='sgd',
                loss=tf.keras.losses.SparseCategoricalCrossentropy())
  ```
  Fsparse_categorical_crossentropyc                s   t  jt|||d dS )a  Initializes `SparseCategoricalCrossentropy` instance.

    Args:
      from_logits: Whether `y_pred` is expected to be a logits tensor. By
        default, we assume that `y_pred` encodes a probability distribution.
      reduction: Type of `tf.keras.losses.Reduction` to apply to
        loss. Default value is `AUTO`. `AUTO` indicates that the reduction
        option will be determined by the usage context. For almost all cases
        this defaults to `SUM_OVER_BATCH_SIZE`. When used with
        `tf.distribute.Strategy`, outside of built-in training loops such as
        `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE`
        will raise an error. Please see this custom training [tutorial](
          https://www.tensorflow.org/tutorials/distribute/custom_training) for
            more details.
      name: Optional name for the instance. Defaults to
        'sparse_categorical_crossentropy'.
    )r   r   rX   N)rB   r%   r^   )r"   rX   r   r   )r(   r#   r$   r%     s
    z&SparseCategoricalCrossentropy.__init__)	r)   r;   r<   r=   r   r   r9   r%   rL   r#   r#   )r(   r$   r]     s   .r]   zkeras.losses.Hingec                   s*   e Zd ZdZejjdf fdd	Z  ZS )Hingea  Computes the hinge loss between `y_true` and `y_pred`.

  `loss = maximum(1 - y_true * y_pred, 0)`

  `y_true` values are expected to be -1 or 1. If binary (0 or 1) labels are
  provided we will convert them to -1 or 1.

  Standalone usage:

  >>> y_true = [[0., 1.], [0., 0.]]
  >>> y_pred = [[0.6, 0.4], [0.4, 0.6]]
  >>> # Using 'auto'/'sum_over_batch_size' reduction type.
  >>> h = tf.keras.losses.Hinge()
  >>> h(y_true, y_pred).numpy()
  1.3

  >>> # Calling with 'sample_weight'.
  >>> h(y_true, y_pred, sample_weight=[1, 0]).numpy()
  0.55

  >>> # Using 'sum' reduction type.
  >>> h = tf.keras.losses.Hinge(
  ...     reduction=tf.keras.losses.Reduction.SUM)
  >>> h(y_true, y_pred).numpy()
  2.6

  >>> # Using 'none' reduction type.
  >>> h = tf.keras.losses.Hinge(
  ...     reduction=tf.keras.losses.Reduction.NONE)
  >>> h(y_true, y_pred).numpy()
  array([1.1, 1.5], dtype=float32)

  Usage with the `compile()` API:

  ```python
  model.compile(optimizer='sgd', loss=tf.keras.losses.Hinge())
  ```
  hingec                s   t  jt||d dS )a  Initializes `Hinge` instance.

    Args:
      reduction: Type of `tf.keras.losses.Reduction` to apply to
        loss. Default value is `AUTO`. `AUTO` indicates that the reduction
        option will be determined by the usage context. For almost all cases
        this defaults to `SUM_OVER_BATCH_SIZE`. When used with
        `tf.distribute.Strategy`, outside of built-in training loops such as
        `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE`
        will raise an error. Please see this custom training [tutorial](
          https://www.tensorflow.org/tutorials/distribute/custom_training) for
            more details.
      name: Optional name for the instance. Defaults to 'hinge'.
    )r   r   N)rB   r%   r`   )r"   r   r   )r(   r#   r$   r%   *  s    zHinge.__init__)	r)   r;   r<   r=   r   r   r9   r%   rL   r#   r#   )r(   r$   r_     s   'r_   zkeras.losses.SquaredHingec                   s*   e Zd ZdZejjdf fdd	Z  ZS )SquaredHingea)  Computes the squared hinge loss between `y_true` and `y_pred`.

  `loss = square(maximum(1 - y_true * y_pred, 0))`

  `y_true` values are expected to be -1 or 1. If binary (0 or 1) labels are
  provided we will convert them to -1 or 1.

  Standalone usage:

  >>> y_true = [[0., 1.], [0., 0.]]
  >>> y_pred = [[0.6, 0.4], [0.4, 0.6]]
  >>> # Using 'auto'/'sum_over_batch_size' reduction type.
  >>> h = tf.keras.losses.SquaredHinge()
  >>> h(y_true, y_pred).numpy()
  1.86

  >>> # Calling with 'sample_weight'.
  >>> h(y_true, y_pred, sample_weight=[1, 0]).numpy()
  0.73

  >>> # Using 'sum' reduction type.
  >>> h = tf.keras.losses.SquaredHinge(
  ...     reduction=tf.keras.losses.Reduction.SUM)
  >>> h(y_true, y_pred).numpy()
  3.72

  >>> # Using 'none' reduction type.
  >>> h = tf.keras.losses.SquaredHinge(
  ...     reduction=tf.keras.losses.Reduction.NONE)
  >>> h(y_true, y_pred).numpy()
  array([1.46, 2.26], dtype=float32)

  Usage with the `compile()` API:

  ```python
  model.compile(optimizer='sgd', loss=tf.keras.losses.SquaredHinge())
  ```
  squared_hingec                s   t  jt||d dS )a  Initializes `SquaredHinge` instance.

    Args:
      reduction: Type of `tf.keras.losses.Reduction` to apply to
        loss. Default value is `AUTO`. `AUTO` indicates that the reduction
        option will be determined by the usage context. For almost all cases
        this defaults to `SUM_OVER_BATCH_SIZE`. When used with
        `tf.distribute.Strategy`, outside of built-in training loops such as
        `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE`
        will raise an error. Please see this custom training [tutorial](
          https://www.tensorflow.org/tutorials/distribute/custom_training) for
            more details.
      name: Optional name for the instance. Defaults to 'squared_hinge'.
    )r   r   N)rB   r%   rb   )r"   r   r   )r(   r#   r$   r%   e  s    zSquaredHinge.__init__)	r)   r;   r<   r=   r   r   r9   r%   rL   r#   r#   )r(   r$   ra   <  s   'ra   zkeras.losses.CategoricalHingec                   s*   e Zd ZdZejjdf fdd	Z  ZS )CategoricalHingea  Computes the categorical hinge loss between `y_true` and `y_pred`.

  `loss = maximum(neg - pos + 1, 0)`
  where `neg=maximum((1-y_true)*y_pred) and pos=sum(y_true*y_pred)`

  Standalone usage:

  >>> y_true = [[0, 1], [0, 0]]
  >>> y_pred = [[0.6, 0.4], [0.4, 0.6]]
  >>> # Using 'auto'/'sum_over_batch_size' reduction type.
  >>> h = tf.keras.losses.CategoricalHinge()
  >>> h(y_true, y_pred).numpy()
  1.4

  >>> # Calling with 'sample_weight'.
  >>> h(y_true, y_pred, sample_weight=[1, 0]).numpy()
  0.6

  >>> # Using 'sum' reduction type.
  >>> h = tf.keras.losses.CategoricalHinge(
  ...     reduction=tf.keras.losses.Reduction.SUM)
  >>> h(y_true, y_pred).numpy()
  2.8

  >>> # Using 'none' reduction type.
  >>> h = tf.keras.losses.CategoricalHinge(
  ...     reduction=tf.keras.losses.Reduction.NONE)
  >>> h(y_true, y_pred).numpy()
  array([1.2, 1.6], dtype=float32)

  Usage with the `compile()` API:

  ```python
  model.compile(optimizer='sgd', loss=tf.keras.losses.CategoricalHinge())
  ```
  categorical_hingec                s   t  jt||d dS )a  Initializes `CategoricalHinge` instance.

    Args:
      reduction: Type of `tf.keras.losses.Reduction` to apply to
        loss. Default value is `AUTO`. `AUTO` indicates that the reduction
        option will be determined by the usage context. For almost all cases
        this defaults to `SUM_OVER_BATCH_SIZE`. When used with
        `tf.distribute.Strategy`, outside of built-in training loops such as
        `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE`
        will raise an error. Please see this custom training [tutorial](
          https://www.tensorflow.org/tutorials/distribute/custom_training) for
            more details.
      name: Optional name for the instance. Defaults to 'categorical_hinge'.
    )r   r   N)rB   r%   rd   )r"   r   r   )r(   r#   r$   r%     s    zCategoricalHinge.__init__)	r)   r;   r<   r=   r   r   r9   r%   rL   r#   r#   )r(   r$   rc   y  s   %rc   zkeras.losses.Poissonc                   s*   e Zd ZdZejjdf fdd	Z  ZS )Poissona  Computes the Poisson loss between `y_true` and `y_pred`.

  `loss = y_pred - y_true * log(y_pred)`

  Standalone usage:

  >>> y_true = [[0., 1.], [0., 0.]]
  >>> y_pred = [[1., 1.], [0., 0.]]
  >>> # Using 'auto'/'sum_over_batch_size' reduction type.
  >>> p = tf.keras.losses.Poisson()
  >>> p(y_true, y_pred).numpy()
  0.5

  >>> # Calling with 'sample_weight'.
  >>> p(y_true, y_pred, sample_weight=[0.8, 0.2]).numpy()
  0.4

  >>> # Using 'sum' reduction type.
  >>> p = tf.keras.losses.Poisson(
  ...     reduction=tf.keras.losses.Reduction.SUM)
  >>> p(y_true, y_pred).numpy()
  0.999

  >>> # Using 'none' reduction type.
  >>> p = tf.keras.losses.Poisson(
  ...     reduction=tf.keras.losses.Reduction.NONE)
  >>> p(y_true, y_pred).numpy()
  array([0.999, 0.], dtype=float32)

  Usage with the `compile()` API:

  ```python
  model.compile(optimizer='sgd', loss=tf.keras.losses.Poisson())
  ```
  poissonc                s   t  jt||d dS )a  Initializes `Poisson` instance.

    Args:
      reduction: Type of `tf.keras.losses.Reduction` to apply to
        loss. Default value is `AUTO`. `AUTO` indicates that the reduction
        option will be determined by the usage context. For almost all cases
        this defaults to `SUM_OVER_BATCH_SIZE`. When used with
        `tf.distribute.Strategy`, outside of built-in training loops such as
        `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE`
        will raise an error. Please see this custom training [tutorial](
          https://www.tensorflow.org/tutorials/distribute/custom_training) for
            more details.
      name: Optional name for the instance. Defaults to 'poisson'.
    )r   r   N)rB   r%   rf   )r"   r   r   )r(   r#   r$   r%     s    zPoisson.__init__)	r)   r;   r<   r=   r   r   r9   r%   rL   r#   r#   )r(   r$   re     s   $re   zkeras.losses.LogCoshc                   s*   e Zd ZdZejjdf fdd	Z  ZS )LogCosha  Computes the logarithm of the hyperbolic cosine of the prediction error.

  `logcosh = log((exp(x) + exp(-x))/2)`,
  where x is the error `y_pred - y_true`.

  Standalone usage:

  >>> y_true = [[0., 1.], [0., 0.]]
  >>> y_pred = [[1., 1.], [0., 0.]]
  >>> # Using 'auto'/'sum_over_batch_size' reduction type.
  >>> l = tf.keras.losses.LogCosh()
  >>> l(y_true, y_pred).numpy()
  0.108

  >>> # Calling with 'sample_weight'.
  >>> l(y_true, y_pred, sample_weight=[0.8, 0.2]).numpy()
  0.087

  >>> # Using 'sum' reduction type.
  >>> l = tf.keras.losses.LogCosh(
  ...     reduction=tf.keras.losses.Reduction.SUM)
  >>> l(y_true, y_pred).numpy()
  0.217

  >>> # Using 'none' reduction type.
  >>> l = tf.keras.losses.LogCosh(
  ...     reduction=tf.keras.losses.Reduction.NONE)
  >>> l(y_true, y_pred).numpy()
  array([0.217, 0.], dtype=float32)

  Usage with the `compile()` API:

  ```python
  model.compile(optimizer='sgd', loss=tf.keras.losses.LogCosh())
  ```
  log_coshc                s   t  jt||d dS )a  Initializes `LogCosh` instance.

    Args:
      reduction: Type of `tf.keras.losses.Reduction` to apply to
        loss. Default value is `AUTO`. `AUTO` indicates that the reduction
        option will be determined by the usage context. For almost all cases
        this defaults to `SUM_OVER_BATCH_SIZE`. When used with
        `tf.distribute.Strategy`, outside of built-in training loops such as
        `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE`
        will raise an error. Please see this custom training [tutorial](
          https://www.tensorflow.org/tutorials/distribute/custom_training) for
            more details.
      name: Optional name for the instance. Defaults to 'log_cosh'.
    )r   r   N)rB   r%   rh   )r"   r   r   )r(   r#   r$   r%     s    zLogCosh.__init__)	r)   r;   r<   r=   r   r   r9   r%   rL   r#   r#   )r(   r$   rg     s   %rg   zkeras.losses.KLDivergencec                   s*   e Zd ZdZejjdf fdd	Z  ZS )KLDivergencea
  Computes Kullback-Leibler divergence loss between `y_true` and `y_pred`.

  `loss = y_true * log(y_true / y_pred)`

  See: https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence

  Standalone usage:

  >>> y_true = [[0, 1], [0, 0]]
  >>> y_pred = [[0.6, 0.4], [0.4, 0.6]]
  >>> # Using 'auto'/'sum_over_batch_size' reduction type.
  >>> kl = tf.keras.losses.KLDivergence()
  >>> kl(y_true, y_pred).numpy()
  0.458

  >>> # Calling with 'sample_weight'.
  >>> kl(y_true, y_pred, sample_weight=[0.8, 0.2]).numpy()
  0.366

  >>> # Using 'sum' reduction type.
  >>> kl = tf.keras.losses.KLDivergence(
  ...     reduction=tf.keras.losses.Reduction.SUM)
  >>> kl(y_true, y_pred).numpy()
  0.916

  >>> # Using 'none' reduction type.
  >>> kl = tf.keras.losses.KLDivergence(
  ...     reduction=tf.keras.losses.Reduction.NONE)
  >>> kl(y_true, y_pred).numpy()
  array([0.916, -3.08e-06], dtype=float32)

  Usage with the `compile()` API:

  ```python
  model.compile(optimizer='sgd', loss=tf.keras.losses.KLDivergence())
  ```
  kl_divergencec                s   t  jt||d dS )a  Initializes `KLDivergence` instance.

    Args:
      reduction: Type of `tf.keras.losses.Reduction` to apply to
        loss. Default value is `AUTO`. `AUTO` indicates that the reduction
        option will be determined by the usage context. For almost all cases
        this defaults to `SUM_OVER_BATCH_SIZE`. When used with
        `tf.distribute.Strategy`, outside of built-in training loops such as
        `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE`
        will raise an error. Please see this custom training [tutorial](
          https://www.tensorflow.org/tutorials/distribute/custom_training) for
            more details.
      name: Optional name for the instance. Defaults to 'kl_divergence'.
    )r   r   N)rB   r%   rj   )r"   r   r   )r(   r#   r$   r%   M  s    zKLDivergence.__init__)	r)   r;   r<   r=   r   r   r9   r%   rL   r#   r#   )r(   r$   ri   %  s   &ri   zkeras.losses.Huberc                   s,   e Zd ZdZdejjdf fdd	Z  ZS )Hubera7  Computes the Huber loss between `y_true` and `y_pred`.

  For each value x in `error = y_true - y_pred`:

  ```
  loss = 0.5 * x^2                  if |x| <= d
  loss = 0.5 * d^2 + d * (|x| - d)  if |x| > d
  ```
  where d is `delta`. See: https://en.wikipedia.org/wiki/Huber_loss

  Standalone usage:

  >>> y_true = [[0, 1], [0, 0]]
  >>> y_pred = [[0.6, 0.4], [0.4, 0.6]]
  >>> # Using 'auto'/'sum_over_batch_size' reduction type.
  >>> h = tf.keras.losses.Huber()
  >>> h(y_true, y_pred).numpy()
  0.155

  >>> # Calling with 'sample_weight'.
  >>> h(y_true, y_pred, sample_weight=[1, 0]).numpy()
  0.09

  >>> # Using 'sum' reduction type.
  >>> h = tf.keras.losses.Huber(
  ...     reduction=tf.keras.losses.Reduction.SUM)
  >>> h(y_true, y_pred).numpy()
  0.31

  >>> # Using 'none' reduction type.
  >>> h = tf.keras.losses.Huber(
  ...     reduction=tf.keras.losses.Reduction.NONE)
  >>> h(y_true, y_pred).numpy()
  array([0.18, 0.13], dtype=float32)

  Usage with the `compile()` API:

  ```python
  model.compile(optimizer='sgd', loss=tf.keras.losses.Huber())
  ```
  g      ?
huber_lossc                s   t  jt|||d dS )aB  Initializes `Huber` instance.

    Args:
      delta: A float, the point where the Huber loss function changes from a
        quadratic to linear.
      reduction: Type of `tf.keras.losses.Reduction` to apply to
        loss. Default value is `AUTO`. `AUTO` indicates that the reduction
        option will be determined by the usage context. For almost all cases
        this defaults to `SUM_OVER_BATCH_SIZE`. When used with
        `tf.distribute.Strategy`, outside of built-in training loops such as
        `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE`
        will raise an error. Please see this custom training [tutorial](
          https://www.tensorflow.org/tutorials/distribute/custom_training) for
            more details.
      name: Optional name for the instance. Defaults to 'huber_loss'.
    )r   r   deltaN)rB   r%   huber)r"   rm   r   r   )r(   r#   r$   r%     s    zHuber.__init__)	r)   r;   r<   r=   r   r   r9   r%   rL   r#   r#   )r(   r$   rk   a  s   *rk   z keras.metrics.mean_squared_errorzkeras.metrics.msezkeras.metrics.MSEzkeras.losses.mean_squared_errorzkeras.losses.msezkeras.losses.MSEc             C   s.   t |}t| |j} tjt|| ddS )a  Computes the mean squared error between labels and predictions.

  After computing the squared distance between the inputs, the mean value over
  the last dimension is returned.

  `loss = mean(square(y_true - y_pred), axis=-1)`

  Standalone usage:

  >>> y_true = np.random.randint(0, 2, size=(2, 3))
  >>> y_pred = np.random.random(size=(2, 3))
  >>> loss = tf.keras.losses.mean_squared_error(y_true, y_pred)
  >>> assert loss.shape == (2,)
  >>> assert np.array_equal(
  ...     loss.numpy(), np.mean(np.square(y_true - y_pred), axis=-1))

  Args:
    y_true: Ground truth values. shape = `[batch_size, d0, .. dN]`.
    y_pred: The predicted values. shape = `[batch_size, d0, .. dN]`.

  Returns:
    Mean squared error values. shape = `[batch_size, d0, .. dN-1]`.
  rV   )rZ   )r   "convert_to_tensor_v2_with_dispatchr   castdtyper   meansquared_difference)r1   r2   r#   r#   r$   rN     s    
rN   Fc          	      s  dd dd fdd  fdd}t |tjsH|| S |j d	d
 }t|dkrxtj||jd}nt	j
g |jd}dd ||fD }|rdd |D }|d |d	 d	 kr|d	 dd
 |d	< tj|t|d	kd}	t|}
t|
 tj|	||f|dS Q R X dS )a  Apply a loss function on a per batch basis.

  Args:
    loss_fn: The loss function
    y_true: truth values (RaggedTensor)
    y_pred: predicted values (RaggedTensor)
    y_pred_extra_dim: whether y_pred has an additional dimension compared to
      y_true

  Returns:
    Loss-function result. A dense tensor if the output has a single dimension
    (per-batch loss value); a ragged tensor otherwise.
  c             S   s   t dd |  D S )zReturns true if this RaggedTensor has the same row_lenghts across

       all ragged dimensions and thus can be converted to a dense tensor
       without loss of information.

    Args:
      rt: RaggedTensor.
    c             S   s2   g | ]*}t t t |t td gqS )g        )r   equalZreduce_variancerp   r   floatxr   Zconstant).0Zrow_lensr#   r#   r$   
<listcomp>  s   zH_ragged_tensor_apply_loss.<locals>.rt_is_equiv_dense.<locals>.<listcomp>)r   
reduce_allZnested_row_lengths)rtr#   r#   r$   rt_is_equiv_dense  s    	z4_ragged_tensor_apply_loss.<locals>.rt_is_equiv_densec             S   s   t dd | D S )Nc             s   s&   | ]}t |tjr| n|V  qd S )N)
isinstancer   RaggedTensor	to_tensor)rv   ry   r#   r#   r$   	<genexpr>  s   zG_ragged_tensor_apply_loss.<locals>._convert_to_dense.<locals>.<genexpr>)tuple)inputsr#   r#   r$   _convert_to_dense  s    z4_ragged_tensor_apply_loss.<locals>._convert_to_densec                sB    |  }|r&t |tjs&tj|}n|s>t |tjr>| }|S )z Adapt the result to ragged or dense tensor according to the expected

        output type. This is done so that all the return values of the map
        operation have the same type.
    )r{   r   r|   Zfrom_tensorr}   )r   ragged_outputr)loss_fnr#   r$   
_call_loss  s    z-_ragged_tensor_apply_loss.<locals>._call_lossc                sH    \}}t |tjr@t| fdd fddS   S )Nc                  s    S )Nr#   r#   )r   r   r   r   r#   r$   <lambda>      z=_ragged_tensor_apply_loss.<locals>._wrapper.<locals>.<lambda>c                  s
    S )Nr#   r#   )r   r   r   r#   r$   r     r   )r{   r   r|   r   Zcond)r   r   r'   r2   )r   r   r   rz   )r   r   r$   _wrapper  s    z+_ragged_tensor_apply_loss.<locals>._wrapper   rV   r   )shaperq   c             S   s   g | ]
}|j qS r#   )Znested_row_splits)rv   ry   r#   r#   r$   rw     s    z-_ragged_tensor_apply_loss.<locals>.<listcomp>c             S   s   g | ]}t |qS r#   )len)rv   slistr#   r#   r$   rw     s    N)r   )Zelemsrq   )r{   r   r|   r}   r   as_listr   ZRaggedTensorSpecrq   r	   Z
TensorSpec	functoolspartialr   Zassert_splits_matchr   Zcontrol_dependenciesr   map_fn)r   r1   r2   y_pred_extra_dimr   ZlshapespecZnested_splits_listZrdimsr   Zassertion_listr#   )r   r   r   rz   r$   _ragged_tensor_apply_loss  s&    

r   c             C   s   t t| |S )a  Implements support for handling RaggedTensors.

  Args:
    y_true: RaggedTensor truth values. shape = `[batch_size, d0, .. dN]`.
    y_pred: RaggedTensor predicted values. shape = `[batch_size, d0, .. dN]`.

  Returns:
    Mean squared error values. shape = `[batch_size, d0, .. dN-1]`.
    When the number of dimensions of the batch feature vector [d0, .. dN] is
    greater than one the return value is a RaggedTensor. Otherwise a Dense
    tensor with dimensions [batch_size] is returned.
  )r   rN   )r1   r2   r#   r#   r$   _ragged_tensor_mse  s    r   z!keras.metrics.mean_absolute_errorzkeras.metrics.maezkeras.metrics.MAEz keras.losses.mean_absolute_errorzkeras.losses.maezkeras.losses.MAEc             C   s0   t |}t| |j} tjt||  ddS )a  Computes the mean absolute error between labels and predictions.

  `loss = mean(abs(y_true - y_pred), axis=-1)`

  Standalone usage:

  >>> y_true = np.random.randint(0, 2, size=(2, 3))
  >>> y_pred = np.random.random(size=(2, 3))
  >>> loss = tf.keras.losses.mean_absolute_error(y_true, y_pred)
  >>> assert loss.shape == (2,)
  >>> assert np.array_equal(
  ...     loss.numpy(), np.mean(np.abs(y_true - y_pred), axis=-1))

  Args:
    y_true: Ground truth values. shape = `[batch_size, d0, .. dN]`.
    y_pred: The predicted values. shape = `[batch_size, d0, .. dN]`.

  Returns:
    Mean absolute error values. shape = `[batch_size, d0, .. dN-1]`.
  rV   )rZ   )r   ro   r   rp   rq   r   rr   abs)r1   r2   r#   r#   r$   rP   '  s    
rP   c             C   s   t t| |S )z-RaggedTensor adapter for mean_absolute_error.)r   rP   )r1   r2   r#   r#   r$   _ragged_tensor_maeE  s    r   z,keras.metrics.mean_absolute_percentage_errorzkeras.metrics.mapezkeras.metrics.MAPEz+keras.losses.mean_absolute_percentage_errorzkeras.losses.mapezkeras.losses.MAPEc             C   sN   t |}t| |j} t| | tt| t  }dtj	|dd S )a  Computes the mean absolute percentage error between `y_true` and `y_pred`.

  `loss = 100 * mean(abs((y_true - y_pred) / y_true), axis=-1)`

  Standalone usage:

  >>> y_true = np.random.random(size=(2, 3))
  >>> y_true = np.maximum(y_true, 1e-7)  # Prevent division by zero
  >>> y_pred = np.random.random(size=(2, 3))
  >>> loss = tf.keras.losses.mean_absolute_percentage_error(y_true, y_pred)
  >>> assert loss.shape == (2,)
  >>> assert np.array_equal(
  ...     loss.numpy(),
  ...     100. * np.mean(np.abs((y_true - y_pred) / y_true), axis=-1))

  Args:
    y_true: Ground truth values. shape = `[batch_size, d0, .. dN]`.
    y_pred: The predicted values. shape = `[batch_size, d0, .. dN]`.

  Returns:
    Mean absolute percentage error values. shape = `[batch_size, d0, .. dN-1]`.
  g      Y@rV   )rZ   )
r   ro   r   rp   rq   r   r   maximumepsilonrr   )r1   r2   diffr#   r#   r$   rR   K  s    
rR   c             C   s   t t| |S )zSupport RaggedTensors.)r   rR   )r1   r2   r#   r#   r$   _ragged_tensor_mapeo  s    r   z,keras.metrics.mean_squared_logarithmic_errorzkeras.metrics.mslezkeras.metrics.MSLEz+keras.losses.mean_squared_logarithmic_errorzkeras.losses.mslezkeras.losses.MSLEc             C   sb   t |}t| |j} tt|t d }tt| t d }tj	t
||ddS )aF  Computes the mean squared logarithmic error between `y_true` and `y_pred`.

  `loss = mean(square(log(y_true + 1) - log(y_pred + 1)), axis=-1)`

  Standalone usage:

  >>> y_true = np.random.randint(0, 2, size=(2, 3))
  >>> y_pred = np.random.random(size=(2, 3))
  >>> loss = tf.keras.losses.mean_squared_logarithmic_error(y_true, y_pred)
  >>> assert loss.shape == (2,)
  >>> y_true = np.maximum(y_true, 1e-7)
  >>> y_pred = np.maximum(y_pred, 1e-7)
  >>> assert np.allclose(
  ...     loss.numpy(),
  ...     np.mean(
  ...         np.square(np.log(y_true + 1.) - np.log(y_pred + 1.)), axis=-1))

  Args:
    y_true: Ground truth values. shape = `[batch_size, d0, .. dN]`.
    y_pred: The predicted values. shape = `[batch_size, d0, .. dN]`.

  Returns:
    Mean squared logarithmic error values. shape = `[batch_size, d0, .. dN-1]`.
  g      ?rV   )rZ   )r   ro   r   rp   rq   logr   r   r   rr   rs   )r1   r2   Z	first_logZ
second_logr#   r#   r$   rT   w  s    
rT   c             C   s   t t| |S )z.Implements support for handling RaggedTensors.)r   rT   )r1   r2   r#   r#   r$   _ragged_tensor_msle  s    r   c                sP   t  d}t  d}t t ||} fdd}t|| fdd}|S )z!Converts binary labels into -1/1.r   r   c                  s   d  d S )Ng       @g      ?r#   r#   )r1   r#   r$   _convert_binary_labels  s    z5_maybe_convert_labels.<locals>._convert_binary_labelsc                  s    S )Nr#   r#   )r1   r#   r$   r     r   z'_maybe_convert_labels.<locals>.<lambda>)r   rt   rx   
logical_orr   )r1   Z	are_zerosZare_onesZ	is_binaryr   Zupdated_y_truer#   )r1   r$   _maybe_convert_labels  s    r   zkeras.metrics.squared_hingezkeras.losses.squared_hingec             C   sD   t |}t| |j} t| } tjtt	d| |  dddS )aA  Computes the squared hinge loss between `y_true` and `y_pred`.

  `loss = mean(square(maximum(1 - y_true * y_pred, 0)), axis=-1)`

  Standalone usage:

  >>> y_true = np.random.choice([-1, 1], size=(2, 3))
  >>> y_pred = np.random.random(size=(2, 3))
  >>> loss = tf.keras.losses.squared_hinge(y_true, y_pred)
  >>> assert loss.shape == (2,)
  >>> assert np.array_equal(
  ...     loss.numpy(),
  ...     np.mean(np.square(np.maximum(1. - y_true * y_pred, 0.)), axis=-1))

  Args:
    y_true: The ground truth values. `y_true` values are expected to be -1 or 1.
      If binary (0 or 1) labels are provided we will convert them to -1 or 1.
      shape = `[batch_size, d0, .. dN]`.
    y_pred: The predicted values. shape = `[batch_size, d0, .. dN]`.

  Returns:
     Squared hinge loss values. shape = `[batch_size, d0, .. dN-1]`.
  g      ?g        rV   )rZ   )
r   ro   r   rp   rq   r   r   rr   squarer   )r1   r2   r#   r#   r$   rb     s
    
rb   zkeras.metrics.hingezkeras.losses.hingec             C   s>   t |}t| |j} t| } tjtd| |  dddS )a  Computes the hinge loss between `y_true` and `y_pred`.

  `loss = mean(maximum(1 - y_true * y_pred, 0), axis=-1)`

  Standalone usage:

  >>> y_true = np.random.choice([-1, 1], size=(2, 3))
  >>> y_pred = np.random.random(size=(2, 3))
  >>> loss = tf.keras.losses.hinge(y_true, y_pred)
  >>> assert loss.shape == (2,)
  >>> assert np.array_equal(
  ...     loss.numpy(),
  ...     np.mean(np.maximum(1. - y_true * y_pred, 0.), axis=-1))

  Args:
    y_true: The ground truth values. `y_true` values are expected to be -1 or 1.
      If binary (0 or 1) labels are provided they will be converted to -1 or 1.
      shape = `[batch_size, d0, .. dN]`.
    y_pred: The predicted values. shape = `[batch_size, d0, .. dN]`.

  Returns:
    Hinge loss values. shape = `[batch_size, d0, .. dN-1]`.
  g      ?g        rV   )rZ   )	r   ro   r   rp   rq   r   r   rr   r   )r1   r2   r#   r#   r$   r`     s    
r`   zkeras.losses.categorical_hingec             C   sb   t |}t| |j} tj| | dd}tjd|  | dd}td|j}t|| d |S )aX  Computes the categorical hinge loss between `y_true` and `y_pred`.

  `loss = maximum(neg - pos + 1, 0)`
  where `neg=maximum((1-y_true)*y_pred) and pos=sum(y_true*y_pred)`

  Standalone usage:

  >>> y_true = np.random.randint(0, 3, size=(2,))
  >>> y_true = tf.keras.utils.to_categorical(y_true, num_classes=3)
  >>> y_pred = np.random.random(size=(2, 3))
  >>> loss = tf.keras.losses.categorical_hinge(y_true, y_pred)
  >>> assert loss.shape == (2,)
  >>> pos = np.sum(y_true * y_pred, axis=-1)
  >>> neg = np.amax((1. - y_true) * y_pred, axis=-1)
  >>> assert np.array_equal(loss.numpy(), np.maximum(0., neg - pos + 1.))

  Args:
    y_true: The ground truth values. `y_true` values are expected to be
    either `{-1, +1}` or `{0, 1}` (i.e. a one-hot-encoded tensor).
    y_pred: The predicted values.

  Returns:
    Categorical hinge loss values.
  rV   )rZ   g      ?g        )r   ro   r   rp   rq   
reduce_sumZ
reduce_maxr   )r1   r2   posnegzeror#   r#   r$   rd     s    
rd   zkeras.losses.huber)Zv1      ?c          
   C   s   t j|t d}t j| t d} t j|t d}t || }t |}tjd|jd}tj	t
||k|t | || |t |  ddS )a  Computes Huber loss value.

  For each value x in `error = y_true - y_pred`:

  ```
  loss = 0.5 * x^2                  if |x| <= d
  loss = d * |x| - 0.5 * d^2        if |x| > d
  ```
  where d is `delta`. See: https://en.wikipedia.org/wiki/Huber_loss

  Args:
    y_true: tensor of true targets.
    y_pred: tensor of predicted targets.
    delta: A float, the point where the Huber loss function changes from a
      quadratic to linear.

  Returns:
    Tensor with one scalar loss entry per sample.
  )rq   g      ?rV   )rZ   )r   rp   r   ru   subtractr   r   ro   rq   rr   r   Zwhere_v2r   )r1   r2   rm   errorZ	abs_errorZhalfr#   r#   r$   rn     s    
rn   zkeras.losses.log_coshzkeras.losses.logcoshzkeras.metrics.log_coshzkeras.metrics.logcoshc             C   s6   t |}t| |j} dd }tj|||  ddS )a  Logarithm of the hyperbolic cosine of the prediction error.

  `log(cosh(x))` is approximately equal to `(x ** 2) / 2` for small `x` and
  to `abs(x) - log(2)` for large `x`. This means that 'logcosh' works mostly
  like the mean squared error, but will not be so strongly affected by the
  occasional wildly incorrect prediction.

  Standalone usage:

  >>> y_true = np.random.random(size=(2, 3))
  >>> y_pred = np.random.random(size=(2, 3))
  >>> loss = tf.keras.losses.logcosh(y_true, y_pred)
  >>> assert loss.shape == (2,)
  >>> x = y_pred - y_true
  >>> assert np.allclose(
  ...     loss.numpy(),
  ...     np.mean(x + np.log(np.exp(-2. * x) + 1.) - math_ops.log(2.), axis=-1),
  ...     atol=1e-5)

  Args:
    y_true: Ground truth values. shape = `[batch_size, d0, .. dN]`.
    y_pred: The predicted values. shape = `[batch_size, d0, .. dN]`.

  Returns:
    Logcosh error values. shape = `[batch_size, d0, .. dN-1]`.
  c             S   s&   | t d|   t t d| j S )Ng       g       @)r   Zsoftplusrp   r   rq   )xr#   r#   r$   _logcosh[  s    zlog_cosh.<locals>._logcoshrV   )rZ   )r   ro   r   rp   rq   r   rr   )r1   r2   r   r#   r#   r$   rh   :  s    
rh   z&keras.metrics.categorical_crossentropyz%keras.losses.categorical_crossentropyrV   c                sb   t tjt j t d  fdd}t |fddtj||dS )a  Computes the categorical crossentropy loss.

  Standalone usage:

  >>> y_true = [[0, 1, 0], [0, 0, 1]]
  >>> y_pred = [[0.05, 0.95, 0], [0.1, 0.8, 0.1]]
  >>> loss = tf.keras.losses.categorical_crossentropy(y_true, y_pred)
  >>> assert loss.shape == (2,)
  >>> loss.numpy()
  array([0.0513, 2.303], dtype=float32)

  Args:
    y_true: Tensor of one-hot true targets.
    y_pred: Tensor of predicted targets.
    from_logits: Whether `y_pred` is expected to be a logits tensor. By default,
      we assume that `y_pred` encodes a probability distribution.
    label_smoothing: Float in [0, 1]. If > `0` then smooth the labels. For
      example, if `0.1`, use `0.1 / num_classes` for non-target labels
      and `0.9 + 0.1 / num_classes` for target labels.
    axis: Defaults to -1. The dimension along which the entropy is
      computed.

  Returns:
    Categorical crossentropy loss value.
  )rq   c                 s,   t td j} d    |   S )NrV   g      ?)r   rp   r   r   rq   )Znum_classes)rY   r2   r1   r#   r$   _smooth_labels  s    z0categorical_crossentropy.<locals>._smooth_labelsc                  s    S )Nr#   r#   )r1   r#   r$   r     r   z*categorical_crossentropy.<locals>.<lambda>)rX   rZ   )	r   ro   r   rp   rq   r   ru   r   r\   )r1   r2   rX   rY   rZ   r   r#   )rY   r2   r1   r$   r\   b  s    !
r\   c             C   s   t jt|||d}t|| |S )aW  Implements support for handling RaggedTensors.

  Args:
    y_true: Tensor of one-hot true targets.
    y_pred: Tensor of predicted targets.
    from_logits: Whether `y_pred` is expected to be a logits tensor. By default,
      we assume that `y_pred` encodes a probability distribution.
    label_smoothing: Float in [0, 1]. If > `0` then smooth the labels. For
      example, if `0.1`, use `0.1 / num_classes` for non-target labels
      and `0.9 + 0.1 / num_classes` for target labels.
    axis: The axis along which to compute crossentropy (the features axis).
        Defaults to -1.

  Returns:
    Categorical crossentropy loss value.

  Expected shape: (batch, sequence_len, n_classes) with sequence_len
  being variable per batch.
  Return shape: (batch, sequence_len).

  When used by CategoricalCrossentropy() with the default reduction
  (SUM_OVER_BATCH_SIZE), the reduction averages the loss over the
  number of elements independent of the batch. E.g. if the RaggedTensor
  has 2 batches with [2, 1] values respectivly the resulting loss is
  the sum of the individual loss values divided by 3.
  )rX   rY   rZ   )r   r   r\   r   )r1   r2   rX   rY   rZ   rC   r#   r#   r$   '_ragged_tensor_categorical_crossentropy  s    !r   z-keras.metrics.sparse_categorical_crossentropyz,keras.losses.sparse_categorical_crossentropyc             C   s*   t |}t| |j} tj| |||dS )a  Computes the sparse categorical crossentropy loss.

  Standalone usage:

  >>> y_true = [1, 2]
  >>> y_pred = [[0.05, 0.95, 0], [0.1, 0.8, 0.1]]
  >>> loss = tf.keras.losses.sparse_categorical_crossentropy(y_true, y_pred)
  >>> assert loss.shape == (2,)
  >>> loss.numpy()
  array([0.0513, 2.303], dtype=float32)

  Args:
    y_true: Ground truth values.
    y_pred: The predicted values.
    from_logits: Whether `y_pred` is expected to be a logits tensor. By default,
      we assume that `y_pred` encodes a probability distribution.
    axis: Defaults to -1. The dimension along which the entropy is
      computed.

  Returns:
    Sparse categorical crossentropy loss value.
  )rX   rZ   )r   ro   r   rp   rq   r   r^   )r1   r2   rX   rZ   r#   r#   r$   r^     s    
r^   c             C   s    t jt||d}t|| |ddS )a4   Implements support for handling RaggedTensors.

      Expected y_pred shape: (batch, sequence_len, n_classes) with sequence_len
      being variable per batch.
      Return shape: (batch, sequence_len).

      When used by SparseCategoricalCrossentropy() with the default reduction
      (SUM_OVER_BATCH_SIZE), the reduction averages the loss over the
      number of elements independent of the batch. E.g. if the RaggedTensor
      has 2 batches with [2, 1] values respectively, the resulting loss is
      the sum of the individual loss values divided by 3.
  )rX   rZ   T)r   )r   r   r^   r   )r1   r2   rX   rZ   rC   r#   r#   r$   ._ragged_tensor_sparse_categorical_crossentropy  s    r   z!keras.metrics.binary_crossentropyz keras.losses.binary_crossentropyc                sh   t |}t|jt j t d  fdd}t |fddtjtj	||d|dS )a  Computes the binary crossentropy loss.

  Standalone usage:

  >>> y_true = [[0, 1], [0, 0]]
  >>> y_pred = [[0.6, 0.4], [0.4, 0.6]]
  >>> loss = tf.keras.losses.binary_crossentropy(y_true, y_pred)
  >>> assert loss.shape == (2,)
  >>> loss.numpy()
  array([0.916 , 0.714], dtype=float32)

  Args:
    y_true: Ground truth values. shape = `[batch_size, d0, .. dN]`.
    y_pred: The predicted values. shape = `[batch_size, d0, .. dN]`.
    from_logits: Whether `y_pred` is expected to be a logits tensor. By default,
      we assume that `y_pred` encodes a probability distribution.
    label_smoothing: Float in [0, 1]. If > `0` then smooth the labels by
      squeezing them towards 0.5 That is, using `1. - 0.5 * label_smoothing`
      for the target class and `0.5 * label_smoothing` for the non-target class.
    axis: The axis along which the mean is computed. Defaults to -1.

  Returns:
    Binary crossentropy loss value. shape = `[batch_size, d0, .. dN-1]`.
  )rq   c                  s   d   d   S )Ng      ?g      ?r#   r#   )rY   r1   r#   r$   r     s    z+binary_crossentropy.<locals>._smooth_labelsc                  s    S )Nr#   r#   )r1   r#   r$   r     r   z%binary_crossentropy.<locals>.<lambda>)rX   )rZ   )
r   ro   r   rp   rq   r   ru   r   rr   rW   )r1   r2   rX   rY   rZ   r   r#   )rY   r1   r$   rW     s     
rW   c             C   s   t jt|||d}t|| |S )a  Implements support for handling RaggedTensors.

  Args:
    y_true: Tensor of one-hot true targets.
    y_pred: Tensor of predicted targets.
    from_logits: Whether `y_pred` is expected to be a logits tensor. By default,
      we assume that `y_pred` encodes a probability distribution.
    label_smoothing: Float in [0, 1]. If > `0` then smooth the labels. For
      example, if `0.1`, use `0.1 / num_classes` for non-target labels
      and `0.9 + 0.1 / num_classes` for target labels.
    axis: Axis along which to compute crossentropy.

  Returns:
    Binary crossentropy loss value.

  Expected shape: (batch, sequence_len) with sequence_len being variable
  per batch.
  Return shape: (batch,); returns the per batch mean of the loss values.

  When used by BinaryCrossentropy() with the default reduction
  (SUM_OVER_BATCH_SIZE), the reduction averages the per batch losses over
  the number of batches.
  )rX   rY   rZ   )r   r   rW   r   )r1   r2   rX   rY   rZ   rC   r#   r#   r$   "_ragged_tensor_binary_crossentropy#  s    r   zkeras.metrics.kl_divergencez)keras.metrics.kullback_leibler_divergencezkeras.metrics.kldzkeras.metrics.KLDzkeras.losses.kl_divergencez(keras.losses.kullback_leibler_divergencezkeras.losses.kldzkeras.losses.KLDc             C   sX   t |}t| |j} t| t d} t|t d}tj| t	| |  ddS )aN  Computes Kullback-Leibler divergence loss between `y_true` and `y_pred`.

  `loss = y_true * log(y_true / y_pred)`

  See: https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence

  Standalone usage:

  >>> y_true = np.random.randint(0, 2, size=(2, 3)).astype(np.float64)
  >>> y_pred = np.random.random(size=(2, 3))
  >>> loss = tf.keras.losses.kullback_leibler_divergence(y_true, y_pred)
  >>> assert loss.shape == (2,)
  >>> y_true = tf.keras.backend.clip(y_true, 1e-7, 1)
  >>> y_pred = tf.keras.backend.clip(y_pred, 1e-7, 1)
  >>> assert np.array_equal(
  ...     loss.numpy(), np.sum(y_true * np.log(y_true / y_pred), axis=-1))

  Args:
    y_true: Tensor of true targets.
    y_pred: Tensor of predicted targets.

  Returns:
    A `Tensor` with loss.

  Raises:
    TypeError: If `y_true` cannot be cast to the `y_pred.dtype`.
  r   rV   )rZ   )
r   ro   r   rp   rq   r   Zclipr   r   r   )r1   r2   r#   r#   r$   rj   H  s
    "
rj   zkeras.metrics.poissonzkeras.losses.poissonc             C   s<   t |}t| |j} tj|| t|t    ddS )a2  Computes the Poisson loss between y_true and y_pred.

  The Poisson loss is the mean of the elements of the `Tensor`
  `y_pred - y_true * log(y_pred)`.

  Standalone usage:

  >>> y_true = np.random.randint(0, 2, size=(2, 3))
  >>> y_pred = np.random.random(size=(2, 3))
  >>> loss = tf.keras.losses.poisson(y_true, y_pred)
  >>> assert loss.shape == (2,)
  >>> y_pred = y_pred + 1e-7
  >>> assert np.allclose(
  ...     loss.numpy(), np.mean(y_pred - y_true * np.log(y_pred), axis=-1),
  ...     atol=1e-5)

  Args:
    y_true: Ground truth values. shape = `[batch_size, d0, .. dN]`.
    y_pred: The predicted values. shape = `[batch_size, d0, .. dN]`.

  Returns:
     Poisson loss value. shape = `[batch_size, d0, .. dN-1]`.

  Raises:
    InvalidArgumentError: If `y_true` and `y_pred` have incompatible shapes.
  rV   )rZ   )	r   ro   r   rp   rq   r   rr   r   r   )r1   r2   r#   r#   r$   rf   q  s    
rf   zkeras.losses.cosine_similarityzkeras.metrics.cosine_proximityzkeras.metrics.cosinezkeras.losses.cosine_proximityzkeras.losses.cosinec             C   s0   t j| |d} t j||d}tj| | |d S )a  Computes the cosine similarity between labels and predictions.

  Note that it is a number between -1 and 1. When it is a negative number
  between -1 and 0, 0 indicates orthogonality and values closer to -1
  indicate greater similarity. The values closer to 1 indicate greater
  dissimilarity. This makes it usable as a loss function in a setting
  where you try to maximize the proximity between predictions and
  targets. If either `y_true` or `y_pred` is a zero vector, cosine
  similarity will be 0 regardless of the proximity between predictions
  and targets.

  `loss = -sum(l2_norm(y_true) * l2_norm(y_pred))`

  Standalone usage:

  >>> y_true = [[0., 1.], [1., 1.], [1., 1.]]
  >>> y_pred = [[1., 0.], [1., 1.], [-1., -1.]]
  >>> loss = tf.keras.losses.cosine_similarity(y_true, y_pred, axis=1)
  >>> loss.numpy()
  array([-0., -0.999, 0.999], dtype=float32)

  Args:
    y_true: Tensor of true targets.
    y_pred: Tensor of predicted targets.
    axis: Axis along which to determine similarity.

  Returns:
    Cosine similarity tensor.
  )rZ   )r   Zl2_normalizer   r   )r1   r2   rZ   r#   r#   r$   cosine_similarity  s    (r   zkeras.losses.CosineSimilarityc                   s,   e Zd ZdZdejjdf fdd	Z  ZS )CosineSimilaritya8
  Computes the cosine similarity between labels and predictions.

  Note that it is a number between -1 and 1. When it is a negative number
  between -1 and 0, 0 indicates orthogonality and values closer to -1
  indicate greater similarity. The values closer to 1 indicate greater
  dissimilarity. This makes it usable as a loss function in a setting
  where you try to maximize the proximity between predictions and targets.
  If either `y_true` or `y_pred` is a zero vector, cosine similarity will be 0
  regardless of the proximity between predictions and targets.

  `loss = -sum(l2_norm(y_true) * l2_norm(y_pred))`

  Standalone usage:

  >>> y_true = [[0., 1.], [1., 1.]]
  >>> y_pred = [[1., 0.], [1., 1.]]
  >>> # Using 'auto'/'sum_over_batch_size' reduction type.
  >>> cosine_loss = tf.keras.losses.CosineSimilarity(axis=1)
  >>> # l2_norm(y_true) = [[0., 1.], [1./1.414, 1./1.414]]
  >>> # l2_norm(y_pred) = [[1., 0.], [1./1.414, 1./1.414]]
  >>> # l2_norm(y_true) . l2_norm(y_pred) = [[0., 0.], [0.5, 0.5]]
  >>> # loss = mean(sum(l2_norm(y_true) . l2_norm(y_pred), axis=1))
  >>> #       = -((0. + 0.) +  (0.5 + 0.5)) / 2
  >>> cosine_loss(y_true, y_pred).numpy()
  -0.5

  >>> # Calling with 'sample_weight'.
  >>> cosine_loss(y_true, y_pred, sample_weight=[0.8, 0.2]).numpy()
  -0.0999

  >>> # Using 'sum' reduction type.
  >>> cosine_loss = tf.keras.losses.CosineSimilarity(axis=1,
  ...     reduction=tf.keras.losses.Reduction.SUM)
  >>> cosine_loss(y_true, y_pred).numpy()
  -0.999

  >>> # Using 'none' reduction type.
  >>> cosine_loss = tf.keras.losses.CosineSimilarity(axis=1,
  ...     reduction=tf.keras.losses.Reduction.NONE)
  >>> cosine_loss(y_true, y_pred).numpy()
  array([-0., -0.999], dtype=float32)

  Usage with the `compile()` API:

  ```python
  model.compile(optimizer='sgd', loss=tf.keras.losses.CosineSimilarity(axis=1))
  ```

  Args:
    axis: The axis along which the cosine similarity is computed
      (the features axis). Defaults to -1.
    reduction: Type of `tf.keras.losses.Reduction` to apply to loss.
      Default value is `AUTO`. `AUTO` indicates that the reduction option will
      be determined by the usage context. For almost all cases this defaults to
      `SUM_OVER_BATCH_SIZE`. When used with `tf.distribute.Strategy`, outside of
      built-in training loops such as `tf.keras` `compile` and `fit`, using
      `AUTO` or `SUM_OVER_BATCH_SIZE` will raise an error. Please see this
      custom training [tutorial]
      (https://www.tensorflow.org/tutorials/distribute/custom_training) for more
        details.
    name: Optional name for the instance.
  rV   r   c                s   t  jt|||d d S )N)r   r   rZ   )rB   r%   r   )r"   rZ   r   r   )r(   r#   r$   r%     s    zCosineSimilarity.__init__)	r)   r;   r<   r=   r   r   r9   r%   rL   r#   r#   )r(   r$   r     s   ?r   c             C   s>   t | tp8t | tr| jtkp8t| dr2| jdkp8| dk}|S )Nr)   r\   )r{   r[   rA   rC   r\   hasattrr)   )lossresultr#   r#   r$   is_categorical_crossentropy  s    




r   zkeras.losses.serializec             C   s   t | S )zSerializes loss function or `Loss` instance.

  Args:
    loss: A Keras `Loss` instance or a loss function.

  Returns:
    Loss configuration dictionary.
  )r   )r   r#   r#   r$   	serialize   s    
r   zkeras.losses.deserializec             C   s   t | t |ddS )a>  Deserializes a serialized loss class/function instance.

  Args:
      name: Loss configuration.
      custom_objects: Optional dictionary mapping names (strings) to custom
        objects (classes and functions) to be considered during deserialization.

  Returns:
      A Keras `Loss` instance or a loss function.
  zloss function)Zmodule_objectscustom_objectsZprintable_module_name)r   globals)r   r   r#   r#   r$   deserialize-  s
    r   zkeras.losses.getc             C   sV   | dkrdS t | tr&t| } t| S t | tr8t| S t| rD| S td|  dS )a^  Retrieves a Keras loss as a `function`/`Loss` class instance.

  The `identifier` may be the string name of a loss function or `Loss` class.

  >>> loss = tf.keras.losses.get("categorical_crossentropy")
  >>> type(loss)
  <class 'function'>
  >>> loss = tf.keras.losses.get("CategoricalCrossentropy")
  >>> type(loss)
  <class '...keras.losses.CategoricalCrossentropy'>

  You can also specify `config` of the loss to this function by passing dict
  containing `class_name` and `config` as an identifier. Also note that the
  `class_name` must map to a `Loss` class

  >>> identifier = {"class_name": "CategoricalCrossentropy",
  ...               "config": {"from_logits": True}}
  >>> loss = tf.keras.losses.get(identifier)
  >>> type(loss)
  <class '...keras.losses.CategoricalCrossentropy'>

  Args:
    identifier: A loss identifier. One of None or string name of a loss
      function/class or loss configuration dictionary or a loss function or a
      loss class instance.

  Returns:
    A Keras loss as a `function`/ `Loss` class instance.

  Raises:
    ValueError: If `identifier` cannot be interpreted.
  Nz.Could not interpret loss function identifier: )r{   strr   rH   callabler:   )
identifierr#   r#   r$   get@  s    "

r   Zint32)F)r   )Fr   rV   )Fr   rV   )FrV   )FrV   )Fr   rV   )Fr   rV   )rV   )N)lr=   r?   r   Z tensorflow.python.autograph.corer   Z tensorflow.python.autograph.implr   r-   Ztensorflow.python.distributer   Ztensorflow.python.eagerr   Ztensorflow.python.frameworkr   r   r   r	   r
   Ztensorflow.python.kerasr   Ztensorflow.python.keras.utilsr   r   Z+tensorflow.python.keras.utils.generic_utilsr   r   Ztensorflow.python.opsr   r   r   r   Ztensorflow.python.ops.lossesr   Ztensorflow.python.ops.raggedr   r   r   Ztensorflow.python.utilr   Z tensorflow.python.util.tf_exportr   Ztensorflow.tools.docsr   r   rA   rM   rO   rQ   rS   rU   r[   r]   r_   ra   rc   re   rg   ri   rk   Zadd_dispatch_supportrN   r   Zdispatch_for_typesr|   r   rP   r   rR   r   rT   r   r   rb   r`   rd   rn   rh   r\   r   r^   r   rW   r   rj   rf   r   r   ZbceZBCEZmseZMSEZmaeZMAEZmapeZMAPEZmsleZMSLEZkldZKLDZkullback_leibler_divergenceZlogcoshrl   r   r   r   r   Zsparse_softmax_cross_entropyZLABEL_DTYPES_FOR_LOSSESr#   r#   r#   r$   <module>   s>   )599<<fRK:<:78;B
Q " "
 &  *  #   )   $"#J
0