Ë
    ÷Q(hø2  ã                   óÖ   — d Z ddlZddl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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 m!Z!  G d„ deee
«      Z"y)z!
Nearest Centroid Classification
é    N)ÚReal)Úsparseé   )ÚBaseEstimatorÚClassifierMixinÚ_fit_context)Ú#DiscriminantAnalysisPredictionMixin)Úpairwise_distancesÚpairwise_distances_argmin)ÚLabelEncoder)Úget_tags)Úavailable_if)ÚIntervalÚ
StrOptions)Úcheck_classification_targets)Úcsc_median_axis_0)Úcheck_is_fittedÚvalidate_datac                   óN  ‡ — e Zd ZU dZ eddh«      g eeddd¬«      dgd ed	d
h«      gdœZee	d<   	 ddd
dœd„Z
 ed¬«      d„ «       Zˆ fd„Zd„ Zd„ Z  ee«      ej$                  «      Z  ee«      ej&                  «      Z  ee«      ej(                  «      Zˆ fd„Zˆ xZS )ÚNearestCentroidaž  Nearest centroid classifier.

    Each class is represented by its centroid, with test samples classified to
    the class with the nearest centroid.

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

    Parameters
    ----------
    metric : {"euclidean", "manhattan"}, default="euclidean"
        Metric to use for distance computation.

        If `metric="euclidean"`, the centroid for the samples corresponding to each
        class is the arithmetic mean, which minimizes the sum of squared L1 distances.
        If `metric="manhattan"`, the centroid is the feature-wise median, which
        minimizes the sum of L1 distances.

        .. versionchanged:: 1.5
            All metrics but `"euclidean"` and `"manhattan"` were deprecated and
            now raise an error.

        .. versionchanged:: 0.19
            `metric='precomputed'` was deprecated and now raises an error

    shrink_threshold : float, default=None
        Threshold for shrinking centroids to remove features.

    priors : {"uniform", "empirical"} or array-like of shape (n_classes,),         default="uniform"
        The class prior probabilities. By default, the class proportions are
        inferred from the training data.

        .. versionadded:: 1.6

    Attributes
    ----------
    centroids_ : array-like of shape (n_classes, n_features)
        Centroid of each class.

    classes_ : array of shape (n_classes,)
        The unique classes labels.

    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

    deviations_ : ndarray of shape (n_classes, n_features)
        Deviations (or shrinkages) of the centroids of each class from the
        overall centroid. Equal to eq. (18.4) if `shrink_threshold=None`,
        else (18.5) p. 653 of [2]. Can be used to identify features used
        for classification.

        .. versionadded:: 1.6

    within_class_std_dev_ : ndarray of shape (n_features,)
        Pooled or within-class standard deviation of input data.

        .. versionadded:: 1.6

    class_prior_ : ndarray of shape (n_classes,)
        The class prior probabilities.

        .. versionadded:: 1.6

    See Also
    --------
    KNeighborsClassifier : Nearest neighbors classifier.

    Notes
    -----
    When used for text classification with tf-idf vectors, this classifier is
    also known as the Rocchio classifier.

    References
    ----------
    [1] Tibshirani, R., Hastie, T., Narasimhan, B., & Chu, G. (2002). Diagnosis of
    multiple cancer types by shrunken centroids of gene expression. Proceedings
    of the National Academy of Sciences of the United States of America,
    99(10), 6567-6572. The National Academy of Sciences.

    [2] Hastie, T., Tibshirani, R., Friedman, J. (2009). The Elements of Statistical
    Learning Data Mining, Inference, and Prediction. 2nd Edition. New York, Springer.

    Examples
    --------
    >>> from sklearn.neighbors import NearestCentroid
    >>> import numpy as np
    >>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
    >>> y = np.array([1, 1, 1, 2, 2, 2])
    >>> clf = NearestCentroid()
    >>> clf.fit(X, y)
    NearestCentroid()
    >>> print(clf.predict([[-0.8, -1]]))
    [1]
    Ú	manhattanÚ	euclideanr   NÚneither)Úclosedz
