
    0PhN              
          d Z ddlZddlmZ ddlmZ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 dd
lmZmZmZ ddlmZmZ ddlmZmZ ddlmZmZ  edg eeddd          g eeddd          dgdgedgdd          dddddd            Z d Z! eddgid          ddddddddd            Z"d#d Z# G d! d"ee          Z$dS )$a  Mean shift clustering algorithm.

Mean shift clustering aims to discover *blobs* in a smooth density of
samples. It is a centroid based algorithm, which works by updating candidates
for centroids to be the mean of the points within a given region. These
candidates are then filtered in a post-processing stage to eliminate
near-duplicates to form the final set of centroids.

Seeding is performed using a binning technique for scalability.
    N)defaultdict)IntegralReal   )config_context)BaseEstimatorClusterMixin_fit_context)pairwise_distances_argmin)NearestNeighbors)check_arraycheck_random_stategen_batches)Intervalvalidate_params)Paralleldelayed)check_is_fittedvalidate_data
array-like   bothclosedleftrandom_state)Xquantile	n_samplesr   n_jobsTprefer_skip_nested_validationg333333?)r   r   r   r    c                :   t          |           } t          |          }|0|                    | j        d                   d|         }| |         } t	          | j        d         |z            }|dk     rd}t          ||          }|                    |            d}t          t          |           d          D ]Q}	|	                    | |	ddf         d          \  }
}|t          j        |
d	                                          z  }R|| j        d         z  S )
a  Estimate the bandwidth to use with the mean-shift algorithm.

    This function takes time at least quadratic in `n_samples`. For large
    datasets, it is wise to subsample by setting `n_samples`. Alternatively,
    the parameter `bandwidth` can be set to a small value without estimating
    it.

    Parameters
    ----------
    X : array-like of shape (n_samples, n_features)
        Input points.

    quantile : float, default=0.3
        Should be between [0, 1]
        0.5 means that the median of all pairwise distances is used.

    n_samples : int, default=None
        The number of samples to use. If not given, all samples are used.

    random_state : int, RandomState instance, default=None
        The generator used to randomly select the samples from input points
        for bandwidth estimation. Use an int to make the randomness
        deterministic.
        See :term:`Glossary <random_state>`.

    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.

    Returns
    -------
    bandwidth : float
        The bandwidth parameter.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.cluster import estimate_bandwidth
    >>> X = np.array([[1, 1], [2, 1], [1, 0],
    ...               [4, 7], [3, 5], [3, 6]])
    >>> estimate_bandwidth(X, quantile=0.5)
    np.float64(1.61...)
    Nr   r   n_neighborsr    g        i  Treturn_distanceaxis)r   r   permutationshapeintr   fitr   len
kneighborsnpmaxsum)r   r   r   r   r    idxr%   nbrs	bandwidthbatchd_s               [/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/sklearn/cluster/_mean_shift.pyestimate_bandwidthr:      s   p 	AA%l33L&&qwqz22:I:>cFagaj8+,,KQFCCCDHHQKKKISVVS)) - -q{DAA1RVAA&&&**,,,		qwqz!!    c                    |                                 d         }d|z  }d}	 |                    | g|d          d         }||         }t          |          dk    rnK| }	t          j        |d          } t          j                            | |	z
            |k    s||k    rn|dz  }t          |           t          |          |fS )	NradiusgMbP?r   TFr&   r(   r   )
