U
    9%e%                     @   s   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
 ddlmZmZ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 G dd deeZdS )z!
Nearest Centroid Classification
    N)Real)sparse)_VALID_METRICS   )BaseEstimatorClassifierMixin_fit_context)pairwise_distances_argmin)LabelEncoder)Interval
StrOptions)check_classification_targets)csc_median_axis_0)check_is_fittedc                   @   s   e Zd ZU dZeedddh Zeeeddh dege	e
dd	d
dd	gdZeed< dd	dddZedddd Zdd Zd	S )NearestCentroidag  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"
        Metric to use for distance computation. See the documentation of
        `scipy.spatial.distance
        <https://docs.scipy.org/doc/scipy/reference/spatial.distance.html>`_ and
        the metrics listed in
        :class:`~sklearn.metrics.pairwise.distance_metrics` for valid metric
        values. Note that "wminkowski", "seuclidean" and "mahalanobis" are not
        supported.

        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.

        .. deprecated:: 1.3
            Support for metrics other than `euclidean` and `manhattan` and for
            callables was deprecated in version 1.3 and will be removed in
            version 1.5.

        .. 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]
    ZmahalanobisZ
seuclideanZ
wminkowski	manhattan	euclidean)
deprecatedr   NZneither)closedmetricshrink_threshold_parameter_constraints)r   c                C   s   || _ || _d S )Nr   )selfr   r    r   b/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/sklearn/neighbors/_nearest_centroid.py__init__{   s    zNearestCentroid.__init__T)Zprefer_skip_nested_validationc                 C   s  t | jtr"| jdkr"tdt | jdkrD| j||dgd\}}n| j||ddgd\}}t|}|rx| j	rxt
dt| |j\}}t }||}|j | _}|j}	|	dk rt
d	|	 tj|	|ftjd
| _t|	}
t|	D ]}||k}t||
|< |rt|d }| jdkrV|sBtj|| dd| j|< nt|| | j|< q| jdkrltd || jdd| j|< q| j	rt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.
        )r   r   zSupport for distance metrics other than euclidean and manhattan and for callables was deprecated in version 1.3 and will be removed in version 1.5.r   Zcsc)accept_sparsecsrz2threshold shrinking not supported for sparse inputr   z>The number of classes has to be greater than one; got %d class)Zdtyper   )Z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)%
isinstancer   strwarningswarnFutureWarning_validate_dataspissparser   
ValueErrorr   shaper
   Zfit_transformclasses_sizenpemptyZfloat64
centroids_ZzerosrangesumwhereZmedianr   ZmeanallZptpsqrtZreshapelensignabsZclipZnewaxis)r   XyZis_X_sparseZ	n_samplesZ
n_featuresleZy_indclassesZ	n_classesZnkZ	cur_classZcenter_maskZdataset_centroid_mZvariancesmmmsZ	deviationZsignsZmsdr   r   r   fit   st    






zNearestCentroid.fitc                 C   s0   t |  | j|ddd}| jt|| j| j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   r8   r   r   r   predict   s
    zNearestCentroid.predict)r   )__name__
__module____qualname____doc__setr   Z_valid_metricsr   callabler   r   r   dict__annotations__r   r   r@   rB   r   r   r   r   r      s   
S 


kr   )rF   r#   numbersr   numpyr-   Zscipyr   r'   Zsklearn.metrics.pairwiser   baser   r   r   Zmetrics.pairwiser	   Zpreprocessingr
   Zutils._param_validationr   r   Zutils.multiclassr   Zutils.sparsefuncsr   Zutils.validationr   r   r   r   r   r   <module>   s   	