
    AVhn&                        d 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Zd Zej&                  d        Z edg      ej*                  j,                  fd       Z edg      dej*                  j,                  fd       Z edg      dd       Z edg      dd       Z edg      	 	 	 dd       Zy) z0Utilities for manipulating the loss collections.    )context)constant_op)dtypes)ops)	array_ops)	check_opscond)confusion_matrix)math_ops)tf_contextlib)	tf_exportNc                      j                   }|j                  }ىj                   }|j                  }|,|*||z
  dk7  s|d   dk(  rt        j                         \   nt	        j
                         t	        j
                        z
   fdt        j                  dt	        j                          d          fd}t        j                  t        j                  d      |      \    fS j                   }|j                  }	|	dk(  r fS |F|	D|	|z
  dk(  rt	        j                  dg      n||	z
  dk(  rt	        j                  dg       fS t	        j
                        }
|
t	        j
                         z
  fdfdfd}t        j                  t        j                  |
d      fd	|       fS )
a  Squeeze or expand last dimension if needed.

  1. Squeezes last dim of `y_pred` or `y_true` if their rank differs by 1
  (using `confusion_matrix.remove_squeezable_dimensions`).
  2. Squeezes or expands last dim of `sample_weight` if its rank differs by 1
  from the new rank of `y_pred`.
  If `sample_weight` is scalar, it is kept scalar.

  This will use static shape if available. Otherwise, it will add graph
  operations, which could result in a performance hit.

  Args:
    y_pred: Predicted values, a `Tensor` of arbitrary dimensions.
    y_true: Optional label `Tensor` whose dimensions match `y_pred`.
    sample_weight: Optional weight scalar or `Tensor` whose dimensions match
      `y_pred`.

  Returns:
    Tuple of `y_pred`, `y_true` and `sample_weight`. Each of them possibly has
    the last dimension squeezed,
    `sample_weight` could be extended by one dimension.
    If `sample_weight` is None, (y_pred, y_true) is returned.
     c                  0    t        j                         S N)r   remove_squeezable_dimensionsy_predy_trues   Q/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/ops/losses/util.py<lambda>z.squeeze_or_expand_dimensions.<locals>.<lambda>H   s    -JJ
&     c                  :    t        j                    fd      S )Nc                       fS r    r   s   r   r   z@squeeze_or_expand_dimensions.<locals>.<lambda>.<locals>.<lambda>L   s    /? r   r	   )is_last_dim_1squeeze_dimsr   r   s   r   r   z.squeeze_or_expand_dimensions.<locals>.<lambda>K   s    499
'?$A r   r   c                  2    t        j                   dg      S Nr   )r   squeezesample_weights   r   r   z.squeeze_or_expand_dimensions.<locals>.<lambda>c   s    )"3"3MB4"H r   c                  j    fd} t        j                   t        j                  d      | fd      S )Nc                  2    t        j                   dg      S r!   )r   expand_dimsr#   s   r   r   zMsqueeze_or_expand_dimensions.<locals>._maybe_expand_weights.<locals>.<lambda>f   s    Y22=2$G r   r   c                       S r   r   r#   s   r   r   zMsqueeze_or_expand_dimensions.<locals>._maybe_expand_weights.<locals>.<lambda>h   s    } r   r
   r   equal)expand_weights	rank_diffr$   s    r   _maybe_expand_weightsz;squeeze_or_expand_dimensions.<locals>._maybe_expand_weightse   s.    GN99y"%~7LN Nr   c                  Z    t        j                   t        j                  d             S )Nr   r)   )r-   maybe_squeeze_weightsr,   s   r   _maybe_adjust_weightsz;squeeze_or_expand_dimensions.<locals>._maybe_adjust_weightsj   s(    99y!$&; r   c                       S r   r   r#   s   r   r   z.squeeze_or_expand_dimensions.<locals>.<lambda>r   s    m r   )shapendimsr   r   r   rankr   r*   r
   r"   r'   )r   r   r$   y_pred_shapey_pred_ranky_true_shapey_true_rankmaybe_squeeze_dimsweights_shapeweights_rankweights_rank_tensorr0   r-   r   r/   r,   r   s   ```         @@@@@r   squeeze_or_expand_dimensionsr=      s   0 ,""+ <<L$$Kk&=

