B
    ӻd)                @   sj  d Z ddlZddl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( 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-m0Z0 dd"l1m2Z2 dd#l1m3Z3 dd$l1m4Z4 dd%l5m6Z6 dd&l7m8Z8 dd'l7m9Z9 dd(l7m:Z: dd)l7m;Z; dd*l7m<Z< dd+l7m=Z= dd,l7m>Z? dd-l7m@Z@ dd.lAmBZB dd/lAmCZC dd0lDmEZE dd1lFmGZG eEd2G d3d4 d4ejHejId5ZJG d6d7 d7eJZKeEd8G d9d: d:eKZLeEd;G d<d= d=eKZMeEd>G d?d@ d@eMZNeEdAG dBdC dCeMZOeEdDG dEdF dFeOZPeEdGG dHdI dIeOZQeEdJG dKdL dLeOZReEdMG dNdO dOeOZSeEdPG dQdR dReOZTeEdSG dTdU dUeOZUG dVdW dWeJZVeEdXG dYdZ dZeVZWeEd[G d\d] d]eVZXeEd^G d_d` d`eVZYeEdaG dbdc dceVZZeEddG dedf dfeJZ[eEdgG dhdi dieJZ\G djdk dkeJejId5Z]eEdlG dmdn dne]Z^eEdoG dpdq dqe]Z_eEdrG dsdt dte]Z`eEduG dvdw dwe]ZaeEdxG dydz dzeJZbeEd{G d|d} d}eOZceEd~G dd deOZdeEdG dd deOZeeEdG dd deOZfeEdG dd deOZgeEdG dd deOZheEdG dd deOZieEdG dd deOZjeEdG dd deMZkeEdG dd deOZleEdG dd deOZmeEdG dd deOZneEdG dd deJZoeEdG dd deJZpeEdG dd deOZqeEdG dd deOZreEdG dd deOZsG dd deKZtG dd detZudd ZveEdeBjwdddZxeEdeBjwdd ZyeEdeBjwdd ZzeEdeBjwdddZ{eEdeBjwdddĄZ|dddǄZ}ev Z~Ze ZZe& ZZe$ ZZe% ZZe' ZZe}Ze#ZddɄ Zdd˄ ZeEd̃dd΄ ZeEdσdddфZeEd҃ddԄ Zddք ZdS )zBuilt-in metrics.    N)ag_ctx)api)distribution_strategy_context)context)def_function)constant_op)dtypes)ops)tensor_shape)activations)backend)
base_layer)base_layer_utils)keras_tensor)binary_crossentropy)categorical_crossentropy)categorical_hinge)hinge)kullback_leibler_divergence)logcosh)mean_absolute_error)mean_absolute_percentage_error)mean_squared_error)mean_squared_logarithmic_error)poisson)sparse_categorical_crossentropy)squared_hinge)metric_serialization)generic_utils)losses_utils)metrics_utils)deserialize_keras_object)serialize_keras_object)to_list)is_tensor_or_variable)	array_ops)	check_ops)confusion_matrix)init_ops)math_ops)nn)	variables)weights_broadcast_ops)dispatch)nest)keras_export)doc_controlszkeras.metrics.Metricc                   s   e Zd ZdZd fdd	Z fddZdd Zed	d
 Zdd Z	dd Z
ejdd Zejdd Zejdejjejjddf fdd	Zedd Zedd Zedd Zejejdd Z  ZS )Metrica	  Encapsulates metric logic and state.

  Args:
    name: (Optional) string name of the metric instance.
    dtype: (Optional) data type of the metric result.
    **kwargs: Additional layer keywords arguments.

  Standalone usage:

  ```python
  m = SomeMetric(...)
  for input in ...:
    m.update_state(input)
  print('Final result: ', m.result().numpy())
  ```

  Usage with `compile()` API:

  ```python
  model = tf.keras.Sequential()
  model.add(tf.keras.layers.Dense(64, activation='relu'))
  model.add(tf.keras.layers.Dense(64, activation='relu'))
  model.add(tf.keras.layers.Dense(10, activation='softmax'))

  model.compile(optimizer=tf.keras.optimizers.RMSprop(0.01),
                loss=tf.keras.losses.CategoricalCrossentropy(),
                metrics=[tf.keras.metrics.CategoricalAccuracy()])

  data = np.random.random((1000, 32))
  labels = np.random.random((1000, 10))

  dataset = tf.data.Dataset.from_tensor_slices((data, labels))
  dataset = dataset.batch(32)

  model.fit(dataset, epochs=10)
  ```

  To be implemented by subclasses:
  * `__init__()`: All state variables should be created in this method by
    calling `self.add_weight()` like: `self.var = self.add_weight(...)`
  * `update_state()`: Has all updates to the state variables like:
    self.var.assign_add(...).
  * `result()`: Computes and returns a value for the metric
    from the state variables.

  Example subclass implementation:

  ```python
  class BinaryTruePositives(tf.keras.metrics.Metric):

    def __init__(self, name='binary_true_positives', **kwargs):
      super(BinaryTruePositives, self).__init__(name=name, **kwargs)
      self.true_positives = self.add_weight(name='tp', initializer='zeros')

    def update_state(self, y_true, y_pred, sample_weight=None):
      y_true = tf.cast(y_true, tf.bool)
      y_pred = tf.cast(y_pred, tf.bool)

      values = tf.logical_and(tf.equal(y_true, True), tf.equal(y_pred, True))
      values = tf.cast(values, self.dtype)
      if sample_weight is not None:
        sample_weight = tf.cast(sample_weight, self.dtype)
        sample_weight = tf.broadcast_to(sample_weight, values.shape)
        values = tf.multiply(values, sample_weight)
      self.true_positives.assign_add(tf.reduce_sum(values))

    def result(self):
      return self.true_positives
  ```
  Nc                sR   t t| jf ||d| d| _d| _t sN|d kr@t n
t	
|j| _d S )N)namedtypeT)superr1   __init__ZstatefulZbuiltr   Zv2_dtype_behavior_enabledr   floatxr   Zas_dtyper2   _dtype)selfr2   r3   kwargs)	__class__ Q/var/www/html/venv/lib/python3.7/site-packages/tensorflow/python/keras/metrics.pyr5      s    zMetric.__init__c                s   t t| | }t s t| r4|jfdd}n"t|jtj	rJ|j}nt
|j}tt|||_|j  fdd}tt|||_|S )Nc                 s   t  }t |}|| |S )N)r   control_status_ctx	autograph
tf_convert)argsr9   control_statusZag_update_state)obj_update_stater;   r<   update_state_fn   s    z'Metric.__new__.<locals>.update_state_fnc                 s   t  }t |}|| |S )N)r   r=   r>   r?   )r@   r9   rA   Z	ag_result)
obj_resultr;   r<   	result_fn   s    z!Metric.__new__.<locals>.result_fn)r4   r1   __new__r   Zis_in_eager_or_tf_functionis_built_inupdate_state
isinstancer   Functionfunctiontypes
MethodTyper    Zupdate_state_wrapperresultZresult_wrapper)clsr@   r9   objrC   rE   )r:   )rD   rB   r<   rF      s    zMetric.__new__c                s*    fdd}ddl m} |j|f||S )zAccumulates statistics and then computes metric result value.

    Args:
      *args:
      **kwargs: A mini-batch of inputs to the Metric,
        passed on to `update_state()`.

    Returns:
      The metric value tensor.
    c           	      sl   t dd t| |fD r"d}n j| |}g }|dk	rD|| t|   } |_|S Q R X dS )z;Updates the state of the metric in a replica-local context.c             s   s   | ]}t |tjV  qd S )N)rI   r   ZKerasTensor).0argr;   r;   r<   	<genexpr>   s   z<Metric.__call__.<locals>.replica_local_fn.<locals>.<genexpr>N)	anyr.   flattenrH   appendr	   control_dependenciesrN   Z_metric_obj)r@   r9   Z	update_opZ
update_opsZresult_t)r8   r;   r<   replica_local_fn   s    

z)Metric.__call__.<locals>.replica_local_fnr   )distributed_training_utils)Z"tensorflow.python.keras.distributerY   Zcall_replica_local_fn)r8   r@   r9   rX   rY   r;   )r8   r<   __call__   s    zMetric.__call__c             C   s   | j S )N)r7   )r8   r;   r;   r<   r3      s    zMetric.dtypec             C   s   | j | jdS )z.Returns the serializable config of the metric.)r2   r3   )r2   r3   )r8   r;   r;   r<   
get_config   s    zMetric.get_configc             C   sB   t | js(td| jjf  |  S tdd | j	D  dS )zResets all of the metric state variables.

    This function is called between epochs/steps,
    when a metric is evaluated during training.
    zMetric %s implements a `reset_states()` method; rename it to `reset_state()` (without the final "s"). The name `reset_states()` has been deprecated to improve API consistency.c             S   s   g | ]}|d fqS )r   r;   )rQ   vr;   r;   r<   
<listcomp>   s    z&Metric.reset_state.<locals>.<listcomp>N)
r   
is_defaultreset_stateswarningswarnr:   __name__r   batch_set_valuer+   )r8   r;   r;   r<   reset_state   s
    zMetric.reset_statec             O   s   t ddS )a  Accumulates statistics for the metric.

    Note: This function is executed as a graph function in graph mode.
    This means:
      a) Operations on the same resource are executed in textual order.
         This should make it easier to do things like add the updated
         value of a variable to another, for example.
      b) You don't need to worry about collecting the update ops to execute.
         All update ops added to the graph by this function will be executed.
      As a result, code should generally work the same way with graph or
      eager execution.

    Args:
      *args:
      **kwargs: A mini-batch of inputs to the Metric.
    z"Must be implemented in subclasses.N)NotImplementedError)r8   r@   r9   r;   r;   r<   rH      s    zMetric.update_statec             C   s   t ddS )zComputes and returns the metric value tensor.

    Result computation is an idempotent operation that simply calculates the
    metric value using the state variables.
    z"Must be implemented in subclasses.N)re   )r8   r;   r;   r<   rN     s    zMetric.resultr;   c                sj   t  rt  }nd}t|r(tjj}t	 0 t
t| j|||dkrN| jn|d|g ||dS Q R X dS )z0Adds state variable. Only for use by subclasses.NF)r2   shaper3   	trainableinitializercollectionssynchronizationaggregation)distribute_ctxZhas_strategyZget_strategyr   Zis_tpu_strategyvariables_moduleVariableSynchronizationZON_WRITEr	   
init_scoper4   r1   
add_weightr7   )r8   r2   rf   rk   rj   rh   r3   Zstrategy)r:   r;   r<   rp     s    




zMetric.add_weightc             C   s8   | j r0| j}x| jD ]}||j7 }qW | |S g S d S )N)rg   _trainable_weights_metricstrainable_weights_dedup_weights)r8   rs   mr;   r;   r<   rs   >  s    
zMetric.trainable_weightsc             C   sX   | j r(| j}x@| jD ]}||j7 }qW n&| j| j }x| jD ]}||j7 }q<W | |S )N)rg   Z_non_trainable_weightsrr   non_trainable_weightsrq   weightsrt   )r8   rv   ru   r;   r;   r<   rv   I  s    zMetric.non_trainable_weightsc             C   s
   t | S )N)r   ZMetricSavedModelSaver)r8   r;   r;   r<   _trackable_saved_model_saverW  s    z#Metric._trackable_saved_model_saverc             C   s   |   S )N)rd   )r8   r;   r;   r<   r_   [  s    zMetric.reset_states)NN)rb   
__module____qualname____doc__r5   rF   rZ   propertyr3   r[   rd   abcabstractmethodrH   rN   r0   Zfor_subclass_implementersrm   ZVariableAggregationSUMrn   ZON_READrp   rs   rv   rx   r   defaultZdo_not_generate_docsr_   __classcell__r;   r;   )r:   r<   r1   J   s(   G
#)
r1   )	metaclassc                   s4   e Zd ZdZd	 fdd	Zd
ddZdd Z  ZS )ReducezEncapsulates metrics that perform a reduce operation on the values.

  Args:
    reduction: a `tf.keras.metrics.Reduction` enum value.
    name: string name of the metric instance.
    dtype: (Optional) data type of the metric result.
  Nc                sV   t t| j||d || _| jdtjd| _|tj	j
tj	jgkrR| jdtjd| _d S )N)r2   r3   total)rh   count)r4   r   r5   	reductionrp   r(   zeros_initializerr   r    	ReductionSUM_OVER_BATCH_SIZEWEIGHTED_MEANr   )r8   r   r2   r3   )r:   r;   r<   r5   l  s    zReduce.__init__c       
   	   C   s  t |g|\\}}yt|| j}W n< ttfk
rb   d|f }t|trV|d7 }t	|Y nX |dk	rt|| j}t
j||d\}}}yt||}W nj tk
r
   t|}t|}| jt jjkrtj|tt||d}ntj|tt||d}Y nX t||}t|}t|g | j|}W dQ R X | jt jjkrZ|S | jt jjkrtt|| j}	nJ| jt jjkr|dkrtt|| j}	n
t|}	nt d| j t|g | j!|	S Q R X dS )zAccumulates statistics for computing the metric.

    Args:
      values: Per-example value.
      sample_weight: Optional weighting of each example. Defaults to 1.

    Returns:
      Update op.
    zDThe output of a metric function can only be a single Tensor. Got: %szA. To return a dict of values, implement a custom Metric subclass.N)sample_weight)axiszreduction [%s] not implemented)"r    ,ragged_assert_compatible_and_get_flat_valuesr)   castr7   
ValueError	TypeErrorrI   dictRuntimeErrorr   squeeze_or_expand_dimensionsr,   broadcast_weightsr   ndimr   r   r   
reduce_sumlistrangereduce_meanmultiplyr	   rW   r   
assign_addr   r%   sizer   re   r   )
r8   valuesr   msg_r   weight_ndimZ	value_sumupdate_total_op
num_valuesr;   r;   r<   rH   v  sR    





zReduce.update_statec             C   sR   | j tjjkrt| jS | j tjjtjjgkr@t	
| j| jS td| j  d S )Nzreduction [%s] not implemented)r   r    r   r   r%   identityr   r   r   r)   
div_no_nanr   re   )r8   r;   r;   r<   rN     s    zReduce.result)N)N)rb   ry   rz   r{   r5   rH   rN   r   r;   r;   )r:   r<   r   c  s   

