B
    ӻd                @   s  d Z ddl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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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#l0m1Z1 dd$l2m3Z3 dd%l4m5Z5 dd&l6m7Z7 dd'l6m8Z8 dd(l6m9Z9 dd)l6m:Z: dd*l6m;Z; dd+l<m=Z= dd,l>m?Z? dd-l>m@Z@ dd.lAmBZC dd/lDmEZF dd0lGmHZH ydd1lImJZJ W n eKk
rn   dZJY nX G d2d3 d3e&jLZLG d4d5 d5eLZMG d6d7 d7eNZOG d8d9 d9eNZPd:d; ZQd<d= ZRd>d? ZSd@dA ZTdS )Bz-V1 Training-related part of the Keras engine.    N)tf2)dataset_ops)iterator_ops)distribution_strategy_context)parameter_server_strategy)parameter_server_strategy_v2)context)def_function)constant_op)ops)sparse_tensor)tensor_shape)tensor_spec)tensor_util)	type_spec)backend)losses)metrics)optimizer_v1)
optimizers)distributed_training_utils)distributed_training_utils_v1)
base_layer)training)training_arrays_v1)training_distributed_v1)training_eager_v1)training_generator_v1)training_utils)training_utils_v1)loss_scale_optimizer)policy)optimizer_v2)saving_utils)model_serialization)
data_utils)layer_utils)losses_utils)
tf_inspect)tf_utils)ModeKeys)	array_ops)math_ops)
tf_logging)base)nest)issparsec                   s  e Zd ZdZ fddZdd Zejdd Zdd	 Z	d fdd	Z
ejdddZejdd Ze fddZe fddZedd Zejdd Zdd Zdd!d"Zdd#d$Zdd%d&Zd'd( Zdd)d*Zdd+d,Zd-d. Zdd/d0Zdd1d2Zdd3d4Zd5d6 Zd7d8 Zd9d: Zd;d< Z d=d> Z!d?d@ Z"ddAdBZ#dCdD Z$ejddEdFZ%dGdH Z&dIdJ Z'dKdL Z(dMdN Z)ejdOdP Z*dQdR Z+ddSdTZ,dUdV Z-dWdX Z.dYdZ Z/d[d\ Z0d]d^ Z1dd_d`Z2ddadbZ3dcdd Z4dedf Z5dgdh Z6didj Z7dkdl Z8ddmdnZ9ddpdqZ:ddrdsZ;dtdu Z<dvdw Z=ddxdyZ>ejdzd{ Z?ejd|d} Z@ed~d ZAedd ZBedd ZCedd ZDedd ZEedd ZFedd ZGedd ZHedd ZIedd ZJdd ZKdd ZLdd ZMdd ZNedd ZOdddZPedd ZQ  ZRS )Modela&  `Model` groups layers into an object with training and inference features.

  There are two ways to instantiate a `Model`:

  1 - With the "functional API", where you start from `Input`,
  you chain layer calls to specify the model's forward pass,
  and finally you create your model from inputs and outputs:

  ```python
  import tensorflow as tf

  inputs = tf.keras.Input(shape=(3,))
  x = tf.keras.layers.Dense(4, activation=tf.nn.relu)(inputs)
  outputs = tf.keras.layers.Dense(5, activation=tf.nn.softmax)(x)
  model = tf.keras.Model(inputs=inputs, outputs=outputs)
  ```

  2 - By subclassing the `Model` class: in that case, you should define your
  layers in `__init__` and you should implement the model's forward pass
  in `call`.

  ```python
  import tensorflow as tf

  class MyModel(tf.keras.Model):

    def __init__(self):
      super(MyModel, self).__init__()
      self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu)
      self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax)

    def call(self, inputs):
      x = self.dense1(inputs)
      return self.dense2(x)

  model = MyModel()
  ```

  If you subclass `Model`, you can optionally have
  a `training` argument (boolean) in `call`, which you can use to specify
  a different behavior in training and inference:

  ```python
  import tensorflow as tf

  class MyModel(tf.keras.Model):

    def __init__(self):
      super(MyModel, self).__init__()
      self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu)
      self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax)
      self.dropout = tf.keras.layers.Dropout(0.5)

    def call(self, inputs, training=False):
      x = self.dense1(inputs)
      if training:
        x = self.dropout(x, training=training)
      return self.dense2(x)

  model = MyModel()
  ```
  c                s\   t t| j|| d | _d | _t r<t r<| 	t
  d| _d | _t | _d| _d S )NF)superr1   __init___distribution_strategy#_compile_time_distribution_strategyr   #executing_eagerly_outside_functionsr   has_strategy_set_strategyget_strategy_compile_distribution_run_eagerly_experimental_run_tf_function_v1_compile_was_called)selfargskwargs)	__class__ \/var/www/html/venv/lib/python3.7/site-packages/tensorflow/python/keras/engine/training_v1.pyr3      s    

zModel.__init__c             C   s   d S )NrB   )r>   rB   rB   rC   _init_batch_counters   s    zModel._init_batch_countersc             C   s
   || _ d S )N)r5   )r>   strategyrB   rB   rC   r8      s    zModel._set_strategyc          	   C   s8   | j p
| j}|r,|  tj| S Q R X tj| S )z[Retrieves the weights of the model.

    Returns:
        A flat list of Numpy arrays.
    N)r4   r5   scoper   ZLayerget_weights)r>   rE   rB   rB   rC   rG      s    
zModel.get_weightsFc                s@   t | jr,| jjjdkr,t|s,tdtt	| 
|||S )a	  Loads all layer weights, either from a TensorFlow or an HDF5 weight file.

    If `by_name` is False weights are loaded based on the network's
    topology. This means the architecture should be the same as when the weights
    were saved.  Note that layers that don't have weights are not taken into
    account in the topological ordering, so adding or removing layers is fine as
    long as they don't have weights.

    If `by_name` is True, weights are loaded into layers only if they share the
    same name. This is useful for fine-tuning or transfer-learning models where
    some of the layers have changed.

    Only topological loading (`by_name=False`) is supported when loading weights
    from the TensorFlow format. Note that topological loading differs slightly
    between TensorFlow and HDF5 formats for user-defined classes inheriting from
    `tf.keras.Model`: HDF5 loads based on a flattened list of weights, while the
    TensorFlow format loads based on the object-local names of attributes to
    which layers are assigned in the `Model`'s constructor.

    Args:
        filepath: String, path to the weights file to load. For weight files in
            TensorFlow format, this is the file prefix (the same as was passed
            to `save_weights`).
        by_name: Boolean, whether to load weights by name or by topological
            order. Only topological loading is supported for weight files in
            TensorFlow format.
        skip_mismatch: Boolean, whether to skip loading of layers where there is
            a mismatch in the number of weights, or a mismatch in the shape of
            the weight (only valid when `by_name=True`).

    Returns:
        When loading a weight file in TensorFlow format, returns the same status
        object as `tf.train.Checkpoint.restore`. When graph building, restore
        ops are run automatically as soon as the network is built (on first call
        for user-defined classes inheriting from `Model`, immediately if it is
        already built).

        When loading weights in HDF5 format, returns `None`.

    Raises:
        ImportError: If h5py is not available and the weight file is in HDF5
            format.
        ValueError: If `skip_mismatch` is set to `True` when `by_name` is
          `False`.
       zULoad weights is not yet supported with TPUStrategy with steps_per_run greater than 1.)r   is_tpu_strategyr4   extendedZsteps_per_runr#   Zis_hdf5_filepath
ValueErrorr2   r1   load_weights)r>   filepathby_nameZskip_mismatch)rA   rB   rC   rL      s
    .
zModel.load_weightsrmspropNc	          	   K   s  |    |	dd| _|	dd| _d| _|	dd |	dd| _dd	d
dh}
t|	 |
 }|rrtd|f |	| _	| j	rd| _| j
