
    6biE                     6   S r SSKrSSKJs  Jr  SSKJr  SSK	J
r
  SSKJr  SSKJr  SSKJr  SSKJr  SS	KJr  \R,                  r\R.                  r\R0                  r\R2                  rS
 rS rS rS rS r\" SS5       " S S\
R>                  5      5       r g)z)Keras discretization preprocessing layer.    N)backend)base_preprocessing_layer)preprocessing_utils)layer_utils)tf_utils)
tf_logging)keras_exportc                    [         R                  " U S/5      n [         R                  " U 5      n [         R                  " [         R                  " U 5      [         R
                  5      nSU-  n[         R                  " X#-  [         R                  5      nUn[         R                  " US5      nXSU2   n[         R                  " U5      nU[         R                  " U[         R
                  5      -  n[         R                  " Xx/5      $ )a!  Reduce a 1D sequence of values to a summary.

This algorithm is based on numpy.quantiles but modified to allow for
intermediate steps between multiple data sets. It first finds the target
number of bins as the reciprocal of epsilon and then takes the individual
values spaced at appropriate intervals to arrive at that target.
The final step is to return the corresponding counts between those values
If the target num_bins is larger than the size of values, the whole array is
returned (with weights of 1).

Args:
    values: 1D `np.ndarray` to be summarized.
    epsilon: A `'float32'` that determines the approximate desired
      precision.

Returns:
    A 2D `np.ndarray` that is a summary of the inputs. First column is the
    interpolated partition values, the second is the weights (counts).
      ?   N)
tfreshapesortcastsizefloat32int32maximum	ones_likestack)	valuesepsilonelementsnum_buckets	incrementstartstep
boundariesweightss	            j/home/james-whalen/.local/lib/python3.13/site-packages/tf_keras/src/layers/preprocessing/discretization.py	summarizer"   %   s    * ZZ%FWWV_Fwwrwwv

3H-K.9IE::i#Dt$Jll:&Gbjj11G88Z)**    c                 Z   ^ [         R                  " U4S jU /[         R                  5      $ )a  Compress a summary to within `epsilon` accuracy.

The compression step is needed to keep the summary sizes small after
merging, and also used to return the final target boundaries. It finds the
new bins based on interpolating cumulative weight percentages from the large
summary.  Taking the difference of the cumulative weights from the previous
bin's cumulative weight will give the new weight for that bin.

Args:
    summary: 2D `np.ndarray` summary to be compressed.
    epsilon: A `'float32'` that determines the approxmiate desired
      precision.

Returns:
    A 2D `np.ndarray` that is a compressed summary. First column is the
    interpolated partition values, the second is the weights (counts).
c                    > [        U T5      $ N)_compress_summary_numpy)sr   s    r!   <lambda>compress.<locals>.<lambda>[   s    )!W5r#   )r   numpy_functionr   )summaryr   s    `r!   compressr-   G   s%    & 5y"** r#   c                    U R                   S   U-  S:  a  U $ U[        R                  " SSU5      -   nU S   R                  5       nX3S   -  n[        R                  " X$U S   5      n[        R                  " X$U5      nU[        R
                  " [        R                  " S/5      USS 45      -
  n[        R                  " XV45      n U R                  [        R                  5      $ )zCompress a summary with numpy.r   g        r   r   r   N)
shapenparangecumsuminterpconcatenatearrayr   astyper   )r,   r   percentscum_weightscum_weight_percentsnew_binsnew_weightss          r!   r'   r'   _   s    }}Q'!A%3W55H!*##%K%B7yy
CH))H;GK	1#CR()! K hh./G>>"**%%r#   c                     [         R                  " X4SS9n[         R                  " U[         R                  " US   5      SS9n[	        X25      $ )a  Weighted merge sort of summaries.

Given two summaries of distinct data, this function merges (and compresses)
them to stay within `epsilon` error tolerance.

