a
    Sic@                     @   sn   d Z ddlZddlm  mZ ddlmZ ddl	m
Z
 ddlmZ ddlmZ eddG d	d
 d
e
jZdS )z"Normalization preprocessing layer.    N)backend)base_preprocessing_layer)preprocessing_utils)keras_exportzkeras.layers.Normalizationz5keras.layers.experimental.preprocessing.Normalizationc                       s   e Zd ZdZd fdd	Z fddZd fd	d
	Zdd Zdd Zdd Z	dd Z
dd Zdd Z fddZdd Z  ZS )NormalizationaM  A preprocessing layer which normalizes continuous features.

    This layer will shift and scale inputs into a distribution centered around
    0 with standard deviation 1. It accomplishes this by precomputing the mean
    and variance of the data, and calling `(input - mean) / sqrt(var)` at
    runtime.

    The mean and variance values for the layer must be either supplied on
    construction or learned via `adapt()`. `adapt()` will compute the mean and
    variance of the data and store them as the layer's weights. `adapt()` should
    be called before `fit()`, `evaluate()`, or `predict()`.

    For an overview and full list of preprocessing layers, see the preprocessing
    [guide](https://www.tensorflow.org/guide/keras/preprocessing_layers).

    Args:
        axis: Integer, tuple of integers, or None. The axis or axes that should
          have a separate mean and variance for each index in the shape. For
          example, if shape is `(None, 5)` and `axis=1`, the layer will track 5
          separate mean and variance values for the last axis. If `axis` is set
          to `None`, the layer will normalize all elements in the input by a
          scalar mean and variance. Defaults to -1, where the last axis of the
          input is assumed to be a feature dimension and is normalized per
          index. Note that in the specific case of batched scalar inputs where
          the only axis is the batch axis, the default will normalize each index
          in the batch separately. In this case, consider passing `axis=None`.
        mean: The mean value(s) to use during normalization. The passed value(s)
          will be broadcast to the shape of the kept axes above; if the value(s)
          cannot be broadcast, an error will be raised when this layer's
          `build()` method is called.
        variance: The variance value(s) to use during normalization. The passed
          value(s) will be broadcast to the shape of the kept axes above; if the
          value(s) cannot be broadcast, an error will be raised when this
          layer's `build()` method is called.
        invert: If True, this layer will apply the inverse transformation
          to its inputs: it would turn a normalized input back into its
          original form.

    Examples:

    Calculate a global mean and variance by analyzing the dataset in `adapt()`.

    >>> adapt_data = np.array([1., 2., 3., 4., 5.], dtype='float32')
    >>> input_data = np.array([1., 2., 3.], dtype='float32')
    >>> layer = tf.keras.layers.Normalization(axis=None)
    >>> layer.adapt(adapt_data)
    >>> layer(input_data)
    <tf.Tensor: shape=(3,), dtype=float32, numpy=
    array([-1.4142135, -0.70710677, 0.], dtype=float32)>

    Calculate a mean and variance for each index on the last axis.

    >>> adapt_data = np.array([[0., 7., 4.],
    ...                        [2., 9., 6.],
    ...                        [0., 7., 4.],
    ...                        [2., 9., 6.]], dtype='float32')
    >>> input_data = np.array([[0., 7., 4.]], dtype='float32')
    >>> layer = tf.keras.layers.Normalization(axis=-1)
    >>> layer.adapt(adapt_data)
    >>> layer(input_data)
    <tf.Tensor: shape=(1, 3), dtype=float32, numpy=
    array([-1., -1., -1.], dtype=float32)>

    Pass the mean and variance directly.

    >>> input_data = np.array([[1.], [2.], [3.]], dtype='float32')
    >>> layer = tf.keras.layers.Normalization(mean=3., variance=2.)
    >>> layer(input_data)
    <tf.Tensor: shape=(3, 1), dtype=float32, numpy=
    array([[-1.4142135 ],
           [-0.70710677],
           [ 0.        ]], dtype=float32)>

    Use the layer to de-normalize inputs (after adapting the layer).

    >>> adapt_data = np.array([[0., 7., 4.],
    ...                        [2., 9., 6.],
    ...                        [0., 7., 4.],
    ...                        [2., 9., 6.]], dtype='float32')
    >>> input_data = np.array([[1., 2., 3.]], dtype='float32')
    >>> layer = tf.keras.layers.Normalization(axis=-1, invert=True)
    >>> layer.adapt(adapt_data)
    >>> layer(input_data)
    <tf.Tensor: shape=(1, 3), dtype=float32, numpy=
    array([2., 10., 8.], dtype=float32)>
    NFc                    s   t  jf i | tjdd |d u r2d}nt|trD|f}nt|}|| _	t|t
