
    6bi                     B   S r SSKrSSKrSSKrSSKrSSKJs  Jr	  SSK
Jr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SS	KJr  SS
KJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  \" S5       " S S\R@                  \RB                  S95       r" " S S\"5      r#\" S5       " S S\#5      5       r$\" S5       " S S\#5      5       r%\" S5       " S S\%5      5       r&\" S5       " S  S!\"5      5       r' " S" S#\#5      r( " S$ S%\(5      r)S& r*S' r+S( r, " S) S*\-5      r.g)+zBase Metric classes.    N)backend)dtensor_api)utils)
base_layer)base_layer_utils)keras_tensor)metric_serialization)generic_utils)losses_utils)metrics_utils)tf_utils)keras_export)doc_controlszkeras.metrics.Metricc                     ^  \ rS rSrSrSU 4S jjrU 4S jrS rS rSS jr	\
S	 5       rS
 rS r\R                  S 5       rS r\R                  S 5       r\R(                  S\R,                  R.                  \R0                  R2                  SS4U 4S jj5       r\
S 5       r\
S 5       r\
S 5       r\R>                  \R@                  S 5       5       r!Sr"U =r#$ )Metric)   a  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 scalar value or a dict of scalar values
  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                    > [         TU ]  " SXS.UD6  SU l        SU l        [        R
                  " 5       (       d>  Uc  [        R                  " 5       O[        R                  " U5      R                  U l        g g )NnamedtypeT )super__init__statefulbuiltr   v2_dtype_behavior_enabledr   floatxtfas_dtyper   _dtype)selfr   r   kwargs	__class__s       Z/home/james-whalen/.local/lib/python3.13/site-packages/tf_keras/src/metrics/base_metric.pyr   Metric.__init__r   sb    :d:6:
99;; %*M r{{57I7N7N K <    c                 d  >^^ [         [        U ]  U 5      n[        R                  " 5       (       d  [        U 5      (       a  UR                  mU4S jnOj[        UR                  [        R                  R                  R                  5      (       a  UR                  nO [        R                  " UR                  5      n[        R                  " [        R                  " U5      U5      Ul        UR                   mU4S jn[        R                  " [        R"                  " U5      U5      Ul        U$ )Nc                     > [         R                  R                  R                  5       n[         R                  R                  R	                  TU5      nU" U 0 UD6$ Nr   __internal__	autographcontrol_status_ctx
tf_convert)argsr"   control_statusag_update_stateobj_update_states       r$   update_state_fn'Metric.__new__.<locals>.update_state_fn   sL    !#!:!:!M!M!O"$//";";"F"F$n# '777r&   c                     > [         R                  R                  R                  5       n[         R                  R                  R	                  TU5      nU" U 0 UD6$ r)   r*   )r/   r"   r0   	ag_result
obj_results       r$   	result_fn!Metric.__new__.<locals>.result_fn   sL    __66IIKN11<<NI d-f--r&   )r   r   __new__r   is_in_eager_or_tf_functionis_built_inupdate_state
isinstancer   r+   functionFunctiontypes
MethodTyper   update_state_wrapperresultresult_wrapper)	clsr/   r"   objr3   r8   r7   r2   r#   s	         @@r$   r:   Metric.__new__}   s    FC(- 6688K<L<L"//8 #**BOO,D,D,M,MNN"%"2"2"$++c.>.>"? ++..?
 ZZ
	. %%((3S

 
r&   c                 H   ^  U 4S jnSSK Jn  UR                  " U/UQ70 UD6$ )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                    > [        S [        R                  R                  X45       5       5      (       a  SnOTR                  " U 0 UD6n/ nUb  UR                  U5        [        R                  " U5         TR                  5       n[        U[        5      (       a  [        S0 UD6nTUl        UsSSS5        $ ! , (       d  f       g= f)z;Updates the state of the metric in a replica-local context.c              3   V   #    U  H  n[        U[        R                  5      v   M!     g 7fr)   )r>   r   KerasTensor).0args     r$   	<genexpr><Metric.__call__.<locals>.replica_local_fn.<locals>.<genexpr>   s'      :C 3 8 899:s   ')Nr   )anyr   nestflattenr=   appendcontrol_dependenciesrD   r>   dict_MetricDict_metric_obj)r/   r"   	update_op
update_opsresult_tr!   s        r$   replica_local_fn)Metric.__call__.<locals>.replica_local_fn   s     77??D>:   !	 --t>v>	J$!!),((4;;=
 h--*6X6H (,$' 544s   89B;;
C	r   )distributed_training_utils)tf_keras.src.distributer^   call_replica_local_fn)r!   r/   r"   r\   r^   s   `    r$   __call__Metric.__call__   s6    	 B	
 *??
#
'-
 	
r&   c                     SR                  S U R                  5       R                  5        5       5      nU R                  R                   SU S3$ )N,c              3   4   #    U  H  u  pU S U 3v   M     g7f)=Nr   )rM   kvs      r$   rO   !Metric.__str__.<locals>.<genexpr>   s     I/Htq1#Qqc
/Hs   ())join
get_configitemsr#   __name__)r!   r/   s     r$   __str__Metric.__str__   sD    xxIt/@/F/F/HII..))*!D633r&   c                      U R                  U R                  5       5      nU R                  (       a  UR	                  U R                  5       5        X!U '   U$ ! [         a  n[        SU S35      eS nAff = f)NzCalling `__deepcopy__()` on a TF-Keras metric requires the metric to be serializable,  i.e. it should implement `get_config()`.

Error encountered during serialization: [])from_configrm   NotImplementedErrorweightsset_weightsget_weights)r!   memonew_selfes       r$   __deepcopy__Metric.__deepcopy__   s}    	''(9:H <<  !1!1!34T
 # 	%< =>3aA 	s   A 
A5!A00A5c                     U R                   $ r)   )r    r!   s    r$   r   Metric.dtype   s    {{r&   c                 4    U R                   U R                  S.$ )z.Returns the serializable config of the metric.r   r   r   s    r$   rm   Metric.get_config   s    		DJJ77r&   c                 8   [         R                  " U R                  5      (       d>  [        R                  " SU R
                  R                  < S3SS9  U R                  5       $ [        R                  " U R                   Vs/ s H  oS4PM     sn5        gs  snf )zResets all of the metric state variables.

This function is called between epochs/steps,
when a metric is evaluated during training.
Metric z 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.   )
stacklevelr   N)
r
   
is_defaultreset_stateswarningswarnr#   ro   r   batch_set_value	variablesr!   rh   s     r$   reset_stateMetric.reset_state   sw     ''(9(9::MM #'.."9"9<  $$&&##T^^$D^V^$DE$Ds   Bc                     [        S5      e)aa  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.
"Must be implemented in subclasses.ru   )r!   r/   r"   s      r$   r=   Metric.update_state  s    & ""FGGr&   c                 (   / nU H  n[        U R                  5      [        UR                  5      :w  a  [        SU SU  35      e[        U R                  UR                  5       H%  u  pEUR	                  UR                  U5      5        M'     M     U$ )a  Merges the state from one or more metrics.

This method can be used by distributed systems to merge the state
computed by different metric instances. Typically the state will be
stored in the form of the metric's weights. For example, a
tf.keras.metrics.Mean metric contains a list of two weight values: a
total and a count. If there were two instances of a
tf.keras.metrics.Accuracy that each independently aggregated partial
state for an overall accuracy calculation, these two metric's states
could be combined as follows:

>>> m1 = tf.keras.metrics.Accuracy()
>>> _ = m1.update_state([[1], [2]], [[0], [2]])

>>> m2 = tf.keras.metrics.Accuracy()
>>> _ = m2.update_state([[3], [4]], [[3], [4]])

>>> m2.merge_state([m1])
>>> m2.result().numpy()
0.75

Args:
  metrics: an iterable of metrics. The metrics must have compatible
    state.

Raises:
  ValueError: If the provided iterable does not contain metrics matching
    the metric's required specifications.
r   z is not compatible with )lenrv   
ValueErrorziprT   
assign_add)r!   metricsassign_add_opsmetricweightweight_to_adds         r$   merge_stateMetric.merge_state   s    < F4<< C$77 fX%=dVD  *-T\\6>>)J%%%f&7&7&FG *K  r&   c                     [        S5      e)zComputes and returns the scalar metric value tensor or a dict of
scalars.

Result computation is an idempotent operation that simply calculates the
metric value using the state variables.

Returns:
  A scalar tensor, or a dictionary of scalar tensors.
r   r   r   s    r$   rD   Metric.resultH  s     ""FGGr&   r   c                   > [         R                  R                  5       (       a  [         R                  R                  5       nOSn0 n[        R
                  " U5      (       a  [         R                  R                  n[        U SS5      bJ  S[        R                  R                  U R                  [         R                  " U5      R                  5      0n[        R                   " 5       (       a
   S	S jn	XS'   [        R"                  " U S9   [$        T
U ]L  " S
UUUc  U R(                  OUSU/ UUS.UD6sSSS5        $ ! , (       d  f       g= f)z0Adds state variable. Only for use by subclasses.N_meshlayoutc                     [         R                  " XU5      u  pESS/nU H  nUR                  US 5        M     SUS'   [        R                  " SUUUS.UD6$ )Nuse_resourcecollectionsF$experimental_enable_variable_lifting)initial_valuer   shaper   )r   infer_init_val_and_dtypepopr   Variable)initializerr   r   r"   init_val	var_dtypev1_only_argsv1_args           r$   local_v2_var_creator/Metric.add_weight.<locals>.local_v2_var_creatorz  st     '7&O&O'# !/>*FJJvt, +AF=>{{ "*# 	 r&   getter)layerF)r   r   r   	trainabler   r   synchronizationaggregation)NNNr   )r   
distributehas_strategyget_strategyr   is_tpu_strategyVariableSynchronizationON_WRITEgetattrdtensorLayout
replicatedr   TensorShaperankr   in_local_vars_contextmaybe_init_scoper   
add_weightr    )r!   r   r   r   r   r   r   strategyadditional_kwargsr   r#   s             r$   r   Metric.add_weightV  s    ==%%''}}113HH ""8,, 88AAO4$'3 '..33JJu 5 : :! ))++ 59" +?h'&&T27% 
%*]dkk' /'
 $
 322s   (D??
Ec                     U R                   (       a>  U R                  nU R                   H  nXR                  -  nM     U R	                  U5      $ / $ r)   )r   _trainable_weights_metricstrainable_weights_dedup_weights)r!   r   ms      r$   r   Metric.trainable_weights  sK     >> $ 7 7]]!%8%88! #&&'899Ir&   c                    U R                   (       a.  U R                  nU R                   H  nXR                  -  nM     O:U R                  U R                  -   nU R                   H  nXR
                  -  nM     U R                  U5      $ r)   )r   _non_trainable_weightsr   non_trainable_weightsr   rv   r   )r!   r   r   s      r$   r   Metric.non_trainable_weights  s~     >>$($?$?!]]%)@)@@% # ++d.E.EE " ]]%2% #""#899r&   c                 .    [         R                  " U 5      $ r)   )r	   MetricSavedModelSaverr   s    r$   _trackable_saved_model_saver#Metric._trackable_saved_model_saver  s    #99$??r&   c                 "    U R                  5       $ r)   )r   r   s    r$   r   Metric.reset_states  s    
 !!r&   )r    r   r   NNr)   )$ro   
