
    -iP6                         S r SSKJrJr  SSKrSSKJrJrJ	r	J
r
Jr  SSKJrJr  SSKJrJr  SSKJrJrJrJrJr  SS	KJrJrJrJr  SS
KJr  SSKJ r J!r!  SSK"J#r#   " S S\#\\5      r$g)z
Sequential feature selection
    )IntegralRealN   )BaseEstimatorMetaEstimatorMixin_fit_contextcloneis_classifier)check_scoringget_scorer_names)check_cvcross_val_score)MetadataRouterMethodMapping_raise_for_params_routing_enabledprocess_routing)
HasMethodsInterval
RealNotInt
StrOptions)get_tags)check_is_fittedvalidate_data   )SelectorMixinc                   $  ^  \ rS rSr% Sr\" S/5      /\" S15      \" \SSSS9\" \	SS	S
S9/S	\" \
S	S	S
S9/\" SS15      /S	\" \" \" 5       5      5      \/S/S	\	/S.r\\S'   SS	SS	SS	S.S jr\" SS9SS j5       rS rS rU 4S jrS rSrU =r$ )SequentialFeatureSelector   a  Transformer that performs Sequential Feature Selection.

This Sequential Feature Selector adds (forward selection) or
removes (backward selection) features to form a feature subset in a
greedy fashion. At each stage, this estimator chooses the best feature to
add or remove based on the cross-validation score of an estimator. In
the case of unsupervised learning, this Sequential Feature Selector
looks only at the features (X), not the desired outputs (y).

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

.. versionadded:: 0.24

Parameters
----------
estimator : estimator instance
    An unfitted estimator.

n_features_to_select : "auto", int or float, default="auto"
    If `"auto"`, the behaviour depends on the `tol` parameter:

    - if `tol` is not `None`, then features are selected while the score
      change does not exceed `tol`.
    - otherwise, half of the features are selected.

    If integer, the parameter is the absolute number of features to select.
    If float between 0 and 1, it is the fraction of features to select.

    .. versionadded:: 1.1
       The option `"auto"` was added in version 1.1.

    .. versionchanged:: 1.3
       The default changed from `"warn"` to `"auto"` in 1.3.

tol : float, default=None
    If the score is not incremented by at least `tol` between two
    consecutive feature additions or removals, stop adding or removing.

    `tol` can be negative when removing features using `direction="backward"`.
    `tol` is required to be strictly positive when doing forward selection.
    It can be useful to reduce the number of features at the cost of a small
    decrease in the score.

    `tol` is enabled only when `n_features_to_select` is `"auto"`.

    .. versionadded:: 1.1

direction : {'forward', 'backward'}, default='forward'
    Whether to perform forward selection or backward selection.

scoring : str or callable, default=None
    Scoring method to use for cross-validation. Options:

    - str: see :ref:`scoring_string_names` for options.
    - callable: a scorer callable object (e.g., function) with signature
      ``scorer(estimator, X, y)`` that returns a single value.
      See :ref:`scoring_callable` for details.
    - `None`: the `estimator`'s
      :ref:`default evaluation criterion <scoring_api_overview>` is used.

cv : int, cross-validation generator or an iterable, default=None
    Determines the cross-validation splitting strategy.
    Possible inputs for cv are:

    - None, to use the default 5-fold cross validation,
    - integer, to specify the number of folds in a `(Stratified)KFold`,
    - :term:`CV splitter`,
    - An iterable yielding (train, test) splits as arrays of indices.

    For integer/None inputs, if the estimator is a classifier and ``y`` is
    either binary or multiclass,
    :class:`~sklearn.model_selection.StratifiedKFold` is used. In all other
    cases, :class:`~sklearn.model_selection.KFold` is used. These splitters
    are instantiated with `shuffle=False` so the splits will be the same
    across calls.

    Refer :ref:`User Guide <cross_validation>` for the various
    cross-validation strategies that can be used here.

n_jobs : int, default=None
    Number of jobs to run in parallel. When evaluating a new feature to
    add or remove, the cross-validation procedure is parallel over the
    folds.
    ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
    ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
    for more details.

