
    0PhS                        d Z ddlZddlmZmZ ddlmZmZ ddl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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!m"Z"  G d deee          Z# G d de#          Z$ G d de#          Z%dS )ad  
Label propagation in the context of this module refers to a set of
semi-supervised classification algorithms. At a high level, these algorithms
work by forming a fully-connected graph between all points given and solving
for the steady-state distribution of labels at each point.

These algorithms perform very well in practice. The cost of running can be very
expensive, at approximately O(N^3) where N is the number of (labeled and
unlabeled) points. The theory (why they perform so well) is motivated by
intuitions from random walk algorithms and geometric relationships in the data.
For more information see the references below.

Model Features
--------------
Label clamping:
  The algorithm tries to learn distributions of labels over the dataset given
  label assignments over an initial subset. In one variant, the algorithm does
  not allow for any errors in the initial assignment (hard-clamping) while
  in another variant, the algorithm allows for some wiggle room for the initial
  assignments, allowing them to change by a fraction alpha in each iteration
  (soft-clamping).

Kernel:
  A function which projects a vector into some higher dimensional space. This
  implementation supports RBF and KNN kernels. Using the RBF kernel generates
  a dense matrix of size O(N^2). KNN kernel will generate a sparse matrix of
  size O(k*N) which will run much faster. See the documentation for SVMs for
  more info on kernels.

Examples
--------
>>> import numpy as np
>>> from sklearn import datasets
>>> from sklearn.semi_supervised import LabelPropagation
>>> label_prop_model = LabelPropagation()
>>> iris = datasets.load_iris()
>>> rng = np.random.RandomState(42)
>>> random_unlabeled_points = rng.rand(len(iris.target)) < 0.3
>>> labels = np.copy(iris.target)
>>> labels[random_unlabeled_points] = -1
>>> label_prop_model.fit(iris.data, labels)
LabelPropagation(...)

Notes
-----
References:
[1] Yoshua Bengio, Olivier Delalleau, Nicolas Le Roux. In Semi-Supervised
Learning (2006), pp. 193-216

[2] Olivier Delalleau, Yoshua Bengio, Nicolas Le Roux. Efficient
Non-Parametric Function Induction in Semi-Supervised Learning. AISTAT 2005
    N)ABCMetaabstractmethod)IntegralReal)sparse   )BaseEstimatorClassifierMixin_fit_context)ConvergenceWarning)
rbf_kernel)NearestNeighbors)Interval
StrOptions)safe_sparse_dot)	laplacian)check_classification_targets)check_is_fittedvalidate_datac                   \    e Zd ZU dZ eddh          eg eeddd          g eeddd          gd eedd	d          g eeddd          g eeddd          gdegd
Z	e
ed<   	 dddd	dddddZddZed             Zd Zd Z ed          d             Z fdZ xZS )BaseLabelPropagationaf  Base class for label propagation module.

     Parameters
     ----------
     kernel : {'knn', 'rbf'} or callable, default='rbf'
         String identifier for kernel function to use or the kernel function
         itself. Only 'rbf' and 'knn' strings are valid inputs. The function
         passed should take two inputs, each of shape (n_samples, n_features),
         and return a (n_samples, n_samples) shaped weight matrix.

     gamma : float, default=20
         Parameter for rbf kernel.

     n_neighbors : int, default=7
         Parameter for knn kernel. Need to be strictly positive.

     alpha : float, default=1.0
         Clamping factor.

     max_iter : int, default=30
         Change maximum number of iterations allowed.

     tol : float, default=1e-3
         Convergence tolerance: threshold to consider the system at steady
         state.

    n_jobs : int, default=None
         The number of parallel jobs to run.
         ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
         ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
         for more details.
    knnrbfr   Nleftclosedneither   kernelgamman_neighborsalphamax_itertoln_jobs_parameter_constraints         MbP?r!   r"   r#   r$   r%   r&   c                h    || _         || _        || _        || _        || _        || _        || _        d S N)r$   r%   r    r!   r"   r#   r&   )selfr    r!   r"   r#   r$   r%   r&   s           j/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/sklearn/semi_supervised/_label_propagation.py__init__zBaseLabelPropagation.__init__x   s>     ! 
& 
    c                    | j         dk    r0|t          ||| j                  S t          ||| j                  S | j         dk    r| j        3t	          | j        | j                                      |          | _        |,| j                            | j        j	        | j        d          S | j        
                    |d          S t          | j                   r.||                      ||          S |                      ||          S d S )	Nr   )r!   r   )r"   r&   connectivity)modeF)return_distance)r    r   r!   nn_fitr   r"   r&   fitkneighbors_graph_fit_X