rtd| j	f | | tdd t| jD }|rt rtd|d|dk	st sd| _|dk	r(t s| jrtdtd || _d| _nt rFt rFt | _t| jtjr^t dt| jt!j"rvt d| js| #| j
||| t| jt$j%r| j&| jddd |pi | _'|| _(|| _)|pg | _*|| _+| j
r|dk	rtdg | _,| - | _.i | _/i | _0| 1  t23 s<| jdk	r<t45| j | 6  | j7r\| j8r\| j9s`dS d| _:t;<| j'| j=| _>| ?|}xNt@| j9| j=| j>|D ]6\}}}}tA|||}|jB|| j
d | j,C| qW t;D| j,| | j
r| E||| dS t4F G  | H|| | I  | jJ| j9| jK| L | M d t;N| j,| | O  d| _Pd| _Qd| _R| jS| _T| jr| jsx4| jUD ]*}| j}|jVW|std||f qW W dQ R X dS )a  Configures the model for training.

    Args:
        optimizer: String (name of optimizer) or optimizer instance.
            See `tf.keras.optimizers`.
        loss: String (name of objective function), objective function or
            `tf.keras.losses.Loss` instance. See `tf.keras.losses`. An objective
            function is any callable with the signature
            `scalar_loss = fn(y_true, y_pred)`. If the model has multiple
            outputs, you can use a different loss on each output by passing a
            dictionary or a list of losses. The loss value that will be
            minimized by the model will then be the sum of all individual
            losses.
        metrics: List of metrics to be evaluated by the model during training
            and testing. Typically you will use `metrics=['accuracy']`.
            To specify different metrics for different outputs of a
            multi-output model, you could also pass a dictionary, such as
            `metrics={'output_a': 'accuracy', 'output_b': ['accuracy', 'mse']}`.
            You can also pass a list (len = len(outputs)) of lists of metrics
            such as `metrics=[['accuracy'], ['accuracy', 'mse']]` or
            `metrics=['accuracy', ['accuracy', 'mse']]`.
        loss_weights: Optional list or dictionary specifying scalar
            coefficients (Python floats) to weight the loss contributions
            of different model outputs.
            The loss value that will be minimized by the model
            will then be the *weighted sum* of all individual losses,
            weighted by the `loss_weights` coefficients.
            If a list, it is expected to have a 1:1 mapping
            to the model's outputs. If a tensor, it is expected to map
            output names (strings) to scalar coefficients.
        sample_weight_mode: If you need to do timestep-wise
            sample weighting (2D weights), set this to `"temporal"`.
            `None` defaults to sample-wise weights (1D).
            If the model has multiple outputs, you can use a different
            `sample_weight_mode` on each output by passing a
            dictionary or a list of modes.
        weighted_metrics: List of metrics to be evaluated and weighted
            by sample_weight or class_weight during training and testing.
        target_tensors: By default, Keras will create placeholders for the
            model's target, which will be fed with the target data during
            training. If instead you would like to use your own
            target tensors (in turn, Keras will not expect external
            Numpy data for these targets at training time), you
            can specify them via the `target_tensors` argument. It can be
            a single tensor (for a single-output model), a list of tensors,
            or a dict mapping output names to target tensors.
        distribute: NOT SUPPORTED IN TF 2.0, please create and compile the
            model under distribution strategy scope instead of passing it to
            compile.
        **kwargs: Any additional arguments.

    Raises:
        ValueError: In case of invalid arguments for
            `optimizer`, `loss`, `metrics` or `sample_weight_mode`.
    run_eagerlyNexperimental_run_tf_functionTZcloningfrom_serializedFZ	feed_dictZfetchesoptionsZrun_metadataz,Invalid keyword argument(s) in `compile`: %szsSession keyword arguments are not supported when `run_eagerly=True`. You passed the following Session arguments: %sc             s   s(   | ] }t |tjot |tj V  qd S )N)
isinstancer   Z	OptimizerZTFOptimizer).0optrB   rB   rC   	<genexpr>E  s   z Model.compile.<locals>.<genexpr>z `tf.compat.v1.keras` Optimizer (zs) is not supported when eager execution is enabled. Use a `tf.keras` Optimizer instead, or disable eager execution.zxDistribute argument in compile is not available in TF 2.0 please create the model under the distribution strategy scope.zkDistribute argument in compile is deprecated please create the model under the distribution strategy scope.zm`tf.compat.v1.distribute.experimental.ParameterServerStrategy` currently only works with the tf.Estimator APIzN`tf.distribute.experimental.ParameterServerStrategy` is only supported in TF2.	optimizer)name	overwritezFtarget_tensors argument is not supported when running a model eagerly.)rP   )targetsskip_target_masksmasksaA  Variable (%s) was not created in the distribution strategy scope of (%s). It is most likely due to not all layers or the model or optimizer being created outside the distribution strategy scope. Try to make sure your code looks similar to the following.
with strategy.scope():
  model=_create_model()
  model.compile(...))X_assert_built_as_v1popr;   r<   r=   _from_serializedsetkeys	TypeError_function_kwargsrP   rK   _set_optimizeranyr/   flattenrX   r   r6   r   enabledloggingwarningr4   r:   r   r7   in_cross_replica_contextr9   rT   r   ZParameterServerStrategyV1NotImplementedErrorr   ZParameterServerStrategyV21_validate_compile_param_for_distribution_strategy	trackableZ	TrackableZ_track_trackablelossloss_weightssample_weight_mode_compile_metrics_compile_weighted_metrics_training_endpoints_get_trainable_state_compiled_trainable_stateZ_distributed_model_cache_distributed_function_cacheZ_clear_lossesr   executing_eagerlyr   Z(configure_and_create_distributed_session_init_metric_attributesbuiltinputsoutputs_is_compiledr   Zprepare_loss_functionsoutput_namesloss_functions"_process_target_tensor_for_compilezip_TrainingEndpointcreate_training_targetappendZprepare_loss_weights_compile_eagerly	get_graph
as_default_cache_output_metric_attributes_set_metric_attributes_handle_metrics_targets_prepare_skip_target_masks_prepare_output_masksprepare_sample_weight_modes*_compile_weights_loss_and_weighted_metricstrain_functiontest_functionpredict_functiontrainable_weights_collected_trainable_weights	variablesrJ   Zvariable_created_in_scope)r>   rX   ro   r   rp   rq   weighted_metricstarget_tensorsZ
distributer@   Zallowed_kwargsZunknown_kwargsZis_any_keras_optimizer_v1onltendpointvrE   rB   rB   rC   compile   s    B












zModel.compilec             C   s   t | dsi | _d S )Nrw   )hasattrrw   )r>   rB   rB   rC   0_init_distributed_function_cache_if_not_compiled  s    
z6Model._init_distributed_function_cache_if_not_compiledc                sV   g }| j r*t| ds tt| jS || j7 }|| j |tt	| j
ddd |S )zEReturns the model's metrics added using `compile`, `add_metric` APIs.r=   F)include_self	recursive)r}   r   r2   r1   r   _compile_metric_functionsextend_metrics_get_metrics_from_layerslist_flatten_layers)r>   r   )rA   rB   rC   r     s    

zModel.metricsc                s^   dg}| j rFt| ds"tt| jS t| jdkrF|dd | jD  |dd | jD 7 }|S )z3Returns the model's display labels for all outputs.ro   r=   rH   c             S   s   g | ]}|  s| qS rB   )should_skip_target	loss_name)rU   erB   rB   rC   
<listcomp>  s   z'Model.metrics_names.<locals>.<listcomp>c             S   s   g | ]
}|j qS rB   )rY   )rU   mrB   rB   rC   r     s    )	r}   r   r2   r1   metrics_nameslenrt   r   r   )r>   r   )rA   rB   rC   r     s    
zModel.metrics_namesc             C   sh   | j dkrt std| js:| j dkr2t S | j S n*t sJtd| j dkr\tdt S dS )a  Settable attribute indicating whether the model should run eagerly.

    Running eagerly means that your model will be run step by step,
    like Python code. Your model might run slower, but it should become easier
    for you to debug it by stepping into individual layer calls.

    By default, we will attempt to compile your model to a static graph to
    deliver the best execution performance.

    Returns:
      Boolean, whether the model should run eagerly.
    TzBYou can only set `run_eagerly=True` if eager execution is enabled.NzYour model contains layers that can only be successfully run in eager execution (layers constructed with `dynamic=True`). You must enable eager execution with `tf.enable_eager_execution()`.FzYour model contains layers that can only be successfully run in eager execution (layers constructed with `dynamic=True`). You cannot set `run_eagerly=False`.)r;   r   rx   rK   dynamicr	   Zfunctions_run_eagerly)r>   rB   rB   rC   rP     s    

zModel.run_eagerlyc             C   s
   || _ d S )N)r;   )r>   valuerB   rB   rC   rP   >  s    c             C   s|   t |tjtjfrtd| jr>|  r6tt	 S t	 S t
|rPt S t|rbt S | jrpt S t S dS )z>Select training loop for fit/eval/predict based on the inputs.a  For performance reasons Keras `fit`, `evaluate` and`predict` accept tf.data `Datasets` as input but not iterators that have been manually generated from Datasets by users. Please directly pass in the original `Dataset` object instead of passing in `iter(dataset)`.N)rT   r   IteratorIteratorBaserK   r4   _in_multi_worker_moder   Z#DistributionMultiWorkerTrainingLoopZ$DistributionSingleWorkerTrainingLoopr%   Zis_generator_or_sequencer   ZGeneratorOrSequenceTrainingLoopr   Zis_eager_dataset_or_iteratorZ"EagerDatasetOrIteratorTrainingLooprP   ZGeneratorLikeTrainingLoopr   ZArrayLikeTrainingLoop)r>   r{   rB   rB   rC   _select_training_loopB  s    



zModel._select_training_looprH           Tr   
   c             K   s   |    d|kr$td |d}|r8tdt| |   | d | |}|j	| |||||||||	|
||||||||dS )aZ!  Trains the model for a fixed number of epochs (iterations on a dataset).

    Args:
        x: Input data. It could be:
          - A Numpy array (or array-like), or a list of arrays
            (in case the model has multiple inputs).
          - A TensorFlow tensor, or a list of tensors
            (in case the model has multiple inputs).
          - A dict mapping input names to the corresponding array/tensors,
            if the model has named inputs.
          - A `tf.data` dataset. Should return a tuple
            of either `(inputs, targets)` or
            `(inputs, targets, sample_weights)`.
          - A generator or `keras.utils.Sequence` returning `(inputs, targets)`
            or `(inputs, targets, sample weights)`.
        y: Target data. Like the input data `x`,
          it could be either Numpy array(s) or TensorFlow tensor(s).
          It should be consistent with `x` (you cannot have Numpy inputs and
          tensor targets, or inversely). If `x` is a dataset, generator,
          or `keras.utils.Sequence` instance, `y` should
          not be specified (since targets will be obtained from `x`).
        batch_size: Integer or `None`.
            Number of samples per gradient update.
            If unspecified, `batch_size` will default to 32.
            Do not specify the `batch_size` if your data is in the
            form of symbolic tensors, datasets,
            generators, or `keras.utils.Sequence` instances (since they generate
            batches).
        epochs: Integer. Number of epochs to train the model.
            An epoch is an iteration over the entire `x` and `y`
            data provided.
            Note that in conjunction with `initial_epoch`,
            `epochs` is to be understood as "final epoch".
            The model is not trained for a number of iterations
            given by `epochs`, but merely until the epoch
            of index `epochs` is reached.
        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 `keras.callbacks.Callback` instances.
            List of callbacks to apply during training.
            See `tf.keras.callbacks`.
        validation_split: Float between 0 and 1.
            Fraction of the training data to be used as validation data.
            The model will set apart this fraction of the training data,
            will not train on it, and will evaluate
            the loss and any model metrics
            on this data at the end of each epoch.
            The validation data is selected from the last samples
            in the `x` and `y` data provided, before shuffling. This argument is
            not supported when `x` is a dataset, generator or
           `keras.utils.Sequence` instance.
        validation_data: Data on which to evaluate
            the loss and any model metrics at the end of each epoch.
            The model will not be trained on this data.
            `validation_data` will override `validation_split`.
            `validation_data` could be:
              - tuple `(x_val, y_val)` of Numpy arrays or tensors
              - tuple `(x_val, y_val, val_sample_weights)` of Numpy arrays
              - dataset
            For the first two cases, `batch_size` must be provided.
            For the last case, `validation_steps` could be provided.
        shuffle: Boolean (whether to shuffle the training data
            before each epoch) or str (for 'batch').
            'batch' is a special option for dealing with the
            limitations of HDF5 data; it shuffles in batch-sized chunks.
            Has no effect when `steps_per_epoch` is not `None`.
        class_weight: Optional dictionary mapping class indices (integers)
            to a weight (float) value, used for weighting the loss function
            (during training only).
            This can be useful to tell the model to
            "pay more attention" to samples from
            an under-represented class.
        sample_weight: Optional Numpy array of weights for
            the training samples, used for weighting the loss function
            (during training only). You can either pass a flat (1D)
            Numpy array with the same length as the input samples
            (1:1 mapping between weights and samples),
            or in the case of temporal data,
            you can pass a 2D array with shape
            `(samples, sequence_length)`,
            to apply a different weight to every timestep of every sample.
            In this case you should make sure to specify
            `sample_weight_mode="temporal"` in `compile()`. This argument is not
            supported when `x` is a dataset, generator, or
           `keras.utils.Sequence` instance, instead provide the sample_weights
            as the third element of `x`.
        initial_epoch: Integer.
            Epoch at which to start training
            (useful for resuming a previous training run).
        steps_per_epoch: Integer or `None`.
            Total number of steps (batches of samples)
            before declaring one epoch finished and starting the
            next epoch. When training with input tensors such as
            TensorFlow data tensors, the default `None` is equal to
            the number of samples in your dataset divided by
            the batch size, or 1 if that cannot be determined. If x is a
            `tf.data` dataset, and 'steps_per_epoch'
            is None, the epoch will run until the input dataset is exhausted.
            This argument is not supported with array inputs.
        validation_steps: Only relevant if `validation_data` is provided and
            is a `tf.data` dataset. Total number of steps (batches of
            samples) to draw before stopping when performing validation
            at the end of every epoch. If 'validation_steps' is None, validation
            will run until the `validation_data` dataset is exhausted. In the
            case of a infinite dataset, it will run into a infinite loop.
            If 'validation_steps' is specified and only part of the dataset
            will be consumed, the evaluation will start from the beginning of
            the dataset at each epoch. This ensures that the same validation
            samples are used every time.
        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.
        max_queue_size: Integer. Used for generator or `keras.utils.Sequence`
            input only. Maximum size for the generator queue.
            If unspecified, `max_queue_size` will default to 10.
        workers: Integer. Used for generator or `keras.utils.Sequence` input
            only. Maximum number of processes to spin up
            when using process-based threading. If unspecified, `workers`
            will default to 1. If 0, will execute the generator on the main
            thread.
        use_multiprocessing: Boolean. Used for generator or
            `keras.utils.Sequence` input only. If `True`, use process-based
            threading. If unspecified, `use_multiprocessing` will default to
            `False`. Note that because this implementation relies on
            multiprocessing, you should not pass non-picklable arguments to
            the generator as they can't be passed easily to children processes.
        **kwargs: Used for backwards compatibility.

    Returns:
        A `History` object. Its `History.history` attribute is
        a record of training loss values and metrics values
        at successive epochs, as well as validation loss values
        and validation metrics values (if applicable).

    Raises:
        RuntimeError: If the model was never compiled.
        ValueError: In case of mismatch between the provided input data
            and what the model expects.
    Znb_epochz;The `nb_epoch` argument in `fit` has been renamed `epochs`.z Unrecognized keyword arguments: fit)xy
batch_sizeepochsverbose	callbacksvalidation_splitvalidation_datashuffleclass_weightsample_weightinitial_epochsteps_per_epochvalidation_stepsvalidation_freqmax_queue_sizeworkersuse_multiprocessing)
r^   ri   rj   r_   rc   str_assert_compile_was_called_check_call_argsr   r   )r>   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r@   funcrB   rB   rC   r   g  s>     '


z	Model.fitc             C   sD   |    |   | d | |}|j| |||||||||	|
dS )a  Returns the loss value & metrics values for the model in test mode.

    Computation is done in batches (see the `batch_size` arg.)

    Args:
        x: Input data. It could be:
          - A Numpy array (or array-like), or a list of arrays
            (in case the model has multiple inputs).
          - A TensorFlow tensor, or a list of tensors
            (in case the model has multiple inputs).
          - A dict mapping input names to the corresponding array/tensors,
            if the model has named inputs.
          - A `tf.data` dataset.
          - A generator or `keras.utils.Sequence` instance.
        y: Target data. Like the input data `x`,
          it could be either Numpy array(s) or TensorFlow tensor(s).
          It should be consistent with `x` (you cannot have Numpy inputs and
          tensor targets, or inversely).
          If `x` is a dataset, generator or
          `keras.utils.Sequence` instance, `y` should not be specified (since
          targets will be obtained from the iterator/dataset).
        batch_size: Integer or `None`.
            Number of samples per batch of computation.
            If unspecified, `batch_size` will default to 32.
            Do not specify the `batch_size` if your data is in the
            form of symbolic tensors, dataset,
            generators, or `keras.utils.Sequence` instances (since they generate
            batches).
        verbose: 0 or 1. Verbosity mode.
            0 = silent, 1 = progress bar.
        sample_weight: Optional Numpy array of weights for
            the test samples, used for weighting the loss function.
            You can either pass a flat (1D)
            Numpy array with the same length as the input samples
            (1:1 mapping between weights and samples),
            or in the case of temporal data,
            you can pass a 2D array with shape
            `(samples, sequence_length)`,
            to apply a different weight to every timestep of every sample.
            In this case you should make sure to specify
            `sample_weight_mode="temporal"` in `compile()`. This argument is not
            supported when `x` is a dataset, instead pass
            sample weights as the third element of `x`.
        steps: Integer or `None`.
            Total number of steps (batches of samples)
            before declaring the evaluation round finished.
            Ignored with the default value of `None`.
            If x is a `tf.data` dataset and `steps` is
            None, 'evaluate' will run until the dataset is exhausted.
            This argument is not supported with array inputs.
        callbacks: List of `keras.callbacks.Callback` instances.
            List of callbacks to apply during evaluation.
            See [callbacks](/api_docs/python/tf/keras/callbacks).
        max_queue_size: Integer. Used for generator or `keras.utils.Sequence`
            input only. Maximum size for the generator queue.
            If unspecified, `max_queue_size` will default to 10.
        workers: Integer. Used for generator or `keras.utils.Sequence` input
            only. Maximum number of processes to spin up when using
            process-based threading. If unspecified, `workers` will default
            to 1. If 0, will execute the generator on the main thread.
        use_multiprocessing: Boolean. Used for generator or
            `keras.utils.Sequence` input only. If `True`, use process-based
            threading. If unspecified, `use_multiprocessing` will default to
            `False`. Note that because this implementation relies on
            multiprocessing, you should not pass non-picklable arguments to
            the generator as they can't be passed easily to children processes.

    Returns:
        Scalar test loss (if the model has a single output and no metrics)
        or list of scalars (if the model has multiple outputs
        and/or metrics). The attribute `model.metrics_names` will give you
        the display labels for the scalar outputs.

    Raises:
        ValueError: in case of invalid arguments.
    evaluate)
r   r   r   r   r   stepsr   r   r   r   )r^   r   r   r   r   )r>   r   r   r   r   r   r   r   r   r   r   r   rB   rB   rC   r   .  s     W

zModel.evaluatec	       
      C   s8   |    | d | |}	|	j| ||||||||d	S )aF
  Generates output predictions for the input samples.

    Computation is done in batches (see the `batch_size` arg.)

    Args:
        x: Input samples. It could be:
          - A Numpy array (or array-like), or a list of arrays
            (in case the model has multiple inputs).
          - A TensorFlow tensor, or a list of tensors
            (in case the model has multiple inputs).
          - A `tf.data` dataset.
          - A generator or `keras.utils.Sequence` instance.
        batch_size: Integer or `None`.
            Number of samples per batch of computation.
            If unspecified, `batch_size` will default to 32.
            Do not specify the `batch_size` if your data is in the
            form of symbolic tensors, dataset,
            generators, or `keras.utils.Sequence` instances (since they generate
            batches).
        verbose: Verbosity mode, 0 or 1.
        steps: Total number of steps (batches of samples)
            before declaring the prediction round finished.
            Ignored with the default value of `None`. If x is a `tf.data`
            dataset and `steps` is None, `predict` will
            run until the input dataset is exhausted.
        callbacks: List of `keras.callbacks.Callback` instances.
            List of callbacks to apply during prediction.
            See [callbacks](/api_docs/python/tf/keras/callbacks).
        max_queue_size: Integer. Used for generator or `keras.utils.Sequence`
            input only. Maximum size for the generator queue.
            If unspecified, `max_queue_size` will default to 10.
        workers: Integer. Used for generator or `keras.utils.Sequence` input
            only. Maximum number of processes to spin up when using
            process-based threading. If unspecified, `workers` will default
            to 1. If 0, will execute the generator on the main thread.
        use_multiprocessing: Boolean. Used for generator or
            `keras.utils.Sequence` input only. If `True`, use process-based
            threading. If unspecified, `use_multiprocessing` will default to
            `False`. Note that because this implementation relies on
            multiprocessing, you should not pass non-picklable arguments to
            the generator as they can't be passed easily to children processes.


    Returns:
        Numpy array(s) of predictions.

    Raises:
        ValueError: In case of mismatch between the provided
            input data and the model's expectations,
            or in case a stateful model receives a number of samples
            that is not a multiple of the batch size.
    predict)r   r   r   r   r   r   r   r   )r^   r   r   r   )
r>   r   r   r   r   r   r   r   r   r   rB   rB   rC   r     s    =

zModel.predictc             C   s2   |   }x|D ]}|  qW | jr.t|  dS )zResets the state of metrics.N)_get_training_eval_metricsZreset_stater4   r   Z_reset_metrics)r>   r   r   rB   rB   rC   reset_metrics  s
    
zModel.reset_metricsc       
      C   s  |    | d | jr(t r(td| j||||dd\}}}| jsN| jrtj	| |||| j
d}|d |d  |d  }d	d
 |D }n`t| }|t|pg  t|pg  }	tt ts|	dg7 }	| j|d |   | |	}|r|   t|dkr|d S |S )ay  Runs a single gradient update on a single batch of data.

    Args:
        x: Input data. It could be:
          - A Numpy array (or array-like), or a list of arrays
              (in case the model has multiple inputs).
          - A TensorFlow tensor, or a list of tensors
              (in case the model has multiple inputs).
          - A dict mapping input names to the corresponding array/tensors,
              if the model has named inputs.
          - A `tf.data` dataset.
        y: Target data. Like the input data `x`, it could be either Numpy
          array(s) or TensorFlow tensor(s). It should be consistent with `x`
          (you cannot have Numpy inputs and tensor targets, or inversely). If
          `x` is a dataset, `y` should not be specified
          (since targets will be obtained from the iterator).
        sample_weight: Optional array of the same length as x, containing
          weights to apply to the model's loss for each sample. In the case of
          temporal data, you can pass a 2D array with shape (samples,
          sequence_length), to apply a different weight to every timestep of
          every sample. In this case you should make sure to specify
          sample_weight_mode="temporal" in compile(). This argument is not
          supported when `x` is a dataset.
        class_weight: Optional dictionary mapping class indices (integers) to a
          weight (float) to apply to the model's loss for the samples from this
          class during training. This can be useful to tell the model to "pay
          more attention" to samples from an under-represented class.
        reset_metrics: If `True`, the metrics returned will be only for this
          batch. If `False`, the metrics will be statefully accumulated across
          batches.

    Returns:
        Scalar training loss
        (if the model has a single output and no metrics)
        or list of scalars (if the model has multiple outputs
        and/or metrics). The attribute `model.metrics_names` will give you
        the display labels for the scalar outputs.

    Raises:
      ValueError: In case of invalid user-provided arguments.
    train_on_batchzU`train_on_batch` is not supported for models distributed with tf.distribute.Strategy.T)r   r   extract_tensors_from_dataset)sample_weightsoutput_loss_metrics