Attributes
----------
n_features_in_ : int
    Number of features seen during :term:`fit`. Only defined if the
    underlying estimator exposes such an attribute when fit.

    .. versionadded:: 0.24

feature_names_in_ : ndarray of shape (`n_features_in_`,)
    Names of features seen during :term:`fit`. Defined only when `X`
    has feature names that are all strings.

    .. versionadded:: 1.0

n_features_to_select_ : int
    The number of features that were selected.

support_ : ndarray of shape (n_features,), dtype=bool
    The mask of selected features.

See Also
--------
GenericUnivariateSelect : Univariate feature selector with configurable
    strategy.
RFE : Recursive feature elimination based on importance weights.
RFECV : Recursive feature elimination based on importance weights, with
    automatic selection of the number of features.
SelectFromModel : Feature selection based on thresholds of importance
    weights.

Examples
--------
>>> from sklearn.feature_selection import SequentialFeatureSelector
>>> from sklearn.neighbors import KNeighborsClassifier
>>> from sklearn.datasets import load_iris
>>> X, y = load_iris(return_X_y=True)
>>> knn = KNeighborsClassifier(n_neighbors=3)
>>> sfs = SequentialFeatureSelector(knn, n_features_to_select=3)
>>> sfs.fit(X, y)
SequentialFeatureSelector(estimator=KNeighborsClassifier(n_neighbors=3),
                          n_features_to_select=3)
