o
    tBhc                     @   s   d Z ddlZddlmZ ddlmZ ddlmZm	Z	 ddl
Z
ddlmZmZ dd	lmZmZmZ dd
lmZ G dd deeeZG dd deeeZdS )zNearest Neighbor Classification    N)stats   )weighted_mode)_is_arraylike_num_samples   )_check_weights_get_weights)NeighborsBaseKNeighborsMixinRadiusNeighborsMixin)ClassifierMixinc                	       sV   e Zd ZdZ	ddddddddd	 fd
dZdd Zdd Zdd Zdd Z  Z	S )KNeighborsClassifiera!  Classifier implementing the k-nearest neighbors vote.

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

    Parameters
    ----------
    n_neighbors : int, default=5
        Number of neighbors to use by default for :meth:`kneighbors` queries.

    weights : {'uniform', 'distance'} or callable, default='uniform'
        Weight function used in prediction.  Possible values:

        - 'uniform' : uniform weights.  All points in each neighborhood
          are weighted equally.
        - 'distance' : weight points by the inverse of their distance.
          in this case, closer neighbors of a query point will have a
          greater influence than neighbors which are further away.
        - [callable] : a user-defined function which accepts an
          array of distances, and returns an array of the same shape
          containing the weights.

    algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, default='auto'
        Algorithm used to compute the nearest neighbors:

        - 'ball_tree' will use :class:`BallTree`
        - 'kd_tree' will use :class:`KDTree`
        - 'brute' will use a brute-force search.
        - 'auto' will attempt to decide the most appropriate algorithm
          based on the values passed to :meth:`fit` method.

        Note: fitting on sparse input will override the setting of
        this parameter, using brute force.

    leaf_size : int, default=30
        Leaf size passed to BallTree or KDTree.  This can affect the
        speed of the construction and query, as well as the memory
        required to store the tree.  The optimal value depends on the
        nature of the problem.

    p : int, default=2
        Power parameter for the Minkowski metric. When p = 1, this is
        equivalent to using manhattan_distance (l1), and euclidean_distance
        (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used.

    metric : str or callable, default='minkowski'
        The distance metric to use for the tree.  The default metric is
        minkowski, and with p=2 is equivalent to the standard Euclidean
        metric. For a list of available metrics, see the documentation of
        :class:`~sklearn.metrics.DistanceMetric` and the metrics listed in
        `sklearn.metrics.pairwise.PAIRWISE_DISTANCE_FUNCTIONS`. Note that the
        "cosine" metric uses :func:`~sklearn.metrics.pairwise.cosine_distances`.
        If metric is "precomputed", X is assumed to be a distance matrix and
        must be square during fit. X may be a :term:`sparse graph`,
        in which case only "nonzero" elements may be considered neighbors.

    metric_params : dict, default=None
        Additional keyword arguments for the metric function.

    n_jobs : int, default=None
        The number of parallel jobs to run for neighbors search.
        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.
        Doesn't affect :meth:`fit` method.

    Attributes
    ----------
    classes_ : array of shape (n_classes,)
        Class labels known to the classifier

    effective_metric_ : str or callble
        The distance metric used. It will be same as the `metric` parameter
        or a synonym of it, e.g. 'euclidean' if the `metric` parameter set to
        'minkowski' and `p` parameter set to 2.

    effective_metric_params_ : dict
        Additional keyword arguments for the metric function. For most metrics
        will be same with `metric_params` parameter, but may also contain the
        `p` parameter value if the `effective_metric_` attribute is set to
        'minkowski'.

    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_samples_fit_ : int
        Number of samples in the fitted data.

    outputs_2d_ : bool
        False when `y`'s shape is (n_samples, ) or (n_samples, 1) during fit
        otherwise True.

    See Also
    --------
    RadiusNeighborsClassifier: Classifier based on neighbors within a fixed radius.
    KNeighborsRegressor: Regression based on k-nearest neighbors.
    RadiusNeighborsRegressor: Regression based on neighbors within a fixed radius.
    NearestNeighbors: Unsupervised learner for implementing neighbor searches.

    Notes
    -----
    See :ref:`Nearest Neighbors <neighbors>` in the online documentation
    for a discussion of the choice of ``algorithm`` and ``leaf_size``.

    .. warning::

       Regarding the Nearest Neighbors algorithms, if it is found that two
       neighbors, neighbor `k+1` and `k`, have identical distances
       but different labels, the results will depend on the ordering of the
       training data.

    https://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm

    Examples
    --------
    >>> X = [[0], [1], [2], [3]]
    >>> y = [0, 0, 1, 1]
    >>> from sklearn.neighbors import KNeighborsClassifier
    >>> neigh = KNeighborsClassifier(n_neighbors=3)
    >>> neigh.fit(X, y)
    KNeighborsClassifier(...)
    >>> print(neigh.predict([[1.1]]))
    [0]
    >>> print(neigh.predict_proba([[0.9]]))
    [[0.666... 0.333...]]
       uniformauto   r   	minkowskiN)weights	algorithm	leaf_sizepmetricmetric_paramsn_jobsc          	   	      s$   t  j|||||||d || _d S )N)n_neighborsr   r   r   r   r   r   )super__init__r   )	selfr   r   r   r   r   r   r   r   	__class__ x/var/www/html/riverr-enterprise-integrations-main/venv/lib/python3.10/site-packages/sklearn/neighbors/_classification.pyr      s   
	zKNeighborsClassifier.__init__c                 C   s   t | j| _| ||S )a  Fit the k-nearest neighbors classifier from the training dataset.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features) or                 (n_samples, n_samples) if metric='precomputed'
            Training data.

        y : {array-like, sparse matrix} of shape (n_samples,) or                 (n_samples, n_outputs)
            Target values.

        Returns
        -------
        self : KNeighborsClassifier
            The fitted k-nearest neighbors classifier.
        )r   r   _fit)r   Xyr!   r!   r"   fit   s   zKNeighborsClassifier.fitc                 C   s  | j dkr| j|dd}d}n| |\}}| j}| j}| js)| jd}| jg}t|}t|}t|| j }t	j
