
    0Ph                        d Z ddlZddlZddlZddlZddlmZ ddlmZ ddl	m
Z
mZ ddlmZmZmZ ddlZddlZddlmZ ddlmZ dd	lmZmZmZ dd
lmZmZm Z  ddl!m"Z" ddl#m$Z$m%Z% ddl&m'Z'm(Z( ddl)m*Z* ddl+m,Z, ej-        ej.        ej/        fZ0d[dddZ1	 d\dZ2dddddZ3dddddZ4dddddZ5d Z6d  Z7d! Z8d" Z9d# Z:d$ Z;d% Z<d& Z=d' Z>	 	 d]d(Z?d) Z@d* ZAd+ ZBd, ZC	 d^dd-ddddddddddddd.d/ZDd^d0ZE	 d^dd-ddddddddddddd1d2ZFd_d3ZGdddd4d5ZHd6 ZId7 ZJd8ddd9d:ZKdeLfd;ZMd[deLd<d=ZNd>d?d@ZOdA ZPdddBdCdDZQd^dEZR	 d`dFZSdadIZTdJ ZUd[dKZVdL ZWdM ZXdN ZYdO ZZdP Z[d[ddQdRZ\d[dSZ]d[dTZ^dU Z_dV Z`dW ZadX Zb	 	 	 	 	 dbdZZcdS )czJFunctions to validate input and parameters within scikit-learn estimators.    N)Sequence)suppress)reducewraps)	Parameterisclass	signature   )
get_config)DataConversionWarningNotFittedErrorPositiveSpectrumWarning)_asarray_with_order_is_numpy_namespaceget_namespace)_deprecate_force_all_finite)ComplexWarning_preserve_dia_indices_dtype   )FiniteStatuscy_isfinite)get_tags)_object_dtype_isnanz1.3)versionc                ,    fd}|  ||           S |S )a  Decorator 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                 Z    t                     g g j                                        D ]Z\  }}|j        t          j        k    r                    |           0|j        t          j        k    r                    |           [t                      fd            }|S )Nc                     t          |           t                    z
  }|dk    r | i |S d t          d |         | | d                    D             }d                    |          }t          j        d| d dt
                     |                    t          j        |                       di |S )Nr   c                 @    g | ]\  }}d                      ||          S )z{}={})format).0nameargs      X/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/sklearn/utils/validation.py
<listcomp>zi_deprecate_positional_args.<locals>._inner_deprecate_positional_args.<locals>.inner_f.<locals>.<listcomp>B   s:       D# tS))      , zPass z as keyword args. From version z> passing these as positional arguments will result in an error )lenzipjoinwarningswarnFutureWarningupdate
parameters)	argskwargs
extra_argsargs_msgall_argsfkwonly_argssigr   s	       r#   inner_fzU_deprecate_positional_args.<locals>._inner_deprecate_positional_args.<locals>.inner_f;   s    TS]]2JQq$)&))) !$[*%=tZKLL?Q!R!R  H yy**HM.H . .. . .    MM#cnd334441;;v;;r%   )	r	   r/   itemskindr   POSITIONAL_OR_KEYWORDappendKEYWORD_ONLYr   )r5   r!   paramr8   r4   r6   r7   r   s   `   @@@r#    _inner_deprecate_positional_argszD_deprecate_positional_args.<locals>._inner_deprecate_positional_args0   s    ll>//11 	) 	)KD%zY<<<%%%%y555""4(((	q	 	 	 	 	 	 	 	 
	, r%   r'   )funcr   r?   s    ` r#   _deprecate_positional_argsrA   "   s<    " " " " "H //555++r%   F c                 8   t          |           \  }}t                      d         rdS |                    |           } |sO| j        t	          j        d          k    r2|s0t          |                                           rt          d          |                    | j        d          sdS t	          j	        d          5  |
                    |                    |                     }ddd           n# 1 swxY w Y   |rdS t          | |||||           dS )	z-Like assert_all_finite, but only for ndarray.assume_finiteNobjectzInput contains NaNzreal floatingzcomplex floatingignore)over)xp	allow_nan	msg_dtypeestimator_name
input_name)r   _get_configasarraydtypenpr   any
ValueErrorisdtypeerrstateisfinitesum_assert_all_finite_element_wise)XrJ   rK   rL   rM   rI   is_array_apifirst_pass_isfinites           r#   _assert_all_finiter\   Z   sq   
 %Q''B}}_% 


1A  3AGrx'9'999)9q!!%%'' 	31222 ::agDEE  
(	#	#	# 5 5 kk"&&))445 5 5 5 5 5 5 5 5 5 5 5 5 5 5 #	%     s   )C66C:=C:)rK   rL   rM   c                P   |t           u o/| j        j        o#| j        j        t           j        t           j        hv }|rIt          |                     d          |          }|rdn|t          j
        k    }|t          j        k    }	nT|                    |                    |                     }	|rdn'|                    |                    |                     }|	s|rI|rd}
n||n| j        }d|}
|r|dz   nd}d| d	|
 d
}|r|dk    r|r	|d| dz  }t          |          d S )N)rJ   FNaNz"infinity or a value too large for  rB   zInput z	contains .rY   
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)rQ   data
contiguousrP   typefloat32float64r   reshaper   has_nanhas_infiniterR   isinfisnanrS   )rY   rI   rJ   rK   rL   rM   
use_cythonouthas_nan_errorhas_inftype_errpadded_input_namemsg_errs                r#   rX   rX      sy   
 	bSQV&S17<BJ
;S+S   D!))B--9===!*K|7K0K22&&!%%!*Crxx{{0C0C "- " 	JHH%.%:		IIIIIH0:BJ,,B,BBxBBB 	jC//M/ 5^ 5 5 5G !!!3" "r%   rJ   rL   rM   c                b    t          t          j        |           r| j        n| |||           dS )a  Throw a ValueError if X contains NaN or infinity.

    Parameters
    ----------
    X : {ndarray, sparse matrix}
        The input data.

    allow_nan : bool, default=False
        If True, do not throw error when `X` contains 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.

    Examples
    --------
    >>> 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.
    rt   N)r\   spissparserc   )rY   rJ   rL   rM   s       r#   assert_all_finiterx      sE    L +a..'a%	     r%   T
