Ë
    ÜÍ:j™6  ã                   óÒ   — d Z ddlmZmZ ddlZddlmZmZ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mZmZmZmZ dd	lmZmZmZmZ dd
lm Z  ddl!m"Z"m#Z#  G d„ deee«      Z$y)z
Sequential feature selection
é    )ÚIntegralÚRealN)ÚBaseEstimatorÚMetaEstimatorMixinÚ_fit_contextÚcloneÚis_classifier)ÚSelectorMixin)Ú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_datac                   ó.  ‡ — e Zd ZU dZ edg«      g edh«       eeddd¬«       eeddd	¬«      gd ee	ddd	¬«      g ed
dh«      gd e e
 e«       «      «      egdgdegdœZeed<   ddd
ddddœd„Z ed¬«      dd„«       Zd„ Zd„ Zˆ fd„Zd„ Zˆ xZS )ÚSequentialFeatureSelectoraA  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   é   Ú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                óf   — || _         || _        || _        || _        || _        || _        || _        y ©Nr&   )Úselfr'   r(   r)   r*   r+   r,   r-   s           úz/home/mcse/projects/srt_converter/srt-converter-venv/lib/python3.12/site-packages/sklearn/feature_selection/_sequential.pyÚ__init__z"SequentialFeatureSelector.__init__·   s6   € ð #ˆŒØ$8ˆÔ!ØˆŒØ"ˆŒØˆŒØˆŒØˆ�ó    F)Úprefer_skip_nested_validationc                 ó"  — t        || d«       | j                  «       }t        | |dd|j                  j                   ¬«      }|j
                  d   }| j                  dk(  r"| j                  �|dz
  | _        nˆ|dz  | _        n}t        | j                  t        «      r,| j                  |k\  rt        d«      ‚| j                  | _        n7t        | j                  t        «      rt        || j                  z  «      | _        | j                  �)| j                  d	k  r| j                  d
k(  rt        d«      ‚t        | j                   |t#        | j$                  «      ¬«      }t'        | j$                  «      }t)        j*                  |t,        ¬«      }| j                  dk(  s| j                  d
k(  r| j                  n|| j                  z
  }	t(        j.                   }
| j                  duxr | j                  dk(  }t1        «       rt3        | dfi |¤Ž t5        |	«      D ]9  } | j6                  |||||fi |¤Ž\  }}|r||
z
  | j                  k  r n	|}
d||<   Œ; | j                  dk(  r| }|| _        | j8                  j;                  «       | _        | S )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   Úcscé   )Ú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_nanr?   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)r2   ÚXÚyÚparamsÚtagsÚ
n_featuresr,   Úcloned_estimatorÚcurrent_maskÚn_iterationsÚ	old_scoreÚis_auto_selectÚ_Únew_feature_idxÚ	new_scores                  r3   r   zSequentialFeatureSelector.fitÊ   si  € ôD 	˜& $¨Ô.Ø×$Ñ$Ó&ˆÜØØØØ !Ø"&§/¡/×";Ñ";Ð;ô
ˆð —W‘W˜Q‘Zˆ
à×$Ñ$¨Ò.Ø�x‰xÐ#ð .8¸!©^�Õ*à-7¸1©_�Õ*Ü˜×1Ñ1´8Ô<Ø×(Ñ(¨JÒ6Ü Ð!MÓNÐNØ)-×)BÑ)BˆDÕ&Ü˜×1Ñ1´4Ô8Ü),¨Z¸$×:SÑ:SÑ-SÓ)TˆDÔ&à�8‰8Ð D§H¡H¨q¢L°T·^±^ÀyÒ5PÜØLóð ô �d—g‘g˜q¬]¸4¿>¹>Ó-JÔKˆä  §¡Ó0Ðô
 —x‘x j¼Ô=ˆð ×(Ñ(¨FÒ2°d·n±nÈ	Ò6Qð ×&Ò&à˜d×8Ñ8Ñ8ð 	ô —V‘V�Gˆ	ØŸ™¨Ð-ÒU°$×2KÑ2KÈvÑ2Uˆô
 ÔÜ˜D %Ñ2¨6Ò2Ü�|Ó$ò 	1ˆAØ)I¨×)IÑ)IØ  ! Q¨¨Lñ*Ø<Bñ*Ñ&ˆO˜Yñ  I°	Ñ$9¸T¿X¹XÒ#EÙà!ˆIØ,0ˆL˜Ò)ð	1ð �>‰>˜ZÒ'Ø(˜=ˆLà$ˆŒØ%)§]¡]×%6Ñ%6Ó%8ˆÔ"àˆr5   c           
      ó>  ‡— t        j                  | «      }i Š|D ]i  }|j                  «       }	d|	|<   | j                  dk(  r|	 }	|d d …|	f   }
