
    {Kgg                     *   d Z ddlZddl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	Z
ddlmZ ddl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 ddlmZ ddlmZ ddl m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z) dddZ*dddZ+ G d dee      Z, G d d      Z- G d d      Z. G d d      Z/ G d d      Z0 G d de      Z1 G d d       Z2 G d! d"      Z3 G d# d$      Z4 G d% d&      Z5 G d' d(      Z6 G d) d*      Z7 G d+ d,      Z8d- Z9d. Z:d/ Z;d0 Z<y)1z>Base classes for all estimators and various utility functions.    N)defaultdict   )__version__)config_context
get_config)InconsistentVersionWarning)_HTMLDocumentationLinkMixinestimator_html_repr)_MetadataRequester_routing_enabled)validate_parameter_constraints)_SetOutputMixin_DEFAULT_TAGS)	_IS_32BIT)	_check_feature_names_in_check_y_generate_get_feature_names_out_get_feature_names
_is_fitted_num_featurescheck_arraycheck_is_fitted	check_X_yTsafec                ~    t        | d      r%t        j                  |       s| j                         S t	        | |      S )a  Construct a new unfitted estimator with the same parameters.

    Clone does a deep copy of the model in an estimator
    without actually copying attached data. It returns a new estimator
    with the same parameters that has not been fitted on any data.

    .. versionchanged:: 1.3
        Delegates to `estimator.__sklearn_clone__` if the method exists.

    Parameters
    ----------
    estimator : {list, tuple, set} of estimator instance or a single             estimator instance
        The estimator or group of estimators to be cloned.
    safe : bool, default=True
        If safe is False, clone will fall back to a deep copy on objects
        that are not estimators. Ignored if `estimator.__sklearn_clone__`
        exists.

    Returns
    -------
    estimator : object
        The deep copy of the input, an estimator if input is an estimator.

    Notes
    -----
    If the estimator's `random_state` parameter is an integer (or if the
    estimator doesn't have a `random_state` parameter), an *exact clone* is
    returned: the clone and the original estimator will give the exact same
    results. Otherwise, *statistical clone* is returned: the clone might
    return different results from the original estimator. More details can be
    found in :ref:`randomness`.

    Examples
    --------
    >>> from sklearn.base import clone
    >>> from sklearn.linear_model import LogisticRegression
    >>> X = [[-1, 0], [0, 1], [0, -1], [1, 0]]
    >>> y = [0, 0, 1, 1]
    >>> classifier = LogisticRegression().fit(X, y)
    >>> cloned_classifier = clone(classifier)
    >>> hasattr(classifier, "classes_")
    True
    >>> hasattr(cloned_classifier, "classes_")
    False
    >>> classifier is cloned_classifier
    False
    __sklearn_clone__r   )hasattrinspectisclassr   _clone_parametrized)	estimatorr   s     P/home/alanp/www/video.onchill/myenv/lib/python3.12/site-packages/sklearn/base.pycloner%   (   s7    b y-.wy7Q**,,yt44    c          	         t        |       }|t        u r/| j                         D ci c]  \  }}|t        ||       c}}S |t        t
        t        t        fv r! || D cg c]  }t        ||       c}      S t        | d      rt        | t               rV|st        j                  |       S t        | t               rt        d      t        dt        |       dt        |       d      | j                  }| j                  d      }|j                         D ]  \  }}	t        |	d      ||<     |di |}
	 t        j                  | j                         |
_        |
j                  d      }|D ]!  }||   }||   }||ust%        d	| d
|       t        | d      r$t        j                  | j&                        |
_        |
S c c}}w c c}w # t"        $ r Y w xY w)zLDefault implementation of clone. See :func:`sklearn.base.clone` for details.r   
get_paramszaCannot clone object. You should provide an instance of scikit-learn estimator instead of a class.zCannot clone object 'z' (type zb): it does not seem to be a scikit-learn estimator as it does not implement a 'get_params' method.FdeepzCannot clone object z?, as the constructor either does not set or modifies parameter _sklearn_output_config )typedictitemsr%   listtupleset	frozensetr   
isinstancecopydeepcopy	TypeErrorrepr	__class__r(   _metadata_requestAttributeErrorRuntimeErrorr+   )r#   r   estimator_typekveklassnew_object_paramsnameparam
new_object
params_setparam1param2s                 r$   r"   r"   ^   s    )_N3<??3DE3D41a5&&3DEE	D%i8	8IFIquQT2IFGGY-It1L==++)T*C    /39otIP  E!,,%,8(..0e"'E":$ 1 +*+J'+}}Y5P5P'Q
$ &&E&2J ""4(D!BKTS 	 " y23,0MM,,-

) e FF6  s   G!G=$G 	G"!G"c                        e Zd ZdZed        ZddZd Zd ZddZ	 fdZ
 fdZd	 Zd
 Zd Zd Z	 	 	 	 	 ddZd Zed        Zd Zd Z xZS )BaseEstimatoraq  Base class for all estimators in scikit-learn.

    Inheriting from this class provides default implementations of:

    - setting and getting parameters used by `GridSearchCV` and friends;
    - textual and HTML representation displayed in terminals and IDEs;
    - estimator serialization;
    - parameters validation;
    - data validation;
    - feature names validation.

    Read more in the :ref:`User Guide <rolling_your_own_estimator>`.


    Notes
    -----
    All estimators should specify all the parameters that can be set
    at the class level in their ``__init__`` as explicit keyword
    arguments (no ``*args`` or ``**kwargs``).

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.base import BaseEstimator
    >>> class MyEstimator(BaseEstimator):
    ...     def __init__(self, *, param=1):
    ...         self.param = param
    ...     def fit(self, X, y=None):
    ...         self.is_fitted_ = True
    ...         return self
    ...     def predict(self, X):
    ...         return np.full(shape=X.shape[0], fill_value=self.param)
    >>> estimator = MyEstimator(param=2)
    >>> estimator.get_params()
    {'param': 2}
    >>> X = np.array([[1, 2], [2, 3], [3, 4]])
    >>> y = np.array([1, 0, 1])
    >>> estimator.fit(X, y).predict(X)
    array([2, 2, 2])
    >>> estimator.set_params(param=3).fit(X, y).predict(X)
    array([3, 3, 3])
    c                    t        | j                  d| j                        }|t        j                  u rg S t        j                  |      }|j
                  j                         D cg c],  }|j                  dk7  r|j                  |j                  k7  r|. }}|D ]-  }|j                  |j                  k(  st        d| d|d       t        |D cg c]  }|j                   c}      S c c}w c c}w )z%Get parameter names for the estimatordeprecated_originalselfzpscikit-learn estimators should always specify their parameters in the signature of their __init__ (no varargs). z with constructor z! doesn't  follow this convention.)getattr__init__objectr    	signature
