
    BVh+                        d Z ddlZddlZddlmZ ddlmZ ddlmZ ddlmZ ddlm	Z	 ddlm
Z
 dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ d Zd Z G d dej*                        Z G d dej*                        Z	 	 	 	 	 	 	 	 ddZy)z?Contains functions for evaluation and summarization of metrics.    N)dtypes)ops)	array_ops)init_ops)math_ops)	state_ops)variable_scope)
tf_logging)basic_session_run_hooks)monitored_session)session_run_hookc            	         t        j                         } | j                  t         j                  j                        }t        |      dk(  r|d   S t        |      dkD  rt        d      t        j                  dg t        j                  t        j                         dt         j                  j                  t         j                  j                  g      }|S )zGets or creates the eval step `Tensor`.

  Returns:
    A `Tensor` representing a counter for the evaluation step.

  Raises:
    ValueError: If multiple `Tensors` have been added to the
      `tf.GraphKeys.EVAL_STEP` collection.
     r   z0Multiple tensors added to tf.GraphKeys.EVAL_STEP	eval_stepF)shapedtypeinitializer	trainablecollections)r   get_default_graphget_collection	GraphKeys	EVAL_STEPlen
ValueErrorr	   get_variabler   int64r   zeros_initializerLOCAL_VARIABLES)graph
eval_stepscounters      U/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/training/evaluation.py_get_or_create_eval_stepr$   !   s     


!%##CMM$;$;<*_a=
:
G
HH))ll..0]]22CMM4K4KLNG N    c                     t        | t              rt        | j                               } t	        j
                  |       5  t        j                  t               j                               cddd       S # 1 sw Y   yxY w)a  Gets the eval step `Tensor` value after running `update_ops`.

  Args:
    update_ops: A list of `Tensors` or a dictionary of names to `Tensors`, which
      are run before reading the eval step value.

  Returns:
    A `Tensor` representing the value for the evaluation step.
  N)

isinstancedictlistvaluesr   control_dependenciesr   identityr$   
read_value)
update_opss    r#   _get_latest_eval_step_valuer/   <   sc     
D!j'')*J

+ G68CCEFG G Gs   +A44A=c                   6    e Zd ZdZd	dZd Zd Zd Zd Zd Z	y)
_MultiStepStopAfterNEvalsHookGRun hook used by the evaluation routines to run the `eval_ops` N times.c                 .    || _         d| _        || _        y)zConstructs the run hook.

    Args:
      num_evals: The number of evaluations to run for. if set to None, will
        iterate the dataset until all inputs are exhausted.
      steps_per_run: Number of steps executed per run call.
    N)
_num_evals_evals_completed_steps_per_run_initial_value)self	num_evalssteps_per_runs      r#   __init__z&_MultiStepStopAfterNEvalsHook.__init__P   s      DO D(5D%r%   c                     || _         y Nr5   r7   updated_eval_steps     r#   _set_evals_completed_tensorz9_MultiStepStopAfterNEvalsHook._set_evals_completed_tensor\   
    -Dr%   c                 6    t        j                         | _        y r<   )r   $get_or_create_steps_per_run_variable_steps_per_run_variable)r7   s    r#   beginz#_MultiStepStopAfterNEvalsHook.begin_   s    DDF 	 r%   c                     | j                   | j                  }n t        | j                  | j                         }| j                  j	                  ||       y )Nsession)r4   r6   minrD   load)r7   rH   coordstepss       r#   after_create_sessionz2_MultiStepStopAfterNEvalsHook.after_create_sessionc   sF    //e$33T__Ee  %%eW%=r%   c                 D    t        j                  d| j                  i      S Nevals_completedr   SessionRunArgsr5   r7   run_contexts     r#   
before_runz(_MultiStepStopAfterNEvalsHook.before_runk   #    **	D1124 4r%   c                    |j                   d   }| j                  | j                  }n#t        | j                  |z
  | j                        }| j                  j                  ||j                         | j                  t        j                  d|       n!t        j                  d|| j                         | j                  !|| j                  k\  r|j                          y y y )NrP   rG   Evaluation [%d]Evaluation [%d/%d])
resultsr4   r6   rI   rD   rJ   rH   logginginforequest_stop)r7   rT   
run_valuesrP   rL   s        r#   	after_runz'_MultiStepStopAfterNEvalsHook.after_runo   s     (():;O//e$//O3335e  %%e[5H5H%Ill$o6ll'$//J"$//'I  (J"r%   N)r   )
__name__
__module____qualname____doc__r:   r@   rE   rM   rU   r_    r%   r#   r1   r1   M   s$    O
6.G>4!r%   r1   c                   *    e Zd ZdZddZd Zd Zd Zy)_StopAfterNEvalsHookr2   c                     || _         d| _        || _        ||dk  rd| _        yt        j                  |dz        | _        y)zConstructs the run hook.

    Args:
      num_evals: The number of evaluations to run for. if set to None, will
        iterate the dataset until all inputs are exhausted.
      log_progress: Whether to log evaluation progress, defaults to True.
    N   r   g      $@)r4   r5   _log_progressmathfloor_log_frequency)r7   r8   log_progresss      r#   r:   z_StopAfterNEvalsHook.__init__   sF      DO D%D!*!2i"n1D::i#o6 	r%   c                     || _         y r<   r=   r>   s     r#   r@   z0_StopAfterNEvalsHook._set_evals_completed_tensor   rA   r%   c                 D    t        j                  d| j                  i      S rO   rQ   rS   s     r#   rU   z_StopAfterNEvalsHook.before_run   rV   r%   c                 ^   |j                   d   }| j                  re| j                  t        j                  d|       nB|| j
                  z  dk(  s| j                  |k(  r!t        j                  d|| j                         | j                  !|| j                  k\  r|j                          y y y )NrP   rX   r   rY   )rZ   ri   r4   r[   r\   rl   r]   )r7   rT   r^   rP   s       r#   r_   z_StopAfterNEvalsHook.after_run   s     (():;O		 &8t222q8__/
