
    ijNN                         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 Z ed	       G d
 de
             Zy)    N)backend)ops)keras_export)	DataLayer)	PyDataset)
tensorflowc                 0    t        | t              r| d   S | S )z@Return input from batch; handle (x, y) or (x, y, sample_weight).r   )
isinstancetuple)batchs    /var/www/html/emotional.easysim.app/public_html/venv/lib/python3.12/site-packages/keras/src/layers/preprocessing/normalization.py_extract_batchr      s    %QxL    zkeras.layers.Normalizationc                   d     e Zd ZdZ	 d fd	Zd Zd Zd Zd Zd Z	 fdZ
 fd	Zd
 Zd Z xZS )Normalizationa  A preprocessing layer that 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()`.

    **Note:** This layer is safe to use inside a `tf.data` or `grain` pipeline
    (independently of which backend you're using).

    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.
            When `-1`, 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`. Defaults to `-1`.
        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.
            `mean` and `variance` must be specified together.
        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.
            `mean` and `variance` must be specified together.
        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 = keras.layers.Normalization(axis=None)
    >>> layer.adapt(adapt_data)
    >>> layer(input_data)
    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 = keras.layers.Normalization(axis=-1)
    >>> layer.adapt(adapt_data)
    >>> layer(input_data)
    array([-1., -1., -1.], dtype=float32)

    Pass the mean and variance directly.

    >>> input_data = np.array([[1.], [2.], [3.]], dtype='float32')
    >>> layer = keras.layers.Normalization(mean=3., variance=2.)
    >>> layer(input_data)
    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 = keras.layers.Normalization(axis=-1, invert=True)
    >>> layer.adapt(adapt_data)
    >>> layer(input_data)
    array([2., 10., 8.], dtype=float32)
    c                    t        |   di | |d}nt        |t              r|f}nt	        |      }|| _        || _        || _        || _        d| _	        d | _
        d | _        |d u|d uk7  rt        d| d|       |t        j                  |      t        j                  |      k7  r7t        dt        j                  |       dt        j                  |             t        t        j                  |            t        | j
                        kD  rDt        dt        | j
                         dt        j                  |       d	| j
                         y y )
N TzUWhen setting values directly, both `mean` and `variance` must be set. Received: mean=z and variance=zcWhen setting values directly, `mean` and `variance` must have the same shape. Received: mean shape z and variance shape zEThe rank of `mean` must be less than or equal to the number of axes (z). Received: mean shape z
 for axis )super__init__r
   intr   axis
input_meaninput_varianceinvertsupports_masking_build_input_shapemean
ValueErrornpshapelen)selfr   r   variancer   kwargs	__class__s         r   r   zNormalization.__init__n   sj    	"6"<Dc"7D;D	& $"&	 ($"67//3fN8*N  xx~(!33 ""$((4.!1 2&&(hhx&8%9;  288D>"S^3 ''*499~&6 7""$((4.!1DII;H  4 r   c           	      :    y t               _        t        fd j                  D              rt	        d d j                         t        t         j                  D cg c]  }|dk\  r|n|z    c}             _         j                  D ]%  }|   	t	        d j                   d d|        t         fdt              D               _	        t              D cg c]  }| j                  v rdnd	 c} _
        t              D cg c]  }| j                  v r|   nd	 c} _        t        fd
 j                  D              }| _         j                  g j                  d|dd       _         j                  d|dd       _         j                  ddddd       _        d _         j'                          y t)        j*                   j                        }t)        j*                   j,                        }t)        j.                  |      dk(  rAt)        j0                  | j                        }t)        j0                  | j                        }nd	gz  }t)        j2                  |      }t)        j.                  |      }t        d	|d	z         D ]  }	 j                  |	    }