kneighborscallable)r/   Xys      r0   _get_kernelz BaseLabelPropagation._get_kernel   s    ;%y!!Qdj9999!!Qdj9999[E!!{". $ 0  #a&&  y{33K&(8~ 4    {--a-GGGdk"" 	)y{{1a((({{1a(((		) 	)r2   c                      t          d          )NzHGraph construction must be implemented to fit a label propagation model.)NotImplementedError)r/   s    r0   _build_graphz!BaseLabelPropagation._build_graph   s    !V
 
 	
r2   c                     |                      |          }| j        t          j        |d                                                   S )a%  Perform inductive inference across the model.

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

        Returns
        -------
        y : ndarray of shape (n_samples,)
            Predictions for input data.
        r   axis)predict_probaclasses_npargmaxravel)r/   r=   probass      r0   predictzBaseLabelPropagation.predict   s?    " ##A&&}RYvA6667==???r2   c                 z    t                      t           |g dd          }                      j        |          } j        dk    r!t          j         fd|D                       }n|j        }t          | j	                  }t          j
        t          j        |d                    j        }||z  }|S )a  Predict probability for each possible outcome.

        Compute the probability estimates for each single sample in X
        and each possible outcome seen during training (categorical
        distribution).

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

        Returns
        -------
        probabilities : ndarray of shape (n_samples, n_classes)
            Normalized probability distributions across
            class labels.
        )csccsrcoodokbsrlildiaFaccept_sparseresetr   c                 R    g | ]#}t          j        j        |         d           $S )r   rD   )rH   sumlabel_distributions_).0weight_matrixr/   s     r0   
<listcomp>z6BaseLabelPropagation.predict_proba.<locals>.<listcomp>   s@       % F44]C!LLL  r2   r   rD   )r   r   r?   X_r    rH   arrayTr   rZ   
atleast_2drY   )r/   r=   X_2dweight_matricesprobabilities
normalizers   `     r0   rF   z"BaseLabelPropagation.predict_proba   s    $ 	KKK	
 
 
 **47D99;%H   )8   MM ./O+OT=VWWM]26-a#@#@#@AAC
#r2   T)prefer_skip_nested_validationc                 ~   t          | ||ddgd          \  }}|| _        t          |           |                                 }t	          j        |          }||dk             }|| _        t          |          t          |          }}t	          j        |          }|dk    }t	          j	        ||f          | _
        |D ]}d| j
        ||k    ||k    f<   t	          j        | j
                  }	| j        dk    rd|	|<   n|	d| j        z
  z  }	t	          j	        | j        j        d         |f          }
|d	d	t          j        f         }t!          j        |          r|                                }t'          | j                  D ]| _        t	          j        | j
        |
z
                                            | j        k     r n| j
        }
t3          || j
                  | _
        | j        dk    rit	          j        | j
        d
          d	d	t          j        f         }d||dk    <   | xj
        |z  c_
        t	          j        || j
        |	          | _
        t	          j        | j        | j
                  |	z   | _
        t9          j        d| j        z  t<                     | xj        dz  c_        t	          j        | j
        d
          d	d	t          j        f         }d||dk    <   | xj
        |z  c_
        | j        t	          j        | j
        d
                   }|                                 | _!        | S )a~  Fit a semi-supervised label propagation model to X.

        The input samples (labeled and unlabeled) are provided by matrix X,
        and target labels are provided by matrix y. We conventionally apply the
        label -1 to unlabeled samples in matrix y in a semi-supervised
        classification.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            Training data, where `n_samples` is the number of samples
            and `n_features` is the number of features.

        y : array-like of shape (n_samples,)
            Target class values with unlabeled points marked as -1.
            All unlabeled samples will be transductively assigned labels
            internally, which are stored in `transduction_`.

        Returns
        -------
        self : object
            Returns the instance itself.
        rO   rN   TrU   r   propagationr   NrD   z,max_iter=%d was reached without convergence.)category)"r   r^   r   rB   rH   uniquerG   lenasarrayzerosrZ   copy_variantr#   shapenewaxisr   issparsetocsrranger$   n_iter_absrY   r%   r   wheremultiplywarningswarnr   rI   rJ   transduction_)r/   r=   r>   graph_matrixclasses	n_samples	n_classes	unlabeledlabely_static
l_previousre   transductions                r0   r8   zBaseLabelPropagation.fit   sH   2  %.
 
 
1 $Q''' ((** )A,,'R-("1vvs7||9	JqMMG	 %'Hi-C$D$D! 	H 	HEFGD%a5j'U2B&BCC74455=M))"#HY DJ&HXtw}Q/;<<
aaam,	?<(( 	0'--//L!$-00 	 	DLvd/*<==AACCdhNN2J(7d7) )D% }--VD$=AFFFqqq"*}U
./
:?+))Z7)),.Ht8(- -)) K
D,EFFQ )) M>N+    LLALLVD5A>>>qqq"*}M
&'
:?#!!Z/!! }RYt/Hq%Q%Q%QR)//11r2   c                 `    t                                                      }d|j        _        |S )NT)super__sklearn_tags__
input_tagsr   )r/   tags	__class__s     r0   r   z%BaseLabelPropagation.__sklearn_tags__S  s'    ww''))!%r2   r   r.   )__name__
__module____qualname____doc__r   r<   r   r   r   r'   dict__annotations__r1   r?   r   rB   rL   rF   r   r8   r   __classcell__r   s   @r0   r   r   L   s         D :uen--x8(4D8889 1d9EEEFq!I>>>?Xh4	BBBCq$v6667"$ $D         0) ) ) ). 
 
 ^