total_lossoutput_lossesr   c             S   s   g | ]}t |qS rB   )_non_none_constant_value)rU   r   rB   rB   rC   r   8  s    z(Model.train_on_batch.<locals>.<listcomp>)r   rH   r   )r   r   r4   r   rk   rl   _standardize_user_datarP   r   r   _output_loss_metricsr   ModelInputsas_listr   rT   r   symbolic_learning_phaseint_update_sample_weight_modes_make_train_functionr   r   r   )
r>   r   r   r   r   r   r   output_dictr|   ZinsrB   rB   rC   r     s:    /



zModel.train_on_batchc       	      C   s   |    | d | jr(t r(td| j|||dd\}}}| jsL| jrtj	| |||| j
d}|d |d  |d  }d	d
 |D }nHt| }|t|pg  t|pg  }| j|d |   | |}|r|   t|dkr|d S |S )a@  Test the model on a single batch of samples.

    Args:
        x: Input data. It could be:
          - A Numpy array (or array-like), or a list of arrays
            (in case the model has multiple inputs).
          - A TensorFlow tensor, or a list of tensors
            (in case the model has multiple inputs).
          - A dict mapping input names to the corresponding array/tensors,
            if the model has named inputs.
          - A `tf.data` dataset.
        y: Target data. Like the input data `x`,
          it could be either Numpy array(s) or TensorFlow tensor(s).
          It should be consistent with `x` (you cannot have Numpy inputs and
          tensor targets, or inversely). If `x` is a dataset `y` should
          not be specified (since targets will be obtained from the iterator).
        sample_weight: Optional array of the same length as x, containing
            weights to apply to the model's loss for each sample.
            In the case of temporal data, you can pass a 2D array
            with shape (samples, sequence_length),
            to apply a different weight to every timestep of every sample.
            In this case you should make sure to specify
            sample_weight_mode="temporal" in compile(). This argument is not
            supported when `x` is a dataset.
        reset_metrics: If `True`, the metrics returned will be only for this
          batch. If `False`, the metrics will be statefully accumulated across
          batches.

    Returns:
        Scalar test loss (if the model has a single output and no metrics)
        or list of scalars (if the model has multiple outputs
        and/or metrics). The attribute `model.metrics_names` will give you
        the display labels for the scalar outputs.

    Raises:
        ValueError: In case of invalid user-provided arguments.
    test_on_batchzT`test_on_batch` is not supported for models distributed with tf.distribute.Strategy.T)r   r   )r   r   r   r   r   c             S   s   g | ]}t |qS rB   )r   )rU   r   rB   rB   rC   r     s    z'Model.test_on_batch.<locals>.<listcomp>)r   rH   r   )r   r   r4   r   rk   rl   r   rP   r   r   r   r   r   r   r   r   _make_test_functionr   r   r   )	r>   r   r   r   r   r   r   r|   r{   rB   rB   rC   r   K  s4    &