||	    ||
<    t)        j4                  ||      }t)        j4                  ||      }t)        j0                  | j                        }t)        j0                  | j                        }t)        j6                  | j8                         _        t)        j6                  | j8                         _        d _        y c c}w c c}w c c}w )Nc              3   8   K   | ]  }| k  xs |k\    y wNr   ).0andims     r   	<genexpr>z&Normalization.build.<locals>.<genexpr>   s#     9!qD5y%AI%9s   zPAll `axis` values must be in the range [-ndim, ndim). Received inputs with ndim=z, while axis=r   zDAll `axis` values to be kept must have a known shape. Received axis=z, inputs.shape=z, with unknown axis at index c              3   @   K   | ]  }|j                   vs|  y wr(   )
_keep_axis)r)   dr"   s     r   r,   z&Normalization.build.<locals>.<genexpr>   s!      "
at&>A"
s      c              3   (   K   | ]	  }|     y wr(   r   )r)   r/   input_shapes     r   r,   z&Normalization.build.<locals>.<genexpr>   s     "Ka;q>"Ks   r   zerosF)namer    initializer	trainabler#   onescountr   r   )r4   r    dtyper5   r6   Tr9   )r!   r   anyr   r   r   sortedr.   range_reduce_axis_reduce_axis_mask_broadcast_shape_mean_and_var_shaper   
add_weight
adapt_meanadapt_variancer8   builtfinalize_stater   convert_to_tensorr   r+   broadcast_tor    reshapecastcompute_dtyper   r#   )r"   r2   r/   mean_and_var_shaper   r#   expanded_shape
mean_shape	mean_ndimiaxis_idxr+   s   ``         @r   buildzNormalization.build   st   ;"-9tyy99--1F-		{L   tyyA!aAQX-AB
  	A1~% %%)YYK 0$$/= 12236 	 " "
T{"
 

 7<Dk"
12doo%A1,"

 DI;!
>?a4??2KN9!
 #"K4??"KK#5 ??""oo(#	 . DO #'//("	 #2 #D # ) DJ DJ! ((9D,,T-@-@AHxx~"''d.C.CD++Hd6K6KL #$t YYt_
HHTN	 q)a-0 >A#r2H/91"~N8,> {{48;;x@ ''d.C.CD++Hd6K6KLT-?-?@DIHHXT5G5GHDMDJa B "
!
s   *N0NNc           
      N	   d}t        |t        j                        st        j                  |      r|j
                  }n)t        |t        j                  j                        r3d } ||      }t        |      dk(  r|j                  d      } ||      }nt        |t              rt        |d         j
                  }nt        |d      rd}t        |      }t        |d      }|t!        d	      t        |      }t#        |d
d      }|"t%        dt'        |      j(                   d      t+        |      }t-        j.                  |g|      }nt%        dt'        |       d      | j0                  s| j3                  |       nA| j4                  D ]2  }||   | j6                  |   k7  st!        d| j6                   d|        t        |t        j                        rDt        j8                  || j:                        }t        j<                  || j:                        }	n9t        j                  |      rDt?        j8                  || j:                        }t?        j<                  || j:                        }	nt        |t        j                  j                  t        f      s|rt?        j@                  | jB                        }t?        j@                  | jB                        }	d}
|D ]U  t              t        jD                  | jF                        | j4                  D ]Z  }j
                  |   }| j6                  |   }|$|'||k7  s-t!        d| j6                   dt+        j
                         d       t?        j8                  | j:                        }t?        j<                  | j:                        }| j:                  r+fd| j:                  D        }tI        jJ                  |      }nd}|
|z  }
tM        |      |
z  }d|z
  }||z  ||z  z   }|	||z
  dz  z   |z  |||z
  dz  z   |z  z   }	|}X ntO        dt'        |             | jP                  jS                  |       | jT                  jS                  |	       | jW                          y)ax  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` to the layer.

        Arg:
            data: The data to train on. It can be passed as a NumPy array, a
                backend-native eager tensor, a `tf.data.Dataset`, a
                `keras.utils.PyDataset`, or an iterable of batches (e.g. a
                list of arrays or a generator yielding batches). If a dataset
                or iterable, *it must be batched*. Keras will assume that each
                element is a batch, and if that assumption doesn't hold, the
                mean and variance may be incorrectly computed.
        Fc                 r    | j                   }t        |t              r|d   n|}t        |j                        S )Nr   )element_specr
   r   r    )r/   rU   x_specs      r   get_input_shapez,Normalization.adapt.<locals>.get_input_shape  s9     ~~ ",6 !O% 
 V\\**r   r0      r   __iter__TNzadapt() received an empty iterable (no batches). Expected at least one batch. Pass a non-empty iterable of arrays or tensors, e.g. layer.adapt([x]) or layer.adapt(list_of_batches).r    zadapt() expects an iterable that yields arrays or tensors with a `.shape` attribute (e.g. numpy arrays or backend tensors). Got an element of type zF. Ensure each yielded element is array-like with a `.shape` attribute.zUnsupported data type: z. `adapt` supports `np.ndarray`, backend tensors, `tf.data.Dataset`, `keras.utils.PyDataset`, and iterables of batches (e.g. list, generator).z%The layer was built with input_shape=zO, but adapt() is being called with data with an incompatible shape, data.shape=)r   r:   z:adapt() yielded a batch with incompatible shape. Expected z, got .c              3   <   K   | ]  }j                   |     y wr(   )r    )r)   r/   r   s     r   r,   z&Normalization.adapt.<locals>.<genexpr>r  s      *+,A*s   g      ?   ),r
   r   ndarrayr   	is_tensorr    tfdataDatasetr!   r   r   r   hasattriternextr   getattr	TypeErrortype__name__r   	itertoolschainrE   rR   r.   r   r   r>   varr   r3   rA   rG   rK   mathprodfloatNotImplementedErrorrC   assignrD   rF   )r"   r`   data_is_iterabler2   rW   	data_iterfirst_batchr/   