@ @ @(' ' 'R \555f f 65fP        r2   r   )	metaclassc                        e Zd ZU dZdZi ej        Zeed<   e	                    d           	 ddddd	d
d fdZ
d Z fdZ xZS )LabelPropagationa
  Label Propagation classifier.

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

    Parameters
    ----------
    kernel : {'knn', 'rbf'} or callable, default='rbf'
        String identifier for kernel function to use or the kernel function
        itself. Only 'rbf' and 'knn' strings are valid inputs. The function
        passed should take two inputs, each of shape (n_samples, n_features),
        and return a (n_samples, n_samples) shaped weight matrix.

    gamma : float, default=20
        Parameter for rbf kernel.

    n_neighbors : int, default=7
        Parameter for knn kernel which need to be strictly positive.

    max_iter : int, default=1000
        Change maximum number of iterations allowed.

    tol : float, default=1e-3
        Convergence tolerance: threshold to consider the system at steady
        state.

    n_jobs : int, default=None
        The number of parallel jobs to run.
        ``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
    ----------
    X_ : {array-like, sparse matrix} of shape (n_samples, n_features)
        Input array.

    classes_ : ndarray of shape (n_classes,)
        The distinct labels used in classifying instances.

    label_distributions_ : ndarray of shape (n_samples, n_classes)
        Categorical distribution for each item.

    transduction_ : ndarray of shape (n_samples)
        Label assigned to each item during :term:`fit`.

    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
        Number of iterations run.

    See Also
    --------
    LabelSpreading : Alternate label propagation strategy more robust to noise.

    References
    ----------
    Xiaojin Zhu and Zoubin Ghahramani. Learning from labeled and unlabeled data
    with label propagation. Technical Report CMU-CALD-02-107, Carnegie Mellon
    University, 2002 http://pages.cs.wisc.edu/~jerryzhu/pub/CMU-CALD-02-107.pdf

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn import datasets
    >>> from sklearn.semi_supervised import LabelPropagation
    >>> label_prop_model = LabelPropagation()
    >>> iris = datasets.load_iris()
    >>> rng = np.random.RandomState(42)
    >>> random_unlabeled_points = rng.rand(len(iris.target)) < 0.3
    >>> labels = np.copy(iris.target)
    >>> labels[random_unlabeled_points] = -1
    >>> label_prop_model.fit(iris.data, labels)
    LabelPropagation(...)
    ri   r'   r#   r   r(   r)   i  r+   N)r!   r"   r$   r%   r&   c          	      X    t                                          ||||||d            d S )N)r    r!   r"   r$   r%   r&   r#   r   r1   )r/   r    r!   r"   r$   r%   r&   r   s          r0   r1   zLabelPropagation.__init__  sE     	# 	 	
 	
 	
 	
 	