Br   zkeras.metrics.Sumc                   s"   e Zd ZdZd fdd	Z  ZS )Suma1  Computes the (weighted) sum of the given values.

  For example, if values is [1, 3, 5, 7] then the sum is 16.
  If the weights were specified as [1, 1, 0, 0] then the sum would be 4.

  This metric creates one variable, `total`, that is used to compute the sum of
  `values`. This is ultimately returned as `sum`.

  If `sample_weight` is `None`, weights default to 1.  Use `sample_weight` of 0
  to mask values.

  Args:
    name: (Optional) string name of the metric instance.
    dtype: (Optional) data type of the metric result.

  Standalone usage:

  >>> m = tf.keras.metrics.Sum()
  >>> m.update_state([1, 3, 5, 7])
  >>> m.result().numpy()
  16.0

  Usage with `compile()` API:

  ```python
  model.add_metric(tf.keras.metrics.Sum(name='sum_1')(outputs))
  model.compile(optimizer='sgd', loss='mse')
  ```
  sumNc                s   t t| jtjj||d d S )N)r   r2   r3   )r4   r   r5   r    r   r   )r8   r2   r3   )r:   r;   r<   r5     s    zSum.__init__)r   N)rb   ry   rz   r{   r5   r   r;   r;   )r:   r<   r     s   r   zkeras.metrics.Meanc                   s"   e Zd ZdZd fdd	Z  ZS )Meana  Computes the (weighted) mean of the given values.

  For example, if values is [1, 3, 5, 7] then the mean is 4.
  If the weights were specified as [1, 1, 0, 0] then the mean would be 2.

  This metric creates two variables, `total` and `count` that are used to
  compute the average of `values`. This average is ultimately returned as `mean`
  which is an idempotent operation that simply divides `total` by `count`.

  If `sample_weight` is `None`, weights default to 1.
  Use `sample_weight` of 0 to mask values.

  Args:
    name: (Optional) string name of the metric instance.
    dtype: (Optional) data type of the metric result.

  Standalone usage:

  >>> m = tf.keras.metrics.Mean()
  >>> m.update_state([1, 3, 5, 7])
  >>> m.result().numpy()
  4.0
  >>> m.reset_state()
  >>> m.update_state([1, 3, 5, 7], sample_weight=[1, 1, 0, 0])
  >>> m.result().numpy()
  2.0

  Usage with `compile()` API:

  ```python
  model.add_metric(tf.keras.metrics.Mean(name='mean_1')(outputs))
  model.compile(optimizer='sgd', loss='mse')
  ```
  meanNc                s   t t| jtjj||d d S )N)r   r2   r3   )r4   r   r5   r    r   r   )r8   r2   r3   )r:   r;   r<   r5     s    
zMean.__init__)r   N)rb   ry   rz   r{   r5   r   r;   r;   )r:   r<   r     s   #r   zkeras.metrics.MeanRelativeErrorc                   s<   e Zd ZdZd	 fdd	Zd
 fdd	Z fddZ  ZS )MeanRelativeErroraw  Computes the mean relative error by normalizing with the given values.

  This metric creates two local variables, `total` and `count` that are used to
  compute the mean relative error. This is weighted by `sample_weight`, and
  it is ultimately returned as `mean_relative_error`:
  an idempotent operation that simply divides `total` by `count`.

  If `sample_weight` is `None`, weights default to 1.
  Use `sample_weight` of 0 to mask values.

  Args:
    normalizer: The normalizer values with same shape as predictions.
    name: (Optional) string name of the metric instance.
    dtype: (Optional) data type of the metric result.

  Standalone usage:

  >>> m = tf.keras.metrics.MeanRelativeError(normalizer=[1, 3, 2, 3])
  >>> m.update_state([1, 3, 2, 3], [2, 4, 6, 8])

  >>> # metric = mean(|y_pred - y_true| / normalizer)
  >>> #        = mean([1, 1, 4, 5] / [1, 3, 2, 3]) = mean([1, 1/3, 2, 5/3])
  >>> #        = 5/4 = 1.25
  >>> m.result().numpy()
  1.25

  Usage with `compile()` API:

  ```python
  model.compile(
    optimizer='sgd',
    loss='mse',
    metrics=[tf.keras.metrics.MeanRelativeError(normalizer=[1, 3])])
  ```
  Nc                s,   t t| j||d t|| j}|| _d S )N)r2   r3   )r4   r   r5   r)   r   r7   
normalizer)r8   r   r2   r3   )r:   r;   r<   r5   :  s    zMeanRelativeError.__init__c                s   t || j}t || j}t||g|\\}}}t||\}}t|| j\}| _|j	
|j	 t t || | j}tt| j||dS )a_  Accumulates metric statistics.

    Args:
      y_true: The ground truth values.
      y_pred: The predicted values.
      sample_weight: Optional weighting of each example. Defaults to 1. Can be a
        `Tensor` whose rank is either 0, or the same rank as `y_true`, and must
        be broadcastable to `y_true`.

    Returns:
      Update op.
    )r   )r)   r   r7   r    r   r   r   Zremove_squeezable_dimensionsr   rf   assert_is_compatible_withr   absr4   r   rH   )r8   y_truey_predr   Zrelative_errors)r:   r;   r<   rH   ?  s    
zMeanRelativeError.update_statec                sJ   | j }dt|rt|n|i}tt|  }tt|	 t|	  S )Nr   )
r   r$   r   evalr4   r   r[   r   r   items)r8   nconfigbase_config)r:   r;   r<   r[   ]  s    zMeanRelativeError.get_config)NN)N)rb   ry   rz   r{   r5   rH   r[   r   r;   r;   )r:   r<   r     s   $r   zkeras.metrics.MeanMetricWrapperc                   sL   e Zd ZdZd fdd	Zd fdd	Z fddZe fd	d
Z  Z	S )MeanMetricWrapperaQ  Wraps a stateless metric function with the Mean metric.

  You could use this class to quickly build a mean metric from a function. The
  function needs to have the signature `fn(y_true, y_pred)` and return a
  per-sample loss array. `MeanMetricWrapper.result()` will return
  the average metric value across all samples seen so far.

  For example:

  ```python
  def accuracy(y_true, y_pred):
    return tf.cast(tf.math.equal(y_true, y_pred), tf.float32)

  accuracy_metric = tf.keras.metrics.MeanMetricWrapper(fn=accuracy)

  keras_model.compile(..., metrics=accuracy_metric)
  ```

  Args:
    fn: The metric function to wrap, with signature `fn(y_true, y_pred,
      **kwargs)`.
    name: (Optional) string name of the metric instance.
    dtype: (Optional) data type of the metric result.
    **kwargs: Keyword arguments to pass on to `fn`.
  Nc                s$   t t| j||d || _|| _d S )N)r2   r3   )r4   r   r5   _fn
_fn_kwargs)r8   fnr2   r3   r9   )r:   r;   r<   r5     s    zMeanMetricWrapper.__init__c                sz   t || j}t || j}t||g|\\}}}t||\}}t| j	t
 }|||f| j}tt| j||dS )a  Accumulates metric statistics.

    `y_true` and `y_pred` should have the same shape.

    Args:
      y_true: Ground truth values. shape = `[batch_size, d0, .. dN]`.
      y_pred: The predicted values. shape = `[batch_size, d0, .. dN]`.
      sample_weight: Optional `sample_weight` acts as a
        coefficient for the metric. If a scalar is provided, then the metric is
        simply scaled by the given value. If `sample_weight` is a tensor of size
        `[batch_size]`, then the metric 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 metric element of `y_pred` is scaled by the
        corresponding value of `sample_weight`. (Note on `dN-1`: all metric
        functions reduce by 1 dimension, usually the last axis (-1)).

    Returns:
      Update op.
    )r   )r)   r   r7   r    r   r   r   r>   r?   r   r   r=   r   r4   r   rH   )r8   r   r   r   ag_fnmatches)r:   r;   r<   rH     s    
zMeanMetricWrapper.update_statec                sv   i }t | tkr| j|d< x0| j D ]"\}}t|r@t|n|||< q&W tt| 	 }t
t| t|  S )Nr   )typer   r   r   r   r$   r   r   r4   r[   r   r   )r8   r   kr\   r   )r:   r;   r<   r[     s    
zMeanMetricWrapper.get_configc                s4   | dd }| tkr$| t|f|S tt| |S )Nr   )popr   getr4   from_config)rO   r   r   )r:   r;   r<   r     s    zMeanMetricWrapper.from_config)NN)N)
rb   ry   rz   r{   r5   rH   r[   classmethodr   r   r;   r;   )r:   r<   r   d  s
   "r   zkeras.metrics.Accuracyc                   s"   e Zd ZdZd fdd	Z  ZS )Accuracya  Calculates how often predictions equal labels.

  This metric creates two local variables, `total` and `count` that are used to
  compute the frequency with which `y_pred` matches `y_true`. This frequency is
  ultimately returned as `binary accuracy`: an idempotent operation that simply
  divides `total` by `count`.

  If `sample_weight` is `None`, weights default to 1.
  Use `sample_weight` of 0 to mask values.

  Args:
    name: (Optional) string name of the metric instance.
    dtype: (Optional) data type of the metric result.

  Standalone usage:

  >>> m = tf.keras.metrics.Accuracy()
  >>> m.update_state([[1], [2], [3], [4]], [[0], [2], [3], [4]])
  >>> m.result().numpy()
  0.75

  >>> m.reset_state()
  >>> m.update_state([[1], [2], [3], [4]], [[0], [2], [3], [4]],
  ...                sample_weight=[1, 1, 0, 0])
  >>> m.result().numpy()
  0.5

  Usage with `compile()` API:

  ```python
  model.compile(optimizer='sgd',
                loss='mse',
                metrics=[tf.keras.metrics.Accuracy()])
  ```
  accuracyNc                s   t t| jt||d d S )N)r3   )r4   r   r5   r   )r8   r2   r3   )r:   r;   r<   r5     s    zAccuracy.__init__)r   N)rb   ry   rz   r{   r5   r   r;   r;   )r:   r<   r     s   $r   zkeras.metrics.BinaryAccuracyc                   s"   e Zd ZdZd fdd	Z  ZS )BinaryAccuracya  Calculates how often predictions match binary labels.

  This metric creates two local variables, `total` and `count` that are used to
  compute the frequency with which `y_pred` matches `y_true`. This frequency is
  ultimately returned as `binary accuracy`: an idempotent operation that simply
  divides `total` by `count`.

  If `sample_weight` is `None`, weights default to 1.
  Use `sample_weight` of 0 to mask values.

  Args:
    name: (Optional) string name of the metric instance.
    dtype: (Optional) data type of the metric result.
    threshold: (Optional) Float representing the threshold for deciding
    whether prediction values are 1 or 0.

  Standalone usage:

  >>> m = tf.keras.metrics.BinaryAccuracy()
  >>> m.update_state([[1], [1], [0], [0]], [[0.98], [1], [0], [0.6]])
  >>> m.result().numpy()
  0.75

  >>> m.reset_state()
  >>> m.update_state([[1], [1], [0], [0]], [[0.98], [1], [0], [0.6]],
  ...                sample_weight=[1, 0, 0, 1])
  >>> m.result().numpy()
  0.5

  Usage with `compile()` API:

  ```python
  model.compile(optimizer='sgd',
                loss='mse',
                metrics=[tf.keras.metrics.BinaryAccuracy()])
  ```
  binary_accuracyN      ?c                s   t t| jt|||d d S )N)r3   	threshold)r4   r   r5   r   )r8   r2   r3   r   )r:   r;   r<   r5     s    
zBinaryAccuracy.__init__)r   Nr   )rb   ry   rz   r{   r5   r   r;   r;   )r:   r<   r     s   &r   z!keras.metrics.CategoricalAccuracyc                   s"   e Zd ZdZd fdd	Z  ZS )CategoricalAccuracyag  Calculates how often predictions match one-hot labels.

  You can provide logits of classes as `y_pred`, since argmax of
  logits and probabilities are same.

  This metric creates two local variables, `total` and `count` that are used to
  compute the frequency with which `y_pred` matches `y_true`. This frequency is
  ultimately returned as `categorical accuracy`: an idempotent operation that
  simply divides `total` by `count`.

  `y_pred` and `y_true` should be passed in as vectors of probabilities, rather
  than as labels. If necessary, use `tf.one_hot` to expand `y_true` as a vector.

  If `sample_weight` is `None`, weights default to 1.
  Use `sample_weight` of 0 to mask values.

  Args:
    name: (Optional) string name of the metric instance.
    dtype: (Optional) data type of the metric result.

  Standalone usage:

  >>> m = tf.keras.metrics.CategoricalAccuracy()
  >>> m.update_state([[0, 0, 1], [0, 1, 0]], [[0.1, 0.9, 0.8],
  ...                 [0.05, 0.95, 0]])
  >>> m.result().numpy()
  0.5

  >>> m.reset_state()
  >>> m.update_state([[0, 0, 1], [0, 1, 0]], [[0.1, 0.9, 0.8],
  ...                 [0.05, 0.95, 0]],
  ...                sample_weight=[0.7, 0.3])
  >>> m.result().numpy()
  0.3

  Usage with `compile()` API:

  ```python
  model.compile(
    optimizer='sgd',
    loss='mse',
    metrics=[tf.keras.metrics.CategoricalAccuracy()])
  ```
  categorical_accuracyNc                s   t t| jt||d d S )N)r3   )r4   r   r5   r   )r8   r2   r3   )r:   r;   r<   r5   D  s    
zCategoricalAccuracy.__init__)r   N)rb   ry   rz   r{   r5   r   r;   r;   )r:   r<   r     s   -r   z'keras.metrics.SparseCategoricalAccuracyc                   s"   e Zd ZdZd fdd	Z  ZS )SparseCategoricalAccuracya  Calculates how often predictions match integer labels.

  ```python
  acc = np.dot(sample_weight, np.equal(y_true, np.argmax(y_pred, axis=1))
  ```

  You can provide logits of classes as `y_pred`, since argmax of
  logits and probabilities are same.

  This metric creates two local variables, `total` and `count` that are used to
  compute the frequency with which `y_pred` matches `y_true`. This frequency is
  ultimately returned as `sparse categorical accuracy`: an idempotent operation
  that simply divides `total` by `count`.

  If `sample_weight` is `None`, weights default to 1.
  Use `sample_weight` of 0 to mask values.

  Args:
    name: (Optional) string name of the metric instance.
    dtype: (Optional) data type of the metric result.

  Standalone usage:

  >>> m = tf.keras.metrics.SparseCategoricalAccuracy()
  >>> m.update_state([[2], [1]], [[0.1, 0.6, 0.3], [0.05, 0.95, 0]])
  >>> m.result().numpy()
  0.5

  >>> m.reset_state()
  >>> m.update_state([[2], [1]], [[0.1, 0.6, 0.3], [0.05, 0.95, 0]],
  ...                sample_weight=[0.7, 0.3])
  >>> m.result().numpy()
  0.3

  Usage with `compile()` API:

  ```python
  model.compile(
      optimizer='sgd',
      loss='mse',
      metrics=[tf.keras.metrics.SparseCategoricalAccuracy()])
  ```
  sparse_categorical_accuracyNc                s   t t| jt||d d S )N)r3   )r4   r   r5   r   )r8   r2   r3   )r:   r;   r<   r5   w  s    
z"SparseCategoricalAccuracy.__init__)r   N)rb   ry   rz   r{   r5   r   r;   r;   )r:   r<   r   I  s   ,r   z%keras.metrics.TopKCategoricalAccuracyc                   s"   e Zd ZdZd fdd	Z  ZS )TopKCategoricalAccuracyai  Computes how often targets are in the top `K` predictions.

  Args:
    k: (Optional) Number of top elements to look at for computing accuracy.
      Defaults to 5.
    name: (Optional) string name of the metric instance.
    dtype: (Optional) data type of the metric result.

  Standalone usage:

  >>> m = tf.keras.metrics.TopKCategoricalAccuracy(k=1)
  >>> m.update_state([[0, 0, 1], [0, 1, 0]],
  ...                [[0.1, 0.9, 0.8], [0.05, 0.95, 0]])
  >>> m.result().numpy()
  0.5

  >>> m.reset_state()
  >>> m.update_state([[0, 0, 1], [0, 1, 0]],
  ...                [[0.1, 0.9, 0.8], [0.05, 0.95, 0]],
  ...                sample_weight=[0.7, 0.3])
  >>> m.result().numpy()
  0.3

  Usage with `compile()` API:

  ```python
  model.compile(optimizer='sgd',
                loss='mse',
                metrics=[tf.keras.metrics.TopKCategoricalAccuracy()])
  ```
     top_k_categorical_accuracyNc                s   t t| jt|||d d S )N)r3   r   )r4   r   r5   r   )r8   r   r2   r3   )r:   r;   r<   r5     s    