||f|d jd}	t|D ]8\}
}|du r]tj|||
f dd	\}}nt|||
f |dd	\}}t	j| t	jd}|||	dd|
f< qG| js|	 }	|	S )
  Predict the class labels for the provided data.

        Parameters
        ----------
        X : array-like of shape (n_queries, n_features),                 or (n_queries, n_indexed) if metric == 'precomputed'
            Test samples.

        Returns
        -------
        y : ndarray of shape (n_queries,) or (n_queries, n_outputs)
            Class labels for each data sample.
        r   Freturn_distanceNr   r   dtyper   axis)r   
kneighborsclasses__youtputs_2d_reshapelenr   r	   npemptyr-   	enumerater   moder   asarrayravelintptake)r   r$   	neigh_ind
neigh_distr1   r2   	n_outputs	n_queriesr   y_predk	classes_kr9   _r!   r!   r"   predict   s,   
zKNeighborsClassifier.predictc                 C   s:  | j dkr| j|dd}d}n| |\}}| j}| j}| js)| jd}| jg}t|}t|| j }|du r<t	|}t
|}g }	t|D ]L\}
}|dd|
f | }t||jf}t|jD ]\}}|||f  |dd|f 7  < qb|jddddtjf }d||d	k< || }|	| qG| js|	d
 }	|	S )a	  Return probability estimates for the test data X.

        Parameters
        ----------
        X : array-like of shape (n_queries, n_features),                 or (n_queries, n_indexed) if metric == 'precomputed'
            Test samples.

        Returns
        -------
        p : ndarray of shape (n_queries, n_classes), or a list of n_outputs                 of such arrays if n_outputs > 1.
            The class probabilities of the input samples. Classes are ordered
            by lexicographic order.
        r   Fr(   Nr*   r   r.         ?        r   )r   r0   r1   r2   r3   r4   r   r	   r6   	ones_likearanger8   zerossizeTsumnewaxisappend)r   r$   r>   r?   r1   r2   rA   r   all_rowsprobabilitiesrC   rD   pred_labelsproba_kiidx
normalizerr!   r!   r"   predict_proba   s6   


"z"KNeighborsClassifier.predict_probac                 C      ddiS N
multilabelTr!   r   r!   r!   r"   
_more_tags3     zKNeighborsClassifier._more_tags)r   
__name__
__module____qualname____doc__r   r&   rF   rX   r]   __classcell__r!   r!   r   r"   r      s"     	/:r   c                
       sX   e Zd ZdZ	dddddddddd	 fd