__module____qualname____firstlineno____doc__r   r:   ra   rp   r|   propertyr   rm   r   abcabstractmethodr=   r   rD   r   for_subclass_implementersr   VariableAggregationSUMr   ON_READr   r   r   r   r
   defaultdo_not_generate_docsr   __static_attributes____classcell__r#   s   @r$   r   r   )   s.   EN	(T3
j4"  8F$ 	H H(&P 	
H 
H ++ **..22::A ,AJ   : : @ @ &&" ' "r&   r   )	metaclassc                   @   ^  \ rS rSrSrSU 4S jjrSS jrS rSrU =r	$ )Reducei  zEncapsulates 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.
c                    > [         TU ]  X#S9  Xl        U R                  SSS9U l        U[
        R                  R                  [
        R                  R                  4;   a  U R                  SSS9U l	        g g )Nr   totalzeros)r   count)
r   r   	reductionr   r   r   	ReductionSUM_OVER_BATCH_SIZEWEIGHTED_MEANr   )r!   r   r   r   r#   s       r$   r   Reduce.__init__  sr    d0"__W'_B
##77##11
 
 gFDJ	
r&   c           
         [         R                  " U/U5      u  u  nn [        R                  " XR                  5      nUbx  [        R                  " X R                  5      n[        R                  " XS9u  nnn [        R                  R                  R                  X!5      n[        R0                  " X5      n[        R(                  " U5      n[        R2                  " U/5         U R4                  R7                  U5      nSSS5        U R"                  [         R$                  R&                  :X  a  W$ U R"                  [         R$                  R8                  :X  a6  [        R                  " [        R:                  " U5      U R                  5      n	OU R"                  [         R$                  R<                  :X  aP  Uc6  [        R                  " [        R:                  " U5      U R                  5      n	O0[        R(                  " U5      n	O[?        SU R"                   S35      e[        R2                  " W/5         U R@                  R7                  U	5      sSSS5        $ ! [
        [        4 a,    SU S3n[        U[        5      (       a  US-  n[        U5      ef = f! [
         a    [        R                   " U5      n[        R                   " U5      nU R"                  [         R$                  R&                  :X  a*  [        R(                  " U[+        [-        Xe5      5      S9n GN[        R.                  " U[+        [-        Xe5      5      S9n GNf = f! , (       d  f       GNY= f! , (       d  f       g= f)	zAccumulates statistics for computing the metric.

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

Returns:
  Update op.
zGThe output of a metric function can only be a single Tensor. Received: z. z?To return a dict of values, implement a custom Metric subclass.Nsample_weightaxisReduction "M" not implemented. Expected "sum", "weighted_mean", or "sum_over_batch_size".)!r   ,ragged_assert_compatible_and_get_flat_valuesr   castr    r   	TypeErrorr>   rV   RuntimeErrorr   squeeze_or_expand_dimensionsr+   opsbroadcast_weightsr   ndimr   r   r   
reduce_sumlistrangereduce_meanmultiplyrU   r   r   r   sizer   ru   r   )
r!   valuesr   msg_r  weight_ndim	value_sumupdate_total_op
num_valuess
             r$   r=   Reduce.update_state  s    )UUHm
	 	
	$WWV[[1F $GGM;;?M 99	 " 3 3 E E!! [[7FMM&)	$$i[1"jj33I>O 2 >>]44888"" >>]44HHH$++>J^^}66DDD$WWRWWV_dkkB
]]=9
%dnn- .D D 
 $$o%67::((4 87} I& 
	$#HB(  &$''  s##
	$4  ||F+%ll=9>>]%<%<%@%@@]]T%*B%CF  ^^T%*B%CF 21* 87s<    I  ;)J 'M;M' <JBM''MM
M$'
M5c                    U R                   [        R                  R                  :X  a   [        R
                  " U R                  5      $ U R                   [        R                  R                  [        R                  R                  4;   a4  [        R                  R                  U R                  U R                  5      $ [        SU R                    S35      e)Nr   r   )r   r   r   r   r   identityr   r   r   mathdivide_no_nanr   ru   r   s    r$   rD   Reduce.result'  s    >>]44888;;tzz**^^##11##77 
 
 77((TZZ@@%dnn- .D D r&   )r   r   r   r)   )
ro   r   r   r   r   r   r=   rD   r   r   r   s   @r$   r   r     s    GP5d r&   r   zkeras.metrics.Sumc                   N   ^  \ rS rSrSr\R                  SU 4S jj5       rSrU =r	$ )Sumi6  a	  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')
```
c                 R   > [         TU ]  [        R                  R                  XS9  g N)r   r   r   )r   r   r   r   r   r!   r   r   r#   s      r$   r   Sum.__init__V  s&    #--11 	 	
r&   r   )sumN
ro   r   r   r   r   dtensor_utilsinject_meshr   r   r   r   s   @r$   r  r  6  s"    < 
 
r&   r  zkeras.metrics.Meanc                   N   ^  \ rS rSrSr\R                  SU 4S jj5       rSrU =r	$ )Meani]  a  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')
```
c                 T   > [         TU ]  [        R                  R                  UUS9  g r  )r   r   r   r   r   r   s      r$   r   Mean.__init__  s*    #--;; 	 	
r&   r   )meanNr#  r   s   @r$   r'  r'  ]  s#    "H 
 
r&   r'  zkeras.metrics.MeanMetricWrapperc                      ^  \ rS rSrSr\R                  SU 4S jj5       rS	U 4S jjrU 4S jr	\
U 4S j5       rSrU =r$ )
MeanMetricWrapperi  a-  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`.
c                 8   > [         TU ]  X#S9  Xl        X@l        g )Nr   r   r   _fn
_fn_kwargsr!   fnr   r   r"   r#   s        r$   r   MeanMetricWrapper.__init__  s    d0 r&   c                 R  > [         R                  " XR                  5      n[         R                  " X R                  5      n[        R                  " X/U5      u  u  nnn[
        R                  " X!5      u  p![         R                  R                  R                  U R                  [         R                  R                  R                  5       5      nU" X40 U R                  D6n[
        R                  " U5      n[
        R                  " XSX`R                  5      n[         TU ]E  XSS9$ )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  r    r   r  r   r  r+   r,   r.   r/  r-   r0  get_maskapply_valid_maskr   r   r=   r!   y_truey_predr   ag_fnmatchesmaskr#   s          r$   r=   MeanMetricWrapper.update_state  s    , -- )UUm
	 	
 &BB
 ))44HHboo//BBD
 :$//:$$W-$55D..
 w#G#IIr&   c                   > U R                   R                  5        VVs0 s H9  u  pU[        R                  " U5      (       a  [        R
                  " U5      OU_M;     nnn[        U 5      [        L a  U R                  US'   [        TU ])  5       n[        [        UR                  5       5      [        UR                  5       5      -   5      $ s  snnf )Nr2  )r0  rn   r   is_tensor_or_variabler   evaltyper,  r/  r   rm   rV   r
  r!   rg   rh   configbase_configr#   s        r$   rm   MeanMetricWrapper.get_config  s     --/
/ ("@"@"C"Cw||AJ/ 	 

 :**  88F4Lg(*D**,-V\\^0DDEE
s   A Cc                    > SSK Jn  UR                  SS 5      nU [        L a  U " U" U5      40 UD6$ [        [        U ]  U5      $ )Nr   )getr2  )tf_keras.src.metricsrG  r   r,  r   rt   )rF   rC  rG  r2  r#   s       r$   rt   MeanMetricWrapper.from_config  sH    , ZZd###s2w)&))&8@@r&   r/  r0  r   r)   )ro   r   r   r   r   r$  r%  r   r=   rm   classmethodrt   r   r   r   s   @r$   r,  r,    sE    4 ! !
*JXF A Ar&   r,  zkeras.metrics.MeanTensorc                      ^  \ rS rSrSr\R                  SU 4S jj5       rS r\	S 5       r
\	S 5       rSS jrS rS	 rS
rU =r$ )
MeanTensori  a  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.]])
c                    > [         TU ]  XS9  S U l        S U l        S U l        SU l        Ub  U R                  U5        g g )Nr   F)r   r   _shape_total_count_built_build)r!   r   r   r   r#   s       r$   r   MeanTensor.__init__  sF    d0KK r&   c                    [         R                  " U5      U l        U R                  U l        U R	                  SUSS9U l        U R	                  SUSS9U l        [         R                  " 5          [         R                  " 5       (       d)  [        R                  " [        R                  " 5       5        S S S 5        SU l        g ! , (       d  f       N= f)Nr   r   )r   r   r   r   T)r   r   rO  _build_input_shaper   rP  rQ  
init_scopeexecuting_eagerlyr   _initialize_variables_get_sessionrR  )r!   r   s     r$   rS  MeanTensor._build#  s    nnU+"&++oo7 & 
 oo7 & 
 ]]_''))--g.B.B.DE   _s   .AC