jrftdt|t
jrztd|d u|d ukrtd|||| _|| _|| _d S )Nr   T zJNormalization does not support passing a Variable for the `mean` init arg.zNNormalization does not support passing a Variable for the `variance` init arg.zcWhen setting values directly, both `mean` and `variance` must be set. Got mean: {} and variance: {})super__init__r   keras_kpl_gaugeget_cellset
isinstanceinttupleaxistfVariable
ValueErrorformat
input_meaninput_varianceinvert)selfr   meanvariancer   kwargs	__class__r   d/var/www/html/django/DPS/env/lib/python3.9/site-packages/keras/layers/preprocessing/normalization.pyr
   y   s6    
zNormalization.__init__c                    s  t    t ttfr4tdd  D r4tdt 	  t
 tfddjD rttdjtfddjD _jD ]$} | d u rtdj |qfd	dtD _fd
dtD _ fddtD _t fddjD }jd u rzjd|jddd_jd|jddd_jddtjddd_  n\jt| }jt| }t|j}t|j}t |j_!t |j_"d S )Nc                 s   s   | ]}t |tjV  qd S N)r   r   TensorShape).0shaper   r   r   	<genexpr>   s   z&Normalization.build.<locals>.<genexpr>zNormalization only accepts a single input. If you are passing a python list or tuple as a single input, please convert to a numpy array or `tf.Tensor`.c                 3   s    | ]}|  k p| kV  qd S r    r   )r"   andimr   r   r$          zPAll `axis` values must be in the range [-ndim, ndim). Found ndim: `{}`, axis: {}c                    s    g | ]}|d kr|n|  qS )r   r   r"   dr&   r   r   
<listcomp>   r(   z'Normalization.build.<locals>.<listcomp>zqAll `axis` values to be kept must have known shape. Got axis: {}, input shape: {}, with unknown axis at index: {}c                    s   g | ]}| j vr|qS r   
_keep_axisr)   r   r   r   r+      r(   c                    s   g | ]}| j v rd ndqS )r      r,   r)   r.   r   r   r+      s   c                    s"   g | ]}|j v r | nd qS )r/   r,   r)   )input_shaper   r   r   r+      s   c                 3   s   | ]} | V  qd S r    r   r)   )r0   r   r   r$      r(   r   zerosF)namer#   dtypeinitializer	trainabler   onescountr   )#r	   buildr   listr   allr   r   r!   as_listlenanyr   r   sortedr-   range_reduce_axisZ_reduce_axis_mask_broadcast_shaper   
add_weightcompute_dtype
adapt_meanadapt_varianceint64r7   finalize_statenpr6   r   reshapecastr   r   )r   r0   r*   Zmean_and_var_shaper   r   r   )r0   r'   r   r   r8      sx    


