
    2Vh6                         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  ed       G d	 d
e             Zd Zd Zd Zd Zy)    N)backend)keras_export)TFDataLayer)argument_validation)numerical_utils)
tensorflowzkeras.layers.Discretizationc                        e Zd ZdZ	 	 	 	 	 	 	 d fd	Zed        ZddZd Zd Z	d Z
d Zd	 Zd
 Zd Zedd       Z xZS )Discretizationaj  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.

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

    Input shape:
        Any array 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, `bin_boundaries` should not be set and
            `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. Only supported with TensorFlow
            backend. If `True`, returns a `SparseTensor` instead of
            a dense `Tensor`. Defaults to `False`.

    Examples:

    Discretize 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 = Discretization(bin_boundaries=[0., 1., 2.])
    >>> layer(input)
    array([[0, 2, 3, 1],
           [1, 3, 2, 1]])

    Discretize 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 = Discretization(num_bins=4, epsilon=0.01)
    >>> layer.adapt(input)
    >>> layer(input)
    array([[0, 2, 3, 2],
           [1, 3, 3, 1]])
    c                 p   ||dk(  rdnt        j                         }t        |   ||       |r0t         j                  s t        dt        j                                 |r|dk(  rt        d| d|       t        j                  |d| j                  j                  d	       ||d
k  rt        d| d      ||t        d| d| d      ||t        d      || _
        || _        || _        || _        || _        | j                  rd | _        y t!        j"                  g g gd      | _        y )Nintint64)namedtypez*`sparse=True` cannot be used with backend zn`sparse=True` may only be used if `output_mode` is `'one_hot'`, `'multi_hot'`, or `'count'`. Received: sparse=z and output_mode=)r   one_hot	multi_hotcountoutput_mode)allowable_stringscaller_namearg_namer   zC`num_bins` must be greater than or equal to 0. Received: `num_bins=`zLBoth `num_bins` and `bin_boundaries` should not be set. Received: `num_bins=z` and `bin_boundaries=z6You need to set either `num_bins` or `bin_boundaries`.float32r   )r   floatxsuper__init__SUPPORTS_SPARSE_TENSORS
ValueErrorr   validate_string_arg	__class____name__bin_boundariesnum_binsepsilonr   sparsesummarynparray)	selfr"   r#   r$   r   r%   r   r   r    s	           ]/home/dcms/DCMS/lib/python3.12/site-packages/keras/src/layers/preprocessing/discretization.pyr   zDiscretization.__init__X   s    =*e3G9IEd%0'99<W__=N<OP  kU*$$*8 ,*m-  	// //"
	
 HqL''/j3  N$>''/j 1##1"2!5 
  6H  - &DL88RHI>DL    c                 *    t        j                         S N)r   r   r)   s    r*   input_dtypezDiscretization.input_dtype   s    ~~r+   c                 4   | j                   t        d      | j                          t        |t        j
                  j                        r,||j                  |      }|D ]  }| j                  |        n| j                  |       | j                          y)a  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.

        Arguments:
            data: The data to train on. It can be passed either as a
                batched `tf.data.Dataset`,
                or as a NumPy array.
            steps: Integer or `None`.
                Total number of steps (batches of samples) to process.
                If `data` is a `tf.data.Dataset`, and `steps` is `None`,
                `adapt()` 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 or list inputs.
        NzlCannot adapt a Discretization layer that has been initialized with `bin_boundaries`, use `num_bins` instead.)
r#   r   reset_state
isinstancetfdataDatasettakeupdate_statefinalize_state)r)   r4   stepsbatchs       r*   adaptzDiscretization.adapt   s    2 == A  	dBGGOO, yy' )!!%() d#r+   c                     t        j                  |      j                  d      }t        || j                        }t        || j                  | j                        | _        y )Nr   )r'   r(   astype	summarizer$   merge_summariesr&   )r)   r4   r&   s      r*   r7   zDiscretization.update_state   sB    xx~$$Y/D$,,/&wdllKr+   c                     | j                   y t        | j                  | j                         j                         | _        y r-   )r#   get_bin_boundariesr&   tolistr"   r.   s    r*   r8   zDiscretization.finalize_state   s3    == 0LL$--

