
    Mpjh                         S SK r S SKJr  S SKrS SKJrJr  S SKJ	r	  S SK
JrJr  S SKJrJr  S SKJrJrJrJrJr  S SKJrJr  S S	KJr  S S
KJrJrJrJr   " S S\\	5      r g)    N)Real)OneToOneFeatureMixin_fit_context)_BaseEncoder)_fit_encoding_fast_fit_encoding_fast_auto_smooth)Bunch	indexable)MetadataRouterMethodMapping_raise_for_params_routing_enabledprocess_routing)Interval
StrOptions)type_of_target)_check_feature_names_in_check_ycheck_consistent_lengthcheck_is_fittedc            
       (  ^  \ rS rSr% Sr\" S15      \/\" 1 Sk5      /\" S15      \" \SSSS9/S	/S
\" S15      /S\" S15      /S.r	\
\S'         SS jr\" SS9S 5       r\" SS9S 5       rS rS rS rS rS rSS jrS rU 4S jrSrU =r$ )TargetEncoder!   u!  Target Encoder for regression and classification targets.

Each category is encoded based on a shrunk estimate of the average target
values for observations belonging to the category. The encoding scheme mixes
the global target mean with the target mean conditioned on the value of the
category (see [MIC]_).

When the target type is "multiclass", encodings are based
on the conditional probability estimate for each class. The target is first
binarized using the "one-vs-all" scheme via
:class:`~sklearn.preprocessing.LabelBinarizer`, then the average target
value for each class and each category is used for encoding, resulting in
`n_features` * `n_classes` encoded output features.

:class:`TargetEncoder` considers missing values, such as `np.nan` or `None`,
as another category and encodes them like any other category. Categories
that are not seen during :meth:`fit` are encoded with the target mean, i.e.
`target_mean_`.

For a demo on the importance of the `TargetEncoder` internal :term:`cross fitting`,
see
:ref:`sphx_glr_auto_examples_preprocessing_plot_target_encoder_cross_val.py`.
For a comparison of different encoders, refer to
:ref:`sphx_glr_auto_examples_preprocessing_plot_target_encoder.py`. Read
more in the :ref:`User Guide <target_encoder>`.

.. note::
    `fit(X, y).transform(X)` does not equal `fit_transform(X, y)` because a
    :term:`cross fitting` scheme is used in `fit_transform` for encoding.
    See the :ref:`User Guide <target_encoder>` for details.

.. versionadded:: 1.3

Parameters
----------
categories : "auto" or list of shape (n_features,) of array-like, default="auto"
    Categories (unique values) per feature:

    - `"auto"` : Determine categories automatically from the training data.
    - list : `categories[i]` holds the categories expected in the i-th column. The
      passed categories should not mix strings and numeric values within a single
      feature, and should be sorted in case of numeric values.

    The used categories are stored in the `categories_` fitted attribute.

target_type : {"auto", "continuous", "binary", "multiclass"}, default="auto"
    Type of target.

    - `"auto"` : Type of target is inferred with
      :func:`~sklearn.utils.multiclass.type_of_target`.
    - `"continuous"` : Continuous target
    - `"binary"` : Binary target
    - `"multiclass"` : Multiclass target

    .. note::
        The type of target inferred with `"auto"` may not be the desired target
        type used for modeling. For example, if the target consisted of integers
        between 0 and 100, then :func:`~sklearn.utils.multiclass.type_of_target`
        will infer the target as `"multiclass"`. In this case, setting
        `target_type="continuous"` will specify the target as a regression
        problem. The `target_type_` attribute gives the target type used by the
        encoder.

    .. versionchanged:: 1.4
       Added the option 'multiclass'.

smooth : "auto" or float, default="auto"
    The amount of mixing of the target mean conditioned on the value of the
    category with the global target mean. A larger `smooth` value will put
    more weight on the global target mean.
    If `"auto"`, then `smooth` is set to an empirical Bayes estimate.

cv : int, cross-validation generator or an iterable, default=None
    Determines the splitting strategy used in the internal :term:`cross fitting`
    during :meth:`fit_transform`. Splitters where each sample index doesn't appear
    in the validation fold exactly once, raise a `ValueError`.
    Possible inputs for cv are:

    - `None`, to use a 5-fold cross-validation chosen internally based on
        `target_type`,
    - integer, to specify the number of folds for the cross-validation chosen
        internally based on `target_type`,
    - :term:`CV splitter` that does not repeat samples across validation folds,
    - an iterable yielding (train, test) splits as arrays of indices.

    For integer/None inputs, if `target_type` is `"continuous"`, :class:`KFold` is
    used, otherwise :class:`StratifiedKFold` is used.

    Refer :ref:`User Guide <cross_validation>` for more information on
    cross-validation strategies.

    .. versionchanged:: 1.9
        Cross-validation generators and iterables can also be passed as `cv`.

shuffle : bool, default=True
    Whether to shuffle the data in :meth:`fit_transform` before splitting into
    folds. Note that the samples within each split will not be shuffled. Only
    applies if `cv` is an int or `None`. If `cv` is a cross-validation generator or
    an iterable, `shuffle` is ignored.

    .. deprecated:: 1.9
        `shuffle` is deprecated and will be removed in 1.11. Pass a cross-validation
        generator as `cv` argument to specify the shuffling instead.

random_state : int, RandomState instance or None, default=None
    When `shuffle` is True, `random_state` affects the ordering of the
    indices, which controls the randomness of each fold. Otherwise, this
    parameter has no effect.
    Pass an int for reproducible output across multiple function calls.
    See :term:`Glossary <random_state>`.

    .. deprecated:: 1.9
        `random_state` is deprecated and will be removed in 1.11. Pass a
        cross-validation generator as `cv` argument to specify the random state of
        the shuffling instead.

Attributes
----------
encodings_ : list of shape (n_features,) or (n_features * n_classes) of                     ndarray
    Encodings learnt on all of `X`.
    For feature `i`, `encodings_[i]` are the encodings matching the
    categories listed in `categories_[i]`. When `target_type_` is
    "multiclass", the encoding for feature `i` and class `j` is stored in
    `encodings_[j + (i * len(classes_))]`. E.g., for 2 features (f) and
    3 classes (c), encodings are ordered:
    f0_c0, f0_c1, f0_c2, f1_c0, f1_c1, f1_c2,

categories_ : list of shape (n_features,) of ndarray
    The categories of each input feature determined during fitting or
    specified in `categories`
    (in order of the features in `X` and corresponding with the output
    of :meth:`transform`).

target_type_ : str
    Type of target.

target_mean_ : float
    The overall mean of the target. This value is only used in :meth:`transform`
    to encode categories.

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

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.

classes_ : ndarray or None
    If `target_type_` is 'binary' or 'multiclass', holds the label for each class,
    otherwise `None`.

See Also
--------
OrdinalEncoder : Performs an ordinal (integer) encoding of the categorical features.
    Contrary to TargetEncoder, this encoding is not supervised. Treating the
    resulting encoding as a numerical features therefore lead arbitrarily
    ordered values and therefore typically lead to lower predictive performance
    when used as preprocessing for a classifier or regressor.
OneHotEncoder : Performs a one-hot encoding of categorical features. This
    unsupervised encoding is better suited for low cardinality categorical
    variables as it generate one new feature per unique category.

References
----------
.. [MIC] :doi:`Micci-Barreca, Daniele. "A preprocessing scheme for high-cardinality
   categorical attributes in classification and prediction problems"
   SIGKDD Explor. Newsl. 3, 1 (July 2001), 27–32. <10.1145/507533.507538>`

Examples
--------
With `smooth="auto"`, the smoothing parameter is set to an empirical Bayes estimate:

>>> import numpy as np
>>> from sklearn.preprocessing import TargetEncoder
>>> X = np.array([["dog"] * 20 + ["cat"] * 30 + ["snake"] * 38], dtype=object).T
>>> y = [90.3] * 5 + [80.1] * 15 + [20.4] * 5 + [20.1] * 25 + [21.2] * 8 + [49] * 30
>>> enc_auto = TargetEncoder(smooth="auto")
>>> X_trans = enc_auto.fit_transform(X, y)

>>> # A high `smooth` parameter puts more weight on global mean on the categorical
>>> # encodings:
>>> enc_high_smooth = TargetEncoder(smooth=5000.0).fit(X, y)
>>> enc_high_smooth.target_mean_
np.float64(44.3)
>>> enc_high_smooth.encodings_
[array([44.1, 44.4, 44.3])]

>>> # On the other hand, a low `smooth` parameter puts more weight on target
>>> # conditioned on the value of the categorical:
>>> enc_low_smooth = TargetEncoder(smooth=1.0).fit(X, y)
>>> enc_low_smooth.encodings_
[array([21, 80.8, 43.2])]
auto>   r   binary
continuous
multiclassr   Nleft)closed	cv_objectboolean
deprecatedrandom_state)
categoriestarget_typesmoothcvshuffler#   _parameter_constraintsc                 L    Xl         X0l        X l        X@l        XPl        X`l        g N)r$   r&   r%   r'   r(   r#   )selfr$   r%   r&   r'   r(   r#   s          a/var/www/html/pdf-tiff/venv/lib/python3.13/site-packages/sklearn/preprocessing/_target_encoder.py__init__TargetEncoder.__init__   s$     %&(    T)prefer_skip_nested_validationc                 (    U R                  X5        U $ )a  Fit the :class:`TargetEncoder` to X and y.