z TopKCategoricalAccuracy.__init__)r   r   N)rb   ry   rz   r{   r5   r   r;   r;   )r:   r<   r   |  s    r   z+keras.metrics.SparseTopKCategoricalAccuracyc                   s"   e Zd ZdZd fdd	Z  ZS )SparseTopKCategoricalAccuracya   Computes how often integer targets are in the top `K` predictions.

  Args:
    k: (Optional) Number of top elements to look at for computing accuracy.
      Defaults to 5.
    name: (Optional) string name of the metric instance.
    dtype: (Optional) data type of the metric result.

  Standalone usage:

  >>> m = tf.keras.metrics.SparseTopKCategoricalAccuracy(k=1)
  >>> m.update_state([2, 1], [[0.1, 0.9, 0.8], [0.05, 0.95, 0]])
  >>> m.result().numpy()
  0.5

  >>> m.reset_state()
  >>> m.update_state([2, 1], [[0.1, 0.9, 0.8], [0.05, 0.95, 0]],
  ...                sample_weight=[0.7, 0.3])
  >>> m.result().numpy()
  0.3

  Usage with `compile()` API:

  ```python
  model.compile(
    optimizer='sgd',
    loss='mse',
    metrics=[tf.keras.metrics.SparseTopKCategoricalAccuracy()])
  ```
  r   !sparse_top_k_categorical_accuracyNc                s   t t| jt|||d d S )N)r3   r   )r4   r   r5   r   )r8   r   r2   r3   )r:   r;   r<   r5     s    
z&SparseTopKCategoricalAccuracy.__init__)r   r   N)rb   ry   rz   r{   r5   r   r;   r;   )r:   r<   r     s   r   c                   sH   e Zd ZdZd fdd	ZdddZdd Zd	d
 Z fddZ  Z	S )_ConfusionMatrixConditionCountaa  Calculates the number of the given confusion matrix condition.

  Args:
    confusion_matrix_cond: One of `metrics_utils.ConfusionMatrix` conditions.
    thresholds: (Optional) Defaults to 0.5. A float value or a python list/tuple
      of float threshold values in [0, 1]. A threshold is compared with
      prediction values to determine the truth value of predictions (i.e., above
      the threshold is `true`, below is `false`). One metric value is generated
      for each threshold value.
    name: (Optional) string name of the metric instance.
    dtype: (Optional) data type of the metric result.
  Nc                s^   t t| j||d || _|| _tj|dd| _t| j| _	| j
dt| jftjd| _d S )N)r2   r3   g      ?)default_thresholdaccumulator)rf   rh   )r4   r   r5   _confusion_matrix_condinit_thresholdsr    parse_init_thresholds
thresholds is_evenly_distributed_thresholds_thresholds_distributed_evenlyrp   lenr(   r   r   )r8   confusion_matrix_condr   r2   r3   )r:   r;   r<   r5     s    
z'_ConfusionMatrixConditionCount.__init__c             C   s"   t j| j| ji||| j| j|dS )ac  Accumulates the metric statistics.

    Args:
      y_true: The ground truth values.
      y_pred: The predicted values.
      sample_weight: Optional weighting of each example. Defaults to 1. Can be a
        `Tensor` whose rank is either 0, or the same rank as `y_true`, and must
        be broadcastable to `y_true`.

    Returns:
      Update op.
    )r   thresholds_distributed_evenlyr   )r    !update_confusion_matrix_variablesr   r   r   r   )r8   r   r   r   r;   r;   r<   rH     s    
z+_ConfusionMatrixConditionCount.update_statec             C   s*   t | jdkr| jd }n| j}t|S )N   r   )r   r   r   r	   "convert_to_tensor_v2_with_dispatch)r8   rN   r;   r;   r<   rN     s    z%_ConfusionMatrixConditionCount.resultc                s,   t t| j t fdd| jD  d S )Nc                s   g | ]}|t  ffqS r;   )npzeros)rQ   r\   )num_thresholdsr;   r<   r]     s    z>_ConfusionMatrixConditionCount.reset_state.<locals>.<listcomp>)r   r#   r   r   rc   r+   )r8   r;   )r   r<   rd     s    z*_ConfusionMatrixConditionCount.reset_statec                s4   d| j i}tt|  }tt| t|  S )Nr   )r   r4   r   r[   r   r   r   )r8   r   r   )r:   r;   r<   r[   	  s    
z)_ConfusionMatrixConditionCount.get_config)NNN)N)
rb   ry   rz   r{   r5   rH   rN   rd   r[   r   r;   r;   )r:   r<   r     s     
r   zkeras.metrics.FalsePositivesc                   s"   e Zd ZdZd fdd	Z  ZS )FalsePositivesa  Calculates the number of false positives.

  If `sample_weight` is given, calculates the sum of the weights of
  false positives. This metric creates one local variable, `accumulator`
  that is used to keep track of the number of false positives.

  If `sample_weight` is `None`, weights default to 1.
  Use `sample_weight` of 0 to mask values.

  Args:
    thresholds: (Optional) Defaults to 0.5. A float value or a python
      list/tuple of float threshold values in [0, 1]. A threshold is compared
      with prediction values to determine the truth value of predictions
      (i.e., above the threshold is `true`, below is `false`). One metric
      value is generated for each threshold value.
    name: (Optional) string name of the metric instance.
    dtype: (Optional) data type of the metric result.

  Standalone usage:

  >>> m = tf.keras.metrics.FalsePositives()
  >>> m.update_state([0, 1, 0, 0], [0, 0, 1, 1])
  >>> m.result().numpy()
  2.0

  >>> m.reset_state()
  >>> m.update_state([0, 1, 0, 0], [0, 0, 1, 1], sample_weight=[0, 0, 1, 0])
  >>> m.result().numpy()
  1.0

  Usage with `compile()` API:

  ```python
  model.compile(optimizer='sgd',
                loss='mse',
                metrics=[tf.keras.metrics.FalsePositives()])
  ```
  Nc                s    t t| jtjj|||d d S )N)r   r   r2   r3   )r4   r   r5   r    ConfusionMatrixFALSE_POSITIVES)r8   r   r2   r3   )r:   r;   r<   r5   8  s
    
zFalsePositives.__init__)NNN)rb   ry   rz   r{   r5   r   r;   r;   )r:   r<   r     s   'r   zkeras.metrics.FalseNegativesc                   s"   e Zd ZdZd fdd	Z  ZS )FalseNegativesa  Calculates the number of false negatives.

  If `sample_weight` is given, calculates the sum of the weights of
  false negatives. This metric creates one local variable, `accumulator`
  that is used to keep track of the number of false negatives.

  If `sample_weight` is `None`, weights default to 1.
  Use `sample_weight` of 0 to mask values.

  Args:
    thresholds: (Optional) Defaults to 0.5. A float value or a python
      list/tuple of float threshold values in [0, 1]. A threshold is compared
      with prediction values to determine the truth value of predictions
      (i.e., above the threshold is `true`, below is `false`). One metric
      value is generated for each threshold value.
    name: (Optional) string name of the metric instance.
    dtype: (Optional) data type of the metric result.

  Standalone usage:

  >>> m = tf.keras.metrics.FalseNegatives()
  >>> m.update_state([0, 1, 1, 1], [0, 1, 0, 0])
  >>> m.result().numpy()
  2.0

  >>> m.reset_state()
  >>> m.update_state([0, 1, 1, 1], [0, 1, 0, 0], sample_weight=[0, 0, 1, 0])
  >>> m.result().numpy()
  1.0

  Usage with `compile()` API:

  ```python
  model.compile(optimizer='sgd',
                loss='mse',
                metrics=[tf.keras.metrics.FalseNegatives()])
  ```
  Nc                s    t t| jtjj|||d d S )N)r   r   r2   r3   )r4   r   r5   r    r   FALSE_NEGATIVES)r8   r   r2   r3   )r:   r;   r<   r5   i  s
    
zFalseNegatives.__init__)NNN)rb   ry   rz   r{   r5   r   r;   r;   )r:   r<   r   @  s   'r   zkeras.metrics.TrueNegativesc                   s"   e Zd ZdZd fdd	Z  ZS )TrueNegativesa  Calculates the number of true negatives.

  If `sample_weight` is given, calculates the sum of the weights of
  true negatives. This metric creates one local variable, `accumulator`
  that is used to keep track of the number of true negatives.

  If `sample_weight` is `None`, weights default to 1.
  Use `sample_weight` of 0 to mask values.

  Args:
    thresholds: (Optional) Defaults to 0.5. A float value or a python
      list/tuple of float threshold values in [0, 1]. A threshold is compared
      with prediction values to determine the truth value of predictions
      (i.e., above the threshold is `true`, below is `false`). One metric
      value is generated for each threshold value.
    name: (Optional) string name of the metric instance.
    dtype: (Optional) data type of the metric result.

  Standalone usage:

  >>> m = tf.keras.metrics.TrueNegatives()
  >>> m.update_state([0, 1, 0, 0], [1, 1, 0, 0])
  >>> m.result().numpy()
  2.0

  >>> m.reset_state()
  >>> m.update_state([0, 1, 0, 0], [1, 1, 0, 0], sample_weight=[0, 0, 1, 0])
  >>> m.result().numpy()
  1.0

  Usage with `compile()` API:

  ```python
  model.compile(optimizer='sgd',
                loss='mse',
                metrics=[tf.keras.metrics.TrueNegatives()])
  ```
  Nc                s    t t| jtjj|||d d S )N)r   r   r2   r3   )r4   r   r5   r    r   TRUE_NEGATIVES)r8   r   r2   r3   )r:   r;   r<   r5     s
    
zTrueNegatives.__init__)NNN)rb   ry   rz   r{   r5   r   r;   r;   )r:   r<   r   q  s   'r   zkeras.metrics.TruePositivesc                   s"   e Zd ZdZd fdd	Z  ZS )TruePositivesa  Calculates the number of true positives.

  If `sample_weight` is given, calculates the sum of the weights of
  true positives. This metric creates one local variable, `true_positives`
  that is used to keep track of the number of true positives.

  If `sample_weight` is `None`, weights default to 1.
  Use `sample_weight` of 0 to mask values.

  Args:
    thresholds: (Optional) Defaults to 0.5. A float value or a python
      list/tuple of float threshold values in [0, 1]. A threshold is compared
      with prediction values to determine the truth value of predictions
      (i.e., above the threshold is `true`, below is `false`). One metric
      value is generated for each threshold value.
    name: (Optional) string name of the metric instance.
    dtype: (Optional) data type of the metric result.

  Standalone usage:

  >>> m = tf.keras.metrics.TruePositives()
  >>> m.update_state([0, 1, 1, 1], [1, 0, 1, 1])
  >>> m.result().numpy()
  2.0

  >>> m.reset_state()
  >>> m.update_state([0, 1, 1, 1], [1, 0, 1, 1], sample_weight=[0, 0, 1, 0])
  >>> m.result().numpy()
  1.0

  Usage with `compile()` API:

  ```python
  model.compile(optimizer='sgd',
                loss='mse',
                metrics=[tf.keras.metrics.TruePositives()])
  ```
  Nc                s    t t| jtjj|||d d S )N)r   r   r2   r3   )r4   r   r5   r    r   TRUE_POSITIVES)r8   r   r2   r3   )r:   r;   r<   r5     s
    
zTruePositives.__init__)NNN)rb   ry   rz   r{   r5   r   r;   r;   )r:   r<   r     s   'r   zkeras.metrics.Precisionc                   sH   e Zd ZdZd fdd	ZdddZdd Zd	d
 Z fddZ  Z	S )	Precisiona
  Computes the precision of the predictions with respect to the labels.

  The metric creates two local variables, `true_positives` and `false_positives`
  that are used to compute the precision. This value is ultimately returned as
  `precision`, an idempotent operation that simply divides `true_positives`
  by the sum of `true_positives` and `false_positives`.

  If `sample_weight` is `None`, weights default to 1.
  Use `sample_weight` of 0 to mask values.

  If `top_k` is set, we'll calculate precision as how often on average a class
  among the top-k classes with the highest predicted values of a batch entry is
  correct and can be found in the label for that entry.

  If `class_id` is specified, we calculate precision by considering only the
  entries in the batch for which `class_id` is above the threshold and/or in the
  top-k highest predictions, and computing the fraction of them for which
  `class_id` is indeed a correct label.

  Args:
    thresholds: (Optional) A float value or a python list/tuple of float
      threshold values in [0, 1]. A threshold is compared with prediction
      values to determine the truth value of predictions (i.e., above the
      threshold is `true`, below is `false`). One metric value is generated
      for each threshold value. If neither thresholds nor top_k are set, the
      default is to calculate precision with `thresholds=0.5`.
    top_k: (Optional) Unset by default. An int value specifying the top-k
      predictions to consider when calculating precision.
    class_id: (Optional) Integer class ID for which we want binary metrics.
      This must be in the half-open interval `[0, num_classes)`, where
      `num_classes` is the last dimension of predictions.
    name: (Optional) string name of the metric instance.
    dtype: (Optional) data type of the metric result.

  Standalone usage:

  >>> m = tf.keras.metrics.Precision()
  >>> m.update_state([0, 1, 1, 1], [1, 0, 1, 1])
  >>> m.result().numpy()
  0.6666667

  >>> m.reset_state()
  >>> m.update_state([0, 1, 1, 1], [1, 0, 1, 1], sample_weight=[0, 0, 1, 0])
  >>> m.result().numpy()
  1.0

  >>> # With top_k=2, it will calculate precision over y_true[:2] and y_pred[:2]
  >>> m = tf.keras.metrics.Precision(top_k=2)
  >>> m.update_state([0, 0, 1, 1], [1, 1, 1, 1])
  >>> m.result().numpy()
  0.0

  >>> # With top_k=4, it will calculate precision over y_true[:4] and y_pred[:4]
  >>> m = tf.keras.metrics.Precision(top_k=4)
  >>> m.update_state([0, 0, 1, 1], [1, 1, 1, 1])
  >>> m.result().numpy()
  0.5

  Usage with `compile()` API:

  ```python
  model.compile(optimizer='sgd',
                loss='mse',
                metrics=[tf.keras.metrics.Precision()])
  ```
  Nc                s   t t| j||d || _|| _|| _|d kr2dntj}tj||d| _	t
| j	| _| jdt| j	ftjd| _| jdt| j	ftjd| _d S )N)r2   r3   g      ?)r   true_positives)rf   rh   false_positives)r4   r   r5   r   top_kclass_idr    NEG_INFr   r   r   r   rp   r   r(   r   r   r   )r8   r   r   r   r2   r3   r   )r:   r;   r<   r5     s     