Args:
    prev_summary: 2D `np.ndarray` summary to be merged with `next_summary`.
    next_summary: 2D `np.ndarray` summary to be merged with `prev_summary`.
    epsilon: A float that determines the approxmiate desired precision.

Returns:
    A 2-D `np.ndarray` that is a merged summary. First column is the
    interpolated partition values, the second is the weights (counts).
r   )axisr   )r   concatgatherargsortr-   )prev_summarynext_summaryr   mergeds       r!   merge_summariesrD   p   sA     YY3!<FYYvrzz&)41=FF$$r#   c                 .    [        U SU-  5      SS S24   $ )Nr   r   r   )r-   )r,   num_binss     r!   get_bin_boundariesrG      s     GS8^,QV44r#   zkeras.layers.Discretizationz6keras.layers.experimental.preprocessing.Discretizationc                      ^  \ rS rSrSr     SU 4S jjrU 4S jrSU 4S jjrS rS r	S r
U 4S	 jrS
 rS rS rSrU =r$ )Discretization   a  A preprocessing layer which buckets continuous features by ranges.

This layer will place each element of its input data into one of several
contiguous ranges and output an integer index indicating which range each
element was placed in.

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

Input shape:
  Any `tf.Tensor` or `tf.RaggedTensor` of dimension 2 or higher.

Output shape:
  Same as input shape.

Arguments:
  bin_boundaries: A list of bin boundaries. The leftmost and rightmost bins
    will always extend to `-inf` and `inf`, so `bin_boundaries=[0., 1., 2.]`
    generates bins `(-inf, 0.)`, `[0., 1.)`, `[1., 2.)`, and `[2., +inf)`.
    If this option is set, `adapt()` should not be called.
  num_bins: The integer number of bins to compute. If this option is set,
    `adapt()` should be called to learn the bin boundaries.
  epsilon: Error tolerance, typically a small fraction close to zero (e.g.
    0.01). Higher values of epsilon increase the quantile approximation, and
    hence result in more unequal buckets, but could improve performance
    and resource consumption.
  output_mode: Specification for the output of the layer. Values can be
   `"int"`, `"one_hot"`, `"multi_hot"`, or
    `"count"` configuring the layer as follows:
      - `"int"`: Return the discretized bin indices directly.
      - `"one_hot"`: Encodes each individual element in the input into an
        array the same size as `num_bins`, containing a 1 at the input's bin
        index. If the last dimension is size 1, will encode on that
        dimension.  If the last dimension is not size 1, will append a new
        dimension for the encoded output.
      - `"multi_hot"`: Encodes each sample in the input into a single array
        the same size as `num_bins`, containing a 1 for each bin index
        index present in the sample. Treats the last dimension as the sample
        dimension, if input shape is `(..., sample_length)`, output shape
        will be `(..., num_tokens)`.
      - `"count"`: As `"multi_hot"`, but the int array contains a count of
        the number of times the bin index appeared in the sample.
    Defaults to `"int"`.
  sparse: Boolean. Only applicable to `"one_hot"`, `"multi_hot"`,
    and `"count"` output modes. If True, returns a `SparseTensor` instead of
    a dense `Tensor`. Defaults to `False`.

Examples:

Bucketize float values based on provided buckets.
>>> input = np.array([[-1.5, 1.0, 3.4, .5], [0.0, 3.0, 1.3, 0.0]])
>>> layer = tf.keras.layers.Discretization(bin_boundaries=[0., 1., 2.])
>>> layer(input)
<tf.Tensor: shape=(2, 4), dtype=int64, numpy=
array([[0, 2, 3, 1],
       [1, 3, 2, 1]])>

Bucketize float values based on a number of buckets to compute.
>>> input = np.array([[-1.5, 1.0, 3.4, .5], [0.0, 3.0, 1.3, 0.0]])
>>> layer = tf.keras.layers.Discretization(num_bins=4, epsilon=0.01)
>>> layer.adapt(input)
>>> layer(input)
<tf.Tensor: shape=(2, 4), dtype=int64, numpy=
array([[0, 2, 3, 2],
       [1, 3, 3, 1]])>