It is discouraged to use this method because it can introduce data leakage.
Use `fit_transform` on training data instead.

.. note::
    `fit(X, y).transform(X)` does not equal `fit_transform(X, y)` because a
    :term:`cross fitting` scheme is used in `fit_transform` for encoding.
    See the :ref:`User Guide <target_encoder>` for details.

Parameters
----------
X : array-like of shape (n_samples, n_features)
    The data to determine the categories of each feature.

y : array-like of shape (n_samples,)
    The target data used to encode the categories.

Returns
-------
self : object
    Fitted encoder.
)_fit_encodings_all)r,   Xys      r-   fitTargetEncoder.fit   s    2 	%r0   c           	         SSK JnJnJnJn  SSKJn  [        X0S5        U R                  X5      u  ppU R                  S:w  d  U R                  S:w  a  [        R                  " S[        5        U R                  S:X  a  SOU R                  nSU0nU R                  S:w  a  U R                  US	'   U" U R                  U4S
U R                  S:g  0UD6n[!        5       (       a)  US   b  [#        XUS   5      u  pUS'   [%        U S40 UD6nO['        ['        0 S9S9n[)        XXWU45      (       d  [*        R,                  " UR.                  S   5      nUR0                  " X40 UR2                  R0                  D6 H  u  nnUU==   S-  ss'   M     [*        R4                  " US:H  5      (       d  [7        S5      eU R                  S:X  aV  [*        R8                  " U	R.                  S   U	R.                  S   [;        U R<                  5      -  4[*        R>                  S9nO#[*        R@                  " U	[*        R>                  S9nUR0                  " X40 UR2                  R0                  D6 Hy  u  nnU	USS24   UU   nn[*        RB                  " USS9nU R                  S:X  a  U RE                  UUUU5      nOU RG                  UUUU5      nU RI                  UU	U
) UUU5        M{     U$ )a  Fit :class:`TargetEncoder` and transform `X` with the target encoding.

This method uses a :term:`cross fitting` scheme to prevent target leakage
and overfitting in downstream predictors. It is the recommended method for
encoding training data.

.. note::
    `fit(X, y).transform(X)` does not equal `fit_transform(X, y)` because a
    :term:`cross fitting` scheme is used in `fit_transform` for encoding.
    See the :ref:`User Guide <target_encoder>` for details.

Parameters
----------
X : array-like of shape (n_samples, n_features)
    The data to determine the categories of each feature.

y : array-like of shape (n_samples,)
    The target data used to encode the categories.

**params : dict
    Parameters to route to the internal CV object.

    Can only be used in conjunction with a cross-validation generator as CV
    object.

    For instance, `groups` (array-like of shape `(n_samples,)`) can be routed to
    a CV splitter that accepts `groups`, such as :class:`GroupKFold` or
    :class:`StratifiedGroupKFold`.

    .. versionadded:: 1.9
        Only available if `enable_metadata_routing=True`, which can be
        set by using ``sklearn.set_config(enable_metadata_routing=True)``.
        See :ref:`Metadata Routing User Guide <metadata_routing>` for
        more details.

Returns
-------
X_trans : ndarray of shape (n_samples, n_features) or                     (n_samples, (n_features * n_classes))
    Transformed input.
r   )
GroupKFoldKFoldStratifiedGroupKFoldStratifiedKFold)check_cvfit_transformr"   z`TargetEncoder.shuffle` and `TargetEncoder.random_state` are deprecated in version 1.9 and will be removed in version 1.11. Pass a cross-validation generator as `cv` argument to specify the shuffling behaviour instead.Tr(   r#   
classifierr   groupsN)split)splitter   zValidation indices from `cv` must cover each sample index exactly once with no overlap. Pass a splitter with non-overlapping validation folds as `cv` or refer to the docs for other options.r   dtypeaxis)%sklearn.model_selectionr9   r:   r;   r<   sklearn.model_selection._splitr=   r   r3   r(   r#   warningswarnFutureWarningr'   target_type_r   r
   r   r	   
isinstancenpzerosshaperA   rB   all
ValueErroremptylenclasses_float64
empty_likemean_fit_encoding_multiclass"_fit_encoding_binary_or_continuous_transform_X_ordinal)r,   r4   r5   paramsr9   r:   r;   r<   r=   	X_ordinalX_known_mask	y_encodedn_categoriesr(   	cv_kwargsr'   routed_params
seen_count_test_idxX_out	train_idxX_trainy_trainy_train_mean	encodingss                             r-   r>   TargetEncoder.fit_transform  s   X	
 	
 	<&8;?;R;RST;X8	 <<<'4+<+<+LMM%  ,,,6$DLL(	,(,(9(9In% GG
 ((L8
 	
 h+)219I)J&fX&+D/LVLM!5r?;M
 U5IJ
 
 !''!*-J!xxM0F0F0L0LM88$)$  N66*/** W  ,HH#Y__Q%7#dmm:L%LMjjE
 MM)2::>E#%88A#QM4J4J4P4P#QIx(A6	)8LWG7773L  L0 99  		 !CC  		 %%% $R4 r0   c                    U R                  USSS9u  p#U R                  S:X  aV  [        R                  " UR                  S   UR                  S   [        U R                  5      -  4[        R                  S9nO#[        R                  " U[        R                  S9nU R                  UUU) [        S5      U R                  U R                  5        U$ )	a  Transform X with the target encoding.

This method internally uses the `encodings_` attribute learnt during
:meth:`TargetEncoder.fit_transform` to transform test data.

.. note::
    `fit(X, y).transform(X)` does not equal `fit_transform(X, y)` because a
    :term:`cross fitting` scheme is used in `fit_transform` for encoding.
    See the :ref:`User Guide <target_encoder>` for details.

Parameters
----------
X : array-like of shape (n_samples, n_features)
    The data to determine the categories of each feature.

Returns
-------
X_trans : ndarray of shape (n_samples, n_features) or                     (n_samples, (n_features * n_classes))
    Transformed input.
ignore	allow-nanhandle_unknownensure_all_finiter   r   rC   rD   N)
_transformrM   rO   rT   rQ   rU   rV   rW   rX   r\   slice
encodings_target_mean_)r,   r4   r^   r_   rg   s        r-   	transformTargetEncoder.transform  s    , #'//h+ #2 #
	
 ,HH#Y__Q%7#dmm:L%LMjjE
 MM)2::>E!!M$KOO	
 r0   c                    SSK JnJn  [        X5        U R	                  USSS9  U R
                  S:X  a+  Sn[        USS	9nXe;  a  [        S
U< SU S35      eX`l        OU R
                  U l        SU l	        U R                  S:X  a*  U" 5       nUR                  U5      nUR                  U l	        OEU R                  S:X  a*  U" 5       nUR                  U5      nUR                  U l	        O[        USU S9n[        R                  " USS9U l        U R                  USSS9u  p[        R                   " S U R"                   5       [        R$                  ['        U R"                  5      S9nU R                  S:X  a  U R)                  U	UUU R                  5      nOU R+                  U	UUU R                  5      nXl        XX+4$ )z(Fit a target encoding with all the data.r   )LabelBinarizerLabelEncoderro   rp   rq   r   )r   r   r   r5   )
input_namez3Unknown label type: Target type was inferred to be z. Only z are supported.Nr   r   T)	y_numeric	estimatorrF   c              3   8   #    U  H  n[        U5      v   M     g 7fr+   )rU   ).0category_for_features     r-   	<genexpr>3TargetEncoder._fit_encodings_all.<locals>.<genexpr>  s     TCS+?S%&&CSs   )rE   count)sklearn.preprocessingr{   r|   r   _fitr%   r   rS   rM   rV   r>   r   rO   rY   rw   rt   fromitercategories_int64rU   rZ   r[   rv   )r,   r4   r5   r{   r|   accepted_target_typesinferred_type_of_targetlabel_encoderlabel_binarizerr^   r_   ra   rl   s                r-   r3    TargetEncoder._fit_encodings_all  s    	G%		!H	Lv%$J!&4Q3&G#&C I.19N8O P!! 
 !8 $ 0 0D((NM++A.A)22DM,.,.O--a0A+44DMdd;AGGAA."&//h+ #2 #
	 {{T4CSCST((d&&'

 ,55!!	I ??!!	I $77r0   c                     U R                   S:X  a'  [        R                  " U5      n[        UUUUU5      nU$ [	        UUUU R                   U5      nU$ )zLearn target encodings.r   )r&   rO   varr   r   )r,   r^   r5   ra   target_mean
y_variancerl   s          r-   r[   0TargetEncoder._fit_encoding_binary_or_continuous  se     ;;& J6I  +I r0   c                 0  ^^ U R                   m[        U R                  5      m/ n[        T5       H3  nUSS2U4   nU R	                  UUUXF   5      nUR                  U5        M5     UU4S j[        T5       5       n	U	 V
s/ s H  oU
   PM	     sn
$ s  sn
f )a  Learn multiclass encodings.

Learn encodings for each class (c) then reorder encodings such that
the same features (f) are grouped together. `reorder_index` enables
converting from:
f0_c0, f1_c0, f0_c1, f1_c1, f0_c2, f1_c2
to:
f0_c0, f0_c1, f0_c2, f1_c0, f1_c1, f1_c2
Nc              3   X   >#    U  H  n[        UTT-  T5        H  nUv   M	     M!     g 7fr+   )range)r   startidx	n_classes
n_featuress      r-   r   9TargetEncoder._fit_encoding_multiclass.<locals>.<genexpr>A  s3      
*UY%;jI I *s   '*)n_features_in_rU   rV   r   r[   extend)r,   r^   r5   ra   r   rl   iy_classencodingreorder_indexr   r   r   s              @@r-   rZ   &TargetEncoder._fit_encoding_multiclass)  s     ((
&		y!A1gG>>	H X& "
z*

 +88-3#-888s   Bc                    U R                   S:X  aM  [        U R                  5      n[        U5       H(  u  pX-  n
X-  nXXJ4      XU4'   Xk   XSS2U
4   U4'   M*     g[        U5       H  u  pXXH4      XU4'   XaUSS2U4   U4'   M      g)a  Transform X_ordinal using encodings.

In the multiclass case, `X_ordinal` and `X_unknown_mask` have column
(axis=1) size `n_features`, while `encodings` has length of size
`n_features * n_classes`. `feat_idx` deals with this by repeating
feature indices by `n_classes` E.g., for 3 features, 2 classes:
0,0,1,1,2,2

Additionally, `target_mean` is of shape (`n_classes`,) so `mean_idx`
cycles through 0 to `n_classes` - 1, `n_features` times.
r   N)rM   rU   rV   	enumerate)r,   rg   r^   X_unknown_maskrow_indicesrl   r   r   e_idxr   feat_idxmean_idxs               r-   r\   "TargetEncoder._transform_X_ordinalH  s    ( ,DMM*I#,Y#7 - ,,4{?T5U,V5()<G<QQ[1589 $8 $-Y#7,4{?Q5R,S5()9DnQX.56 $8r0   c                     [        U S5        [        X5      nU R                  S:X  aF  U VVs/ s H  nU R                    H
  nU SU 3PM     M      nnn[        R
                  " U[        S9$ U$ s  snnf )a+  Get output feature names for transformation.

Parameters
----------
input_features : array-like of str or None, default=None
    Not used, present here for API consistency by convention.

Returns
-------
feature_names_out : ndarray of str objects
    Transformed feature names. `feature_names_in_` is used unless it is
    not defined, in which case the following input feature names are
    generated: `["x0", "x1", ..., "x(n_features_in_ - 1)"]`.
    When `type_of_target_` is "multiclass" the names are of the format
    '<feature_name>_<class_name>'.
r   r   re   rD   )r   r   rM   rV   rO   asarrayobject)r,   input_featuresfeature_namesfeature_name
class_names        r-   get_feature_names_out#TargetEncoder.get_feature_names_outj  s    " 	.//E, %2$1L"&--J  .*."/ /$1  
 ::m6::  s   %A0c                 x    [        U S9nUR                  U R                  [        5       R                  SSS9S9  U$ )a"  Get metadata routing of this object.

Please check :ref:`User Guide <metadata_routing>` on how the routing
mechanism works.

.. versionadded:: 1.9

Returns
-------
routing : MetadataRouter
    A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating
    routing information.
)ownerr>   rA   )callercallee)rB   method_mapping)r   addr'   r   )r,   routers     r-   get_metadata_routing"TargetEncoder.get_metadata_routing  sD      d+

 WW(?..og.V 	 	
 r0   c                 F   > [         TU ]  5       nSUR                  l        U$ )NT)super__sklearn_tags__target_tagsrequired)r,   tags	__class__s     r-   r   TargetEncoder.__sklearn_tags__  s#    w')$(!r0   )
r$   rV   r'   rv   r#   r(   r&   rw   r%   rM   )r   r   r      r"   r"   r+   )__name__
__module____qualname____firstlineno____doc__r   listr   r   r)   dict__annotations__r.   r   r6   r>   rx   r3   r[   rZ   r\   r   r   r   __static_attributes____classcell__)r   s   @r-   r   r   !   s    AH "6(+T2"#QRSvh'$4)OPmz<.9:'\N)CD$D  !)  5 66 5J 6JX+Z;8z.9> ED!:6 r0   r   )!rJ   numbersr   numpyrO   sklearn.baser   r   sklearn.preprocessing._encodersr   *sklearn.preprocessing._target_encoder_fastr   r   sklearn.utilsr	   r
    sklearn.utils._metadata_requestsr   r   r   r   r   sklearn.utils._param_validationr   r   sklearn.utils.multiclassr   sklearn.utils.validationr   r   r   r   r    r0   r-   <module>r      sN       ; 8 +  A 3 D
(, D
r0   