deprecated)copyforce_all_finiteensure_all_finitec                   t          ||          }t          | t          j                  s.t          | t          j                  s5t          j        |           s!t          | g dt          j        ||d          S t          j        |           r7| j	        t          j
        t          j        fv r|r|                                 n| S | j	        t          j
        t          j        fv r(|r$|                     | j        d         rdnd          n| S | j	        j        dv r| j	        j        dk    rt          j
        }nt          j        }|                     |          S )	a  Convert 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.])
    csrcsccooF)accept_sparserP   rz   r|   	ensure_2dF_CONTIGUOUSFCuib   )r   
isinstancerQ   matrixndarrayrv   rw   check_arrayrg   rP   rf   rz   flagsr:   itemsizeastype)rY   rz   r{   r|   return_dtypes        r#   as_float_arrayr      sB   | 44DFWXX!RY &q"*%%&.0k!nn& ///*/
 
 
 	
 
Q 	&AG
BJ'???&qvvxxxQ&	
RZ,	,	,BFMqvvQW^4=cc#>>>AM7<5  QW%5%:%::LL:Lxx%%%r%   c                     t          j        |           rdS t          | d          pt          | d          pt          | d          S )z(Returns whether the input is array-like.F__len__shape	__array__)rv   rw   hasattrxs    r#   _is_arrayliker   1  sE    	{1~~ u1i  RGAw$7$7R71k;R;RRr%   c                 J    t          |           ot          j        |            S )z3Return True if array is array-like and not a scalar)r   rQ   isscalararrays    r#   _is_arraylike_not_scalarr   9  s"    :E(:(:$::r%   c                 B    t          |            ot          | d          S )a  Use 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   )rY   s    r#   _use_interchange_protocolr   >  s$     Q?GA$?$??r%   c                    t          |           }|j        dk    r|j        }n|j         d|j         }d| }t          | d          sCt          | d          s3t          | d          st	          |          t          j        |           } t          | d          rVt          | j        d          rt          | j                  dk    r|d| j         z  }t	          |          | j        d         S | d	         }t          |t          t          t          f          r)|d
t          |          j         z  }t	          |          	 t          |          S # t          $ r}t	          |          |d}~ww xY w)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
    builtinsra   z5Unable to find the number of features from X of type r   r   r   r   z with shape r   z where the samples are of type N)re   
__module____qualname__r   	TypeErrorrQ   rO   r   r(   r   strbytesdict	Exception)rY   type_	type_namemessagefirst_sampleerrs         r#   _num_featuresr   H  s   $ GGE:%%&		'>>%*<>>	QiQQG1i   G)<)< q+&& 	%G$$$ JqMMq' qw	** 	%c!'lla.?.?/ag///GG$$$wqzQ4L ,eT 233 !VT,5G5G5TVVV   * <    * * *  c)*s   E 
E4E//E4c                    dt          |           z  }t          | d          r#t          | j                  rt	          |          t          |           r&|                                                                 S t          | d          sDt          | d          s4t          | d          rt          j	        |           } nt	          |          t          | d          rd| j
        ]t          | j
                  dk    rt	          d| d	          t          | j
        d         t          j                  r| j
        d         S 	 t          |           S # t          $ r}t	          |          |d}~ww xY w)