c                   > SU;   aB  [         R                  " S5        [        US   [        5      (       a	  Uc  US   nOUc  US   nUS	 SU;  d  US   c3  U[        :X  a  [
        R                  O[        R                  " 5       US'   OAUS:X  a;  [
        R                  " US   5      R                  (       d  [
        R                  US'   [        TU ]0  " S0 UD6  U[        :X  aB  [
        R                  " U R                  5      R                  (       d  US   n[        SU 35      e[        R                   " U[        ["        [$        [&        4U R(                  R*                  SS9  U(       a  U[        :X  a  [        SU S	U 35      eUb   US
:  a  [        SR-                  U5      5      eUb  Ub  [        SR-                  X!5      5      e[.        R0                  " U5      nXl        Ub  UO/ U l        X l        X0l        X@l        XPl        g )NbinszBbins is deprecated, please use bin_boundaries or num_bins instead.dtypeintzMWhen `output_mode='int'`, `dtype` should be an integer type. Received: dtype=output_mode)allowable_strings
layer_namearg_namezi`sparse` may only be true if `output_mode` is `'one_hot'`, `'multi_hot'`, or `'count'`. Received: sparse=z and output_mode=r   zG`num_bins` must be greater than or equal to 0. You passed `num_bins={}`zhBoth `num_bins` and `bin_boundaries` should not be set. You passed `num_bins={}` and `bin_boundaries={}` )loggingwarning
isinstancerN   INTr   int64r   floatxas_dtype
is_integersuper__init__compute_dtype
ValueErrorr   validate_string_argONE_HOT	MULTI_HOTCOUNT	__class____name__formatutilslistify_tensorsinput_bin_boundariesbin_boundariesrF   r   rO   sparse)	selfrj   rF   r   rO   rk   kwargsinput_dtyperd   s	           r!   r]   Discretization.__init__   s    VOOA &.#..83C!&>'!'v & F7O$;'3.GNN4D 7O 5 VG_)E)P)P !hhF7O"6" 3KK 2 23>> /K))47  	''"GY>~~.."		
 kS($$*8 ,*m-  HqL++16(+;  N$>&&,fX&F 
 ..~>$2!,8Nb 	 !&r#   c                    > [         TU ]  U5        U R                  b  g U R                  SS[        R
                  S SS9U l        g )Nr,   )   Nc                 
    / / /$ r&   rS   r/   rM   s     r!   r)   &Discretization.build.<locals>.<lambda>0  s    .r#   F)namer/   rM   initializer	trainable)r\   buildri   
add_weightr   r   r,   )rl   input_shaperd   s     r!   rx   Discretization.build$  sL    k"$$0 **  ' 	
r#   c                 "   > [         TU ]  XUS9  g)aq  Computes bin boundaries from quantiles in a input dataset.

Calling `adapt()` on a `Discretization` layer is an alternative to
passing in a `bin_boundaries` argument during construction. A
`Discretization` layer should always be either adapted over a dataset or
passed `bin_boundaries`.

During `adapt()`, the layer will estimate the quantile boundaries of the
input dataset. The number of quantiles can be controlled via the
`num_bins` argument, and the error tolerance for quantile boundaries can
be controlled via the `epsilon` argument.

In order to make `Discretization` efficient in any distribution context,
the computed boundaries 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)rl   datar}   r~   rd   s       r!   r   Discretization.adapt8  s    \ 	d?r#   c                    U R                   b$  [        SR                  U R                   5      5      eU R                  (       d  [	        S5      e[
        R                  " U5      nUR                  [
        R                  :w  a%  [
        R                  " U[
        R                  5      n[        XR                  5      nU R                  R                  [        X R                  U R                  5      5        g )NzCannot adapt a Discretization layer that has been initialized with `bin_boundaries`, use `num_bins` instead. You passed `bin_boundaries={}`.z-`build` must be called before `update_state`.)ri   r_   rf   builtRuntimeErrorr   convert_to_tensorrM   r   r   r"   r   r,   assignrD   )rl   r   r,   s      r!   update_stateDiscretization.update_stateh  s    $$0''-vd.G.G'H  zzNOO##D)::#774,DD,,/G\\4<<@	
r#   c                     U R                   c  U R                  (       d  g [        R                  " [	        U R
                  U R                  5      5      U l        g r&   )ri   r   rg   rh   rG   r,   rF   rj   rl   s    r!   finalize_stateDiscretization.finalize_state{  s>    $$0

 $33t||T]];
