§
    ¨éUgB  ã                   ó°   — d dl Z d dlmZ d dlZddlmZmZmZ ddl	m
Z
 ddlmZmZmZ ddlmZ ddlmZ dd	lmZmZmZmZ d
dlmZ  G d„ dee¦  «        ZdS )é    N)ÚIntegralé   )ÚBaseEstimatorÚTransformerMixinÚ_fit_context)Úresample)ÚIntervalÚOptionsÚ
StrOptions)Ú"_deprecate_Xt_in_inverse_transform©Ú_weighted_percentile)Ú_check_feature_names_inÚ_check_sample_weightÚcheck_arrayÚcheck_is_fittedé   )ÚOneHotEncoderc            
       ó4  — e Zd ZU dZ eeddd¬¦  «        dg eh d£¦  «        g eh d£¦  «        g eee	j
        e	j        h¦  «        dg eed	dd¬¦  «        dgd
gdœZeed<   	 dddddddœd„Z ed¬¦  «        dd„¦   «         Zd„ Zd„ Zdddœd„Zdd„ZdS )ÚKBinsDiscretizera  
    Bin continuous data into intervals.

    Read more in the :ref:`User Guide <preprocessing_discretization>`.

    .. versionadded:: 0.20

    Parameters
    ----------
    n_bins : int or array-like of shape (n_features,), default=5
        The number of bins to produce. Raises ValueError if ``n_bins < 2``.

    encode : {'onehot', 'onehot-dense', 'ordinal'}, default='onehot'
        Method used to encode the transformed result.

        - 'onehot': Encode the transformed result with one-hot encoding
          and return a sparse matrix. Ignored features are always
          stacked to the right.
        - 'onehot-dense': Encode the transformed result with one-hot encoding
          and return a dense array. Ignored features are always
          stacked to the right.
        - 'ordinal': Return the bin identifier encoded as an integer value.

    strategy : {'uniform', 'quantile', 'kmeans'}, default='quantile'
        Strategy used to define the widths of the bins.

        - 'uniform': All bins in each feature have identical widths.
        - 'quantile': All bins in each feature have the same number of points.
        - 'kmeans': Values in each bin have the same nearest center of a 1D
          k-means cluster.

        For an example of the different strategies see:
        :ref:`sphx_glr_auto_examples_preprocessing_plot_discretization_strategies.py`.

    dtype : {np.float32, np.float64}, default=None
        The desired data-type for the output. If None, output dtype is
        consistent with input dtype. Only np.float32 and np.float64 are
        supported.

        .. versionadded:: 0.24

    subsample : int or None, default=200_000
        Maximum number of samples, used to fit the model, for computational
        efficiency.
        `subsample=None` means that all the training samples are used when
        computing the quantiles that determine the binning thresholds.
        Since quantile computation relies on sorting each column of `X` and
        that sorting has an `n log(n)` time complexity,
        it is recommended to use subsampling on datasets with a
        very large number of samples.

        .. versionchanged:: 1.3
            The default value of `subsample` changed from `None` to `200_000` when
            `strategy="quantile"`.

        .. versionchanged:: 1.5
            The default value of `subsample` changed from `None` to `200_000` when
            `strategy="uniform"` or `strategy="kmeans"`.

    random_state : int, RandomState instance or None, default=None
        Determines random number generation for subsampling.
        Pass an int for reproducible results across multiple function calls.
        See the `subsample` parameter for more details.
        See :term:`Glossary <random_state>`.

        .. versionadded:: 1.1

    Attributes
    ----------
    bin_edges_ : ndarray of ndarray of shape (n_features,)
        The edges of each bin. Contain arrays of varying shapes ``(n_bins_, )``
        Ignored features will have empty arrays.

    n_bins_ : ndarray of shape (n_features,), dtype=np.int64
        Number of bins per feature. Bins whose width are too small
        (i.e., <= 1e-8) are removed with a warning.

    n_features_in_ : int
        Number of features seen during :term:`fit`.

        .. versionadded:: 0.24

    feature_names_in_ : ndarray of shape (`n_features_in_`,)
        Names of features seen during :term:`fit`. Defined only when `X`
        has feature names that are all strings.

        .. versionadded:: 1.0

    See Also
    --------
    Binarizer : Class used to bin values as ``0`` or
        ``1`` based on a parameter ``threshold``.

    Notes
    -----

    For a visualization of discretization on different datasets refer to
    :ref:`sphx_glr_auto_examples_preprocessing_plot_discretization_classification.py`.
    On the effect of discretization on linear models see:
    :ref:`sphx_glr_auto_examples_preprocessing_plot_discretization.py`.

    In bin edges for feature ``i``, the first and last values are used only for
    ``inverse_transform``. During transform, bin edges are extended to::

      np.concatenate([-np.inf, bin_edges_[i][1:-1], np.inf])

    You can combine ``KBinsDiscretizer`` with
    :class:`~sklearn.compose.ColumnTransformer` if you only want to preprocess
    part of the features.

    ``KBinsDiscretizer`` might produce constant features (e.g., when
    ``encode = 'onehot'`` and certain bins do not contain any data).
    These features can be removed with feature selection algorithms
    (e.g., :class:`~sklearn.feature_selection.VarianceThreshold`).

    Examples
    --------
    >>> from sklearn.preprocessing import KBinsDiscretizer
    >>> X = [[-2, 1, -4,   -1],
    ...      [-1, 2, -3, -0.5],
    ...      [ 0, 3, -2,  0.5],
    ...      [ 1, 4, -1,    2]]
    >>> est = KBinsDiscretizer(
    ...     n_bins=3, encode='ordinal', strategy='uniform'
    ... )
    >>> est.fit(X)
    KBinsDiscretizer(...)
    >>> Xt = est.transform(X)
    >>> Xt  # doctest: +SKIP
    array([[ 0., 0., 0., 0.],
           [ 1., 1., 1., 0.],
           [ 2., 2., 2., 1.],
           [ 2., 2., 2., 2.]])

    Sometimes it may be useful to convert the data back into the original
    feature space. The ``inverse_transform`` function converts the binned
    data into the original feature space. Each value will be equal to the mean
    of the two bin edges.

    >>> est.bin_edges_[0]
    array([-2., -1.,  0.,  1.])
    >>> est.inverse_transform(Xt)
    array([[-1.5,  1.5, -3.5, -0.5],
           [-0.5,  2.5, -2.5, -0.5],
           [ 0.5,  3.5, -1.5,  0.5],
           [ 0.5,  3.5, -1.5,  1.5]])
    r   NÚleft)Úclosedz