>>> sfs.get_support()
array([ True, False,  True,  True])
>>> sfs.transform(X).shape
(150, 3)
fitautor   r   right)closedNneitherforwardbackward	cv_object	estimatorn_features_to_selecttol	directionscoringcvn_jobs_parameter_constraints   )r*   r+   r,   r-   r.   r/   c                X    Xl         X l        X0l        X@l        XPl        X`l        Xpl        g Nr(   )selfr)   r*   r+   r,   r-   r.   r/   s           X/var/www/html/venv/lib/python3.13/site-packages/sklearn/feature_selection/_sequential.py__init__"SequentialFeatureSelector.__init__   s(     #$8!"    F)prefer_skip_nested_validationc                 R   [        X0S5        U R                  5       n[        U USSUR                  R                  (       + S9nUR
                  S   nU R                  S:X  a#  U R                  b  US-
  U l        OUS-  U l        O[        U R                  [        5      (       a-  U R                  U:  a  [        S5      eU R                  U l        O;[        U R                  [        5      (       a  [        XPR                  -  5      U l        U R                  b+  U R                  S	:  a  U R                  S
:X  a  [        S5      e[        U R                   U[#        U R$                  5      S9n['        U R$                  5      n[(        R*                  " U[,        S9nU R                  S:X  d  U R                  S
:X  a  U R                  OXPR                  -
  n	[(        R.                  * n
U R                  SL=(       a    U R                  S:H  n[1        5       (       a  [3        U S40 UD6  [5        U	5       H;  nU R6                  " XqX&U40 UD6u  pU(       a  X-
  U R                  :  a    O
Un
SX'   M=     U R                  S:X  a  U) nXl        U R8                  R;                  5       U l        U $ )a.  Learn the features to select from X.

Parameters
----------
X : array-like of shape (n_samples, n_features)
    Training vectors, where `n_samples` is the number of samples and
    `n_features` is the number of predictors.

y : array-like of shape (n_samples,), default=None
    Target values. This parameter may be ignored for
    unsupervised learning.

**params : dict, default=None
    Parameters to be passed to the underlying `estimator`, `cv`
    and `scorer` objects.

    .. versionadded:: 1.6

        Only available if `enable_metadata_routing=True`,
        which can be set by using
        ``sklearn.set_config(enable_metadata_routing=True)``.
        See :ref:`Metadata Routing User Guide <metadata_routing>` for
        more details.

Returns
-------
self : object
    Returns the instance itself.
r    cscr   )accept_sparseensure_min_featuresensure_all_finiter   r!   Nz*n_features_to_select must be < n_features.r   r%   z:tol must be strictly positive when doing forward selection
classifier)shapedtypeTr&   )r   __sklearn_tags__r   
input_tags	allow_nanrA   r*   r+   n_features_to_select_
isinstancer   
ValueErrorr   intr,   r   r.   r
   r)   r	   npzerosboolinfr   r   range_get_best_new_feature_scoresupport_sum)r4   Xyparamstags
n_featuresr.   cloned_estimatorcurrent_maskn_iterations	old_scoreis_auto_select_new_feature_idx	new_scores                  r5   r    SequentialFeatureSelector.fit   sY   D 	&.$$& !"&//";";;
 WWQZ
$$.xx# .8!^*-71_*118<<((J6 !MNN)-)B)BD&11488),Z:S:S-S)TD&88DHHqLT^^y5PL  dggq]4>>-JK 0
 xxj= ((F2dnn	6Q &&888 	 VVG	-U$2K2Kv2U
 D%262|$A)-)I)I QL*<B*&O I$9TXX#E!I,0L) % >>Z'(=L$%)]]%6%6%8"r8   c                 :  ^ [         R                  " U) 5      n0 mU Hg  nUR                  5       n	SX'   U R                  S:X  a  U	) n	US S 2U	4   n
[	        UU
UUU R
                  U R                  US9R                  5       TU'   Mi     [        TU4S jS9nUTU   4$ )NTr&   )r.   r-   r/   rT   c                    > TU    $ r3    )feature_idxscoress    r5   <lambda>GSequentialFeatureSelector._get_best_new_feature_score.<locals>.<lambda>C  s
    f[>Qr8   )key)	rJ   flatnonzerocopyr,   r   r-   r/   meanmax)r4   r)   rR   rS   r.   rX   rT   candidate_feature_indicesrc   candidate_maskX_newr]   rd   s               @r5   rO   5SequentialFeatureSelector._get_best_new_feature_score,  s     %'NNL=$A!4K)..0N*.N'~~+"0a'(E"1{{# df ; 5 f*QR 777r8   c                 0    [        U 5        U R                  $ r3   )r   rP   )r4   s    r5   _get_support_mask+SequentialFeatureSelector._get_support_maskF  s    }}r8   c                   > [         TU ]  5       n[        U R                  5      R                  R
                  UR                  l        [        U R                  5      R                  R                  UR                  l        U$ r3   )superrC   r   r)   rD   rE   sparse)r4   rU   	__class__s     r5   rC   *SequentialFeatureSelector.__sklearn_tags__J  sW    w')$,T^^$<$G$G$Q$Q!!)$..!9!D!D!K!Kr8   c                    [        U R                  R                  S9nUR                  U R                  [        5       R                  SSS9S9  UR                  [        U R                  [        U R                  5      S9[        5       R                  SSS9S9  UR                  [        U R                  U R                  S9[        5       R                  SS	S9S
9  U$ )a"  Get metadata routing of this object.

Please check :ref:`User Guide <metadata_routing>` on how the routing
mechanism works.

.. versionadded:: 1.6

Returns
-------
routing : MetadataRouter
    A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating
    routing information.
)ownerr    )callercallee)r)   method_mappingr?   split)splitterr|   )r-   score)scorerr|   )r   rv   __name__addr)   r   r   r.   r
   r   r-   )r4   routers     r5   get_metadata_routing.SequentialFeatureSelector.get_metadata_routingP  s      dnn&=&=>

nn(?..eE.J 	 	
 	

dgg-2OP(?..eG.L 	 	
 	

 F(?..eG.L 	 	
 r8   )	r.   r,   r)   r*   rF   r/   r-   rP   r+   r3   )r   
__module____qualname____firstlineno____doc__r   r   r   r   r   r   setr   callabler0   dict__annotations__r6   r   r    rO   rq   rC   r   __static_attributes____classcell__)rv   s   @r5   r   r      s    DN !%)*x ZAg6Xq$y9!

 htT4	BC )Z!89:*S)9);%<=xHm"$D $ $& &+b	bH84 r8   r   )%r   numbersr   r   numpyrJ   baser   r   r   r	   r
   metricsr   r   model_selectionr   r   utils._metadata_requestsr   r   r   r   r   utils._param_validationr   r   r   r   utils._tagsr   utils.validationr   r   _baser   r   rb   r8   r5   <module>r      sM    #  X X 5 7  S R " =  O/A= Or8   