zModel.test_on_batchc             C   s   |  d | jr t r td| j|dd\}}}| js@| jrtt|}t	|t
jjrlt|dkrl|d }| |S |   | |}t|dkr|d S |S )a  Returns predictions for a single batch of samples.

    Args:
        x: Input data. It could be:
          - A Numpy array (or array-like), or a list of arrays
            (in case the model has multiple inputs).
          - A TensorFlow tensor, or a list of tensors
            (in case the model has multiple inputs).
          - A `tf.data` dataset.

    Returns:
        Numpy array(s) of predictions.

    Raises:
        ValueError: In case of mismatch between given number of inputs and
          expectations of the model.
    predict_on_batchzW`predict_on_batch` is not supported for models distributed with tf.distribute.Strategy.T)r   rH   r   )r   r4   r   rk   rl   r   rP   r   cast_if_floating_dtyperT   collectionsabcSequencer   _make_predict_functionr   )r>   r   r{   _r|   rB   rB   rC   r     s$    


zModel.predict_on_batchc             C   s0   t d | j|||||||||	|
||||dS )zFits the model on data yielded batch-by-batch by a Python generator.

    DEPRECATED:
      `Model.fit` now supports generators, so there is no longer any need to use
      this endpoint.
    z`model.fit_generator` is deprecated and will be removed in a future version. Please use `Model.fit`, which supports generators.)r   r   r   r   r   r   r   r   r   r   r   r   r   )warningswarnr   )r>   	generatorr   r   r   r   r   r   r   r   r   r   r   r   r   rB   rB   rC   fit_generator  s     
zModel.fit_generatorc          	   C   s,   t d | d | j|||||||dS )zEvaluates the model on a data generator.

    DEPRECATED:
      `Model.evaluate` now supports generators, so there is no longer any need
      to use this endpoint.
    z`Model.evaluate_generator` is deprecated and will be removed in a future version. Please use `Model.evaluate`, which supports generators.evaluate_generator)r   r   r   r   r   r   )r   r   r   r   )r>   r   r   r   r   r   r   r   rB   rB   rC   r     s    

zModel.evaluate_generatorc          	   C   s"   t d | j|||||||dS )zGenerates predictions for the input samples from a data generator.

    DEPRECATED:
      `Model.predict` now supports generators, so there is no longer any need
      to use this endpoint.
    z`Model.predict_generator` is deprecated and will be removed in a future version. Please use `Model.predict`, which supports generators.)r   r   r   r   r   r   )r   r   r   )r>   r   r   r   r   r   r   r   rB   rB   rC   predict_generator	  s    
zModel.predict_generatorc             C   st   | j }|jr$|jdt|j  }n|j}d|kr<|d t|dkrp|dd }td| d t| d dS )z.Check that `call` has only one positional arg.Nr      zModels passed to `z\` can only have `training` and the first argument in `call` as positional arguments, found: .)Z_call_full_argspecdefaultsr?   r   removerK   r   )r>   method_nameZfullargspecZpositional_args
extra_argsrB   rB   rC   r   #  s    
zModel._check_call_argsc             C   s   t |ttfr dd |D | _nt|| _t | jtjrD| jj	}n| jj
dkrVd}nd}|dk	rt | jtjst | jtrtd| j | jt | jtjstd| j| jf |dkrt| j| _nt| j|| _dS )zSets self.optimizer.

    Sets self.optimizer to `optimizer`, potentially wrapping it with a
    LossScaleOptimizer.

    Args:
      optimizer: The optimizer(s) to assign to self.optimizer.
    c             S   s   g | ]}t |qS rB   )r   get)rU   rV   rB   rB   rC   r   @  s    z(Model._set_optimizer.<locals>.<listcomp>Zmixed_float16r   Nz{When a dtype policy with a loss scale is used, you can only pass a single optimizer. Using policy %s and got optimizers: %sz"optimizer" must be an instance of tf.keras.optimizers.Optimizer when a dype policy with a loss scale  used, but got: %s. Using policy: %s)rT   r   tuplerX   r   r   Z_dtype_policyr!   ZPolicyV1
loss_scalerY   r    ZLossScaleOptimizerrK   r"   ZOptimizerV2ZLossScaleOptimizerV1)r>   rX   r   rB   rB   rC   re   6  s*    	
zModel._set_optimizerc             C   s&   t |\}}}| j|||||ddS )z%Unpack and check the validation data.r   )r   r   r   
steps_name)r   Zunpack_validation_datar   )r>   r   r   r   Zval_xZval_yZval_sample_weightsrB   rB   rC   _prepare_validation_data_  s    zModel._prepare_validation_datac             C   s^   | j rZ|rtd|rtd|r*td|r6tdt| rZ| jrR| jrR| jsZtdd S )Nz@sample_weight_mode is not supported with tf.distribute.Strategy.z>weighted_metrics is not supported with tf.distribute.Strategy.z<target_tensors is not supported with tf.distribute.Strategy.zNWe currently do not support enabling `run_eagerly` with distribution strategy.zWe currently do not support distribution strategy with a `Sequential` model that is created without `input_shape`/`input_dim` set in its first layer or a subclassed model.)r4   rl   rK   r   Zis_distributing_by_cloningrz   r{   r|   )r>   rP   rq   r   r   rB   rB   rC   rm   l  s    
z7Model._validate_compile_param_for_distribution_strategyc             C   s   | j rdd | jD S |d k	rt|tr0|g kst|trdt|t| jkrtdt| j|f qt|trt|	 
| j}|rtdj|t| jdg }x | jD ]}|||d  qW |}qt|r|g}qtd|ndd | jD }|S )Nc             S   s   g | ]}d qS )NrB   )rU   r   rB   rB   rC   r     s    z<Model._process_target_tensor_for_compile.<locals>.<listcomp>zWhen passing a list as `target_tensors`, it should have one entry per model output. The model has %s outputs, but you passed target_tensors=%sz`Unknown entry in `target_tensors` dictionary: "{name}". Only expected the following keys: {keys})rY   rb   zTExpected `target_tensors` to be a list or tuple or dict or a single tensor, but got:c             S   s   g | ]}d qS )NrB   )rU   r   rB   rB   rC   r     s    )rP   r~   rT   r   r   r|   rK   dictra   rb   
differenceformatr   r   r   r   
is_tf_typerc   )r>   r   Zunexpected_target_tensor_namesZtmp_target_tensorsrY   rB   rB   rC   r     s6    


z(Model._process_target_tensor_for_compilec             C   s<   t | j| |   | || d | _|   | j| _d S )N)	r   r   rt   _prepare_sample_weightsr   r   r   r   r   )r>   r   r   rq   rB   rB   rC   r     s    
zModel._compile_eagerlyc             C   sX   | j s
dS |r>tdd |D r>x2| jD ]}|jp4d|_q(W nx| jD ]
}d|_qFW dS )a  Updates sample weight modes based on training/eval inputs.

    Sample weight placeholders will be created for all or no outputs
    based on whether sample_weight is provided for any output.

    If model contains `_sample_weight_modes` we check if the input
    `sample_weights` corresponds to the sample weight modes.
      1. Set sample weight mode to be 'temporal' for output i, if `compile`
        sample_weight_mode was set to `temporal` and sample weight inputs
        are given for one or more outputs.
      2. Set sample weight mode to be 'samplewise' for output i, if `compile`
        sample_weight_mode was not set and sample weight inputs are given for
        one or more outputs.
      3. Reset sample weight mode to None for output i if sample weight mode
        was set but there is no sample weight input.

    Args:
      sample_weights: List of sample weights of the same length as model outputs
        or None.
    Nc             s   s   | ]}|d k	V  qd S )NrB   )rU   srB   rB   rC   rW     s    z4Model._update_sample_weight_modes.<locals>.<genexpr>
samplewise)r}   rf   rt   rq   )r>   r   r   rB   rB   rC   r     s    z!Model._update_sample_weight_modesc             C   s.   | j s
dS tdd | jD }|r*|   |S )NFc             s   s   | ]}|  V  qd S )N)sample_weights_mismatch)rU   r   rB   rB   rC   rW     s    zEModel._recompile_weights_loss_and_weighted_metrics.<locals>.<genexpr>)r}   rf   rt   r   )r>   Z	recompilerB   rB   rC   ,_recompile_weights_loss_and_weighted_metrics  s    z2Model._recompile_weights_loss_and_weighted_metricsc          	   C   sl   t   V |dk	r | | | | |  }| j| j| j| 	 | j
|dd | || _W dQ R X dS )a'  Compiles the model loss and weighted metric sub-graphs.

    This may be used to set graph tensors as sample weights (instead of creating
    placeholders). This functionality is necessary for
    `tf.keras.estimator.model_to_estimator`, which calls Keras models in a v1
    graph, and creates iterator tensors for inputs, targets, and sample weights.

    Args:
      sample_weights: List of tensors to use as the sample weights. Must be the
        same length as the number of outputs. If left as `None`, placeholders
        are used instead.
    NT)r[   r\   r   r]   return_weighted_metrics)r   r   r   r   r  r   r   r|   r   r   r   _prepare_total_lossr   )r>   r   r]   rB   rB   rC   r     s    