array-like>   úonehot-denseÚonehotÚordinal>   ÚkmeansÚuniformÚquantiler   Úrandom_state©Ún_binsÚencodeÚstrategyÚdtypeÚ	subsampler   Ú_parameter_constraintsé   r   r   i@ )r"   r#   r$   r%   r   c                óZ   — || _         || _        || _        || _        || _        || _        d S ©Nr    )Úselfr!   r"   r#   r$   r%   r   s          úd/var/www/surfInsights/venv3-11/lib/python3.11/site-packages/sklearn/preprocessing/_discretization.pyÚ__init__zKBinsDiscretizer.__init__¸   s5   € ð ˆŒØˆŒØ ˆŒØˆŒ
Ø"ˆŒØ(ˆÔÐÐó    T)Úprefer_skip_nested_validationc                 ó   ‡‡— |                       |d¬¦  «        }| j        t          j        t          j        fv r| j        }n|j        }|j        \  }}‰�#| j        dk    rt          d| j        ›d�¦  «        ‚| j        �(|| j        k    rt          |d| j        | j
        ¬¦  «        }|j        d	         }|                      |¦  «        }‰�t          ‰||j        ¬¦  «        Št          j        |t          ¬¦  «        }t          |¦  «        D �]»}	|dd…|	f         Š‰                     ¦   «         ‰                     ¦   «         }}