parametersvaluesrC   kindVAR_KEYWORDVAR_POSITIONALr<   sorted)clsinitinit_signatureprR   s        r$   _get_param_nameszBaseEstimator._get_param_names   s    
 s||%:CLLI6??"I !**40 $..557
7vvAFFamm$; 7 	 

 Avv)))"
 36~	G   z2z!qvvz233
 3s   '1C/C4c                    t               }| j                         D ]i  t        |       }|rTt        |d      rHt	        |t
              s8|j                         j                         }|j                  fd|D               ||<   k |S )ae  
        Get parameters for this estimator.

        Parameters
        ----------
        deep : bool, default=True
            If True, will return the parameters for this estimator and
            contained subobjects that are estimators.

        Returns
        -------
        params : dict
            Parameter names mapped to their values.
        r(   c              3   8   K   | ]  \  }}d z   |z   |f  yw)__Nr,   ).0r>   valkeys      r$   	<genexpr>z+BaseEstimator.get_params.<locals>.<genexpr>   s#     JzVQC$JNC0zs   )	r.   r\   rN   r   r4   r-   r(   r/   update)rM   r*   outvalue
deep_itemsrb   s        @r$   r(   zBaseEstimator.get_params   sy     f((*CD#&E|4Zt=T"--/557


JzJJCH + 
r&   c           
         |s| S | j                  d      }t        t              }|j                         D ]`  \  }}|j	                  d      \  }}}||vr%| j                         }t        d|d|  d|d      |r	|||   |<   Ot        | ||       |||<   b |j                         D ]  \  }}	 ||   j                  di |	  | S )	a  Set the parameters of this estimator.

        The method works on simple estimators as well as on nested objects
        (such as :class:`~sklearn.pipeline.Pipeline`). The latter have
        parameters of the form ``<component>__<parameter>`` so that it's
        possible to update each component of a nested object.

        Parameters
        ----------
        **params : dict
            Estimator parameters.

        Returns
        -------
        self : estimator instance
            Estimator instance.
        Tr)   r_   zInvalid parameter z for estimator z. Valid parameters are: .r,   )	r(   r   r.   r/   	partitionr\   
ValueErrorsetattr
set_params)
rM   paramsvalid_paramsnested_paramsrb   rf   delimsub_keylocal_valid_params
sub_paramss
             r$   rm   zBaseEstimator.set_params   s    $ KD1#D) ,,.JC"%--"5C,&%)%:%:%<" (tf E--?,B!E 
 .3c"7+c5)$)S! )  -224OC(L((6:6  5 r&   c                     t        |       S N)r"   rM   s    r$   r   zBaseEstimator.__sklearn_clone__'  s    "4((r&   c                 $   ddl m} d} |ddd|      }|j                  |       }t        dj	                  |j                                     }||kD  r|dz  }d|z  }t        j                  ||      j                         }	t        j                  ||d d d	         j                         }
d
||	|
  v r/|dz  }t        j                  ||d d d	         j                         }
d}|	t        |      z   t        |      |
z
  k  r|d |	 dz   ||
 d  z   }|S )Nr   )_EstimatorPrettyPrinter   T)compactindentindent_at_namen_max_elements_to_show    z^(\s*\S){%d}
z[^\n]*\nz...)	utils._pprintry   pformatlenjoinsplitrematchend)rM   
N_CHAR_MAXry   N_MAX_ELEMENTS_TO_SHOWpprepr_
n_nonblanklimregexleft_lim	right_limellipsiss               r$   __repr__zBaseEstimator.__repr__*  s(   
 	;!# %#9	
 

4  /0

"/C#c)E xxu-113Hdd488:IuXyj11 $HHUE$B$K8<<>	H#h-'#e*y*@@ix(505)3EEr&   c                 f   t        | dd       rt        d      	 t        |          }|| j                  j                         }t        |       j                  j                  d      rt        |j                         t              S |S # t        $ r | j                  j                         }Y jw xY w)N	__slots__zSYou cannot use `__slots__` in objects inheriting from `sklearn.base.BaseEstimator`.sklearn.)_sklearn_version)rN   r7   super__getstate____dict__r5   r;   r-   
__module__
startswithr.   r/   r   )rM   stater9   s     r$   r   zBaseEstimator.__getstate__^  s    4d+0 
	)G(*E} **,
 :  ++J7DDL  	)MM&&(E	)s   *B
 
#B0/B0c                 j   t        |       j                  j                  d      rT|j                  dd      }|t        k7  r9t        j                  t        | j                  j                  t        |             	 t        | -  |       y # t        $ r | j                  j                  |       Y y w xY w)Nr   r   zpre-0.18)estimator_namecurrent_sklearn_versionoriginal_sklearn_version)r-   r   r   popr   warningswarnr   r9   __name__r   __setstate__r;   r   rd   )rM   r   pickle_versionr9   s      r$   r   zBaseEstimator.__setstate__t  s    :  ++J7"YY'9:FN,.'+~~'>'>0;1?	(G ' 	(MM  '	(s   ;B $B21B2c                     t         S rv   r   rw   s    r$   
_more_tagszBaseEstimator._more_tags  s    r&   c                     i }t        t        j                  | j                              D ]1  }t	        |d      s|j                  |       }|j                  |       3 |S )Nr   )reversedr    getmror9   r   r   rd   )rM   collected_tags
base_class	more_tagss       r$   	_get_tagszBaseEstimator._get_tags  sV    "7>>$..#ABJz<0 '11$7	%%i0 C r&   c           	      x   	 t        |      }|r|| _        yt        | d      sy|| j                  k7  r3t        d| d| j                  j
                   d| j                   d      y# t        $ rI}|s=t        | d      r1t        d| j                  j
                   d| j                   d      |Y d}~yd}~ww xY w)	a  Set the `n_features_in_` attribute, or check against it.

        Parameters
        ----------
        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`.
        n_features_in_z%X does not contain any features, but z is expecting z	 featuresNzX has z features, but z features as input.)r   r7   r   rk   r9   r   r   )rM   Xreset