z0Model._compile_weights_loss_and_weighted_metricsc             C   s   dd | j D S )a  Boolean mask for whether the target in the output list should be skipped.

    If the loss function corresponding to a model output is None, then this
    output will be skipped during total loss calculation and feed targets
    preparation.

    Returns:
      A boolean list for whether the corresponding target in the output list
      should be skipped during loss calculation.
    c             S   s   g | ]}|d kqS )NrB   )rU   r   rB   rB   rC   r     s    z4Model._prepare_skip_target_masks.<locals>.<listcomp>)r   )r>   rB   rB   rC   r     s    z Model._prepare_skip_target_masksc             C   s   dd | j D S )z-Returns masks corresponding to model outputs.c             S   s   g | ]}t |d dqS )Z_keras_maskN)getattr)rU   r   rB   rB   rC   r     s    z/Model._prepare_output_masks.<locals>.<listcomp>)r|   )r>   rB   rB   rC   r     s    zModel._prepare_output_masksc             C   s  | j rtdg }td xNt| j|D ]<\}}| rDq0|jj}|j	}|j
}|j}| }	|j}
t|	 |dk	rt||j}|
dkr|}
ntj||
d\}}}
|
|9 }
t|dr|||}tj||
tjjd}|j}|tjjkrtjj}tj||d}n||||
d}tjj}W dQ R X t| jdkrH|| |tjjkr`t|}| ||  q0W |s| j!st"d	| #d| #| j$ }|rt%t&|}| t| t&|}|rt%|}nd
}W dQ R X |S )zComputes total loss from loss functions.

    Args:
        masks: List of mask values corresponding to each model output.

    Returns:
        A list of loss weights of python floats.

    Raises:
        TypeError: If model run_eagerly is True.
    zEtotal loss can not be computed when compiled with run_eagerly = True.ro   N)r   	reduction)r   r
  )r
  rH   z@The model cannot be compiled because it has no loss to optimize.g        )'rP   rc   r   
name_scoper   rt   r   training_targettargetoutputloss_fnloss_weightr   r   r,   castdtyper'   Zsqueeze_or_expand_dimensionsr   callZcompute_weighted_lossZReductionV2NONEr
  ZAUTOZSUM_OVER_BATCH_SIZEZreduce_weighted_lossr   r|   output_loss_metricZscale_loss_for_distributionr   r   rK   Zget_losses_forr{   Zadd_nZcast_losses_to_common_dtype)r>   r]   Z	loss_listr   masky_truey_predr  r  r   r   r   Zper_sample_lossesZweighted_lossesZloss_reductionZoutput_lossZcustom_lossesZtotal_custom_lossr   rB   rB   rC   r    sj    



zModel._prepare_total_lossc             C   s0   t | dr| jr| jS t | dr,| jr,| jS | S )z*Returns the Callback Model for this Model._replicated_modelcallback_model)r   r  r  )r>   rB   rB   rC   _get_callback_model{  s
    zModel._get_callback_modelc             C   s*   | j |d }t|| _| j|  d S )Nr   )r4   unwrapDistributedCallbackModelr  set_original_model)r>   Zgrouped_modelZfirst_replicated_modelrB   rB   rC   _make_callback_model  s    

zModel._make_callback_modelc             C   s  t |tjtjtjfs t|r<|dk	r8td	||dS | j
ddd}t|d}|rft|}|dk	rf| jrt| jr| jj}nd}|dk	r|| dkrtd	|||| }||krtd	||t |tjtjtjfrTttt|d d j}	|	dk	rT|	| dkr2td		|	||	| }
|
|krTtd
	|
||dkrf|| }|dkr~|dkr~d}|S )a  Validates that the `batch_size` provided is consistent with InputLayer.

    It's possible that the user specified a static batch size in their
    InputLayer. If so, this method checks the provided `batch_size` and `x`
    arguments are consistent with this static batch size. Also, if
    `batch_size` is `None`, this method will attempt to infer the batch size
    from the static batch size of the InputLayer. Lastly, ValueError will be
    raised if `x` is a tf.data.Dataset and `batch_size` is specified as we
    expect users to provide batched datasets.

    Args:
      batch_size: The batch_size provided as an argument to
        fit/evaluate/predict.
      steps: The steps provided as an argument to fit/evaluate/predict.
      x: The data passed as `x` to fit/evaluate/predict.

    Returns:
      The validated batch_size, auto-inferred from the first layer if not
      provided.
    NzlThe `batch_size` argument must not be specified for the given input type. Received input: {}, batch_size: {}F)r   r   rH   r   zOThe `batch_size` argument ({}) must be divisible the by number of replicas ({})zhThe `batch_size` argument value {} is incompatible with the specified batch size of your Input Layer: {}zXThe batch output shape of your `Dataset` {} cannot be divisible by number of replicas {}z{The batch output shape of your `Dataset` is {}, which is incompatible with the specified batch size of your Input Layer: {}    )rT   r   	DatasetV1	DatasetV2r%   r   r(   isgeneratorrK   r   r   nextr   Zget_static_batch_sizer4   r   Zglobal_batch_size_supportedZnum_replicas_in_syncr   r   r   r   Z	Dimensionr/   rg   Zget_legacy_output_shapesr   )r>   r   r   r   layersZfirst_layerZstatic_batch_sizeZnum_splits_for_dsZper_replica_batch_sizeZds_batch_sizeZds_per_replica_batch_sizerB   rB   rC   _validate_or_infer_batch_size  s\    












z#Model._validate_or_infer_batch_sizec             C   sr   |dk	r6t |t | jkrFtdt | jt |ndgt | j }x&t| j|D ]\}}|||j qTW dS )z*Sets sample weight attribute on the model.Nz^Provided sample weights must have same length as the number of outputs. Expected: {}, got: {}.)r   rt   rK   r   r   populate_sample_weightrq   )r>   r   r   weightrB   rB   rC   r    s    zModel._prepare_sample_weightsc             C   s   g }x>| j D ]4}|dks$|jjdkr0|d q||j  qW tj|| j|| j| j	d| _
tj|| j|| j| j	dd| _dS )zBCaches metric name and function attributes for every model output.N)rR   T)rR   Zis_weighted)r|   shapeZrankr   r   r   Zcollect_per_output_metric_infor~   r   r`   _per_output_metrics_per_output_weighted_metrics)r>   r   r   Zoutput_shapesr  rB   rB   rC   r     s    z%Model._cache_output_metric_attributesc             C   s\   t | jdkr,t|dds,d| j| |f }d}|}x"|| jkrVd||f }|d7 }q6W |S )a  Makes the metric name unique.

      If there are multiple outputs for which the metrics are calculated, the
      metric names have to be made unique by appending an integer.

    Args:
      metric_name: Metric name that corresponds to the metric specified by the
          user. For example: 'acc'.
      metric_fn: The Metric object.
      output_index: The index of the model output for which the metric name is
        being added.

    Returns:
      string, name of the model's unique metric name
    rH   r`   Fz%s_%sz%s_%d)r   r~   r	  r   )r>   metric_name	metric_fnoutput_indexjZbase_metric_namerB   rB   rC   _add_unique_metric_name  s    zModel._add_unique_metric_namec             C   s
   g | _ dS )z$Initialized model metric attributes.N)r   )r>   rB   rB   rC   ry   3  s    zModel._init_metric_attributesc             C   sJ   t  }x<| D ]0\}}| |||}||_|||< | j| qW |S )aL  Sets the metric attributes on the model for the given output.

    Args:
      metrics_dict: A dict with metric names as keys and metric fns as values.
      output_index: The index of the model output for which the metric
        attributes are added.

    Returns:
      Metrics dict updated with unique metric names as keys.
    )r   OrderedDictitemsr0  _namer   r   )r>   metrics_dictr.  Zupdated_metrics_dictr,  r-  rB   rB   rC   !_set_per_output_metric_attributes9  s    
z'Model._set_per_output_metric_attributesc             C   s   g }g }xpt | jD ]b\}}| rF|| j|  || j|  q|| | j| | || | j| | qW t| jdkrx(| jD ]}| stj	|
 d|_qW || _|| _dS )zBSets the metric attributes on the model for all the model outputs.rH   )rY   N)	enumeratert   r   r   r*  r+  r5  r   metrics_moduleZMeanr   r  )r>   Zupdated_per_output_metricsZ#updated_per_output_weighted_metricsir   rB   rB   rC   r   P  s*    zModel._set_metric_attributesc       
   
   C   sR   g }xH|  D ]<\}}t|$ tj|||||d}	||	 W dQ R X qW |S )ap  Calls metric functions for a single output.

    Args:
      metrics_dict: A dict with metric names as keys and metric fns as values.
      y_true: Target output.
      y_pred: Predicted output.
      mask: Computed mask value for the current output.
      weights: Weights to be applied on the current output.

    Returns:
      A list of metric result tensors.
    )weightsr  N)r2  r   r  r   Zcall_metric_functionr   )
r>   r4  r  r  r  r9  metric_resultsr,  r-  Zmetric_resultrB   rB   rC   _handle_per_output_metricsm  s    z Model._handle_per_output_metricsc             C   s   |pdgt | }g }td xtt |D ]}	||	 r>q0|rJ||	 nd}
|rZ||	 nd}|rj||	 nd}|sv|s|| | j|	 ||
| |s|r0|| j| j|	 ||
||r||	 ndd q0W W dQ R X |S )a  Handles calling metric functions.

    Args:
      outputs: List of outputs (predictions).
      targets: List of targets.
      skip_target_masks: Optional. List of boolean for whether the corresponding
        target should be ignored or not.
      sample_weights: Optional list of sample weight arrays.
      masks: List of computed output mask values.
      return_weighted_metrics: Flag that indicates whether weighted metrics
        should be computed instead of unweighted metrics. This flag is ignored
        when `return_weighted_and_unweighted_metrics` is enabled.
      return_weighted_and_unweighted_metrics: Flag that is used to indicate
        whether both weighted and unweighted metrics should be computed. When
        this is not enabled, we use `return_weighted_metrics` param to indicate
        whether weighted or unweighted metrics should be returned.

    Returns:
      A list of metric result tensors.
    Fr   N)r9  )r   r   r  ranger   r;  r*  r+  )r>   r|   r[   r\   r   r]   r  Z&return_weighted_and_unweighted_metricsr:  r8  r  r  Zoutput_maskrB   rB   rC   r     s.    $zModel._handle_metricsc             C   s6   t | dsdS t| jt| jkr2ttjdd dS )aC  Check trainable weights count consistency.

    This will raise a warning if `trainable_weights` and
    `_collected_trainable_weights` are inconsistent (i.e. have different
    number of parameters).
    Inconsistency will typically arise when one modifies `model.trainable`
    without calling `model.compile` again.
    r   NzDiscrepancy between trainable weights and collected trainable weights, did you set `model.trainable` without calling `model.compile` after ?rH   )r   r   r   r   ri   Zlog_first_nWARN)r>   rB   rB   rC   $_check_trainable_weights_consistency  s    	
z*Model._check_trainable_weights_consistencyc          
   C   sF  |   }|   t| jtr$tdt| dd d ks:|rB|  }| | j	 | j
| j | j }tt ts||t g7 }t  d td8 | jj| j| jd}|| d 7 }|| | j7 }W d Q R X |  }dd |D }W d Q R X td6 tj|| jg| f|dd| j}t| d| W d Q R X | | d S )Nz:The `optimizer` in `compile` should be a single optimizer.r   r   )paramsro   c             S   s   g | ]}t |d r|jqS )_call_result)r   r@  )rU   r   rB   rB   rC   r     s    z.Model._make_train_function.<locals>.<listcomp>)updatesrY   )r  r>  rT   rX   r   rK   r	  ru   Z_set_trainable_staterv   _feed_inputs_feed_targets_feed_sample_weightsr   r   r   r   r   r  Zget_updatesr   r   Zget_updates_forr{   r   functionrd   setattr)r>   has_recompiledZcurrent_trainable_stater{   rA  r   metrics_tensorsfnrB   rB   rC   r     s6    

zModel._make_train_functionc          	   C   s   |   }t| dd d ks|r| j| j | j }t   |  }dd |D }W d Q R X t	d< | j
}tj|| jg| f|dd| j}t| d| W d Q R X d S )Nr   c             S   s   g | ]}t |d r|jqS )r@  )r   r@  )rU   r   rB   rB   rC   r     s    z-Model._make_test_function.<locals>.<listcomp>Z
evaluation)rA  rY   )r  r	  rB  rC  rD  r   r   r   r   r  state_updatesrE  r   rd   rF  )r>   rG  r{   r   rH  rA  rI  rB   rB   rC   r      s    

zModel._make_test_functionc          	   C   sh   t | dsd | _| jd krd| j}t| di }ttj& tj|| j	f| j
dd|| _W d Q R X d S )Nr   rd   )rA  rY   )r   r   rB  r	  r   r  r*   PREDICTrE  r|   rJ  )r>   r{   r@   rB   rB   rC   r     s    

zModel._make_predict_functionc             C   sL   |t jkr|   | jS |t jkr0|   | jS |t jkrH|   | j	S d S )N)
r*   ZTRAINr   r   ZTESTr   r   rK  r   r   )r>   moderB   rB   rC   _make_execution_function+  s    


zModel._make_execution_functionc
          	   C   s  |rt d|dk	r0| r0t| jr0t dt|tjrJ|rJt	| | j}
|

 , t rjd}nt }t|d }t|tjr`t|}|dk	rt|}|dk	rt|}|||f}q||f}n|}|
