o
    Meyx                     @   sx  d Z ddlZddlZddlm  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 zddlmZ W n ey\   dZY nw ddddddddddddddejdddfddZdd Zdd Z dd Z!dd Z"d'ddZ#d'ddZ$dd  Z%d!d" Z&ej'eejd#Z(ej'eej)dd$Z*ej'eej+dd$Z,G d%d& d&ej-Z.dS )(z>Part of the Keras training engine related to plain array data.    N)backend)	callbacks)distributed_training_utils_v1)training_utils_v1)io_utils)make_batches)slice_arrays)ModeKeys)
tf_logging)issparse   TFstepsc           7      K   sD  d|v r	| d}|rtd| d}d}t|tjjjjtjjf}|r;|du r5d}tj	| ||||d}t
|| j}| jrQtj| j|tjkrIdndd	}|  |pV|du}|du}|p^|}|rf|rf|}nt| ||||}|swt|||}n|}t| || t| |}d}t|tjjjjtjjfr|du rtj	| |||d
d}t
|| j}t| ||	|
tj}|}n|rtj|d jd pd}|tjkr|rt||| |rdnd} tj|| |||||| ||d
}tdur|sg }!t| |}"tt||"D ]\}#\}$}%t|$rt !|%s|!"|# q|tj#kr%tj$||rdn||d}&ntj%||r-dn||d}&| j&r<t'| | d|j(_)|*| | +||}t,||D ](}'|j(j)r[ ni }(|tj#krg| -  |tjkrs|.|'|( |r2|du rt/j0})n|})d}*|*|)k r1|*dd}+|1|d|*|+ zt2|r| jrt3| s|},n| },||,}-W n< tj4j5y   |r|rd|j(_)t67d||| f  n|*dkr|*}||&_8nd|j(_)t67d||| f  Y nEw t|-t9s|-g}-| jrt:| j|-| |}-|*dkr|&;|- |&<|- |=| |+|-|}+|1|d|*|+ |*d7 }*|j(j)r,n|*|)k snt/>|}.|dkrCt?|.|}.n	|rLt/j@A|. tB||}/t|/D ]\}0\}1}2|.|1|2 }3tC|/dkrk|}4n.z!|rt|d tDrtE|dd |3|d g }4ntE||3}4W n ty   tdw tdur|!D ]}#|4|# F |4|#< q|0tC|3d}+|1|d|0|+ ||4}-t|-t9s|-g}-|0dkr|&;|- |&<|-|1|2 |=| |+|-|}+|1|d|0|+ |j(j)r nqU|&G  |&jH}5|=| |(|5|}(tC|5dkr|5d }5|r\tI||'r\|j(j)s\| j&r&tJ| tj tK| ||	|
|||dtjd|dud
d}6t|6t9sB|6g}6|j=| |(|6|dd}(|r\|'|d k r\tL|| j |tjkrh|M|'|( |rx|'|d k rxtL|| j qPd| _N|O| | jr| j&rtJ| | |Pddd |tjkr| jQS |5S )a8  Loop function for arrays of data with modes TRAIN/TEST/PREDICT.

    Args:
        model: Keras Model instance.
        inputs: Either a list or dictionary of arrays, or a dataset instance.
        targets: List/dictionary of input arrays.
        sample_weights: Optional list of sample weight arrays.
        batch_size: Integer batch size or None if unknown.
        epochs: Number of times to iterate over the data
        verbose: 0, 1, or 2. Verbosity mode.
          0 = silent, 1 = progress bar, 2 = one line per epoch.
          Note that the progress bar is not particularly useful when
          logged to a file, so verbose=2 is recommended when not running
          interactively (eg, in a production environment).
        callbacks: List of callbacks to be called during training
        val_inputs: Either a list or dictionary of arrays, or a dataset
          instance.
        val_targets: List/dictionary of target arrays.
        val_sample_weights: Optional list of sample weight arrays.
        shuffle: Whether to shuffle the data at the beginning of each epoch
          concatenation of list the display names of the outputs of `f` and the
          list of display names of the outputs of `f_val`.
        initial_epoch: Epoch at which to start training (useful for resuming a
          previous training run)
        steps_per_epoch: Total number of steps (batches of samples) before
          declaring one epoch finished and starting the next epoch. Ignored with
          the default value of `None`.
        validation_steps: Number of steps to run validation for (only if doing
          validation from data tensors). Ignored with the default value of
          `None`.
        validation_freq: Only relevant if validation data is provided. Integer
          or `collections.abc.Container` instance (e.g. list, tuple, etc.). If
          an integer, specifies how many training epochs to run before a new
          validation run is performed, e.g. `validation_freq=2` runs validation
          every 2 epochs. If a Container, specifies the epochs on which to run
          validation, e.g. `validation_freq=[1, 2, 10]` runs validation at the
          end of the 1st, 2nd, and 10th epochs.
        mode: One of ModeKeys.TRAIN/ModeKeys.TEST/ModeKeys.PREDICT.
        validation_in_fit: if true, then this method is invoked from within
          training iteration (for validation). In the case where `val_inputs` is
          a dataset, this flag indicates that its iterator and feed values are
          already created so should properly reuse resources.
        prepared_feed_values_from_dataset: if True, `inputs` is a list of feed
          tensors returned from `_prepare_feed_values` call on the validation
          dataset, so do not call it again on `inputs`. Should only be used for
          inline validation (i.e., only if `validation_in_fit` is also True).
        steps_name: The string name of the steps argument, either `steps`,
          `validation_steps`, or `steps_per_epoch`. Only used for error message
          formatting.
        **kwargs: Additional arguments for backwards compatibility.

    Returns:
        - In TRAIN mode: `History` object.
        - In TEST mode: Evaluation metrics.
        - In PREDICT mode: Outputs of the Model called on inputs.

    Raises:
        ValueError: in case of invalid arguments.
    r   zUnknown arguments: FNT)epochs
steps_namer   r   )ZstrategyZlearning_phasevalidation_stepssamples)do_validation
batch_sizer   steps_per_epochr   
count_modeverbosemode)Znum_samplesr   )batchsizebeginzYour dataset ran out of data; interrupting training. Make sure that your dataset can generate at least `%s * epochs` batches (in this case, %d batches). You may need to use the repeat() function when building your dataset.zYour dataset iterator ran out of data; interrupting training. Make sure that your iterator can generate at least `%s * epochs` batches (in this case, %d batches). You may need to use the repeat() function when building your dataset.endr   zPTypeError while preparing batch. If using HDF5 input data, pass shuffle="batch".)
targetssample_weightsr   r   r   r   r   validation_in_fit!prepared_feed_values_from_datasetr   Zval_)prefix)Rpop	TypeError
isinstancetfcompatv1dataDatasetr   Zinfer_steps_for_dataset_get_iterator_distribution_strategyr   Zdistributed_scoper	   TRAIN	__enter___prepare_feed_values_get_num_samples_or_steps_update_sample_weight_mode_make_execution_functionTESTnestflattenshape_print_train_infocbksZconfigure_callbacksr   _get_model_feed	enumeratezipr   Z	is_sparseappendPREDICTZOutputsAggregatorZMetricsAggregatorZ_compile_distributionZ"_copy_weights_to_distributed_modelmodelZstop_trainingZ_call_begin_hookZ#_maybe_load_initial_epoch_from_ckptrangeZreset_metricsZon_epoch_beginnpinfZ_call_batch_hookcallableZis_distributing_by_cloningerrorsZOutOfRangeErrorloggingwarningr   listZ_per_replica_aggregate_batchcreateZ	aggregateZ	make_logsZarangeZbatch_shufflerandomshuffler   lenintr   ZtoarrayfinalizeresultsZshould_run_validationZ_copy_weights_to_original_modelmodel_iteration_reinitialize_iteratorZon_epoch_endZ_successful_loop_finishZ_call_end_hook__exit__history)7r=   inputsr   r   r   r   r   r   
val_inputsval_targetsval_sample_weightsrH   initial_epochr   r   validation_freqr   r   r    r   kwargsZreset_dataset_after_each_epochZinput_iterator
is_datasetscopeZ	use_stepsr   insnum_samples_or_stepsfZval_iteratorval_samples_or_stepsr   Zindices_for_conversion_to_densefeediZ
input_dataZfeed_tensorZ
aggregatorepochZ
epoch_logsZtarget_stepsstepZ
batch_logsZactual_inputsZ
batch_outsZindex_arrayZbatchesZbatch_indexZbatch_startZ	batch_endZ	batch_idsZ	ins_batchrL   Zval_results rb   OD:\Projects\ConvertPro\env\Lib\site-packages\keras/engine/training_arrays_v1.pyrM   )   s  S











	
#






