Ë
    ÷Q(hM  ã                   óò   — d Z ddlZ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 ddlmZ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 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$m%Z%  G d„ deee«      Z&y)z!
Neighborhood Component Analysis
é    N)ÚIntegralÚReal)Úwarn)Úminimizeé   )ÚBaseEstimatorÚClassNamePrefixFeaturesOutMixinÚTransformerMixinÚ_fit_context)ÚPCA)ÚConvergenceWarning)Úpairwise_distances)ÚLabelEncoder)ÚIntervalÚ
StrOptions)Úsoftmax)Úcheck_classification_targets)Úcheck_random_state)Úcheck_arrayÚcheck_is_fittedÚvalidate_datac            
       ó  ‡ — e Zd ZU dZ eeddd¬«      dg eh d£«      ej                  gdg eeddd¬«      g ee	ddd¬«      ge
dgd	gd
gdœZeed<   	 dddddddddœd„Z ed¬«      d„ «       Zd„ Zd„ Zd„ Zdd„Zˆ fd„Zed„ «       Zˆ xZS )ÚNeighborhoodComponentsAnalysisa·  Neighborhood Components Analysis.

    Neighborhood Component Analysis (NCA) is a machine learning algorithm for
    metric learning. It learns a linear transformation in a supervised fashion
    to improve the classification accuracy of a stochastic nearest neighbors
    rule in the transformed space.

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

    Parameters
    ----------
    n_components : int, default=None
        Preferred dimensionality of the projected space.
        If None it will be set to `n_features`.

    init : {'auto', 'pca', 'lda', 'identity', 'random'} or ndarray of shape             (n_features_a, n_features_b), default='auto'
        Initialization of the linear transformation. Possible options are
        `'auto'`, `'pca'`, `'lda'`, `'identity'`, `'random'`, and a numpy
        array of shape `(n_features_a, n_features_b)`.

        - `'auto'`
            Depending on `n_components`, the most reasonable initialization
            is chosen. If `n_components <= min(n_features, n_classes - 1)`
            we use `'lda'`, as it uses labels information. If not, but
            `n_components < min(n_features, n_samples)`, we use `'pca'`, as
            it projects data in meaningful directions (those of higher
            variance). Otherwise, we just use `'identity'`.

        - `'pca'`
            `n_components` principal components of the inputs passed
            to :meth:`fit` will be used to initialize the transformation.
            (See :class:`~sklearn.decomposition.PCA`)

        - `'lda'`
            `min(n_components, n_classes)` most discriminative
            components of the inputs passed to :meth:`fit` will be used to
            initialize the transformation. (If `n_components > n_classes`,
            the rest of the components will be zero.) (See
            :class:`~sklearn.discriminant_analysis.LinearDiscriminantAnalysis`)

        - `'identity'`
            If `n_components` is strictly smaller than the
            dimensionality of the inputs passed to :meth:`fit`, the identity
            matrix will be truncated to the first `n_components` rows.

        - `'random'`
            The initial transformation will be a random array of shape
            `(n_components, n_features)`. Each value is sampled from the
            standard normal distribution.

        - numpy array
            `n_features_b` must match the dimensionality of the inputs passed
            to :meth:`fit` and n_features_a must be less than or equal to that.
            If `n_components` is not `None`, `n_features_a` must match it.

    warm_start : bool, default=False
        If `True` and :meth:`fit` has been called before, the solution of the
        previous call to :meth:`fit` is used as the initial linear
        transformation (`n_components` and `init` will be ignored).

    max_iter : int, default=50
        Maximum number of iterations in the optimization.

    tol : float, default=1e-5
        Convergence tolerance for the optimization.

    callback : callable, default=None
        If not `None`, this function is called after every iteration of the
        optimizer, taking as arguments the current solution (flattened
        transformation matrix) and the number of iterations. This might be
        useful in case one wants to examine or store the transformation
        found after each iteration.

    verbose : int, default=0
        If 0, no progress messages will be printed.
        If 1, progress messages will be printed to stdout.
        If > 1, progress messages will be printed and the `disp`
        parameter of :func:`scipy.optimize.minimize` will be set to
        `verbose - 2`.

    random_state : int or numpy.RandomState, default=None
        A pseudo random number generator object or a seed for it if int. If
        `init='random'`, `random_state` is used to initialize the random
        transformation. If `init='pca'`, `random_state` is passed as an
        argument to PCA when initializing the transformation. Pass an int
        for reproducible results across multiple function calls.
        See :term:`Glossary <random_state>`.

    Attributes
    ----------
    components_ : ndarray of shape (n_components, n_features)
        The linear transformation learned during fitting.

    n_features_in_ : int
        Number of features seen during :term:`fit`.

        .. versionadded:: 0.24

    n_iter_ : int
        Counts the number of iterations performed by the optimizer.

    random_state_ : numpy.RandomState
        Pseudo random number generator object used during initialization.

    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

    See Also
    --------
    sklearn.discriminant_analysis.LinearDiscriminantAnalysis : Linear
        Discriminant Analysis.
    sklearn.decomposition.PCA : Principal component analysis (PCA).

    References
    ----------
    .. [1] J. Goldberger, G. Hinton, S. Roweis, R. Salakhutdinov.
           "Neighbourhood Components Analysis". Advances in Neural Information
           Processing Systems. 17, 513-520, 2005.
           http://www.cs.nyu.edu/~roweis/papers/ncanips.pdf

    .. [2] Wikipedia entry on Neighborhood Components Analysis
           https://en.wikipedia.org/wiki/Neighbourhood_components_analysis

    Examples
    --------
    >>> from sklearn.neighbors import NeighborhoodComponentsAnalysis
    >>> from sklearn.neighbors import KNeighborsClassifier
    >>> from sklearn.datasets import load_iris
    >>> from sklearn.model_selection import train_test_split
    >>> X, y = load_iris(return_X_y=True)
    >>> X_train, X_test, y_train, y_test = train_test_split(X, y,
    ... stratify=y, test_size=0.7, random_state=42)
    >>> nca = NeighborhoodComponentsAnalysis(random_state=42)
    >>> nca.fit(X_train, y_train)
    NeighborhoodComponentsAnalysis(...)
    >>> knn = KNeighborsClassifier(n_neighbors=3)
    >>> knn.fit(X_train, y_train)
    KNeighborsClassifier(...)
    >>> print(knn.score(X_test, y_test))
    0.933333...
    >>> knn.fit(nca.transform(X_train), y_train)
    KNeighborsClassifier(...)
    >>> print(knn.score(nca.transform(X_test), y_test))
    0.961904...
    é   NÚleft)Úclosed>   ÚldaÚpcaÚautoÚrandomÚidentityÚbooleanr   ÚverboseÚrandom_state©Ún_componentsÚinitÚ