z)Return number of samples in array-like x.z'Expected sequence or array-like, got %sfitr   r   r   Nr   zTInput should have at least 1 dimension i.e. satisfy `len(x.shape) > 0`, got scalar `z
` instead.)re   r   callabler   r   r   r   num_rowsrQ   rO   r   r(   r   numbersIntegral)r   r   
type_errors      r#   _num_samplesr   }  s   7$q''AGq% !Xae__ !    ## ,  ))+++1i   %G)<)< %1k"" 	%
1AAG$$$q' 	qw2qw<<1C34C C C   agaj'"233 	71:11vv 1 1 1  j01s   E 
E2E--E2c                     | t          | t                    rt          j        | d          } n2t	          | d          s"t          d                    |                     | S )am  Check 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)
    Nr   )locationverbosecachezg'memory' should be None, a string or have the same interface as joblib.Memory. Got memory='{}' instead.)r   r   joblibMemoryr   rS   r   )memorys    r#   check_memoryr     sh    : ~FC00~:::VW%% 
((.v
 
 	

 Mr%   c                      d | D             }t          j        |          }t          |          dk    rt          dd |D             z            dS )a  Check 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)
    c                 0    g | ]}|t          |          S N)r   r    rY   s     r#   r$   z+check_consistent_length.<locals>.<listcomp>  s    @@@1!-|A---r%   r   z>Found input variables with inconsistent numbers of samples: %rc                 ,    g | ]}t          |          S r'   )int)r    ls     r#   r$   z+check_consistent_length.<locals>.<listcomp>  s    '''!s1vv'''r%   N)rQ   uniquer(   rS   )arrayslengthsuniquess      r#   check_consistent_lengthr     sk    $ A@@@@Gi  G
7||aL''w'''(
 
 	
 r%   c                     t          j        |           r|                                 S t          | d          st          | d          r| S | | S t	          j        |           S )a  Ensure 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)rv   rw   tocsrr   rQ   r   )iterables    r#   _make_indexabler     si     
{8 ~~	=	)	) WXv-F-F 		8Hr%   c                  0    d | D             }t          |  |S )a  Make 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)>]
    c                 ,    g | ]}t          |          S r'   )r   r   s     r#   r$   zindexable.<locals>.<listcomp>  s     444Qoa  444r%   )r   )	iterablesresults     r#   	indexabler     s'    < 54)444FV$$Mr%   c                    || j         }d}t          |           j        }	t          |t                    r|g}t          | |           |du r|rd|z   nd}
t          d|
 d          t          |t          t          f          rIt          |          dk    rt          d          | j        |vr|                     |d                   } d	}n|d	urt          d
| d          || j         k    r|                     |          } n|r|s|                                 } |rLt          | d          s t!          j        d| j         dd           nt%          | j        |dk    ||           |r|d         }t)          | |	|           | S )a  Convert 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.
    NFz for rB   zSparse data was passedzQ, but dense data is required. Use '.toarray()' to convert to a dense numpy array.r   z]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'.rc   zCan't check z sparse matrix for nan or inf.r
   
stacklevel	allow-nanrt   )rP   re   __name__r   r   _check_large_sparser   listtupler(   rS   r   asformatr   rz   r   r+   r,   r\   rc   r   )sparse_containerr   rP   rz   r|   accept_large_sparserL   rM   changed_formatsparse_container_type_namepadded_inputrequested_sparse_formats               r#   _ensure_sparse_formatr     sB   ~ } &N!%&6!7!7!@-%% (& (*=>>>/9Aw++rB\ B B B
 
 	
 
MD%=	1	1 
}""*  
 "-77/88q9IJJ!N	d	"	">,9> > >
 
 	

  &&&+22599	 3n 3+0022 '00 	MV/6VVV    
  %+{:-%	     
"/"2#8:Q	
 	
 	
 r%   c                     t          | d          rN| j        It          | j        d          r6| j        j        dk    r(t          d                    |                     d S d S d S d S )NrP   r:   cComplex data not supported
{}
)r   rP   r:   rS   r   r   s    r#   _ensure_no_complex_datar     s|    wKK#EK(( $K##;BB5IIJJJK K######r%   c                 P    | #t          | t                    r| S | j        j        S d S r   )r   r   	__class__r   )	estimators    r#   _check_estimator_namer     s1    i%% 	0&//4r%   c                    ddl m} ddlm}m}m}  ||           rdS t          | |          rdS 	 ddlm} n# t          $ r Y dS w xY wt          | |          s ||           sdS  ||           rdS  ||           rdS dS )zDReturn True if pandas extension pd_dtype need to be converted early.r   SparseDtype)is_bool_dtypeis_float_dtypeis_integer_dtypeTF)is_extension_array_dtype)	pandasr   pandas.api.typesr   r   r   r   r   ImportError)pd_dtyper   r   r   r   r   s         r#   $_pandas_dtype_needs_early_conversionr     s    #"""""          }X  t(K(( u=======   uu (K(( 
0H0H0R0R 
 u		!	!  t		(	#	# t5s   8 
AAc                 L    t          | d          ot          | j        d          S )NrP   na_value)r   rP   r   s    r#   _is_extension_array_dtyper     s#    5'""Gwu{J'G'GGr%   numeric)r   rP   orderrz   force_writeabler{   r|   ensure_non_negativer   allow_ndensure_min_samplesensure_min_featuresr   rM   c          
      h  % t          ||          }t          | t          j                  rt	          d          t          |           \  }}| }t          |t                    o|dk    }t          | dd          }|st          |d          sd}d}d}d}t          | d          rt          | j	        d          rt          t                    5  d	d
lm% %fd}t          | d          s@| j	                            |                                          rt!          j        d           ddd           n# 1 swxY w Y   t%          | j	                  }t          d |D                       }t'          d |D                       rt          j        | }n|r t          d |D                       rt*          }n{t-          |           st          | d          r\t          | d          rLt/          |           }t1          | j                  }t          | j        t          j                  r| j        }nd}|r'|#t          |d          r|j        dk    r|j        }nd}t          |t$          t8          f          r|||v rd}n|d	         }|r||n|}|                     |          } d}|dvrt=          d|d          |#t?          |          rt          j        |          }tA          |          }|d|z  nd}t          | d          r| j!        dk    rt          t                    5  d	d
lm% %fd}| j	                            |                                          rv| j"        #                                } | j        t          j        d          k    r@tI          d |j	        D                       }tK          |          dk    rt=          d          ddd           n# 1 swxY w Y   tM          j'        |           rMtQ          |            tS          | |||||||          } |
r#| j!        dk     rt=          d| j*         d           n*t!          j+                    5  	 t!          j,        d!tZ                     |p|.                    |d"          rZt_          | ||#          } |.                    | j        d$          rta          | d|||%           |                    | |d&          } nt_          | |||'          } n5# tZ          $ r(}t=          d(1                    |                     |d}~ww xY wddd           n# 1 swxY w Y   tQ          |            |
rV| j!        d	k    r"t=          d)1                    |                     | j!        dk    r|d*| d+}nd,|  d }t=          |          |r2t          | j        d          r| j        j        d-v rt=          d.          |s$| j!        d/k    rt=          d0| j!        |fz            |rta          | |||d1k    2           |rMt?          |          r*t          j2        | |          rt_          | ||d3|4          } nt_          | ||d3|4          } |d	k    r0tg          |           }||k     rt=          d5|| j*        ||fz            |d	k    r9| j!        dk    r.| j*        d         } | |k     rt=          d6| | j*        ||fz            |	r|}!|r|!d7| z  }!ti          | |!           |rtM          j'        |           sd8d9ini }"tM          j'        |           r| j5        n| }#t          |#d:d          }$t          |$d;d3          sGtm          |          r+	 d3|#j7        _8        n*# t<          $ r  | j9        d<i |"} Y nw xY w | j9        d<i |"} | S )=a  Input 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.htmlr   rP   Nr:   Fdtypesr   r   r   c                 $    t          |           S r   r   rP   r   s    r#   	is_sparsezcheck_array.<locals>.is_sparse      !%555r%   sparsezWpandas.DataFrame with sparse columns found.It will be converted to a dense numpy array.c              3   4   K   | ]}t          |          V  d S r   )r   r    is     r#   	<genexpr>zcheck_array.<locals>.<genexpr>  s<       )
 )
89033)
 )
 )
 )
 )
 )
r%   c              3   J   K   | ]}t          |t          j                  V  d S r   )r   rQ   rP   )r    
dtype_iters     r#   r  zcheck_array.<locals>.<genexpr>  s.      NNJz*bh//NNNNNNr%   c              3   ,   K   | ]}|t           k    V  d S r   )rE   )r    ds     r#   r  zcheck_array.<locals>.<genexpr>  s&      /Q/QV/Q/Q/Q/Q/Q/Qr%   r   O)TFr   z7ensure_all_finite should be a bool or 'allow-nan'. Got z	 instead.z by %srB   r   c                 $    t          |           S r   r
  r  s    r#   r  zcheck_array.<locals>.is_sparse  r  r%   rE   c                 &    g | ]}|j         j        S r'   )subtyper!   )r    dts     r#   r$   zcheck_array.<locals>.<listcomp>  s    (U(U(UR(U(U(Ur%   zPandas 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.)r   rP   rz   r|   r   rL   rM   r
   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.errorintegral)r  rI   rF   )rJ   rK   rL   rM   )rz   )r  rP   rI   r   zExpected 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.   z*Found array with dim %d. %s expected <= 2.r   )rM   rL   rJ   T)rP   r  rz   rI   zMFound 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 r  Kr   	writeabler'   ):r   r   rQ   r   r   r   r   getattrr   r  r   r   r   r   applyrR   r+   r,   r   allresult_typerE   r   re   r   rP   r:   rg   r   r   rS   r   r   ndimr  to_coosetr(   rv   rw   r   r   r   catch_warningssimplefilterr   rT   r   r\   r   may_share_memoryr   check_non_negativerc   _is_pandas_df_or_seriesr   r!  rz   )&r   r   r   rP   r  rz   r  r{   r|   r  r   r  r  r  r   rM   rI   is_array_api_compliant
array_origdtype_numeric
dtype_origdtypes_origpandas_requires_conversiontype_if_seriesr  	new_dtyperL   contextunique_dtypescomplex_warningmsg	n_samples
n_featureswhomcopy_params
array_datar   r   s&                                        @r#   r   r     s
   d 44DFWXX%## 
Q
 
 	
 "/u!5!5B J uc**Au	/AM..J! '*f*E*E 
 K!&Nuh #GEL+$F$F # k"" 
	 
	******6 6 6 6 6 5(++ 0B0B90M0M0Q0Q0S0S C  
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 5<((%( )
 )
=H)
 )
 )
 &
 &
" NN+NNNNN 	 5JJ' 	 C/Q/Q[/Q/Q/Q,Q,Q 	 J
#E
*
* 
geV.D.D 
'wK K 
 e%I%+%V%V"ek28,, 	JJ J 	"
F++ #3&& JEEE%$'' !jE&9&9EE !HE!  #(-JJU	Y'' :::. . . .
 
 	

 044*955N+4+@h''bG uh EJNNk"" 	 	******6 6 6 6 6 |!!),,0022 ++--;"(8"4"444$'(U(U:CT(U(U(U$V$VM=))A--(,  	 	 	 	 	 	 	 	 	 	 	 	 	 	 	( 
{5 q&&&%'/ 3)!	
 	
 	
  	a25; 2 2 2   $&& 	' 	''%g~>>>$E:)F)F$ 0UrJJJEzz%+/TUU *!&+&++9'1    IIeUI??EE/U%TVWWWE! ' ' ' 6==eDD &'''	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	'8 	 &&& 	&zQ 6 7=fUmm	   zQ!-#n # # # C:5 : : :  !oo% 	WU[&99 	ek>NRW>W>WJ    	EJ!OO<:~./  
  	%-+{:	     	"2&& 
&uj99 /U%dr  E
 ,e$2   A ''	)))0ek+=wGH   Q5:??[^
+++2u{,?IJ    ( 	,+>+++D5$''' 2 -/K,>,>FwnnB#%;u#5#5@UZZ5

GT22uk400 	2 'z22 26 26J$..! 6 6 6&EJ5555EEE6 #
11[11Lso   AD77D;>D;-B.O''O+.O+&U	(BTU	
T:#T55T::U		UU;^ ^"!^"c                     |sTdg}| j         dk    rddg}n| j         dv rddg}ndS |D ]0}t          | |          j        }||vrt          d	| d
          /dS dS )zGRaise a ValueError if X has 64bit indices and accept_large_sparse=Falseint32r   colrow)r   r   bsrindicesindptrNzCOnly 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   r"  rP   rS   )rY   r   supported_indices
index_keyskeyindices_datatypes         r#   r   r     s     $I8uJJX...#X.JJF 		 		C&q#4'888 W,W W W   9 		 		r%   )r   rP   r  rz   r  r{   r|   r   r  multi_outputr  r  	y_numericr   c                    |&|d}nt          |          }t          | d          t          ||	          }	t          | |||||||	|
||||d          } t	          ||||          }t          | |           | |fS )ao  Input 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])
    Nr   z2 requires y to be passed, but the target y is NonerY   )r   r   rP   r  rz   r  r|   r   r  r  r  r   rM   )rJ  rK  r   )r   rS   r   r   _check_yr   )rY   yr   r   rP   r  rz   r  r{   r|   r   r  rJ  r  r  rK  r   rL   s                     r#   	check_X_yrO    s    x 	y(NN29==NQQQ
 
 	
 44DFWXX	#/'+-/	 	 	A" 	iXXXAAq!!!a4Kr%   c           	      F   |rt          | ddddd|          } nAt          |          }t          | d          } t          | d|           t	          |            |rDt          | j        d	          r/| j        j        d
k    r|                     t          j
                  } | S )z4Isolated part of check_X_y dedicated to y validationr   TFNrN  )r   r|   r   rP   rM   r   )r,   )rM   rL   r:   r  )r   r   column_or_1dr\   r   r   rP   r:   r   rQ   rg   )rN  rJ  rK  r   rL   s        r#   rM  rM  r  s     #"
 
 
 /y99&&&1^LLLL""" !WQWf-- !!',#2E2EHHRZ  Hr%   )rP   r,   devicec                   t          |           \  }}t          | d|ddd          } | j        }t          |          dk    r't	          |                    | d          d||          S t          |          d	k    rQ|d         dk    rE|rt          j        d
t          d	           t	          |                    | d          d||          S t          d
                    |                    )a  Ravel 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 <array_api>` 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])
    FrN  r   )r   rP   rM   r|   r  r   )r^   r   )r  rI   rR  r
   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().r   z9y should be a 1d array, got an array of shape {} instead.)r   r   r   r(   r   rh   r+   r,   r   rS   r   )rN  rP   r,   rR  rI   _r   s          r#   rQ  rQ    s#   L !EB		 	 	A GE