array-likeÚ	empiricalÚuniform©ÚmetricÚshrink_thresholdÚpriorsÚ_parameter_constraints)r   r    c                ó.   — || _         || _        || _        y )Nr   )Úselfr   r   r    s       úa/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/sklearn/neighbors/_nearest_centroid.pyÚ__init__zNearestCentroid.__init__�   s   € ð ˆŒØ 0ˆÔØˆ�ó    T)Úprefer_skip_nested_validationc                 óŠ  — | j                   dk(  rt        | ||dg¬«      \  }}n8t        | «      j                  j                  rdnd}t        | |||ddg¬«      \  }}t        j                  |«      }t        |«       |j                  \  }}t        «       }|j                  |«      }|j                  x| _        }	|	j                  }
|
dk  rt        d	|
z  «      ‚| j                  d
k(  rJt        j                   |d¬«      \  }}t        j"                  |«      t%        t'        |«      «      z  | _        nU| j                  dk(  r"t        j*                  d|
z  g|
z  «      | _        n$t        j*                  | j                  «      | _        | j(                  dk  j-                  «       rt        d«      ‚t        j.                  | j(                  j1                  «       d«      sFt3        j4                  dt6        «       | j(                  | j(                  j1                  «       z  | _        t        j8                  |
|ft        j:                  ¬«      | _        t        j>                  |
«      }tA        |
«      D ]°  }||k(  }t        j0                  |«      ||<   |rt        jB                  |«      d   }| j                   dk(  rF|s(t        jD                  ||   d¬«      | j<                  |<   ŒstG        ||   «      | j<                  |<   Œ�||   jI                  d¬«      | j<                  |<   Œ² t        jJ                  || j<                  |   z
  d¬«      dz  }t        jJ                  t        jL                  |j1                  d¬«      ||
z
  z  «      d¬«      | _'        t-        | jN                  dk(  «      rt3        j4                  d«       d}|rTt        jP                  |jS                  d¬«      |jU                  d¬«      z
  jW                  «       dk(  «      rt        |«      ‚|s8t        jP                  t        jX                  |d¬«      dk(  «      rt        |«      ‚|jI                  d¬«      }t        jL                  d|z  d|z  z
  «      }| jN                  t        jD                  | jN                  «      z   }|j[                  t'        |«      d«      }||z  }t        jJ                  | j<                  |z
  |z  d¬«      | _.        | j^                  rÀt        j`                  | j\                  «      }t        jb                  | j\                  «      | j^                  z
  | _.        t        jd                  | j\                  dd| j\                  ¬«       | xj\                  |z  c_.        || j\                  z  }t        jJ                  ||z   d¬«      | _        | S )a0  
        Fit the NearestCentroid model according to the given training data.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            Training vector, where `n_samples` is the number of samples and
            `n_features` is the number of features.
            Note that centroid shrinking cannot be used with sparse matrices.
        y : array-like of shape (n_samples,)
            Target values.

        Returns
        -------
        self : object
            Fitted estimator.
        r   Úcsc)Úaccept_sparseú	allow-nanTÚcsr)Úensure_all_finiter*   r   z>The number of classes has to be greater than one; got %d classr   )Úreturn_inverser   é   r   zpriors must be non-negativeg      ð?zAThe priors do not sum to 1. Normalizing such that it sums to one.©Údtype)ÚaxisF)Úcopyz†self.within_class_std_dev_ has at least 1 zero standard deviation.Inputs within the same classes for at least 1 feature are identical.z2All features have zero variance. Division by zero.N)Úout)3r   r   r   Ú
input_tagsÚ	allow_nanÚspÚissparser   Úshaper   Úfit_transformÚclasses_ÚsizeÚ
ValueErrorr    ÚnpÚuniqueÚbincountÚfloatÚlenÚclass_prior_ÚasarrayÚanyÚiscloseÚsumÚwarningsÚwarnÚUserWarningÚemptyÚfloat64Ú
centroids_ÚzerosÚrangeÚwhereÚmedianr   ÚmeanÚarrayÚsqrtÚwithin_class_std_dev_ÚallÚmaxÚminÚtoarrayÚptpÚreshapeÚdeviations_r   ÚsignÚabsÚclip)r#   ÚXÚyr-   Úis_X_sparseÚ	n_samplesÚ
n_featuresÚleÚy_indÚclassesÚ	n_classesÚ_Úclass_countsÚnkÚ	cur_classÚcenter_maskÚvarianceÚerr_msgÚdataset_centroid_ÚmÚsÚmmÚmsÚsignsÚmsds                            r$   ÚfitzNearestCentroid.fit˜   sÃ  € ð* �;‰;˜+Ò%Ü   q¨!¸E¸7ÔC‰DˆA‰qô  (¨›~×8Ñ8×BÒB‘Èð ô !ØØØØ"3Ø$ e˜nô‰DˆAˆqô —k‘k !“nˆÜ$ QÔ'à !§¡Ñˆ	�:Ü‹^ˆØ× Ñ  Ó#ˆØ"$§+¡+Ð-ˆŒ˜Ø—L‘Lˆ	Ø�qŠ=ÜØPØñóð ð
 �;‰;˜+Ò%Ü Ÿi™i¨¸$Ô?‰OˆAˆ|Ü "§¡¨LÓ 9¼EÄ#ÀaÃ&»MÑ IˆDÕØ�[‰[˜IÒ%Ü "§
¡
¨A°	©M¨?¸YÑ+FÓ GˆDÕä "§
¡
¨4¯;©;Ó 7ˆDÔà×Ñ Ñ!×&Ñ&Ô(ÜÐ:Ó;Ð;Ü�z‰z˜$×+Ñ+×/Ñ/Ó1°3Ô7Ü�M‰MØSÜôð !%× 1Ñ 1°D×4EÑ4E×4IÑ4IÓ4KÑ KˆDÔô Ÿ(™( I¨zÐ#:Ä"Ç*Á*ÔMˆŒô �X‰X�iÓ ˆä˜yÓ)ò 	IˆIØ 9Ñ,ˆKÜŸF™F ;Ó/ˆBˆy‰MÙÜ Ÿh™h {Ó3°AÑ6�à�{‰{˜kÒ)á"Ü13·±¸1¸[¹>ÐPQÔ1R�D—O‘O IÒ.ä1BÀ1À[Á>Ó1R�D—O‘O IÒ.à-.¨{©^×-@Ñ-@ÀaÐ-@Ó-H�—‘ 	Ò*ð	Iô  —8‘8˜A §¡°Ñ 6Ñ6¸UÔCÀqÑHˆÜ%'§X¡XÜ�G‰G�H—L‘L a�LÓ(¨I¸	Ñ,AÑBÓCÈ%ô&
ˆÔ"ô ˆt×)Ñ)¨QÑ.Ô/Ü�M‰MðWôð
 GˆÙœ2Ÿ6™6 1§5¡5¨a 5£=°1·5±5¸a°5³=Ñ#@×"IÑ"IÓ"KÈqÑ"PÔQÜ˜WÓ%Ð%Ù¤§¡¬¯©¨q°qÔ(9¸QÑ(>Ô!?Ü˜WÓ%Ð%àŸF™F¨˜F›NÐä�G‰G�S˜2‘X #¨	¡/Ñ2Ó3ˆð ×&Ñ&¬¯©°4×3MÑ3MÓ)NÑNˆØ�Y‰Y”s˜1“v˜qÓ!ˆØ�!‰VˆÜŸ8™8Ø�_‰_Ð0Ñ0°BÑ6¸Uô
ˆÔð
 × Ò Ü—G‘G˜D×,Ñ,Ó-ˆEÜ!Ÿv™v d×&6Ñ&6Ó7¸$×:OÑ:OÑOˆDÔÜ�G‰G�D×$Ñ$ a¨°4×3CÑ3CÕDØ×Ò Ñ%Õà�t×'Ñ'Ñ'ˆCÜ Ÿh™hÐ'8¸3Ñ'>ÀUÔKˆDŒOØˆr&   c                 ó„  •— t        | «       t        j                  | j                  dt	        | j
                  «      z  «      j                  «       rbt        | «      j                  j                  rdnd}t        | ||dd¬«      }| j
                  t        || j                  | j                  ¬«         S t        ‰| �=  |«      S )a€  Perform classification on an array of test vectors `X`.

        The predicted class `C` for each sample in `X` is returned.

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

        Returns
        -------
        y_pred : ndarray of shape (n_samples,)
            The predicted classes.
        r/   r+   Tr,   F)r-   r*   Úreset©r   )r   r>   rF   rC   rB   r;   rV   r   r5   r6   r   r   rM   r   ÚsuperÚpredict)r#   r`   r-   Ú	__class__s      €r$   r|   zNearestCentroid.predict  s©   ø€ ô 	˜ÔÜ�:‰:�d×'Ñ'¨¬S°·±Ó-?Ñ)?Ó@×DÑDÔFô  (¨›~×8Ñ8×BÒB‘Èð ô ØØØ"3Ø#ØôˆAð —=‘=Ü)¨!¨T¯_©_ÀTÇ[Á[ÔQñð ô ‘7‘? 1Ó%Ð%r&   c           	      óâ  — t        | d«       t        | |dddt        j                  ¬«      }t        j                  |j
                  d   | j                  j                  ft        j                  ¬«      }| j                  dk7  }|d d …|fxx   | j                  |   z  cc<   | j                  j                  «       }|d d …|fxx   | j                  |   z  cc<   t        | j                  j                  «      D ]t  }t        |||g   | j                  ¬«      j                  «       }|d	z  }t        j                  | d