zNormalization.buildc                    s   t  j|||d dS )a	  Computes the mean and variance of values in a dataset.

        Calling `adapt()` on a `Normalization` layer is an alternative to
        passing in `mean` and `variance` arguments during layer construction. A
        `Normalization` layer should always either be adapted over a dataset or
        passed `mean` and `variance`.

        During `adapt()`, the layer will compute a `mean` and `variance`
        separately for each position in each axis specified by the `axis`
        argument. To calculate a single `mean` and `variance` over the input
        data, simply pass `axis=None`.

        In order to make `Normalization` efficient in any distribution context,
        the computed mean and variance are kept static with respect to any
        compiled `tf.Graph`s that call the layer. As a consequence, if the layer
        is adapted a second time, any models using the layer should be
        re-compiled. For more information see
        `tf.keras.layers.experimental.preprocessing.PreprocessingLayer.adapt`.

        `adapt()` is meant only as a single machine utility to compute layer
        state.  To analyze a dataset that cannot fit on a single machine, see
        [Tensorflow Transform](
        https://www.tensorflow.org/tfx/transform/get_started)
        for a multi-machine, map-reduce solution.

        Arguments:
          data: The data to train on. It can be passed either as a
              `tf.data.Dataset`, or as a numpy array.
          batch_size: Integer or `None`.
              Number of samples per state update.
              If unspecified, `batch_size` will default to 32.
              Do not specify the `batch_size` if your data is in the
              form of datasets, generators, or `keras.utils.Sequence` instances
              (since they generate batches).
          steps: Integer or `None`.
              Total number of steps (batches of samples)
              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' is None, the epoch will run until
              the input dataset is exhausted. When passing an infinitely
              repeating dataset, you must specify the `steps` argument. This
              argument is not supported with array inputs.
        )
batch_sizestepsN)r	   adapt)r   datarK   rL   r   r   r   rM      s    .zNormalization.adaptc                 C   s*  | j d urtd| j | j| js,td| |}t|| j	j
}tjj|| jd\}}tj|| jj
d}| jrt|| j}t|}nd}|| j }tj|| jdtj|| jd }d| }	| j	|	 ||  }
| j| j	|
 d  |	 |||
 d  |  }| j	|
 | j| | j| d S )	NzCannot `adapt` a Normalization layer that is initialized with static `mean` and `variance`, you passed mean {} and variance {}.z-`build` must be called before `update_state`.)axes)out_typer/   )r3   g      ?   )r   r   r   r   builtRuntimeError_standardize_inputsr   rJ   rD   r3   nnmomentsr@   r#   r7   gatherreduce_prodrC   rE   assign)r   rN   
batch_meanbatch_variancebatch_shapeZbatch_reduce_shapebatch_counttotal_countZbatch_weightZexisting_weightZ
total_meanZtotal_variancer   r   r   update_state   sB    


zNormalization.update_statec                 C   sT   | j d us| jsd S | jt| j | jt| j | jt| j d S r    )	r   rR   rD   rY   r   
zeros_likerE   	ones_liker7   r.   r   r   r   reset_stateL  s
    zNormalization.reset_statec                 C   s`   | j d us| jsd S t| j| j| _t| j| j| _t| j	| j| _
t| j
| j| _
d S r    )r   rR   r   rI   rD   rA   r   rJ   rC   rE   r   r.   r   r   r   rG   T  s    zNormalization.finalize_statec                 C   sf   |  |}t|| j}| jr@|| j tt| jt	
  S || j tt| jt	
  S d S r    )rT   r   rJ   rC   r   r   maximumsqrtr   r   epsilonr   inputsr   r   r   call_  s    
zNormalization.callc                 C   s   |S r    r   )r   r0   r   r   r   compute_output_shapem  s    z"Normalization.compute_output_shapec                 C   s   |S r    r   )r   
input_specr   r   r   compute_output_signaturep  s    z&Normalization.compute_output_signaturec                    s2   t   }|| jt| jt| jd |S )N)r   r   r   )r	   
get_configupdater   utilslistify_tensorsr   r   )r   configr   r   r   rl   s  s    


zNormalization.get_configc                 C   s(   t |}|j| jkr$t || j}|S r    )r   convert_to_tensorr3   rC   rJ   rf   r   r   r   rT   ~  s    
z!Normalization._standardize_inputs)r   NNF)NN)__name__
__module____qualname____doc__r
   r8   rM   r_   rb   rG   rh   ri   rk   rl   rT   __classcell__r   r   r   r   r      s   X 'P0,r   )ru   numpyrH   tensorflow.compat.v2compatv2r   kerasr   keras.enginer   Zkeras.layers.preprocessingr   rn    tensorflow.python.util.tf_exportr   PreprocessingLayerr   r   r   r   r   <module>   s   