dZdd Zdd Zdd Zdd Z  Z	S )RadiusNeighborsClassifiera  Classifier implementing a vote among neighbors within a given radius.

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

    Parameters
    ----------
    radius : float, default=1.0
        Range of parameter space to use by default for :meth:`radius_neighbors`
        queries.

    weights : {'uniform', 'distance'} or callable, default='uniform'
        Weight function used in prediction.  Possible values:

        - 'uniform' : uniform weights.  All points in each neighborhood
          are weighted equally.
        - 'distance' : weight points by the inverse of their distance.
          in this case, closer neighbors of a query point will have a
          greater influence than neighbors which are further away.
        - [callable] : a user-defined function which accepts an
          array of distances, and returns an array of the same shape
          containing the weights.

        Uniform weights are used by default.

    algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, default='auto'
        Algorithm used to compute the nearest neighbors:

        - 'ball_tree' will use :class:`BallTree`
        - 'kd_tree' will use :class:`KDTree`
        - 'brute' will use a brute-force search.
        - 'auto' will attempt to decide the most appropriate algorithm
          based on the values passed to :meth:`fit` method.

        Note: fitting on sparse input will override the setting of
        this parameter, using brute force.

    leaf_size : int, default=30
        Leaf size passed to BallTree or KDTree.  This can affect the
        speed of the construction and query, as well as the memory
        required to store the tree.  The optimal value depends on the
        nature of the problem.

    p : int, default=2
        Power parameter for the Minkowski metric. When p = 1, this is
        equivalent to using manhattan_distance (l1), and euclidean_distance
        (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used.

    metric : str or callable, default='minkowski'
        Distance metric to use for the tree.  The default metric is
        minkowski, and with p=2 is equivalent to the standard Euclidean
        metric. For a list of available metrics, see the documentation of
        :class:`~sklearn.metrics.DistanceMetric`.
        If metric is "precomputed", X is assumed to be a distance matrix and
        must be square during fit. X may be a :term:`sparse graph`,
        in which case only "nonzero" elements may be considered neighbors.

    outlier_label : {manual label, 'most_frequent'}, default=None
        Label for outlier samples (samples with no neighbors in given radius).

        - manual label: str or int label (should be the same type as y)
          or list of manual labels if multi-output is used.
        - 'most_frequent' : assign the most frequent label of y to outliers.
        - None : when any outlier is detected, ValueError will be raised.

    metric_params : dict, default=None
        Additional keyword arguments for the metric function.

    n_jobs : int, default=None
        The number of parallel jobs to run for neighbors search.
        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

    **kwargs : dict
        Additional keyword arguments passed to the constructor.

        .. deprecated:: 1.0
            The RadiusNeighborsClassifier class will not longer accept extra
            keyword parameters in 1.2 since they are unused.

    Attributes
    ----------
    classes_ : ndarray of shape (n_classes,)
        Class labels known to the classifier.

    effective_metric_ : str or callable
        The distance metric used. It will be same as the `metric` parameter
        or a synonym of it, e.g. 'euclidean' if the `metric` parameter set to
        'minkowski' and `p` parameter set to 2.

    effective_metric_params_ : dict
        Additional keyword arguments for the metric function. For most metrics
        will be same with `metric_params` parameter, but may also contain the
        `p` parameter value if the `effective_metric_` attribute is set to
        'minkowski'.

    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_samples_fit_ : int
        Number of samples in the fitted data.

    outlier_label_ : int or array-like of shape (n_class,)
        Label which is given for outlier samples (samples with no neighbors
        on given radius).

    outputs_2d_ : bool
        False when `y`'s shape is (n_samples, ) or (n_samples, 1) during fit
        otherwise True.

    See Also
    --------
    KNeighborsClassifier : Classifier implementing the k-nearest neighbors
        vote.
    RadiusNeighborsRegressor : Regression based on neighbors within a
        fixed radius.
    KNeighborsRegressor : Regression based on k-nearest neighbors.
    NearestNeighbors : Unsupervised learner for implementing neighbor
        searches.

    Notes
    -----
    See :ref:`Nearest Neighbors <neighbors>` in the online documentation
    for a discussion of the choice of ``algorithm`` and ``leaf_size``.

    https://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm

    Examples
    --------
    >>> X = [[0], [1], [2], [3]]
    >>> y = [0, 0, 1, 1]
    >>> from sklearn.neighbors import RadiusNeighborsClassifier
    >>> neigh = RadiusNeighborsClassifier(radius=1.0)
    >>> neigh.fit(X, y)
    RadiusNeighborsClassifier(...)
    >>> print(neigh.predict([[1.5]]))
    [0]
    >>> print(neigh.predict_proba([[1.0]]))
    [[0.66666667 0.33333333]]
    rG   r   r   r   r   r   N)r   r   r   r   r   outlier_labelr   r   c             	      sN   t |
dkrtd|
  dt t j|||||||	d || _|| _d S )Nr   zPassing additional keyword parameters has no effect and is deprecated in 1.0. An error will be raised from 1.2 and beyond. The ignored keyword parameter(s) are: .)radiusr   r   r   r   r   r   )	r5   warningswarnkeysFutureWarningr   r   r   rf   )r   rh   r   r   r   r   r   rf   r   r   kwargsr   r!   r"   r     s$   	