t        j                   | j"                  |   «      z  z   «      |d d …|f<   Œv |S )NrM   TFr,   )r3   ry   r*   r1   r   r0   rz   r   g       @)r   r   r>   rL   rK   r9   r;   r<   rU   rM   r3   rO   r
   r   ÚravelÚsqueezeÚlogrC   )r#   r`   ÚX_normalizedÚdiscriminant_scoreÚmaskÚcentroids_normalizedÚ	class_idxÚ	distancess           r$   Ú_decision_functionz"NearestCentroid._decision_function8  sQ  € ä˜˜lÔ+ä$Ø�!˜$ e¸5ÌÏ
É
ô
ˆô  ŸX™XØ×Ñ Ñ" D§M¡M×$6Ñ$6Ð7¼r¿z¹zô
Ðð ×)Ñ)¨QÑ.ˆØ’Q˜�WÓ ×!;Ñ!;¸DÑ!AÑAÓØ#Ÿ™×3Ñ3Ó5ÐØšQ ˜WÓ%¨×)CÑ)CÀDÑ)IÑIÓ%ä˜tŸ}™}×1Ñ1Ó2ò 	ˆIÜ*ØÐ2°I°;Ñ?ÈÏÉôç‰e‹gð ð ˜!‰OˆIÜ/1¯z©zØ�
˜S¤2§6¡6¨$×*;Ñ*;¸IÑ*FÓ#GÑGÑGó0Ðšq )˜|Ò,ð	ð "Ð!r&   c                 ó    — | j                   dk(  S )Nr   rz   )r#   s    r$   Ú_check_euclidean_metricz'NearestCentroid._check_euclidean_metricT  s   € Ø�{‰{˜kÑ)Ð)r&   c                 ó‚   •— t         ‰| �  «       }| j                  dk(  |j                  _        d|j                  _        |S )NÚnan_euclideanT)r{   Ú__sklearn_tags__r   r5   r6   r   )r#   Útagsr}   s     €r$   r�   z NearestCentroid.__sklearn_tags__c  s6   ø€ Ü‰wÑ'Ó)ˆØ$(§K¡K°?Ñ$Bˆ�‰Ô!Ø!%ˆ�‰ÔØˆr&   )r   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r   r!   ÚdictÚ__annotations__r%   r   rw   r|   rˆ   rŠ   r   r	   Údecision_functionÚpredict_probaÚpredict_log_probar�   Ú__classcell__)r}   s   @r$   r   r      sö   ø… ñeñP ˜{¨KÐ8Ó9Ð:Ù% d¨A¨t¸IÔFÈÐMØ¡¨[¸)Ð,DÓ!EÐFñ$Ð˜Dó ð ð	ð Øô	ñ °Ô5ñ{ó 6ð{ôz &òD"ò8*ð >™Ð%<Ó=Ø+×=Ñ=óÐð :‘LÐ!8Ó9Ø+×9Ñ9ó€Mð >™Ð%<Ó=Ø+×=Ñ=óÐ÷ð r&   r   )#r’   rH   Únumbersr   Únumpyr>   Úscipyr   r7   Úbaser   r   r   Údiscriminant_analysisr	   Úmetrics.pairwiser
   r   Úpreprocessingr   Úutilsr   Úutils._available_ifr   Úutils._param_validationr   r   Úutils.multiclassr   Úutils.sparsefuncsr   Úutils.validationr   r   r   © r&   r$   ú<module>r§      sP   ðñó Ý ã Ý ç ?Ñ ?Ý G÷õ )Ý Ý .ß :Ý ;Ý 1ß =ôJØ'¨¸-õJr&   