Cc                 @    U R                   (       a  U R                  $ S $ r)   )rR  rP  r   s    r$   r   MeanTensor.total2      "kkt{{3t3r&   c                 @    U R                   (       a  U R                  $ S $ r)   )rR  rQ  r   s    r$   r   MeanTensor.count6  r^  r&   c           
          [         R                  " XR                  5      nU R                  (       d  U R	                  UR
                  5        O@UR
                  U R                  :w  a&  [        SU R                   SUR
                   S35      e[         R                  " U5      nUb  [         R                  " X R                  5      n[        R                  " XS9u  nnn [         R                  R                  R                  X!5      n[         R&                  " X25      n[         R&                  " X5      nU R(                  R+                  U5      n[         R,                  " U/5         U R.                  R+                  U5      sSSS5        $ ! [         aV    [        R                  " U5      n[        R                  " U5      n[         R                   " U[#        [%        Xe5      5      S9n Nf = f! , (       d  f       g= f)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.
zeMeanTensor input values must always have the same shape. Expected shape (set during the first call): z. Got: .Nr   r   )r   r  r    rR  rS  r   rO  r   	ones_liker   r  r+   r  r  r   r  r  r
  r  r  rP  r   rU   rQ  )r!   r  r   r  r  r  r  r  s           r$   r=   MeanTensor.update_state:  s    -{{KK%\\T[[(F;;-  ~Q(  \\&)
$GGM;;?M 99	 " 3 3 E E!! Z?J[[7F++008$$o%67;;))*5 87  ||F+%ll=9eK&>!?	 87s    )F 'G/AG,+G,/
G=c                     U R                   (       d  [        S5      e[        R                  R	                  U R
                  U R                  5      $ )NzMeanTensor does not have any value yet. Please call the MeanTensor instance or use `.update_state(value)` before retrieving the result.)rR  r   r   r  r  r   r   r   s    r$   rD   MeanTensor.resulto  s<    {{0 
 ww$$TZZ<<r&   c           
          U R                   (       a_  [        R                  " U R                   Vs/ s H2  o[        R
                  " UR                  R                  5       5      4PM4     sn5        g g s  snf r)   )rR  r   r   r   npr   r   as_listr   s     r$   r   MeanTensor.reset_statex  sL    ;;##;?>>J>aRXXaggoo/01>J Js   9A2)rV  rR  rQ  rO  rP  )mean_tensorNNr)   )ro   r   r   r   r   r$  r%  r   rS  r   r   r   r=   rD   r   r   r   r   s   @r$   rM  rM    se    !F   4 4 4 436j= r&   rM  c                   0   ^  \ rS rSrSrSU 4S jjrSrU =r$ )SumOverBatchSizei  a  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.
c                 T   > [         TU ]  [        R                  R                  UUS9  g r  )r   r   r   r   r   r   s      r$   r   SumOverBatchSize.__init__  s*    #--AA 	 	
r&   r   )sum_over_batch_sizeNro   r   r   r   r   r   r   r   r   s   @r$   rm  rm    s    
 
r&   rm  c                   L   ^  \ rS rSrSrSU 4S jjrSU 4S jjrU 4S jrSrU =r	$ )	SumOverBatchSizeMetricWrapperi  zAWraps a function with the `SumOverBatchSizeMetricWrapper` metric.c                 8   > [         TU ]  X#S9  Xl        X@l        g)a:  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`.
r   Nr.  r1  s        r$   r   &SumOverBatchSizeMetricWrapper.__init__  s     	d0 r&   c                   > [         R                  " XR                  5      n[         R                  " X R                  5      n[        R                  " X!5      u  p![         R
                  R                  R                  U R                  [         R
                  R                  R                  5       5      nU" X40 U R                  D6n[        R                  " U5      n[        R                  " XSX`R                  5      n[        TU ]=  XSS9$ )Nr   )r   r  r    r   r  r+   r,   r.   r/  r-   r0  r5  r6  r   r   r=   r7  s          r$   r=   *SumOverBatchSizeMetricWrapper.update_state  s    --%BB
 ))44HHboo//BBD
 :$//:$$W-$55D..
 w#G#IIr&   c                 d  > U R                   R                  5        VVs0 s H9  u  pU[        R                  " U5      (       a  [        R
                  " U5      OU_M;     nnn[        TU ]  5       n[        [        UR                  5       5      [        UR                  5       5      -   5      $ s  snnf r)   )
r0  rn   r   r?  r   r@  r   rm   rV   r
  rB  s        r$   rm   (SumOverBatchSizeMetricWrapper.get_config  s     --/
/ ("@"@"C"Cw||AJ/ 	 
 g(*D**,-V\\^0DDEE
s   A B,rJ  r   r)   )
ro   r   r   r   r   r   r=   rm   r   r   r   s   @r$   rs  rs    s    K!J"F Fr&   rs  c                 j   [        U [        5      (       a  [        R                  " 5       (       a)  U R                  R                  U R                  5       5      $ [        R                  " 5          U R                  R                  U R                  5       5      sSSS5        $ U $ ! , (       d  f       U $ = f)zFReturns a clone of the metric if stateful, otherwise returns it as is.N)	r>   r   r   r   r#   rt   rm   r   rW  )r   s    r$   clone_metricr{    s    &&!! ))++##//0A0A0CDD''33F4E4E4GH !M !Ms   .)B##
B2c                 J    [         R                  R                  [        U 5      $ )z"Clones the given metric list/dict.)r   rR   map_structurer{  )r   s    r$   clone_metricsr~    s    77  w77r&   c                     U R                   R                  SR                  [        R                   R	                  S5      S S 5      5      $ )Nrb  )r   
startswithrl   r   split)rF   s    r$   r<   r<     s=    >>$$""((-cr23 r&   c                   ,   ^  \ rS rSrSrU 4S jrSrU =r$ )rW   i  z+Wrapper for returned dictionary of metrics.c                 4   > [         TU ]  " S0 UD6  S U l        g )Nr   )r   r   rX   )r!   r"   r#   s     r$   r   _MetricDict.__init__  s    "6"r&   )rX   rq  r   s   @r$   rW   rW     s    5   r&   rW   )/r   r   rA   r   numpyrh  tensorflow.compat.v2compatv2r   tf_keras.srcr   tf_keras.src.dtensorr   r   r   r$  tf_keras.src.enginer   r   r   &tf_keras.src.saving.legacy.saved_modelr	   tf_keras.src.utilsr
   r   r   r    tensorflow.python.util.tf_exportr   tensorflow.tools.docsr   LayerABCMetar   r   r  r'  r,  rM  rm  rs  r{  r~  r<   rV   rW   r   r&   r$   <module>r     sM    
    ! !   7 7 * 0 , G , + , ' : . $%U"Z U" &U"pqV qh !"#
& #
 ##
L "#+
6 +
 $+
\ /0dA dA 1dAN ()G G *GT
v 
.(F$4 (FV 8
 $  r&   