warm_startÚmax_iterÚtolÚcallbackr#   r$   Ú_parameter_constraintsr   Fé2   gñhãˆµøä>)r'   r(   r)   r*   r+   r#   r$   c                ót   — || _         || _        || _        || _        || _        || _        || _        || _        y ©Nr%   )	Úselfr&   r'   r(   r)   r*   r+   r#   r$   s	            úT/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/sklearn/neighbors/_nca.pyÚ__init__z'NeighborhoodComponentsAnalysis.__init__Ë   s>   € ð )ˆÔØˆŒ	Ø$ˆŒØ ˆŒØˆŒØ ˆŒØˆŒØ(ˆÕó    T)Úprefer_skip_nested_validationc           
      óŽ  — t        | ||d¬«      \  }}t        |«       t        «       j                  |«      }| j                  �E| j                  |j
                  d   kD  r)t        d| j                  › d|j
                  d   › d�«      ‚| j                  rkt        | d«      r_| j                  j
                  d   |j
                  d   k7  r6t        d	|j
                  d   › d
| j                  j
                  d   › d�«      ‚| j                  }t        |t        j                  «      ròt        |«      }|j
                  d   |j
                  d   k7  r,t        d|j
                  d   › d|j
                  d   › d�«      ‚|j
                  d   |j
                  d   kD  r,t        d|j
                  d   › d|j
                  d   › d�«      ‚| j                  �E| j                  |j
                  d   k7  r)t        d| j                  › d|j
                  d   › d�«      ‚t        | j                   «      | _        t%        j$                  «       }|dd…t        j&                  f   |t        j&                  dd…f   k(  }t        j(                  | j+                  |||«      «      }| j,                  dkD  r| j,                  dz
  nd}d| j.                  ||dfd|| j0                  t3        | j4                  |¬«      | j6                  dœ}d| _        t;        di |¤Ž}	|	j<                  j?                  d|j
                  d   «      | _	        t%        j$                  «       |z
  }| j,                  rg| j@                  jB                  }