get_paramsradius_neighborsr.   r0   meanlinalgnormtuple)
my_meanr   r4   max_iterr5   stop_threshcompleted_iterationsi_nbrspoints_withinmy_old_means
             r9   _mean_shift_single_seedrK   l   s    !!(+I"K"&&y)U&SSTUV&	}""'-a000 INN7[011[@@#x//!" >>3}--/CCCr;   r   F,  )r5   seedsbin_seedingmin_bin_freqcluster_allrE   r    c          	      p    t          |||||||                              |           }|j        |j        fS )a  Perform mean shift clustering of data using a flat kernel.

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

    Parameters
    ----------

    X : array-like of shape (n_samples, n_features)
        Input data.

    bandwidth : float, default=None
        Kernel bandwidth. If not None, must be in the range [0, +inf).

        If None, the bandwidth is determined using a heuristic based on
        the median of all pairwise distances. This will take quadratic time in
        the number of samples. The sklearn.cluster.estimate_bandwidth function
        can be used to do this more efficiently.

    seeds : array-like of shape (n_seeds, n_features) or None
        Point used as initial kernel locations. If None and bin_seeding=False,
        each data point is used as a seed. If None and bin_seeding=True,
        see bin_seeding.

    bin_seeding : bool, default=False
        If true, initial kernel locations are not locations of all
        points, but rather the location of the discretized version of
        points, where points are binned onto a grid whose coarseness
        corresponds to the bandwidth. Setting this option to True will speed
        up the algorithm because fewer seeds will be initialized.
        Ignored if seeds argument is not None.

    min_bin_freq : int, default=1
       To speed up the algorithm, accept only those bins with at least
       min_bin_freq points as seeds.

    cluster_all : bool, default=True
        If true, then all points are clustered, even those orphans that are
        not within any kernel. Orphans are assigned to the nearest kernel.
        If false, then orphans are given cluster label -1.

    max_iter : int, default=300
        Maximum number of iterations, per seed point before the clustering
        operation terminates (for that seed point), if has not converged yet.

    n_jobs : int, default=None
        The number of jobs to use for the computation. The following tasks benefit
        from the parallelization:

        - The search of nearest neighbors for bandwidth estimation and label
          assignments. See the details in the docstring of the
          ``NearestNeighbors`` class.
        - Hill-climbing optimization for all seeds.

        See :term:`Glossary <n_jobs>` for more details.

        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

        .. versionadded:: 0.17
           Parallel Execution using *n_jobs*.

    Returns
    -------

    cluster_centers : ndarray of shape (n_clusters, n_features)
        Coordinates of cluster centers.

    labels : ndarray of shape (n_samples,)
        Cluster labels for each point.

    Notes
    -----
    For a usage example, see
    :ref:`sphx_glr_auto_examples_cluster_plot_mean_shift.py`.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.cluster import mean_shift
    >>> X = np.array([[1, 1], [2, 1], [1, 0],
    ...               [4, 7], [3, 5], [3, 6]])
    >>> cluster_centers, labels = mean_shift(X, bandwidth=2)
    >>> cluster_centers
    array([[3.33..., 6.     ],
           [1.33..., 0.66...]])
    >>> labels
    array([1, 1, 1, 0, 0, 0])
    )r5   rM   rO   rN   rP   r    rE   )	MeanShiftr-   cluster_centers_labels_)	r   r5   rM   rN   rO   rP   rE   r    models	            r9   
mean_shiftrV      sP    P !   
c!ff 
 !5=00r;   c                    |dk    r| S t          t                    }| D ]6}t          j        ||z            }|t	          |          xx         dz  cc<   7t          j        fd|                                D             t          j                  }t          |          t          |           k    rt          j
        d|z             | S ||z  }|S )a  Find seeds for mean_shift.

    Finds seeds by first binning data onto a grid whose lines are
    spaced bin_size apart, and then choosing those bins with at least
    min_bin_freq points.

    Parameters
    ----------

    X : array-like of shape (n_samples, n_features)
        Input points, the same points that will be used in mean_shift.

    bin_size : float
        Controls the coarseness of the binning. Smaller values lead
        to more seeding (which is computationally more expensive). If you're
        not sure how to set this, set it to the value of the bandwidth used
        in clustering.mean_shift.

    min_bin_freq : int, default=1
        Only bins with at least min_bin_freq will be selected as seeds.
        Raising this value decreases the number of seeds found, which
        makes mean_shift computationally cheaper.

    Returns
    -------
    bin_seeds : array-like of shape (n_samples, n_features)
        Points used as initial kernel positions in clustering.mean_shift.
    r   r   c                 &    g | ]\  }}|k    |S  rY   ).0pointfreqrO   s      r9   
<listcomp>z!get_bin_seeds.<locals>.<listcomp>  s'    LLL;5$t|7K7K7K7K7Kr;   dtypezJBinning data failed with provided bin_size=%f, using data points as seeds.)r   r,   r0   roundrC   arrayitemsfloat32r.   warningswarn)r   bin_sizerO   	bin_sizesr[   binned_point	bin_seedss     `    r9   get_bin_seedsrj      s    : 1}} C  I , ,x 011%%%&&&!+&&&& LLLL)//"3"3LLLj  I 9~~QX	
 	
 	
 H$Ir;   c                       e Zd ZU dZ eeddd          dgddgdg eeddd	          gdgedg eeddd	          gd