jj||d}|r|td|d }|dkr||}|	 o |
jj}t|
rP|sP|jd }|| dkrPd	}|j||d
}n"t|tjsrtt|||| W dQ R X |S )a+  Runs validation checks on input and target data passed by the user.

    This is called when using tf.distribute.Strategy to train, evaluate or serve
    the model.

    Args:
      x: Input data. A numpy array or `tf.data` dataset.
      y: Target data. A numpy array or None if x is a `tf.data` dataset.
      sample_weight: An optional sample-weight array passed by the user to
        weight the importance of each sample in `x`.
      class_weight: An optional class-weight array by the user to
        weight the importance of samples in `x` based on the class they belong
        to, as conveyed by `y`.
      batch_size: Integer batch size. If provided, it is used to run additional
        validation checks on stateful models.
      validation_split: Float between 0 and 1.
        Fraction of the training data to be used as validation data.
      shuffle: Boolean whether to shuffle the training data before each epoch.
      epochs: Integer epochs. If > 1, repeat the numpy training data epochs
        times when converting to training dataset.
      allow_partial_batch: Boolean whether to enforce that all batches have the
        same size.

    Returns:
      Dataset instance.

    Raises:
      ValueError: In case of invalid user-provided data.
      RuntimeError: If the model was never compiled.
    zL`class_weight` is currently not supported when using tf.distribute.Strategy.NzB`sample_weight` is currently not supported when using TPUStrategy.r   )sessioni      rH   T)drop_remainder)rl   allr   rI   r4   rT   r   r"  r   verify_dataset_shuffledrF   r   r6   Zget_sessionr/   rg   npZndarrayr   Zlist_to_tuplerJ   Zexperimental_make_numpy_datasetr   maxrepeatZ"experimental_require_static_shapesr)  batchAssertionErrorvalidate_dataset_input)r>   r   r   r   r   r   r   r   r   Zallow_partial_batchrE   rN  Zfirst_x_valueZin_tupleZdsrP  Zdataset_sizerB   rB   rC   #_distribution_standardize_user_data6  sP    (








z)Model._distribution_standardize_user_datar   c          
   C   sF  t |tjtjfrJt||||	 |
r0t| d}|rt|\}}}n:t |tj	rt||||	 |}t
|\}}}d}nd}|rt||| | js| ||\}}}d}ng }t | jt}d}|}d}| js| jr| |||| d}| j}|s,|r,|r,|s,tdd |D r,g g dfS | j||||||||dS )a  Runs validation checks on input and target data passed by the user.

    Also standardizes the data to lists of arrays, in order.

    Also builds and compiles the model on the fly if it is a subclassed model
    that has never been called before (and thus has no inputs/outputs).

    This is a purely internal method, subject to refactoring at any time.

    Args:
      x: Input data. It could be:
        - A Numpy array (or array-like), or a list of arrays
          (in case the model has multiple inputs).
        - A TensorFlow tensor, or a list of tensors
          (in case the model has multiple inputs).
        - A dict mapping input names to the corresponding array/tensors,
          if the model has named inputs.
        - A `tf.data` dataset.
      y: Target data. Like the input data `x`,
        it could be either Numpy array(s) or TensorFlow tensor(s).
        It should be consistent with `x` (you cannot have Numpy inputs and
        tensor targets, or inversely). If `x` is a dataset, `y` should not be
        specified (since targets will be obtained from the iterator).
      sample_weight: An optional sample-weight array passed by the user to
        weight the importance of each sample in `x`.
      class_weight: An optional class-weight array by the user to
        weight the importance of samples in `x` based on the class they belong
        to, as conveyed by `y`. If both `sample_weight` and `class_weight` are
        provided, the weights are multiplied.
      batch_size: Integer batch size. If provided, it is used to run additional
        validation checks on stateful models.
      check_steps: boolean, True if we want to check for validity of `steps` and
        False, otherwise. For example, when we are standardizing one batch of
        data for train_on_batch/predict_on_batch/test_on_batch APIs, `steps`
        value is not required and we should not check for its validity in these
        cases.
      steps_name: The public API's parameter name for `steps`.
      steps: Integer or `None`. Total number of steps (batches of samples) to
        execute.
      validation_split: Float between 0 and 1.
        Fraction of the training data to be used as validation data.
      shuffle: Boolean whether to shuffle the training data before each epoch.
      extract_tensors_from_dataset: Boolean. When `x` is a dataset instance,
        this indicates whether to extract actual tensors from the dataset or
        instead output the dataset instance itself.
        Set to True when calling from `train_on_batch`/etc.

    Returns:
      A tuple of 3: inputs (arrays or dicts, depending on whether `x` was a dict
      or not), target arrays, sample-weight arrays.
      If the model's input and targets are symbolic, these lists are empty
      (since the model takes no user-provided data, instead the data comes
      from the symbolic inputs/targets).

    Raises:
      ValueError: In case of invalid user-provided data.
      RuntimeError: If the model was never compiled.
    TFc             s   s   | ]}t |V  qd S )N)_is_symbolic_tensor)rU   r   rB   rB   rC   rW   $	  s    z/Model._standardize_user_data.<locals>.<genexpr>N)rP   dict_inputs
is_datasetr   r   )rT   r   r!  r"  r   rX  rR  r   r   r   Zunpack_iterator_inputZcheck_steps_argumentr{   _build_model_with_inputsr   r}   rX   _compile_from_inputsrP   rf   _standardize_tensors)r>   r   r   r   r   r   Zcheck_stepsr   r   r   r   r   r\  iterator
all_inputsZy_inputr[  Zis_build_calledZis_compile_calledrP   rB   rB   rC   r     sN    F




zModel._standardize_user_datac	             C   s  |r| j }	d }
n| js"| j}	d }
n| j}	| j}
t|tjtjfsTtj	||	|
ddd}t|tjr~t
|}t|tr|d }nntj|dd}tj| jdd}g }x&t||D ]\}}|t|| qW tj||dd}dd }t||}tj|dd}tj| jdd}x(t||D ]\}}tj||dd qW |d k	r t| j| j | j}| j}| jshd }n| j}tj	||d dd	d
}t||}t||}dd t||||D }| jst||| | jr|st|| j | t!j"|||dd\}}}ng }d }| j#rR|rR|sR|d j$d | dkrRt%dt&|d j$d  d |rzt|tjtjfszt't|	|}|||fS )NFinput)check_batch_axisexception_prefixr   )Zexpand_compositesc             S   sB   t | r| jS t| dr4t| dr4t| j| jS t	| S dS )z9Grab type_spec without converting array-likes to tensors.r)  r  N)
r)   Zis_extension_typeZ
_type_specr   r   
TensorSpecr)  r  r   Ztype_spec_from_value)r   rB   rB   rC   _type_spec_from_value]	  s
    
z9Model._standardize_tensors.<locals>._type_spec_from_valueTr  )Zshapesrc  rd  c             S   s$   g | ]\}}}}t ||||qS rB   )r   Zstandardize_weights)rU   refswZcwrL  rB   rB   rC   r   	  s   z.Model._standardize_tensors.<locals>.<listcomp>)Zcheck_all_flatzzIn a stateful network, you should only pass inputs with a number of samples that can be divided by the batch size. Found: z samples)(input_namesZ_is_graph_network_feed_input_names_feed_input_shapesrT   r   r!  r"  r   Zstandardize_input_dataZget_structurer   r/   rg   r{   r   r   _convert_scipy_sparse_tensorZpack_sequence_asmap_structureZassert_same_structurer   rt   rq   _feed_output_names_sample_weight_modes_feed_output_shapesZstandardize_sample_weightsZstandardize_class_weightsr4   Zcheck_array_lengthsZ#check_loss_and_target_compatibility_feed_loss_fnsr   Zhandle_partial_sample_weightsZstatefulr)  rK   r   r   )r>   r   r   r   rP   r[  r\  r   r   Zfeed_input_namesZfeed_input_shapesZx_shapesZflat_inputsZflat_expected_inputsZconverted_xabrf  Zfeed_output_namesZfeed_sample_weight_modesZfeed_output_shapesr   Zclass_weightsr   rB   rB   rC   r_  /	  s    




zModel._standardize_tensorsc                s$  g }d} }t  tjtjfr.t \ }}t | t  ttfrV|t 7 }n8t  t	rd}t
  } fdd|D }n
|  x$|D ]}t|rtd|f qW t |tjtjtjfr| jst | j dd }	t|	 }
nt rt }
n }
| |
 |||fS )zFBuild the model (set model inputs/outputs), mainly for subclass model.FTc                s   g | ]} | qS rB   rB   )rU   k)r{   rB   rC   r   	  s    z2Model._build_model_with_inputs.<locals>.<listcomp>as  All SparseTensor and RaggedTensor inputs must be explicitly declared using a keras.Input() with sparse=True or ragged=True. We found an undeclared input %s. For Sequential models, please add a keras.Input() as your first Layer. For subclassed models, please call self._set_inputs() on your input set, which you can create using keras.Input() for each input to your model.c             S   s   t | j| jS )N)r   re  r)  r  )r   rB   rB   rC   create_tensor_spec	  s    z:Model._build_model_with_inputs.<locals>.create_tensor_spec)rT   r   r!  r"  r   r   validate_input_typesr   r   r   sortedrb   r   Zis_composite_or_composite_valuerK   r   r   r{   r   r  r/   rm  has_tensors_set_inputs)r>   r{   r[   Zprocessed_inputsZis_dict_inputsorig_inputsr   rb   Zinput_tensorru  Zcast_inputsrB   )r{   rC   r]  	  s<    





zModel._build_model_with_inputsc             C   s   |d k	rXt |r t || j}t j||ddd t|ttfrN|t|7 }n
|| t	dd |D rt
dd |D stdt| d t| t|tjtjtjf}|st rd }n0|d k	rt|ttfs|g}d	d
 |D }nd }| j| j| j| j| j| j|| j| j| jd	 d S )NFr  )Z
allow_dict
field_namec             s   s   | ]}t |V  qd S )N)r   r  )rU   r   rB   rB   rC   rW   	  s    z-Model._compile_from_inputs.<locals>.<genexpr>c             s   s   | ]}t |V  qd S )N)r   r  )rU   r   rB   rB   rC   rW   	  s    zODo not pass inputs that mix Numpy arrays and TensorFlow tensors. You passed: x=z; y=c             S   s   g | ]}t |r|qS rB   )rZ  )rU   r   rB   rB   rC   r   
  s    z.Model._compile_from_inputs.<locals>.<listcomp>)	rX   ro   r   r   rp   r   rq   rP   rQ   )r   rx  Z#cast_if_floating_dtype_and_mismatchr|   rv  rT   r   r   r   rf   rQ  rK   r   r   r!  r"  r   r   r   rx   r   rX   ro   rr   rs   rp   rq   rP   r<   )r>   ra  r  rz  Zorig_targetr\  r   rB   rB   rC   r^  	  sB    