|	jD                  s*tG        djI                  |
|	jJ                  «      tL        «       tO        djI                  |
|«      «       | S )ao  Fit the model according to the given training data.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
            The training samples.

        y : array-like of shape (n_samples,)
            The corresponding training labels.

        Returns
        -------
        self : object
            Fitted estimator.
        r   )Úensure_min_samplesNr   zDThe preferred dimensionality of the projected space `n_components` (z8) cannot be greater than the given data dimensionality (z)!Úcomponents_zThe new inputs dimensionality (zT) does not match the input dimensionality of the previously learned transformation (z).zThe input dimensionality (zc) of the given linear transformation `init` must match the dimensionality of the given inputs `X` (r   zThe output dimensionality (z]) of the given linear transformation `init` cannot be greater than its input dimensionality (zV) does not match the output dimensionality of the given linear transformation `init` (éÿÿÿÿzL-BFGS-Bg      ð¿T)ÚmaxiterÚdisp)ÚmethodÚfunÚargsÚjacÚx0r*   Úoptionsr+   z[{}] NCA did not converge: {}z[{}] Training took {:8.2f}s.© )(r   r   r   Úfit_transformr&   ÚshapeÚ
ValueErrorr(   Úhasattrr7   r'   Ú
isinstanceÚnpÚndarrayr   r   r$   Úrandom_state_ÚtimeÚnewaxisÚravelÚ_initializer#   Ú_loss_grad_lbfgsr*   Údictr)   Ú	_callbackÚn_iter_r   ÚxÚreshapeÚ	__class__Ú__name__Úsuccessr   ÚformatÚmessager   Úprint)r0   ÚXÚyr'   Út_trainÚsame_class_maskÚtransformationr:   Úoptimizer_paramsÚ
opt_resultÚcls_names              r1   Úfitz"NeighborhoodComponentsAnalysis.fità   s—  € ô$ ˜T 1 a¸AÔ>‰ˆˆ1Ü$ QÔ'Ü‹N×(Ñ(¨Ó+ˆð ×ÑÐ(¨T×->Ñ->ÀÇÁÈÁÒ-KÜð3Ø37×3DÑ3DÐ2Eð F#à#$§7¡7¨1¡: ,¨bð2óð ð �OŠOÜ˜˜mÔ,Ø× Ñ ×&Ñ& qÑ)¨Q¯W©W°Q©ZÒ7äØ1°!·'±'¸!±*°ð >6à6:×6FÑ6F×6LÑ6LÈQÑ6OÐ5PÐPRðTóð ð �y‰yˆÜ�dœBŸJ™JÔ'Ü˜tÓ$ˆDà�z‰z˜!‰} §¡¨¡
Ò*Ü Ø0°·±¸A±°ð @?à?@¿w¹wÀq¹z¸lÈ"ðNóð ð �z‰z˜!‰}˜tŸz™z¨!™}Ò,Ü Ø1°$·*±*¸Q±-°ð A>à>B¿j¹jÈ¹m¸_ÈBðPóð ð × Ñ Ð,°×1BÑ1BÀdÇjÁjÐQRÁmÒ1SÜ ð7Ø7;×7HÑ7HÐ6Ið Jð  $Ÿz™z¨!™}˜o¨Rð	1óð ô 0°×0AÑ0AÓBˆÔô —)‘)“+ˆð šAœrŸz™z˜MÑ*¨a´·
±
ºA°Ñ.>Ñ>ˆô Ÿ™ $×"2Ñ"2°1°a¸Ó">Ó?ˆð $(§<¡<°!Ò#3ˆt�|‰|˜aÒ¸ˆà Ø×(Ñ(Ø˜¨Ð.ØØ Ø—8‘8Ü D§M¡M¸Ô=ØŸ™ñ	
Ðð ˆŒÜÑ1Ð 0Ñ1ˆ
ð &Ÿ<™<×/Ñ/°°A·G±G¸A±JÓ?ˆÔô —)‘)“+ Ñ'ˆØ�<Š<Ø—~‘~×.Ñ.ˆHð ×%Ò%ÜØ3×:Ñ:Ø  *×"4Ñ"4óô 'ô	ô Ð0×7Ñ7¸À'ÓJÔKàˆr3   c                 óˆ   — t        | «       t        | |d¬«      }t        j                  || j                  j
                  «      S )a¬  Apply the learned transformation to the given data.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
            Data samples.

        Returns
        -------
        X_embedded: ndarray of shape (n_samples, n_components)
            The data samples transformed.

        Raises
        ------
        NotFittedError
            If :meth:`fit` has not been called before.
        F)Úreset)r   r   rG   Údotr7   ÚT)r0   rZ   s     r1   Ú	transformz(NeighborhoodComponentsAnalysis.transformX  s7   € ô& 	˜ÔÜ˜$ ¨Ô/ˆä�v‰v�a˜×)Ñ)×+Ñ+Ó,Ð,r3   c                 ó”  — |}| j                   rt        | d«      r| j                  }|S t        |t        j
                  «      r	 |S |j                  \  }}| j                  xs |}|dk(  rGt        t	        j                  |«      «      }|t        ||dz
  «      k  rd}n|t        ||«      k  rd}nd}|dk(  r%t	        j                  ||j                  d   «      }|S |dk(  r-| j                  j                  ||j                  d   f¬«      }|S |d	v �r6t        j                  «       }	|dk(  rlt        || j                  ¬
«      }
| j                   r+t#        dd¬«       t$        j&                  j)                  «        |
j+                  |«       |
j                  }nv|dk(  rqddlm}  ||¬«      }| j                   r+t#        dd¬«       t$        j&                  j)                  «        |j+                  ||«       |j0                  j2                  d| }| j                   r/t#        dj5                  t        j                  «       |	z
  «      «       |S )a  Initialize the transformation.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
            The training samples.

        y : array-like of shape (n_samples,)
            The training labels.

        init : str or ndarray of shape (n_features_a, n_features_b)
            The validated initialization of the linear transformation.

        Returns
        -------
        transformation : ndarray of shape (n_components, n_features)
            The initialized linear transformation.

        r7   r   r   r   r   r!   r    )Úsize>   r   r   )r&   r$   z Finding principal components... Ú )Úendr   )ÚLinearDiscriminantAnalysis)r&   z*Finding most discriminative components... Nzdone in {:5.2f}s)r(   rE   r7   rF   rG   rH   rC   r&   ÚlenÚuniqueÚminÚeyerI   Ústandard_normalrJ   r   r#   rY   ÚsysÚstdoutÚflushrb   Údiscriminant_analysisrl   Ú	scalings_rf   rW   )r0   rZ   r[   r'   r^   Ú	n_samplesÚ
n_featuresr&   Ú	n_classesÚ	init_timer   rl   r   s                r1   rM   z*NeighborhoodComponentsAnalysis._initializep  s  € ð* ˆØ�?Š?œw t¨]Ô;Ø!×-Ñ-ˆNðT ÐôS ˜œbŸj™jÔ)ØðP ÐðM %&§G¡GÑ!ˆI�zØ×,Ñ,Ò:°
ˆLØ�vŠ~Ü¤§	¡	¨!£Ó-�	Ø¤3 z°9¸q±=Ó#AÒAØ ‘DØ!¤C¨
°IÓ$>Ò>Ø ‘Dà%�DØ�zÒ!Ü!#§¡¨°a·g±g¸a±jÓ!A�ð6 Ðð5 ˜Ò!Ø!%×!3Ñ!3×!CÑ!CØ&¨¯©°©
Ð3ð "Dó "�ð2 Ðð- ˜Ò'Ü ŸI™I›K�	Ø˜5’=ÜØ%1À×@RÑ@Rô�Cð —|’|ÜÐ@ÀbÕIÜŸ
™
×(Ñ(Ô*Ø—G‘G˜A”JØ%(§_¡_‘NØ˜U’]ÝRá4À,ÔO�CØ—|’|ÜÐJÐPRÕSÜŸ
™
×(Ñ(Ô*Ø—G‘G˜A˜q”MØ%(§]¡]§_¡_°]°lÐ%C�NØ—<’<ÜÐ,×3Ñ3´D·I±I³KÀ)Ñ4KÓLÔMØÐr3   c                 ó~   — | j                   �| j                  || j                  «       | xj                  dz  c_        y)zêCalled after each iteration of the optimizer.

        Parameters
        ----------
        transformation : ndarray of shape (n_components * n_features,)
            The solution computed by the optimizer in this iteration.
        Nr   )r+   rQ   )r0   r^   s     r1   rP   z(NeighborhoodComponentsAnalysis._callback³  s.   € ð �=‰=Ð$Ø�M‰M˜.¨$¯,©,Ô7à�Š˜ÑŽr3   c                 óÄ  — | j                   dk(  r�| xj                   dz  c_         | j                  rng d¢}d} |j                  |Ž }| j                  j                  }t        dj                  |«      «       t        dj                  |||dt        |«      z  «      «       t        j                  «       }	|j                  d|j                  d   «      }t        j                  ||j                  «      }
