a
    [=ic+                     @   s   d Z ddlZddlZddlmZ ddlmZ ddlmZ ddlmZ ddlm	Z	 ddlm
Z
 dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ dd Zdd ZG dd dejZG dd dejZdddZdS )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                  C   sp   t  } | t jj}t|dkr*|d S t|dkr@tdn,tjdg t	j
t dt jjt jjgd}|S d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dtypeZinitializerZ	trainablecollectionsN)r   Zget_default_graphZget_collectionZ	GraphKeysZ	EVAL_STEPlen
ValueErrorr   Zget_variabler   int64r   Zzeros_initializerZLOCAL_VARIABLES)graphZ
eval_stepscounter r   v/home/droni/.local/share/virtualenvs/DPS-5Je3_V2c/lib/python3.9/site-packages/tensorflow/python/training/evaluation.py_get_or_create_eval_step!   s    

r   c                 C   sT   t | trt|  } t|   tt 	 W  d   S 1 sF0    Y  dS )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   Zcontrol_dependenciesr   identityr   Z
read_value)Z
update_opsr   r   r   _get_latest_eval_step_value<   s    

r   c                   @   sB   e Zd ZdZdddZdd Zdd Zd	d
 Zdd Zdd Z	dS )_MultiStepStopAfterNEvalsHookGRun hook used by the evaluation routines to run the `eval_ops` N times.r   c                 C   s   || _ d| _|| _dS )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_evalsZsteps_per_runr   r   r   __init__P   s    z&_MultiStepStopAfterNEvalsHook.__init__c                 C   s
   || _ d S Nr#   r%   Zupdated_eval_stepr   r   r   _set_evals_completed_tensor\   s    z9_MultiStepStopAfterNEvalsHook._set_evals_completed_tensorc                 C   s   t  | _d S r(   )r
   $get_or_create_steps_per_run_variable_steps_per_run_variable)r%   r   r   r   begin_   s    z#_MultiStepStopAfterNEvalsHook.beginc                 C   s4   | j d u r| j}nt| j| j }| jj||d d S )Nsession)r"   r$   minr-   load)r%   r0   Zcoordstepsr   r   r   after_create_sessionc   s    
z2_MultiStepStopAfterNEvalsHook.after_create_sessionc                 C   s   t d| jiS Nevals_completedr   ZSessionRunArgsr#   r%   run_contextr   r   r   
before_runk   s    z(_MultiStepStopAfterNEvalsHook.before_runc                 C   s   |j d }| jd u r| j}nt| j| | j}| jj||jd | jd u rXtd| ntd|| j | jd ur|| jkr|	  d S )Nr6   r/   Evaluation [%d]Evaluation [%d/%d])
resultsr"   r$   r1   r-   r2   r0   logginginforequest_stop)r%   r9   
run_valuesr6   r3   r   r   r   	after_runo   s    



z'_MultiStepStopAfterNEvalsHook.after_runN)r   )
__name__
__module____qualname____doc__r'   r+   r.   r4   r:   rB   r   r   r   r   r    M   s   
r    c                   @   s2   e Zd ZdZdddZdd Zdd Zd	d
 ZdS )_StopAfterNEvalsHookr!   Tc                 C   s:   || _ d| _|| _|du s"|dk r&dnt|d | _dS )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      $@)r"   r#   _log_progressmathfloor_log_frequency)r%   r&   Zlog_progressr   r   r   r'      s    	z_StopAfterNEvalsHook.__init__c                 C   s
   || _ d S r(   r)   r*   r   r   r   r+      s    z0_StopAfterNEvalsHook._set_evals_completed_tensorc                 C   s   t d| jiS r5   r7   r8   r   r   r   r:      s    z_StopAfterNEvalsHook.before_runc                 C   sp   |j d }| jrP| jd u r(td| n(|| j dks@| j|krPtd|| j | jd url|| jkrl|  d S )Nr6   r;   r   r<   )r=   rI   r"   r>   r?   rL   r@   )r%   r9   rA   r6   r   r   r   rB      s    

z_StopAfterNEvalsHook.after_runN)T)rC   rD   rE   rF   r'   r+   r:   rB   r   r   r   r   rG      s
   
rG    c	                 C   s  t  }	t|pg }|durtdd |D rRt }
tj|	tj|
|	j	ddd}ntj|	ddd}t
|trv||d< n&t
|ttfrt||g }n||g}t|}|D ]}t
|ttfr|| qtd	td
t   t }tj|| ||d}t||}|| tj||d4}|durD| sD||| q*W d   n1 sZ0    Y  tdt |  tdtdt   |jS )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                 s   s   | ]}t |tV  qd S r(   )r   r    ).0hr   r   r   	<genexpr>       z!_evaluate_once.<locals>.<genexpr>)r   T)Zuse_lockingr   update_eval_stepzStarting evaluation at z%Y-%m-%dT%H:%M:%S)scaffoldZ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
   r,   r   Z
assign_addr   castr   r   r   tupler   rG   r    r+   r>   r?   timestrftime	localtimer   ZChiefSessionCreatorZFinalOpsHookappendZMonitoredSessionZshould_stoprunformatZfinal_ops_values)Zcheckpoint_pathrT   rS   Zeval_opsZ	feed_dictZ	final_opsZfinal_ops_feed_dictrW   rU   r   Zsteps_per_run_variablerR   Zeval_step_valuerO   startrV   Zfinal_ops_hookr0   r   r   r   _evaluate_once   s^    5




0rb   )rM   NNNNNNN)rF   rJ   r[   Ztensorflow.python.frameworkr   r   Ztensorflow.python.opsr   r   r   r   r   Ztensorflow.python.platformr	   r>   Ztensorflow.python.trainingr
   r   r   r   r   ZSessionRunHookr    rG   rb   r   r   r   r   <module>   s4   4(        