M









rM   c                 C   s*   |t jkr
| j}|S | j| j | j }|S N)r	   r<   _feed_inputs_feed_targetsZ_feed_sample_weights)r=   r   r^   rb   rb   rc   r8     s   
r8   c                 C   sB   |rdnd}d|  d| }|r|d| d| 7 }t | d S )Nr   r   z	Train on  z, validate on )r   Z	print_msg)r[   r]   rX   	incrementmsgrb   rb   rc   r6   	  s
   r6   c                 C   s   |r|S t | ||dS )zEReturns total number of samples when training in batch mode or steps.r   )r   Zcheck_num_samples)rZ   r   r   rb   rb   rc   r/     s
   r/   c                    s   j r*t tjjjjtjjfrt j   fdd}t	 r'|S | S t tjjjjtjjtjjjj
frFj dd\ t   tpQg tpWg    }tjkrptt tsp|dg7 }|S )a  Prepare feed values to the model execution function.

    Args:
      model: Model to prepare feed values for.
      inputs: List or dict of model inputs.
      targets: Optional list of model targets.
      sample_weights: Optional list of sample weight arrays.
      mode: One of ModeKeys.TRAIN/ModeKeys.TEST/ModeKeys.PREDICT.

    Returns:
      Feed values for the model in the given mode.
    c                      s   t  S rd   )r   r.   rb   rQ   r   r=   r   r   rb   rc   get_distributed_inputs-  s   