zPrecision.__init__c          
   C   s6   t jt jj| jt jj| ji||| j| j| j	| j
|dS )a  Accumulates true positive and false positive statistics.

    Args:
      y_true: The ground truth values, with the same dimensions as `y_pred`.
        Will be cast to `bool`.
      y_pred: The predicted values. Each element must be in the range `[0, 1]`.
      sample_weight: Optional weighting of each example. Defaults to 1. Can be a
        `Tensor` whose rank is either 0, or the same rank as `y_true`, and must
        be broadcastable to `y_true`.

    Returns:
      Update op.
    )r   r   r   r   r   )r    r   r   r   r   r   r   r   r   r   r   )r8   r   r   r   r;   r;   r<   rH   1  s    
zPrecision.update_statec             C   s0   t | j| j| j }t| jdkr,|d S |S )Nr   r   )r)   r   r   r   r   r   )r8   rN   r;   r;   r<   rN   L  s    zPrecision.resultc                s2   t t| j t fdd| j| jfD  d S )Nc                s   g | ]}|t  ffqS r;   )r   r   )rQ   r\   )r   r;   r<   r]   S  s   z)Precision.reset_state.<locals>.<listcomp>)r   r#   r   r   rc   r   r   )r8   r;   )r   r<   rd   Q  s    zPrecision.reset_statec                s<   | j | j| jd}tt|  }tt| t|  S )N)r   r   r   )	r   r   r   r4   r   r[   r   r   r   )r8   r   r   )r:   r;   r<   r[   W  s
    
zPrecision.get_config)NNNNN)N)
rb   ry   rz   r{   r5   rH   rN   rd   r[   r   r;   r;   )r:   r<   r     s   C    
r   zkeras.metrics.Recallc                   sH   e Zd ZdZd fdd	ZdddZdd Zd	d
 Z fddZ  Z	S )Recalla  Computes the recall of the predictions with respect to the labels.

  This metric creates two local variables, `true_positives` and
  `false_negatives`, that are used to compute the recall. This value is
  ultimately returned as `recall`, an idempotent operation that simply divides
  `true_positives` by the sum of `true_positives` and `false_negatives`.

  If `sample_weight` is `None`, weights default to 1.
  Use `sample_weight` of 0 to mask values.

  If `top_k` is set, recall will be computed as how often on average a class
  among the labels of a batch entry is in the top-k predictions.

  If `class_id` is specified, we calculate recall by considering only the
  entries in the batch for which `class_id` is in the label, and computing the
  fraction of them for which `class_id` is above the threshold and/or in the
  top-k predictions.

  Args:
    thresholds: (Optional) A float value or a python list/tuple of float
      threshold values in [0, 1]. A threshold is compared with prediction
      values to determine the truth value of predictions (i.e., above the
      threshold is `true`, below is `false`). One metric value is generated
      for each threshold value. If neither thresholds nor top_k are set, the
      default is to calculate recall with `thresholds=0.5`.
    top_k: (Optional) Unset by default. An int value specifying the top-k
      predictions to consider when calculating recall.
    class_id: (Optional) Integer class ID for which we want binary metrics.
      This must be in the half-open interval `[0, num_classes)`, where
      `num_classes` is the last dimension of predictions.
    name: (Optional) string name of the metric instance.
    dtype: (Optional) data type of the metric result.

  Standalone usage:

  >>> m = tf.keras.metrics.Recall()
  >>> m.update_state([0, 1, 1, 1], [1, 0, 1, 1])
  >>> m.result().numpy()
  0.6666667

  >>> m.reset_state()
  >>> m.update_state([0, 1, 1, 1], [1, 0, 1, 1], sample_weight=[0, 0, 1, 0])
  >>> m.result().numpy()
  1.0

  Usage with `compile()` API:

  ```python
  model.compile(optimizer='sgd',
                loss='mse',
                metrics=[tf.keras.metrics.Recall()])
  ```
  Nc                s   t t| j||d || _|| _|| _|d kr2dntj}tj||d| _	t
| j	| _| jdt| j	ftjd| _| jdt| j	ftjd| _d S )N)r2   r3   g      ?)r   r   )rf   rh   false_negatives)r4   r   r5   r   r   r   r    r   r   r   r   r   rp   r   r(   r   r   r   )r8   r   r   r   r2   r3   r   )r:   r;   r<   r5     s     

zRecall.__init__c          
   C   s6   t jt jj| jt jj| ji||| j| j| j	| j
|dS )a  Accumulates true positive and false negative statistics.

    Args:
      y_true: The ground truth values, with the same dimensions as `y_pred`.
        Will be cast to `bool`.
      y_pred: The predicted values. Each element must be in the range `[0, 1]`.
      sample_weight: Optional weighting of each example. Defaults to 1. Can be a
        `Tensor` whose rank is either 0, or the same rank as `y_true`, and must
        be broadcastable to `y_true`.

    Returns:
      Update op.
    )r   r   r   r   r   )r    r   r   r   r   r   r   r   r   r   r   )r8   r   r   r   r;   r;   r<   rH     s    
zRecall.update_statec             C   s0   t | j| j| j }t| jdkr,|d S |S )Nr   r   )r)   r   r   r   r   r   )r8   rN   r;   r;   r<   rN     s    zRecall.resultc                s2   t t| j t fdd| j| jfD  d S )Nc                s   g | ]}|t  ffqS r;   )r   r   )rQ   r\   )r   r;   r<   r]     s   z&Recall.reset_state.<locals>.<listcomp>)r   r#   r   r   rc   r   r   )r8   r;   )r   r<   rd     s    zRecall.reset_statec                s<   | j | j| jd}tt|  }tt| t|  S )N)r   r   r   )	r   r   r   r4   r   r[   r   r   r   )r8   r   r   )r:   r;   r<   r[     s
    
zRecall.get_config)NNNNN)N)
rb   ry   rz   r{   r5   rH   rN   rd   r[   r   r;   r;   )r:   r<   r   a  s   6    
r   c                   sH   e Zd ZdZd fdd	ZdddZdd	 Z fd
dZdd Z  Z	S )SensitivitySpecificityBasezAbstract base class for computing sensitivity and specificity.

  For additional information about specificity and sensitivity, see
  [the following](https://en.wikipedia.org/wiki/Sensitivity_and_specificity).
     Nc                s   t t| j||d  dkr$td|| _|| _| jd ftjd| _	| jd ftjd| _
| jd ftjd| _| jd ftjd| _ d	krd
g| _d| _n2 fddt d D }dg| dg | _d| _d S )N)r2   r3   r   z`num_thresholds` must be > 0.r   )rf   rh   true_negativesr   r   r   g      ?Fc                s    g | ]}|d  d  d   qS )r   g      ?r;   )rQ   i)r   r;   r<   r]   
  s   z7SensitivitySpecificityBase.__init__.<locals>.<listcomp>   g        g      ?T)r4   r   r5   r   valuer   rp   r(   r   r   r   r   r   r   r   r   )r8   r   r   r   r2   r3   r   )r:   )r   r<   r5     s8    
z#SensitivitySpecificityBase.__init__c          	   C   sF   t jt jj| jt jj| jt jj| jt jj	| j
i||| j| j| j|dS )ai  Accumulates confusion matrix statistics.

    Args:
      y_true: The ground truth values.
      y_pred: The predicted values.
      sample_weight: Optional weighting of each example. Defaults to 1. Can be a
        `Tensor` whose rank is either 0, or the same rank as `y_true`, and must
        be broadcastable to `y_true`.

    Returns:
      Update op.
    )r   r   r   r   )r    r   r   r   r   r   r   r   r   r   r   r   r   r   )r8   r   r   r   r;   r;   r<   rH     s    


z'SensitivitySpecificityBase.update_statec                s:   t | j | j| j| j| jf}t fdd|D  d S )Nc                s   g | ]}|t  ffqS r;   )r   r   )rQ   r\   )r   r;   r<   r]   /  s    z:SensitivitySpecificityBase.reset_state.<locals>.<listcomp>)r   r   r   r   r   r   r   rc   )r8   confusion_matrix_variablesr;   )r   r<   rd   *  s
    
z&SensitivitySpecificityBase.reset_statec                s4   d| j i}tt|  }tt| t|  S )Nr   )r   r4   r   r[   r   r   r   )r8   r   r   )r:   r;   r<   r[   2  s    
z%SensitivitySpecificityBase.get_configc             C   sD   t ||| j}tt |d}tt ||}t ||dS )a  Returns the maximum of dependent_statistic that satisfies the constraint.

    Args:
      constrained: Over these values the constraint
        is specified. A rank-1 tensor.
      dependent: From these values the maximum that satiesfies the
        constraint is selected. Values in this tensor and in
        `constrained` are linked by having the same threshold at each
        position, hence this tensor must have the same shape.
      predicate: A binary boolean functor to be applied to arguments
      `constrained` and `self.value`, e.g. `tf.greater`.

    Returns maximal dependent value, if no value satiesfies the constraint 0.0.
    r   g        )r%   Zwhere_v2r   r)   Zgreaterr   Z
reduce_maxgather)r8   ZconstrainedZ	dependent	predicateZfeasibleZfeasible_existsZmax_dependentr;   r;   r<   _find_max_under_constraint7  s    z5SensitivitySpecificityBase._find_max_under_constraint)r   NNN)N)
rb   ry   rz   r{   r5   rH   rd   r[   r   r   r;   r;   )r:   r<   r     s      !
r   z&keras.metrics.SensitivityAtSpecificityc                   s6   e Zd ZdZd
 fdd	Zdd Z fdd	Z  ZS )SensitivityAtSpecificityam  Computes best sensitivity where specificity is >= specified value.

  the sensitivity at a given specificity.

  `Sensitivity` measures the proportion of actual positives that are correctly
  identified as such (tp / (tp + fn)).
  `Specificity` measures the proportion of actual negatives that are correctly
  identified as such (tn / (tn + fp)).

  This metric creates four local variables, `true_positives`, `true_negatives`,
  `false_positives` and `false_negatives` that are used to compute the
  sensitivity at the given specificity. The threshold for the given specificity
  value is computed and used to evaluate the corresponding sensitivity.

  If `sample_weight` is `None`, weights default to 1.
  Use `sample_weight` of 0 to mask values.

  If `class_id` is specified, we calculate precision by considering only the
  entries in the batch for which `class_id` is above the threshold predictions,
  and computing the fraction of them for which `class_id` is indeed a correct
  label.

  For additional information about specificity and sensitivity, see
  [the following](https://en.wikipedia.org/wiki/Sensitivity_and_specificity).

  Args:
    specificity: A scalar value in range `[0, 1]`.
    num_thresholds: (Optional) Defaults to 200. The number of thresholds to
      use for matching the given specificity.
    class_id: (Optional) Integer class ID for which we want binary metrics.
      This must be in the half-open interval `[0, num_classes)`, where
      `num_classes` is the last dimension of predictions.
    name: (Optional) string name of the metric instance.
    dtype: (Optional) data type of the metric result.

  Standalone usage:

  >>> m = tf.keras.metrics.SensitivityAtSpecificity(0.5)
  >>> m.update_state([0, 0, 0, 1, 1], [0, 0.3, 0.8, 0.3, 0.8])
  >>> m.result().numpy()
  0.5

  >>> m.reset_state()
  >>> m.update_state([0, 0, 0, 1, 1], [0, 0.3, 0.8, 0.3, 0.8],
  ...                sample_weight=[1, 1, 2, 2, 1])
  >>> m.result().numpy()
  0.333333

  Usage with `compile()` API:

  ```python
  model.compile(
      optimizer='sgd',
      loss='mse',
      metrics=[tf.keras.metrics.SensitivityAtSpecificity()])
  ```
  r   Nc                sB   |dk s|dkrt d|| _|| _tt| j|||||d d S )Nr   r   z*`specificity` must be in the range [0, 1].)r   r   r2   r3   )r   specificityr   r4   r   r5   )r8   r   r   r   r2   r3   )r:   r;   r<   r5     s    
z!SensitivityAtSpecificity.__init__c             C   s<   t | j| j| j }t | j| j| j }| ||t jS )N)r)   r   r   r   r   r   r   greater_equal)r8   specificitiessensitivitiesr;   r;   r<   rN     s    zSensitivityAtSpecificity.resultc                s8   | j | jd}tt|  }tt| t|  S )N)r   r   )r   r   r4   r   r[   r   r   r   )r8   r   r   )r:   r;   r<   r[     s    
z#SensitivityAtSpecificity.get_config)r   NNN)rb   ry   rz   r{   r5   rN   r[   r   r;   r;   )r:   r<   r   M  s   :   r   z&keras.metrics.SpecificityAtSensitivityc                   s6   e Zd ZdZd
 fdd	Zdd Z fdd	Z  ZS )SpecificityAtSensitivityaD  Computes best specificity where sensitivity is >= specified value.

  `Sensitivity` measures the proportion of actual positives that are correctly
  identified as such (tp / (tp + fn)).
  `Specificity` measures the proportion of actual negatives that are correctly
  identified as such (tn / (tn + fp)).

  This metric creates four local variables, `true_positives`, `true_negatives`,
  `false_positives` and `false_negatives` that are used to compute the
  specificity at the given sensitivity. The threshold for the given sensitivity
  value is computed and used to evaluate the corresponding specificity.

  If `sample_weight` is `None`, weights default to 1.
  Use `sample_weight` of 0 to mask values.

  If `class_id` is specified, we calculate precision by considering only the
  entries in the batch for which `class_id` is above the threshold predictions,
  and computing the fraction of them for which `class_id` is indeed a correct
  label.

  For additional information about specificity and sensitivity, see
  [the following](https://en.wikipedia.org/wiki/Sensitivity_and_specificity).

  Args:
    sensitivity: A scalar value in range `[0, 1]`.
    num_thresholds: (Optional) Defaults to 200. The number of thresholds to
      use for matching the given sensitivity.
    class_id: (Optional) Integer class ID for which we want binary metrics.
      This must be in the half-open interval `[0, num_classes)`, where
      `num_classes` is the last dimension of predictions.
    name: (Optional) string name of the metric instance.
    dtype: (Optional) data type of the metric result.

  Standalone usage:

  >>> m = tf.keras.metrics.SpecificityAtSensitivity(0.5)
  >>> m.update_state([0, 0, 0, 1, 1], [0, 0.3, 0.8, 0.3, 0.8])
  >>> m.result().numpy()
  0.66666667

  >>> m.reset_state()
  >>> m.update_state([0, 0, 0, 1, 1], [0, 0.3, 0.8, 0.3, 0.8],
  ...                sample_weight=[1, 1, 2, 2, 2])
  >>> m.result().numpy()
  0.5

  Usage with `compile()` API:

  ```python
  model.compile(
      optimizer='sgd',
      loss='mse',
      metrics=[tf.keras.metrics.SpecificityAtSensitivity()])
  ```
  r   Nc                sB   |dk s|dkrt d|| _|| _tt| j|||||d d S )Nr   r   z*`sensitivity` must be in the range [0, 1].)r   r   r2   r3   )r   sensitivityr   r4   r  r5   )r8   r  r   r   r2   r3   )r:   r;   r<   r5     s    