|
|k    rKt%          j        d
|	z  ¦  «         d	||	<   t          j        t          j         t          j        g¦  «        ||	<   Œˆ| j        dk    r$t          j        |
|||	         d	z   ¦  «        ||	<   �nl| j        dk    r~t          j        dd||	         d	z   ¦  «        }‰€,t          j        t          j        ‰|¦  «        ¦  «        ||	<   �nt          j        ˆˆfd„|D ¦   «         t          j        ¬¦  «        ||	<   nã| j        dk    rØddlm} t          j        |
|||	         d	z   ¦  «        }|d	d…         |dd…         z   dd…df         dz  } |||	         |d	¬¦  «        }|                     ‰dd…df         ‰¬¦  «        j        dd…df         }|                     ¦   «          |d	d…         |dd…         z   dz  ||	<   t          j        |
||	         |f         ||	<   | j        dv r�t          j        ||	         t          j        ¬¦  «        dk    }||	         |         ||	<   tA          ||	         ¦  «        d	z
  ||	         k    r2t%          j        d|	z  ¦  «         tA          ||	         ¦  «        d	z
  ||	<   �Œ½|| _!        || _"        d| j#        v rotI          d„ | j"        D ¦   «         | j#        dk    |¬¦  «        | _%        | j%                             t          j        d	tA          | j"        ¦  «        f¦  «        ¦  «         | S )as  
        Fit the estimator.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
            Data to be discretized.

        y : None
            Ignored. This parameter exists only for compatibility with
            :class:`~sklearn.pipeline.Pipeline`.

        sample_weight : ndarray of shape (n_samples,)
            Contains weight values to be associated with each sample.
            Cannot be used when `strategy` is set to `"uniform"`.

            .. versionadded:: 1.3

        Returns
        -------
        self : object
            Returns the instance itself.
        Únumeric©r$   Nr   zY`sample_weight` was provided but it cannot be used with strategy='uniform'. Got strategy=z	 instead.F)ÚreplaceÚ	n_samplesr   r   z3Feature %d is constant and will be replaced with 0.r   r   éd   c                 ó2   •— g | ]}t          ‰‰|¦  «        ‘ŒS © r   )Ú.0ÚqÚcolumnÚsample_weights     €€r+   ú