z4_prepare_feed_values.<locals>.get_distributed_inputsT)Zextract_tensors_from_dataset)r+   r$   r%   r&   r'   r(   r)   r   get_iteratorZexecuting_eagerlyIterator_standardize_user_datar   ZModelInputsas_listrE   r	   r,   r   symbolic_learning_phaserJ   )r=   rQ   r   r   r   rk   rZ   rb   rj   rc   r.     s8   


r.   c                 C   s   |rt | |S t| S rd   )r   rl   r   )rQ   distribution_strategyrb   rb   rc   r*   U  s
   
r*   c                 C   s"   |r
t | | d S t|  d S rd   )r   Zinitialize_iteratorr   )iteratorrq   rb   rb   rc   rN   ]  s
   rN   c                 C   s   | j r	t| |S | |S )z2Makes function to run one step of model execution.)r+   r   r1   )r=   r   rb   rb   rc   r1   f  s
   
r1   c                 C   s   |t jkrdS d}t|s6|t| jt| j d }|t jko'tt	 t
 }|r0|dd }| j|d | jrBt| || dS dS )z0Updates the sample_weight_mode of a given model.Nr   )r   )r	   r<   rA   rI   re   rf   r,   r$   r   rp   rJ   Z_update_sample_weight_modesr+   r   )r=   r   rQ   r   Zhas_learning_phase_plrb   rb   rc   r0   o  s$   
r0   )r   )r   rH   c                   @   sb   e Zd ZdZ															dddZ							dd	d
Z				dddZdS )ArrayLikeTrainingLoopa=  TrainingLoop that handle inputs like array.

    This is the default handler for most of the input data types, includes
    symbolic tensors or Numpy array-like, Datasets and iterators in graph mode
    (since they generate symbolic tensors). This Function is used to handle
    model with `run_eagerly` = False.
    Nr           Tr   c                 K   s  | |||}|j|||||dd|||
d
\}}}|	r&||	||\}}}n(|rCd|  k r2dk rCn nt||||\}}}}}}n|rItdd\}}}t|fi d|d	|d
|d|d|d|d|d|d|d|d|
d|d|d|d|ddS )NTr   )sample_weightclass_weightr   check_stepsr   r   validation_splitrH   rt   g      ?zH`validation_steps` should not be specified if `validation_data` is None.)NNNrQ   r   r   r   r   r   r   rR   rS   rT   rH   rU   r   rV   r   )_validate_or_infer_batch_sizern   Z_prepare_validation_datar   Z"split_training_and_validation_data
ValueErrorfit_loop)selfr=   xyr   r   r   r   rx   Zvalidation_datarH   rv   ru   rU   r   r   rV   rW   r   Zval_xZval_yrT   rb   rb   rc   fit  s   
	
zArrayLikeTrainingLoop.fitc	              
   K   sD   | |||}|j||||dd|d\}}}
t||||
||||dS )NTr   )ru   r   rw   r   r   )rQ   r   r   r   r   r   r   )ry   rn   	test_loop)r|   r=   r}   r~   r   r   ru   r   r   rW   r   rb   rb   rc   evaluate  s(   	zArrayLikeTrainingLoop.evaluatec           	      K   s:   | |||}|j|dd|d\}}}t||||||dS )NTr   )rw   r   r   )r   r   r   r   )ry   rn   predict_loop)	r|   r=   r}   r   r   r   r   rW   _rb   rb   rc   predict  s   
zArrayLikeTrainingLoop.predict)NNNr   r   Nrt   NTNNr   NNr   )NNNr   NNN)Nr   NN)__name__
__module____qualname____doc__r   r   r   rb   rb   rb   rc   rs     s>    
S
%rs   rd   )/r   	functoolsnumpyr?   Ztensorflow.compat.v2r&   v2r%   Zkerasr   r   r7   Zkeras.distributer   Zkeras.enginer   Zkeras.utilsr   Zkeras.utils.generic_utilsr   r   Zkeras.utils.mode_keysr	   Ztensorflow.python.platformr
   rC   Zscipy.sparser   ImportErrorr,   rM   r8   r6   r/   r.   r*   rN   r1   r0   partialr{   r2   r   r<   r   ZTrainingLooprs   rb   rb   rb   rc   <module>   sp   
   W	
;
		!