Zee	d<   dddddddd
dZ
 ed          dd            Zd ZdS )rR   a1  Mean shift clustering using a flat kernel.

    Mean shift clustering aims to discover "blobs" in a smooth density of
    samples. It is a centroid-based algorithm, which works by updating
    candidates for centroids to be the mean of the points within a given
    region. These candidates are then filtered in a post-processing stage to
    eliminate near-duplicates to form the final set of centroids.

    Seeding is performed using a binning technique for scalability.

    For an example of how to use MeanShift clustering, refer to:
    :ref:`sphx_glr_auto_examples_cluster_plot_mean_shift.py`.

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

    Parameters
    ----------
    bandwidth : float, default=None
        Bandwidth used in the flat kernel.

        If not given, the bandwidth is estimated using
        sklearn.cluster.estimate_bandwidth; see the documentation for that
        function for hints on scalability (see also the Notes, below).

    seeds : array-like of shape (n_samples, n_features), default=None
        Seeds used to initialize kernels. If not set,
        the seeds are calculated by clustering.get_bin_seeds
        with bandwidth as the grid size and default values for
        other parameters.

    bin_seeding : bool, default=False
        If true, initial kernel locations are not locations of all
        points, but rather the location of the discretized version of
        points, where points are binned onto a grid whose coarseness
        corresponds to the bandwidth. Setting this option to True will speed
        up the algorithm because fewer seeds will be initialized.
        The default value is False.
        Ignored if seeds argument is not None.

    min_bin_freq : int, default=1
       To speed up the algorithm, accept only those bins with at least
       min_bin_freq points as seeds.

    cluster_all : bool, default=True
        If true, then all points are clustered, even those orphans that are
        not within any kernel. Orphans are assigned to the nearest kernel.
        If false, then orphans are given cluster label -1.

    n_jobs : int, default=None
        The number of jobs to use for the computation. The following tasks benefit
        from the parallelization:

        - The search of nearest neighbors for bandwidth estimation and label
          assignments. See the details in the docstring of the
          ``NearestNeighbors`` class.
        - Hill-climbing optimization for all seeds.

        See :term:`Glossary <n_jobs>` for more details.

        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

    max_iter : int, default=300
        Maximum number of iterations, per seed point before the clustering
        operation terminates (for that seed point), if has not converged yet.

        .. versionadded:: 0.22

    Attributes
    ----------
    cluster_centers_ : ndarray of shape (n_clusters, n_features)
        Coordinates of cluster centers.

    labels_ : ndarray of shape (n_samples,)
        Labels of each point.

    n_iter_ : int
        Maximum number of iterations performed on each seed.

        .. versionadded:: 0.22

    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
    --------
    KMeans : K-Means clustering.

    Notes
    -----

    Scalability:

    Because this implementation uses a flat kernel and
    a Ball Tree to look up members of each kernel, the complexity will tend
    towards O(T*n*log(n)) in lower dimensions, with n the number of samples
    and T the number of points. In higher dimensions the complexity will
    tend towards O(T*n^2).

    Scalability can be boosted by using fewer seeds, for example by using
    a higher value of min_bin_freq in the get_bin_seeds function.

    Note that the estimate_bandwidth function is much less scalable than the
    mean shift algorithm and will be the bottleneck if it is used.

    References
    ----------

    Dorin Comaniciu and Peter Meer, "Mean Shift: A robust approach toward
    feature space analysis". IEEE Transactions on Pattern Analysis and
    Machine Intelligence. 2002. pp. 603-619.

    Examples
    --------
    >>> from sklearn.cluster import MeanShift
    >>> import numpy as np
    >>> X = np.array([[1, 1], [2, 1], [1, 0],
    ...               [4, 7], [3, 5], [3, 6]])
    >>> clustering = MeanShift(bandwidth=2).fit(X)
    >>> clustering.labels_
    array([1, 1, 1, 0, 0, 0])
    >>> clustering.predict([[0, 0], [5, 5]])
    array([1, 0])
    >>> clustering
    MeanShift(bandwidth=2)
    r   Nneitherr   r   booleanr   r   )r5   rM   rN   rO   rP   r    rE   _parameter_constraintsFTrL   c                h    || _         || _        || _        || _        || _        || _        || _        d S N)r5   rM   rN   rP   rO   r    rE   )selfr5   rM   rN   rO   rP   r    rE   s           r9   __init__zMeanShift.__init__  s<     #
&&( r;   r!   c                     t                      j        }|t           j                  } j        }|  j        rt          | j                  }n}j        \  }}i }t          |d          
                               t           j                   fd|D                       }t          t          |                    D ]-}	||	         d         r||	         d         |||	         d         <   .t          d |D                        _        |st!          d|z            t#          |                                d	 d
          }