t        |
d	¬
«      }t        j                  |t        j                  «       t!        | «      }||z  }t        j"                  |dd	¬«      }t        j"                  |«      }|||z  z
  }||j                  z   }t        j                  ||j#                  d¬«       «       d|
j                  j                  |«      j                  |«      z  }| j                  rrt        j                  «       |	z
  }	d}t        |j                  | j                  j                  | j                   ||	«      «       t$        j&                  j)                  «        ||z  ||j+                  «       z  fS )a  Compute the loss and the loss gradient w.r.t. `transformation`.

        Parameters
        ----------
        transformation : ndarray of shape (n_components * n_features,)
            The raveled linear transformation on which to compute loss and
            evaluate gradient.

        X : ndarray of shape (n_samples, n_features)
            The training samples.

        same_class_mask : ndarray of shape (n_samples, n_samples)
            A mask where `mask[i, j] == 1` if `X[i]` and `X[j]` belong
            to the same class, and `0` otherwise.

        Returns
        -------
        loss : float
            The loss computed for the given transformation.

        gradient : ndarray of shape (n_components * n_features,)
            The new (flattened) gradient of the loss.
        r   r   )Ú	IterationzObjective ValuezTime(s)z{:>10} {:>20} {:>10}z[{}]z[{}] {}
[{}] {}ú-r8   T)Úsquared)ÚaxisÚkeepdims)r€   r   z[{}] {:>10} {:>20.6e} {:>10.2f})rQ   r#   rW   rT   rU   rY   rm   rJ   rS   rC   rG   re   rf   r   Úfill_diagonalÚinfr   Úsumrr   rs   rt   rL   )r0   r^   rZ   r]   ÚsignÚheader_fieldsÚ
header_fmtÚheaderra   Ú	t_funcallÚ
X_embeddedÚp_ijÚmasked_p_ijÚpÚlossÚweighted_p_ijÚweighted_p_ij_symÚgradientÚ
values_fmts                      r1   rN   z/NeighborhoodComponentsAnalysis._loss_grad_lbfgsÀ  sü  € ð2 �<‰<˜1ÒØ�LŠL˜AÑ�LØ�|Š|Ú K�Ø3�
Ø*˜×*Ñ*¨MÐ:�ØŸ>™>×2Ñ2�Ü�f—m‘m HÓ-Ô.ÜØ&×-Ñ-Ø  &¨(°C¼#¸f»+Ñ4Eóôô —I‘I“Kˆ	à'×/Ñ/°°A·G±G¸A±JÓ?ˆÜ—V‘V˜A˜~×/Ñ/Ó0ˆ
ô " *°dÔ;ˆÜ
×Ñ˜œrŸv™vÔ&Ü˜�u‹~ˆð ˜_Ñ,ˆÜ�F‰F�; Q°Ô6ˆÜ�v‰v�a‹yˆð $ d¨Q¡hÑ.ˆØ)¨M¯O©OÑ;ÐÜ
×ÑÐ*¨]×->Ñ->ÀAÐ->Ó-FÐ,FÔGØ�z—|‘|×'Ñ'Ð(9Ó:×>Ñ>¸qÓAÑAˆð �<Š<ÜŸ	™	› iÑ/ˆIØ:ˆJÜØ×!Ñ!Ø—N‘N×+Ñ+¨T¯\©\¸4Àóôô
 �J‰J×ÑÔà�d‰{˜D 8§>¡>Ó#3Ñ3Ð3Ð3r3   c                 óF   •— t         ‰| �  «       }d|j                  _        |S )NT)ÚsuperÚ__sklearn_tags__Útarget_tagsÚrequired)r0   ÚtagsrT   s     €r1   r•   z/NeighborhoodComponentsAnalysis.__sklearn_tags__
  s#   ø€ Ü‰wÑ'Ó)ˆØ$(ˆ×ÑÔ!Øˆr3   c                 ó4   — | j                   j                  d   S )z&Number of transformed output features.r   )r7   rC   )r0   s    r1   Ú_n_features_outz.NeighborhoodComponentsAnalysis._n_features_out  s   € ð ×Ñ×%Ñ% aÑ(Ð(r3   r/   )g      ð?)rU   Ú
__module__Ú__qualname__Ú__doc__r   r   r   rG   rH   r   Úcallabler,   rO   Ú__annotations__r2   r   rb   rg   rM   rP   rN   r•   Úpropertyrš   Ú__classcell__)rT   s   @r1   r   r   !   s÷   ø… ñTñp �X˜q $¨vÔ6Øð
ñ
 ÒCÓDØ�J‰Jð
ð !�kÙ˜h¨¨4¸Ô?Ð@Ù˜˜q $¨vÔ6Ð7Ø˜tÐ$Ø�;Ø'Ð(ñ$Ð˜Dó ð& ð)ð ØØØØØØô)ñ* °Ô5ñuó 6ðuòn-ò0AòFóH4ôTð
 ñ)ó ô)r3   r   )'r�   rr   rJ   Únumbersr   r   Úwarningsr   ÚnumpyrG   Úscipy.optimizer   Úbaser   r	   r
   r   Údecompositionr   Ú
exceptionsr   Úmetricsr   Úpreprocessingr   Úutils._param_validationr   r   Úutils.extmathr   Úutils.multiclassr   Úutils.randomr   Úutils.validationr   r   r   r   rA   r3   r1   ú<module>r°      s\   ðñó Û ß "Ý ã Ý #÷ó õ  Ý +Ý (Ý (ß :Ý #Ý ;Ý -ß JÑ Jôq)Ø#Ð%5°}õq)r3   