z!SpecificityAtSensitivity.__init__c             C   s<   t | j| j| j }t | j| j| j }| ||t jS )N)r)   r   r   r   r   r   r   r   )r8   r   r   r;   r;   r<   rN     s    zSpecificityAtSensitivity.resultc                s8   | j | jd}tt|  }tt| t|  S )N)r   r  )r   r  r4   r  r[   r   r   r   )r8   r   r   )r:   r;   r<   r[     s    
z#SpecificityAtSensitivity.get_config)r   NNN)rb   ry   rz   r{   r5   rN   r[   r   r;   r;   )r:   r<   r    s   8   r  zkeras.metrics.PrecisionAtRecallc                   s6   e Zd ZdZd
 fdd	Zdd Z fdd	Z  ZS )PrecisionAtRecalla  Computes best precision where recall is >= specified value.

  This metric creates four local variables, `true_positives`, `true_negatives`,
  `false_positives` and `false_negatives` that are used to compute the
  precision at the given recall. The threshold for the given recall
  value is computed and used to evaluate the corresponding precision.

  If `sample_weight` is `None`, weights default to 1.
  Use `sample_weight` of 0 to mask values.

  If `class_id` is specified, we calculate precision by considering only the
  entries in the batch for which `class_id` is above the threshold predictions,
  and computing the fraction of them for which `class_id` is indeed a correct
  label.

  Args:
    recall: A scalar value in range `[0, 1]`.
    num_thresholds: (Optional) Defaults to 200. The number of thresholds to
      use for matching the given recall.
    class_id: (Optional) Integer class ID for which we want binary metrics.
      This must be in the half-open interval `[0, num_classes)`, where
      `num_classes` is the last dimension of predictions.
    name: (Optional) string name of the metric instance.
    dtype: (Optional) data type of the metric result.

  Standalone usage:

  >>> m = tf.keras.metrics.PrecisionAtRecall(0.5)
  >>> m.update_state([0, 0, 0, 1, 1], [0, 0.3, 0.8, 0.3, 0.8])
  >>> m.result().numpy()
  0.5

  >>> m.reset_state()
  >>> m.update_state([0, 0, 0, 1, 1], [0, 0.3, 0.8, 0.3, 0.8],
  ...                sample_weight=[2, 2, 2, 1, 1])
  >>> m.result().numpy()
  0.33333333

  Usage with `compile()` API:

  ```python
  model.compile(
      optimizer='sgd',
      loss='mse',
      metrics=[tf.keras.metrics.PrecisionAtRecall(recall=0.8)])
  ```
  r   Nc                sB   |dk s|dkrt d|| _|| _tt| j|||||d d S )Nr   r   z%`recall` must be in the range [0, 1].)r   r   r   r2   r3   )r   recallr   r4   r  r5   )r8   r  r   r   r2   r3   )r:   r;   r<   r5   9  s    
zPrecisionAtRecall.__init__c             C   s<   t | j| j| j }t | j| j| j }| ||t jS )N)r)   r   r   r   r   r   r   )r8   recalls
precisionsr;   r;   r<   rN   J  s    zPrecisionAtRecall.resultc                s8   | j | jd}tt|  }tt| t|  S )N)r   r  )r   r  r4   r  r[   r   r   r   )r8   r   r   )r:   r;   r<   r[   R  s    zPrecisionAtRecall.get_config)r   NNN)rb   ry   rz   r{   r5   rN   r[   r   r;   r;   )r:   r<   r    s   0   r  zkeras.metrics.RecallAtPrecisionc                   s6   e Zd ZdZd
 fdd	Zdd Z fdd	Z  ZS )RecallAtPrecisiona  Computes best recall where precision is >= specified value.

  For a given score-label-distribution the required precision might not
  be achievable, in this case 0.0 is returned as recall.

  This metric creates four local variables, `true_positives`, `true_negatives`,
  `false_positives` and `false_negatives` that are used to compute the
  recall at the given precision. The threshold for the given precision
  value is computed and used to evaluate the corresponding recall.

  If `sample_weight` is `None`, weights default to 1.
  Use `sample_weight` of 0 to mask values.

  If `class_id` is specified, we calculate precision by considering only the
  entries in the batch for which `class_id` is above the threshold predictions,
  and computing the fraction of them for which `class_id` is indeed a correct
  label.

  Args:
    precision: A scalar value in range `[0, 1]`.
    num_thresholds: (Optional) Defaults to 200. The number of thresholds to
      use for matching the given precision.
    class_id: (Optional) Integer class ID for which we want binary metrics.
      This must be in the half-open interval `[0, num_classes)`, where
      `num_classes` is the last dimension of predictions.
    name: (Optional) string name of the metric instance.
    dtype: (Optional) data type of the metric result.

  Standalone usage:

  >>> m = tf.keras.metrics.RecallAtPrecision(0.8)
  >>> m.update_state([0, 0, 1, 1], [0, 0.5, 0.3, 0.9])
  >>> m.result().numpy()
  0.5

  >>> m.reset_state()
  >>> m.update_state([0, 0, 1, 1], [0, 0.5, 0.3, 0.9],
  ...                sample_weight=[1, 0, 0, 1])
  >>> m.result().numpy()
  1.0

  Usage with `compile()` API:

  ```python
  model.compile(
      optimizer='sgd',
      loss='mse',
      metrics=[tf.keras.metrics.RecallAtPrecision(precision=0.8)])
  ```
  r   Nc                sB   |dk s|dkrt d|| _|| _tt| j|||||d d S )Nr   r   z(`precision` must be in the range [0, 1].)r   r   r   r2   r3   )r   	precisionr   r4   r  r5   )r8   r  r   r   r2   r3   )r:   r;   r<   r5     s    
zRecallAtPrecision.__init__c             C   s<   t | j| j| j }t | j| j| j }| ||t jS )N)r)   r   r   r   r   r   r   )r8   r  r  r;   r;   r<   rN     s    zRecallAtPrecision.resultc                s8   | j | jd}tt|  }tt| t|  S )N)r   r  )r   r  r4   r  r[   r   r   r   )r8   r   r   )r:   r;   r<   r[     s    
zRecallAtPrecision.get_config)r   NNN)rb   ry   rz   r{   r5   rN   r[   r   r;   r;   )r:   r<   r  X  s   3   r  zkeras.metrics.AUCc            
       sd   e Zd ZdZd fdd	Zed	d
 Zdd ZdddZdd Z	dd Z
dd Z fddZ  ZS )AUCaH  Approximates the AUC (Area under the curve) of the ROC or PR curves.

  The AUC (Area under the curve) of the ROC (Receiver operating
  characteristic; default) or PR (Precision Recall) curves are quality measures
  of binary classifiers. Unlike the accuracy, and like cross-entropy
  losses, ROC-AUC and PR-AUC evaluate all the operational points of a model.

  This class approximates AUCs using a Riemann sum. During the metric
  accumulation phrase, predictions are accumulated within predefined buckets
  by value. The AUC is then computed by interpolating per-bucket averages. These
  buckets define the evaluated operational points.

  This metric creates four local variables, `true_positives`, `true_negatives`,
  `false_positives` and `false_negatives` that are used to compute the AUC.
  To discretize the AUC curve, a linearly spaced set of thresholds is used to
  compute pairs of recall and precision values. The area under the ROC-curve is
  therefore computed using the height of the recall values by the false positive
  rate, while the area under the PR-curve is the computed using the height of
  the precision values by the recall.

  This value is ultimately returned as `auc`, an idempotent operation that
  computes the area under a discretized curve of precision versus recall values
  (computed using the aforementioned variables). The `num_thresholds` variable
  controls the degree of discretization with larger numbers of thresholds more
  closely approximating the true AUC. The quality of the approximation may vary
  dramatically depending on `num_thresholds`. The `thresholds` parameter can be
  used to manually specify thresholds which split the predictions more evenly.

  For a best approximation of the real AUC, `predictions` should be distributed
  approximately uniformly in the range [0, 1] (if `from_logits=False`). The
  quality of the AUC approximation may be poor if this is not the case. Setting
  `summation_method` to 'minoring' or 'majoring' can help quantify the error in
  the approximation by providing lower or upper bound estimate of the AUC.

  If `sample_weight` is `None`, weights default to 1.
  Use `sample_weight` of 0 to mask values.

  Args:
    num_thresholds: (Optional) Defaults to 200. The number of thresholds to
      use when discretizing the roc curve. Values must be > 1.
    curve: (Optional) Specifies the name of the curve to be computed, 'ROC'
      [default] or 'PR' for the Precision-Recall-curve.
    summation_method: (Optional) Specifies the [Riemann summation method](
        https://en.wikipedia.org/wiki/Riemann_sum) used.
        'interpolation' (default) applies mid-point summation scheme for `ROC`.
        For PR-AUC, interpolates (true/false) positives but not the ratio that
        is precision (see Davis & Goadrich 2006 for details);
        'minoring' applies left summation
        for increasing intervals and right summation for decreasing intervals;
        'majoring' does the opposite.
    name: (Optional) string name of the metric instance.
    dtype: (Optional) data type of the metric result.
    thresholds: (Optional) A list of floating point values to use as the
      thresholds for discretizing the curve. If set, the `num_thresholds`
      parameter is ignored. Values should be in [0, 1]. Endpoint thresholds
      equal to {-epsilon, 1+epsilon} for a small positive epsilon value will
      be automatically included with these to correctly handle predictions
      equal to exactly 0 or 1.
    multi_label: boolean indicating whether multilabel data should be
      treated as such, wherein AUC is computed separately for each label and
      then averaged across labels, or (when False) if the data should be
      flattened into a single label before AUC computation. In the latter
      case, when multilabel data is passed to AUC, each label-prediction pair
      is treated as an individual data point. Should be set to False for
      multi-class data.
    num_labels: (Optional) The number of labels, used when `multi_label` is
      True. If `num_labels` is not specified, then state variables get created
      on the first call to `update_state`.
    label_weights: (Optional) list, array, or tensor of non-negative weights
      used to compute AUCs for multilabel data. When `multi_label` is True,
      the weights are applied to the individual label AUCs when they are
      averaged to produce the multi-label AUC. When it's False, they are used
      to weight the individual label predictions in computing the confusion
      matrix on the flattened data. Note that this is unlike class_weights in
      that class_weights weights the example depending on the value of its
      label, whereas label_weights depends only on the index of that label
      before flattening; therefore `label_weights` should not be used for
      multi-class data.
    from_logits: boolean indicating whether the predictions (`y_pred` in
      `update_state`) are probabilities or sigmoid logits. As a rule of thumb,
      when using a keras loss, the `from_logits` constructor argument of the
      loss should match the AUC `from_logits` constructor argument.

  Standalone usage:

  >>> m = tf.keras.metrics.AUC(num_thresholds=3)
  >>> m.update_state([0, 0, 1, 1], [0, 0.5, 0.3, 0.9])
  >>> # threshold values are [0 - 1e-7, 0.5, 1 + 1e-7]
  >>> # tp = [2, 1, 0], fp = [2, 0, 0], fn = [0, 1, 2], tn = [0, 2, 2]
  >>> # tp_rate = recall = [1, 0.5, 0], fp_rate = [1, 0, 0]
  >>> # auc = ((((1+0.5)/2)*(1-0)) + (((0.5+0)/2)*(0-0))) = 0.75
  >>> m.result().numpy()
  0.75

  >>> m.reset_state()
  >>> m.update_state([0, 0, 1, 1], [0, 0.5, 0.3, 0.9],
  ...                sample_weight=[1, 0, 0, 1])
  >>> m.result().numpy()
  1.0

  Usage with `compile()` API:

  ```python
  # Reports the AUC of a model outputing a probability.
  model.compile(optimizer='sgd',
                loss=tf.keras.losses.BinaryCrossentropy(),
                metrics=[tf.keras.metrics.AUC()])

  # Reports the AUC of a model outputing a logit.
  model.compile(optimizer='sgd',
                loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
                metrics=[tf.keras.metrics.AUC(from_logits=True)])
  ```
  r   ROCinterpolationNFc          	      s  t |tjr0|ttjkr0td|ttjt |tjr`|ttjkr`td|ttj|d k	rt|d | _t	|}t
tdg| dg | _n6 dkrtd | _ fdd	t d D }d
| _tdt  g| dt  g | _t |tjr|| _ntj|| _t |tjr6|| _ntj|| _tt| j||d || _|	d k	rtj|	| jd}	tj|	ddg}t| |	| _ W d Q R X nd | _ |
| _!d| _"| jr|rt#$d |g}| %| n|rtd| %d  d S )Nz,Invalid curve: "{}". Valid options are: "{}"z7Invalid summation method: "{}". Valid options are: "{}"r   g        g      ?r   z`num_thresholds` must be > 1.c                s    g | ]}|d  d  d   qS )r   g      ?r;   )rQ   r   )r   r;   r<   r]   I  s   z AUC.__init__.<locals>.<listcomp>T)r2   r3   )r3   z3All values of `label_weights` must be non-negative.)messageFz7`num_labels` is needed only when `multi_label` is True.)&rI   r    AUCCurver   r   formatAUCSummationMethodr   r   sortedr   r   arrayr   r   r   epsilon_thresholdscurveZfrom_strsummation_methodr4   r	  r5   multi_labelr   Zconstantr3   r&   Zassert_non_negativer	   rW   label_weights_from_logits_builtr
   TensorShape_build)r8   r   r  r  r2   r3   r   r  Z
num_labelsr  from_logitsZchecksrf   )r:   )r   r<   r5   "  sf    




zAUC.__init__c             C   s
   t | jS )z'The thresholds used for evaluating AUC.)r   r  )r8   r;   r;   r<   r   y  s    zAUC.thresholdsc          	   C   s   | j rB|jdkrtd|j |d | _tt| j| jg}ntt| jg}|| _| j	d|t
jd| _| j	d|t
jd| _| j	d|t
jd| _| j	d|t
jd| _| j rt  t stt  W d	Q R X d
| _d	S )zCInitialize TP, FP, TN, and FN tensors, given the shape of the data.r   zD`y_true` must have rank=2 when `multi_label` is True. Found rank %s.r   r   )rf   rh   r   r   r   NT)r  ndimsr   _num_labelsr
   r  Z	Dimensionr   _build_input_shaperp   r(   r   r   r   r   r   r	   ro   r   executing_eagerlyr   _initialize_variables_get_sessionr  )r8   rf   Zvariable_shaper;   r;   r<   r  ~  s>    



z
AUC._buildc             C   s  g }| j s| t|j | js,| jdk	r|dfg}| jrf|| jdf| j	df| j
df| jdfg | jdk	r|| jdf tj|ddg}| jrdn| j}| jrt|}t|J tjtjj| jtjj| j	tjj| j
tjj| ji||| j| j|| j|dS Q R X dS )ai  Accumulates confusion matrix statistics.

    Args:
      y_true: The ground truth values.
      y_pred: The predicted values.
      sample_weight: Optional weighting of each example. Defaults to 1. Can be a
        `Tensor` whose rank is either 0, or the same rank as `y_true`, and must
        be broadcastable to `y_true`.

    Returns:
      Update op.
    N)NL)Tr$  )r$  z#Number of labels is not consistent.)r  )r   r   r  r  )r  r  r
   r  rf   r  r  extendr   r   r   r   rV   r&   Zassert_shapesr  r   Zsigmoidr	   rW   r    r   r   r   r   r   r   r  r   )r8   r   r   r   depsZshapesr  r;   r;   r<   rH     sD    