n_featuresr@   s        r$   _check_n_featureszBaseEstimator._check_n_features  s    "	&q)J ",Dt-. ,,,ODNN4K4K3L M  $ 3 344GI  -+  		WT+;< ;~~../~**+96 	 		s   A' '	B90?B44B9c                   |r.t        |      }||| _        yt        | d      rt        | d       yt	        | dd      }t        |      }||y|0|.t        j                  d| j                  j                   d       y|0|.t        j                  d| j                  j                   d       yt        |      t        |      k7  st        j                  ||k7        rod}t        |      }t        |      }t        ||z
        }	t        ||z
        }
d }|	r|d	z  }| ||	      z  }|
r|d
z  }| ||
      z  }|
s|	s|dz  }t        |      y)a  Set or check the `feature_names_in_` attribute.

        .. versionadded:: 1.0

        Parameters
        ----------
        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`.
        Nfeature_names_in_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}t        |       D ]  \  }}||k\  r|dz  } |S |d| dz  } |S )Nr      z- ...
z- r   )	enumerate)namesoutputmax_n_namesirC   s        r$   	add_namesz5BaseEstimator._check_feature_names.<locals>.add_names   sT    (/GAtK')+ 4&m+F	  0
 r&   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   delattrrN   r   r   r9   r   r   npanyr2   rW   rk   )rM   r   r   feature_names_infitted_feature_namesX_feature_namesmessagefitted_feature_names_setX_feature_names_setunexpected_namesmissing_namesr   s               r$   _check_feature_namesz"BaseEstimator._check_feature_names  s   ( 1!4+)9&
 	 23 12&t-@$G,Q/'O,C&+?+GMM+DNN,C,C+D E! ! "';'GMMNN++,,JL  #$O(<< O3A
 V  (++?'@$"%o"6%&9<T&TU"#;>Q#QRM  @@9%566OO9]33 )9T W%%GA
r&   c                    | j                  ||       |6| j                         d   r#t        d| j                  j                   d      t        |t              xr |dk(  }|du xs t        |t              xr |dk(  }|r|rt        d      d| i}	i |	|}|s|s|r|}
n||r|s|}
nu||f}
np|s|rt        |fd	d
i|}
n]|r|st        |fi |}
nL|r6|\  }}d|vri |	|}t        |fd	d
i|}d|vri |	|}t        |fd	di|}nt        ||fi |\  }}||f}
|s%|j                  dd      r| j                  ||       |
S )ao  Validate input data and set or check the `n_features_in_` attribute.

        Parameters
        ----------
        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`, `check_array` is called on `X`. If the estimator's
              requires_y tag is True, then an error will be raised.
            - If `'no_validation'`, `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 `check_array` or `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 validate_X_y(). Else, it must be a tuple of kwargs
            to be used for calling 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.

        cast_to_ndarray : bool, default=True
            Cast `X` and `y` to ndarray with checks in `check_params`. If
            `False`, `X` and `y` are unchanged and only `feature_names_in_` and
            `n_features_in_` are checked.

        **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.
        )r   N
requires_yzThis z= estimator requires y to be passed, but the target y is None.no_validationz*Validation should be done on X, y or both.r#   
input_namer   y	ensure_2dT)r   r   rk   r9   r   r4   strr   r   r   getr   )rM   r   r   r   validate_separatelycast_to_ndarraycheck_paramsno_val_Xno_val_ydefault_check_paramsre   check_X_paramscheck_y_paramss                r$   _validate_datazBaseEstimator._validate_data  s   N 	!!!5!19),7//0 1E E 
 a%>!*>9K