5zzQ"JJq%  6
 
 
 	
 5zzQ58q== 		M@ &    #JJq%  6
 
 
 	
 CJJ5QQ  r%   c                 &   | | t           j        u rt           j        j        j        S t	          | t
          j                  rt           j                            |           S t	          | t           j        j                  r| S t          d| z            )a  Turn 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...
    Nz=%r cannot be used to seed a numpy.random.RandomState instance)	rQ   randommtrand_randr   r   r   RandomStaterS   )seeds    r#   check_random_stater[    s    , |try((y%%$()) +y$$T***$	-.. 
G$N  r%   c                 X    t          | d          o|t          | j                  j        v S )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   )r   r	   r   r/   )r   	parameters     r#   has_fit_parameterr^    s0    : 		5!! 	=9=11<<r%   绽|=)tolraise_warningraise_exceptionc                   | j         dk    s| j        d         | j        d         k    r't          d                    | j                            t	          j        |           rR| | j        z
  }|j        dvr|                                }t          j	        t          |j                  |k               }nt          j        | | j        |          }|sx|rt          d          |rt          j        dd	           t	          j        |           r.d
| j        z   } t          d| | j        z   z  |                      } nd| | j        z   z  } | S )a  Make 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)
    <Compressed Sparse Row sparse matrix of dtype 'int64'
        with 6 stored elements and shape (3, 3)>
    r
   r   r   z3array must be 2-dimensional and square. shape = {0}r~   )atolzArray must be symmetriczYArray is not symmetric, and will be converted to symmetric by average with its transpose.r   tog      ?)r&  r   rS   r   rv   rw   Tr   rQ   r$  absrc   allcloser+   r,   r"  )r   r`  ra  rb  diff	symmetric