zAUC.update_statec       	   
   C   s  | j d| jd  | j dd  }| j | j }|d| jd  |dd  }tj|t|ddd}| j dd t||dd  }tt	|d| jd  dk|dd dktj|d| jd  t|dd dddt
|dd }tj|||t|   t| j dd | jdd  ddd}| jrtj|| jd dd	}| jdkrntj|| jdS tjtt|| jt| j| jdS ntj|d
dS dS )a  Interpolation formula inspired by section 4 of Davis & Goadrich 2006.

    https://www.biostat.wisc.edu/~page/rocpr.pdf

    Note here we derive & use a closed formula not present in the paper
    as follows:

      Precision = TP / (TP + FP) = TP / P

    Modeling all of TP (true positive), FP (false positive) and their sum
    P = TP + FP (predicted positive) as varying linearly within each interval
    [A, B] between successive thresholds, we get

      Precision slope = dTP / dP
                      = (TP_B - TP_A) / (P_B - P_A)
                      = (TP - TP_A) / (P - P_A)
      Precision = (TP_A + slope * (P - P_A)) / P

    The area within the interval is (slope / total_pos_weight) times

      int_A^B{Precision.dP} = int_A^B{(TP_A + slope * (P - P_A)) * dP / P}
      int_A^B{Precision.dP} = int_A^B{slope * dP + intercept * dP / P}

    where intercept = TP_A - slope * P_A = TP_B - slope * P_B, resulting in

      int_A^B{Precision.dP} = TP_B - TP_A + intercept * log(P_B / P_A)

    Bringing back the factor (slope / total_pos_weight) we'd put aside, we get

      slope * [dTP + intercept *  log(P_B / P_A)] / total_pos_weight

    where dTP == TP_B - TP_A.

    Note that when P_A == 0 the above calculation simplifies into

      int_A^B{Precision.dTP} = int_A^B{slope * dTP} = slope * (TP_B - TP_A)

    which is really equivalent to imputing constant precision throughout the
    first bucket having >0 true positives.

    Returns:
      pr_auc: an approximation of the area under the P-R curve.
    Nr   r   
prec_slope)r2   Zrecall_relative_ratiopr_auc_increment	_by_label)r2   r   interpolate_pr_auc)r   r   r   r)   r   maximumr   r%   wherelogical_and	ones_likelogr   r  r   r2   r  r   )	r8   ZdtppZdpr(  Z	interceptZsafe_p_ratior)  by_label_aucr;   r;   r<   r+    s:    ,
"("
zAUC.interpolate_pr_aucc       	      C   s  | j tjjkr$| jtjjkr$|  S t	| j
| j
| j }| j tjjkrht	| j| j| j }|}|}nt	| j
| j
| j }|}|}| jtjjkr|d | jd  |dd   d }nT| jtjjkrt|d | jd  |dd  }n"t|d | jd  |dd  }| jrt|d | jd  |dd   |}tj|| jd dd}| jd krltj|| jdS tj	tt|| jt| j| jdS n2tjt|d | jd  |dd   || jdS d S )Nr   g       @r*  r   )r2   r   )r2   )r  r    r  ZPRr  r  ZINTERPOLATIONr+  r)   r   r   r   r
  r   r   r   ZMINORINGminimumr,  r  r   r   r2   r  r   )	r8   r  Zfp_ratexyr  ZheightsZriemann_termsr2  r;   r;   r<   rN   :	  sD    $$" 
$z
AUC.resultc                sV    j rR j j j jf} jr:t fdd|D  nt fdd|D  d S )Nc                s"   g | ]}|t  j jffqS r;   )r   r   r   r  )rQ   r\   )r8   r;   r<   r]   t	  s   z#AUC.reset_state.<locals>.<listcomp>c                s   g | ]}|t  jffqS r;   )r   r   r   )rQ   r\   )r8   r;   r<   r]   w	  s   )r  r   r   r   r   r  r   rc   )r8   r   r;   )r8   r<   rd   n	  s    
zAUC.reset_statec                sp   t | jrt| j}n| j}| j| jj| jj| jdd | j	|d}t
t|  }tt| t|  S )Nr   )r   r  r  r   r  r  )r$   r  r   r   r   r  r   r  r   r  r4   r	  r[   r   r   r   )r8   r  r   r   )r:   r;   r<   r[   z	  s    
zAUC.get_config)
r   r
  r  NNNFNNF)N)rb   ry   rz   r{   r5   r|   r   r  rH   r+  rN   rd   r[   r   r;   r;   )r:   r<   r	    s$   s         M*
AQ4r	  zkeras.metrics.CosineSimilarityc                   s"   e Zd ZdZd fdd	Z  ZS )CosineSimilarityaD  Computes the cosine similarity between the labels and predictions.

  `cosine similarity = (a . b) / ||a|| ||b||`

  See: [Cosine Similarity](https://en.wikipedia.org/wiki/Cosine_similarity).

  This metric keeps the average cosine similarity between `predictions` and
  `labels` over a stream of data.

  Args:
    name: (Optional) string name of the metric instance.
    dtype: (Optional) data type of the metric result.
    axis: (Optional) Defaults to -1. The dimension along which the cosine
      similarity is computed.

  Standalone usage:

  >>> # 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]]
  >>> # result = mean(sum(l2_norm(y_true) . l2_norm(y_pred), axis=1))
  >>> #        = ((0. + 0.) +  (0.5 + 0.5)) / 2
  >>> m = tf.keras.metrics.CosineSimilarity(axis=1)
  >>> m.update_state([[0., 1.], [1., 1.]], [[1., 0.], [1., 1.]])
  >>> m.result().numpy()
  0.49999997

  >>> m.reset_state()
  >>> m.update_state([[0., 1.], [1., 1.]], [[1., 0.], [1., 1.]],
  ...                sample_weight=[0.3, 0.7])
  >>> m.result().numpy()
  0.6999999

  Usage with `compile()` API:

  ```python
  model.compile(
      optimizer='sgd',
      loss='mse',
      metrics=[tf.keras.metrics.CosineSimilarity(axis=1)])
  ```
  cosine_similarityNr6  c                s   t t| jt|||d d S )N)r3   r   )r4   r7  r5   r8  )r8   r2   r3   r   )r:   r;   r<   r5   	  s    
zCosineSimilarity.__init__)r8  Nr6  )rb   ry   rz   r{   r5   r   r;   r;   )r:   r<   r7  	  s   +r7  zkeras.metrics.MeanAbsoluteErrorc                   s"   e Zd ZdZd fdd	Z  ZS )MeanAbsoluteErrora  Computes the mean absolute error between the labels and predictions.

  Args:
    name: (Optional) string name of the metric instance.
    dtype: (Optional) data type of the metric result.

  Standalone usage:

  >>> m = tf.keras.metrics.MeanAbsoluteError()
  >>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]])
  >>> m.result().numpy()
  0.25

  >>> m.reset_state()
  >>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]],
  ...                sample_weight=[1, 0])
  >>> m.result().numpy()
  0.5

  Usage with `compile()` API:

  ```python
  model.compile(
      optimizer='sgd',
      loss='mse',
      metrics=[tf.keras.metrics.MeanAbsoluteError()])
  ```
  r   Nc                s   t t| jt||d d S )N)r3   )r4   r9  r5   r   )r8   r2   r3   )r:   r;   r<   r5   	  s    
zMeanAbsoluteError.__init__)r   N)rb   ry   rz   r{   r5   r   r;   r;   )r:   r<   r9  	  s   r9  z)keras.metrics.MeanAbsolutePercentageErrorc                   s"   e Zd ZdZd fdd	Z  ZS )MeanAbsolutePercentageErrora  Computes the mean absolute percentage error between `y_true` and `y_pred`.

  Args:
    name: (Optional) string name of the metric instance.
    dtype: (Optional) data type of the metric result.

  Standalone usage:

  >>> m = tf.keras.metrics.MeanAbsolutePercentageError()
  >>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]])
  >>> m.result().numpy()
  250000000.0

  >>> m.reset_state()
  >>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]],
  ...                sample_weight=[1, 0])
  >>> m.result().numpy()
  500000000.0

  Usage with `compile()` API:

  ```python
  model.compile(
      optimizer='sgd',
      loss='mse',
      metrics=[tf.keras.metrics.MeanAbsolutePercentageError()])
  ```
  r   Nc                s   t t| jt||d d S )N)r3   )r4   r:  r5   r   )r8   r2   r3   )r:   r;   r<   r5   
  s    
z$MeanAbsolutePercentageError.__init__)r   N)rb   ry   rz   r{   r5   r   r;   r;   )r:   r<   r:  	  s   r:  zkeras.metrics.MeanSquaredErrorc                   s"   e Zd ZdZd fdd	Z  ZS )MeanSquaredErrora  Computes the mean squared error between `y_true` and `y_pred`.

  Args:
    name: (Optional) string name of the metric instance.
    dtype: (Optional) data type of the metric result.

  Standalone usage:

  >>> m = tf.keras.metrics.MeanSquaredError()
  >>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]])
  >>> m.result().numpy()
  0.25

  >>> m.reset_state()
  >>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]],
  ...                sample_weight=[1, 0])
  >>> m.result().numpy()
  0.5

  Usage with `compile()` API:

  ```python
  model.compile(
      optimizer='sgd',
      loss='mse',
      metrics=[tf.keras.metrics.MeanSquaredError()])
  ```
  r   Nc                s   t t| jt||d d S )N)r3   )r4   r;  r5   r   )r8   r2   r3   )r:   r;   r<   r5   '
  s    
zMeanSquaredError.__init__)r   N)rb   ry   rz   r{   r5   r   r;   r;   )r:   r<   r;  
  s   r;  z)keras.metrics.MeanSquaredLogarithmicErrorc                   s"   e Zd ZdZd fdd	Z  ZS )MeanSquaredLogarithmicErrora  Computes the mean squared logarithmic error between `y_true` and `y_pred`.

  Args:
    name: (Optional) string name of the metric instance.
    dtype: (Optional) data type of the metric result.

  Standalone usage:

  >>> m = tf.keras.metrics.MeanSquaredLogarithmicError()
  >>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]])
  >>> m.result().numpy()
  0.12011322

  >>> m.reset_state()
  >>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]],
  ...                sample_weight=[1, 0])
  >>> m.result().numpy()
  0.24022643

  Usage with `compile()` API:

  ```python
  model.compile(
      optimizer='sgd',
      loss='mse',
      metrics=[tf.keras.metrics.MeanSquaredLogarithmicError()])
  ```
  r   Nc                s   t t| jt||d d S )N)r3   )r4   r<  r5   r   )r8   r2   r3   )r:   r;   r<   r5   K
  s    
z$MeanSquaredLogarithmicError.__init__)r   N)rb   ry   rz   r{   r5   r   r;   r;   )r:   r<   r<  ,
  s   r<  zkeras.metrics.Hingec                   s"   e Zd ZdZd fdd	Z  ZS )Hingea  Computes the hinge metric between `y_true` and `y_pred`.

  `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.

  Args:
    name: (Optional) string name of the metric instance.
    dtype: (Optional) data type of the metric result.

  Standalone usage:

  >>> m = tf.keras.metrics.Hinge()
  >>> m.update_state([[0, 1], [0, 0]], [[0.6, 0.4], [0.4, 0.6]])
  >>> m.result().numpy()
  1.3

  >>> m.reset_state()
  >>> m.update_state([[0, 1], [0, 0]], [[0.6, 0.4], [0.4, 0.6]],
  ...                sample_weight=[1, 0])
  >>> m.result().numpy()
  1.1

  Usage with `compile()` API:

  ```python
  model.compile(optimizer='sgd', loss='mse', metrics=[tf.keras.metrics.Hinge()])
  ```
  r   Nc                s   t t| jt||d d S )N)r3   )r4   r=  r5   r   )r8   r2   r3   )r:   r;   r<   r5   o
  s    zHinge.__init__)r   N)rb   ry   rz   r{   r5   r   r;   r;   )r:   r<   r=  P
  s   r=  zkeras.metrics.SquaredHingec                   s"   e Zd ZdZd fdd	Z  ZS )SquaredHingea  Computes the squared hinge metric between `y_true` and `y_pred`.

  `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.

  Args:
    name: (Optional) string name of the metric instance.
    dtype: (Optional) data type of the metric result.

  Standalone usage:

  >>> m = tf.keras.metrics.SquaredHinge()
  >>> m.update_state([[0, 1], [0, 0]], [[0.6, 0.4], [0.4, 0.6]])
  >>> m.result().numpy()
  1.86

  >>> m.reset_state()
  >>> m.update_state([[0, 1], [0, 0]], [[0.6, 0.4], [0.4, 0.6]],
  ...                sample_weight=[1, 0])
  >>> m.result().numpy()
  1.46

  Usage with `compile()` API:

  ```python
  model.compile(
      optimizer='sgd',
      loss='mse',
      metrics=[tf.keras.metrics.SquaredHinge()])
  ```
  r   Nc                s   t t| jt||d d S )N)r3   )r4   r>  r5   r   )r8   r2   r3   )r:   r;   r<   r5   
  s    zSquaredHinge.__init__)r   N)rb   ry   rz   r{   r5   r   r;   r;   )r:   r<   r>  s
  s    r>  zkeras.metrics.CategoricalHingec                   s"   e Zd ZdZd fdd	Z  ZS )CategoricalHingea  Computes the categorical hinge metric between `y_true` and `y_pred`.

  Args:
    name: (Optional) string name of the metric instance.
    dtype: (Optional) data type of the metric result.

  Standalone usage:

  >>> m = tf.keras.metrics.CategoricalHinge()
  >>> m.update_state([[0, 1], [0, 0]], [[0.6, 0.4], [0.4, 0.6]])
  >>> m.result().numpy()
  1.4000001

  >>> m.reset_state()
  >>> m.update_state([[0, 1], [0, 0]], [[0.6, 0.4], [0.4, 0.6]],
  ...                sample_weight=[1, 0])
  >>> m.result().numpy()
  1.2

  Usage with `compile()` API:

  ```python
  model.compile(
      optimizer='sgd',
      loss='mse',
      metrics=[tf.keras.metrics.CategoricalHinge()])
  ```
  r   Nc                s   t t| jt||d d S )N)r3   )r4   r?  r5   r   )r8   r2   r3   )r:   r;   r<   r5   
  s    zCategoricalHinge.__init__)r   N)rb   ry   rz   r{   r5   r   r;   r;   )r:   r<   r?  
  s   r?  z"keras.metrics.RootMeanSquaredErrorc                   s8   e Zd ZdZd
 fdd	Zd fdd	Zdd	 Z  ZS )RootMeanSquaredErrora/  Computes root mean squared error metric between `y_true` and `y_pred`.

  Standalone usage:

  >>> m = tf.keras.metrics.RootMeanSquaredError()
  >>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]])
  >>> m.result().numpy()
  0.5

  >>> m.reset_state()
  >>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]],
  ...                sample_weight=[1, 0])
  >>> m.result().numpy()
  0.70710677

  Usage with `compile()` API:

  ```python
  model.compile(
      optimizer='sgd',
      loss='mse',
      metrics=[tf.keras.metrics.RootMeanSquaredError()])
  ```
  root_mean_squared_errorNc                s   t t| j||d d S )N)r3   )r4   r@  r5   )r8   r2   r3   )r:   r;   r<   r5   
  s    zRootMeanSquaredError.__init__c                sL   t || j}t || j}t||\}}t ||}tt| j||dS )ap  Accumulates root mean squared error statistics.

    Args:
      y_true: The ground truth values.
      y_pred: The predicted values.
      sample_weight: Optional weighting of each example. Defaults to 1. Can be a
        `Tensor` whose rank is either 0, or the same rank as `y_true`, and must
        be broadcastable to `y_true`.

    Returns:
      Update op.
    )r   )	r)   r   r7   r   r   Zsquared_differencer4   r@  rH   )r8   r   r   r   Zerror_sq)r:   r;   r<   rH   
  s    