,,+_doo
N"$//'I  (J"r%   N)T)r`   ra   rb   rc   r:   r@   rU   r_   rd   r%   r#   rf   rf      s    O8 .4
!r%   rf   c	                    t               }	t        |xs g       }|t        d |D              rLt        j                         }
t        j                  |	t        j                  |
|	j                        d      }nt        j                  |	dd      }t        |t              r||d<   n*t        |t        t        f      rt        |      |gz   }n||g}t        |      }|D ]*  }t        |t        t        f      s|j!                  |       , t#        j$                  dt'        j(                  d	t'        j*                               z          t'        j&                         }t-        j.                  || ||
      }t        j0                  ||      }|j3                  |       t-        j4                  ||      5 }|3|j7                         s#|j9                  ||       |j7                         s#ddd       t#        j$                  dj;                  t'        j&                         |z
               t#        j$                  dt'        j(                  dt'        j*                               z          |j<                  S # 1 sw Y   xY w)ay	  Evaluates the model at the given checkpoint path.

  During a single evaluation, the `eval_ops` is run until the session is
  interrupted or requested to finish. This is typically requested via a
  `tf.contrib.training.StopAfterNEvalsHook` which results in `eval_ops` running
  the requested number of times.

  Optionally, a user can pass in `final_ops`, a single `Tensor`, a list of
  `Tensors` or a dictionary from names to `Tensors`. The `final_ops` is
  evaluated a single time after `eval_ops` has finished running and the fetched
  values of `final_ops` are returned. If `final_ops` is left as `None`, then
  `None` is returned.

  One may also consider using a `tf.contrib.training.SummaryAtEndHook` to record
  summaries after the `eval_ops` have run. If `eval_ops` is `None`, the
  summaries run immediately after the model checkpoint has been restored.

  Note that `evaluate_once` creates a local variable used to track the number of
  evaluations run via `tf.contrib.training.get_or_create_eval_step`.
  Consequently, if a custom local init op is provided via a `scaffold`, the
  caller should ensure that the local init op also initializes the eval step.

  Args:
    checkpoint_path: The path to a checkpoint to use for evaluation.
    master: The BNS address of the TensorFlow master.
    scaffold: An tf.compat.v1.train.Scaffold instance for initializing variables
      and restoring variables. Note that `scaffold.init_fn` is used by the
      function to restore the checkpoint. If you supply a custom init_fn, then
      it must also take care of restoring the model from its checkpoint.
    eval_ops: A single `Tensor`, a list of `Tensors` or a dictionary of names to
      `Tensors`, which is run until the session is requested to stop, commonly
      done by a `tf.contrib.training.StopAfterNEvalsHook`.
    feed_dict: The feed dictionary to use when executing the `eval_ops`.
    final_ops: A single `Tensor`, a list of `Tensors` or a dictionary of names
      to `Tensors`.
    final_ops_feed_dict: A feed dictionary to use when evaluating `final_ops`.
    hooks: List of `tf.estimator.SessionRunHook` callbacks which are run inside
      the evaluation loop.
    config: An instance of `tf.compat.v1.ConfigProto` that will be used to
      configure the `Session`. If left as `None`, the default will be used.

  Returns:
    The fetched values of `final_ops` or `None` if `final_ops` is `None`.
  Nc              3   <   K   | ]  }t        |t                y wr<   )r'   r1   ).0hs     r#   	<genexpr>z!_evaluate_once.<locals>.<genexpr>   s     
GA:a67
Gs   )r   T)use_lockingr   update_eval_stepzStarting evaluation at z%Y-%m-%dT%H:%M:%S)scaffoldcheckpoint_filename_with_pathmasterconfig)session_creatorhookszInference Time : {:0.5f}szFinished evaluation at z%Y-%m-%d-%H:%M:%S)r$   r)   anyr   rC   r   
assign_addr   castr   r'   r(   tupler/   rf   r1   r@   r[   r\   timestrftime	localtimer   ChiefSessionCreatorFinalOpsHookappendMonitoredSessionshould_stoprunformatfinal_ops_values)checkpoint_pathrz   rx   eval_ops	feed_dict	final_opsfinal_ops_feed_dictr}   r{   r   steps_per_run_variablerw   eval_step_valuert   startr|   final_ops_hookrH   s                     r#   _evaluate_oncer      s*   j '() u{
%

G
GG
!
F
F
H "--

--.ioo
F
 #--iM(D!%5h!"	Hudm	,h#3"44h,-h1(;O 7	A,.KL	M	%%o67 
,,(}}0$..2BCD E
))+%%99$3	/ +77	8KM.,,~))%U4 )7>##%Hi( ##%)
 
,,*11$))+2EFG	,,(}}0$..2BCD E		(	(() )s   55I66I?) NNNNNNN)rc   rj   r   tensorflow.python.frameworkr   r   tensorflow.python.opsr   r   r   r   r	   tensorflow.python.platformr
   r[   tensorflow.python.trainingr   r   r   r$   r/   SessionRunHookr1   rf   r   rd   r%   r#   <module>r      s    F   . + + * * + 0 < > 8 76G"1!$4$C$C 1!h$!+:: $!P   !!'+i)r%   