`L i`. 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 ` 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) Nrr n_neighborsr giTreturn_distanceaxis) r r permutationshapeintr fitrlen kneighborsnpmaxsum) rrrrr idxr%nbrs bandwidthbatchd_s a/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sklearn/cluster/_mean_shift.pyestimate_bandwidthr:sp AA%l3L&&qwwqz2:I> cFaggaj8+,KQ  F CDHHQKISVS)-q{DA1RVVAA&**,, - qwwqz !!cR|jd}d|z}d} |j|g|dd}||}t|dk(rnJ|} tj|d}tj j || z |ks||k(rn|dz }vt|t||fS)NradiusgMbP?rFr&r(r) get_paramsradius_neighborsr.r0meanlinalgnormtuple) my_meanrr4max_iterr5 stop_threshcompleted_iterationsi_nbrs points_within my_old_means r9_mean_shift_single_seedrKls!(+I"K &&y)U&STUV& }  "  ''-a0 IINN7[0 1[ @#x/ !  >3}-/C CCr;rF,)r5seeds bin_seeding min_bin_freq cluster_allrEr c tt|||||||j|}|j|jfS)a Perform mean shift clustering of data using a flat kernel. Read more in the :ref:`User Guide `. 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 ` for more details. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary ` 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]) )r5rMrOrNrPr rE) MeanShiftr-cluster_centers_labels_) rr5rMrNrOrPrEr models r9 mean_shiftrVsIP !  c!f   ! !5== 00r;c|dk(r|Stt}|D]0}tj||z }|t |xxdz cc<2tj |j Dcgc] \}}||k\s |c}}tj}t|t|k(rtjd|z|S||z}|Scc}}w)aFind 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. rrdtypezJBinning data failed with provided bin_size=%f, using data points as seeds.) rr,r0roundrCarrayitemsfloat32r.warningswarn)rbin_sizerO bin_sizespoint binned_pointfreq bin_seedss r9 get_bin_seedsrfs:1}C I,xx 01 % %&!+&, "+//"3L;5$t|7KLjjI 9~Q X  H$I  Ms . C <C c eZdZUdZeeddddgddgdgeeddd gdgedgeeddd gd Zee d <ddd dd ddd dZ e d ddZ dZ y)rRaMean 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 `. 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 ` for more details. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary ` 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) For a comparison of Mean Shift clustering with other clustering algorithms, see :ref:`sphx_glr_auto_examples_cluster_plot_cluster_comparison.py` rNneitherrrbooleanrr)r5rMrNrOrPr rE_parameter_constraintsFTrLcf||_||_||_||_||_||_||_yN)r5rMrNrPrOr rE)selfr5rMrNrOrPr rEs r9__init__zMeanShift.__init__s8# &&(   r;r!chtj}|tj}j}|&j rt |j}n}j\}}i}t|djtjfd|D}tt|D]} || ds || d||| d<t|D cgc]} | d c} _|st!d|zt#|j%dd } t'j(| D cgc]} | d c} } t'j*t| t, }t|jj| t/| D],\} }|| s j1|gd d}d||<d|| <.| |}tdjj|t'j2|t4 }j7\}}j8r|j;}n:|j=d|j;|k}|j;|||<||c__ Scc} wcc} w)aHPerform 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. )r r)r=r c3bK|]&}tt|j(ywrl)rrKrE).0seedrr4rms r9 z MeanShift.fit..s0/  -G+ ,T1dDMM J/ s,/rrzNo point was within bandwidth=%f of any seed. Try a different seeding strategy or increase the bandwidth.c|d|dfS)Nrr)tups r9zMeanShift.fit..sSVSV,r;T)keyreverserXFr&r$)!rr5r:r rMrNrfrOr+r r-rranger.r1n_iter_ ValueErrorsortedr\r0r[onesbool enumerater?zerosr,r/rPflattenfillrSrT)rmryr5rMr n_featurescenter_intensity_dictall_resixsorted_by_intensityrvsorted_centersuniquecenter neighbor_idxscluster_centerslabels distancesidxs bool_selectorr4s`` @r9r-z MeanShift.fits" $ "NN  *1T[[AI  =%aD4E4EF ! : "  y;??B/($++./ /   s5z" EAqz!}7>qz!}%gajm4 E'2QAaD23 $T % ! ' ' ),  5H"Ic3q6"IJ^,D9yEII  #>2 IAvay $ 5 5vhPU 5 V! )*}%q  )0 AdkkBFFW)3///!, 4   \\^F KKO%--/9rs #"$<<8(@@?.=^dAq89xD@$G'(T" #' '*TRV?" ?"FD.<."'   m1 m1`2jWG mWGr;