
    -iS                        S r SSKrSSKJrJr  SSKJrJr  SSKr	SSK
Jr  SSKJrJrJr  SSKJr  SS	KJr  SS
KJr  SSKJrJr  SSKJr  SSKJr  SSKJr  SSK J!r!J"r"   " S S\\\S9r# " S S\#5      r$ " S S\#5      r%g)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                     ^  \ rS rSr% Sr\" SS15      \/\" \SSSS9/\" \	SSS	S9/S\" \SS
S	S9/\" \	SSS	S9/\" \SSSS9/S\	/S.r
\\S'    SSSS
SSSS.S jjrSS jr\S 5       rS rS r\" SS9S 5       rU 4S jrSrU =r$ )BaseLabelPropagationL   a  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                X    XPl         X`l        Xl        X l        X0l        X@l        Xpl        g N)r%   r&   r!   r"   r#   r$   r'   )selfr!   r"   r#   r$   r%   r&   r'   s           ]/var/www/html/venv/lib/python3.13/site-packages/sklearn/semi_supervised/_label_propagation.py__init__BaseLabelPropagation.__init__x   s,     ! 
& 
    c                 B   U R                   S:X  a+  Uc  [        XU R                  S9$ [        XU R                  S9$ U R                   S:X  a  U R                  c2  [	        U R
                  U R                  S9R                  U5      U l        Uc9  U R                  R                  U R                  R                  U R
                  SS9$ U R                  R                  USS9$ [        U R                   5      (       a%  Uc  U R                  X5      $ U R                  X5      $ g )	Nr   )r"   r   )r#   r'   connectivity)modeF)return_distance)r!   r   r"   nn_fitr   r#   r'   fitkneighbors_graph_fit_X
kneighborscallable)r0   Xys      r1   _get_kernel BaseLabelPropagation._get_kernel   s    ;;%y!!djj99!!djj99[[E!{{". $ 0 0#a&  y{{33KK&&(8(8~ 4   {{--a-GGdkk""y{{1(({{1((	 #r4   c                     [        S5      e)NzHGraph construction must be implemented to fit a label propagation model.)NotImplementedError)r0   s    r1   _build_graph!BaseLabelPropagation._build_graph   s    !V
 	
r4   c                     U R                  U5      nU R                  [        R                  " USS9   R	                  5       $ )zPerform 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)r0   r?   probass      r1   predictBaseLabelPropagation.predict   s7    " ##A&}}RYYvA67==??r4   c           
         [        U 5        [        U U/ SQSS9nU R                  U R                  U5      nU R                  S:X  aH  [
        R                  " U Vs/ s H%  n[
        R                  " U R                  U   SS9PM'     sn5      nO!UR                  n[        X0R                  5      n[
        R                  " [
        R                  " USS95      R                  nXV-  nU$ s  snf )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   r   rH   r   )r   r   rA   X_r!   rL   arraysumlabel_distributions_Tr   
atleast_2d)r0   r?   X_2dweight_matricesweight_matrixprobabilities
normalizers          r1   rJ   "BaseLabelPropagation.predict_proba   s    $ 	K	
 **477D9;;%HH *9)8 FF444]C!L)8M .//O+O=V=VWM]]266-a#@ACC
#s   ,C(T)prefer_skip_nested_validationc                    [        U UUSS/SS9u  pXl        [        U5        U R                  5       n[        R
                  " U5      nXDS:g     nX@l        [        U5      [        U5      pe[        R                  " U5      nUS:H  n[        R                  " XV45      U l
        U H  nSU R                  X(:H  XH:H  4'   M     [        R                  " U R                  5      n	U R                  S:X  a  SX'   OU	SU R                  -
  -  n	[        R                  " U R                  R                  S   U45      n
US	S	2[        R                  4   n[         R"                  " U5      (       a  UR%                  5       n['        U R(                  5       GH,  U l        [        R,                  " U R                  U
-
  5      R/                  5       U R0                  :  a    GO!U R                  n
[3        X0R                  5      U l
        U R                  S:X  ax  [        R.                  " U R                  SS
9S	S	2[        R                  4   nSXS:H  '   U =R                  U-  sl
        [        R4                  " XpR                  U	5      U l
        M  [        R6                  " U R                  U R                  5      U	-   U l
        GM/     [8        R:                  " SU R(                  -  [<        S9  U =R*                  S-  sl        [        R.                  " U R                  SS
9S	S	2[        R                  4   nSXS:H  '   U =R                  U-  sl
        U R                  [        R>                  " U R                  SS
9   nURA                  5       U l!        U $ )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.
rT   rS   TrZ   r   propagationr   NrH   z,max_iter=%d was reached without convergence.)category)"r   r]   r   rE   rL   uniquerK   lenasarrayzerosr`   copy_variantr$   shapenewaxisr   issparsetocsrranger%   n_iter_absr_   r&   r   wheremultiplywarningswarnr   rM   rN   transduction_)r0   r?   r@   graph_matrixclasses	n_samples	n_classes	unlabeledlabely_static
l_previousrg   transductions                r1   r:   BaseLabelPropagation.fit   s   2  %.
 $Q' ((* ))A,R-("1vs7|9JJqMG	 %'HHi-C$D!EFGD%%aj'2B&BC  774445==M)"#H DJJ&HXXtww}}Q/;<
am,	??<(('--/L!$--0DLvvd//*<=AACdhhN22J(777)D% }}-VVD$=$=AFq"**}U
./
?+))Z7),.HH88(-) KK

D,E,EFQ )% 1, MM>N+ LLALVVD55A>q"**}M
&'
?#!!Z/! }}RYYt/H/Hq%QR)//1r4   c                 F   > [         TU ]  5       nSUR                  l        U$ )NT)super__sklearn_tags__
input_tagsr   )r0   tags	__class__s     r1   r   %BaseLabelPropagation.__sklearn_tags__S  s!    w')!%r4   )r]   r$   rK   r"   r!   r`   r%   ry   r'   r#   r9   r&   r   r   r/   )__name__
__module____qualname____firstlineno____doc__r   r>   r   r   r   r(   dict__annotations__r2   rA   r   rE   rP   rJ   r   r:   r   __static_attributes____classcell__r   s   @r1   r   r   L   s    D uen-x84D89 1d9EFq!I>?h4	BCq$v67"$D   0). 
 

@('R 5f 6fP r4   r   )	metaclassc                      ^  \ rS rSr% SrSr0 \R                  Er\\	S'   \R                  S5         SSSSS	S
S.U 4S jjjrS rU 4S jrSrU =r$ )LabelPropagationiY  a	  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(...)
rl   r(   r$   r)   r*   i  r,   N)r"   r#   r%   r&   r'   c          
      ,   > [         TU ]  UUUUUUS S9  g )N)r!   r"   r#   r%   r&   r'   r$   r   r2   )r0   r!   r"   r#   r%   r&   r'   r   s          r1   r2   LabelPropagation.__init__  s,     	# 	 	
r4   c                 n   U R                   S:X  a  SU l        U R                  U R                  5      nUR	                  SS9n[
        R                  " U5      (       a?  U=R                  [        R                  " [        R                  " U5      5      -  sl        U$ XSS2[        R                  4   -  nU$ )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   rH   )r!   r9   rA   r]   r_   r   rv   datarL   diagr^   ru   )r0   affinity_matrixrg   s      r1   rE   LabelPropagation._build_graph  s     ;;%DK**4773$((a(0
???++  BGGBHHZ,@$AA   !RZZ-88Or4   c                 "   > [         TU ]  X5      $ )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   r:   )r0   r?   r@   r   s      r1   r:   LabelPropagation.fit  s    & w{1  r4   r9   r   )r   r   r   r   r   rs   r   r(   r   r   popr2   rE   r:   r   r   r   s   @r1   r   r   Y  sj    Rh H#R&:&Q&Q#RDRw' 
 
 
( ! !r4   r   c                      ^  \ rS rSr% SrSr0 \R                  Er\\	S'   \
" \SSSS9/\S	'    SS
SSSSSS.U 4S jjjrS rSrU =r$ )LabelSpreadingi  a  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*   g?r+   r,   Nr-   c          
      ,   > [         TU ]  UUUUUUUS9  g )Nr    r   )	r0   r!   r"   r#   r$   r%   r&   r'   r   s	           r1   r2   LabelSpreading.__init__R  s,     	# 	 	
r4   c                 j   U R                   S:X  a  SU l        U R                  R                  S   nU R	                  U R                  5      n[        USS9nU* n[        R                  " U5      (       a*  UR                  UR                  :H  nSUR                  U'   U$ SUR                  SSUS-   2'   U$ )z=Graph matrix for Label Spreading computes the graph laplacianr   Nr   T)normedg        r   )r!   r9   r]   rt   rA   csgraph_laplacianr   rv   rowcolr   flat)r0   r   r   r   	diag_masks        r1   rE   LabelSpreading._build_graphh  s     ;;%DKGGMM!$	**4773%odC	J	??9%%!6I(+INN9%  03INN+i!m+,r4   r   r   )r   r   r   r   r   rs   r   r(   r   r   r   r   r2   rE   r   r   r   s   @r1   r   r     ss    ]~ H#R&:&Q&Q#RDR'/a9'M&N7# 
 
 
, r4   r   )&r   r}   abcr   r   numbersr   r   numpyrL   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    r4   r1   <module>r      sl   3p  ' "   ? ? + ) ( : + 8 ; =J?MW JZQ!+ Q!hI) Ir4   