
    0PhV                         d dl Z d dlmZmZ d dl mZ d dlZddlmZm	Z	m
Z
mZmZ ddlmZmZmZ ddlmZmZmZm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 m!Z! dgZ" G d de	e
e          Z#dS )    N)IntegralReal)warn   )BaseEstimatorClassifierMixinMetaEstimatorMixin_fit_contextclone)Bunchget_tags	safe_mask)
HasMethodsHiddenInterval
StrOptions)MetadataRouterMethodMapping_raise_for_params_routing_enabledprocess_routing)available_if)_estimator_hascheck_is_fittedvalidate_dataSelfTrainingClassifierc                   v    e Zd ZU dZd edg          g edg           e edh                    g eeddd          g ed	d
h          g ee	ddd          g ee	ddd          dgdgdZ
eed<   	 	 	 	 	 	 	 d#dZd Z ed          d             Z e ed                    d             Z e ed                    d             Z e ed                    d             Z e ed                    d             Z e ed                    d              Zd! Z fd"Z xZS )$r   a  Self-training classifier.

    This :term:`metaestimator` allows a given supervised classifier to function as a
    semi-supervised classifier, allowing it to learn from unlabeled data. It
    does this by iteratively predicting pseudo-labels for the unlabeled data
    and adding them to the training set.

    The classifier will continue iterating until either max_iter is reached, or
    no pseudo-labels were added to the training set in the previous iteration.

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

    Parameters
    ----------
    estimator : estimator object
        An estimator object implementing `fit` and `predict_proba`.
        Invoking the `fit` method will fit a clone of the passed estimator,
        which will be stored in the `estimator_` attribute.

        .. versionadded:: 1.6
            `estimator` was added to replace `base_estimator`.

    base_estimator : estimator object
        An estimator object implementing `fit` and `predict_proba`.
        Invoking the `fit` method will fit a clone of the passed estimator,
        which will be stored in the `estimator_` attribute.

        .. deprecated:: 1.6
            `base_estimator` was deprecated in 1.6 and will be removed in 1.8.
            Use `estimator` instead.

    threshold : float, default=0.75
        The decision threshold for use with `criterion='threshold'`.
        Should be in [0, 1). When using the `'threshold'` criterion, a
        :ref:`well calibrated classifier <calibration>` should be used.

    criterion : {'threshold', 'k_best'}, default='threshold'
        The selection criterion used to select which labels to add to the
        training set. If `'threshold'`, pseudo-labels with prediction
        probabilities above `threshold` are added to the dataset. If `'k_best'`,
        the `k_best` pseudo-labels with highest prediction probabilities are
        added to the dataset. When using the 'threshold' criterion, a
        :ref:`well calibrated classifier <calibration>` should be used.

    k_best : int, default=10
        The amount of samples to add in each iteration. Only used when
        `criterion='k_best'`.

    max_iter : int or None, default=10
        Maximum number of iterations allowed. Should be greater than or equal
        to 0. If it is `None`, the classifier will continue to predict labels
        until no new pseudo-labels are added, or all unlabeled samples have
        been labeled.

    verbose : bool, default=False
        Enable verbose output.

    Attributes
    ----------
    estimator_ : estimator object
        The fitted estimator.

    classes_ : ndarray or list of ndarray of shape (n_classes,)
        Class labels for each output. (Taken from the trained
        `estimator_`).

    transduction_ : ndarray of shape (n_samples,)
        The labels used for the final fit of the classifier, including
        pseudo-labels added during fit.

    labeled_iter_ : ndarray of shape (n_samples,)
        The iteration in which each sample was labeled. When a sample has
        iteration 0, the sample was already labeled in the original dataset.
        When a sample has iteration -1, the sample was not labeled in any
        iteration.

    n_features_in_ : int
        Number of features seen during :term:`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_iter_ : int
        The number of rounds of self-training, that is the number of times the
        base estimator is fitted on relabeled variants of the training set.

    termination_condition_ : {'max_iter', 'no_change', 'all_labeled'}
        The reason that fitting was stopped.

        - `'max_iter'`: `n_iter_` reached `max_iter`.
        - `'no_change'`: no new labels were predicted.
        - `'all_labeled'`: all unlabeled samples were labeled before `max_iter`
          was reached.

    See Also
    --------
    LabelPropagation : Label propagation classifier.
    LabelSpreading : Label spreading model for semi-supervised learning.

    References
    ----------
    :doi:`David Yarowsky. 1995. Unsupervised word sense disambiguation rivaling
    supervised methods. In Proceedings of the 33rd annual meeting on
    Association for Computational Linguistics (ACL '95). Association for
    Computational Linguistics, Stroudsburg, PA, USA, 189-196.
    <10.3115/981658.981684>`

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn import datasets
    >>> from sklearn.semi_supervised import SelfTrainingClassifier
    >>> from sklearn.svm import SVC
    >>> rng = np.random.RandomState(42)
    >>> iris = datasets.load_iris()
    >>> random_unlabeled_points = rng.rand(iris.target.shape[0]) < 0.3
    >>> iris.target[random_unlabeled_points] = -1
    >>> svc = SVC(probability=True, gamma="auto")
    >>> self_training_model = SelfTrainingClassifier(svc)
    >>> self_training_model.fit(iris.data, iris.target)
    SelfTrainingClassifier(...)
    Nfit
deprecatedg        g      ?left)closed	thresholdk_best   r   verbose)	estimatorbase_estimatorr"   	criterionr#   max_iterr%   _parameter_constraints      ?
   Fc                 h    || _         || _        || _        || _        || _        || _        || _        d S N)r&   r"   r(   r#   r)   r%   r'   )selfr&   r'   r"   r(   r#   r)   r%   s           f/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/sklearn/semi_supervised/_self_training.py__init__zSelfTrainingClassifier.__init__   s>     #""  -    c                 *   | j         5| j        dk    r*t          | j                  }t          dt                     nV| j         | j        dk    rt          d          | j         | j        dk    rt          d          t          | j                   }|S )zGet the estimator.

        Returns
        -------
        estimator_ : estimator object
            The cloned estimator object.
        Nr   zg`base_estimator` has been deprecated in 1.6 and will be removed in 1.8. Please use `estimator` instead.zFYou must pass an estimator to SelfTrainingClassifier. Use `estimator`.zLYou must pass only one estimator to SelfTrainingClassifier. Use `estimator`.)r&   r'   r   r   FutureWarning
ValueError)r/   
estimator_s     r0   _get_estimatorz%SelfTrainingClassifier._get_estimator   s     >!d&9\&I&It233J?     ^#(;|(K(K$   ^'D,?<,O,O$  
 t~..Jr2   )prefer_skip_nested_validationc                 
   t          || d           |                                 | _        t          | ||g dd          \  }}|j        j        dv rt          d          |dk    }t          j        |          rt          j
        dt                     | j        d	k    rE| j        |j        d
         t          j        |          z
  k    rt          j
        dt                     t!                      rt#          | dfi |}nt%          t%          i                     }t          j        |          | _        t          j        |d          | _        d
| j        |<   d
| _        t          j        |          s
| j        | j        | j        k     r| xj        dz  c_         | j        j        |t5          ||                   | j        |         fi |j        j         | j                            |t5          ||                              }| j        j        t          j        |d                   }t          j        |d          }| j        dk    r|| j         k    }	nktC          | j        |j        d
                   }
|
|j        d
         k    rt          j"        |tF                    }	nt          j$        | |
          d|
         }	t          j%        |           d
         |	         }||	         | j        |<   d||<   | j        | j        |<   |j        d
         d
k    rd| _&        nZ| j'        r&tQ          d| j         d|j        d
          d           t          j        |          s| j        | j        | j        k     | j        | j        k    rd| _&        t          j        |          rd| _&         | j        j        |t5          ||                   | j        |         fi |j        j         | j        j        | _        | S )av  
        Fit self-training classifier using `X`, `y` as training data.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            Array representing the data.

        y : {array-like, sparse matrix} of shape (n_samples,)
            Array representing the labels. Unlabeled samples should have the
            label -1.

        **params : dict
            Parameters to pass to the underlying estimators.

            .. 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
            Fitted estimator.
        r   )csrcsclildokF)accept_sparseensure_all_finite)USz~y has dtype string. If you wish to predict on string targets, use dtype object, and use -1 as the label for unlabeled samples.zy contains no unlabeled samplesr#   r   zsk_best is larger than the amount of unlabeled samples. All unlabeled samples will be labeled in the first iteration)r   r&   Nr$   )axisr"   )dtypeT	no_changezEnd of iteration z, added z new labels.r)   all_labeled))r   r7   r6   r   rE   kindr5   npallwarningsr   UserWarningr(   r#   shapesumr   r   r   copytransduction_	full_likelabeled_iter_n_iter_r)   r   r   r&   predict_probaclasses_argmaxmaxr"   min	ones_likeboolargpartitionnonzerotermination_condition_r%   print)r/   Xyparams	has_labelrouted_paramsprobpred	max_probaselectedn_to_selectselected_fulls               r0   r   zSelfTrainingClassifier.fit   sC   @ 	&$...--// 666#
 
 
1 7<:%%7   G	6) 	JM;[III>X%%K!'!*rvi'8'8888M*     	;+D%BB6BBMM!EbMMM:::MWQZZ\!R00()9%&## +	M!T\DM%A%ALLALLDO)Ay))*"9-   )-   ?009Q
3K3K1LMMD?+BId,C,C,CDDt!,,,I ~,,$t~5!$+yq/ABB)/!"444!|ITBBBHH  "	z;GGUH J	z2215h?M 15XD}-'+Im$04D}-"1%**.9+| C C C+1!4C C C  Q &## +	M!T\DM%A%AX <4=((*4D'6) 	8*7D'i9%%&y)	
 	
 %)	
 	
 	

 0r2   predictc                    t          |            t          || d           t                      rt          | dfi |}nt	          t	          i                     }t          | |ddd          } | j        j        |fi |j        j        S )a  Predict the classes of `X`.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            Array representing the data.

        **params : dict of str -> object
            Parameters to pass to the underlying estimator's ``predict`` method.

            .. 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
        -------
        y : ndarray of shape (n_samples,)
            Array with predicted labels.
        rj   )rj   rC   TFr>   r?   reset)	r   r   r   r   r   r   r6   rj   r&   r/   r_   ra   rc   s       r0   rj   zSelfTrainingClassifier.predicts  s    0 	&$	222 	?+D)FFvFFMM!E",=,=,=>>>M#
 
 
 't&qLLM,C,KLLLr2   rT   c                    t          |            t          || d           t                      rt          | dfi |}nt	          t	          i                     }t          | |ddd          } | j        j        |fi |j        j        S )a%  Predict probability for each possible outcome.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            Array representing the data.

        **params : dict of str -> object
            Parameters to pass to the underlying estimator's
            ``predict_proba`` method.

            .. 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
        -------
        y : ndarray of shape (n_samples, n_features)
            Array with prediction probabilities.
        rT   )rT   rC   TFrl   )	r   r   r   r   r   r   r6   rT   r&   rn   s       r0   rT   z$SelfTrainingClassifier.predict_proba  s    2 	&$888 	E+D/LLVLLMM!E,C,C,CDDDM#
 
 
 -t,QXX-2I2WXXXr2   decision_functionc                    t          |            t          || d           t                      rt          | dfi |}nt	          t	          i                     }t          | |ddd          } | j        j        |fi |j        j        S )a4  Call decision function of the `estimator`.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            Array representing the data.

        **params : dict of str -> object
            Parameters to pass to the underlying estimator's
            ``decision_function`` method.

            .. 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
        -------
        y : ndarray of shape (n_samples, n_features)
            Result of the decision function of the `estimator`.
        rp   )rp   rC   TFrl   )	r   r   r   r   r   r   r6   rp   r&   rn   s       r0   rp   z(SelfTrainingClassifier.decision_function      2 	&$(;<<< 	I+D2EPPPPMM!EB,G,G,GHHHM#
 
 
 1t0
 
(:
 
 	
r2   predict_log_probac                    t          |            t          || d           t                      rt          | dfi |}nt	          t	          i                     }t          | |ddd          } | j        j        |fi |j        j        S )a1  Predict log probability for each possible outcome.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            Array representing the data.

        **params : dict of str -> object
            Parameters to pass to the underlying estimator's
            ``predict_log_proba`` method.

            .. 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
        -------
        y : ndarray of shape (n_samples, n_features)
            Array with log prediction probabilities.
        rs   )rs   rC   TFrl   )	r   r   r   r   r   r   r6   rs   r&   rn   s       r0   rs   z(SelfTrainingClassifier.predict_log_proba  rr   r2   scorec                    t          |            t          || d           t                      rt          | dfi |}nt	          t	          i                     }t          | |ddd          } | j        j        ||fi |j        j        S )aB  Call score on the `estimator`.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            Array representing the data.

        y : array-like of shape (n_samples,)
            Array representing the labels.

        **params : dict of str -> object
            Parameters to pass to the underlying estimator's ``score`` method.

            .. 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
        -------
        score : float
            Result of calling score on the `estimator`.
        ru   )ru   rC   TFrl   )	r   r   r   r   r   r   r6   ru   r&   )r/   r_   r`   ra   rc   s        r0   ru   zSelfTrainingClassifier.score"  s    6 	&$000 	=+D'DDVDDMM!EOOO<<<M#
 
 
 %t$QKK]-D-JKKKr2   c                    t          | j        j                  }|                    | j        t                                          dd                              dd                              dd                              dd                              dd                              dd                              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   )calleecallerru   rj   rT   rp   rs   )r&   method_mapping)r   	__class____name__addr&   r   )r/   routers     r0   get_metadata_routingz+SelfTrainingClassifier.get_metadata_routingO  s      dn&=>>>