<listcomp>z(KBinsDiscretizer.fit.<locals>.<listcomp>  s5   ø€ ð ð ð à !õ 1°¸ÈÑJÔJðð ð r-   r   r   )ÚKMeanséÿÿÿÿç      à?)Ú
n_clustersÚinitÚn_init)r:   )r   r   )Úto_beging:Œ0âŽyE>zqBins whose width are too small (i.e., <= 1e-8) in feature %d are removed. Consider decreasing the number of bins.r   c                 ó6   — g | ]}t          j        |¦  «        ‘ŒS r6   )ÚnpÚarange©r7   Úis     r+   r;   z(KBinsDiscretizer.fit.<locals>.<listcomp>?  s    € Ð?Ð?Ð?¨Q�BœI a™LœLÐ?Ð?Ð?r-   )Ú
categoriesÚsparse_outputr$   )&Ú_validate_datar$   rD   Úfloat64Úfloat32Úshaper#   Ú
ValueErrorr%   r   r   Ú_validate_n_binsr   ÚzerosÚobjectÚrangeÚminÚmaxÚwarningsÚwarnÚarrayÚinfÚlinspaceÚasarrayÚ
percentileÚclusterr<   ÚfitÚcluster_centers_ÚsortÚr_Úediff1dÚlenÚ
bin_edges_Ún_bins_r"   r   Ú_encoder)r*   ÚXÚyr:   Úoutput_dtyper3   Ú
n_featuresr!   Ú	bin_edgesÚjjÚcol_minÚcol_maxÚ	quantilesr<   Úuniform_edgesr@   ÚkmÚcentersÚmaskr9   s      `               @r+   r]   zKBinsDiscretizer.fitÉ   s­  øø€ ð2 ×Ò ¨ÐÑ3Ô3ˆàŒ:�"œ*¥b¤jÐ1Ð1Ð1Øœ:ˆLˆLàœ7ˆLà !¤Ñˆ	�:àÐ$¨¬¸)Ò)CÐ)CÝð.à”=ð.ð .ð .ñô ð ð Œ>Ð%¨)°d´nÒ*DÐ*DåØØØœ.Ø!Ô.ð	ñ ô ˆAð ”W˜Q”Zˆ
Ø×&Ò& zÑ2Ô2ˆàÐ$Ý0°ÀÈÌÐQÑQÔQˆMå”H˜Z­vÐ6Ñ6Ô6ˆ	Ý˜
Ñ#Ô#ð 6	8ñ 6	8ˆBØ�q�q�q˜"�u”XˆFØ%Ÿzšz™|œ|¨V¯ZªZ©\¬\�WˆGà˜'Ò!Ð!Ý”ØIÈBÑNñô ð ð ��r‘
Ý "¤­2¬6¨'µ2´6Ð):Ñ ;Ô ;�	˜"‘ØàŒ} 	Ò)Ð)Ý "¤¨G°W¸fÀR¼jÈ1¹nÑ MÔ M�	˜"‘‘à” *Ò,Ð,ÝœK¨¨3°°r´
¸Q±Ñ?Ô?�	Ø Ð(Ý$&¤J­r¬}¸VÀYÑ/OÔ/OÑ$PÔ$P�I˜b‘M‘Må$&¤Jðð ð ð ð à%.ðñ ô õ !œjð%ñ %ô %�I˜b‘M�Mð ” (Ò*Ð*Ø,Ð,Ð,Ð,Ð,Ð,õ !#¤¨G°W¸fÀR¼jÈ1¹nÑ MÔ M�Ø% a b bÔ)¨M¸#¸2¸#Ô,>Ñ>ÀÀÀÀ4ÀÔHÈ3ÑN�ð �V v¨b¤z¸ÀQÐGÑGÔG�ØŸ&š&Ø˜1˜1˜1˜d˜7”O°=ð !ñ ô ä" 1 1 1 a 4ô)�ð —’‘”�Ø!(¨¨¨¤¨w°s¸°s¬|Ñ!;¸sÑ B�	˜"‘Ý "¤ g¨y¸¬}¸gÐ&EÔ F�	˜"‘ð Œ}Ð 6Ð6Ð6Ý”z )¨B¤-½"¼&ÐAÑAÔAÀDÒH�Ø )¨"¤¨dÔ 3�	˜"‘Ý�y ”}Ñ%Ô%¨Ñ)¨V°B¬ZÒ7Ð7Ý”Mð9à;=ñ>ñô ð õ
 "% Y¨r¤]Ñ!3Ô!3°aÑ!7�F˜2‘Jùà#ˆŒØˆŒà�t”{Ð"Ð"Ý)Ø?Ð?°$´,Ð?Ñ?Ô?Ø"œk¨XÒ5Ø"ðñ ô ˆDŒMð ŒM×Ò�bœh¨­3¨t¬|Ñ+<Ô+<Ð'=Ñ>Ô>Ñ?Ô?Ð?àˆr-   c                 ó  — | j         }t          |t          ¦  «        rt          j        ||t
          ¬¦  «        S t          |t
          dd¬¦  «        }|j        dk    s|j        d         |k    rt          d¦  «        ‚|dk     ||k    z  }t          j
        |¦  «        d         }|j        d         dk    rLd	                     d
„ |D ¦   «         ¦  «        }t          d                     t          j        |¦  «        ¦  «        ‚|S )z0Returns n_bins_, the number of bins per feature.r1   TF)r$   ÚcopyÚ	ensure_2dr   r   z8n_bins must be a scalar or array of shape (n_features,).r   z, c              3   ó4   K  — | ]}t          |¦  «        V — Œd S r)   )ÚstrrF   s     r+   ú	<genexpr>z4KBinsDiscretizer._validate_n_bins.<locals>.<genexpr>X  s(   è è € ÐBÐB¨1¥ A¡¤ÐBÐBÐBÐBÐBÐBr-   zk{} received an invalid number of bins at indices {}. Number of bins must be at least 2, and must be an int.)r!   Ú
isinstancer   rD   ÚfullÚintr   ÚndimrM   rN   ÚwhereÚjoinÚformatr   Ú__name__)r*   ri   Ú	orig_binsr!   Úbad_nbins_valueÚviolating_indicesÚindicess          r+   rO   z!KBinsDiscretizer._validate_n_binsI  s  € à”Kˆ	Ý�i¥Ñ*Ô*ð 	=Ý”7˜: y½Ð<Ñ<Ô<Ð<å˜Y­c¸ÈÐNÑNÔNˆàŒ;˜Š?ˆ?˜fœl¨1œo°Ò;Ð;ÝÐWÑXÔXÐXà! Aš:¨&°IÒ*=Ñ>ˆåœH _Ñ5Ô5°aÔ8ÐØÔ" 1Ô%¨Ò)Ð)Ø—i’iÐBÐBÐ0AÐBÑBÔBÑBÔBˆGÝð:ç:@º&Ý$Ô-¨wñ;ô ;ñô ð ð ˆr-   c                 ó2  — t          | ¦  «         | j        €t          j        t          j        fn| j        }|                      |d|d¬¦  «        }| j        }t          |j        d         ¦  «        D ]8}t          j	        ||         dd…         |dd…|f         d¬¦  «        |dd…|f<   Œ9| j
        d	k    r|S d}d
| j
        v r| j        j        }|j        | j        _        	 | j                             |¦  «        }|| j        _        n# || j        _        w xY w|S )a‹  
        Discretize the data.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
            Data to be discretized.

        Returns
        -------
        Xt : {ndarray, sparse matrix}, dtype={np.float32, np.float64}
            Data in the binned space. Will be a sparse matrix if
            `self.encode='onehot'` and ndarray otherwise.
        NTF)rt   r$   Úresetr   r=   Úright)Úsider   r   )r   r$   rD   rK   rL   rJ   rc   rR   rM   Úsearchsortedr"   re   Ú	transform)r*   rf   r$   ÚXtrj   rk   Ú
dtype_initÚXt_encs           r+   rŠ   zKBinsDiscretizer.transformb  s-  € õ 	˜ÑÔÐð -1¬JÐ,>•”�RœZÐ(Ð(ÀDÄJˆØ× Ò  ¨°UÀ%Ð ÑHÔHˆà”Oˆ	Ý˜œ œÑ$Ô$ð 	Vð 	VˆBÝœ¨	°"¬°a¸°dÔ(;¸RÀÀÀÀ2À¼YÈWÐUÑUÔUˆBˆqˆqˆq�"ˆu‰IˆIàŒ;˜)Ò#Ð#ØˆIàˆ
Ø�t”{Ð"Ð"ØœÔ,ˆJØ"$¤(ˆDŒMÔð	-Ø”]×,Ò,¨RÑ0Ô0ˆFð #-ˆDŒMÔÐø *ˆDŒMÔÐ,Ð,Ð,Ð,Øˆs   ÃD ÄD)r‹   c                óV  — t          ||¦  «        }t          | ¦  «         d| j        v r| j                             |¦  «        }t          |dt          j        t          j        f¬¦  «        }| j	        j
        d         }|j
        d         |k    r.t          d                     ||j
        d         ¦  «        ¦  «        ‚t          |¦  «        D ]]}| j        |         }|dd…         |dd…         z   d	z  }||dd…|f                              t          j        ¦  «                 |dd…|f<   Œ^|S )
a¹  
        Transform discretized data back to original feature space.

        Note that this function does not regenerate the original data
        due to discretization rounding.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
            Transformed data in the binned space.

        Xt : array-like of shape (n_samples, n_features)
            Transformed data in the binned space.

            .. deprecated:: 1.5
                `Xt` was deprecated in 1.5 and will be removed in 1.7. Use `X` instead.

        Returns
        -------
        Xinv : ndarray, dtype={np.float32, np.float64}
            Data in the original feature space.
        r   T)rt   r$   r   r   z8Incorrect number of features. Expecting {}, received {}.Nr=   r>   )r   r   r"   re   Úinverse_transformr   rD   rK   rL   rd   rM   rN   r   rR   rc   ÚastypeÚint64)r*   rf   r‹   ÚXinvri   rk   rj   Úbin_centerss           r+   r�   z"KBinsDiscretizer.inverse_transform‰  s/  € õ. /¨q°"Ñ5Ô5ˆå˜ÑÔÐà�t”{Ð"Ð"Ø”×/Ò/°Ñ2Ô2ˆAå˜1 4µ´
½B¼JÐ/GÐHÑHÔHˆØ”\Ô'¨Ô*ˆ
ØŒ:�aŒ=˜JÒ&Ð&ÝØJ×QÒQØ ¤
¨1¤ñô ñô ð õ ˜
Ñ#Ô#ð 	Fð 	FˆBØœ¨Ô+ˆIØ$ Q R Rœ=¨9°S°b°S¬>Ñ9¸SÑ@ˆKØ% t¨A¨A¨A¨r¨E¤{×&:Ò&:½2¼8Ñ&DÔ&DÔEˆD����B�‰KˆKàˆr-   c                 óš   — t          | d¦  «         t          | |¦  «        }t          | d¦  «        r| j                             |¦  «        S |S )aÔ  Get output feature names.

        Parameters
        ----------
        input_features : array-like of str or None, default=None
            Input features.

            - If `input_features` is `None`, then `feature_names_in_` is
              used as feature names in. If `feature_names_in_` is not defined,
              then the following input feature names are generated:
              `["x0", "x1", ..., "x(n_features_in_ - 1)"]`.
            - If `input_features` is an array-like, then `input_features` must
              match `feature_names_in_` if `feature_names_in_` is defined.

        Returns
        -------
        feature_names_out : ndarray of str objects
            Transformed feature names.
        Ún_features_in_re   )r   r   Úhasattrre   Úget_feature_names_out)r*   Úinput_featuress     r+   r—   z&KBinsDiscretizer.get_feature_names_out·  sU   € õ( 	˜Ð.Ñ/Ô/Ð/Ý0°°~ÑFÔFˆÝ�4˜Ñ$Ô$ð 	GØ”=×6Ò6°~ÑFÔFÐFð Ðr-   )r'   )NNr)   )r€   Ú
__module__Ú__qualname__Ú__doc__r	   r   r   r
   ÚtyperD   rK   rL   r&   ÚdictÚ__annotations__r,   r   r]   rO   rŠ   r�   r—   r6   r-   r+   r   r      s…  € € € € € € ðRð Rðj �8˜H a¨°fÐ=Ñ=Ô=¸|ÐLØ�:ÐCÐCÐCÑDÔDÐEØ�ZÐ AÐ AÐ AÑBÔBÐCØ�'˜$ ¤¨R¬ZÐ 8Ñ9Ô9¸4Ð@Ø�h˜x¨¨D¸Ð@Ñ@Ô@À$ÐGØ'Ð(ð$ð $Ð˜Dð ð ñ ð ð)ð ØØØØð)ð )ð )ð )ð )ð" €\°Ð5Ñ5Ô5ð}ð }ð }ñ 6Ô5ð}ð~ð ð ð2%ð %ð %ðN,¨dð ,ð ,ð ,ð ,ð ,ð\ð ð ð ð ð r-   r   )rU   Únumbersr   ÚnumpyrD   Úbaser   r   r   Úutilsr   Úutils._param_validationr	   r
   r   Úutils.deprecationr   Úutils.statsr   Úutils.validationr   r   r   r   Ú	_encodersr   r   r6   r-   r+   ú<module>r¨      s1  ðð €€€Ø Ð Ð Ð Ð Ð à Ð Ð Ð à @Ð @Ð @Ð @Ð @Ð @Ð @Ð @Ð @Ð @Ø Ð Ð Ð Ð Ð Ø CÐ CÐ CÐ CÐ CÐ CÐ CÐ CÐ CÐ CØ BÐ BÐ BÐ BÐ BÐ BØ .Ð .Ð .Ð .Ð .Ð .ðð ð ð ð ð ð ð ð ð ð ð ð %Ð $Ð $Ð $Ð $Ð $ðwð wð wð wð wÐ'¨ñ wô wð wð wð wr-   