zModel._compile_from_inputsc             C   s   |  | | |}|dkrxi }| jrN|dkr>t s>t }|dk	rN||d< y| |f|}W n tk
rv   d}Y nX | | dS )an  Set model's input and output specs based on the input data received.

    This is to be used for Model subclasses, which do not know at instantiation
    time what their inputs look like.

    Args:
      inputs: Single array, or list of arrays. The arrays could be placeholders,
        Numpy arrays, data tensors, or TensorSpecs.
        - if placeholders: the model is built on top of these placeholders,
          and we expect Numpy data to be fed for them when calling `fit`/etc.
        - if Numpy data or TensorShapes: we create placeholders matching the
          TensorShapes or shapes of the Numpy arrays. We expect Numpy data to be
          fed for these placeholders when calling `fit`/etc.
        - if data tensors: the model is built on top of these tensors.
          We do not expect any Numpy data to be provided when calling `fit`/etc.
      outputs: None, a data tensor, or a list of tensors. If None, the
        outputs will be determined by invoking `self.call()`, otherwise the
        provided value will be used.
      training: Boolean or None. Only relevant in symbolic mode. Specifies
        whether to build the model's graph in inference mode (False), training
        mode (True), or using the Keras learning phase (None).
    Raises:
      ValueError: If dict inputs are passed to a Sequential Model where the
        first layer isn't FeatureLayer.
    Nr   )	Z_set_save_spec_set_input_attrsZ_expects_training_argr   r6   r   Zlearning_phaserl   _set_output_attrs)r>   r{   r|   r   r@   rB   rB   rC   ry  
  s    


zModel._set_inputsc             C   sH  | j rtd| jjdkr| jst|rFdt|j	 dd  }ndt
|tjrldt|	 dd  }n>t
|trt| jd stdd}ndt|jdd  }|| _| |}t|}| }|jdd	| _ | | _g | _g | _g | _xL| D ]@\}}t|r | j| | j| | jt| q W |S )
z3Sets attributes related to the inputs of the Model.zModel inputs are already set.Z
Sequential)NrH   Nr   zpPassing a dictionary input to a Sequential Model which doesn't have FeatureLayer as the first layer is an error.T)Zreturn_single_as_list)r{   rK   rA   __name__rz   r   r  r   r)  r   rT   r   ZTensorShaper   r   Zis_feature_layerr%  Z_build_input_shapeZ_maybe_cast_inputsr   Zget_symbolic_inputsZget_input_namesri  rB  rj  rk  as_dictr   is_placeholderr   	int_shape)r>   r{   Zinput_shapeZmodel_inputsrt  r   rB   rB   rC   r|  K
  s6    




zModel._set_input_attrsc             C   s&   t |}|| _t|| _d| _dS )z4Sets attributes related to the outputs of the Model.TN)r/   rg   r|   r   Zgeneric_output_namesr~   rz   )r>   r|   rB   rB   rC   r}  x
  s    
zModel._set_output_attrsc             C   s   dd | j D S )z(The output target tensors for the model.c             S   s   g | ]}|  r|jjqS rB   )has_training_targetr  r  )rU   r   rB   rB   rC   r   
  s   z"Model._targets.<locals>.<listcomp>)rt   )r>   rB   rB   rC   r   
  s    zModel._targetsc             C   s   dd | j D S )Nc             S   s   g | ]}|  r|jjqS rB   )has_feedable_training_targetr  r  )rU   r   rB   rB   rC   r   
  s   z'Model._feed_targets.<locals>.<listcomp>)rt   )r>   rB   rB   rC   rC  
  s    zModel._feed_targetsc             C   s   dd | j D S )Nc             S   s   g | ]}|  r|jqS rB   )r  output_name)rU   r   rB   rB   rC   r   
  s   z,Model._feed_output_names.<locals>.<listcomp>)rt   )r>   rB   rB   rC   rn  
  s    zModel._feed_output_namesc             C   s   dd | j D S )Nc             S   s   g | ]}|  r|jqS rB   )r  feed_output_shape)rU   r   rB   rB   rC   r   
  s   z-Model._feed_output_shapes.<locals>.<listcomp>)rt   )r>   rB   rB   rC   rp  
  s    zModel._feed_output_shapesc             C   s   dd | j D S )Nc             S   s   g | ]}|  r|jqS rB   )r  r  )rU   r   rB   rB   rC   r   
  s   z(Model._feed_loss_fns.<locals>.<listcomp>)rt   )r>   rB   rB   rC   rq  
  s    zModel._feed_loss_fnsc             C   s   dd | j D S )Nc             S   s   g | ]
}|j qS rB   )r  )rU   r   rB   rB   rC   r   
  s    z,Model._loss_weights_list.<locals>.<listcomp>)rt   )r>   rB   rB   rC   _loss_weights_list
  s    zModel._loss_weights_listc             C   s   t | drdd | jD S d S )Nrt   c             S   s   g | ]}|j d k	r|j qS )N)r  )rU   r   rB   rB   rC   r   
  s   z.Model._output_loss_metrics.<locals>.<listcomp>)r   rt   )r>   rB   rB   rC   r   
  s    

zModel._output_loss_metricsc             C   s   dd | j D S )Nc             S   s   g | ]
}|j qS rB   )r   )rU   r   rB   rB   rC   r   
  s    z(Model.sample_weights.<locals>.<listcomp>)rt   )r>   rB   rB   rC   r   
  s    zModel.sample_weightsc             C   s   dd | j D S )Nc             S   s   g | ]
}|j qS rB   )rq   )rU   r   rB   rB   rC   r   
  s    z.Model._sample_weight_modes.<locals>.<listcomp>)rt   )r>   rB   rB   rC   ro  
  s    zModel._sample_weight_modesc             C   s   dd | j D S )Nc             S   s   g | ]}|j d k	r|j qS )N)r   )rU   r   rB   rB   rC   r   
  s    z.Model._feed_sample_weights.<locals>.<listcomp>)rt   )r>   rB   rB   rC   rD  
  s    zModel._feed_sample_weightsc             C   s   | j dk	r| j ||S |S )a$  Maybe load initial epoch from ckpt considering possible worker recovery.

    Refer to tensorflow/python/keras/distribute/worker_training_state.py
    for more information.

    Args:
      initial_epoch: The original initial_epoch user passes in in `fit()`.
      mode: The mode for running `model.fit()`.

    Returns:
      If the training is recovering from previous failure under multi-worker
      training setting, return the epoch the training is supposed to continue
      at. Otherwise, return the `initial_epoch` the user passes in.
    N)Z_training_stateZ"maybe_load_initial_epoch_from_ckpt)r>   r   rL  rB   rB   rC   #_maybe_load_initial_epoch_from_ckpt
  s    
z)Model._maybe_load_initial_epoch_from_ckptc             C   s4   g }| t| ddpg  | t| ddp,g  |S )zReturns all the metrics that are to be reported.

    This includes the output loss metrics, compile metrics/weighted metrics,
    add_metric metrics.
    r   Nr   )r   r	  )r>   r   rB   rB   rC   r   
  s    z Model._get_training_eval_metricsc             C   s   | j stdd S )NzZYou must compile your model before training/testing. Use `model.compile(optimizer, loss)`.)_compile_was_calledRuntimeError)r>   rB   rB   rC   r   
  s    z Model._assert_compile_was_calledc             C   s(   | j }|st rt }|o&|j S )a  Method to infer if this `Model` is working in multi-worker settings.

    Multi-worker training refers to the setup where the training is
    distributed across multiple workers, as opposed to the case where
    only a local process performs the training. This function is
    used to infer for example whether or not a distribute coordinator
    should be run, and thus TensorFlow servers should be started for
    communication with other servers in the cluster, or whether or not
    saving/restoring checkpoints is relevant for preemption fault tolerance.

    Experimental. Signature and implementation are subject to change.

    Returns:
      Whether this model indicates it's working in multi-worker settings.
    )r4   r   r7   r9   rJ   r   )r>   rE   rB   rB   rC   r   
  s    zModel._in_multi_worker_modec             C   s
   t | S )N)r$   ZModelSavedModelSaver)r>   rB   rB   rC   _trackable_saved_model_saver  s    z"Model._trackable_saved_model_saverc             C   s(   ~|    | j| j| j| j| jd}|S )N)ro   r   rp   rq   r   )r   ro   rr   rp   rq   rs   )r>   Zuser_metricsr@   rB   rB   rC   _get_compile_args  s    
zModel._get_compile_argsc             C   s   | j S )N)r=   )r>   rB   rB   rC   r    s    zModel._compile_was_called)FF)rO   NNNNNNN)NNNrH   rH   Nr   NTNNr   NNrH   r   rH   F)
NNNrH   NNNr   rH   F)Nr   NNr   rH   F)NNNT)NNT)NrH   rH   NNNrH   Nr   rH   FTr   )NNr   rH   Fr   )NNr   rH   Fr   )N)N)N)N)NNNNFF)NNNNr   FrH   F)
NNNNFr   Nr   FF)NN)NN)T)Sr~  
__module____qualname____doc__r3   rD   rn   Z no_automatic_dependency_trackingr8   rG   rL   r   r   propertyr   r   rP   setterr   r   r   r   r   r   r   r   r   r   r   r   re   r   rm   r   r   r   r  r   r   r   r  r  r  r&  r  r   r0  ry   r5  r   r;  r   r>  r   r   r   rM  rY  r   r_  r]  r^  ry  r|  r}  r   rC  rn  rp  rq  r  r   r   ro  rD  r  r   r   r   r  r  r  __classcell__rB   rB   )rA   rC   r1   K   sL  >5        u'&                 
 7         
a      
D   
Y
L0            
     
     
)(

$_\
#"
     
1/       
h         
 
?.
/-	


r1   c                   sR   e Zd ZdZ fddZdd Zddd	Zdd
dZdddZ fddZ	  Z
S )r  z=Model that is used for callbacks with tf.distribute.Strategy.c                s   t t|   |j| _d S )N)r2   r  r3   rX   )r>   model)rA   rB   rC   r3     s    z!DistributedCallbackModel.__init__c             C   s
   || _ d S )N)_original_model)r>   Z
orig_modelrB   rB   rC   r  #  s    z+DistributedCallbackModel.set_original_modelTNc             C   s   | j j|||d d S )N)rZ   save_format)r  save_weights)r>   rM   rZ   r  rB   rB   rC   r  &  s    
z%DistributedCallbackModel.save_weightsc             C   s*   |   }| j| | jj|ddd d S )NTF)rZ   include_optimizer)rG   r  set_weightssave)r>   rM   rZ   r  Zdistributed_model_weightsrB   rB   rC   r  *  s    zDistributedCallbackModel.saveFc             C   s0   | j j|dd | j  }t| j j| | d S )NF)rN   )r  rL   rG   r   r  r4   )r>   rM   rN   Zorig_model_weightsrB   rB   rC   rL   2  s
    