z"RadiusNeighborsClassifier.__init__c                 C   sR  t | j| _| || | j}| j}| js| jd}| jg}| jdu r'd}n}| jdkrLg }t|D ]\}}t	
|dd|f }|||   q2nXt| jrot| jtsot| jt|krktd| jt|| j}n| jgt| }t||D ]'\}	}
t|
rt|
tstd|	|
t	|	|
j|	jkrtd|
|	q||| _| S )a  Fit the radius neighbors classifier from the training dataset.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features) or                 (n_samples, n_samples) if metric='precomputed'
            Training data.

        y : {array-like, sparse matrix} of shape (n_samples,) or                 (n_samples, n_outputs)
            Target values.

        Returns
        -------
        self : RadiusNeighborsClassifier
            The fitted radius neighbors classifier.
        r*   Nmost_frequentzJThe length of outlier_label: {} is inconsistent with the output length: {}zCThe outlier_label of classes {} is supposed to be a scalar, got {}.zCThe dtype of outlier_label {} is inconsistent with classes {} in y.)r   r   r#   r1   r2   r3   r4   rf   r8   r6   bincountrP   argmaxr   
isinstancestrr5   
ValueErrorformatzip	TypeErrorr-   outlier_label_)r   r$   r%   r1   r2   rw   rC   rD   label_countclasseslabelr!   r!   r"   r&     sN   

zRadiusNeighborsClassifier.fitc                 C   s   |  |}| j}| js|g}| jg}t|}|d jd }tj||f|d jd}t|D ]1\}}|j	dd}	|| 
|	|dd|f< |dkjdd}
|
 r^t|
}| j| |||f< q-| jsf| }|S )r'   r   r,   r   r.   N)rX   r1   r3   r5   shaper6   r7   r-   r8   rp   r=   allanyflatnonzerorw   r;   )r   r$   probsr1   r@   rA   rB   rC   probmax_prob_indexoutlier_zero_probszero_prob_indexr!   r!   r"   rF   9  s&   

z!RadiusNeighborsClassifier.predictc                    s>  t |}| |\}}tj|td}dd |D |dd< t|}t| }| j}| j | js;| j	d | jg}| j
du rK|jdkrKtd| t|| j}	|	durY|	| }	g }
t|D ]\}tjt|td} fdd|D |dd< t||jf}tt||jf}|	du rt|| D ]\}}tj||jd	||ddf< qnt|| D ]\}}tj||	| |jd	||ddf< q|||ddf< |jdkr| j
 }t||k}|jd
krd|||d f< ntd| j
  |jd
dddtjf }d||dk< || }|
| q_| js|
d }
|
S )a	  Return probability estimates for the test data X.

        Parameters
        ----------
        X : array-like of shape (n_queries, n_features),                 or (n_queries, n_indexed) if metric == 'precomputed'
            Test samples.

        Returns
        -------
        p : ndarray of shape (n_queries, n_classes), or a list of                 n_outputs of such arrays if n_outputs > 1.
            The class probabilities of the input samples. Classes are ordered
            by lexicographic order.
        r,   c                 S   s   g | ]}t |d kqS )r   )r5   ).0nindr!   r!   r"   
<listcomp>x      z;RadiusNeighborsClassifier.predict_proba.<locals>.<listcomp>Nr*   r   zNo neighbors found for test samples %r, you can try using larger radius, giving a label for outliers, or considering removing them from your dataset.c                    s   g | ]} |f qS r!   r!   )r   indr2   rC   r!   r"   r     r   )	minlengthr   rG   ziOutlier label {} is not in training classes. All class probabilities of outliers will be assigned with 0.r.   rH   )r   radius_neighborsr6   rK   boolr~   r1   r2   r3   r4   rw   rL   rs   r	   r   r8   r5   objectro   ri   rj   rt   rN   rO   rP   )r   r$   rA   r?   r>   outlier_maskoutliersinliersr1   r   rR   rD   rS   rT   	proba_inlrU   rV   _outlier_labellabel_indexrW   r!   r   r"   rX   c  sf   



z'RadiusNeighborsClassifier.predict_probac                 C   rY   rZ   r!   r\   r!   r!   r"   r]     r^   z$RadiusNeighborsClassifier._more_tags)rG   r_   r!   r!   r   r"   re   7  s$     #I*Xre   )rc   numpyr6   scipyr   utils.extmathr   utils.validationr   r   ri   _baser   r	   r
   r   r   baser   r   re   r!   r!   r!   r"   <module>   s    
  #