ó
    Ñ]j¿S  ã                   ó”   • S SK Jr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  S SKJrJrJrJr   " S	 S
\\	5      rg)é    )ÚIntegralÚRealN)ÚOneToOneFeatureMixinÚ_fit_context)Ú_BaseEncoder)Ú_fit_encoding_fastÚ_fit_encoding_fast_auto_smooth)Ú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S9/S
/S/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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 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, default=5
    Determines the number of folds in the :term:`cross fitting` strategy used in
    :meth:`fit_transform`. For classification targets, `StratifiedKFold` is used
    and for continuous targets, `KFold` is used.

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.

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>`.

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é   ÚbooleanÚrandom_state)Ú
categoriesÚtarget_typeÚsmoothÚcvÚshuffler   Ú_parameter_constraintsTc                 ó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          Úb/home/mande/repo/quber/.venv/lib/python3.13/site-packages/sklearn/preprocessing/_target_encoder.pyÚ__init__ÚTargetEncoder.__init__É   s$   € ð %ŒØŒØ&ÔØŒØŒØ(Õó    )Ú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 	×Ñ Ô%Øˆr)   c           	      ó  • SSK JnJn  U R                  X5      u  pVpxU R                  S:X  a'  U" U R
                  U R                  U R                  S9n	O&U" U R
                  U R                  U R                  S9n	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                  X5       Hu  u  p¼X[SS24   X{   pí[        R                   " USS	9nU R                  S:X  a  U R#                  UUUU5      nOU R%                  UUUU5      nU R'                  U
UU) UUU5        Mw     U
$ )
aD  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.

Returns
-------
X_trans : ndarray of shape (n_samples, n_features) or                     (n_samples, (n_features * n_classes))
    Transformed input.
r   )ÚKFoldÚStratifiedKFoldr   )r!   r   r   é   ©ÚdtypeN©Úaxis)Úsklearn.model_selectionr2   r3   r,   Útarget_type_r    r!   r   ÚnpÚemptyÚshapeÚlenÚclasses_Úfloat64Ú
empty_likeÚsplitÚmeanÚ_fit_encoding_multiclassÚ"_fit_encoding_binary_or_continuousÚ_transform_X_ordinal)r%   r-   r.   r2   r3   Ú	X_ordinalÚX_known_maskÚ	y_encodedÚn_categoriesr    ÚX_outÚ	train_idxÚtest_idxÚX_trainÚy_trainÚy_train_meanÚ	encodingss                    r&   Úfit_transformÚTargetEncoder.fit_transformõ   sw  € ÷6	
ð
 <@×;RÑ;RÐSTÓ;XÑ8ˆ	 ð
 ×Ñ Ó,Ù�t—w‘w¨¯©À4×CTÑCTÑU‰Bá Ø—‘ §¡¸D×<MÑ<MñˆBð
 ×Ñ Ó,Ü—H’HØ—‘ Ñ# Y§_¡_°QÑ%7¼#¸d¿m¹mÓ:LÑ%LÐMÜ—j‘jñ‰Eô
 —M’M )´2·:±:Ñ>ˆEà#%§8¡8¨A¦>ÑˆIØ(²A¨Ñ6¸	Ñ8L�WÜŸ7š7 7°Ñ3ˆLà× Ñ  LÓ0Ø ×9Ñ9ØØØ Ø ó	‘	ð !×CÑCØØØ Ø ó	�	ð ×%Ñ%ØØØ�ØØØöñ% $2ð4 ˆr)   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   r4   r5   N)Ú
_transformr:   r;   r<   r=   r>   r?   r@   rA   rF   ÚsliceÚ
encodings_Útarget_mean_)r%   r-   rG   rH   rK   s        r&   Ú	transformÚTargetEncoder.transformF  s»   € ð, #'§/¡/Ø˜h¸+ð #2ð #
Ñˆ	ð
 ×Ñ Ó,Ü—H’HØ—‘ Ñ# Y§_¡_°QÑ%7¼#¸d¿m¹mÓ:LÑ%LÐMÜ—j‘jñ‰Eô
 —M’M )´2·:±:Ñ>ˆEà×!Ñ!ØØØˆMÜ�$‹KØ�O‰OØ×Ñô	
ð ˆr)   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XÀl        XšX+4$ )z(Fit a target encoding with all the data.r   )ÚLabelBinarizerÚLabelEncoderrU   rV   rW   r   )r   r   r   r.   )Ú
input_namez3Unknown label type: Target type was inferred to be z. Only z are supported.Nr   r   T)Ú	y_numericÚ	estimatorr7   c              3   ó8   #   • U  H  n[        U5      v •  M     g 7fr$   )r>   )Ú.0Úcategory_for_features     r&   Ú	<genexpr>Ú3TargetEncoder._fit_encodings_all.<locals>.<genexpr>š  s   é € ÐTÒCSÐ+?ŒSÐ%×&Ð&ÒCSùs   ‚)r6   Úcount)Úsklearn.preprocessingra   rb   r   Ú_fitr   r   Ú
ValueErrorr:   r?   rR   r   r;   rC   r]   rZ   ÚfromiterÚcategories_Úint64r>   rD   rE   r\   )r%   r-   r.   ra   rb   Úaccepted_target_typesÚinferred_type_of_targetÚlabel_encoderÚlabel_binarizerrG   rH   rJ   rQ   s                r&   r,   Ú TargetEncoder._fit_encodings_alls  sÍ  € ÷ 	Gä Ô%Ø�	‰	�! HÀˆ	ÑLà×Ñ˜vÓ%Ø$JÐ!Ü&4°QÀ3Ñ&GÐ#Ø&ÓCÜ ØIØ.Ñ1°Ð9NÐ8Oð P!ð!óð ð
 !8Õà $× 0Ñ 0ˆDÔàˆŒØ×Ñ Ó(Ù(›NˆMØ×+Ñ+¨AÓ.ˆAØ)×2Ñ2ˆD�MØ×Ñ ,Ó.Ù,Ó.ˆOØ×-Ñ-¨aÓ0ˆAØ+×4Ñ4ˆD�Mä˜ d°dÑ;ˆAäŸGšG A¨AÑ.ˆÔà"&§/¡/Ø˜h¸+ð #2ð #
Ñˆ	ô —{’{ÙTÀ4×CSÒCSÓTÜ—(‘(Ü�d×&Ñ&Ó'ñ
ˆð
 ×Ñ Ó,Ø×5Ñ5ØØØØ×!Ñ!ó	‰Ið ×?Ñ?ØØØØ×!Ñ!ó	ˆIð $Œà¨Ð7Ð7r)   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   r;   Úvarr	   r   )r%   rG   r.   rJ   Útarget_meanÚ
y_variancerQ   s          r&   rE   Ú0TargetEncoder._fit_encoding_binary_or_continuous°  se   € ð �;‰;˜&Ó ÜŸš ›ˆJÜ6ØØØØØóˆIð Ðô +ØØØØ—‘ØóˆIð Ðr)   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  o¥U
   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)rg   ÚstartÚidxÚ	n_classesÚ
n_featuress      €€r&   ri   Ú9TargetEncoder._fit_encoding_multiclass.<locals>.<genexpr>ß  s3   øé € ð 
â*�Ü˜U Y°Ñ%;¸j×I�õ áIñ Ú*ùs   ƒ'*)Ún_features_in_r>   r?   r~   rE   Úextend)r%   rG   r.   rJ   ry   rQ   ÚiÚy_classÚencodingÚreorder_indexr€   r�   r‚   s              @@r&   rD   Ú&TargetEncoder._fit_encoding_multiclassÇ  s�   ù€ ð ×(Ñ(ˆ
Ü˜Ÿ™Ó&ˆ	àˆ	Ü�yÖ!ˆAØš˜1˜‘gˆGØ×>Ñ>ØØØØ‘ó	ˆHð ×Ñ˜XÖ&ñ "õ
ä˜zÔ*ó
ˆñ
 +8Ó8ª- 3˜#”©-Ñ8Ð8ùÒ8s   ÂBc                 ó  • U R                   S:X  aM  [        U R                  5      n[        U5       H(  u  p‰X‡-  n
X‡-  nX’XJ4      XU4'   Xk   XSS2U
4   U4'   M*     g[        U5       H  u  p‰X’XH4      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)r:   r>   r?   Ú	enumerate)r%   rK   rG   ÚX_unknown_maskÚrow_indicesrQ   ry   r�   Úe_idxrˆ   Úfeat_idxÚmean_idxs               r&   rF   Ú"TargetEncoder._transform_X_ordinalæ  s³   € ð( ×Ñ Ó,Ü˜DŸM™MÓ*ˆIÜ#,¨YÖ#7‘�à Ñ-�à Ñ,�Ø,4¸{Ð?TÑ5UÑ,V� 5Ð(Ñ)Ø<GÑ<Q�¢Q¨ [Ñ1°5Ð8Ó9ò $8ô $-¨YÖ#7‘�Ø,4¸{Ð?QÑ5RÑ,S� 5Ð(Ñ)Ø9D�n¢Q¨ XÑ.°Ð5Ó6ò $8r)   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   Ú_r5   )r   r   r:   r?   r;   ÚasarrayÚobject)r%   Úinput_featuresÚfeature_namesÚfeature_nameÚ
class_names        r&   Úget_feature_names_outÚ#TargetEncoder.get_feature_names_out  sƒ   € ô" 	˜Ð.Ô/Ü/°ÓEˆØ×Ñ Ó,ñ %2ôâ$1�LØ"&§-¥-�Jð  �.  * Ó.á"/ñ /Ù$1ð ñ ô
 —:’:˜m´6Ñ:Ð:à Ð ùós   ­%A0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Ñ'Ó)ˆØ$(ˆ×ÑÔ!Øˆr)   )
r   r?   r    r\   r   r!   r   r]   r   r:   )r   r   r   é   TNr$   )Ú__name__Ú
__module__Ú__qualname__Ú__firstlineno__Ú__doc__r   Úlistr
   r   r   r"   ÚdictÚ__annotations__r'   r   r/   rR   r^   r,   rE   rD   rF   r›   rŸ   Ú__static_attributes__Ú__classcell__)r£   s   @r&   r   r      sæ   ø‡ ñeñP " 6 (Ó+¨TÐ2Ù"Ò#QÓRÐSÙ˜v˜hÓ'©°$¸¸4ÈÑ)OÐPÙ˜ ! T°&Ñ9Ð:Ø�;Ø'Ð(ñ$Ð˜Dó ð ØØØØØô)ñ  °Ñ5ñó 6ðñ6 °Ñ5ñNó 6ðNò`+òZ;8òzò.9ò> EôD!÷:ó r)   r   )Únumbersr   r   Únumpyr;   Úsklearn.baser   r   Úsklearn.preprocessing._encodersr   Ú*sklearn.preprocessing._target_encoder_fastr   r	   Úsklearn.utils._param_validationr
   r   Úsklearn.utils.multiclassr   Úsklearn.utils.validationr   r   r   r   r   © r)   r&   Ú<module>r¹      s<   ð÷ #ã ç ;Ý 8÷÷ AÝ 3÷ó ôPÐ(¨,õ Pr)   