o
    tBhj                      @   s   d Z ddlZddl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 dd
lmZ G dd de	eZdS )z!
Nearest Centroid Classification
    N)sparse   )BaseEstimatorClassifierMixin)pairwise_distances)LabelEncoder)check_is_fitted)csc_median_axis_0)check_classification_targetsc                   @   s0   e Zd ZdZdddddZdd Zd	d
 Zd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 : str or callable, default="euclidean"
        The metric to use when calculating distance between instances in a
        feature array. If metric is a string or callable, it must be one of
        the options allowed by
        :func:`~sklearn.metrics.pairwise_distances` for its metric
        parameter. The centroids for the samples corresponding to each class is
        the point from which the sum of the distances (according to the metric)
        of all samples that belong to that particular class are minimized.
        If the `"manhattan"` metric is provided, this centroid is the median
        and for all other metrics, the centroid is now set to be the mean.

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

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

    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

    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
    ----------
    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.

    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]
    	euclideanN)shrink_thresholdc                C   s   || _ || _d S )N)metricr   )selfr   r    r   z/var/www/html/riverr-enterprise-integrations-main/venv/lib/python3.10/site-packages/sklearn/neighbors/_nearest_centroid.py__init__a   s   
zNearestCentroid.__init__c                 C   st  | j dkr	td| j dkr| j||dgd\}}n| j||ddgd\}}t|}|r4| jr4tdt| |j\}}t }|	|}|j
 | _
}|j}	|	dk rXtd	|	 tj|	|ftjd
| _t|	}
t|	D ]I}||k}t||
|< |rt|d }| j dkr|stj|| dd| j|< qlt|| | j|< ql| j dkrtd || jdd| j|< ql| jr8ttj|dddkrtdtj|dd}td|
 d|  }|| j|  d }|jdd}t|||	  }|t|7 }|t|d}|| }| j| | }t|}t|| j }tj |dd|d ||9 }|| }|tj!ddf | | _| 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.
        precomputedzPrecomputed is not supported.	manhattancsc)accept_sparsecsrz2threshold shrinking not supported for sparse inputr   z>The number of classes has to be greater than one; got %d class)dtyper   axisr   zjAveraging for metrics other than euclidean and manhattan not supported. The average is set to be the mean.z2All features have zero variance. Division by zero.g      ?   N)out)"r   
ValueError_validate_dataspissparser   r
   shaper   fit_transformclasses_sizenpemptyfloat64
centroids_zerosrangesumwheremedianr	   warningswarnmeanallptpsqrtreshapelensignabsclipnewaxis)r   Xyis_X_sparse	n_samples
n_featuresley_indclasses	n_classesnk	cur_classcenter_maskdataset_centroid_mvariancesmmms	deviationsignsmsdr   r   r   fite   sn   









zNearestCentroid.fitc                 C   s8   t |  | j|ddd}| jt|| j| jdjdd S )aK  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)
            Test samples.

        Returns
        -------
        C : ndarray of shape (n_samples,)
            The predicted classes.

        Notes
        -----
        If the metric constructor parameter is `"precomputed"`, `X` is assumed
        to be the distance matrix between the data to be predicted and
        `self.centroids_`.
        r   F)r   reset)r   r   r   )r   r   r#   r   r(   r   argmin)r   r:   r   r   r   predict   s
   zNearestCentroid.predict)r   )__name__
__module____qualname____doc__r   rO   rR   r   r   r   r   r      s
    J_r   )rV   r.   numpyr%   scipyr   r   baser   r   metrics.pairwiser   preprocessingr   utils.validationr   utils.sparsefuncsr	   utils.multiclassr
   r   r   r   r   r   <module>   s    	