t	        ||
||| j
                  | j                  |¬«      j                  «       ‰|<   Œk t        ‰ˆfd„¬«      }|‰|   fS )NTr$   )r,   r+   r-   rR   c                 ó   •— ‰|    S r1   © )Úfeature_idxÚscoress    €r3   ú<lambda>zGSequentialFeatureSelector._get_best_new_feature_score.<locals>.<lambda>I  s   ø€ ¸fÀ[Ñ>Q€ r5   )Úkey)	rH   ÚflatnonzeroÚcopyr*   r   r+   r-   ÚmeanÚmax)r2   r'   rP   rQ   r,   rV   rR   Úcandidate_feature_indicesr`   Úcandidate_maskÚX_newr[   ra   s               @r3   rM   z5SequentialFeatureSelector._get_best_new_feature_score2  s»   ø€ ô %'§N¡N°L°=Ó$AÐ!ØˆØ4ò 	ˆKØ)×.Ñ.Ó0ˆNØ*.ˆN˜;Ñ'Ø�~‰~ Ò+Ø"0 �Ø’a˜Ð'Ñ(ˆEÜ"1ØØØØØŸ™Ø—{‘{Øô#÷ ‰d‹fð �;Òð	ô ˜fÓ*QÔRˆØ  Ñ 7Ð7Ð7r5   c                 ó0   — t        | «       | j                  S r1   )r   rN   )r2   s    r3   Ú_get_support_maskz+SequentialFeatureSelector._get_support_maskL  s   € Ü˜ÔØ�}‰}Ðr5   c                 ó  •— t         ‰| �  «       }t        | j                  «      j                  j
                  |j                  _        t        | j                  «      j                  j                  |j                  _        |S r1   )ÚsuperrA   r   r'   rB   rC   Úsparse)r2   rS   Ú	__class__s     €r3   rA   z*SequentialFeatureSelector.__sklearn_tags__P  sW   ø€ Ü‰wÑ'Ó)ˆÜ$,¨T¯^©^Ó$<×$GÑ$G×$QÑ$Qˆ�‰Ô!Ü!)¨$¯.©.Ó!9×!DÑ!D×!KÑ!Kˆ�‰ÔØˆr5   c                 óÈ  — t        | ¬«      }|j                  | j                  t        «       j                  dd¬«      ¬«       |j                  t	        | j
                  t        | j                  «      ¬«      t        «       j                  dd¬«      ¬«       |j                  t        | j                  | j                  ¬«      t        «       j                  dd	¬«      ¬
«       |S )aj  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)Úsplitterru   )r+   Úscore)Úscorerru   )	r   Úaddr'   r   r   r,   r	   r   r+   )r2   Úrouters     r3   Úget_metadata_routingz.SequentialFeatureSelector.get_metadata_routingV  s»   € ô   dÔ+ˆØ�
‰
Ø—n‘nÜ(›?×.Ñ.°eÀEÐ.ÓJð 	ô 	
ð 	�
‰
Ü˜dŸg™g´-ÀÇÁÓ2OÔPÜ(›?×.Ñ.°eÀGÐ.ÓLð 	ô 	
ð 	�
‰
Ü  §¡¸¿¹ÔFÜ(›?×.Ñ.°eÀGÐ.ÓLð 	ô 	
ð ˆr5   r1   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r   r   r   r   Úsetr   Úcallabler.   ÚdictÚ__annotations__r4   r   r   rM   rl   rA   r|   Ú__classcell__)rp   s   @r3   r   r   "   sé   ø… ñDñN ! % Ó)Ð*á˜�xÓ Ù�Z  A¨gÔ6Ù�X˜q $¨yÔ9ð!
ð
 ‘h˜t T¨4¸	ÔBÐCÙ  )¨ZÐ!8Ó9Ð:Ø™*¡SÑ)9Ó);Ó%<Ó=¸xÐHØˆmØ˜Ð"ñ$Ð˜Dó ð$ $ØØØØØôñ& à&+ôòbó	ðbòH8ò4ôör5   r   )%r€   Únumbersr   r   ÚnumpyrH   Úsklearn.baser   r   r   r   r	   Úsklearn.feature_selection._baser
   Úsklearn.metricsr   r   Úsklearn.model_selectionr   r   Ú sklearn.utils._metadata_requestsr   r   r   r   r   Úsklearn.utils._param_validationr   r   r   r   Úsklearn.utils._tagsr   Úsklearn.utils.validationr   r   r   r_   r5   r3   ú<module>r�      sS   ðñ÷ #ã ÷õ õ :ß ;ß =÷õ ÷ YÓ XÝ (ß CôO Ð/AÀ=õ Or5   