_mean_shift.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. """Mean shift clustering algorithm.
  2. Mean shift clustering aims to discover *blobs* in a smooth density of
  3. samples. It is a centroid based algorithm, which works by updating candidates
  4. for centroids to be the mean of the points within a given region. These
  5. candidates are then filtered in a post-processing stage to eliminate
  6. near-duplicates to form the final set of centroids.
  7. Seeding is performed using a binning technique for scalability.
  8. """
  9. # Authors: Conrad Lee <conradlee@gmail.com>
  10. # Alexandre Gramfort <alexandre.gramfort@inria.fr>
  11. # Gael Varoquaux <gael.varoquaux@normalesup.org>
  12. # Martino Sorbaro <martino.sorbaro@ed.ac.uk>
  13. import warnings
  14. from collections import defaultdict
  15. from numbers import Integral, Real
  16. import numpy as np
  17. from .._config import config_context
  18. from ..base import BaseEstimator, ClusterMixin, _fit_context
  19. from ..metrics.pairwise import pairwise_distances_argmin
  20. from ..neighbors import NearestNeighbors
  21. from ..utils import check_array, check_random_state, gen_batches
  22. from ..utils._param_validation import Interval, validate_params
  23. from ..utils.parallel import Parallel, delayed
  24. from ..utils.validation import check_is_fitted
  25. @validate_params(
  26. {
  27. "X": ["array-like"],
  28. "quantile": [Interval(Real, 0, 1, closed="both")],
  29. "n_samples": [Interval(Integral, 1, None, closed="left"), None],
  30. "random_state": ["random_state"],
  31. "n_jobs": [Integral, None],
  32. },
  33. prefer_skip_nested_validation=True,
  34. )
  35. def estimate_bandwidth(X, *, quantile=0.3, n_samples=None, random_state=0, n_jobs=None):
  36. """Estimate the bandwidth to use with the mean-shift algorithm.
  37. This function takes time at least quadratic in `n_samples`. For large
  38. datasets, it is wise to subsample by setting `n_samples`. Alternatively,
  39. the parameter `bandwidth` can be set to a small value without estimating
  40. it.
  41. Parameters
  42. ----------
  43. X : array-like of shape (n_samples, n_features)
  44. Input points.
  45. quantile : float, default=0.3
  46. Should be between [0, 1]
  47. 0.5 means that the median of all pairwise distances is used.
  48. n_samples : int, default=None
  49. The number of samples to use. If not given, all samples are used.
  50. random_state : int, RandomState instance, default=None
  51. The generator used to randomly select the samples from input points
  52. for bandwidth estimation. Use an int to make the randomness
  53. deterministic.
  54. See :term:`Glossary <random_state>`.
  55. n_jobs : int, default=None
  56. The number of parallel jobs to run for neighbors search.
  57. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
  58. ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
  59. for more details.
  60. Returns
  61. -------
  62. bandwidth : float
  63. The bandwidth parameter.
  64. """
  65. X = check_array(X)
  66. random_state = check_random_state(random_state)
  67. if n_samples is not None:
  68. idx = random_state.permutation(X.shape[0])[:n_samples]
  69. X = X[idx]
  70. n_neighbors = int(X.shape[0] * quantile)
  71. if n_neighbors < 1: # cannot fit NearestNeighbors with n_neighbors = 0
  72. n_neighbors = 1
  73. nbrs = NearestNeighbors(n_neighbors=n_neighbors, n_jobs=n_jobs)
  74. nbrs.fit(X)
  75. bandwidth = 0.0
  76. for batch in gen_batches(len(X), 500):
  77. d, _ = nbrs.kneighbors(X[batch, :], return_distance=True)
  78. bandwidth += np.max(d, axis=1).sum()
  79. return bandwidth / X.shape[0]
  80. # separate function for each seed's iterative loop
  81. def _mean_shift_single_seed(my_mean, X, nbrs, max_iter):
  82. # For each seed, climb gradient until convergence or max_iter
  83. bandwidth = nbrs.get_params()["radius"]
  84. stop_thresh = 1e-3 * bandwidth # when mean has converged
  85. completed_iterations = 0
  86. while True:
  87. # Find mean of points within bandwidth
  88. i_nbrs = nbrs.radius_neighbors([my_mean], bandwidth, return_distance=False)[0]
  89. points_within = X[i_nbrs]
  90. if len(points_within) == 0:
  91. break # Depending on seeding strategy this condition may occur
  92. my_old_mean = my_mean # save the old mean
  93. my_mean = np.mean(points_within, axis=0)
  94. # If converged or at max_iter, adds the cluster
  95. if (
  96. np.linalg.norm(my_mean - my_old_mean) < stop_thresh
  97. or completed_iterations == max_iter
  98. ):
  99. break
  100. completed_iterations += 1
  101. return tuple(my_mean), len(points_within), completed_iterations
  102. @validate_params(
  103. {"X": ["array-like"]},
  104. prefer_skip_nested_validation=False,
  105. )
  106. def mean_shift(
  107. X,
  108. *,
  109. bandwidth=None,
  110. seeds=None,
  111. bin_seeding=False,
  112. min_bin_freq=1,
  113. cluster_all=True,
  114. max_iter=300,
  115. n_jobs=None,
  116. ):
  117. """Perform mean shift clustering of data using a flat kernel.
  118. Read more in the :ref:`User Guide <mean_shift>`.
  119. Parameters
  120. ----------
  121. X : array-like of shape (n_samples, n_features)
  122. Input data.
  123. bandwidth : float, default=None
  124. Kernel bandwidth. If not None, must be in the range [0, +inf).
  125. If None, the bandwidth is determined using a heuristic based on
  126. the median of all pairwise distances. This will take quadratic time in
  127. the number of samples. The sklearn.cluster.estimate_bandwidth function
  128. can be used to do this more efficiently.
  129. seeds : array-like of shape (n_seeds, n_features) or None
  130. Point used as initial kernel locations. If None and bin_seeding=False,
  131. each data point is used as a seed. If None and bin_seeding=True,
  132. see bin_seeding.
  133. bin_seeding : bool, default=False
  134. If true, initial kernel locations are not locations of all
  135. points, but rather the location of the discretized version of
  136. points, where points are binned onto a grid whose coarseness
  137. corresponds to the bandwidth. Setting this option to True will speed
  138. up the algorithm because fewer seeds will be initialized.
  139. Ignored if seeds argument is not None.
  140. min_bin_freq : int, default=1
  141. To speed up the algorithm, accept only those bins with at least
  142. min_bin_freq points as seeds.
  143. cluster_all : bool, default=True
  144. If true, then all points are clustered, even those orphans that are
  145. not within any kernel. Orphans are assigned to the nearest kernel.
  146. If false, then orphans are given cluster label -1.
  147. max_iter : int, default=300
  148. Maximum number of iterations, per seed point before the clustering
  149. operation terminates (for that seed point), if has not converged yet.
  150. n_jobs : int, default=None
  151. The number of jobs to use for the computation. The following tasks benefit
  152. from the parallelization:
  153. - The search of nearest neighbors for bandwidth estimation and label
  154. assignments. See the details in the docstring of the
  155. ``NearestNeighbors`` class.
  156. - Hill-climbing optimization for all seeds.
  157. See :term:`Glossary <n_jobs>` for more details.
  158. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
  159. ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
  160. for more details.
  161. .. versionadded:: 0.17
  162. Parallel Execution using *n_jobs*.
  163. Returns
  164. -------
  165. cluster_centers : ndarray of shape (n_clusters, n_features)
  166. Coordinates of cluster centers.
  167. labels : ndarray of shape (n_samples,)
  168. Cluster labels for each point.
  169. Notes
  170. -----
  171. For an example, see :ref:`examples/cluster/plot_mean_shift.py
  172. <sphx_glr_auto_examples_cluster_plot_mean_shift.py>`.
  173. """
  174. model = MeanShift(
  175. bandwidth=bandwidth,
  176. seeds=seeds,
  177. min_bin_freq=min_bin_freq,
  178. bin_seeding=bin_seeding,
  179. cluster_all=cluster_all,
  180. n_jobs=n_jobs,
  181. max_iter=max_iter,
  182. ).fit(X)
  183. return model.cluster_centers_, model.labels_
  184. def get_bin_seeds(X, bin_size, min_bin_freq=1):
  185. """Find seeds for mean_shift.
  186. Finds seeds by first binning data onto a grid whose lines are
  187. spaced bin_size apart, and then choosing those bins with at least
  188. min_bin_freq points.
  189. Parameters
  190. ----------
  191. X : array-like of shape (n_samples, n_features)
  192. Input points, the same points that will be used in mean_shift.
  193. bin_size : float
  194. Controls the coarseness of the binning. Smaller values lead
  195. to more seeding (which is computationally more expensive). If you're
  196. not sure how to set this, set it to the value of the bandwidth used
  197. in clustering.mean_shift.
  198. min_bin_freq : int, default=1
  199. Only bins with at least min_bin_freq will be selected as seeds.
  200. Raising this value decreases the number of seeds found, which
  201. makes mean_shift computationally cheaper.
  202. Returns
  203. -------
  204. bin_seeds : array-like of shape (n_samples, n_features)
  205. Points used as initial kernel positions in clustering.mean_shift.
  206. """
  207. if bin_size == 0:
  208. return X
  209. # Bin points
  210. bin_sizes = defaultdict(int)
  211. for point in X:
  212. binned_point = np.round(point / bin_size)
  213. bin_sizes[tuple(binned_point)] += 1
  214. # Select only those bins as seeds which have enough members
  215. bin_seeds = np.array(
  216. [point for point, freq in bin_sizes.items() if freq >= min_bin_freq],
  217. dtype=np.float32,
  218. )
  219. if len(bin_seeds) == len(X):
  220. warnings.warn(
  221. "Binning data failed with provided bin_size=%f, using data points as seeds."
  222. % bin_size
  223. )
  224. return X
  225. bin_seeds = bin_seeds * bin_size
  226. return bin_seeds
  227. class MeanShift(ClusterMixin, BaseEstimator):
  228. """Mean shift clustering using a flat kernel.
  229. Mean shift clustering aims to discover "blobs" in a smooth density of
  230. samples. It is a centroid-based algorithm, which works by updating
  231. candidates for centroids to be the mean of the points within a given
  232. region. These candidates are then filtered in a post-processing stage to
  233. eliminate near-duplicates to form the final set of centroids.
  234. Seeding is performed using a binning technique for scalability.
  235. Read more in the :ref:`User Guide <mean_shift>`.
  236. Parameters
  237. ----------
  238. bandwidth : float, default=None
  239. Bandwidth used in the flat kernel.
  240. If not given, the bandwidth is estimated using
  241. sklearn.cluster.estimate_bandwidth; see the documentation for that
  242. function for hints on scalability (see also the Notes, below).
  243. seeds : array-like of shape (n_samples, n_features), default=None
  244. Seeds used to initialize kernels. If not set,
  245. the seeds are calculated by clustering.get_bin_seeds
  246. with bandwidth as the grid size and default values for
  247. other parameters.
  248. bin_seeding : bool, default=False
  249. If true, initial kernel locations are not locations of all
  250. points, but rather the location of the discretized version of
  251. points, where points are binned onto a grid whose coarseness
  252. corresponds to the bandwidth. Setting this option to True will speed
  253. up the algorithm because fewer seeds will be initialized.
  254. The default value is False.
  255. Ignored if seeds argument is not None.
  256. min_bin_freq : int, default=1
  257. To speed up the algorithm, accept only those bins with at least
  258. min_bin_freq points as seeds.
  259. cluster_all : bool, default=True
  260. If true, then all points are clustered, even those orphans that are
  261. not within any kernel. Orphans are assigned to the nearest kernel.
  262. If false, then orphans are given cluster label -1.
  263. n_jobs : int, default=None
  264. The number of jobs to use for the computation. The following tasks benefit
  265. from the parallelization:
  266. - The search of nearest neighbors for bandwidth estimation and label
  267. assignments. See the details in the docstring of the
  268. ``NearestNeighbors`` class.
  269. - Hill-climbing optimization for all seeds.
  270. See :term:`Glossary <n_jobs>` for more details.
  271. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
  272. ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
  273. for more details.
  274. max_iter : int, default=300
  275. Maximum number of iterations, per seed point before the clustering
  276. operation terminates (for that seed point), if has not converged yet.
  277. .. versionadded:: 0.22
  278. Attributes
  279. ----------
  280. cluster_centers_ : ndarray of shape (n_clusters, n_features)
  281. Coordinates of cluster centers.
  282. labels_ : ndarray of shape (n_samples,)
  283. Labels of each point.
  284. n_iter_ : int
  285. Maximum number of iterations performed on each seed.
  286. .. versionadded:: 0.22
  287. n_features_in_ : int
  288. Number of features seen during :term:`fit`.
  289. .. versionadded:: 0.24
  290. feature_names_in_ : ndarray of shape (`n_features_in_`,)
  291. Names of features seen during :term:`fit`. Defined only when `X`
  292. has feature names that are all strings.
  293. .. versionadded:: 1.0
  294. See Also
  295. --------
  296. KMeans : K-Means clustering.
  297. Notes
  298. -----
  299. Scalability:
  300. Because this implementation uses a flat kernel and
  301. a Ball Tree to look up members of each kernel, the complexity will tend
  302. towards O(T*n*log(n)) in lower dimensions, with n the number of samples
  303. and T the number of points. In higher dimensions the complexity will
  304. tend towards O(T*n^2).
  305. Scalability can be boosted by using fewer seeds, for example by using
  306. a higher value of min_bin_freq in the get_bin_seeds function.
  307. Note that the estimate_bandwidth function is much less scalable than the
  308. mean shift algorithm and will be the bottleneck if it is used.
  309. References
  310. ----------
  311. Dorin Comaniciu and Peter Meer, "Mean Shift: A robust approach toward
  312. feature space analysis". IEEE Transactions on Pattern Analysis and
  313. Machine Intelligence. 2002. pp. 603-619.
  314. Examples
  315. --------
  316. >>> from sklearn.cluster import MeanShift
  317. >>> import numpy as np
  318. >>> X = np.array([[1, 1], [2, 1], [1, 0],
  319. ... [4, 7], [3, 5], [3, 6]])
  320. >>> clustering = MeanShift(bandwidth=2).fit(X)
  321. >>> clustering.labels_
  322. array([1, 1, 1, 0, 0, 0])
  323. >>> clustering.predict([[0, 0], [5, 5]])
  324. array([1, 0])
  325. >>> clustering
  326. MeanShift(bandwidth=2)
  327. """
  328. _parameter_constraints: dict = {
  329. "bandwidth": [Interval(Real, 0, None, closed="neither"), None],
  330. "seeds": ["array-like", None],
  331. "bin_seeding": ["boolean"],
  332. "min_bin_freq": [Interval(Integral, 1, None, closed="left")],
  333. "cluster_all": ["boolean"],
  334. "n_jobs": [Integral, None],
  335. "max_iter": [Interval(Integral, 0, None, closed="left")],
  336. }
  337. def __init__(
  338. self,
  339. *,
  340. bandwidth=None,
  341. seeds=None,
  342. bin_seeding=False,
  343. min_bin_freq=1,
  344. cluster_all=True,
  345. n_jobs=None,
  346. max_iter=300,
  347. ):
  348. self.bandwidth = bandwidth
  349. self.seeds = seeds
  350. self.bin_seeding = bin_seeding
  351. self.cluster_all = cluster_all
  352. self.min_bin_freq = min_bin_freq
  353. self.n_jobs = n_jobs
  354. self.max_iter = max_iter
  355. @_fit_context(prefer_skip_nested_validation=True)
  356. def fit(self, X, y=None):
  357. """Perform clustering.
  358. Parameters
  359. ----------
  360. X : array-like of shape (n_samples, n_features)
  361. Samples to cluster.
  362. y : Ignored
  363. Not used, present for API consistency by convention.
  364. Returns
  365. -------
  366. self : object
  367. Fitted instance.
  368. """
  369. X = self._validate_data(X)
  370. bandwidth = self.bandwidth
  371. if bandwidth is None:
  372. bandwidth = estimate_bandwidth(X, n_jobs=self.n_jobs)
  373. seeds = self.seeds
  374. if seeds is None:
  375. if self.bin_seeding:
  376. seeds = get_bin_seeds(X, bandwidth, self.min_bin_freq)
  377. else:
  378. seeds = X
  379. n_samples, n_features = X.shape
  380. center_intensity_dict = {}
  381. # We use n_jobs=1 because this will be used in nested calls under
  382. # parallel calls to _mean_shift_single_seed so there is no need for
  383. # for further parallelism.
  384. nbrs = NearestNeighbors(radius=bandwidth, n_jobs=1).fit(X)
  385. # execute iterations on all seeds in parallel
  386. all_res = Parallel(n_jobs=self.n_jobs)(
  387. delayed(_mean_shift_single_seed)(seed, X, nbrs, self.max_iter)
  388. for seed in seeds
  389. )
  390. # copy results in a dictionary
  391. for i in range(len(seeds)):
  392. if all_res[i][1]: # i.e. len(points_within) > 0
  393. center_intensity_dict[all_res[i][0]] = all_res[i][1]
  394. self.n_iter_ = max([x[2] for x in all_res])
  395. if not center_intensity_dict:
  396. # nothing near seeds
  397. raise ValueError(
  398. "No point was within bandwidth=%f of any seed. Try a different seeding"
  399. " strategy or increase the bandwidth."
  400. % bandwidth
  401. )
  402. # POST PROCESSING: remove near duplicate points
  403. # If the distance between two kernels is less than the bandwidth,
  404. # then we have to remove one because it is a duplicate. Remove the
  405. # one with fewer points.
  406. sorted_by_intensity = sorted(
  407. center_intensity_dict.items(),
  408. key=lambda tup: (tup[1], tup[0]),
  409. reverse=True,
  410. )
  411. sorted_centers = np.array([tup[0] for tup in sorted_by_intensity])
  412. unique = np.ones(len(sorted_centers), dtype=bool)
  413. nbrs = NearestNeighbors(radius=bandwidth, n_jobs=self.n_jobs).fit(
  414. sorted_centers
  415. )
  416. for i, center in enumerate(sorted_centers):
  417. if unique[i]:
  418. neighbor_idxs = nbrs.radius_neighbors([center], return_distance=False)[
  419. 0
  420. ]
  421. unique[neighbor_idxs] = 0
  422. unique[i] = 1 # leave the current point as unique
  423. cluster_centers = sorted_centers[unique]
  424. # ASSIGN LABELS: a point belongs to the cluster that it is closest to
  425. nbrs = NearestNeighbors(n_neighbors=1, n_jobs=self.n_jobs).fit(cluster_centers)
  426. labels = np.zeros(n_samples, dtype=int)
  427. distances, idxs = nbrs.kneighbors(X)
  428. if self.cluster_all:
  429. labels = idxs.flatten()
  430. else:
  431. labels.fill(-1)
  432. bool_selector = distances.flatten() <= bandwidth
  433. labels[bool_selector] = idxs.flatten()[bool_selector]
  434. self.cluster_centers_, self.labels_ = cluster_centers, labels
  435. return self
  436. def predict(self, X):
  437. """Predict the closest cluster each sample in X belongs to.
  438. Parameters
  439. ----------
  440. X : array-like of shape (n_samples, n_features)
  441. New data to predict.
  442. Returns
  443. -------
  444. labels : ndarray of shape (n_samples,)
  445. Index of the cluster each sample belongs to.
  446. """
  447. check_is_fitted(self)
  448. X = self._validate_data(X, reset=False)
  449. with config_context(assume_finite=True):
  450. return pairwise_distances_argmin(X, self.cluster_centers_)