
    {Kg8                         d dl Z d dlmZmZ d dlZddlmZmZm	Z	m
Z
 ddlmZ ddlmZmZmZ ddlmZ ddlmZ dd	lmZ d
gZd Z G d d
eee      Zy)    N)IntegralReal   )BaseEstimatorMetaEstimatorMixin_fit_contextclone)	safe_mask)
HasMethodsInterval
StrOptions)_RoutingNotSupportedMixin)available_if)check_is_fittedSelfTrainingClassifierc                       fd}|S )a2  Check if we can delegate a method to the underlying estimator.

    First, we check the fitted `base_estimator_` if available, otherwise we check
    the unfitted `base_estimator`. We raise the original `AttributeError` if
    `attr` does not exist. This function is used together with `available_if`.
    c                 x    t        | d      rt        | j                         yt        | j                         y)Nbase_estimator_T)hasattrgetattrr   base_estimator)selfattrs    j/home/alanp/www/video.onchill/myenv/lib/python3.12/site-packages/sklearn/semi_supervised/_self_training.pycheckz_estimator_has.<locals>.check   s8    4*+D(($/  D''.     )r   r   s   ` r   _estimator_hasr      s     Lr   c            
          e Zd ZU dZdZ edg      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 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y)r   aC  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
    ----------
    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 `base_estimator_` attribute.

    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
    ----------
    base_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
        `base_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(...)
    
classifierfitg        g      ?left)closed	thresholdk_best   Nr   verboser   r$   	criterionr%   max_iterr'   _parameter_constraintsFc                 X    || _         || _        || _        || _        || _        || _        y )Nr(   )r   r   r$   r)   r%   r*   r'   s          r   __init__zSelfTrainingClassifier.__init__   s/     -"" r   )prefer_skip_nested_validationc                 2   | j                  ||g dd      \  }}t        | j                        | _        |j                  j
                  dv rt        d      |dk7  }t        j                  |      rt        j                  dt               | j                  dk(  rL| j                  |j                  d	   t        j                  |      z
  kD  rt        j                  d
t               t        j                   |      | _        t        j$                  |d      | _        d	| j&                  |<   d	| _        t        j                  |      sB| j*                  | j(                  | j*                  k  r| xj(                  dz  c_        | j                  j-                  |t/        ||         | j"                  |          | j                  j1                  |t/        ||                }| j                  j2                  t        j4                  |d         }t        j6                  |d      }| j                  dk(  r|| j8                  kD  }nkt;        | j                  |j                  d	         }||j                  d	   k(  rt        j<                  |t>              }nt        j@                  | |      d| }t        jB                  |       d	   |   }	||   | j"                  |	<   d||	<   | j(                  | j&                  |	<   |	j                  d	   d	k(  rd| _"        ns| jF                  r)tI        d| j(                   d|	j                  d	    d       t        j                  |      s)| j*                  | j(                  | j*                  k  r| j(                  | j*                  k(  rd| _"        t        j                  |      rd| _"        | j                  j-                  |t/        ||         | j"                  |          | j                  j2                  | _        | S )a  
        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.

        Returns
        -------
        self : object
            Fitted estimator.
        )csrcsclildokF)accept_sparseforce_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 iterationNr&   )axisr$   )dtypeT	no_changezEnd of iteration z, added z new labels.r*   all_labeled)%_validate_datar	   r   r   r:   kind
ValueErrornpallwarningswarnUserWarningr)   r%   shapesumcopytransduction_	full_likelabeled_iter_n_iter_r*   r!   r
   predict_probaclasses_argmaxmaxr$   min	ones_likeboolargpartitionnonzerotermination_condition_r'   print)
r   Xy	has_labelprobpred	max_probaselectedn_to_selectselected_fulls
             r   r!   zSelfTrainingClassifier.fit   sv   0 ""q <u # 
1  %T%8%8977<<:%7  G	66)MM;[I>>X%KK!''!*rvvi'888MM*   WWQZ\\!R0()9%&&#MM!T\\DMM%ALLAL  $$)Ay)*D,>,>y,I
 ''55a	!iZ8P6QRD''004a1HIDt!,I ~~,$t~~5!$++yq/AB)//!"44!||ITBH  "	z;GUH JJ	z215h?M 15XD}-'+Im$04D}-""1%*.9+||'~ 6+11!45\CM &&#MM!T\\DMM%AT <<4==(*4D'66)*7D'  i9%&(:(:9(E	
 ,,55r   predictc                 x    t        |        | j                  |ddd      }| j                  j                  |      S )a1  Predict the classes of `X`.

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

        Returns
        -------
        y : ndarray of shape (n_samples,)
            Array with predicted labels.
        TFr4   r5   reset)r   r=   r   r`   r   rW   s     r   r`   zSelfTrainingClassifier.predict-  sF     	"	   
 ##++A..r   rL   c                 x    t        |        | j                  |ddd      }| j                  j                  |      S )aW  Predict probability for each possible outcome.

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

        Returns
        -------
        y : ndarray of shape (n_samples, n_features)
            Array with prediction probabilities.
        TFrb   )r   r=   r   rL   rd   s     r   rL   z$SelfTrainingClassifier.predict_probaD  sF     	"	   
 ##11!44r   decision_functionc                 x    t        |        | j                  |ddd      }| j                  j                  |      S )al  Call decision function of the `base_estimator`.

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

        Returns
        -------
        y : ndarray of shape (n_samples, n_features)
            Result of the decision function of the `base_estimator`.
        TFrb   )r   r=   r   rf   rd   s     r   rf   z(SelfTrainingClassifier.decision_function[  F     	"	   
 ##55a88r   predict_log_probac                 x    t        |        | j                  |ddd      }| j                  j                  |      S )a_  Predict log probability for each possible outcome.

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

        Returns
        -------
        y : ndarray of shape (n_samples, n_features)
            Array with log prediction probabilities.
        TFrb   )r   r=   r   ri   rd   s     r   ri   z(SelfTrainingClassifier.predict_log_probar  rh   r   scorec                 z    t        |        | j                  |ddd      }| j                  j                  ||      S )a  Call score on the `base_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.

        Returns
        -------
        score : float
            Result of calling score on the `base_estimator`.
        TFrb   )r   r=   r   rk   )r   rW   rX   s      r   rk   zSelfTrainingClassifier.score  sH    " 	"	   
 ##))!Q//r   )g      ?r$   
   rm   F)__name__
__module____qualname____doc___estimator_typer   r   r   r   r   r+   dict__annotations__r-   r   r!   r   r   r`   rL   rf   ri   rk   r   r   r   r   r   '   sE   rh #O
 &ug./tS#f=> +x!89:Haf=>h4?F;	$D 	   &+l	l\ .+,/ -/, .125 35, .!4569 79, .!4569 79, .)*0 +0r   )rB   numbersr   r   numpyr@   baser   r   r   r	   utilsr
   utils._param_validationr   r   r   utils.metadata_routingr   utils.metaestimatorsr   utils.validationr   __all__r   r   r   r   r   <module>r~      sG     "  I I  F F > / .#
$&z01=z0r   