conversions          r#   check_symmetricrl    s_   X 	
aU[^u{1~==AHHUU
 
 	
 
{5 :uw;333::<<DF3ty>>C/00		KuwS999	 , 	86777 	MB     ;u 	,,J@GC557?3Z@@BBEE557?+ELr%   c                     |6t          |t          t          f          s|g} | fd|D                       S t           d          r                                 S d t                     D             }t          |          dk    S )a  Determine 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.
    Nc                 0    g | ]}t          |          S r'   )r   )r    attrr   s     r#   r$   z_is_fitted.<locals>.<listcomp>~  s#    KKK79d33KKKr%   __sklearn_is_fitted__c                 f    g | ].}|                     d           |                    d          ,|/S )rT  __)endswith
startswithr    vs     r#   r$   z_is_fitted.<locals>.<listcomp>  sK       ajjoo>?ll4>P>P	  r%   r   )r   r   r   r   rp  varsr(   )r   
attributes
all_or_anyfitted_attrss   `   r#   
_is_fittedr{  c  s    0 *tUm44 	&$JzKKKK
KKKLLLy122 1..000 	??  L |q  r%   )r9  ry  c                V   t          |           r"t          d                    |                     |d}t          | d          st          d| z            t	          |           }|j        s|dS t          | ||          s&t          |dt          |           j	        iz            dS )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 fuction 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.r   z %s is not an estimator instance.r!   )
r   r   r   r   r   requires_fitr{  r   re   r   )r   rx  r9  ry  tagss        r#   check_is_fittedr    s    F y M9@@KKLLL
{A 	
 9e$$ J:iHIIIID !3iZ88 GSFDOO,D#EEFFFG Gr%   )
estimator_r   )	delegatesc                      fd}|S )a  Check 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.
    c                     D ]a}t          | |          rOt          | |          }t          |t                    rt          |d                   c S t          |          c S bt	          d d          )Nr   zNone of the delegates z are present in the class.)r   r"  r   r   rS   )selfdelegate	delegatorro  r  s      r#   checkz_estimator_has.<locals>.check  s    ! 		4 		4H tX&& 4#D(33	i22 4"9Q<66666"9d333334 W)WWWXXXr%   r'   )ro  r  r  s   `` r#   _estimator_hasr    s/    2Y Y Y Y Y Y Lr%   c                 B   t          |           \  }}t          j        |           rJ| j        dv r|                                 } | j        j        dk    rd}n/| j                                        }n|                    |           }|dk     rt          d| d          dS )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.
    )lildokr   z"Negative values in data passed to ra   N)	r   rv   rw   r   r   rc   sizeminrS   )rY   r<  rI   rT  X_mins        r#   r,  r,  
  s     !EB	{1~~ 8~%%		A6;!EEFJJLLEEq		qyyEdEEEFFF yr%   both)min_valmax_valinclude_boundariesc          
        
 d 
t          | |          srt          |t                    r(d                    
fd|D                       }d| d}n 
|          }t          | d| dt	          |           j         d          d	}||vr#t          d
t          |           d| d          ||dk    rt          d          ||dk    rt          d          |dv rt          j	        nt          j
        }	|- |	| |          r!t          | d|  d|dv rdnd d| d          |dv rt          j        nt          j        }	|- |	| |          r!t          | d|  d|dv rdnd d| d          | S )a  Validate 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        }|dk    r|S | t          j        k    rdS | t          j        k    rdS | d| S )z)Convert type into humman readable string.r   floatr   ra   )r   r   r   Realr   )tmodulequalnames      r#   r   zcheck_scalar.<locals>.type_namef  sY    >ZO',7'"""5%%8%%%r%   r&   c              3   .   K   | ]} |          V  d S r   r'   )r    r  r   s     r#   r  zcheck_scalar.<locals>.<genexpr>t  s+      !D!D1))A,,!D!D!D!D!D!Dr%   {}z must be an instance of z, not ra   )leftrightr  neitherz(Unknown value for `include_boundaries`: z. Possible values are: Nr  zU`include_boundaries`='right' without specifying explicitly `max_val` is inconsistent.r  zT`include_boundaries`='left' without specifying explicitly `min_val` is inconsistent.)r  r  z == z
, must be z>=>r`   )r  r  z<=<)r   r   r*   r   re   r   rS   reproperatorltlegtge)r   r!   target_typer  r  r  	types_strtarget_type_strexpected_include_boundariescomparison_operatorr   s             @r#   check_scalarr  &  s   @
& 
& 
& a%% 

k5)) 	5		!D!D!D!D!D!D!DDDI09000OO'i44O ( (_ ( (Q$( ( (
 
 	

 #G!<<<Ct<N7O7O C C$?C C C
 
 	

 -88
 
 	

 -77
 
 	
 *-===8;  221g>> U U U U*.>>>CU UJQU U U
 
 	
 *->>>HK  221g>> V V V V*.???SV VKRV V V
 
 	

 Hr%   c                    t          j        |           } | j        t           j        k    }d}|rdnd}|rdnd}|rdnd}t          j        |                                           st          j        t          j        |                                                     }t          j        t          j	        |                                                     }|||z  k    rt          d||z  z            |r t          j        d||z  z  t                     t          j	        |           } |                                 }	|	d	k     rt          d
|	z            |                                 }
|
| |	z  k     r|
| k     rt          d|
 |	z  z            |
