`L iȧHdZddlZddlZddlZddlZddlmZddlmZddl m Z m Z ddl m Z mZmZddlZddlZddlmZddlmZdd lmZmZmZdd lmZmZm Z dd l!m"Z"dd l#m$Z$m%Z%d dl&m'Z'm(Z(d dl)m*Z*d dl+m,Z,ejZej\ej^fZ0dZdddZ1 d[dZ2dddddZ3dddddZ4dddddZ5dZ6d Z7d!Z8d"Z9d#Z:d$Z;d%Z d\d(Z?d)Z@d*ZAd+ZBd,ZC d]dd-ddddddddd d ddd.d/ZDd]d0ZE d]dd-ddddddddd d ddd1d2ZFd^d3ZGdddd4d5ZHd6ZId7ZJd8ddd9d:ZKdeLfd;ZMdZdeLd<d=ZNd>d?d@ZOdAZPdddBdCdDZQd]dEZRddddFdGZSd_dHZTdIZUdZdJZVdKZWdLZXdMZYdNZZdOZ[dPZ\dZddQdRZ]dZdSZ^dZdTZ_dUZ`dVZadWZbdXZc d`dYZdy)azJFunctions to validate input and parameters within scikit-learn estimators.N)Sequence)suppress)reducewraps) Parameterisclass signature) get_config)DataConversionWarningNotFittedErrorPositiveSpectrumWarning)_asarray_with_order_is_numpy_namespace get_namespace)_deprecate_force_all_finite)ComplexWarning_preserve_dia_indices_dtype) FiniteStatus cy_isfinite)get_tags)_object_dtype_isnanz1.3)versionc&fd}|||S|S)aDecorator for methods that issues warnings for positional arguments. Using the keyword-only argument syntax in pep 3102, arguments after the * will issue a warning when passed as a positional argument. Parameters ---------- func : callable, default=None Function to check arguments on. version : callable, default="1.3" The version when positional arguments will result in error. c\tggjjD]c\}}|jtj k(rj |5|jtjk(sSj |etfd}|S)Nct|tz }|dkr|i|Std||| dDcgc]\}}dj||}}}dj|}t j d|d dt |jt j|di|Scc}}w)Nrz{}={}, zPass z as keyword args. From version z> passing these as positional arguments will result in an error) lenzipformatjoinwarningswarn FutureWarningupdate parameters) argskwargs extra_argsnameargargs_msgall_argsf kwonly_argssigrs ^/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sklearn/utils/validation.pyinner_fzU_deprecate_positional_args.._inner_deprecate_positional_args..inner_f;sTS]2JQ$)&)) "%[*%=tZKL?Q!RD#tS)Hyy*H MMH:%Di ..   MM#cnnd3 4;v; sB:) r r(itemskindrPOSITIONAL_OR_KEYWORDappend KEYWORD_ONLYr)r0r,paramr4r/r1r2rs` @@@r3 _inner_deprecate_positional_argszD_deprecate_positional_args.._inner_deprecate_positional_args0sl >>//1 )KD%zzY<<<%y555""4(  ) q   ,r)funcrr;s ` r3_deprecate_positional_argsr>"s""H /55 ++r<Fct|\}}tdry|j|}|sH|jt jdk(r&|s$t |j r td|j|jdsyt jd5|j|j|}dddryt||||||y#1swYxYw) z-Like assert_all_finite, but only for ndarray. assume_finiteNobjectzInput contains NaNz real floatingzcomplex floatingignore)over)xp allow_nan msg_dtypeestimator_name input_name) r _get_configasarraydtypenprany ValueErrorisdtypeerrstateisfinitesum_assert_all_finite_element_wise)XrGrHrIrJrF is_array_apifirst_pass_isfinites r3_assert_all_finiterYZs %Q'B }_% 1 A AGGrxx'99) q ! % % '12 2 ::aggD E ( #5 kk"&&)45# %  55s +!C))C2)rHrIrJch|tuxrN|jjxr6|jjtj tj hv}|rGt|jd|}|rdn|tjk(}|tjk(} nD|j|j|} |rdn|j|j|}| s|rI|rd} n||n |j}d|} |r|dznd} d| d | d } |r|d k(r |r | d |d z } t| y)N)rGFNaNz"infinity or a value too large for  r?zInput z contains .rV aX does not accept missing values encoded as NaN natively. For supervised learning, you might want to consider sklearn.ensemble.HistGradientBoostingClassifier and Regressor which accept missing values encoded as NaNs natively. Alternatively, it is possible to preprocess the data, for instance by using an imputer transformer in a pipeline or drop samples with missing values. See https://scikit-learn.org/stable/modules/impute.html You can find a list of all estimators that handle NaN values at the following page: https://scikit-learn.org/stable/modules/impute.html#estimators-that-handle-nan-values)rNdata contiguousrMtypefloat32float64rreshaperhas_nan has_infiniterOisinfisnanrP) rVrFrGrHrIrJ use_cythonout has_nan_errorhas_inftype_errpadded_input_namemsg_errs r3rUrUs5 bSQVV&&S177<>> from sklearn.utils import assert_all_finite >>> import numpy as np >>> array = np.array([1, np.inf, np.nan, 4]) >>> try: ... assert_all_finite(array) ... print("Test passed: Array contains only finite values.") ... except ValueError: ... print("Test failed: Array contains non-finite values.") Test failed: Array contains non-finite values. rqN)rYspissparser`)rVrGrIrJs r3assert_all_finiterus)L++a.a% r<T deprecated)copyforce_all_finiteensure_all_finitec t||}t|tjs/t|tjs6t j |s!t|gdtj||dSt j |r@|jtjtjfvr|r|jS|S|jtjtjfvr*|r&|j|jdrdSdS|S|jjdvr*|jjdkrtj}ntj}|j|S) aConvert an array-like to an array of floats. The new dtype will be np.float32 or np.float64, depending on the original type. The function can create a copy or modify the argument depending on the argument copy. Parameters ---------- X : {array-like, sparse matrix} The input data. copy : bool, default=True If True, a copy of X will be created. If False, a copy may still be returned if X's dtype is not a floating point type. force_all_finite : bool or 'allow-nan', default=True Whether to raise an error on np.inf, np.nan, pd.NA in X. The possibilities are: - True: Force all values of X to be finite. - False: accepts np.inf, np.nan, pd.NA in X. - 'allow-nan': accepts only np.nan and pd.NA values in X. Values cannot be infinite. .. versionadded:: 0.20 ``force_all_finite`` accepts the string ``'allow-nan'``. .. versionchanged:: 0.23 Accepts `pd.NA` and converts it into `np.nan` .. deprecated:: 1.6 `force_all_finite` was renamed to `ensure_all_finite` and will be removed in 1.8. ensure_all_finite : bool or 'allow-nan', default=True Whether to raise an error on np.inf, np.nan, pd.NA in X. The possibilities are: - True: Force all values of X to be finite. - False: accepts np.inf, np.nan, pd.NA in X. - 'allow-nan': accepts only np.nan and pd.NA values in X. Values cannot be infinite. .. versionadded:: 1.6 `force_all_finite` was renamed to `ensure_all_finite`. Returns ------- XT : {ndarray, sparse matrix} An array of type float. Examples -------- >>> from sklearn.utils import as_float_array >>> import numpy as np >>> array = np.array([0, 0, 1, 2, 2], dtype=np.int64) >>> as_float_array(array) array([0., 0., 1., 2., 2.]) csrcsccooF) accept_sparserMrwry ensure_2d F_CONTIGUOUSFCuib)r isinstancerNmatrixndarrayrsrt check_arrayrdrMrcrwflagsr6itemsizeastype)rVrwrxry return_dtypes r3as_float_arrayrs|44DFWX!RYY q"** %bkk!n /**/    QAGG BJJ'??qvvx&Q& RZZ, ,BFqvvQWW^4c>M#>MAM 77<<5 QWW%5%5%:::L::Lxx %%r<c~tj|ryt|dxst|dxs t|dS)z(Returns whether the input is array-like.F__len__shape __array__)rsrthasattr)xs r3 _is_arrayliker1s5 {{1~ 1i RGAw$7 R71k;RRr<cHt|xrtj| S)z3Return True if array is array-like and not a scalar)rrNisscalararrays r3_is_arraylike_not_scalarr9s   : E(:$::r<c6t| xr t|dS)aUse interchange protocol for non-pandas dataframes that follow the protocol. Note: at this point we chose not to use the interchange API on pandas dataframe to ensure strict behavioral backward compatibility with older versions of scikit-learn. __dataframe__) _is_pandas_dfr)rVs r3_use_interchange_protocolr>sQ  ?GA$??r<ct|}|jdk(r |j}n|jd|j}d|}t|ds8t|ds,t|ds t |t j |}t|drZt|jdrt|jdkr|d|jz }t ||jdS|d }t|tttfr&|d t|jz }t | t|S#t$r}t ||d }~wwxYw) a Return the number of features in an array-like X. This helper function tries hard to avoid to materialize an array version of X unless necessary. For instance, if X is a list of lists, this function will return the length of the first element, assuming that subsequent elements are all lists of the same length without checking. Parameters ---------- X : array-like array-like to get the number of features. Returns ------- features : int Number of features builtinsr^z5Unable to find the number of features from X of type rrrrz with shape rz where the samples are of type N)rb __module__ __qualname__r TypeErrorrNrLrr rstrbytesdict Exception)rVtype_ type_namemessage first_sampleerrs r3 _num_featuresrHsP$ GE :%&& ''(%*<*<)=> Ei[QG 1i G)<q+&G$ $ JJqMq'qww *c!''la.? aggY/ /GG$ $wwqzQ4L,eT 234T,5G5T5T4UVV  *<  * c)*s9 E E EEcdt|z}t|dr t|jr t |t |r|j jSt|ds9t|ds-t|drtj|}n t |t|dri|j]t|jdk(rt d|d t|jdtjr|jdS t|S#t$r}t ||d}~wwxYw) z)Return number of samples in array-like x.z'Expected sequence or array-like, got %sfitrrrNrzTInput should have at least 1 dimension i.e. satisfy `len(x.shape) > 0`, got scalar `z ` instead.)rbrcallablerrrrnum_rowsrNrLrr rnumbersIntegral)rr type_errors r3 _num_samplesr}s7$q'AGq%Xaee_   # ))++ 1i G)< 1k " 1 AG$ $q'qww2 qww<1 334%zC  aggaj'"2"2 3771: 11v 1 j01s D** E3 D??Ec|t|trtj|d}|St |dst dj ||S)amCheck that ``memory`` is joblib.Memory-like. joblib.Memory-like means that ``memory`` can be converted into a joblib.Memory instance (typically a str denoting the ``location``) or has the same interface (has a ``cache`` method). Parameters ---------- memory : None, str or object with the joblib.Memory interface - If string, the location where to create the `joblib.Memory` interface. - If None, no caching is done and the Memory object is completely transparent. Returns ------- memory : object with the joblib.Memory interface A correct joblib.Memory object. Raises ------ ValueError If ``memory`` is not joblib.Memory-like. Examples -------- >>> from sklearn.utils.validation import check_memory >>> check_memory("caching_dir") Memory(location=caching_dir/joblib) r)locationverbosecachezg'memory' should be None, a string or have the same interface as joblib.Memory. Got memory='{}' instead.)rrjoblibMemoryrrPr")memorys r3 check_memoryrsW:~FC0: M VW % ((.v  Mr<c |Dcgc]}|t|}}tt|dkDr%td|Dcgc] }t |c}zycc}wcc}w)aCheck that all arrays have consistent first dimensions. Checks whether all objects in arrays have the same shape or length. Parameters ---------- *arrays : list or tuple of input objects. Objects that will be checked for consistent length. Examples -------- >>> from sklearn.utils.validation import check_consistent_length >>> a = [1, 2, 3] >>> b = [2, 3, 4] >>> check_consistent_length(a, b) Nrz>Found input variables with inconsistent numbers of samples: %r)rr setrPint)arraysrVlengthsls r3check_consistent_lengthrsg")/@1!-|A@G@ 3w<1 L&'!s1v' (  A(sA AA ctj|r|jSt|ds t|dr|S||St j |S)aEnsure iterable supports indexing or convert to an indexable variant. Convert sparse matrices to csr and other non-indexable iterable to arrays. Let `None` and indexable objects (e.g. pandas dataframes) pass unchanged. Parameters ---------- iterable : {list, dataframe, ndarray, sparse matrix} or None Object to be converted to an indexable iterable. __getitem__iloc)rsrttocsrrrNr)iterables r3_make_indexablersO {{8~~ = )WXv-F   88H r<cP|Dcgc] }t|}}t||Scc}w)aMake arrays indexable for cross-validation. Checks consistent length, passes through None, and ensures that everything can be indexed by converting sparse matrices to csr and converting non-iterable objects to arrays. Parameters ---------- *iterables : {lists, dataframes, ndarrays, sparse matrices} List of objects to ensure sliceability. Returns ------- result : list of {ndarray, sparse matrix, dataframe} or None Returns a list containing indexable arrays (i.e. NumPy array, sparse matrix, or dataframe) or `None`. Examples -------- >>> from sklearn.utils import indexable >>> from scipy.sparse import csr_matrix >>> import numpy as np >>> iterables = [ ... [1, 2, 3], np.array([2, 3, 4]), None, csr_matrix([[5], [6], [7]]) ... ] >>> indexable(*iterables) [[1, 2, 3], array([2, 3, 4]), None, <...Sparse...dtype 'int64'...shape (3, 1)>] )rr) iterablesrVresults r3 indexablers.<+4 4Qoa 4F 4V$ M5s#c| |j}d}t|j} t|tr|g}t |||dur|rd|znd} t d| dt|ttfr>t|dk(r td|j|vr*|j|d}d}n|durtd |d ||jk7r|j|}n|r|s|j}|rNt|d s&t!j"d |jd dnt%|j&|dk(|||r|d} t)|| | |S)aConvert a sparse container to a given format. Checks the sparse format of `sparse_container` and converts if necessary. Parameters ---------- sparse_container : sparse matrix or array Input to validate and convert. accept_sparse : str, bool or list/tuple of str String[s] representing allowed sparse matrix formats ('csc', 'csr', 'coo', 'dok', 'bsr', 'lil', 'dia'). If the input is sparse but not in the allowed format, it will be converted to the first listed format. True allows the input to be any format. False means that a sparse matrix input will raise an error. dtype : str, type or None Data type of result. If None, the dtype of the input is preserved. copy : bool Whether a forced copy will be triggered. If copy=False, a copy might be triggered by a conversion. ensure_all_finite : bool or 'allow-nan' Whether to raise an error on np.inf, np.nan, pd.NA in X. The possibilities are: - True: Force all values of X to be finite. - False: accepts np.inf, np.nan, pd.NA in X. - 'allow-nan': accepts only np.nan and pd.NA values in X. Values cannot be infinite. .. versionadded:: 0.20 ``ensure_all_finite`` accepts the string ``'allow-nan'``. .. versionchanged:: 0.23 Accepts `pd.NA` and converts it into `np.nan` estimator_name : str, default=None The estimator name, used to construct the error message. input_name : str, default="" The data name used to construct the error message. In particular if `input_name` is "X" and the data has NaN values and allow_nan is False, the error message will link to the imputer documentation. Returns ------- sparse_container_converted : sparse matrix or array Sparse container (matrix/array) that is ensured to have an allowed type. Fz for r?zSparse data was passedzQ, but dense data is required. Use '.toarray()' to convert to a dense numpy array.rz]When providing 'accept_sparse' as a tuple or list, it must contain at least one string value.TzfParameter 'accept_sparse' should be a string, boolean or list of strings. You provided 'accept_sparse=z'.r`z Can't check z sparse matrix for nan or inf.r  stacklevel allow-nanrq)rMrb__name__rr_check_large_sparserlisttupler rPr"asformatrrwrr$r%rYr`r) sparse_containerrrMrwryaccept_large_sparserIrJchanged_formatsparse_container_type_name padded_inputrequested_sparse_formats r3_ensure_sparse_formatrs~ } &&N!%&6!7!@!@-%& (*=>/9w+r $\N3B B   MD%= 1 }  "*   " "- 7/88q9IJ !N d " ,,9?" >    &&&+2259 n+002'0 MM/6677UV   %%+{:-%  "/"2# 8:Q  r<ct|drX|jKt|jdr4|jjdk(rtdj |yyyy)NrMr6cComplex data not supported {} )rrMr6rPr"rs r3_ensure_no_complex_datarsaw KK # EKK ( KK   #;BB5IJJ $ ) $ r<cX|(t|tr|S|jjSyN)rr __class__r) estimators r3_check_estimator_namers- i % &&// / r<cddlm}ddlm}m}m}||ryt ||ry ddlm}t ||s||sy||ry||ryy#t$rYywxYw)zDReturn True if pandas extension pd_dtype need to be converted early.r SparseDtype) is_bool_dtypeis_float_dtypeis_integer_dtypeTF)is_extension_array_dtype) pandasrpandas.api.typesrrrrr ImportError)pd_dtyperrrrrs r3$_pandas_dtype_needs_early_conversionrs}# X(K(=(K(0H0R  ! ( #  sA A"!A"cJt|dxrt|jdS)NrMna_value)rrMrs r3_is_extension_array_dtypers 5' " Gwu{{J'GGr<numeric)rrMorderrwforce_writeablerxryensure_non_negativerallow_ndensure_min_samplesensure_min_featuresrrJc &t||}t|tjr t dt |\}}|}t|t xr|dk(}t|dd}|st|dsd}d}d}d}t|drt|jdrtt5d d l m &&fd }t|d s>|jj|jrt!j"d dddt%|j}td|D}t'd|Drtj(|}n|rtd|Dr}t*}nvt-|s t|dr_t|drSt/|}t1|j2}t|j2tj2r |j2}nd}|r,|(t|dr|j4dk(r |j6}nd}t|t$t8fr|||vrd}n|d }|r||n|}|j;|}d}|dvrt=d|d| t?|rtj2|}tA|}|d|znd}t|d r|jBdkDrtt5d d l m &&fd}|jj|j'r|jDjG}|j2tj2dk(rPtI|jDcgc]}|jJjLc}}tO|dkDr t=ddddtQjR|rJtU|tW||||||||}| r|jBdkrt=d|jXdt!jZ5 t!j\d t^|a|ja|d!rOtc|||"}|ja|j2d#rte|d|||$|j;||d%}ntc||||&}dddtU|| r\|jBd k(rt=d(jg||jBdk(r$|d)|d*}t=|d+|d}t=||r9t|j2dr#|j2j4d,vr t=d-| s+|jBd.k\rt=d/|jBd0|d1|rte||||d2k(3|rBt?|r'tjh||r!tc|||d4|5}ntc|||d4|5}| d kDr,tk|} | | krt=d6| |jX| |fz| d kDr?|jBdk(r0|jXd}!|!| krt=d7|!|jX| |fz| r|}"|r|"d8|z }"tm||"|rtQjR|sd9d:ini}#tQjR|r |jnn|}$t|$d;d}%t|%daInput validation on an array, list, sparse matrix or similar. By default, the input is checked to be a non-empty 2D array containing only finite values. If the dtype of the array is object, attempt converting to float, raising on failure. Parameters ---------- array : object Input object to check / convert. accept_sparse : str, bool or list/tuple of str, default=False String[s] representing allowed sparse matrix formats, such as 'csc', 'csr', etc. If the input is sparse but not in the allowed format, it will be converted to the first listed format. True allows the input to be any format. False means that a sparse matrix input will raise an error. accept_large_sparse : bool, default=True If a CSR, CSC, COO or BSR sparse matrix is supplied and accepted by accept_sparse, accept_large_sparse=False will cause it to be accepted only if its indices are stored with a 32-bit dtype. .. versionadded:: 0.20 dtype : 'numeric', type, list of type or None, default='numeric' Data type of result. If None, the dtype of the input is preserved. If "numeric", dtype is preserved unless array.dtype is object. If dtype is a list of types, conversion on the first type is only performed if the dtype of the input is not in the list. order : {'F', 'C'} or None, default=None Whether an array will be forced to be fortran or c-style. When order is None (default), then if copy=False, nothing is ensured about the memory layout of the output array; otherwise (copy=True) the memory layout of the returned array is kept as close as possible to the original array. copy : bool, default=False Whether a forced copy will be triggered. If copy=False, a copy might be triggered by a conversion. force_writeable : bool, default=False Whether to force the output array to be writeable. If True, the returned array is guaranteed to be writeable, which may require a copy. Otherwise the writeability of the input array is preserved. .. versionadded:: 1.6 force_all_finite : bool or 'allow-nan', default=True Whether to raise an error on np.inf, np.nan, pd.NA in array. The possibilities are: - True: Force all values of array to be finite. - False: accepts np.inf, np.nan, pd.NA in array. - 'allow-nan': accepts only np.nan and pd.NA values in array. Values cannot be infinite. .. versionadded:: 0.20 ``force_all_finite`` accepts the string ``'allow-nan'``. .. versionchanged:: 0.23 Accepts `pd.NA` and converts it into `np.nan` .. deprecated:: 1.6 `force_all_finite` was renamed to `ensure_all_finite` and will be removed in 1.8. ensure_all_finite : bool or 'allow-nan', default=True Whether to raise an error on np.inf, np.nan, pd.NA in array. The possibilities are: - True: Force all values of array to be finite. - False: accepts np.inf, np.nan, pd.NA in array. - 'allow-nan': accepts only np.nan and pd.NA values in array. Values cannot be infinite. .. versionadded:: 1.6 `force_all_finite` was renamed to `ensure_all_finite`. ensure_non_negative : bool, default=False Make sure the array has only non-negative values. If True, an array that contains negative values will raise a ValueError. .. versionadded:: 1.6 ensure_2d : bool, default=True Whether to raise a value error if array is not 2D. allow_nd : bool, default=False Whether to allow array.ndim > 2. ensure_min_samples : int, default=1 Make sure that the array has a minimum number of samples in its first axis (rows for a 2D array). Setting to 0 disables this check. ensure_min_features : int, default=1 Make sure that the 2D array has some minimum number of features (columns). The default value of 1 rejects empty datasets. This check is only enforced when the input data has effectively 2 dimensions or is originally 1D and ``ensure_2d`` is True. Setting to 0 disables this check. estimator : str or estimator instance, default=None If passed, include the name of the estimator in warning messages. input_name : str, default="" The data name used to construct the error message. In particular if `input_name` is "X" and the data has NaN values and allow_nan is False, the error message will link to the imputer documentation. .. versionadded:: 1.1.0 Returns ------- array_converted : object The converted and validated array. Examples -------- >>> from sklearn.utils.validation import check_array >>> X = [[1, 2, 3], [4, 5, 6]] >>> X_checked = check_array(X) >>> X_checked array([[1, 2, 3], [4, 5, 6]]) znp.matrix is not supported. Please convert to a numpy array with np.asarray. For more information see: https://numpy.org/doc/stable/reference/generated/numpy.matrix.htmlrrMNr6Fdtypesrrrct|SrrrMrs r3 is_sparsezcheck_array..is_sparse!%55r<sparsezWpandas.DataFrame with sparse columns found.It will be converted to a dense numpy array.c32K|]}t|ywr)r).0is r3 zcheck_array..s) 89 0 3) c3PK|]}t|tj ywr)rrNrM)r dtype_iters r3r zcheck_array..sNJz*bhh/Ns$&c3.K|] }|tk(ywr)rB)rds r3r zcheck_array..s/QV /QsrO)TFrz7ensure_all_finite should be a bool or 'allow-nan'. Got z instead.z by %sr?rct|Srrrs r3rzcheck_array..is_sparserr<rBzPandas DataFrame with mixed sparse extension arrays generated a sparse matrix with object dtype which can not be converted to a scipy sparse matrix.Sparse extension arrays should all have the same numeric type.)rrMrwryrrIrJr z(Expected 2D input, got input with shape z. Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.errorintegral)rrFrC)rGrHrIrJ)rw)rrMrFrzExpected 2D array, got scalar array instead: array={}. Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.z+Expected a 2-dimensional container but got zy instead. Pass a DataFrame containing a single row (i.e. single sample) or a single column (i.e. single feature) instead.z/Expected 2D array, got 1D array instead: array=USVzvdtype='numeric' is not compatible with arrays of bytes/strings.Convert your data to numeric values explicitly instead.zFound array with dim z, while dim <= 2 is requiredr^r)rJrIrGT)rMrrwrFzMFound array with %d sample(s) (shape=%s) while a minimum of %d is required%s.zNFound array with %d feature(s) (shape=%s) while a minimum of %d is required%s.z in rKr writeabler)$E:)F0UrJEzz%++/TU*!&+&++9'1 IIeUI?E/U%TVWE% '8 & zzQ 67=fUm zzQ!-EnEUV##!o% K5'R:: !o% WU[[&9ekk>N>NRW>WJ EJJ!O' |4..5Ya9   %-+{:   "2&&&uj9/U%drE ,e$2A ' ) )0ekk+=wGH  Q5::?[[^ + +2u{{,?IJ    d>*+ +D5$'-/KK,>wnB #%;;u#5UZZ5  GT2uk40'z26 26J$$. L# 1[1 LQ  p)V  @" ' 6==eD&' '' ' 'P"6&EJJ55E L 6si.A[  B[2 [- * [2\+B [?9\8 [*-[22[<? \(\##\((\++\58]]c|s\dg}|jdk(rddg}n|jdvrddg}ny|D]+}t||j}||vstd |d yy) zGRaise a ValueError if X has 64bit indices and accept_large_sparse=Falseint32r~colrow)r|r}bsrindicesindptrNzCOnly sparse matrices with 32-bit integer indices are accepted. Got z indices. Please do report a minimal reproducer on scikit-learn issue tracker so that support for your use-case can be studied by maintainers. See: https://scikit-learn.org/dev/developers/minimal_reproducer.html)r"rrMrP)rVrsupported_indices index_keyskeyindices_datatypes r3rrs $I 88u J XX. .#X.J  C&q#44 '88 ,-.WW  r<)rrMrrwrrxryrr multi_outputrr y_numericrc||d}n t|}t|dt|| } t|||||||| | | | ||d}t || ||}t ||||fS)aoInput validation for standard estimators. Checks X and y for consistent length, enforces X to be 2D and y 1D. By default, X is checked to be non-empty and containing only finite values. Standard input checks are also applied to y, such as checking that y does not have np.nan or np.inf targets. For multi-label y, set multi_output=True to allow 2D and sparse y. If the dtype of X is object, attempt converting to float, raising on failure. Parameters ---------- X : {ndarray, list, sparse matrix} Input data. y : {ndarray, list, sparse matrix} Labels. accept_sparse : str, bool or list of str, default=False String[s] representing allowed sparse matrix formats, such as 'csc', 'csr', etc. If the input is sparse but not in the allowed format, it will be converted to the first listed format. True allows the input to be any format. False means that a sparse matrix input will raise an error. accept_large_sparse : bool, default=True If a CSR, CSC, COO or BSR sparse matrix is supplied and accepted by accept_sparse, accept_large_sparse will cause it to be accepted only if its indices are stored with a 32-bit dtype. .. versionadded:: 0.20 dtype : 'numeric', type, list of type or None, default='numeric' Data type of result. If None, the dtype of the input is preserved. If "numeric", dtype is preserved unless array.dtype is object. If dtype is a list of types, conversion on the first type is only performed if the dtype of the input is not in the list. order : {'F', 'C'}, default=None Whether an array will be forced to be fortran or c-style. If `None`, then the input data's order is preserved when possible. copy : bool, default=False Whether a forced copy will be triggered. If copy=False, a copy might be triggered by a conversion. force_writeable : bool, default=False Whether to force the output array to be writeable. If True, the returned array is guaranteed to be writeable, which may require a copy. Otherwise the writeability of the input array is preserved. .. versionadded:: 1.6 force_all_finite : bool or 'allow-nan', default=True Whether to raise an error on np.inf, np.nan, pd.NA in array. This parameter does not influence whether y can have np.inf, np.nan, pd.NA values. The possibilities are: - True: Force all values of X to be finite. - False: accepts np.inf, np.nan, pd.NA in X. - 'allow-nan': accepts only np.nan or pd.NA values in X. Values cannot be infinite. .. versionadded:: 0.20 ``force_all_finite`` accepts the string ``'allow-nan'``. .. versionchanged:: 0.23 Accepts `pd.NA` and converts it into `np.nan` .. deprecated:: 1.6 `force_all_finite` was renamed to `ensure_all_finite` and will be removed in 1.8. ensure_all_finite : bool or 'allow-nan', default=True Whether to raise an error on np.inf, np.nan, pd.NA in array. This parameter does not influence whether y can have np.inf, np.nan, pd.NA values. The possibilities are: - True: Force all values of X to be finite. - False: accepts np.inf, np.nan, pd.NA in X. - 'allow-nan': accepts only np.nan or pd.NA values in X. Values cannot be infinite. .. versionadded:: 1.6 `force_all_finite` was renamed to `ensure_all_finite`. ensure_2d : bool, default=True Whether to raise a value error if X is not 2D. allow_nd : bool, default=False Whether to allow X.ndim > 2. multi_output : bool, default=False Whether to allow 2D y (array or sparse matrix). If false, y will be validated as a vector. y cannot have np.nan or np.inf values if multi_output=True. ensure_min_samples : int, default=1 Make sure that X has a minimum number of samples in its first axis (rows for a 2D array). ensure_min_features : int, default=1 Make sure that the 2D array has some minimum number of features (columns). The default value of 1 rejects empty datasets. This check is only enforced when X has effectively 2 dimensions or is originally 1D and ``ensure_2d`` is True. Setting to 0 disables this check. y_numeric : bool, default=False Whether to ensure that y has a numeric type. If dtype of y is object, it is converted to float64. Should only be used for regression algorithms. estimator : str or estimator instance, default=None If passed, include the name of the estimator in warning messages. Returns ------- X_converted : object The converted and validated X. y_converted : object The converted and validated y. Examples -------- >>> from sklearn.utils.validation import check_X_y >>> X = [[1, 2], [3, 4], [5, 6]] >>> y = [1, 2, 3] >>> X, y = check_X_y(X, y) >>> X array([[1, 2], [3, 4], [5, 6]]) >>> y array([1, 2, 3]) rz2 requires y to be passed, but the target y is NonerV) rrrMrrwrryrrrrrrJ)r@rAr)rrPrr_check_yr)rVyrrrMrrwrrxryrrr@rrrArrIs r3 check_X_yrEsx y  (N29=NP Q  44DFWX #/ '+-/ A" iXAAq! a4Kr<c 2|rt|ddddd|}n1t|}t|d}t|d|t ||rNt |j d r8|j jd k(r|jtj}|S) z4Isolated part of check_X_y dedicated to y validationr|TFNrD)rryrrMrJr)r%)rJrIr6r) rr column_or_1drYrrrMr6rrNrd)rDr@rArrIs r3rCrCps  " /y9  &1^L"WQWWf-!'',,#2E HHRZZ  Hr<)rMr%devicect|\}}t|d|ddd}|j}t|dk(rt |j |dd||St|d k(rE|ddk(r=|rt jd td t |j |dd||Std j|) aRavel column or 1d numpy array, else raises an error. Parameters ---------- y : array-like Input data. dtype : data-type, default=None Data type for `y`. .. versionadded:: 1.2 warn : bool, default=False To control display of warnings. device : device, default=None `device` object. See the :ref:`Array API User Guide ` for more details. .. versionadded:: 1.6 Returns ------- y : ndarray Output data. Raises ------ ValueError If `y` is not a 1D array or a 2D array with a single row or column. Examples -------- >>> from sklearn.utils.validation import column_or_1d >>> column_or_1d([1, 1]) array([1, 1]) FrDr)rrMrJryrr)r[r)rrFrHr zA column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().rz9y should be a 1d array, got an array of shape {} instead.) rrrr rrer$r%r rPr")rDrMr%rHrF_rs r3rGrGsL ! EB   A GGE 5zQ" JJq% 6   5zQ58q=  MM@& # JJq% 6   CJJ5Q r<cL||tjur$tjjjSt |t j rtjj|St |tjjr|Std|z)aTurn seed into a np.random.RandomState instance. Parameters ---------- seed : None, int or instance of RandomState If seed is None, return the RandomState singleton used by np.random. If seed is an int, return a new RandomState instance seeded with seed. If seed is already a RandomState instance, return it. Otherwise raise ValueError. Returns ------- :class:`numpy:numpy.random.RandomState` The random state object based on `seed` parameter. Examples -------- >>> from sklearn.utils.validation import check_random_state >>> check_random_state(42) RandomState(MT19937) at 0x... z=%r cannot be used to seed a numpy.random.RandomState instance) rNrandommtrand_randrrr RandomStaterP)seeds r3check_random_staterQs}, |tryy(yy%%%$(()yy$$T**$ --. G$N r<c`t|dxr!|t|jjvS)a(Check whether the estimator's fit method supports the given parameter. Parameters ---------- estimator : object An estimator to inspect. parameter : str The searched parameter. Returns ------- is_parameter : bool Whether the parameter was found to be a named parameter of the estimator's fit method. Examples -------- >>> from sklearn.svm import SVC >>> from sklearn.utils.validation import has_fit_parameter >>> has_fit_parameter(SVC(), "sample_weight") True r)rr rr()r parameters r3has_fit_parameterrTs,:  5!Vi9Y]]3K3V3V&V r<绽|=)tol raise_warningraise_exceptionc|jdk7s|jd|jdk7r$tdj|jt j |rY||j z }|jdvr|j}tjt|j|k}n"tj||j |}|s|r td|rtjdd t j |r2d |jz}td ||j zz|}|Sd ||j zz}|S) aMake sure that array is 2D, square and symmetric. If the array is not symmetric, then a symmetrized version is returned. Optionally, a warning or exception is raised if the matrix is not symmetric. Parameters ---------- array : {ndarray, sparse matrix} Input object to check / convert. Must be two-dimensional and square, otherwise a ValueError will be raised. tol : float, default=1e-10 Absolute tolerance for equivalence of arrays. Default = 1E-10. raise_warning : bool, default=True If True then raise a warning if conversion is required. raise_exception : bool, default=False If True then raise an exception if array is not symmetric. Returns ------- array_sym : {ndarray, sparse matrix} Symmetrized version of the input array, i.e. the average of array and array.transpose(). If sparse, then duplicate entries are first summed and zeros are eliminated. Examples -------- >>> import numpy as np >>> from sklearn.utils.validation import check_symmetric >>> symmetric_array = np.array([[0, 1, 2], [1, 0, 1], [2, 1, 0]]) >>> check_symmetric(symmetric_array) array([[0, 1, 2], [1, 0, 1], [2, 1, 0]]) >>> from scipy.sparse import csr_matrix >>> sparse_symmetric_array = csr_matrix(symmetric_array) >>> check_symmetric(sparse_symmetric_array) r rrz3array must be 2-dimensional and square. shape = {0}r{)atolzArray must be symmetriczYArray is not symmetric, and will be converted to symmetric by average with its transpose.rtog?)rrrPr"rsrtTrrNrabsr`allcloser$r%r)rrVrWrXdiff symmetric conversions r3check_symmetricrbs0X  aU[[^u{{1~= A H H U   {{5uww ;;3 3::C/0 KKuwwS9  67 7  MMB   ;;u  ,J@GC5577?3Z@BE L5577?+E Lr<c X|9t|ttfs|g}||Dcgc]}t||c}St|dr|j St |Dcgc](}|j ds|jdr'|*}}t|dkDScc}wcc}w)aDetermine if an estimator is fitted Parameters ---------- estimator : estimator instance Estimator instance for which the check is performed. attributes : str, list or tuple of str, default=None Attribute name(s) given as string or a list/tuple of strings Eg.: ``["coef_", "estimator_", ...], "coef_"`` If `None`, `estimator` is considered fitted if there exist an attribute that ends with a underscore and does not start with double underscore. all_or_any : callable, {all, any}, default=all Specify whether all or any of the given attributes must exist. Returns ------- fitted : bool Whether the estimator is fitted. __sklearn_is_fitted__rJ__r) rrrrrdvarsendswith startswithr )r attributes all_or_anyattrv fitted_attrss r3 _is_fittedrn`s0*tUm4$J K79d3KLLy12..00 ?ajjoall4>PL | q  L sB"%B'<B'B')r/rjct|rtdj||d}t|dstd|zt |}|j s|yt |||s#t|dt|jizy)a Perform is_fitted validation for estimator. Checks if the estimator is fitted by verifying the presence of fitted attributes (ending with a trailing underscore) and otherwise raises a :class:`~sklearn.exceptions.NotFittedError` with the given message. If an estimator does not set any attributes with a trailing underscore, it can define a ``__sklearn_is_fitted__`` method returning a boolean to specify if the estimator is fitted or not. See :ref:`sphx_glr_auto_examples_developing_estimators_sklearn_is_fitted.py` for an example on how to use the API. If no `attributes` are passed, this function will pass if an estimator is stateless. An estimator can indicate it's stateless by setting the `requires_fit` tag. See :ref:`estimator_tags` for more information. Note that the `requires_fit` tag is ignored if `attributes` are passed. Parameters ---------- estimator : estimator instance Estimator instance for which the check is performed. attributes : str, list or tuple of str, default=None Attribute name(s) given as string or a list/tuple of strings Eg.: ``["coef_", "estimator_", ...], "coef_"`` If `None`, `estimator` is considered fitted if there exist an attribute that ends with a underscore and does not start with double underscore. msg : str, default=None The default error message is, "This %(name)s instance is not fitted yet. Call 'fit' with appropriate arguments before using this estimator." For custom messages if "%(name)s" is present in the message string, it is substituted for the estimator name. Eg. : "Estimator, %(name)s, must be fitted before sparsifying". all_or_any : callable, {all, any}, default=all Specify whether all or any of the given attributes must exist. Raises ------ TypeError If the estimator is a class or not an estimator instance NotFittedError If the attributes are not found. Examples -------- >>> from sklearn.linear_model import LogisticRegression >>> from sklearn.utils.validation import check_is_fitted >>> from sklearn.exceptions import NotFittedError >>> lr = LogisticRegression() >>> try: ... check_is_fitted(lr) ... except NotFittedError as exc: ... print(f"Model is not fitted yet.") Model is not fitted yet. >>> lr.fit([[1, 2], [1, 3]], [1, 0]) LogisticRegression() >>> check_is_fitted(lr) z{} is a class, not an instance.NzlThis %(name)s instance is not fitted yet. Call 'fit' with appropriate arguments before using this estimator.rz %s is not an estimator instance.r,) rrr"rr requires_fitrnr rbr)rrir/rjtagss r3check_is_fittedrrsFy9@@KLL { A 9e $:iHII I D   !3 iZ 8SFDO,D,D#EEFF 9r<) estimator_r) delegatescfd}|S)aCheck if we can delegate a method to the underlying estimator. We check the `delegates` in the order they are passed. By default, we first check the fitted estimator if available, otherwise we check the unfitted estimator. Parameters ---------- attr : str Name of the attribute the delegate might or might not have. delegates: tuple of str, default=("estimator_", "estimator") A tuple of sub-estimator(s) to check if we can delegate the `attr` method. Returns ------- check : function Function to check if the delegate has the attribute. Raises ------ ValueError Raised when none of the delegates are present in the object. cD]I}t||st||}t|trt|dcSt|cSt dd)NrzNone of the delegates z are present in the class.)rrrrrP)selfdelegate delegatorrkrts r3checkz_estimator_has..checksj! 4HtX&#D(3 i2"9Q<66"9d33 41)t|\}}tj|rU|jdvr|j }|j j dk(rd}n,|j j}n|j|}|dkrtd|dy)z Check if there is any negative value in an array. Parameters ---------- X : {array-like, sparse matrix} Input data. whom : str Who passed X to this function. )lildokrz"Negative values in data passed to r^N) rrsrtr"rr`sizeminrP)rVr2rFrJX_mins r3r!r!s ! EB {{1~ 88~ % A 66;;! EFFJJLEq  qy=dV1EFFr<both)min_valmax_valinclude_boundariesc  d t||s`t|tr!dj fd|D}d|d}n |}t|d|dt |j dd }||vrt d |d |d||d k(r t d ||dk(r t d|dvrtjntj} |&| ||rt |d|d|dvrdndd|d|dvrtjntj} |&| ||rt |d|d|dvrdndd|d|S)aValidate scalar parameters type and value. Parameters ---------- x : object The scalar parameter to validate. name : str The name of the parameter to be printed in error messages. target_type : type or tuple Acceptable data types for the parameter. min_val : float or int, default=None The minimum valid value the parameter can take. If None (default) it is implied that the parameter does not have a lower bound. max_val : float or int, default=None The maximum valid value the parameter can take. If None (default) it is implied that the parameter does not have an upper bound. include_boundaries : {"left", "right", "both", "neither"}, default="both" Whether the interval defined by `min_val` and `max_val` should include the boundaries. Possible choices are: - `"left"`: only `min_val` is included in the valid interval. It is equivalent to the interval `[ min_val, max_val )`. - `"right"`: only `max_val` is included in the valid interval. It is equivalent to the interval `( min_val, max_val ]`. - `"both"`: `min_val` and `max_val` are included in the valid interval. It is equivalent to the interval `[ min_val, max_val ]`. - `"neither"`: neither `min_val` nor `max_val` are included in the valid interval. It is equivalent to the interval `( min_val, max_val )`. Returns ------- x : numbers.Number The validated number. Raises ------ TypeError If the parameter's type does not match the desired type. ValueError If the parameter's value violates the given bounds. If `min_val`, `max_val` and `include_boundaries` are inconsistent. Examples -------- >>> from sklearn.utils.validation import check_scalar >>> check_scalar(10, "x", int, min_val=1, max_val=20) 10 c|j}|j}|dk(r|S|tjk(ry|tjk(ry|d|S)z)Convert type into humman readable string.rfloatrr^)rrrRealr)tmodulequalnames r3rzcheck_scalar..type_namecsR>> Z O ',,  '"" "8*%%r<rc3.K|] }|ywrr)rrrs r3r zcheck_scalar..qs!D1)A,!Ds{}z must be an instance of z, not r^)leftrightrneitherz(Unknown value for `include_boundaries`: z. Possible values are: rzU`include_boundaries`='right' without specifying explicitly `max_val` is inconsistent.rzT`include_boundaries`='left' without specifying explicitly `min_val` is inconsistent.)rrz == z , must be z>=>r])rrz<=<) rrr#rrbrrPoperatorltlegtge) rr, target_typerrr types_strtarget_type_strexpected_include_boundariescomparison_operatorrs @r3 check_scalarr#s@ & a % k5 ) !D !DDI "9+R0O' 4Of,_,=>Q$$%Q (  #G!<<67I6LM$$?#@ C  -8   -7   *-== 8;;21g>fD*.>>CH'RS U  *->> HKK21g>fD*.??SI7)ST V  Hr<ctj|}|jtjk(}d}|rdnd}|rdnd}|rdnd}tj|j stj tj|j}tj tj|j}|||zkDrtd||z z|r tjd||z zttj|}|j} | d krtd | z|j} | | | zkr| | krtd | | z z| d kr+|r!tjd | | z ztd ||d k<d |k||| zkz} | jr'|r tjd d|z ztd || <|S)aCheck the eigenvalues of a positive semidefinite (PSD) matrix. Checks the provided array of PSD matrix eigenvalues for numerical or conditioning issues and returns a fixed validated version. This method should typically be used if the PSD matrix is user-provided (e.g. a Gram matrix) or computed using a user-provided dissimilarity metric (e.g. kernel function), or if the decomposition process uses approximation methods (randomized SVD, etc.). It checks for three things: - that there are no significant imaginary parts in eigenvalues (more than 1e-5 times the maximum real part). If this check fails, it raises a ``ValueError``. Otherwise all non-significant imaginary parts that may remain are set to zero. This operation is traced with a ``PositiveSpectrumWarning`` when ``enable_warnings=True``. - that eigenvalues are not all negative. If this check fails, it raises a ``ValueError`` - that there are no significant negative eigenvalues with absolute value more than 1e-10 (1e-6) and more than 1e-5 (5e-3) times the largest positive eigenvalue in double (simple) precision. If this check fails, it raises a ``ValueError``. Otherwise all negative eigenvalues that may remain are set to zero. This operation is traced with a ``PositiveSpectrumWarning`` when ``enable_warnings=True``. Finally, all the positive eigenvalues that are too small (with a value smaller than the maximum eigenvalue multiplied by 1e-12 (2e-7)) are set to zero. This operation is traced with a ``PositiveSpectrumWarning`` when ``enable_warnings=True``. Parameters ---------- lambdas : array-like of shape (n_eigenvalues,) Array of eigenvalues to check / fix. enable_warnings : bool, default=False When this is set to ``True``, a ``PositiveSpectrumWarning`` will be raised when there are imaginary parts, negative eigenvalues, or extremely small non-zero eigenvalues. Otherwise no warning will be raised. In both cases, imaginary parts, negative eigenvalues, and extremely small non-zero eigenvalues will be set to zero. Returns ------- lambdas_fixed : ndarray of shape (n_eigenvalues,) A fixed validated copy of the array of eigenvalues. Examples -------- >>> from sklearn.utils.validation import _check_psd_eigenvalues >>> _check_psd_eigenvalues([1, 2]) # nominal case array([1, 2]) >>> _check_psd_eigenvalues([5, 5j]) # significant imag part Traceback (most recent call last): ... ValueError: There are significant imaginary parts in eigenvalues (1 of the maximum real part). Either the matrix is not PSD, or there was an issue while computing the eigendecomposition of the matrix. >>> _check_psd_eigenvalues([5, 5e-5j]) # insignificant imag part array([5., 0.]) >>> _check_psd_eigenvalues([-5, -1]) # all negative Traceback (most recent call last): ... ValueError: All eigenvalues are negative (maximum is -1). Either the matrix is not PSD, or there was an issue while computing the eigendecomposition of the matrix. >>> _check_psd_eigenvalues([5, -1]) # significant negative Traceback (most recent call last): ... ValueError: There are significant negative eigenvalues (0.2 of the maximum positive). Either the matrix is not PSD, or there was an issue while computing the eigendecomposition of the matrix. >>> _check_psd_eigenvalues([5, -5e-5]) # insignificant negative array([5., 0.]) >>> _check_psd_eigenvalues([5, 4e-12]) # bad conditioning (too small) array([5., 0.]) gh㈵>g{Gzt?rUgư>g-q=gH׊>zThere are significant imaginary parts in eigenvalues (%g of the maximum real part). Either the matrix is not PSD, or there was an issue while computing the eigendecomposition of the matrix.zThere are imaginary parts in eigenvalues (%g of the maximum real part). Either the matrix is not PSD, or there was an issue while computing the eigendecomposition of the matrix. Only the real parts will be kept.rzAll eigenvalues are negative (maximum is %g). Either the matrix is not PSD, or there was an issue while computing the eigendecomposition of the matrix.zThere are significant negative eigenvalues (%g of the maximum positive). Either the matrix is not PSD, or there was an issue while computing the eigendecomposition of the matrix.zThere are negative eigenvalues (%g of the maximum positive). Either the matrix is not PSD, or there was an issue while computing the eigendecomposition of the matrix. Negative eigenvalues will be replaced with 0.zBadly conditioned PSD matrix spectrum: the largest eigenvalue is more than %g times the smallest. Small eigenvalues will be replaced with 0.r)rNrrMrdisrealrr]imagmaxrealrPr$r%rrrO) lambdasenable_warningsis_double_precisionsignificant_imag_ratiosignificant_neg_ratiosignificant_neg_valuesmall_pos_ratio max_imag_abs max_real_absmax_eigmin_eigtoo_small_lambdass r3_check_psd_eigenvaluesrs3dhhwG!--2::5"$7DT%8Ed2eO 99W  ! ! #vvbggg./335 vvbggg./335 0<? ?!%1<$?A   MM&*6 )D F (  gggGkkmG{ $ $  ++- ,,w6 60008=D8g;MO  q[ ;@Gh>P R , $%GGaK W?W3L)LM  MM/)+(  &'!" Nr<)rMrrwc &t|}t|\}}|&||j|jfvr |j}||j ||}nt |t jr|j|||}n|||j|jg}t|dd|d|d}|jdk7r td|j|fk7r&tdj|j|f|r t|d |S) aValidate sample weights. Note that passing sample_weight=None will output an array of ones. Therefore, in some cases, you may want to protect the call with: if sample_weight is not None: sample_weight = _check_sample_weight(...) Parameters ---------- sample_weight : {ndarray, Number or None}, shape (n_samples,) Input sample weights. X : {ndarray, list, sparse matrix} Input data. dtype : dtype, default=None dtype of the validated `sample_weight`. If None, and `sample_weight` is an array: - If `sample_weight.dtype` is one of `{np.float64, np.float32}`, then the dtype is preserved. - Else the output has NumPy's default dtype: `np.float64`. If `dtype` is not `{np.float32, np.float64, None}`, then output will be `np.float64`. ensure_non_negative : bool, default=False, Whether or not the weights are expected to be non-negative. .. versionadded:: 1.0 copy : bool, default=False If True, a copy of sample_weight will be created. Returns ------- sample_weight : ndarray of shape (n_samples,) Validated sample weight. It is guaranteed to be "C" contiguous. rMFr sample_weight)rrrMrrwrJrz)Sample weights must be 1D array or scalarz'sample_weight.shape == {}, expected {}!z`sample_weight`)rrrcrdonesrrNumberfullrrrPrr"r!)rrVrMrrwr0rFrJs r3_check_sample_weightrPsTQI ! EB U2::rzz*BB  7 M7>> 2 =F =ZZ,E# &     "HI I   9, .9@@!'')  =*;< r<c|tj|rtj|r|j}|j}|j|jt j |j |j xrYt j |j|jxr-t j|j|j||Stj|s.tj|st j||||Std)aCCheck allclose for sparse and dense data. Both x and y need to be either sparse or dense, they can't be mixed. Parameters ---------- x : {array-like, sparse matrix} First array to compare. y : {array-like, sparse matrix} Second array to compare. rtol : float, default=1e-7 Relative tolerance; see numpy.allclose. atol : float, default=1e-9 absolute tolerance; see numpy.allclose. Note that the default here is more tolerant than the default for numpy.testing.assert_allclose, where atol=0. )rtolrZzFCan only compare two sparse matrices, not a sparse matrix and an array) rsrtrsum_duplicatesrN array_equalr:r;r^r`rP)rrDrrZs r3_allclose_dense_sparsers, {{1~"++a. GGI GGI   NN199aii 0 Bqxx2 B AFFAFFDA [[^BKKN{{1ad66 P r<ct|tr|g}n|}|Dcgc]}t||d}}td|}|4t |j j ddj|d|Scc}w)a Check if `response_method` is available in estimator and return it. .. versionadded:: 1.3 Parameters ---------- estimator : estimator instance Classifier or regressor to check. response_method : {"predict_proba", "predict_log_proba", "decision_function", "predict"} or list of such str Specifies the response method to use get prediction from an estimator (i.e. :term:`predict_proba`, :term:`predict_log_proba`, :term:`decision_function` or :term:`predict`). Possible choices are: - if `str`, it corresponds to the name to the method to return; - if a list of `str`, it provides the method names in order of preference. The method returned corresponds to the first method in the list and which is implemented by `estimator`. Returns ------- prediction_method : callable Prediction method of estimator. Raises ------ AttributeError If `response_method` is not available in `estimator`. Nc|xs|Srr)rrDs r3z(_check_response_method..s AFr<z' has none of the following attributes: rr^)rrrrAttributeErrorrrr#)rresponse_method list_methodsmethodprediction_methods r3_check_response_methodrs</3''( & HTUfFD9UU24EF ""++,,Syy&'q *  VsA6cddlm}i}|jD]_\}}t|st j |rt |t |k7r|||<Ct|||<||||||<a|S)aCheck and validate the parameters passed to a specific method like `fit`. Parameters ---------- X : array-like of shape (n_samples, n_features) Data array. params : dict Dictionary containing the parameters passed to the method. indices : array-like of shape (n_samples,), default=None Indices to be selected if the parameter has the same size as `X`. Returns ------- method_params_validated : dict Validated parameters. We ensure that the values support indexing. r)_safe_indexing)r?rr5rrsrtrr)rVparamsr:rmethod_params_validated param_key param_values r3_check_method_paramsrs(! "(,,.  ;k*2;;{3K + &,q/ 92= #I .2A1M #I .1?' 2G2 #I .  #"r<c tjd}t||j|j fS#t$rYywxYw)z5Return True if the X is a pandas dataframe or series.rFsysmodulesKeyErrorr DataFrameSeriesrVpds r3r"r" E [[ " a",, 2 33 7 AAct tjd}t||jS#t$rYywxYw)z+Return True if the X is a pandas dataframe.rFrrrrrrs r3rr( < [[ " a &&  + 77c tjd}t||j|j |j |jfS#t$rYywxYw)zLReturn True if the X is a pyarrow Table, RecordBatch, Array or ChunkedArray.pyarrowF)rrrrTable RecordBatchArray ChunkedArray)rVpas r3_is_pyarrow_datar1 sQ [[ # a"((BNNBHHbooN OO sA AAc tjd}t||j|j fS#t$rYywxYw)z5Return True if the X is a polars dataframe or series.polarsFrrVpls r3_is_polars_df_or_seriesr: rrct tjd}t||jS#t$rYywxYw)z+Return True if the X is a polars dataframe.rFrrs r3 _is_polars_dfrC rrcd}t|r&tj|jt}nNt |drB|j }tjt|jt}|t|dk(rytdtd|DD}t|dkDrd|vrtd |d t|dk(r |ddk(r|Syy) afGet feature names from X. Support for other array containers should place its implementation here. Parameters ---------- X : {ndarray, dataframe} of shape (n_samples, n_features) Array container to extract feature names. - pandas dataframe : The columns will be considered to be feature names. If the dataframe contains non-string feature names, `None` is returned. - All other array containers will return `None`. Returns ------- names: ndarray or None Feature names of `X`. Unrecognized array containers will return `None`. Nrrrc34K|]}|jywr)r)rrs r3r z%_get_feature_names..w sOa1>>Osc32K|]}t|ywr)rb)rrls r3r z%_get_feature_names..w s.N1tAw.Nr rrz]Feature names are only supported if all input features have string names, but your input has a. as feature name / column name types. If you want feature names to be stored and validated, you must convert them all to strings, by using X.columns = X.columns.astype(str) for example. Otherwise you can remove feature / column names from your input data, or convert them all to a non-string data type.) rrNrLcolumnsrBrrr column_namesr sortedrr)rV feature_names df_protocoltypess r3_get_feature_namesrL s(MQ 199F; O $oo'  4 (@(@(B#C6R M 2a 7 O3.N .N+NO OE 5zA~%5. ""')C C   5zQ58u,-r<generate_namesct|dd}t|dd}|jtj|t}|!tj||s t d|(t ||k7rt d|dt ||S||S|sy| t dtjt|Dcgc]}d | c}tScc}w) aCheck `input_features` and generate names if needed. Commonly used in :term:`get_feature_names_out`. 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. generate_names : bool, default=True Whether to generate names when `input_features` is `None` and `estimator.feature_names_in_` is not defined. This is useful for transformers that validates `input_features` but do not require them in :term:`get_feature_names_out` e.g. `PCA`. Returns ------- feature_names_in : ndarray of str or `None` Feature names in. feature_names_in_Nn_features_in_rz0input_features is not equal to feature_names_in_z?input_features should have length equal to number of features (z), got z7Unable to generate feature names without n_features_in_r)rrNrLrBrrPr range)rinput_featuresrrrrs r3_check_feature_names_inr s: +>EY(8$?N!N&A  ( ~2 OP P  %#n*=*O+,GC4G3HJ $  RSS ::n(=>11#w>f MM>s7 Cct||d|jjj}t j t |Dcgc]}|| c}tScc}w)aGenerate feature names out for estimator using the estimator name as the prefix. The input_feature names are validated but not used. This function is useful for estimators that generate their own names based on `n_features_out`, i.e. PCA. Parameters ---------- estimator : estimator instance Estimator producing output feature names. n_feature_out : int Number of feature names out. input_features : array-like of str or None, default=None Only used to validate feature names with `estimator.feature_names_in_`. Returns ------- feature_names_in : ndarray of str or `None` Feature names in. Frr)rrrlowerrNrLrrB)rn_features_outrrIrs r3_generate_get_feature_names_outr s],I~eL((11779N ::).~)>?AN A3 ?v ?s A)c|}|t|tr/tj|jdtj }t|trt |ds"t|jjdtt|t|jz }|jt|}|r6t|dkDr|dd}|jdtd|d |d t!|jD]*\}}||vs ||}|d vrtd |d |d |||<,|Stj"|gd }|j$drtd|j'd tj(|tj }|j$d|jk7r&td|j$d|jd|S)aOCheck the monotonic constraints and return the corresponding array. This helper function should be used in the `fit` method of an estimator that supports monotonic constraints and called after the estimator has introspected input data to set the `n_features_in_` and optionally the `feature_names_in_` attributes. .. versionadded:: 1.2 Parameters ---------- estimator : estimator instance monotonic_cst : array-like of int, dict of str or None, default=None Monotonic constraints for the features. - If array-like, then it should contain only -1, 0 or 1. Each value will be checked to be in [-1, 0, 1]. If a value is -1, then the corresponding feature is required to be monotonically decreasing. - If dict, then it the keys should be the feature names occurring in `estimator.feature_names_in_` and the values should be -1, 0 or 1. - If None, then an array of 0s will be allocated. Returns ------- monotonic_cst : ndarray of int Monotonic constraints for each feature. Nr)r fill_valuerMrz[ was not fitted on data with feature names. Pass monotonic_cst as an integer array instead.z...zmonotonic_cst contains z unexpected feature names: r^)r[rrzmonotonic_cst['z"'] must be either -1, 0 or 1. Got zDmonotonic_cst must be an array-like of -1, 0 or 1. Observed values: rzmonotonic_cst has shape z but the input data X has z features.)rrrNrrint8rrPrrrrrsortr r8 enumerate setdiff1drtolistrL) r monotonic_cstoriginal_monotonic_cstunexpected_feature_names n_unexpeced feature_idx feature_namecstunexpected_csts r3_check_monotonic_cstr s4:+ =$ ?**'' ,d 39&9:  **3345%% (,*+c)2M2M.NN( $ % ) ) +67K'/014/G/K,,33E: -k];67q:.7y7R7R-S 5) \#990>C*,(-l^+>*?@"112*>  r<c|tj|}|jjdvsutj|ddgstj|ddgstj|dgsstj|dgs\tj|dgsEdj |j Dcgc] }t|c}}td|dd}|Scc}w)aCheck if `pos_label` need to be specified or not. In binary classification, we fix `pos_label=1` if the labels are in the set {-1, 1} or {0, 1}. Otherwise, we raise an error asking to specify the `pos_label` parameters. Parameters ---------- pos_label : int, float, bool, str or None The positive label. y_true : ndarray of shape (n_samples,) The target vector. Returns ------- pos_label : int, float, bool or str If `pos_label` can be inferred, it will be returned. Raises ------ ValueError In the case that `y_true` does not have label in {-1, 1} or {0, 1}, it will raise a `ValueError`. OUSrrr[rzy_true takes value in {zr} and pos_label is not specified: either make y_true take value in {0, 1} or {-1, 1} or pass pos_label explicitly.) rNuniquerMr6rr#r reprrP) pos_labely_trueclassesr classes_reprs r3_check_pos_label_consistencyr3 s:))F# ==   & NN7QF +~~gAw/~~gs+~~gt,~~gs+99w~~7G%H!d1g%HIL*<.988   &IsC.cXtjt|t}||dd|S)aConvert sequence to a 1-D NumPy array of object dtype. numpy.array constructor has a similar use but it's output is ambiguous. It can be 1-D NumPy array of object dtype if the input is a ragged array, but if the input is a list of equal length arrays, then the output is a 2D numpy.array. _to_object_array solves this ambiguity by guarantying that the output is a 1-D NumPy array of objects for any input. Parameters ---------- sequence : array-like of shape (n_elements,) The sequence to be converted. Returns ------- out : ndarray of shape (n_elements,), dtype=object The converted sequence into a 1-D NumPy array of object dtype. Examples -------- >>> import numpy as np >>> from sklearn.utils.validation import _to_object_array >>> _to_object_array([np.array([0]), np.array([1])]) array([array([0]), array([1])], dtype=object) >>> _to_object_array([np.array([0]), np.array([1, 2])]) array([array([0]), array([1, 2])], dtype=object) >>> _to_object_array([np.array([0]), np.array([1, 2])]) array([array([0]), array([1, 2])], dtype=object) rN)rNemptyr rB)sequencerks r3_to_object_arrayre s&> ((3x= /C CF Jr<c|r.t|}|||_yt|dr t|dyt |dd}t|}||y|0|.t j d|jjdy|0|.t j d|jjdyt|t|k7stj||k7rod}t|}t|}t||z } t||z } d} | r|d z }|| | z }| r|d z }|| | z }| s| s|d z }t|y) aFSet or check the `feature_names_in_` attribute of an estimator. .. versionadded:: 1.0 .. versionchanged:: 1.6 Moved from :class:`~sklearn.base.BaseEstimator` to :mod:`sklearn.utils.validation`. Parameters ---------- estimator : estimator instance The estimator to validate the input for. X : {ndarray, dataframe} of shape (n_samples, n_features) The input samples. reset : bool Whether to reset the `feature_names_in_` attribute. If False, the input will be checked for consistency with feature names of data provided when reset was last True. .. note:: It is recommended to call `reset=True` in `fit` and in the first call to `partial_fit`. All other methods that validate `X` should set `reset=False`. NrzX has feature names, but z! was fitted without feature namesz)X does not have valid feature names, but z was fitted with feature nameszBThe feature names should match those that were passed during fit. c`d}d}t|D]\}}||k\r|dz }|S|d|dz }|S)Nr?rz- ... z- r_)r)namesoutput max_n_namesrr,s r3 add_namesz'_check_feature_names..add_names sYFK$U+ (4 #i'FMBtfB-'  ( Mr<z"Feature names unseen at fit time: z1Feature names seen at fit time, yet now missing: z=Feature names must be in the same order as they were in fit. )rrrdelattrrr$r%rrr rNrOrrrP) rrVresetfeature_names_infitted_feature_namesX_feature_namesrfitted_feature_names_setX_feature_names_setunexpected_names missing_namesr%s r3_check_feature_namesr/ s6 -a0  '*:I '  Y 3 4 I2 3"9.A4H(+O#(?"';'C ' (;(;(D(D'EF$ $  #7#C  ##,,--K M    C$88BFF/=X#&';#< !/2!"58P"PQ7:MMN    < g& .>)r4r4TFF)e__doc__rrrr$collections.abcr contextlibr functoolsrrinspectrrr rnumpyrN scipy.sparserrsr?r rK exceptionsr r rutils._array_apirrrutils.deprecationr utils.fixesrr _isfiniterr_tagsrfixesrrdrcfloat16 FLOAT_DTYPESr>rYrUrurrrrrrrrrrrrrrrrrrErCrGrQrTrbrrnrrr{r!rrrrrrr"rrrrrrrrrrr/r2rArr<r3rRsP  $#11 (WWVV;E0& BJJ 3 5,U5,rIK%R$('"Z +^ldT&nS; @2*j1B%P 2( TFRK$NHz   ! #zz 2|    ! %|~ ."dFRBB#(tUK\&*c#!LTGtTGn'B'TGB  } @j\ $UNb$N+\&#R4'P4':z8Nd8Nv:Od/d!HZ"z4 t Dr<