r#   c                 |    U R                   c  U R                  (       d  g U R                  R                  / / /5        g r&   )ri   r   r,   r   r   s    r!   reset_stateDiscretization.reset_state  s-    $$0

RH%r#   c                    > [         TU ]  5       nUR                  U R                  U R                  U R
                  U R                  U R                  S.5        U$ )N)rj   rF   r   rO   rk   )r\   
get_configupdateri   rF   r   rO   rk   )rl   configrd   s     r!   r   Discretization.get_config  sO    #%"&";"; MM<<#//++	
 r#   c                     U$ r&   rS   )rl   rz   s     r!   compute_output_shape#Discretization.compute_output_shape  s    r#   c                 
   U R                  UR                  R                  5       5      n[        U[        R
                  5      (       a  [        R
                  " X R                  S9$ [        R                  " X R                  S9$ )Nrs   )r   r/   as_listrV   r   SparseTensorSpecr^   
TensorSpec)rl   
input_specoutput_shapes      r!   compute_output_signature'Discretization.compute_output_signature  sg    001A1A1I1I1KLj""5"566&&"*<*<  }}<7I7IJJr#   c                 *  ^  U 4S jn[         R                  " U5      (       a   [        R                  R	                  X!5      nO[         R
                  " U5      (       ac  [        R                  " [        R                  " UR                  5      U" UR                  5      [        R                  " UR                  5      S9nOU" U5      n[        R                  " UT R                  [        T R                  5      S-   T R                   T R"                  S9$ )Nc                 T   > [         R                  R                  U TR                  S9$ )N)inputr   )r   raw_ops	Bucketizerj   )inputsrl   s    r!   	bucketize&Discretization.call.<locals>.bucketize  s*    ::'')<)< (  r#   )indicesr   dense_shaper   )rO   depthrk   rM   )r   	is_raggedr   raggedmap_flat_values	is_sparseSparseTensoridentityr   r   r   rg   encode_categorical_inputsrO   lenrj   rk   r^   )rl   r   r   r   s   `   r!   callDiscretization.call  s    	
 f%%ii//	BG''ooFNN3 /KK(:(:;G  'G..((d))*Q.;;$$
 	
r#   )rj   r   ri   rF   rO   rk   r,   )NNg{Gz?rN   F)NN)re   
__module____qualname____firstlineno____doc__r]   rx   r   r   r   r   r   r   r   r   __static_attributes____classcell__)rd   s   @r!   rI   rI      sW    
AJ Rh
(.@`
&
&K
 
r#   rI   )!r   numpyr0   tensorflow.compat.v2compatv2r   tf_keras.srcr   tf_keras.src.enginer   !tf_keras.src.layers.preprocessingr   rg   tf_keras.src.utilsr   r   tensorflow.python.platformr   rT    tensorflow.python.util.tf_exportr	   rW   rb   ra   rc   r"   r-   r'   rD   rG   PreprocessingLayerrI   rS   r#   r!   <module>r      s    0  ! !   8 J * ' = 9iiOO	
--+D0&"%(5 !<m
-@@ m
	m
r#   