nE%00GE22Ii88OODD/8KLL/8KLLGG44 	 	
 	
 	
 r2   c                     t                                                      }| j        (t          | j                  j        j        |j        _        |S r.   )super__sklearn_tags__r&   r   
input_tagssparse)r/   tagsr|   s     r0   r   z'SelfTrainingClassifier.__sklearn_tags__m  s?    ww''))>%%-dn%=%=%H%ODO"r2   )Nr   r+   r"   r,   r,   F)r}   
__module____qualname____doc__r   r   r   r   r   r   r*   dict__annotations__r1   r7   r
   r   r   r   rj   rT   rp   rs   ru   r   r   __classcell__)r|   s   @r0   r   r       s        ~ ~H JJw//0 JwF::|n--..
 htS#f===> j+x!899:8Haf===>Xh4???F;$ $D   & #- - - -(     D \&+  E E	 EN \..++,,'M 'M -,'MR \..1122(Y (Y 32(YT \..!45566*
 *
 76*
X \..!45566*
 *
 76*
X \..))***L *L +**LX  <        r2   )$rK   numbersr   r   r   numpyrI   baser   r   r	   r
   r   utilsr   r   r   utils._param_validationr   r   r   r   utils.metadata_routingr   r   r   r   r   utils.metaestimatorsr   utils.validationr   r   r   __all__r    r2   r0   <module>r      s    " " " " " " " "                        / . . . . . . . . . N N N N N N N N N N N N              0 / / / / / M M M M M M M M M M#
$R	 R	 R	 R	 R	_.@- R	 R	 R	 R	 R	r2   