#q
(\"-=-B)FFF ..(9>>&+AAilnnQ	(?(CDmAyy
..I
&(:LJnff 6>%%-$$,Q6=((L$<k!Q&''t<m	|	#q	(++MB4@m6=(( "}5!INN6$::)HN
 ))nn(!,.C- 
	&&r   c                     t        j                  | t        j                        } t        j                  |t        j                        }t	        | d|      \  } }}t        j
                  | |      S )aH  Scales loss values by the given sample weights.

  `sample_weight` dimensions are updated to match with the dimension of `losses`
  if possible by using squeeze/expand/broadcast.

  Args:
    losses: Loss tensor.
    sample_weight: Sample weights tensor.

  Returns:
    `losses` scaled by `sample_weight` with dtype float32.
  N)r   castr   float32r=   multiply)lossesr$   _s      r   scale_losses_by_sample_weightrD   w   sY     ==0&--v~~>- :dM#&!]			6=	11r   c           	   #   h  K   | j                   j                  }||dk(  rt        d|  d|       d yt        j                  t        j                  t        j                  |       t        j                  dt        j                        d      g      5  d ddd       y# 1 sw Y   yxY ww)	zContext manager that checks that the rank of per_example_loss is at least 1.

  Args:
    per_example_loss: Per example loss tensor.

  Yields:
    A context manager.
  Nr   zoInvalid value passed for `per_example_loss`. Expected a tensor with at least rank 1. Received per_example_loss=z with rank r   )dtypezTInvalid value passed for `per_example_loss`. Expected a tensor with at least rank 1.)message)r2   r4   
ValueErrorr   control_dependenciesr   assert_greater_equalr   r   r?   r   int32)per_example_loss	loss_ranks     r   check_per_example_loss_rankrN      s      $$)))A~88H7I J  
 
	!	!&&NN+,MM!6<<0+	,# 
    s   BB2B&	B2&B/+B2zlosses.add_loss)v1c                 `    |r,t        j                         st        j                  ||        yyy)zAdds a externally defined loss to the collection of losses.

  Args:
    loss: A loss `Tensor`.
    loss_collection: Optional collection to add the loss to.
  N)r   executing_eagerlyr   add_to_collection)lossloss_collections     r   add_lossrU      s)     W668/40 9_r   zlosses.get_lossesc                 .    t        j                  ||       S )zGets the list of losses from the loss_collection.

  Args:
    scope: An optional scope name for filtering the losses to return.
    loss_collection: Optional losses collection.

  Returns:
    a list of loss tensors.
  )r   get_collection)scoperT   s     r   
get_lossesrY      s     
		OU	33r   z losses.get_regularization_lossesc                 ^    t        j                  t         j                  j                  |       S )zGets the list of regularization losses.

  Args:
    scope: An optional scope name for filtering the losses to return.

  Returns:
    A list of regularization losses as Tensors.
  )r   rW   	GraphKeysREGULARIZATION_LOSSESrX   s    r   get_regularization_lossesr^      s!     
		CMM??	GGr   zlosses.get_regularization_lossc                 t    t        |       }|rt        j                  ||      S t        j                  d      S )zGets the total regularization loss.

  Args:
    scope: An optional scope name for filtering the losses to return.
    name: The name of the returned tensor.

  Returns:
    A scalar regularization loss.
  nameg        )r^   r   add_nr   constant)rX   ra   rB   s      r   get_regularization_lossrd      s3     %U+&>>&t,,$$r   zlosses.get_total_lossc                 j    t        |      }| r|t        |      z  }t        j                  ||      S )a~  Returns a tensor whose value represents the total loss.

  In particular, this adds any losses you have added with `tf.add_loss()` to
  any regularization losses that have been added by regularization parameters
  on layers constructors e.g. `tf.layers`. Be very sure to use this if you
  are constructing a loss_op manually. Otherwise regularization arguments
  on `tf.layers` methods will not function.

  Args:
    add_regularization_losses: A boolean indicating whether or not to use the
      regularization losses in the sum.
    name: The name of the returned tensor.
    scope: An optional scope name for filtering the losses to return. Note that
      this filters the losses added with `tf.add_loss()` as well as the
      regularization losses to that scope.

  Returns:
    A `Tensor` whose value represents the total loss.

  Raises:
    ValueError: if `losses` is not iterable.
  r]   r`   )rY   r^   r   rb   )add_regularization_lossesra   rX   rB   s       r   get_total_lossrg      s2    4 E"&
'e44F	T	**r   )NNr   )Ntotal_regularization_loss)T
total_lossN)__doc__tensorflow.python.eagerr   tensorflow.python.frameworkr   r   r   tensorflow.python.opsr   r   r
   r   r   tensorflow.python.utilr    tensorflow.python.util.tf_exportr   r=   rD   contextmanagerrN   r[   LOSSESrU   rY   r^   rd   rg   r   r   r   <module>rr      s	   7 + 3 . + + + & 2 * 0 6V'r20  <  !"#&==#7#7 1 #1 "#$3==+?+? 
4 %
4 123	H 4	H /01% 2%" &'(-1$+ )+r   