z%DistributedCallbackModel.load_weightsc                s*   |dkrt d| d  tt| |S )N)Z_setattr_trackingZ_layerszYou are accessing attribute zF of the DistributedCallbackModel that may not have been set correctly.)ri   rj   r2   r  __getattr__)r>   item)rA   rB   rC   r  :  s    z$DistributedCallbackModel.__getattr__)TN)TT)F)r~  r  r  r  r3   r  r  r  rL   r  r  rB   rB   )rA   rC   r    s   


r  c               @   s  e Zd ZdZd/ddZedd Zedd Zed	d
 Zedd Z	edd Z
e
jdd Z
edd Zejdd Zd0ddZedd Zejdd Zedd Zejdd Zedd Zejdd Zdd  Zd!d" Zd#d$ Zd%d& Zd'd( Zed)d* Zd+d, Zd-d. ZdS )1r   a  A container for the training output/target and related entities.

  In the case of model with multiple outputs, there is a one-to-one mapping
  between model output (y_pred), model target (y_true), loss, metrics etc.
  By unifying these entities into one class, different entity can access
  information between each other, rather than currently access different list of
  attributes of the model.
  Nc	       	      C   s4   || _ || _|| _|| _|| _|| _|| _|| _dS )aE  Initialize the _TrainingEndpoint.

    Note that the output and output_name should be stable as long as the model
    structure doesn't change. The training_target suppose to be mutable since
    the information is provided via `compile()`

    Args:
      output: the output tensor of the model.
      output_name: the unique name of the output tensor.
      loss_fn: the loss function for the output tensor.
      loss_weight: float, the weights for the loss.
      training_target: the _TrainingTarget for the model.
      output_loss_metric: the metric object for the loss function.
      sample_weight: the weights for how a sample is weighted during metric and
        loss calculation. Could be None.
      sample_weight_mode: string, 'temporal', 'samplewise' or None. The mode for
        how the sample_weight is populated.
    N)_output_output_name_loss_fn_loss_weight_training_target_output_loss_metric_sample_weight_sample_weight_mode)	r>   r  r  r  r  r  r  r   rq   rB   rB   rC   r3   N  s    z_TrainingEndpoint.__init__c             C   s   | j S )N)r  )r>   rB   rB   rC   r  r  s    z_TrainingEndpoint.outputc             C   s   | j S )N)r  )r>   rB   rB   rC   r  v  s    z_TrainingEndpoint.output_namec             C   s   t | jS )N)r   r  r  )r>   rB   rB   rC   r)  z  s    z_TrainingEndpoint.shapec             C   s   | j S )N)r  )r>   rB   rB   rC   r  ~  s    z_TrainingEndpoint.loss_fnc             C   s   | j S )N)r  )r>   rB   rB   rC   r    s    z_TrainingEndpoint.loss_weightc             C   s
   || _ d S )N)r  )r>   r   rB   rB   rC   r    s    c             C   s   | j S )N)r  )r>   rB   rB   rC   r    s    z!_TrainingEndpoint.training_targetc             C   s
   || _ d S )N)r  )r>   r   rB   rB   rC   r    s    Fc             C   s   |   rtd|r(tdddd| _dS |  r<td| _nz|dk	rXt|sXd}d}nd}d}|dkrtj	| j
t| j}tjt| j| jd t| j|d}t|||d| _dS )a  Create training_target instance and update the self.training_target.

    Note that the input target should just be a tensor or None, and
    corresponding training target will be created based on the output and
    loss_fn.

    Args:
      target: the target tensor for the current output. Could be None.
      run_eagerly: boolean, whether the model is in run_eagerly mode.

    Raises:
      ValueError if the training_target field for the current instance has
      already been populated.
    zWThe training_target field for the _TrainingEndpoint instance has already been populatedNTF)feedableskip_target_weights_target)ndimrY   sparser  )r  rK   _TrainingTargetr  r   r   r  r   ZLABEL_DTYPES_FOR_LOSSESr   r  r  r  placeholderr   r)  r  	is_sparse)r>   r  rP   r  r  Ztarget_dtyperB   rB   rC   r     s2    
z(_TrainingEndpoint.create_training_targetc             C   s   | j S )N)r  )r>   rB   rB   rC   r    s    z$_TrainingEndpoint.output_loss_metricc             C   s
   || _ d S )N)r  )r>   r   rB   rB   rC   r    s    c             C   s   | j S )N)r  )r>   rB   rB   rC   r     s    z_TrainingEndpoint.sample_weightc             C   s
   || _ d S )N)r  )r>   r   rB   rB   rC   r     s    c             C   s   | j S )N)r  )r>   rB   rB   rC   rq     s    z$_TrainingEndpoint.sample_weight_modec             C   s
   || _ d S )N)r  )r>   r   rB   rB   rC   rq     s    c             C   s
   | j d kS )N)r  )r>   rB   rB   rC   r     s    z$_TrainingEndpoint.should_skip_targetc             C   s   |   p| jd kp| jjS )N)r   r  r  )r>   rB   rB   rC   should_skip_target_weights  s    z,_TrainingEndpoint.should_skip_target_weightsc             C   s
   | j d k	S )N)r  )r>   rB   rB   rC   r    s    z%_TrainingEndpoint.has_training_targetc             C   s   |    o| jd k	o| jjS )N)r   r  r  )r>   rB   rB   rC   r    s    
z._TrainingEndpoint.has_feedable_training_targetc             C   s   | j d k	r| jd S d S )NZ_loss)r  r  )r>   rB   rB   rC   r     s    

z_TrainingEndpoint.loss_namec             C   s   |   sdS t| jtjr(| jjtjks6t| jtjrrt	 dkr^| j
d df| j
dd  S | j
dd d S n<t| jtjrt| jtjrtt| jjjddkrdS | j
S dS )z)The output shape for the feedable target.NZchannels_firstr   rH   r   )rH   )r  rT   r  r   ZLossFunctionWrapperrI  Zsparse_categorical_crossentropyZSparseCategoricalCrossentropyr   Zimage_data_formatr)  ZLossr	  r~  )r>   rB   rB   rC   r    s    z#_TrainingEndpoint.feed_output_shapec             C   s(   | j dk	r| jdkp&| j dko&| jdk	S )z5Check if the sample weight and the mode match or not.N)rq   r   )r>   rB   rB   rC   r    s    z)_TrainingEndpoint.sample_weights_mismatchc             C   s   |dkr*|   s |dks t r*d| _dS |dks6t|dkrPdgg}ddg}ndg}dg}|dk	r|j|std|j||| _n&t	j
tj|t d|| jd d| _dS )	z?Populate the sample weight and based on the sample weight mode.N)temporalr  r  g      ?z8Received sample weight with shape {}. Expected shape {}.)r  Z_sample_weights)r)  rY   )r  r   rx   r  rW  r)  Zis_compatible_withrK   r   r+   Zplaceholder_with_defaultr
   Zconstantr   Zfloatxr  )r>   r   rq   default_valuer)  rB   rB   rC   r'    s(    
z(_TrainingEndpoint.populate_sample_weight)NNNNN)F)r~  r  r  r  r3   r  r  r  r)  r  r  r  r  r   r  r   rq   r   r  r  r  r   r  r  r'  rB   rB   rB   rC   r   D  s:       

2r   c               @   s>   e Zd ZdZdddZedd Zedd	 Zed
d ZdS )r  a  Container for a target tensor (y_true) and its metadata (shape, loss...).

  Args:
    target: A target tensor for the model. It may be `None` if the
      output is excluded from loss computation. It is still kept as None
      since each output of the model should have a corresponding target. If
      the target is None, the rest of the attributes will be None as well.
    feedable: Boolean, whether the target is feedable (requires data to be
      passed in `fit` or `train_on_batch`), or not (model compiled with
      `target_tensors` argument).
    skip_target_weights: Boolean, whether the target should be skipped during
      weights calculation.
  FTc             C   s   || _ || _|| _d S )N)r  	_feedable_skip_target_weights)r>   r  r  r  rB   rB   rC   r3   ;  s    z_TrainingTarget.__init__c             C   s   | j S )N)r  )r>   rB   rB   rC   r  @  s    z_TrainingTarget.targetc             C   s   | j S )N)r  )r>   rB   rB   rC   r  D  s    z_TrainingTarget.feedablec             C   s   | j S )N)r  )r>   rB   rB   rC   r  H  s    z#_TrainingTarget.skip_target_weightsN)FT)	r~  r  r  r  r3   r  r  r  r  rB   rB   rB   rC   r  ,  s
   
r  c             C   s
   t | S )N)r   r  )r   rB   rB   rC   rZ  M  s    rZ  c             C   s   t dk	rt | rt|rl|  }|j|j }}|j|j }}t	t
|dt
|dfd}t|||S t r|td|  S n| S dS )aV  Handle scipy sparse tensor conversions.

  This method takes a value 'value' and returns the proper conversion. If
  value is a scipy sparse tensor and the expected input is a dense tensor,
  we densify 'value'. If value is a scipy sparse tensor and the expected input
  is a TF SparseTensor, we convert 'value' to a SparseTensor. If 'value' is
  not a scipy sparse tensor, or scipy is not imported, we pass it through
  unchanged.

  Args:
    value: An object that may be a scipy sparse tensor
    expected_input: The expected input placeholder.

  Returns:
    The possibly-converted 'value'.
  NrH   zA SciPy sparse matrix was passed to a model that expects dense inputs. Please densify your inputs first, such as by calling `x.toarray().)r0   r   r  Ztocoorowcoldatar)  rS  ZconcatenateZexpand_dimsr   ZSparseTensorr   r6   rK   Ztoarray)r   Zexpected_inputZ
sparse_coor  r  r  r)  indicesrB   rB   rC   rl  Q  s    

rl  c             C   sT   g }t | } x@| D ]8}t|tr@||j |t|j q||j qW |S )zReturns list of metrics from the given layers.

  This will not include the `compile` metrics of a model layer.

  Args:
    layers: List of layers.

  Returns:
    List of metrics.
  )	r&   Zfilter_empty_layer_containersrT   r1   r   r   r   r%  r   )r%  r   layerrB   rB   rC   r   u  s    


r   c             C   s   t | }|d k	r|S | S )N)r   constant_value)r   r  rB   rB   rC   r     s    
r   )Ur  r   r   numpyrS  Ztensorflow.pythonr   Ztensorflow.python.data.opsr   r   Ztensorflow.python.distributer   r   r   Ztensorflow.python.eagerr   r	   Ztensorflow.python.frameworkr
   r   r   r   r   r   r   Ztensorflow.python.kerasr   r   r   r7  r   r   Z"tensorflow.python.keras.distributer   r   Ztensorflow.python.keras.enginer   r   Ztraining_libr   r   r   r   r   r   Z'tensorflow.python.keras.mixed_precisionr    r!   Z$tensorflow.python.keras.optimizer_v2r"   Ztensorflow.python.keras.savingr#   Z*tensorflow.python.keras.saving.saved_modelr$   Ztensorflow.python.keras.utilsr%   r&   r'   r(   r)   Z'tensorflow.python.keras.utils.mode_keysr*   Ztensorflow.python.opsr+   r,   Ztensorflow.python.platformr-   ri   Ztensorflow.python.trackabler.   rn   Ztensorflow.python.utilr/   Zscipy.sparser0   ImportErrorr1   r  objectr   r  rZ  rl  r   r   rB   rB   rB   rC   <module>   s   
                     f( i!$