`L i@ ddlZddlZddlmZddlZddlmZddlmZm Z m Z m Z ddl m Z mZddlmZmZmZmZddlmZdd lmZdd lmZmZmZdd lmZdd lmZm Z m!Z!m"Z"d dgZ#Gdde eZ$Gdd e$Z%Gdde e$Z&y)N)Integral)sparse) BaseEstimatorOneToOneFeatureMixinTransformerMixin _fit_context)_safe_indexing check_array)_check_unknown_encode _get_counts_unique) _get_mask) is_scalar_nan)Interval RealNotInt StrOptions)_get_output_config)_check_feature_names_check_feature_names_in_check_n_featurescheck_is_fitted OneHotEncoderOrdinalEncodercreZdZdZd dZ d dZ d dZedZdZ dZ dZ d Z fd Z xZS) _BaseEncoderzm Base class for encoders that includes the code to categorize and transform the input features. ct|drt|dddk(s`t|d|}t|dsAtj|j tj rt|t|}n|}d}n|}|j\}}g}t|D]0}t||d } t| dd| } |j| 2|||fS) a Perform custom check_array: - convert list of strings to object dtype - check for missing values for object dtype data (check_array does not do that) - return list of features (arrays): this list of features is constructed feature by feature to preserve the data types of pandas DataFrame columns, as otherwise information is lost and cannot be used, e.g. for the `categories_` attribute. ilocndimrrN)dtypeensure_all_finiter!F)indicesaxis) ensure_2dr!r") hasattrgetattrr np issubdtyper!str_objectshaperanger append) selfXr"X_tempneeds_validation n_samples n_features X_columnsiXis e/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sklearn/preprocessing/_encoders.py_check_Xz_BaseEncoder._check_X#s6"wq&!'<'A $BSTF1g&2==rww+OCTU$  1  ! : z" !A115Be4CSB   R  !)Z//c|jt||dt||d|j||\}}}||_|j dk7r#t |j |k7r tdg|_g} |xs |j} t|D]D} || } |j dk(r+t| | } | r| \}}| j|n| }ntj| jtj rt"}n | j}tj$|j | |}|jt"k(rVt'|dt(rC| jj*d k7r*d | d t-| dj.d }t||dd D]}t1|std|d| |j2t t|k7rd | d}t|| jj*dvr\tj4|}d}tj6|d rd nd}tj8|d||d|k7r t||dk(r+t;| |}|rdj=|| }t|| r| jt?| ||jj|Gd|i}|r| |d<i}|rCtA|jD]&\}}t1|d s|j2dz ||<(||d<|jr|jC|| ||S)NTresetr"autozOShape mismatch: if categories is an array, it has to be of shape (n_features,).) return_countsr!rSz In column zY, the predefined categories have type 'bytes' which is incompatible with values of type 'z'.zKNan should be the last element in user provided categories, see categories z in column #z7, the predefined categories contain duplicate elements.OUSz>Unsorted categories are not supported for numerical categorieserrorz5Found unknown categories {0} in column {1} during fitr4category_countsr#missing_indices)"_check_infrequent_enabledrrr:n_features_in_ categorieslen ValueError categories__infrequent_enabledr.rr/r)r*r!r+r,array isinstancebyteskindtype__name__rsizesortisnananyr formatr enumerate _fit_infrequent_category_mapping)r0r1handle_unknownr"rA(return_and_ignore_missing_for_infrequentX_listr4r5rGcompute_countsr7r8resultcatscountsXi_dtypemsgcategory sorted_cats error_msgstop_idxdiffoutputrH feature_idxcategories_for_idxs r9_fitz_BaseEncoder._fitHs| &&($.T1D1(, !2)6) % :) ??f $4??#z1 < &B$*B*Bz"E *AB&( >B!#)LD&#**62!D==2773 &H!xxHxx 2(CJJ&("47E2 ,%QC(!"Q%[112"6 %S/)!%Sb H$X.(DDH6*1#/99GDM 22$QC(77%S/)88==-"$''$-KX&(XXk"o%>rDHvvk)84YhGH(33!W,)"d3D**0&q/)o-!#**;r4+@A    # #D )KE *Ny) (7F$ % 33288==TWCW YYs^WWY&*&6&6q&9!&.>q.AQVWE!Q$KI$ XJ MM:+,-FF   ''v7NOf}r;c|j}t|j|Dcgc]\}}|dn||c}}Scc}}w)z'Infrequent categories for each feature.N)_infrequent_indicesziprN)r0infrequent_indicesrfr$s r9infrequent_categories_z#_BaseEncoder.infrequent_categories_sR"55&))9)9;M%N !'OD'): :   s=cdt|dd}t|dd}|duxr|dk\xs|du|_y)z This functions checks whether _infrequent_enabled is True or False. This has to be called after parameter validation in the fit function. max_categoriesN min_frequencyr#)r(rO)r0rrs r9rIz&_BaseEncoder._check_infrequent_enabled sH !'7>ot< $ & >>Q+>$' $ &  r;cft|jtjr||jk}nat|jtjr||jz}||k}n(t j |jdt}|j|jz dz}|jI|j|kr:|jdz }|dk(rd|ddn t j|dd| }d||<t j|} | jdkDr| SdS)aCompute the infrequent indices. Parameters ---------- category_count : ndarray of shape (n_cardinality,) Category counts. n_samples : int Number of samples. col_idx : int Index of the current category. Only used for the error message. Returns ------- output : ndarray of shape (n_infrequent_categories,) or None If there are infrequent categories, indices of infrequent categories. Otherwise None. rrBr#NT mergesort)rS)rQrnumbersrRealr)rur-rxrVsumrargsort flatnonzero) r0category_countr4col_idxinfrequent_maskmin_frequency_absn_current_featuresfrequent_category_countsmallest_levelsrks r9_identify_infrequentz!_BaseEncoder._identify_infrequents ( d(('*:*: ;,t/A/AAO **GLL 9 )D,>,> > ,/@@O hh~';';A'>dKO+00?3F3F3HH1L    *t/B/BEW/W&*&9&9A&= #&!+%)"#%**^+"N---#4800qv2d2r;c  |rTg}t|D]C\}}||vr)|jtj|||3|j|En|}t|Dcgc]\}}|j |||c}}|_g|_t|j D]\}} |j|} | |j jd3t| } ||vr| dz} tj| tj} | j} | | z }|| | <tjtj| | }tj|| |<|j j| ycc}}w)ahFit infrequent categories. Defines the private attribute: `_default_to_infrequent_mappings`. For feature `i`, `_default_to_infrequent_mappings[i]` defines the mapping from the integer encoding returned by `super().transform()` into infrequent categories. If `_default_to_infrequent_mappings[i]` is None, there were no infrequent categories in the training set. For example if categories 0, 2 and 4 were frequent, while categories 1, 3, 5 were infrequent for feature 7, then these categories are mapped to a single output: `_default_to_infrequent_mappings[7] = array([0, 3, 1, 3, 2, 3])` Defines private attribute: `_infrequent_indices`. `_infrequent_indices[i]` is an array of indices such that `categories_[i][_infrequent_indices[i]]` are all the infrequent category labels. If the feature `i` has no infrequent categories `_infrequent_indices[i]` is None. .. versionadded:: 1.1 Parameters ---------- n_samples : int Number of samples in training set. category_counts: list of ndarray `category_counts[i]` is the category counts corresponding to `self.categories_[i]`. missing_indices : dict Dict mapping from feature_idx to category index with a missing value. Nr#rB)r[r/r)deleterr_default_to_infrequent_mappingsrNrLemptyint64rV setdiff1darange)r0r4rGrHcategory_counts_rlcountrr infreq_idxrbn_catsmappingn_infrequent_catsn_frequent_catsfrequent_indicess r9r\z-_BaseEncoder._fit_infrequent_category_mappingDsF ! &/&@ 3" U/1$++ %)EF%++E2  3 / ,55E+F$ '  % %ni I$  02,'01I1I'J A #K##K0D!44;;DAYFo-! hhvRXX6G * %'88O"1GJ !||BIIf,=zJ (* /(BG$ %  0 0 7 7 @3 A$ s'F c|jsy|xsi}t|jdD]?}|j|}||d||dd|f|f<|jdk(s7d|dd|f<At |j D]G\}}| ||vr|dd|f||k7}n td}tj||||f|||f<Iy)aMap infrequent categories to integer representing the infrequent category. This modifies X_int in-place. Values that were invalid based on `X_mask` are mapped to the infrequent category if there was an infrequent category for that feature. Parameters ---------- X_int: ndarray of shape (n_samples, n_features) Integer encoded categories. X_mask: ndarray of shape (n_samples, n_features) Bool mask for valid values in `X_int`. ignore_category_indices : dict Dictionary mapping from feature_idx to category index to ignore. Ignored indexes will not be grouped and the original ordinal encoding will remain. Nr#rinfrequent_if_existT) rOr.r-rr]r[rslicer)take) r0rrrrinfrequent_idxr7rrows_to_updates r9rz'_BaseEncoder._map_infrequent_categoriess('' "9"?RU[[^, *G!55g>N%2@2CE6!W*%%w. /""&;; &*q'z" *$D$H$HI RJAw++!&q!t0G0J!J!&t')wwwna>O8P'QE.!# $ Rr;cht|}d|j_d|j_|S)NT)super__sklearn_tags__ input_tags categorical allow_nan)r0tags __class__s r9rz_BaseEncoder.__sklearn_tags__s-w')&*#$(! r;T)rFTFF)rFTFN)rU __module__ __qualname____doc__r:rnrpropertyrrIrr\rr __classcell__)rs@r9rrsp #0P16 tr $ BH   '+3ZPAd2Rhr;rc NeZdZUdZedhegeddhddgdehdgeed dd dgeed dd eed d d dgdgedhe gdZ e e d<ddde jddddddZdZdZd!dZdZdZedd"dZdZdZd"dZd Zy)#ra. Encode categorical features as a one-hot numeric array. The input to this transformer should be an array-like of integers or strings, denoting the values taken on by categorical (discrete) features. The features are encoded using a one-hot (aka 'one-of-K' or 'dummy') encoding scheme. This creates a binary column for each category and returns a sparse matrix or dense array (depending on the ``sparse_output`` parameter). By default, the encoder derives the categories based on the unique values in each feature. Alternatively, you can also specify the `categories` manually. This encoding is needed for feeding categorical data to many scikit-learn estimators, notably linear models and SVMs with the standard kernels. Note: a one-hot encoding of y labels should use a LabelBinarizer instead. Read more in the :ref:`User Guide `. For a comparison of different encoders, refer to: :ref:`sphx_glr_auto_examples_preprocessing_plot_target_encoder.py`. Parameters ---------- categories : 'auto' or a list 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 ith 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 can be found in the ``categories_`` attribute. .. versionadded:: 0.20 drop : {'first', 'if_binary'} or an array-like of shape (n_features,), default=None Specifies a methodology to use to drop one of the categories per feature. This is useful in situations where perfectly collinear features cause problems, such as when feeding the resulting data into an unregularized linear regression model. However, dropping one category breaks the symmetry of the original representation and can therefore induce a bias in downstream models, for instance for penalized linear classification or regression models. - None : retain all features (the default). - 'first' : drop the first category in each feature. If only one category is present, the feature will be dropped entirely. - 'if_binary' : drop the first category in each feature with two categories. Features with 1 or more than 2 categories are left intact. - array : ``drop[i]`` is the category in feature ``X[:, i]`` that should be dropped. When `max_categories` or `min_frequency` is configured to group infrequent categories, the dropping behavior is handled after the grouping. .. versionadded:: 0.21 The parameter `drop` was added in 0.21. .. versionchanged:: 0.23 The option `drop='if_binary'` was added in 0.23. .. versionchanged:: 1.1 Support for dropping infrequent categories. sparse_output : bool, default=True When ``True``, it returns a :class:`scipy.sparse.csr_matrix`, i.e. a sparse matrix in "Compressed Sparse Row" (CSR) format. .. versionadded:: 1.2 `sparse` was renamed to `sparse_output` dtype : number type, default=np.float64 Desired dtype of output. handle_unknown : {'error', 'ignore', 'infrequent_if_exist', 'warn'}, default='error' Specifies the way unknown categories are handled during :meth:`transform`. - 'error' : Raise an error if an unknown category is present during transform. - 'ignore' : When an unknown category is encountered during transform, the resulting one-hot encoded columns for this feature will be all zeros. In the inverse transform, an unknown category will be denoted as None. - 'infrequent_if_exist' : When an unknown category is encountered during transform, the resulting one-hot encoded columns for this feature will map to the infrequent category if it exists. The infrequent category will be mapped to the last position in the encoding. During inverse transform, an unknown category will be mapped to the category denoted `'infrequent'` if it exists. If the `'infrequent'` category does not exist, then :meth:`transform` and :meth:`inverse_transform` will handle an unknown category as with `handle_unknown='ignore'`. Infrequent categories exist based on `min_frequency` and `max_categories`. Read more in the :ref:`User Guide `. - 'warn' : When an unknown category is encountered during transform a warning is issued, and the encoding then proceeds as described for `handle_unknown="infrequent_if_exist"`. .. versionchanged:: 1.1 `'infrequent_if_exist'` was added to automatically handle unknown categories and infrequent categories. .. versionadded:: 1.6 The option `"warn"` was added in 1.6. min_frequency : int or float, default=None Specifies the minimum frequency below which a category will be considered infrequent. - If `int`, categories with a smaller cardinality will be considered infrequent. - If `float`, categories with a smaller cardinality than `min_frequency * n_samples` will be considered infrequent. .. versionadded:: 1.1 Read more in the :ref:`User Guide `. max_categories : int, default=None Specifies an upper limit to the number of output features for each input feature when considering infrequent categories. If there are infrequent categories, `max_categories` includes the category representing the infrequent categories along with the frequent categories. If `None`, there is no limit to the number of output features. .. versionadded:: 1.1 Read more in the :ref:`User Guide `. feature_name_combiner : "concat" or callable, default="concat" Callable with signature `def callable(input_feature, category)` that returns a string. This is used to create feature names to be returned by :meth:`get_feature_names_out`. `"concat"` concatenates encoded feature name and category with `feature + "_" + str(category)`.E.g. feature X with values 1, 6, 7 create feature names `X_1, X_6, X_7`. .. versionadded:: 1.3 Attributes ---------- categories_ : list of arrays The categories of each feature determined during fitting (in order of the features in X and corresponding with the output of ``transform``). This includes the category specified in ``drop`` (if any). drop_idx_ : array of shape (n_features,) - ``drop_idx_[i]`` is the index in ``categories_[i]`` of the category to be dropped for each feature. - ``drop_idx_[i] = None`` if no category is to be dropped from the feature with index ``i``, e.g. when `drop='if_binary'` and the feature isn't binary. - ``drop_idx_ = None`` if all the transformed features will be retained. If infrequent categories are enabled by setting `min_frequency` or `max_categories` to a non-default value and `drop_idx[i]` corresponds to a infrequent category, then the entire infrequent category is dropped. .. versionchanged:: 0.23 Added the possibility to contain `None` values. infrequent_categories_ : list of ndarray Defined only if infrequent categories are enabled by setting `min_frequency` or `max_categories` to a non-default value. `infrequent_categories_[i]` are the infrequent categories for feature `i`. If the feature `i` has no infrequent categories `infrequent_categories_[i]` is None. .. versionadded:: 1.1 n_features_in_ : int Number of features seen during :term:`fit`. .. versionadded:: 1.0 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 feature_name_combiner : callable or None Callable with signature `def callable(input_feature, category)` that returns a string. This is used to create feature names to be returned by :meth:`get_feature_names_out`. .. versionadded:: 1.3 See Also -------- OrdinalEncoder : Performs an ordinal (integer) encoding of the categorical features. TargetEncoder : Encodes categorical features using the target. sklearn.feature_extraction.DictVectorizer : Performs a one-hot encoding of dictionary items (also handles string-valued features). sklearn.feature_extraction.FeatureHasher : Performs an approximate one-hot encoding of dictionary items or strings. LabelBinarizer : Binarizes labels in a one-vs-all fashion. MultiLabelBinarizer : Transforms between iterable of iterables and a multilabel format, e.g. a (samples x classes) binary matrix indicating the presence of a class label. Examples -------- Given a dataset with two features, we let the encoder find the unique values per feature and transform the data to a binary one-hot encoding. >>> from sklearn.preprocessing import OneHotEncoder One can discard categories not seen during `fit`: >>> enc = OneHotEncoder(handle_unknown='ignore') >>> X = [['Male', 1], ['Female', 3], ['Female', 2]] >>> enc.fit(X) OneHotEncoder(handle_unknown='ignore') >>> enc.categories_ [array(['Female', 'Male'], dtype=object), array([1, 2, 3], dtype=object)] >>> enc.transform([['Female', 1], ['Male', 4]]).toarray() array([[1., 0., 1., 0., 0.], [0., 1., 0., 0., 0.]]) >>> enc.inverse_transform([[0, 1, 1, 0, 0], [0, 0, 0, 1, 0]]) array([['Male', 1], [None, 2]], dtype=object) >>> enc.get_feature_names_out(['gender', 'group']) array(['gender_Female', 'gender_Male', 'group_1', 'group_2', 'group_3'], ...) One can always drop the first column for each feature: >>> drop_enc = OneHotEncoder(drop='first').fit(X) >>> drop_enc.categories_ [array(['Female', 'Male'], dtype=object), array([1, 2, 3], dtype=object)] >>> drop_enc.transform([['Female', 1], ['Male', 2]]).toarray() array([[0., 0., 0.], [1., 1., 0.]]) Or drop a column for feature only having 2 categories: >>> drop_binary_enc = OneHotEncoder(drop='if_binary').fit(X) >>> drop_binary_enc.transform([['Female', 1], ['Male', 2]]).toarray() array([[0., 1., 0., 0.], [1., 0., 1., 0.]]) One can change the way feature names are created. >>> def custom_combiner(feature, category): ... return str(feature) + "_" + type(category).__name__ + "_" + str(category) >>> custom_fnames_enc = OneHotEncoder(feature_name_combiner=custom_combiner).fit(X) >>> custom_fnames_enc.get_feature_names_out() array(['x0_str_Female', 'x0_str_Male', 'x1_int_1', 'x1_int_2', 'x1_int_3'], dtype=object) Infrequent categories are enabled by setting `max_categories` or `min_frequency`. >>> import numpy as np >>> X = np.array([["a"] * 5 + ["b"] * 20 + ["c"] * 10 + ["d"] * 3], dtype=object).T >>> ohe = OneHotEncoder(max_categories=3, sparse_output=False).fit(X) >>> ohe.infrequent_categories_ [array(['a', 'd'], dtype=object)] >>> ohe.transform([["a"], ["b"]]) array([[0., 0., 1.], [1., 0., 0.]]) r@first if_binaryz array-likeN no_validation>r~rFignorerr#leftclosedrneitherbooleanconcat)rKdropr!r]rr sparse_outputfeature_name_combiner_parameter_constraintsTrF)rKrrr!r]rrrct||_||_||_||_||_||_||_||_yN)rKrr!r]rrrr) r0rKrrr!r]rrrs r9__init__zOneHotEncoder.__init__sA%* , *,%:"r;c|js|S|j|}||S|j|}|6||vr2|j|}t d||j d|d||S)zConvert `drop_idx` into the index for infrequent categories. If there are no infrequent categories, then `drop_idx` is returned. This method is called in `_set_drop_idx` when the `drop` parameter is an array-like. zUnable to drop category z from feature z because it is infrequent)rOrrrNrMitem)r0rldrop_idxdefault_to_infrequentrrKs r9_map_drop_idx_to_infrequentz)OneHotEncoder._map_drop_idx_to_infrequent s''O $ D D[ Q (O"55kB  )h:L.L))+6J*:h+?+D+D+F*IJ'=(AC %X..r;c 0|jd}nt|jtr|jdk(r0tjt |j t}n|jdk(ro|j Dcgc] }t |}}|jr:t|jD]"\}}| ||xx|jdz zcc<$tj|Dcgc] }|dk(rdnd c}t}ntj|jt}t |}|t |j k7r0d} t| jt |j |g} g} tt!||j D]\} \} }t#| s`tj$|| k(d}|jr%| j'|j)| |dn| j'| | ftt#|d r/| j'|j)| |jdz | j'| | ft+| rNd jd j-| Dcgc]\}}d j||c}}} t| tj| t}|_|jr||j.|_yg}t|D]G\} }|j2| }|||}ntj4||k(d}|j'|Itj|t|_ycc}wcc}wcc}}w) aCompute the drop indices associated with `self.categories_`. If `self.drop` is: - `None`, No categories have been dropped. - `'first'`, All zeros to drop the first category. - `'if_binary'`, All zeros if the category is binary and `None` otherwise. - array-like, The indices of the categories that match the categories in `self.drop`. If the dropped category is an infrequent category, then the index for the infrequent category is used. This means that the entire infrequent category is dropped. This methods defines a public `drop_idx_` and a private `_drop_idx_after_grouping`. - `drop_idx_`: Public facing API that references the drop category in `self.categories_`. - `_drop_idx_after_grouping`: Used internally to drop categories *after* the infrequent categories are grouped together. If there are no infrequent categories or drop is `None`, then `drop_idx_=_drop_idx_after_grouping`. NrrBrr#rrzF`drop` should have length equal to the number of features ({}), got {}rDzaThe following categories were supposed to be dropped, but were not found in the training data. {} zCategory: {}, Feature: {})rrQstrr)rurLrNr,rOr[rrVrPasarrayrMrZrrwherer/rrYjoin_drop_idx_after_grouping drop_idx_rr)r0drop_idx_after_groupingcatn_features_out_no_dropr7rn_features_out drop_arraydroplenre missing_drops drop_indicesrldrop_valcat_listrcvrr orig_drop_idxs r9 _set_drop_idxzOneHotEncoder._set_drop_idx#sn0 99 &* #  3 'yyG#*,((3t7G7G3HPV*W'k)>B>N>N)Os#c()O&)O++)243K3K)LI :%-$.q1Z__q5HH1I +-((/E*,q0d:! +'DIIVJ 0 016 B1 1h%X.!xxH(<=a@H}}$++ <<[(ST+V&,,k8-DE!". ''88hmmVWFWX"((+x)@A' B*=! & -:$(Aq!< B B1a H!!o%&(hh|6&J # )@%''+B+J!::DNI)23J)K 0% X(,(L(L)%#'<'D$,M$&NN3HH3T$UVW$XM  / 0 ZZ @DNi*P\sN5N Nc|j|}|jrZ|j|}|I||jk}d}t j ||t j |gtf}|r|j||}|S)zCompute the transformed categories used for column `i`. 1. If there are infrequent categories, the category is named 'infrequent_sklearn'. 2. Dropped columns are removed when remove_dropped=True. infrequent_sklearnrB) rNrOrmaxr) concatenaterPr,_remove_dropped_categories)r0r7remove_droppedrb infreq_map frequent_maskinfrequent_cats r9_compute_transformed_categoriesz-OneHotEncoder._compute_transformed_categoriess"  # #==a@J% *Z^^-= = !5~~-("((N3C6*RS 224;D r;c|j2|j|#tj||j|S|S)zRemove dropped categories.)rr)r)r0rKr7s r9rz(OneHotEncoder._remove_dropped_categoriessC  ) ) 5--a0<99Z)F)Fq)IJ Jr;cV|jDcgc] }t|}}|j-t|jD]\}}| ||xxdzcc<|js|St|j D]"\}}| ||xx|j dz zcc<$|Scc}w)z2Compute the n_features_out for each input feature.r#)rNrLrr[rOrrV)r0rbrkr7rrs r9_compute_n_features_outsz&OneHotEncoder._compute_n_features_outss(,(8(89#d)99  ( ( 4()F)FG # 8'1INI #''M't'?'?@ -MAz! 1I1, ,I -  #:sB&prefer_skip_nested_validationc|j||jd|j|j|_|S)a Fit OneHotEncoder to X. Parameters ---------- X : array-like of shape (n_samples, n_features) The data to determine the categories of each feature. y : None Ignored. This parameter exists only for compatibility with :class:`~sklearn.pipeline.Pipeline`. Returns ------- self Fitted encoder. allow-nan)r]r")rnr]rr_n_features_outs)r0r1ys r9fitzOneHotEncoder.fitsH& ..)   $ = = ? r;ct|td|d}|dk7r0|jr$|j}t |d|d|d|j dk(rd \}}n*|j d uxr|j d v}|j }|j||d | \}}|j\}} |jw|jj} || k7} t|jD]\} } | |  t| | | <| jdd} ||| kDxxdzcc<|| z}|j}t!j"dg|j$z}||d dzj|}t!j&|dzt(}d|d<t!j*|d|dd |j,t!j"|dd |dd t!j.|d}t1j2|||f||df|j,}|js|j5S|S)a Transform X using one-hot encoding. If `sparse_output=True` (default), it returns an instance of :class:`scipy.sparse._csr.csr_matrix` (CSR format). If there are infrequent categories for a feature, set by specifying `max_categories` or `min_frequency`, the infrequent categories are grouped into a single category. Parameters ---------- X : array-like of shape (n_samples, n_features) The data to encode. Returns ------- X_out : {ndarray, sparse matrix} of shape (n_samples, n_encoded_features) Transformed input. If `sparse_output=True`, a sparse matrix will be returned. transform) estimatordensedefaultzH output does not support sparse data. Set sparse_output=False to output z dataframes or disable z1 output via` ohe.set_output(transform="default").r~)TrN>rrr)r]r"rr#rDrrB)r%outr!)r)r-r!)rrr capitalizerMr]rrr-rr|r[rNrLreshaperavelr)cumsumrrrvrr!rwr csr_matrixtoarray)r0r1transform_outputcapitalize_transform_outputrr]rrr4r5to_drop keep_cellsr7rbmaskfeature_indicesr$indptrdatars r9rzOneHotEncoder.transformsv. -kTJ7S y (T-?-?*:*E*E*G './066F5GH78999    & (.I +O^"iit38K8KP9O"00N ))+ ( v!&  :  ( ( 43388:G')J$T%5%56 +41:%!$TGAJ  + ooa,G %'/ "a ' " j F||~))QC$*?*?$?@?3B//668>)a-s3q  vA6!":V\\B &*&*-wwvbz" 7F #ob12**  !!;;= Jr;c t|t|d}|j\}}t|j}t j |j}d}|jd|k7r(t|j||jdt|jDcgc]\}}|j|d}}}t j|D cgc]} | jc} } t j||f| } d} i} |jr |j }nd g|z}t#|D]}|j%|||}|jd}|dk(r,|j||j&|| d d |f<| |z } Y|d d | | |zf}t j(|j+d j-}||| d d |f<|j.d k(s|j.d vr||t j(|j d dk(j-}|j1r|j&|j&||| |<n|j||j&|| ||f<nt j(|j d dk(j-}|j1rL|j&$t j2|}td |d|j&|}|||| ||f<| |z } | rG| jt4k7r| j7t4} | j9D] \}}d | ||f<| Scc}}wcc} w)a Convert the data back to the original representation. When unknown categories are encountered (all zeros in the one-hot encoding), ``None`` is used to represent this category. If the feature with the unknown category has a dropped category, the dropped category will be its inverse. For a given input feature, if there is an infrequent category, 'infrequent_sklearn' will be used to represent the infrequent category. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_encoded_features) The transformed data. Returns ------- X_original : ndarray of shape (n_samples, n_features) Inverse transformed array. csr) accept_sparseIShape of the passed X data is not correct. Expected {0} columns, got {1}.r#F)rrBrN)r%r)rr~zSamples z] can not be inverted when drop=None and handle_unknown='error' because they contain all zeros)rr r-rLrNr)rrrMrZr[r result_typer!rrOrr.rrrargmaxflattenr]rYrr,r{items)r0r1r4_r5rrer7transformed_featuresrdtX_trj found_unknownrcats_wo_dropped n_categoriessublabelsunknowndroppedall_zero_samplesridxrs r9inverse_transformzOneHotEncoder.inverse_transform?s.   /ww 1))*  5 56 X  771: 'SZZ CD D"$"2"23 1  0 05 0 I  ^^3GHCciiH IxxJ/r:   # #!%!9!9 "&*!4 z"3 A"==$Q'O+003L q !--a01N1Nq1QRQT \!Aq1|+++,CZZ  23;;=F(0DAJ""h.##'FF&q)1**SWW!W_%9:BBD;;=55=88;C+2 a(+/+;+;A+> 99!<,WaZ(**SWW!W_%9:BBD;;=44<+->>'+B((&'7&89== $<x'HD!$  Ag3 n zzV#{{6**002 ' T"&T3Y ' _ Is 0M:#Nct|t||}t|jDcgc]\}}|j |}}}|j }g}t t|D]/}||Dcgc]}||||}}|j|1tj|tScc}}wcc}w)aGet output feature names for transformation. 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. rB) rrr[rNr _check_get_feature_name_combinerr.rLextendr)rPr,) r0input_featuresr7rrb name_combiner feature_namestnamess r9get_feature_names_outz#OneHotEncoder.get_feature_names_outs( 0~F"$"2"23 1  0 0 3  ==?  s4y! (ABFq'JQ]>!#4a8JEJ   ' (xx V44 Ks C>Cc|jdk(rdS|jdd}t|tstdt |d|jS)Nrc$|dzt|zS)Nr)r)featurerfs r9z@OneHotEncoder._check_get_feature_name_combiner..sWs]S]-Jr;r9rfzRWhen `feature_name_combiner` is a callable, it should return a Python string. Got z instead.)rrQr TypeErrorrT)r0dry_run_combiners r9r/z.OneHotEncoder._check_get_feature_name_combinersh  % % 1J J#99)ZP .4**./?*@)AL-- -r;rr)rUrrrrlistrrrcallablerdict__annotations__r)float64rrrrrrr rrr-r6r/r;r9rrsQh"6(+T2Wk23\4H I J $HafEtL Xq$v 6 ZAi 8  $",hZ"8(!C$D( jj&;*/0rAh.*566Unun!5F .r;c PeZdZUdZedhegdeeejgeddhgeeejdge eddd dge eddd e e d dd dgd Z e ed <dejddejddddZedddZdZdZy)ra Encode categorical features as an integer array. The input to this transformer should be an array-like of integers or strings, denoting the values taken on by categorical (discrete) features. The features are converted to ordinal integers. This results in a single column of integers (0 to n_categories - 1) per feature. Read more in the :ref:`User Guide `. For a comparison of different encoders, refer to: :ref:`sphx_glr_auto_examples_preprocessing_plot_target_encoder.py`. .. versionadded:: 0.20 Parameters ---------- categories : 'auto' or a list 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 ith column. The passed categories should not mix strings and numeric values, and should be sorted in case of numeric values. The used categories can be found in the ``categories_`` attribute. dtype : number type, default=np.float64 Desired dtype of output. handle_unknown : {'error', 'use_encoded_value'}, default='error' When set to 'error' an error will be raised in case an unknown categorical feature is present during transform. When set to 'use_encoded_value', the encoded value of unknown categories will be set to the value given for the parameter `unknown_value`. In :meth:`inverse_transform`, an unknown category will be denoted as None. .. versionadded:: 0.24 unknown_value : int or np.nan, default=None When the parameter handle_unknown is set to 'use_encoded_value', this parameter is required and will set the encoded value of unknown categories. It has to be distinct from the values used to encode any of the categories in `fit`. If set to np.nan, the `dtype` parameter must be a float dtype. .. versionadded:: 0.24 encoded_missing_value : int or np.nan, default=np.nan Encoded value of missing categories. If set to `np.nan`, then the `dtype` parameter must be a float dtype. .. versionadded:: 1.1 min_frequency : int or float, default=None Specifies the minimum frequency below which a category will be considered infrequent. - If `int`, categories with a smaller cardinality will be considered infrequent. - If `float`, categories with a smaller cardinality than `min_frequency * n_samples` will be considered infrequent. .. versionadded:: 1.3 Read more in the :ref:`User Guide `. max_categories : int, default=None Specifies an upper limit to the number of output categories for each input feature when considering infrequent categories. If there are infrequent categories, `max_categories` includes the category representing the infrequent categories along with the frequent categories. If `None`, there is no limit to the number of output features. `max_categories` do **not** take into account missing or unknown categories. Setting `unknown_value` or `encoded_missing_value` to an integer will increase the number of unique integer codes by one each. This can result in up to `max_categories + 2` integer codes. .. versionadded:: 1.3 Read more in the :ref:`User Guide `. Attributes ---------- categories_ : list of arrays The categories of each feature determined during ``fit`` (in order of the features in X and corresponding with the output of ``transform``). This does not include categories that weren't seen during ``fit``. n_features_in_ : int Number of features seen during :term:`fit`. .. versionadded:: 1.0 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 infrequent_categories_ : list of ndarray Defined only if infrequent categories are enabled by setting `min_frequency` or `max_categories` to a non-default value. `infrequent_categories_[i]` are the infrequent categories for feature `i`. If the feature `i` has no infrequent categories `infrequent_categories_[i]` is None. .. versionadded:: 1.3 See Also -------- OneHotEncoder : Performs a one-hot encoding of categorical features. This encoding is suitable for low to medium cardinality categorical variables, both in supervised and unsupervised settings. TargetEncoder : Encodes categorical features using supervised signal in a classification or regression pipeline. This encoding is typically suitable for high cardinality categorical variables. LabelEncoder : Encodes target labels with values between 0 and ``n_classes-1``. Notes ----- With a high proportion of `nan` values, inferring categories becomes slow with Python versions before 3.10. The handling of `nan` values was improved from Python 3.10 onwards, (c.f. `bpo-43475 `_). Examples -------- Given a dataset with two features, we let the encoder find the unique values per feature and transform the data to an ordinal encoding. >>> from sklearn.preprocessing import OrdinalEncoder >>> enc = OrdinalEncoder() >>> X = [['Male', 1], ['Female', 3], ['Female', 2]] >>> enc.fit(X) OrdinalEncoder() >>> enc.categories_ [array(['Female', 'Male'], dtype=object), array([1, 2, 3], dtype=object)] >>> enc.transform([['Female', 3], ['Male', 1]]) array([[0., 2.], [1., 0.]]) >>> enc.inverse_transform([[1, 0], [0, 1]]) array([['Male', 1], ['Female', 2]], dtype=object) By default, :class:`OrdinalEncoder` is lenient towards missing values by propagating them. >>> import numpy as np >>> X = [['Male', 1], ['Female', 3], ['Female', np.nan]] >>> enc.fit_transform(X) array([[ 1., 0.], [ 0., 1.], [ 0., nan]]) You can use the parameter `encoded_missing_value` to encode missing values. >>> enc.set_params(encoded_missing_value=-1).fit_transform(X) array([[ 1., 0.], [ 0., 1.], [ 0., -1.]]) Infrequent categories are enabled by setting `max_categories` or `min_frequency`. In the following example, "a" and "d" are considered infrequent and grouped together into a single category, "b" and "c" are their own categories, unknown values are encoded as 3 and missing values are encoded as 4. >>> X_train = np.array( ... [["a"] * 5 + ["b"] * 20 + ["c"] * 10 + ["d"] * 3 + [np.nan]], ... dtype=object).T >>> enc = OrdinalEncoder( ... handle_unknown="use_encoded_value", unknown_value=3, ... max_categories=3, encoded_missing_value=4) >>> _ = enc.fit(X_train) >>> X_test = np.array([["a"], ["b"], ["c"], ["d"], ["e"], [np.nan]], dtype=object) >>> enc.transform(X_test) array([[2.], [0.], [1.], [2.], [3.], [4.]]) r@rrFuse_encoded_valueNr#rrrr)rKr!encoded_missing_valuer] unknown_valuerrrrKr!r]rFrErrcf||_||_||_||_||_||_||_yrrG)r0rKr!r]rFrErrs r9rzOrdinalEncoder.__init__s:% ,*%:"*,r;Trc|jdk(rt|jrEtj|jj dk7r{t d|jdt|jtjs>td|jd|jtd|jd|j||jdd }|d |_ |jDcgc] }t|}}|jr6t!|j"D]\}}| ||xxt|zcc< t!|jD]!\}} t| d s||xxd zcc<#|jdk(r8|D]3} d |jcxkr| ksnt d|jd|jrtj|jj dk7rDt|j$r/t dt'|jd|jdt|j$s{t!|D cgc]-\}} ||jvrd |j$cxkr| krnn|/} }} | r6t)|dr|j*| } t d|j$d| |Scc}wcc} }w)a Fit the OrdinalEncoder to X. Parameters ---------- X : array-like of shape (n_samples, n_features) The data to determine the categories of each feature. y : None Ignored. This parameter exists only for compatibility with :class:`~sklearn.pipeline.Pipeline`. Returns ------- self : object Fitted encoder. rDfzOWhen unknown_value is np.nan, the dtype parameter should be a float dtype. Got .z]unknown_value should be an integer or np.nan when handle_unknown is 'use_encoded_value', got zQunknown_value should only be set when handle_unknown is 'use_encoded_value', got rT)r]r"r^rHrDr#rz!The used value for unknown_value zD is one of the values already used for encoding the seen categories.z%There are missing values in features z:. For OrdinalEncoder to encode missing values with dtype: zG, set encoded_missing_value to a non-nan value, or set dtype to a floatfeature_names_in_zencoded_missing_value (z:) is already used to encode a known category in features: )r]rrFr)r!rSrMrQrrr;rn_missing_indicesrNrLrOr[rrEr=r'rL) r0r1r fit_resultsrK cardinalitiesrl infrequentcat_idxrm cardinalityinvalid_featuress r9rzOrdinalEncoder.fits2&   "5 5T//088DJJ',,3$..2jj\<   2 2G4D4DE --.a1    +))*!- ii ..)59   !,,= >;?;K;KLZZL L  # #,5T5P5P+Q B' Z)!+.#j/A. B ,5T5E5E+F , 'G'/34g&!+& ,   "5 5,  **8[8$;--./++   xx #((C/M**5!;D1123499= E++!!;!;< 1:-0H$,$"7"77T77E+E$ $$t%89+/+A+ABR+S($1$2L2L1MNS+,.  sMP$s K(92K-clt|d|j||jd|j\}}|j |j d}|jj D]"\}}|dd|f|k(}|j|||f<$|jdk(r|j||<|S)a' Transform X to ordinal codes. Parameters ---------- X : array-like of shape (n_samples, n_features) The data to encode. Returns ------- X_out : ndarray of shape (n_samples, n_features) Transformed input. rNr)r]r"rFr|NrD) rrr]rMr{r!rrErF)r0r1rrX_transrQ missing_idxX_missing_masks r9rzOrdinalEncoder.transform.s m, ..)$($9$9 ( v ,,tzz,6$($9$9$?$?$A J G["1g:.+=N/3/I/IGNG+ , J   "5 5#11GVG r;ct|t|d}|j\}}t|j}d}|jd|k7r(t |j ||jdtj|jDcgc]}|jc}}tj||f|}i} i} t|dd} t|D]"} |dd| f} | |jvr(t| |j}|j| | |<t!d}|j| }| U| | Pt|t| | z }| |k(| | <| | }tj"|t$}d|| | <||}|j&d k(r@t| |j(}|| | <|}t+|tj,r||z}n|}| |j/d d }||||| f<%| s| r|j/t0d }| r| j3D] \}}d|||f<| r| j3D] \}}d |||f<|Scc}w) aV Convert the data back to the original representation. Parameters ---------- X : array-like of shape (n_samples, n_encoded_features) The transformed data. Returns ------- X_original : ndarray of shape (n_samples, n_features) Inverse transformed array. rr?rr#rBrNFrDrrUr)rr r-rLrNrMrZr)rr!rr(r.rMrrEr ones_likerxr]rFrQndarrayr{r,r)r0r1r4rr5rerr!r"r$infrequent_masksrr7r(X_i_maskrrKinfrequent_encoding_valuefrequent_categories_maskunknown_labels known_labels labels_intr,rs r9r-z OrdinalEncoder.inverse_transformNs  [ 9ww 1))*  X  771: #SZZ AGGAJ?@ @^^43C3CDCciiD ExxJ/r: $T+@$Gz"" =Aq!tWFD)))$VT-G-GH#'#8#8#;x "4[N))!,J!-2DQ2G2S,/ OcBTUVBW>X,X)&,0I&I #"21"5!5,.<< $+O(BG();A)>?'(@A ""&99!*643E3E!F#1 a . nbjj9"l2N%1N/66wU6KJ&0&ros}VV/II#*FF2 , -r#]rj R .LR .j|)<|r;