&( 	r+   c                 Z    | j                   y t        j                  g g gd      | _        y )Nr   r   )r#   r'   r(   r&   r.   s    r*   r1   zDiscretization.reset_state   s%    == xxR	:r+   c                 X    t        j                  |j                  | j                        S )N)shaper   )r   KerasTensorrE   compute_dtype)r)   inputss     r*   compute_output_specz"Discretization.compute_output_spec   s    ""T=O=OPPr+   c                 4    t        |      dk(  r
|d   | _        y )N   0)lenr&   )r)   stores     r*   load_own_variablesz!Discretization.load_own_variables   s    u:? :DLr+   c                 B   | j                   t        d      | j                  j                  j	                  || j                         }t        j                  || j                  t        | j                         dz   | j                  | j                  | j                        S )NzYou need to either pass the `bin_boundaries` argument at construction time or call `adapt(dataset)` before you can start using the `Discretization` layer.rK   )r   depthr   r%   backend_module)r"   r   r   numpydigitizer   encode_categorical_inputsr   rM   rG   r%   )r)   rH   indicess      r*   callzDiscretization.call   s    &:  ,,$$--fd6I6IJ88((d))*Q.$$;;<<
 	
r+   c                     | j                   | j                  | j                  | j                  | j                  | j
                  | j                  dS )Nr"   r#   r$   r   r%   r   r   rY   r.   s    r*   
get_configzDiscretization.get_config   sA    "11||++kkIIZZ
 	
r+   c                     |j                  dd       D|j                  dd       2|j                         }|j                  d      } | di |}||_        |S  | di |S )Nr"   r#    )getcopypopr"   )clsconfigcustom_objectsr"   discretizations        r*   from_configzDiscretization.from_config   sh     JJ'.:

:t,8 [[]F#ZZ(89N ]6]N,:N)!!}V}r+   )NNg{Gz?r   FNNr-   )r!   
__module____qualname____doc__r   propertyr/   r;   r7   r8   r1   rI   rO   rW   rZ   classmethodrd   __classcell__)r    s   @r*   r
   r
      s{    IZ @?D    &PL
;
Q
$	
  r+   r
   c                 J   t        j                  | dg      } t        j                  |       } t        j                  |       }d|z  }||z  }|}t	        |d      }| t        |      dt        |         }t        j                  |      }||z  }t        j                  ||g      S )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).
          ?rK   N)r'   reshapesortsizemaxr   	ones_likestack)	valuesr$   elementsnum_buckets	incrementstartstep
boundariesweightss	            r*   r>   r>     s    ( ZZ%FWWV_FwwvH-K;&IEy!DE
/c$i/0Jll:&GnG88Z)**r+   c                     t        j                  | |fd      }t        j                  |t        j                  |d         d      }t	        ||      S )aC  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 approximate 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).
    rK   )axisr   )r'   concatenater6   argsortcompress_summary)prev_summarynext_summaryr$   mergeds       r*   r?   r?   0  sE     ^^\<8qAFWWVRZZq	2;FFG,,r+   c                 .    t        | d|z        dd df   S )Nrm   r   rl   )r   )r&   r#   s     r*   rA   rA   D  s     GS8^4QV<<r+   c                    | j                   d   |z  dk  r| S |t        j                  dd|      z   }| d   j                         }||d   z  }t        j                  ||| d         }t        j                  |||      }|t        j
                  t        j                  dg      |dd f      z
  }t        j                  ||f      } | j                  d      S )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 approximate 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).
    rK   g        rm   rl   r   Nr   )	rE   r'   arangecumsuminterpr~   r(   rs   r=   )r&   r$   percentscum_weightscum_weight_percentsnew_binsnew_weightss          r*   r   r   H  s    $ }}Q'!A%3W55H!*##%K%B7yy#6
CH))H&9;GK	1#CR()! K hh+./G>>)$$r+   )rS   r'   	keras.srcr   keras.src.api_exportr   ,keras.src.layers.preprocessing.tf_data_layerr   keras.src.utilsr   r   keras.src.utils.module_utilsr   r3   r
   r>   r?   rA   r   r\   r+   r*   <module>r      sT      - D / + 9 +,@[ @ -@F+B-(=%r+   