t'          j        d |
D                       }t'          j        t          |          t,                    }t          | j                  
                    |          t/          |          D ]5\  }	}||	         r(                    |gd          d         }d||<   d||	<   6||         }t          d j                  
                    |          t'          j        |t4                    }                              \  }} j        r|                                }nJ|                    d           |                                |k    }|                                |         ||<   ||c _         _          S )aH  Perform clustering.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
            Samples to cluster.

        y : Ignored
            Not used, present for API consistency by convention.

        Returns
        -------
        self : object
               Fitted instance.
        N)r    r   )r=   r    c              3   b   K   | ])} t          t                    |j                  V  *d S rp   )r   rK   rE   )rZ   seedr   r4   rq   s     r9   	<genexpr>z MeanShift.fit.<locals>.<genexpr>  sR       /
 /
 -G+,,T1dDMJJ/
 /
 /
 /
 /
 /
r;   r   c                     g | ]
}|d          S )r   rY   )rZ   xs     r9   r]   z!MeanShift.fit.<locals>.<listcomp>   s    222QAaD222r;   zNo point was within bandwidth=%f of any seed. Try a different seeding strategy                              or increase the bandwidth.c                 "    | d         | d         fS )Nr   r   rY   )tups    r9   <lambda>zMeanShift.fit.<locals>.<lambda>  s    SVSV, r;   T)keyreversec                     g | ]
}|d          S )r   rY   )rZ   rz   s     r9   r]   z!MeanShift.fit.<locals>.<listcomp>  s    "I"I"Ic3q6"I"I"Ir;   r^   Fr&   r$   )!r   r5   r:   r    rM   rN   rj   rO   r+   r   r-   r   ranger.   r1   n_iter_
ValueErrorsortedrb   r0   ra   onesbool	enumerater?   zerosr,   r/   rP   flattenfillrS   rT   )rq   r   yr5   rM   r   
n_featurescenter_intensity_dictall_resisorted_by_intensitysorted_centersuniquecenterneighbor_idxscluster_centerslabels	distancesidxsbool_selectorr4   s   ``                  @r9   r-   zMeanShift.fit  s:   " $""N	*1T[AAAI
= %aD4EFF !	: "
  y;;;??BB /($+... /
 /
 /
 /
 /
 /
/
 /
 /
 
 

 s5zz"" 	E 	EAqz!} E7>qz!}%gajm422'22233$ 	T   %!'')),,
 
 

 "I"I5H"I"I"IJJ^,,D999yEEEII
 
 #>22 	 	IAvay  $ 5 5vhPU 5 V V! )*}%q	(0  AdkBBBFFWW)3/////!,,	4 	B\\^^FFKKOOO%--//9<M$(LLNN=$AF=!.=v+t|r;   c                     t          |            t          | |d          }t          d          5  t          || j                  cddd           S # 1 swxY w Y   dS )aJ  Predict the closest cluster each sample in X belongs to.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
            New data to predict.

        Returns
        -------
        labels : ndarray of shape (n_samples,)
            Index of the cluster each sample belongs to.
        F)resetT)assume_finiteN)r   r   r   r   rS   )rq   r   s     r9   predictzMeanShift.predict0  s     	$///$/// 	G 	G,Q0EFF	G 	G 	G 	G 	G 	G 	G 	G 	G 	G 	G 	G 	G 	G 	G 	G 	G 	Gs   AAArp   )__name__
__module____qualname____doc__r   r   r   rn   dict__annotations__rr   r
   r-   r   rY   r;   r9   rR   rR   ,  s!        F FR htQY???F%!{!(AtFCCCD!{T"Xh4???@$ $D    ! ! ! ! !& \555[ [ [ 65[zG G G G Gr;   rR   )r   )%r   rd   collectionsr   numbersr   r   numpyr0   _configr   baser   r	   r
   metrics.pairwiser   	neighborsr   utilsr   r   r   utils._param_validationr   r   utils.parallelr   r   utils.validationr   r   r:   rK   rV   rj   rR   rY   r;   r9   <module>r      sz  	 	  # # # # # # " " " " " " " "     $ $ $ $ $ $ < < < < < < < < < < 8 8 8 8 8 8 ( ( ( ( ( ( @ @ @ @ @ @ @ @ @ @ ? ? ? ? ? ? ? ? . . . . . . . . = = = = = = = = ^XdAq8889hxD@@@$G'(T"  #'	 	 	 '*TRV ?" ?" ?" ?"	 	?"FD D D. <."'   
m1 m1 m1 m1	 m1`2 2 2 2jTG TG TG TG TGm TG TG TG TG TGr;   