r2   c                 N   | j         dk    rd| _        |                     | j                  }|                    d          }t          j        |          r5|xj        t          j	        t          j
        |                    z  c_        n||ddt          j        f         z  }|S )zMatrix representing a fully connected graph between each sample

        This basic implementation creates a non-stochastic affinity matrix, so
        class distributions will exceed 1 (normalization may be desired).
        r   Nr   rD   )r    r7   r?   r^   rY   r   rs   datarH   diagr_   rr   )r/   affinity_matrixre   s      r0   rB   zLabelPropagation._build_graph  s     ;%DK**4733$((a(00
??++ 	9  BGBHZ,@,@$A$AA   z!!!RZ-88Or2   c                 H    t                                          ||          S )a  Fit a semi-supervised label propagation model to X.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            Training data, where `n_samples` is the number of samples
            and `n_features` is the number of features.

        y : array-like of shape (n_samples,)
            Target class values with unlabeled points marked as -1.
            All unlabeled samples will be transductively assigned labels
            internally, which are stored in `transduction_`.

        Returns
        -------
        self : object
            Returns the instance itself.
        )r   r8   )r/   r=   r>   r   s      r0   r8   zLabelPropagation.fit  s    & ww{{1a   r2   r   )r   r   r   r   rp   r   r'   r   r   popr1   rB   r8   r   r   s   @r0   r   r   Y  s         R Rh H#R&:&Q#RDRRRw''' 
 
 
 
 
 
 
 
(   ! ! ! ! ! ! ! ! !r2   r   c                        e Zd ZU dZdZi ej        Zeed<    e	e
ddd          ged<   	 dd
dddddd fdZd Z xZS )LabelSpreadinga  LabelSpreading model for semi-supervised learning.

    This model is similar to the basic Label Propagation algorithm,
    but uses affinity matrix based on the normalized graph Laplacian
    and soft clamping across the labels.

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

    Parameters
    ----------
    kernel : {'knn', 'rbf'} or callable, default='rbf'
        String identifier for kernel function to use or the kernel function
        itself. Only 'rbf' and 'knn' strings are valid inputs. The function
        passed should take two inputs, each of shape (n_samples, n_features),
        and return a (n_samples, n_samples) shaped weight matrix.

    gamma : float, default=20
      Parameter for rbf kernel.

    n_neighbors : int, default=7
      Parameter for knn kernel which is a strictly positive integer.

    alpha : float, default=0.2
      Clamping factor. A value in (0, 1) that specifies the relative amount
      that an instance should adopt the information from its neighbors as
      opposed to its initial label.
      alpha=0 means keeping the initial label information; alpha=1 means
      replacing all initial information.

    max_iter : int, default=30
      Maximum number of iterations allowed.

    tol : float, default=1e-3
      Convergence tolerance: threshold to consider the system at steady
      state.

    n_jobs : int, default=None
        The number of parallel jobs to run.
        ``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
    ----------
    X_ : ndarray of shape (n_samples, n_features)
        Input array.

    classes_ : ndarray of shape (n_classes,)
        The distinct labels used in classifying instances.

    label_distributions_ : ndarray of shape (n_samples, n_classes)
        Categorical distribution for each item.

    transduction_ : ndarray of shape (n_samples,)
        Label assigned to each item during :term:`fit`.

    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
        Number of iterations run.

    See Also
    --------
    LabelPropagation : Unregularized graph based semi-supervised learning.

    References
    ----------
    `Dengyong Zhou, Olivier Bousquet, Thomas Navin Lal, Jason Weston,
    Bernhard Schoelkopf. Learning with local and global consistency (2004)
    <https://citeseerx.ist.psu.edu/doc_view/pid/d74c37aabf2d5cae663007cbd8718175466aea8c>`_

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn import datasets
    >>> from sklearn.semi_supervised import LabelSpreading
    >>> label_prop_model = LabelSpreading()
    >>> iris = datasets.load_iris()
    >>> rng = np.random.RandomState(42)
    >>> random_unlabeled_points = rng.rand(len(iris.target)) < 0.3
    >>> labels = np.copy(iris.target)
    >>> labels[random_unlabeled_points] = -1
    >>> label_prop_model.fit(iris.data, labels)
    LabelSpreading(...)
    	spreadingr'   r   r   r   r   r#   r   r(   r)   g?r*   r+   Nr,   c          	      X    t                                          |||||||           d S )Nr   r   )	r/   r    r!   r"   r#   r$   r%   r&   r   s	           r0   r1   zLabelSpreading.__init__R  sE     	# 	 	
 	
 	
 	
 	
r2   c                 (   | j         dk    rd| _        | j        j        d         }|                     | j                  }t          |d          }| }t          j        |          r|j        |j	        k    }d|j
        |<   nd|j        dd|dz   <   |S )z=Graph matrix for Label Spreading computes the graph laplacianr   Nr   T)normedg        r   )r    r7   r^   rq   r?   csgraph_laplacianr   rs   rowcolr   flat)r/   r   r   r   	diag_masks        r0   rB   zLabelSpreading._build_graphh  s     ;%DKGM!$	**4733%odCCC	J	?9%% 	3!6I(+IN9%%/2IN++i!m+,r2   r   )r   r   r   r   rp   r   r'   r   r   r   r   r1   rB   r   r   s   @r0   r   r     s         ] ]~ H#R&:&Q#RDRRR'/xa9'M'M'M&N7# 
 
 
 
 
 
 
 
,      r2   r   )&r   rz   abcr   r   numbersr   r   numpyrH   scipyr   baser	   r
   r   
exceptionsr   metrics.pairwiser   	neighborsr   utils._param_validationr   r   utils.extmathr   utils.fixesr   r   utils.multiclassr   utils.validationr   r   r   r   r    r2   r0   <module>r      s  3 3p  ' ' ' ' ' ' ' ' " " " " " " " "           ? ? ? ? ? ? ? ? ? ? + + + + + + ) ) ) ) ) ) ( ( ( ( ( ( : : : : : : : : + + + + + + 8 8 8 8 8 8 ; ; ; ; ; ; = = = = = = = =J J J J J?MW J J J JZQ! Q! Q! Q! Q!+ Q! Q! Q!hI I I I I) I I I I Ir2   