d	k     r,|r!t          j        d|
 |	z  z  t                     d	| | d	k     <   d	| k     | ||	z  k     z  }|                                r'|r t          j        dd|z  z  t                     d	| |<   | S )a  Check 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?r_  gư>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.r   zAll 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   )rQ   r   rP   rg   isrealr$  rg  imagmaxrealrS   r+   r,   r   r  rR   )lambdasenable_warningsis_double_precisionsignificant_imag_ratiosignificant_neg_ratiosignificant_neg_valuesmall_pos_ratiomax_imag_absmax_real_absmax_eigmin_eigtoo_small_lambdass               r#   _check_psd_eigenvaluesr    s   d hwG!-2:5 "$7ADDT%8BEEd2<eeO 9W!!## vbgg..//3355vbgg..//33550<???! %1<$?A    	M& *6)D	F
 (   ggG kkmmG{{ $$
 
 	
 ++--,,w66600008 =D8g;MO   q[[ ; @Gh>P	R
 ,   $%GGaK  W?W3L)LM 	' 	M /)+ (   &'!"Nr%   c           	      ,   t          |          }|&|t          j        t          j        fvrt          j        }| t          j        ||          } nt          | t          j                  rt          j        || |          } n|t          j        t          j        g}t          | dd|d|d          } | j
        dk    rt          d          | j        |fk    r)t          d	                    | j        |f                    |rt          | d
           | S )a  Validate 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.

    ensure_non_negative : bool, default=False,
        Whether or not the weights are expected to be non-negative.

        .. versionadded:: 1.0

    dtype : dtype, default=None
        dtype of the validated `sample_weight`.
        If None, and the input `sample_weight` is an array, the dtype of the
        input is preserved; otherwise an array with the default numpy dtype
        is be allocated.  If `dtype` is not one of `float32`, `float64`,
        `None`, the output will be of dtype `float64`.

    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.
    NrP   Fr   sample_weight)r   r   rP   r  rz   rM   r   z)Sample weights must be 1D array or scalarz'sample_weight.shape == {}, expected {}!z`sample_weight`)r   rQ   rf   rg   onesr   r   Numberfullr   r&  rS   r   r   r,  )r  rY   rP   rz   r  r:  s         r#   _check_sample_weightr  S  s3   L QIU2:rz*BBB
	777	M7>	2	2 	=FFF=Z,E#&
 
 
 ""HIII9,..9@@!')     ==*;<<<r%   Hz>&.>c                 P   t          j        |           rt          j        |          r|                                 } |                                }|                                  |                                 t	          j        | j        |j                  o@t	          j        | j        |j                  o!t	          j        | j	        |j	        ||          S t          j        |           s,t          j        |          st	          j        | |||          S t          d          )aC  Check 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.
    )rtolrd  zFCan only compare two sparse matrices, not a sparse matrix and an array)rv   rw   r   sum_duplicatesrQ   array_equalrD  rE  rh  rc   rS   )r   rN  r  rd  s       r#   _allclose_dense_sparser    s   , 
{1~~ 7"+a.. 7GGIIGGII		N19ai00 Bqx22BAFAFDAAA	

 [^^ 7BKNN 7{1ad6666
P  r%   c                      t          |t                    r|g}n|} fd|D             }t          d |          }|2t           j        j         dd                    |           d          |S )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`.
    c                 2    g | ]}t          |d           S r   )r"  )r    methodr   s     r#   r$   z*_check_response_method.<locals>.<listcomp>  s%    UUUfFD99UUUr%   c                 
    | p|S r   r'   )r   rN  s     r#   <lambda>z(_check_response_method.<locals>.<lambda>  s
    AF r%   Nz' has none of the following attributes: r&   ra   )r   r   r   AttributeErrorr   r   r*   )r   response_methodlist_methodsprediction_methods   `   r#   _check_response_methodr    s    < /3'' ''(&UUUUUUU224EFF "+ * *yy&&* * *
 
 	

 r%   c                 *   ddl m} i }|                                D ]u\  }}t          |          st	          j        |          r t          |          t          |           k    r|||<   Nt          |          ||<    |||         |          ||<   v|S )a  Check 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)rB   r  r9   r   rv   rw   r   r   )rY   paramsrD  r  method_params_validated	param_keyparam_values          r#   _check_method_paramsr    s    ( !      "(,,..  	;k**	K,,	 K((LOO;; 2=#I.. 2A1M1M#I.1?'	2G2 2#I.. #"r%   c                     	 t           j        d         }n# t          $ r Y dS w xY wt          | |j        |j        f          S )z5Return True if the X is a pandas dataframe or series.r   FsysmodulesKeyErrorr   	DataFrameSeriesrY   pds     r#   r-  r-  	  P    ["   uua",	2333    
##c                 v    	 t           j        d         }n# t          $ r Y dS w xY wt          | |j                  S )z+Return True if the X is a pandas dataframe.r   Fr  r  r  r   r  r  s     r#   r   r   '	  I    ["   uua&&&r  c                     	 t           j        d         }n# t          $ r Y dS w xY wt          | |j        |j        f          S )z5Return True if the X is a polars dataframe or series.polarsFr  rY   pls     r#   _is_polars_df_or_seriesr  0	  r  r  c                 v    	 t           j        d         }n# t          $ r Y dS w xY wt          | |j                  S )z+Return True if the X is a polars dataframe.r  Fr  r  s     r#   _is_polars_dfr  9	  r  r  c                 N   d}t          |           r!t          j        | j        t                    }n^t          | d          rN|                                 }t          j        t          |                                          t                    }|t          |          dk    rdS t          d t          d |D                       D                       }t          |          dk    rd|v rt          d	| d
          t          |          dk    r|d         dk    r|S dS dS )af  Get 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`.
    Nr  r   r   c              3   $   K   | ]}|j         V  d S r   )r   )r    r  s     r#   r  z%_get_feature_names.<locals>.<genexpr>m	  s$      OOa1>OOOOOOr%   c              3   4   K   | ]}t          |          V  d S r   )re   ru  s     r#   r  z%_get_feature_names.<locals>.<genexpr>m	  s(      .N.N1tAww.N.N.N.N.N.Nr%   r   r   z]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.)r   rQ   rO   columnsrE   r   r   r   column_namesr(   sortedr(  r   )rY   feature_namesdf_protocoltypess       r#   _get_feature_namesr  B	  sH   ( M Q S 
19F;;;	O	$	$ Soo''
4(@(@(B(B#C#C6RRRM 2 2a 7 7OO3.N.N.N.N.N+N+NOOOOOE 5zzA~~%5..C"'C C C
 
 	
 5zzQ58u,, ,,r%   generate_namesc                   t          | dd          }t          | dd          }|zt          j        |t                    }|$t          j        ||          st          d          |5t          |          |k    r"t          d| dt          |                     |S ||S |sdS |t          d          t          j        d	 t          |          D             t                    S )
a  Check `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_Nn_features_in_r  z0input_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_c                     g | ]}d | S r   r'   r  s     r#   r$   z+_check_feature_names_in.<locals>.<listcomp>	  s    >>>1w1ww>>>r%   )r"  rQ   rO   rE   r  rS   r(   range)r   input_featuresr  r  r  s        r#   _check_feature_names_inr  	  s*   :  	+>EEY(8$??N!N&AAA(~2
 2