z!RootMeanSquaredError.update_statec             C   s   t t | j| jS )N)r)   sqrtr   r   r   )r8   r;   r;   r<   rN   
  s    zRootMeanSquaredError.result)rA  N)N)rb   ry   rz   r{   r5   rH   rN   r   r;   r;   )r:   r<   r@  
  s   r@  zkeras.metrics.LogCoshErrorc                   s"   e Zd ZdZd fdd	Z  ZS )LogCoshErrora  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)

  Args:
    name: (Optional) string name of the metric instance.
    dtype: (Optional) data type of the metric result.

  Standalone usage:

  >>> m = tf.keras.metrics.LogCoshError()
  >>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]])
  >>> m.result().numpy()
  0.10844523

  >>> m.reset_state()
  >>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]],
  ...                sample_weight=[1, 0])
  >>> m.result().numpy()
  0.21689045

  Usage with `compile()` API:

  ```python
  model.compile(optimizer='sgd',
                loss='mse',
                metrics=[tf.keras.metrics.LogCoshError()])
  ```
  r   Nc                s   t t| jt||d d S )N)r3   )r4   rC  r5   r   )r8   r2   r3   )r:   r;   r<   r5     s    zLogCoshError.__init__)r   N)rb   ry   rz   r{   r5   r   r;   r;   )r:   r<   rC  
  s   rC  zkeras.metrics.Poissonc                   s"   e Zd ZdZd fdd	Z  ZS )Poissona  Computes the Poisson metric between `y_true` and `y_pred`.

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

  Args:
    name: (Optional) string name of the metric instance.
    dtype: (Optional) data type of the metric result.

  Standalone usage:

  >>> m = tf.keras.metrics.Poisson()
  >>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]])
  >>> m.result().numpy()
  0.49999997

  >>> m.reset_state()
  >>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]],
  ...                sample_weight=[1, 0])
  >>> m.result().numpy()
  0.99999994

  Usage with `compile()` API:

  ```python
  model.compile(optimizer='sgd',
                loss='mse',
                metrics=[tf.keras.metrics.Poisson()])
  ```
  r   Nc                s   t t| jt||d d S )N)r3   )r4   rD  r5   r   )r8   r2   r3   )r:   r;   r<   r5   7  s    zPoisson.__init__)r   N)rb   ry   rz   r{   r5   r   r;   r;   )r:   r<   rD    s   rD  zkeras.metrics.KLDivergencec                   s"   e Zd ZdZd fdd	Z  ZS )KLDivergencea  Computes Kullback-Leibler divergence metric between `y_true` and `y_pred`.

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

  Args:
    name: (Optional) string name of the metric instance.
    dtype: (Optional) data type of the metric result.

  Standalone usage:

  >>> m = tf.keras.metrics.KLDivergence()
  >>> m.update_state([[0, 1], [0, 0]], [[0.6, 0.4], [0.4, 0.6]])
  >>> m.result().numpy()
  0.45814306

  >>> m.reset_state()
  >>> m.update_state([[0, 1], [0, 0]], [[0.6, 0.4], [0.4, 0.6]],
  ...                sample_weight=[1, 0])
  >>> m.result().numpy()
  0.9162892

  Usage with `compile()` API:

  ```python
  model.compile(optimizer='sgd',
                loss='mse',
                metrics=[tf.keras.metrics.KLDivergence()])
  ```
  r   Nc                s   t t| jt||d d S )N)r3   )r4   rE  r5   r   )r8   r2   r3   )r:   r;   r<   r5   [  s    
zKLDivergence.__init__)r   N)rb   ry   rz   r{   r5   r   r;   r;   )r:   r<   rE  ;  s   rE  zkeras.metrics.MeanIoUc                   sH   e Zd ZdZd fdd	ZdddZdd Zd	d
 Z fddZ  Z	S )MeanIoUac  Computes the mean Intersection-Over-Union metric.

  Mean Intersection-Over-Union is a common evaluation metric for semantic image
  segmentation, which first computes the IOU for each semantic class and then
  computes the average over classes. IOU is defined as follows:
    IOU = true_positive / (true_positive + false_positive + false_negative).
  The predictions are accumulated in a confusion matrix, weighted by
  `sample_weight` and the metric is then calculated from it.

  If `sample_weight` is `None`, weights default to 1.
  Use `sample_weight` of 0 to mask values.

  Args:
    num_classes: The possible number of labels the prediction task can have.
      This value must be provided, since a confusion matrix of dimension =
      [num_classes, num_classes] will be allocated.
    name: (Optional) string name of the metric instance.
    dtype: (Optional) data type of the metric result.

  Standalone usage:

  >>> # cm = [[1, 1],
  >>> #        [1, 1]]
  >>> # sum_row = [2, 2], sum_col = [2, 2], true_positives = [1, 1]
  >>> # iou = true_positives / (sum_row + sum_col - true_positives))
  >>> # result = (1 / (2 + 2 - 1) + 1 / (2 + 2 - 1)) / 2 = 0.33
  >>> m = tf.keras.metrics.MeanIoU(num_classes=2)
  >>> m.update_state([0, 0, 1, 1], [0, 1, 0, 1])
  >>> m.result().numpy()
  0.33333334

  >>> m.reset_state()
  >>> m.update_state([0, 0, 1, 1], [0, 1, 0, 1],
  ...                sample_weight=[0.3, 0.3, 0.3, 0.1])
  >>> m.result().numpy()
  0.23809525

  Usage with `compile()` API:

  ```python
  model.compile(
    optimizer='sgd',
    loss='mse',
    metrics=[tf.keras.metrics.MeanIoU(num_classes=2)])
  ```
  Nc                s6   t t| j||d || _| jd||ftjd| _d S )N)r2   r3   Ztotal_confusion_matrix)rf   rh   )r4   rF  r5   num_classesrp   r(   r   total_cm)r8   rG  r2   r3   )r:   r;   r<   r5     s    zMeanIoU.__init__c             C   s   t || j}t || j}|jjdkr6t|dg}|jjdkrPt|dg}|dk	rt || j}|jjdkrt|dg}tj||| j|| jd}| j	
|S )am  Accumulates the confusion matrix statistics.

    Args:
      y_true: The ground truth values.
      y_pred: The predicted values.
      sample_weight: Optional weighting of each example. Defaults to 1. Can be a
        `Tensor` whose rank is either 0, or the same rank as `y_true`, and must
        be broadcastable to `y_true`.

    Returns:
      Update op.
    r   r6  N)rw   r3   )r)   r   r7   rf   r  r%   reshaper'   rG  rH  r   )r8   r   r   r   Z
current_cmr;   r;   r<   rH     s"    
zMeanIoU.update_statec             C   s   t jt j| jdd| jd}t jt j| jdd| jd}t jt| j| jd}|| | }t t jt |d| jd}t ||}t t j|dd|S )zBCompute the mean intersection-over-union via the confusion matrix.r   )r   )r3   r   Zmean_iou)r2   )	r)   r   r   rH  r7   r%   Ztensor_diag_part	not_equalr   )r8   Zsum_over_rowZsum_over_colr   denominatorZnum_valid_entriesZiour;   r;   r<   rN     s    zMeanIoU.resultc             C   s    t | jt| j| jf d S )N)r   	set_valuerH  r   r   rG  )r8   r;   r;   r<   rd     s    zMeanIoU.reset_statec                s4   d| j i}tt|  }tt| t|  S )NrG  )rG  r4   rF  r[   r   r   r   )r8   r   r   )r:   r;   r<   r[     s    
zMeanIoU.get_config)NN)N)
rb   ry   rz   r{   r5   rH   rN   rd   r[   r   r;   r;   )r:   r<   rF  `  s   /

&rF  zkeras.metrics.MeanTensorc                   s\   e Zd ZdZd fdd	Zdd Zedd	 Zed
d ZdddZ	dd Z
dd Z  ZS )
MeanTensora  Computes the element-wise (weighted) mean of the given tensors.

  `MeanTensor` returns a tensor with the same shape of the input tensors. The
  mean value is updated by keeping local variables `total` and `count`. The
  `total` tracks the sum of the weighted values, and `count` stores the sum of
  the weighted counts.

  Args:
    name: (Optional) string name of the metric instance.
    dtype: (Optional) data type of the metric result.
    shape: (Optional) A list of integers, a tuple of integers, or a 1-D Tensor
      of type int32. If not specified, the shape is inferred from the values at
      the first call of update_state.

  Standalone usage:

  >>> m = tf.keras.metrics.MeanTensor()
  >>> m.update_state([0, 1, 2, 3])
  >>> m.update_state([4, 5, 6, 7])
  >>> m.result().numpy()
  array([2., 3., 4., 5.], dtype=float32)

  >>> m.update_state([12, 10, 8, 6], sample_weight= [0, 0.2, 0.5, 1])
  >>> m.result().numpy()
  array([2.       , 3.6363635, 4.8      , 5.3333335], dtype=float32)

  >>> m = tf.keras.metrics.MeanTensor(dtype=tf.float64, shape=(1, 4))
  >>> m.result().numpy()
  array([[0., 0., 0., 0.]])
  >>> m.update_state([[0, 1, 2, 3]])
  >>> m.update_state([[4, 5, 6, 7]])
  >>> m.result().numpy()
  array([[2., 3., 4., 5.]])
  mean_tensorNc                sB   t t| j||d d | _d | _d | _d| _|d k	r>| | d S )N)r2   r3   F)r4   rM  r5   _shape_total_countr  r  )r8   r2   r3   rf   )r:   r;   r<   r5     s    zMeanTensor.__init__c          	   C   sp   t || _| j| _| jd|tjd| _| jd|tjd| _t	
  t s\tt  W d Q R X d| _d S )Nr   )rf   rh   r   T)r
   r  rO  r  rp   r(   r   rP  rQ  r	   ro   r   r   r   r!  r"  r  )r8   rf   r;   r;   r<   r    s    
zMeanTensor._buildc             C   s   | j r| jS d S )N)r  rP  )r8   r;   r;   r<   r     s    zMeanTensor.totalc             C   s   | j r| jS d S )N)r  rQ  )r8   r;   r;   r<   r   "  s    zMeanTensor.countc          	   C   s  t || j}| js"| |j n |j| jkrBtd| j|jt	
|}|dk	rt || j}tj||d\}}}yt||}W n@ tk
r   t|}t|}t j|tt||d}Y nX t ||}t ||}| j|}t|g | j|S Q R X dS )zAccumulates statistics for computing the element-wise mean.

    Args:
      values: Per-example value.
      sample_weight: Optional weighting of each example. Defaults to 1.

    Returns:
      Update op.
    zpMeanTensor input values must always have the same shape. Expected shape (set during the first call): {}. Got: {}N)r   )r   )r)   r   r7   r  r  rf   rO  r   r  r%   r/  r   r   r,   r   r   r   r   r   r   r   rP  r   r	   rW   rQ  )r8   r   r   r   r   r   r   r   r;   r;   r<   rH   &  s0    



zMeanTensor.update_statec             C   s   | j stdt| j| jS )NzMeanTensor does not have any result yet. Please call the MeanTensor instance or use `.update_state(value)` before retrieving the result.)r  r   r)   r   r   r   )r8   r;   r;   r<   rN   Q  s    zMeanTensor.resultc                s$    j r t fdd jD  d S )Nc                s    g | ]}|t  j fqS r;   )r   r   rO  as_list)rQ   r\   )r8   r;   r<   r]   \  s    z*MeanTensor.reset_state.<locals>.<listcomp>)r  r   rc   r+   )r8   r;   )r8   r<   rd   Y  s    zMeanTensor.reset_state)rN  NN)N)rb   ry   rz   r{   r5   r  r|   r   r   rH   rN   rd   r   r;   r;   )r:   r<   rM    s   #	
+rM  z keras.metrics.BinaryCrossentropyc                   s"   e Zd ZdZd fdd	Z  ZS )	BinaryCrossentropya  Computes the crossentropy metric between the labels and predictions.

  This is the crossentropy metric class to be used when there are only two
  label classes (0 and 1).

  Args:
    name: (Optional) string name of the metric instance.
    dtype: (Optional) data type of the metric result.
    from_logits: (Optional )Whether output is expected to be a logits tensor.
      By default, we consider that output encodes a probability distribution.
    label_smoothing: (Optional) Float in [0, 1]. When > 0, label values are
      smoothed, meaning the confidence on label values are relaxed.
      e.g. `label_smoothing=0.2` means that we will use a value of `0.1` for
      label `0` and `0.9` for label `1`".

  Standalone usage:

  >>> m = tf.keras.metrics.BinaryCrossentropy()
  >>> m.update_state([[0, 1], [0, 0]], [[0.6, 0.4], [0.4, 0.6]])
  >>> m.result().numpy()
  0.81492424

  >>> m.reset_state()
  >>> m.update_state([[0, 1], [0, 0]], [[0.6, 0.4], [0.4, 0.6]],
  ...                sample_weight=[1, 0])
  >>> m.result().numpy()
  0.9162905

  Usage with `compile()` API:

  ```python
  model.compile(
      optimizer='sgd',
      loss='mse',
      metrics=[tf.keras.metrics.BinaryCrossentropy()])
  ```
  r   NFr   c                s   t t| jt||||d d S )N)r3   r  label_smoothing)r4   rS  r5   r   )r8   r2   r3   r  rT  )r:   r;   r<   r5     s    
zBinaryCrossentropy.__init__)r   NFr   )rb   ry   rz   r{   r5   r   r;   r;   )r:   r<   rS  _  s
   &   rS  z%keras.metrics.CategoricalCrossentropyc                   s"   e Zd ZdZd fdd	Z  ZS )	CategoricalCrossentropya  Computes the crossentropy metric between the labels and predictions.

  This is the crossentropy metric class to be used when there are multiple
  label classes (2 or more). Here we assume that labels are given as a `one_hot`
  representation. eg., When labels values are [2, 0, 1],
   `y_true` = [[0, 0, 1], [1, 0, 0], [0, 1, 0]].

  Args:
    name: (Optional) string name of the metric instance.
    dtype: (Optional) data type of the metric result.
    from_logits: (Optional) Whether output is expected to be a logits tensor.
      By default, we consider that output encodes a probability distribution.
    label_smoothing: (Optional) Float in [0, 1]. When > 0, label values are
      smoothed, meaning the confidence on label values are relaxed. e.g.
      `label_smoothing=0.2` means that we will use a value of `0.1` for label
      `0` and `0.9` for label `1`"

  Standalone usage:

  >>> # EPSILON = 1e-7, y = y_true, y` = y_pred
  >>> # y` = clip_ops.clip_by_value(output, EPSILON, 1. - EPSILON)
  >>> # y` = [[0.05, 0.95, EPSILON], [0.1, 0.8, 0.1]]
  >>> # xent = -sum(y * log(y'), axis = -1)
  >>> #      = -((log 0.95), (log 0.1))
  >>> #      = [0.051, 2.302]
  >>> # Reduced xent = (0.051 + 2.302) / 2
  >>> m = tf.keras.metrics.CategoricalCrossentropy()
  >>> m.update_state([[0, 1, 0], [0, 0, 1]],
  ...                [[0.05, 0.95, 0], [0.1, 0.8, 0.1]])
  >>> m.result().numpy()
  1.1769392

  >>> m.reset_state()
  >>> m.update_state([[0, 1, 0], [0, 0, 1]],
  ...                [[0.05, 0.95, 0], [0.1, 0.8, 0.1]],
  ...                sample_weight=tf.constant([0.3, 0.7]))
  >>> m.result().numpy()
  1.6271976

  Usage with `compile()` API:

  ```python
  model.compile(
    optimizer='sgd',
    loss='mse',
    metrics=[tf.keras.metrics.CategoricalCrossentropy()])
  ```
  r   NFr   c                s   t t| jt||||d d S )N)r3   r  rT  )r4   rU  r5   r   )r8   r2   r3   r  rT  )r:   r;   r<   r5     s    