1c 2 KqO7KIJJ +T2?.?,?(dha@C@<@Ch1--C"
 2E.n4%O(<%O%ONDcD^Dn4%O(<%O%ONDcD^D A661Q$CL,,[$?""1E"2
r&   c                 |    t        | j                  | j                  d      | j                  j                         y)aY  Validate types and values of constructor parameters

        The expected type and values must be defined in the `_parameter_constraints`
        class attribute, which is a dictionary `param_name: list of constraints`. See
        the docstring of `validate_parameter_constraints` for a description of the
        accepted constraints.
        Fr)   )caller_nameN)r   _parameter_constraintsr(   r9   r   rw   s    r$   _validate_paramszBaseEstimator._validate_params  s0     	'''OOO'//	
r&   c                 P    t               d   dk7  rt        d      | j                  S )a  HTML representation of estimator.

        This is redundant with the logic of `_repr_mimebundle_`. The latter
        should be favorted in the long term, `_repr_html_` is only
        implemented for consumers who do not interpret `_repr_mimbundle_`.
        displaydiagramzW_repr_html_ is only defined when the 'display' configuration option is set to 'diagram')r   r;   _repr_html_innerrw   s    r$   _repr_html_zBaseEstimator._repr_html_  s3     <	"i/  
 $$$r&   c                     t        |       S )zThis function is returned by the @property `_repr_html_` to make
        `hasattr(estimator, "_repr_html_") return `True` or `False` depending
        on `get_config()["display"]`.
        )r
   rw   s    r$   r   zBaseEstimator._repr_html_inner  s    
 #4((r&   c                 \    dt        |       i}t               d   dk(  rt        |       |d<   |S )z8Mime bundle used by jupyter kernels to display estimatorz
text/plainr   r   z	text/html)r8   r   r
   )rM   kwargsr   s      r$   _repr_mimebundle_zBaseEstimator._repr_mimebundle_  s3    T
+<	"i/"5d";F;r&   )T)i  )r   r   TFT)r   r   __qualname____doc__classmethodr\   r(   rm   r   r   r   r   r   r   r   r   r   r   propertyr   r   r   __classcell__)r9   s   @r$   rJ   rJ      s    )V 4 4<0*X)2h,( 	,\W&v 
!wr
 % %)r&   rJ   c                   "    e Zd ZdZdZddZd Zy)ClassifierMixina  Mixin class for all classifiers in scikit-learn.

    This mixin defines the following functionality:

    - `_estimator_type` class attribute defaulting to `"classifier"`;
    - `score` method that default to :func:`~sklearn.metrics.accuracy_score`.
    - enforce that `fit` requires `y` to be passed through the `requires_y` tag.

    Read more in the :ref:`User Guide <rolling_your_own_estimator>`.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.base import BaseEstimator, ClassifierMixin
    >>> # Mixin classes should always be on the left-hand side for a correct MRO
    >>> class MyEstimator(ClassifierMixin, BaseEstimator):
    ...     def __init__(self, *, param=1):
    ...         self.param = param
    ...     def fit(self, X, y=None):
    ...         self.is_fitted_ = True
    ...         return self
    ...     def predict(self, X):
    ...         return np.full(shape=X.shape[0], fill_value=self.param)
    >>> estimator = MyEstimator(param=1)
    >>> X = np.array([[1, 2], [2, 3], [3, 4]])
    >>> y = np.array([1, 0, 1])
    >>> estimator.fit(X, y).predict(X)
    array([1, 1, 1])
    >>> estimator.score(X, y)
    0.66...
    
classifierNc                 B    ddl m}  ||| j                  |      |      S )a  
        Return the mean accuracy on the given test data and labels.

        In multi-label classification, this is the subset accuracy
        which is a harsh metric since you require for each sample that
        each label set be correctly predicted.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
            Test samples.

        y : array-like of shape (n_samples,) or (n_samples, n_outputs)
            True labels for `X`.

        sample_weight : array-like of shape (n_samples,), default=None
            Sample weights.

        Returns
        -------
        score : float
            Mean accuracy of ``self.predict(X)`` w.r.t. `y`.
        r   )accuracy_scoresample_weight)metricsr   predict)rM   r   r   r   r   s        r$   scorezClassifierMixin.score  s    0 	,aaNNr&   c                 
    ddiS Nr   Tr,   rw   s    r$   r   zClassifierMixin._more_tags      d##r&   rv   r   r   r   r   _estimator_typer   r   r,   r&   r$   r   r     s    @ #OO8$r&   r   c                   "    e Zd ZdZdZddZd Zy)RegressorMixina  Mixin class for all regression estimators in scikit-learn.

    This mixin defines the following functionality:

    - `_estimator_type` class attribute defaulting to `"regressor"`;
    - `score` method that default to :func:`~sklearn.metrics.r2_score`.
    - enforce that `fit` requires `y` to be passed through the `requires_y` tag.

    Read more in the :ref:`User Guide <rolling_your_own_estimator>`.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.base import BaseEstimator, RegressorMixin
    >>> # Mixin classes should always be on the left-hand side for a correct MRO
    >>> class MyEstimator(RegressorMixin, BaseEstimator):
    ...     def __init__(self, *, param=1):
    ...         self.param = param
    ...     def fit(self, X, y=None):
    ...         self.is_fitted_ = True
    ...         return self
    ...     def predict(self, X):
    ...         return np.full(shape=X.shape[0], fill_value=self.param)
    >>> estimator = MyEstimator(param=0)
    >>> X = np.array([[1, 2], [2, 3], [3, 4]])
    >>> y = np.array([-1, 0, 1])
    >>> estimator.fit(X, y).predict(X)
    array([0, 0, 0])
    >>> estimator.score(X, y)
    0.0
    	regressorNc                 F    ddl m} | j                  |      } ||||      S )a  Return the coefficient of determination of the prediction.

        The coefficient of determination :math:`R^2` is defined as
        :math:`(1 - \frac{u}{v})`, where :math:`u` is the residual
        sum of squares ``((y_true - y_pred)** 2).sum()`` and :math:`v`
        is the total sum of squares ``((y_true - y_true.mean()) ** 2).sum()``.
        The best possible score is 1.0 and it can be negative (because the
        model can be arbitrarily worse). A constant model that always predicts
        the expected value of `y`, disregarding the input features, would get
        a :math:`R^2` score of 0.0.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
            Test samples. For some estimators this may be a precomputed
            kernel matrix or a list of generic objects instead with shape
            ``(n_samples, n_samples_fitted)``, where ``n_samples_fitted``
            is the number of samples used in the fitting for the estimator.

        y : array-like of shape (n_samples,) or (n_samples, n_outputs)
            True values for `X`.

        sample_weight : array-like of shape (n_samples,), default=None
            Sample weights.

        Returns
        -------
        score : float
            :math:`R^2` of ``self.predict(X)`` w.r.t. `y`.

        Notes
        -----
        The :math:`R^2` score used when calling ``score`` on a regressor uses
        ``multioutput='uniform_average'`` from version 0.23 to keep consistent
        with default value of :func:`~sklearn.metrics.r2_score`.
        This influences the ``score`` method of all the multioutput
        regressors (except for
        :class:`~sklearn.multioutput.MultiOutputRegressor`).
        r   )r2_scorer   )r   r  r   )rM   r   r   r   r  y_preds         r$   r   zRegressorMixin.score%  s$    R 	&a6??r&   c                 
    ddiS r   r,   rw   s    r$   r   zRegressorMixin._more_tagsS  r   r&   rv   r   r,   r&   r$   r  r    s    @ "O,@\$r&   r  c                   "    e Zd ZdZdZddZd Zy)ClusterMixinai  Mixin class for all cluster estimators in scikit-learn.

    - `_estimator_type` class attribute defaulting to `"clusterer"`;
    - `fit_predict` method returning the cluster labels associated to each sample.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.base import BaseEstimator, ClusterMixin
    >>> class MyClusterer(ClusterMixin, BaseEstimator):
    ...     def fit(self, X, y=None):
    ...         self.labels_ = np.ones(shape=(len(X),), dtype=np.int64)
    ...         return self
    >>> X = [[1, 2], [2, 3], [3, 4]]
    >>> MyClusterer().fit_predict(X)
    array([1, 1, 1])
    	clustererNc                 @     | j                   |fi | | j                  S )a  
        Perform clustering on `X` and returns cluster labels.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
            Input data.

        y : Ignored
            Not used, present for API consistency by convention.

        **kwargs : dict
            Arguments to be passed to ``fit``.

            .. versionadded:: 1.4

        Returns
        -------
        labels : ndarray of shape (n_samples,), dtype=np.int64
            Cluster labels.
        )fitlabels_)rM   r   r   r   s       r$   fit_predictzClusterMixin.fit_predictl  s!    0 	f||r&   c                 
    dg iS )Npreserves_dtyper,   rw   s    r$   r   zClusterMixin._more_tags  s    !2&&r&   rv   )r   r   r   r   r   r  r   r,   r&   r$   r	  r	  W  s    $ "O6'r&   r	  c                   2    e Zd ZdZed        Zd Zd Zd Zy)BiclusterMixina?  Mixin class for all bicluster estimators in scikit-learn.

    This mixin defines the following functionality:

    - `biclusters_` property that returns the row and column indicators;
    - `get_indices` method that returns the row and column indices of a bicluster;
    - `get_shape` method that returns the shape of a bicluster;
    - `get_submatrix` method that returns the submatrix corresponding to a bicluster.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.base import BaseEstimator, BiclusterMixin
    >>> class DummyBiClustering(BiclusterMixin, BaseEstimator):
    ...     def fit(self, X, y=None):
    ...         self.rows_ = np.ones(shape=(1, X.shape[0]), dtype=bool)
    ...         self.columns_ = np.ones(shape=(1, X.shape[1]), dtype=bool)
    ...         return self
    >>> X = np.array([[1, 1], [2, 1], [1, 0],
    ...               [4, 7], [3, 5], [3, 6]])
    >>> bicluster = DummyBiClustering().fit(X)
    >>> hasattr(bicluster, "biclusters_")
    True
    >>> bicluster.get_indices(0)
    (array([0, 1, 2, 3, 4, 5]), array([0, 1]))
    c                 2    | j                   | j                  fS )z{Convenient way to get row and column indicators together.

        Returns the ``rows_`` and ``columns_`` members.
        )rows_columns_rw   s    r$   biclusters_zBiclusterMixin.biclusters_  s     zz4==((r&   c                     | j                   |   }| j                  |   }t        j                  |      d   t        j                  |      d   fS )a  Row and column indices of the `i`'th bicluster.

        Only works if ``rows_`` and ``columns_`` attributes exist.

        Parameters
        ----------
        i : int
            The index of the cluster.

        Returns
        -------
        row_ind : ndarray, dtype=np.intp
            Indices of rows in the dataset that belong to the bicluster.
        col_ind : ndarray, dtype=np.intp
            Indices of columns in the dataset that belong to the bicluster.
        r   )r  r  r   nonzero)rM   r   rowscolumnss       r$   get_indiceszBiclusterMixin.get_indices  sF    " zz!}--"zz$"BJJw$7$:::r&   c                 H    | j                  |      }t        d |D              S )a-  Shape of the `i`'th bicluster.

        Parameters
        ----------
        i : int
            The index of the cluster.

        Returns
        -------
        n_rows : int
            Number of rows in the bicluster.

        n_cols : int
            Number of columns in the bicluster.
        c              3   2   K   | ]  }t        |        y wrv   )r   )r`   r   s     r$   rc   z+BiclusterMixin.get_shape.<locals>.<genexpr>  s     -WSVWs   )r  r1   )rM   r   indicess      r$   	get_shapezBiclusterMixin.get_shape  s%      ""1%-W---r&   c                     ddl m}  ||d      }| j                  |      \  }}||ddt        j                  f   |f   S )a   Return the submatrix corresponding to bicluster `i`.

        Parameters
        ----------
        i : int
            The index of the cluster.
        data : array-like of shape (n_samples, n_features)
            The data.

        Returns
        -------
        submatrix : ndarray of shape (n_rows, n_cols)
            The submatrix corresponding to bicluster `i`.

        Notes
        -----
        Works with sparse matrices. Only works if ``rows_`` and
        ``columns_`` attributes exist.
        r   )r   csr)accept_sparseN)utils.validationr   r  r   newaxis)rM   r   datar   row_indcol_inds         r$   get_submatrixzBiclusterMixin.get_submatrix  sE    ( 	24u5++A.GArzzM*G344r&   N)	r   r   r   r   r   r  r  r  r(  r,   r&   r$   r  r    s*    6 ) );*.&5r&   r  c                       e Zd ZdZddZy)TransformerMixina  Mixin class for all transformers in scikit-learn.

    This mixin defines the following functionality:

    - a `fit_transform` method that delegates to `fit` and `transform`;
    - a `set_output` method to output `X` as a specific container type.

    If :term:`get_feature_names_out` is defined, then :class:`BaseEstimator` will
    automatically wrap `transform` and `fit_transform` to follow the `set_output`
    API. See the :ref:`developer_api_set_output` for details.

    :class:`OneToOneFeatureMixin` and
    :class:`ClassNamePrefixFeaturesOutMixin` are helpful mixins for
    defining :term:`get_feature_names_out`.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.base import BaseEstimator, TransformerMixin
    >>> class MyTransformer(TransformerMixin, BaseEstimator):
    ...     def __init__(self, *, param=1):
    ...         self.param = param
    ...     def fit(self, X, y=None):
    ...         return self
    ...     def transform(self, X):
    ...         return np.full(shape=len(X), fill_value=self.param)
    >>> transformer = MyTransformer()
    >>> X = [[1, 2], [2, 3], [3, 4]]
    >>> transformer.fit_transform(X)
    array([1, 1, 1])
    Nc                 j   t               rc| j                         j                  d|j                               }|r2t	        j
                  d| j                  j                   dt               |" | j                  |fi |j                  |      S  | j                  ||fi |j                  |      S )a  
        Fit to data, then transform it.

        Fits transformer to `X` and `y` with optional parameters `fit_params`
        and returns a transformed version of `X`.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
            Input samples.

        y :  array-like of shape (n_samples,) or (n_samples, n_outputs),                 default=None
            Target values (None for unsupervised transformations).

        **fit_params : dict
            Additional fit parameters.

        Returns
        -------
        X_new : ndarray array of shape (n_samples, n_features_new)
            Transformed array.
        	transformmethodrn   This object (ah  ) has a `transform` method which consumes metadata, but `fit_transform` does not forward metadata to `transform`. Please implement a custom `fit_transform` method to forward metadata to `transform` as well. Alternatively, you can explicitly do `set_transform_request`and set all values to `False` to disable metadata routed to `transform`, if that's an option.)r   get_metadata_routingconsumeskeysr   r   r9   r   UserWarningr  r,  )rM   r   r   
fit_paramstransform_paramss        r$   fit_transformzTransformerMixin.fit_transform  s    F #88:CC":??+<  D    '(?(?'@ AX X   9488A,,66q99 488Aq/J/99!<<r&   rv   )r   r   r   r   r6  r,   r&   r$   r*  r*    s    @:=r&   r*  c                       e Zd ZdZddZy)OneToOneFeatureMixinap  Provides `get_feature_names_out` for simple transformers.

    This mixin assumes there's a 1-to-1 correspondence between input features
    and output features, such as :class:`~sklearn.preprocessing.StandardScaler`.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.base import OneToOneFeatureMixin
    >>> class MyEstimator(OneToOneFeatureMixin):
    ...     def fit(self, X, y=None):
    ...         self.n_features_in_ = X.shape[1]
    ...         return self
    >>> X = np.array([[1, 2], [3, 4]])
    >>> MyEstimator().fit(X).get_feature_names_out()
    array(['x0', 'x1'], dtype=object)
    Nc                 2    t        | d       t        | |      S )a  Get output feature names for transformation.

        Parameters
        ----------
        input_features : array-like of str or None, default=None
            Input features.

            - If `input_features` is `None`, then `feature_names_in_` is
              used as feature names in. If `feature_names_in_` is not defined,
              then the following input feature names are generated:
              `["x0", "x1", ..., "x(n_features_in_ - 1)"]`.
            - If `input_features` is an array-like, then `input_features` must
              match `feature_names_in_` if `feature_names_in_` is defined.

        Returns
        -------
        feature_names_out : ndarray of str objects
            Same as input features.
        r   )r   r   rM   input_featuress     r$   get_feature_names_outz*OneToOneFeatureMixin.get_feature_names_outc  s    ( 	./&t^<<r&   rv   r   r   r   r   r<  r,   r&   r$   r8  r8  P  s    $=r&   r8  c                       e Zd ZdZddZy)ClassNamePrefixFeaturesOutMixina  Mixin class for transformers that generate their own names by prefixing.

    This mixin is useful when the transformer needs to generate its own feature
    names out, such as :class:`~sklearn.decomposition.PCA`. For example, if
    :class:`~sklearn.decomposition.PCA` outputs 3 features, then the generated feature
    names out are: `["pca0", "pca1", "pca2"]`.

    This mixin assumes that a `_n_features_out` attribute is defined when the
    transformer is fitted. `_n_features_out` is the number of output features
    that the transformer will return in `transform` of `fit_transform`.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.base import ClassNamePrefixFeaturesOutMixin
    >>> class MyEstimator(ClassNamePrefixFeaturesOutMixin):
    ...     def fit(self, X, y=None):
    ...         self._n_features_out = X.shape[1]
    ...         return self
    >>> X = np.array([[1, 2], [3, 4]])
    >>> MyEstimator().fit(X).get_feature_names_out()
    array(['myestimator0', 'myestimator1'], dtype=object)
    Nc                 J    t        | d       t        | | j                  |      S )aF  Get output feature names for transformation.

        The feature names out will prefixed by the lowercased class name. For
        example, if the transformer outputs 3 features, then the feature names
        out are: `["class_name0", "class_name1", "class_name2"]`.

        Parameters
        ----------
        input_features : array-like of str or None, default=None
            Only used to validate feature names with the names seen in `fit`.

        Returns
        -------
        feature_names_out : ndarray of str objects
            Transformed feature names.
        _n_features_out)r;  )r   r   rA  r:  s     r$   r<  z5ClassNamePrefixFeaturesOutMixin.get_feature_names_out  s)    " 	/0.$&&~
 	
r&   rv   r=  r,   r&   r$   r?  r?  {  s    0
r&   r?  c                       e Zd ZdZdZddZy)DensityMixina  Mixin class for all density estimators in scikit-learn.

    This mixin defines the following functionality:

    - `_estimator_type` class attribute defaulting to `"DensityEstimator"`;
    - `score` method that default that do no-op.

    Examples
    --------
    >>> from sklearn.base import DensityMixin
    >>> class MyEstimator(DensityMixin):
    ...     def fit(self, X, y=None):
    ...         self.is_fitted_ = True
    ...         return self
    >>> estimator = MyEstimator()
    >>> hasattr(estimator, "score")
    True
    DensityEstimatorNc                      y)a=  Return the score of the model on the data `X`.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
            Test samples.

        y : Ignored
            Not used, present for API consistency by convention.

        Returns
        -------
        score : float
        Nr,   )rM   r   r   s      r$   r   zDensityMixin.score  s     	r&   rv   )r   r   r   r   r   r   r,   r&   r$   rC  rC    s    & )Or&   rC  c                       e Zd ZdZdZddZy)OutlierMixina  Mixin class for all outlier detection estimators in scikit-learn.

    This mixin defines the following functionality:

    - `_estimator_type` class attribute defaulting to `outlier_detector`;
    - `fit_predict` method that default to `fit` and `predict`.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.base import BaseEstimator, OutlierMixin
    >>> class MyEstimator(OutlierMixin):
    ...     def fit(self, X, y=None):
    ...         self.is_fitted_ = True
    ...         return self
    ...     def predict(self, X):
    ...         return np.ones(shape=len(X))
    >>> estimator = MyEstimator()
    >>> X = np.array([[1, 2], [2, 3], [3, 4]])
    >>> estimator.fit_predict(X)
    array([1., 1., 1.])
    outlier_detectorNc                     t               rc| j                         j                  d|j                               }|r2t	        j
                  d| j                  j                   dt                | j                  |fi |j                  |      S )a.  Perform fit on X and returns labels for X.

        Returns -1 for outliers and 1 for inliers.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            The input samples.

        y : Ignored
            Not used, present for API consistency by convention.

        **kwargs : dict
            Arguments to be passed to ``fit``.

            .. versionadded:: 1.4

        Returns
        -------
        y : ndarray of shape (n_samples,)
            1 for inliers, -1 for outliers.
        r   r-  r/  aY  ) has a `predict` method which consumes metadata, but `fit_predict` does not forward metadata to `predict`. Please implement a custom `fit_predict` method to forward metadata to `predict` as well.Alternatively, you can explicitly do `set_predict_request`and set all values to `False` to disable metadata routed to `predict`, if that's an option.)r   r0  r1  r2  r   r   r9   r   r3  r  r   )rM   r   r   r   r5  s        r$   r  zOutlierMixin.fit_predict  s    > #88:CC   D    '(?(?'@ A: :   txx$V$,,Q//r&   rv   )r   r   r   r   r   r  r,   r&   r$   rG  rG    s    . )O20r&   rG  c                       e Zd ZdZdgZy)MetaEstimatorMixina  Mixin class for all meta estimators in scikit-learn.

    This mixin defines the following functionality:

    - define `_required_parameters` that specify the mandatory `estimator` parameter.

    Examples
    --------
    >>> from sklearn.base import MetaEstimatorMixin
    >>> from sklearn.datasets import load_iris
    >>> from sklearn.linear_model import LogisticRegression
    >>> class MyEstimator(MetaEstimatorMixin):
    ...     def __init__(self, *, estimator=None):
    ...         self.estimator = estimator
    ...     def fit(self, X, y=None):
    ...         if self.estimator is None:
    ...             self.estimator_ = LogisticRegression()
    ...         else:
    ...             self.estimator_ = self.estimator
    ...         return self
    >>> X, y = load_iris(return_X_y=True)
    >>> estimator = MyEstimator().fit(X, y)
    >>> estimator.estimator_
    LogisticRegression()
    r#   N)r   r   r   r   _required_parametersr,   r&   r$   rK  rK  "  s    4 (=r&   rK  c                       e Zd ZdZd Zy)MultiOutputMixinz2Mixin to mark estimators that support multioutput.c                 
    ddiS )NmultioutputTr,   rw   s    r$   r   zMultiOutputMixin._more_tagsC  s    t$$r&   Nr   r   r   r   r   r,   r&   r$   rN  rN  @  s
    <%r&   rN  c                       e Zd ZdZd Zy)_UnstableArchMixinz=Mark estimators that are non-determinstic on 32bit or PowerPCc                 \    dt         xs# t        j                         j                  d      iS )Nnon_deterministic)ppcpowerpc)r   platformmachiner   rw   s    r$   r   z_UnstableArchMixin._more_tagsJ  s/     "A!,,-?@
 	
r&   NrQ  r,   r&   r$   rS  rS  G  s
    G
r&   rS  c                 "    t        | dd      dk(  S )a   Return True if the given estimator is (probably) a classifier.

    Parameters
    ----------
    estimator : object
        Estimator object to test.

    Returns
    -------
    out : bool
        True if estimator is a classifier and False otherwise.

    Examples
    --------
    >>> from sklearn.base import is_classifier
    >>> from sklearn.svm import SVC, SVR
    >>> classifier = SVC()
    >>> regressor = SVR()
    >>> is_classifier(classifier)
    True
    >>> is_classifier(regressor)
    False
    r   Nr   rN   r#   s    r$   is_classifierr]  Q  s    0 9/6,FFr&   c                 "    t        | dd      dk(  S )a  Return True if the given estimator is (probably) a regressor.

    Parameters
    ----------
    estimator : estimator instance
        Estimator object to test.

    Returns
    -------
    out : bool
        True if estimator is a regressor and False otherwise.

    Examples
    --------
    >>> from sklearn.base import is_regressor
    >>> from sklearn.svm import SVC, SVR
    >>> classifier = SVC()
    >>> regressor = SVR()
    >>> is_regressor(classifier)
    False
    >>> is_regressor(regressor)
    True
    r   Nr  r[  r\  s    r$   is_regressorr_  l  s    0 9/6+EEr&   c                 "    t        | dd      dk(  S )a  Return True if the given estimator is (probably) an outlier detector.

    Parameters
    ----------
    estimator : estimator instance
        Estimator object to test.

    Returns
    -------
    out : bool
        True if estimator is an outlier detector and False otherwise.
    r   NrH  r[  r\  s    r$   is_outlier_detectorra    s     9/6:LLLr&   c                       fd}|S )aC  Decorator to run the fit methods of estimators within context managers.

    Parameters
    ----------
    prefer_skip_nested_validation : bool
        If True, the validation of parameters of inner estimators or functions
        called during fit will be skipped.

        This is useful to avoid validating many times the parameters passed by the
        user from the public facing API. It's also useful to avoid validating
        parameters that we pass internally to inner functions that are guaranteed to
        be valid by the test suite.

        It should be set to True for most estimators, except for those that receive
        non-validated objects as parameters, such as meta-estimators that are given
        estimator objects.

    Returns
    -------
    decorated_fit : method
        The decorated fit method.
    c                 F     t        j                          fd       }|S )Nc                     t               d   }j                  dk(  xr t        |       }|s|s| j                          t	        xs |      5   | g|i |cd d d        S # 1 sw Y   y xY w)Nskip_parameter_validationpartial_fit)re  )r   r   r   r   r   )r#   argsr   global_skip_validationpartial_fit_and_fitted
fit_methodprefer_skip_nested_validations        r$   wrapperz0_fit_context.<locals>.decorator.<locals>.wrapper  sy    %/\2M%N" ##}4NI9N # *2H**,1K5K
 ")=d=f=  s   A%%A.)	functoolswraps)rj  rl  rk  s   ` r$   	decoratorz_fit_context.<locals>.decorator  s%    		$	> 
%	>$ r&   r,   )rk  ro  s   ` r$   _fit_contextrp    s    0, r&   )=r   r5   rm  r    rX  r   r   collectionsr   numpyr   r   r   _configr   r   
exceptionsr   utils._estimator_html_reprr	   r
   utils._metadata_requestsr   r   utils._param_validationr   utils._set_outputr   utils._tagsr   utils.fixesr   r#  r   r   r   r   r   r   r   r   r   r%   r"   rJ   r   r  r	  r  r*  r8  r?  rC  rG  rK  rN  rS  r]  r_  ra  rp  r,   r&   r$   <module>r{     s   D
     	  #   / 2 X J C . #
 
 
 " 35l ,0 7td/1C dN@$ @$FR$ R$j1' 1'hd5 d5N[= [=|(= (=V-
 -
`% %PL0 L0^) )<% %
 
G6F6M .r&   