( OPPP%#n*=*=*O*OJ+J J474G4GJ J   $    RSSS:>>n(=(=>>>fMMMMr%   c                     t          | |d           | j        j                                        t	          j        fdt          |          D             t                    S )a  Generate 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.
    Fr  c                     g | ]} | 	S r'   r'   )r    r  rL   s     r#   r$   z3_generate_get_feature_names_out.<locals>.<listcomp>	  s$    ???AN	A		???r%   r  )r  r   r   lowerrQ   rO   r  rE   )r   n_features_outr  rL   s      @r#   _generate_get_feature_names_outr  	  sk    , I~eLLLL(17799N:????~)>)>???v   r%   c                    |}|t          |t                    rLt          j        | j        dt          j                  }t          |t                    rt          | d          st          | j        j	         d          t          t          |          t          | j                  z
            }|                                 t          |          }|rHt          |          dk    r|dd         }|                    d           t          d| d	| d
          t!          | j                  D ]0\  }}||v r'||         }|dvrt          d| d|d
          |||<   1nt          j        |g d          }|j        d         r%t          d|                                 d
          t          j        |t          j                  }|j        d         | j        k    r t          d|j         d| j         d          |S )aO  Check 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_valuerP   r  z[ was not fitted on data with feature names. Pass monotonic_cst as an integer array instead.   z...zmonotonic_cst contains z unexpected feature names: ra   )r^   r   r   zmonotonic_cst['z"'] must be either -1, 0 or 1. Got zDmonotonic_cst must be an array-like of -1, 0 or 1. Observed values: r  zmonotonic_cst has shape z but the input data X has z
 features.)r   r   rQ   r  r  int8r   rS   r   r   r   r(  r  sortr(   r<   	enumerate	setdiff1dr   tolistrO   )	r   monotonic_cstoriginal_monotonic_cstunexpected_feature_namesn_unexpecedfeature_idxfeature_namecstunexpected_csts	            r#   _check_monotonic_cstr  	  s   : +
=$ ? ?*'
 
 

 ,d33 	59&9::   *3 % % %  
 (,*++c)2M.N.NN( ($ %))+++677K' /00144/G/K,,33E::: :k : :6: : :   .7y7R-S-S 5 5)\#9990>C*,,(8l 8 8/28 8 8   25M+.mZZZ@@" 	6)00226 6 6  
 
=@@@q!Y%===>=+> > >"1> > >   r%   c                    | t          j        |          }|j        j        dv spt          j        |ddg          st          j        |ddg          st          j        |dg          spt          j        |dg          sZt          j        |dg          sDd                    d |                                D                       }t          d| d	          d} | S )
a  Check 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`.
    NOUSr   r   r^   r&   c                 ,    g | ]}t          |          S r'   )r  )r    r   s     r#   r$   z0_check_pos_label_consistency.<locals>.<listcomp>P
  s    %H%H%H!d1gg%H%H%Hr%   zy_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.)rQ   r   rP   r:   r  r*   r  rS   )	pos_labely_trueclassesclasses_reprs       r#   _check_pos_label_consistencyr$  )
  s   : )F##=&&N7QF++ '~gAw// ' ~gs++ ' ~gt,,	 '
 ~gs++ '  99%H%Hw~~7G7G%H%H%HIIL8< 8 8 8  
 	r%   c                 d    t          j        t          |           t                    }| |dd<   |S )a  Convert 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)
    r  N)rQ   emptyr(   rE   )sequencern   s     r#   _to_object_arrayr(  [
  s0    > (3x==
/
/
/CCFJr%   c                   |r;t          |          }||| _        n t          | d          rt          | d           dS t	          | dd          }t          |          }||dS |&|$t          j        d| j        j         d           dS |&|$t          j        d| j        j         d           dS t          |          t          |          k    st          j        ||k              rd}t          |          }t          |          }t          ||z
            }	t          ||z
            }
d }|	r|d	z  }| ||	          z  }|
r|d
z  }| ||
          z  }|
s|	s|dz  }t          |          dS )aF  Set 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`.
    Nr  zX 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}d}t          |           D ]\  }}||k    r|dz  } n