z CategoricalCrossentropy.__init__)r   NFr   )rb   ry   rz   r{   r5   r   r;   r;   )r:   r<   rU    s
   1   rU  z+keras.metrics.SparseCategoricalCrossentropyc                   s"   e Zd ZdZd fdd	Z  ZS )	SparseCategoricalCrossentropya^  Computes the crossentropy metric between the labels and predictions.

  Use this crossentropy metric 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` metric.
  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]`.

  Args:
    name: (Optional) string name of the metric instance.
    dtype: (Optional) data type of the metric result.
    from_logits: (Optional) Whether output is expected to be a logits tensor.
      By default, we consider that output encodes a probability distribution.
    axis: (Optional) Defaults to -1. The dimension along which the metric is
      computed.

  Standalone usage:

  >>> # y_true = one_hot(y_true) = [[0, 1, 0], [0, 0, 1]]
  >>> # logits = log(y_pred)
  >>> # softmax = exp(logits) / sum(exp(logits), axis=-1)
  >>> # softmax = [[0.05, 0.95, EPSILON], [0.1, 0.8, 0.1]]
  >>> # xent = -sum(y * log(softmax), 1)
  >>> # log(softmax) = [[-2.9957, -0.0513, -16.1181],
  >>> #                [-2.3026, -0.2231, -2.3026]]
  >>> # y_true * log(softmax) = [[0, -0.0513, 0], [0, 0, -2.3026]]
  >>> # xent = [0.0513, 2.3026]
  >>> # Reduced xent = (0.0513 + 2.3026) / 2
  >>> m = tf.keras.metrics.SparseCategoricalCrossentropy()
  >>> m.update_state([1, 2],
  ...                [[0.05, 0.95, 0], [0.1, 0.8, 0.1]])
  >>> m.result().numpy()
  1.1769392

  >>> m.reset_state()
  >>> m.update_state([1, 2],
  ...                [[0.05, 0.95, 0], [0.1, 0.8, 0.1]],
  ...                sample_weight=tf.constant([0.3, 0.7]))
  >>> m.result().numpy()
  1.6271976

  Usage with `compile()` API:

  ```python
  model.compile(
    optimizer='sgd',
    loss='mse',
    metrics=[tf.keras.metrics.SparseCategoricalCrossentropy()])
  ```
  r   NFr6  c                s   t t| jt||||d d S )N)r3   r  r   )r4   rV  r5   r   )r8   r2   r3   r  r   )r:   r;   r<   r5     s    
z&SparseCategoricalCrossentropy.__init__)r   NFr6  )rb   ry   rz   r{   r5   r   r;   r;   )r:   r<   rV    s
   8   rV  c                   s"   e Zd ZdZd fdd	Z  ZS )SumOverBatchSizea+  Computes the weighted sum over batch size of the given values.

  For example, if values is [1, 3, 5, 7] then the metric value is 4.
  If the weights were specified as [1, 1, 0, 0] then the value would be 1.

  This metric creates two variables, `total` and `count` that are used to
  compute the average of `values`. This average is ultimately returned as sum
  over batch size which is an idempotent operation that simply divides `total`
  by `count`.

  If `sample_weight` is `None`, weights default to 1.  Use `sample_weight` of 0
  to mask values.
  sum_over_batch_sizeNc                s   t t| jtjj||d d S )N)r   r2   r3   )r4   rW  r5   r    r   r   )r8   r2   r3   )r:   r;   r<   r5   *  s    
zSumOverBatchSize.__init__)rX  N)rb   ry   rz   r{   r5   r   r;   r;   )r:   r<   rW    s   rW  c                   s<   e Zd ZdZd	 fdd	Zd
 fdd	Z fddZ  ZS )SumOverBatchSizeMetricWrapperzAWraps a function with the `SumOverBatchSizeMetricWrapper` metric.Nc                s$   t t| j||d || _|| _dS )aV  Creates a `SumOverBatchSizeMetricWrapper` instance.

    Args:
      fn: The metric function to wrap, with signature `fn(y_true, y_pred,
        **kwargs)`.
      name: (Optional) string name of the metric instance.
      dtype: (Optional) data type of the metric result.
      **kwargs: The keyword arguments that are passed on to `fn`.
    )r2   r3   N)r4   rY  r5   r   r   )r8   r   r2   r3   r9   )r:   r;   r<   r5   4  s    
z&SumOverBatchSizeMetricWrapper.__init__c                sb   t || j}t || j}t||\}}t| jt	 }|||f| j
}tt| j||dS )N)r   )r)   r   r7   r   r   r>   r?   r   r   r=   r   r4   rY  rH   )r8   r   r   r   r   r   )r:   r;   r<   rH   B  s    
z*SumOverBatchSizeMetricWrapper.update_statec                s`   i }x0| j  D ]"\}}t|r*t|n|||< qW tt|  }tt	| t	|  S )N)
r   r   r$   r   r   r4   rY  r[   r   r   )r8   r   r   r\   r   )r:   r;   r<   r[   M  s
    z(SumOverBatchSizeMetricWrapper.get_config)NN)N)rb   ry   rz   r{   r5   rH   r[   r   r;   r;   )r:   r<   rY  1  s   rY  c             C   sV   t || g\\}} }| j|j | j|jkr>t|| j}tt| |t	 S )N)
r    r   rf   r   r3   r)   r   equalr   r6   )r   r   r   r;   r;   r<   r   U  s    r   zkeras.metrics.binary_accuracy      ?c             C   s@   t |}t||j}t||k|j}tjt| |ddS )ax  Calculates how often predictions match binary labels.

  Standalone usage:
  >>> y_true = [[1], [1], [0], [0]]
  >>> y_pred = [[1], [1], [0], [0]]
  >>> m = tf.keras.metrics.binary_accuracy(y_true, y_pred)
  >>> assert m.shape == (4,)
  >>> m.numpy()
  array([1., 1., 1., 1.], dtype=float32)

  Args:
    y_true: Ground truth values. shape = `[batch_size, d0, .. dN]`.
    y_pred: The predicted values. shape = `[batch_size, d0, .. dN]`.
    threshold: (Optional) Float representing the threshold for deciding whether
      prediction values are 1 or 0.

  Returns:
    Binary accuracy values. shape = `[batch_size, d0, .. dN-1]`
  r6  )r   )r	   r   r)   r   r3   r   r   rZ  )r   r   r   r;   r;   r<   r   _  s    
r   z"keras.metrics.categorical_accuracyc          	   C   s,   t t t j| ddt j|ddt S )a  Calculates how often predictions match one-hot labels.

  Standalone usage:
  >>> y_true = [[0, 0, 1], [0, 1, 0]]
  >>> y_pred = [[0.1, 0.9, 0.8], [0.05, 0.95, 0]]
  >>> m = tf.keras.metrics.categorical_accuracy(y_true, y_pred)
  >>> assert m.shape == (2,)
  >>> m.numpy()
  array([0., 1.], dtype=float32)

  You can provide logits of classes as `y_pred`, since argmax of
  logits and probabilities are same.

  Args:
    y_true: One-hot ground truth values.
    y_pred: The prediction values.

  Returns:
    Categorical accuracy values.
  r6  )r   )r)   r   rZ  argmaxr   r6   )r   r   r;   r;   r<   r   {  s    r   z)keras.metrics.sparse_categorical_accuracyc             C   s   t |}t | } |jj}| jj}|dk	r^|dk	r^tt| tt|kr^t| dg} t	j
|dd}t|t| krt	|t| }t	t	| |t S )a  Calculates how often predictions match integer labels.

  Standalone usage:
  >>> y_true = [2, 1]
  >>> y_pred = [[0.1, 0.9, 0.8], [0.05, 0.95, 0]]
  >>> m = tf.keras.metrics.sparse_categorical_accuracy(y_true, y_pred)
  >>> assert m.shape == (2,)
  >>> m.numpy()
  array([0., 1.], dtype=float32)

  You can provide logits of classes as `y_pred`, since argmax of
  logits and probabilities are same.

  Args:
    y_true: Integer ground truth values.
    y_pred: The prediction values.

  Returns:
    Sparse categorical accuracy values.
  Nr6  )r   )r	   r   rf   r  r   r   Z	int_shaper%   Zsqueezer)   r\  r3   r   rZ  r6   )r   r   y_pred_ranky_true_rankr;   r;   r<   r     s    

r   z(keras.metrics.top_k_categorical_accuracyr   c          	   C   s$   t t|t j| dd|t S )a'  Computes how often targets are in the top `K` predictions.

  Standalone usage:
  >>> y_true = [[0, 0, 1], [0, 1, 0]]
  >>> y_pred = [[0.1, 0.9, 0.8], [0.05, 0.95, 0]]
  >>> m = tf.keras.metrics.top_k_categorical_accuracy(y_true, y_pred, k=3)
  >>> assert m.shape == (2,)
  >>> m.numpy()
  array([1., 1.], dtype=float32)

  Args:
    y_true: The ground truth values.
    y_pred: The prediction values.
    k: (Optional) Number of top elements to look at for computing accuracy.
      Defaults to 5.

  Returns:
    Top K categorical accuracy value.
  r6  )r   )r)   r   r*   in_top_kr\  r   r6   )r   r   r   r;   r;   r<   r     s    r   z/keras.metrics.sparse_top_k_categorical_accuracyc          	   C   s   t |jj}t | jj}|dk	r`|dk	r`|dkrJt|d|jd g}|dkr`t| dg} tt	|t| d|t
 S )a=  Computes how often integer targets are in the top `K` predictions.

  Standalone usage:
  >>> y_true = [2, 1]
  >>> y_pred = [[0.1, 0.9, 0.8], [0.05, 0.95, 0]]
  >>> m = tf.keras.metrics.sparse_top_k_categorical_accuracy(
  ...     y_true, y_pred, k=3)
  >>> assert m.shape == (2,)
  >>> m.numpy()
  array([1., 1.], dtype=float32)

  Args:
    y_true: tensor of true targets.
    y_pred: tensor of predicted targets.
    k: (Optional) Number of top elements to look at for computing accuracy.
      Defaults to 5.

  Returns:
    Sparse top K categorical accuracy value.
  Nr   r6  r   Zint32)r	   r   rf   r  r%   rI  r)   r   r*   r_  r   r6   )r   r   r   r]  r^  r;   r;   r<   r     s    r   r6  c             C   s.   t j| |d} t j||d}tj| | |dS )a#  Computes the cosine similarity between labels and predictions.

  Args:
    y_true: The ground truth values.
    y_pred: The prediction values.
    axis: (Optional) Defaults to -1. The dimension along which the cosine
      similarity is computed.

  Returns:
    Cosine similarity value.
  )r   )r*   Zl2_normalizer)   r   )r   r   r   r;   r;   r<   cosine_proximity   s    r`  c          	   C   s.   t | tr*t  | j|  S Q R X | S )zFReturns a clone of the metric if stateful, otherwise returns it as is.N)rI   r1   r	   ro   r:   r   r[   )metricr;   r;   r<   clone_metric  s    

rb  c             C   s   t t| S )z"Clones the given metric list/dict.)r.   Zmap_structurerb  )Zmetricsr;   r;   r<   clone_metrics$  s    rc  zkeras.metrics.serializec             C   s   t | S )zSerializes metric function or `Metric` instance.

  Args:
    metric: A Keras `Metric` instance or a metric function.

  Returns:
    Metric configuration dictionary.
  )r"   )ra  r;   r;   r<   	serialize)  s    
rd  zkeras.metrics.deserializec             C   s   t | t |ddS )aB  Deserializes a serialized metric class/function instance.

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

  Returns:
      A Keras `Metric` instance or a metric function.
  zmetric function)Zmodule_objectscustom_objectsZprintable_module_name)r!   globals)r   re  r;   r;   r<   deserialize6  s
    rg  zkeras.metrics.getc             C   sF   t | trt| S t | tr(tt| S t| r4| S td| dS )a  Retrieves a Keras metric as a `function`/`Metric` class instance.

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

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

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

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

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

  Returns:
    A Keras metric as a `function`/ `Metric` class instance.

  Raises:
    ValueError: If `identifier` cannot be interpreted.
  z2Could not interpret metric function identifier: {}N)rI   r   rg  strcallabler   r  )
identifierr;   r;   r<   r   I  s    "

r   c             C   s   | j tj kS )N)ry   r1   )rO   r;   r;   r<   rG   v  s    rG   )r[  )r   )r   )r6  )N)r{   r}   rL   r`   numpyr   Z tensorflow.python.autograph.corer   Z tensorflow.python.autograph.implr   r>   Ztensorflow.python.distributer   rl   Ztensorflow.python.eagerr   r   Ztensorflow.python.frameworkr   r   r	   r
   Ztensorflow.python.kerasr   r   Ztensorflow.python.keras.enginer   r   r   Ztensorflow.python.keras.lossesr   r   r   r   r   r   r   r   r   r   r   r   r   Z*tensorflow.python.keras.saving.saved_modelr   Ztensorflow.python.keras.utilsr   r   r    Z+tensorflow.python.keras.utils.generic_utilsr!   r"   r#   Z&tensorflow.python.keras.utils.tf_utilsr$   Ztensorflow.python.opsr%   r&   r'   r(   r)   r*   r+   rm   r,   Ztensorflow.python.utilr-   r.   Z tensorflow.python.util.tf_exportr/   Ztensorflow.tools.docsr0   ZLayerABCMetar1   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r	  r7  r9  r:  r;  r<  r=  r>  r?  r@  rC  rD  rE  rF  rM  rS  rU  rV  rW  rY  r   Zadd_dispatch_supportr   r   r   r   r   r`  accZACCZbceZBCEZmseZMSEZmaeZMAEZmapeZMAPEZmsleZMSLEr8  Zlog_coshrb  rc  rd  rg  r   rG   r;   r;   r;   r<   <module>   sX    b$)OY),32&%F0000  k][PT   c1####"%"6##$ {4?F$
("
-