total_mean	total_vartotal_count	batch_dimexpected
batch_mean	batch_varbatch_reduce_shapebatch_countbatch_weightexisting_weightnew_total_meanr   s                       @r   adaptzNormalization.adapt   sp   , !dBJJ'7+<+<T+B**Kbggoo.+ *$/K;1$zz#-d3i((a177KT:&# T
Iy$/K" 4  )5K!+w=K"@ K(112 3GG   ,K??K=)<D)$t* 6$ %  zzJJ{#__ q>T%<%<Q%??$''+'>'>&? @==HMK  dBJJ'D,=,=>Jt$*;*;<It$$T->->?J4+<+<=Irww	:;?O4#;#;<J		$":":;IK +,&u-11!3!3  A %AI#66q9H!-$0%1(/#667v$U[[12!5  !XXe$2C2CD
GGE0A0AB	$$*040A0A*& #')),>"?K"#K{*$[1K?"%"40:3LL  n!< BB#$ n!< BB '!!	
 ,
W+,Z &(?T
|&LMMz*""9-r   c                    | j                   | j                  sy t        j                  | j                  | j
                        | _        t        j                  | j                  | j                        | _        t        j                  | j                  | j
                        | _
        t        j                  | j                  | j                        | _
        y r(   )r   rE   r   rI   rC   r@   r   rJ   rK   rD   r#   r"   s    r   rF   zNormalization.finalize_state  s    ??&djj KK1F1FG	HHTYY(:(:;	D$7$79N9NO0B0BCr   c                    | j                   t        d      | j                  j                  j	                  || j
                        }| j                  | j                         }| j                  | j                        }| j                  r| j                  j                  j                  || j                  j                  j                  || j                  j                  j                  | j                  j                  j                  |      t        j                                           S | j                  j                  j                  | j                  j                  j!                  ||      | j                  j                  j                  | j                  j                  j                  |      t        j                                     S )NzAYou must call `.build(input_shape)` on the layer before using it.r:   )r   r   r   corerG   rK   convert_weightr#   r   numpyaddmultiplymaximumsqrtepsilondividesubtract)r"   inputsr   r#   s       r   callzNormalization.call  sc    990  ""44$,, 5 

 ""499-&&t}}5;;<<%%))""++LL&&..**//97??;L  <<%%,,""++FD9""**LL&&++H5w7H r   c                     |S r(   r   )r"   r2   s     r   compute_output_shapez"Normalization.compute_output_shape  s    r   c                 $   t         |          }|j                  | j                  | j                  t        j                  | j                        j                         t        j                  | j                        j                         d       |S )N)r   r   r   r#   )
r   
get_configupdater   r   r   arrayr   tolistr   )r"   configr%   s     r   r   zNormalization.get_config  sj    #%		++188:HHT%8%89@@B		
 r   c                 D    t         |   |       | j                          y r(   )r   load_own_variablesrF   )r"   storer%   s     r   r   z Normalization.load_own_variables  s    "5)r   c                 8    | j                   rd| j                   iS y Nr2   )r   r   s    r   get_build_configzNormalization.get_build_config  s!    ""!4#:#:;; #r   c                 2    |r| j                  |d          y y r   )rR   )r"   r   s     r   build_from_configzNormalization.build_from_config  s    JJvm,- r   )NNF)rh   
__module____qualname____doc__r   rR   r   rF   r   r   r   r   r   r   __classcell__)r%   s   @r   r   r      sH    Up 9>)V`DRh	D!F

<.r   r   )ri   rl   r   r   	keras.srcr   r   keras.src.api_exportr   )keras.src.layers.preprocessing.data_layerr   3keras.src.trainers.data_adapters.py_dataset_adapterr   keras.src.utils.module_utilsr   r_   r   r   r   r   r   <module>r      sI         - ? I 9 *+A.I A. ,A.r   