|d| dz  }|S )NrB   r  z- ...
z- rb   )r  )namesoutputmax_n_namesr  r!   s        r#   	add_namesz'_check_feature_names.<locals>.add_names
  sZ    FK$U++ ( (4##i'FE-t---'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.
)r  r  r   delattrr"  r+   r,   r   r   r(   rQ   rR   r(  r  rS   )r   rY   resetfeature_names_infitted_feature_namesX_feature_namesr   fitted_feature_names_setX_feature_names_setunexpected_namesmissing_namesr.  s               r#   _check_feature_namesr8  
  s)   6  -a00'*:I''Y 344 	4 I2333"9.A4HH(++O#(?"';'C$	(;(D $ $ $	
 	
 	
 	#7#CM#,M M M	
 	
 	
 	   C$8$888BF/= =8 X#&';#<#< !/22!"58P"PQQ7:MMNN	 	 	  	3<<Gyy!1222G 	0KKGyy///G 	X%5 	XWWG!!!? 98r%   c           	      h   	 t          |          }nP# t          $ rC}|s6t          | d          r&t          d| j        j         d| j         d          |Y d}~dS d}~ww xY w|r	|| _        dS t          | d          sdS || j        k    r(t          d| d| j        j         d| j         d          dS )	aq  Set the `n_features_in_` attribute, or check against it on an estimator.

    .. 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, sparse matrix} of shape (n_samples, n_features)
        The input samples.

    reset : bool
        If True, the `n_features_in_` attribute is set to `X.shape[1]`.
        If False and the attribute exists, then check that it is equal to
        `X.shape[1]`. If False and the attribute does *not* exist, then
        the check is skipped.
        .. 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`.
    r  z%X does not contain any features, but z is expecting z	 featuresNzX has z features, but z features as input.)r   r   r   rS   r   r   r  )r   rY   r0  r;  es        r#   _check_n_featuresr;  
  s;   2"1%%

 	 	 	 	,<== 	7&/7 7+7 7 7  	 		  #-	 9.//  	Y---JZ J J	0C0L J J%4J J J
 
 	
 .-s    
A8AAno_validationc                   t          | ||           t          |           }|)|j        j        rt	          d| j        j         d          t          |t                    o|dk    }|du pt          |t                    o|dk    }	|r|	rt	          d          d| i}
i |
|}|r|s|	r|}n|r|	s|}nz||f}nu|s|	rt          |fdd	i|}na|r|	st          |fi |}nO|r8|\  }}d|vri |
|}t          |fdd	i|}d|vri |
|}t          |fdd
i|}nt          ||fi |\  }}||f}|s(|                    dd          rt          | ||           |S )a  Validate input data and set or check feature names and counts of the input.

    This helper function should be used in an estimator that requires input
    validation. This mutates the estimator and sets the `n_features_in_` and
    `feature_names_in_` attributes if `reset=True`.

    .. versionadded:: 1.6

    Parameters
    ----------
    _estimator : estimator instance
        The estimator to validate the input for.

    X : {array-like, sparse matrix, dataframe} of shape             (n_samples, n_features), default='no validation'
        The input samples.
        If `'no_validation'`, no validation is performed on `X`. This is
        useful for meta-estimator which can delegate input validation to
        their underlying estimator(s). In that case `y` must be passed and
        the only accepted `check_params` are `multi_output` and
        `y_numeric`.

    y : array-like of shape (n_samples,), default='no_validation'
        The targets.

        - If `None`, :func:`~sklearn.utils.check_array` is called on `X`. If
          the estimator's `requires_y` tag is True, then an error will be raised.
        - If `'no_validation'`, :func:`~sklearn.utils.check_array` is called
          on `X` and the estimator's `requires_y` tag is ignored. This is a default
          placeholder and is never meant to be explicitly set. In that case `X` must be
          passed.
        - Otherwise, only `y` with `_check_y` or both `X` and `y` are checked with
          either :func:`~sklearn.utils.check_array` or
          :func:`~sklearn.utils.check_X_y` depending on `validate_separately`.

    reset : bool, default=True
        Whether to reset the `n_features_in_` attribute.
        If False, the input will be checked for consistency with 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`.

    validate_separately : False or tuple of dicts, default=False
        Only used if `y` is not `None`.
        If `False`, call :func:`~sklearn.utils.check_X_y`. Else, it must be a tuple of
        kwargs to be used for calling :func:`~sklearn.utils.check_array` on `X` and `y`
        respectively.

        `estimator=self` is automatically added to these dicts to generate
        more informative error message in case of invalid input data.

    skip_check_array : bool, default=False
        If `True`, `X` and `y` are unchanged and only `feature_names_in_` and
        `n_features_in_` are checked. Otherwise, :func:`~sklearn.utils.check_array`
        is called on `X` and `y`.

    **check_params : kwargs
        Parameters passed to :func:`~sklearn.utils.check_array` or
        :func:`~sklearn.utils.check_X_y`. Ignored if validate_separately
        is not False.

        `estimator=self` is automatically added to these params to generate
        more informative error message in case of invalid input data.

    Returns
    -------
    out : {ndarray, sparse matrix} or tuple of these
        The validated input. A tuple is returned if both `X` and `y` are
        validated.
    )r0  NzThis z= estimator requires y to be passed, but the target y is None.r<  z*Validation should be done on X, y or both.r   rM   rY   rN  r   T)r8  r   target_tagsrequiredrS   r   r   r   r   r   rM  rO  getr;  )
_estimatorrY   rN  r0  validate_separatelyskip_check_arraycheck_paramsr~  no_val_Xno_val_ydefault_check_paramsrn   check_X_paramscheck_y_paramss                 r#   validate_datarJ    sN   h Qe4444JDyT%.yAJ(1 A A A
 
 	

 !S!!:a?&:HDyGJq#..G13GH GH GEFFF'4;*;l;L  	H 	CC 	h 	CCQ$CC ( !<<<|<<	 ( q))L)) 	3
 .A*NN.00!K$8!KN!KA@@#@@@A.00!K$8!KN!KA@@#@@@AAQ22\22DAqd 6((d;; 6*au5555Jr%   r   )FNNrB   )NrB   )F)FFN)NFF)r  r  )r<  r<  TFF)d__doc__r   r  r  r+   collections.abcr   
contextlibr   	functoolsr   r   inspectr   r   r	   r   numpyrQ   scipy.sparser  rv   rB   r   rN   
exceptionsr   r   r   utils._array_apir   r   r   utils.deprecationr   utils.fixesr   r   	_isfiniter   r   _tagsr   fixesr   rg   rf   float16FLOAT_DTYPESrA   r\   rX   rx   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rO  rM  rQ  r[  r^  rl  r$  r{  r  r  r,  r  r  r  r  r  r  r-  r   r  r  r  r  r  r  r$  r(  r8  r;  rJ  r'   r%   r#   <module>r[     s   P P
   



  $ $ $ $ $ $       # # # # # # # # 1 1 1 1 1 1 1 1 1 1            ( ( ( ( ( ( W W W W W W W W W W V V V V V V V V V V ; ; ; ; ; ; E E E E E E E E 0 0 0 0 0 0 0 0       & & & & & &
BJ
35,U 5, 5, 5, 5, 5,r IK% % % %R $('" '" '" '" '"Z + + + + +^ ldT& T& T& T& T&nS S S; ; ;
@ @ @2* 2* 2*j1 1 1B% % %P
 
 
6  (     T F F F FRK K K  $ $ $NH H H z 

	!#z z z z zz   2 |
 

	!%| | | | |~   . "d F F F F FR  B  D #(tU K K K K K\ &*c #! #! #! #!LTGt TG TG TG TG TGn 'B ' ' ' ' 'TG G GB } } } } }@j j j j\ CHH H H HV$ $ $ $N+ + +\(# (# (# (#V4 4 4' ' '4 4 4' ' ': : :z8Nd 8N 8N 8N 8N 8Nv   :O O O Od/ / /d! ! !HZ" Z" Z"z4
 4
 4
t 
D D D D D Dr%   