_dbscan.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. """
  2. DBSCAN: Density-Based Spatial Clustering of Applications with Noise
  3. """
  4. # Author: Robert Layton <robertlayton@gmail.com>
  5. # Joel Nothman <joel.nothman@gmail.com>
  6. # Lars Buitinck
  7. #
  8. # License: BSD 3 clause
  9. import warnings
  10. from numbers import Integral, Real
  11. import numpy as np
  12. from scipy import sparse
  13. from ..base import BaseEstimator, ClusterMixin, _fit_context
  14. from ..metrics.pairwise import _VALID_METRICS
  15. from ..neighbors import NearestNeighbors
  16. from ..utils._param_validation import Interval, StrOptions
  17. from ..utils.validation import _check_sample_weight
  18. from ._dbscan_inner import dbscan_inner
  19. def dbscan(
  20. X,
  21. eps=0.5,
  22. *,
  23. min_samples=5,
  24. metric="minkowski",
  25. metric_params=None,
  26. algorithm="auto",
  27. leaf_size=30,
  28. p=2,
  29. sample_weight=None,
  30. n_jobs=None,
  31. ):
  32. """Perform DBSCAN clustering from vector array or distance matrix.
  33. Read more in the :ref:`User Guide <dbscan>`.
  34. Parameters
  35. ----------
  36. X : {array-like, sparse (CSR) matrix} of shape (n_samples, n_features) or \
  37. (n_samples, n_samples)
  38. A feature array, or array of distances between samples if
  39. ``metric='precomputed'``.
  40. eps : float, default=0.5
  41. The maximum distance between two samples for one to be considered
  42. as in the neighborhood of the other. This is not a maximum bound
  43. on the distances of points within a cluster. This is the most
  44. important DBSCAN parameter to choose appropriately for your data set
  45. and distance function.
  46. min_samples : int, default=5
  47. The number of samples (or total weight) in a neighborhood for a point
  48. to be considered as a core point. This includes the point itself.
  49. metric : str or callable, default='minkowski'
  50. The metric to use when calculating distance between instances in a
  51. feature array. If metric is a string or callable, it must be one of
  52. the options allowed by :func:`sklearn.metrics.pairwise_distances` for
  53. its metric parameter.
  54. If metric is "precomputed", X is assumed to be a distance matrix and
  55. must be square during fit.
  56. X may be a :term:`sparse graph <sparse graph>`,
  57. in which case only "nonzero" elements may be considered neighbors.
  58. metric_params : dict, default=None
  59. Additional keyword arguments for the metric function.
  60. .. versionadded:: 0.19
  61. algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, default='auto'
  62. The algorithm to be used by the NearestNeighbors module
  63. to compute pointwise distances and find nearest neighbors.
  64. See NearestNeighbors module documentation for details.
  65. leaf_size : int, default=30
  66. Leaf size passed to BallTree or cKDTree. This can affect the speed
  67. of the construction and query, as well as the memory required
  68. to store the tree. The optimal value depends
  69. on the nature of the problem.
  70. p : float, default=2
  71. The power of the Minkowski metric to be used to calculate distance
  72. between points.
  73. sample_weight : array-like of shape (n_samples,), default=None
  74. Weight of each sample, such that a sample with a weight of at least
  75. ``min_samples`` is by itself a core sample; a sample with negative
  76. weight may inhibit its eps-neighbor from being core.
  77. Note that weights are absolute, and default to 1.
  78. n_jobs : int, default=None
  79. The number of parallel jobs to run for neighbors search. ``None`` means
  80. 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means
  81. using all processors. See :term:`Glossary <n_jobs>` for more details.
  82. If precomputed distance are used, parallel execution is not available
  83. and thus n_jobs will have no effect.
  84. Returns
  85. -------
  86. core_samples : ndarray of shape (n_core_samples,)
  87. Indices of core samples.
  88. labels : ndarray of shape (n_samples,)
  89. Cluster labels for each point. Noisy samples are given the label -1.
  90. See Also
  91. --------
  92. DBSCAN : An estimator interface for this clustering algorithm.
  93. OPTICS : A similar estimator interface clustering at multiple values of
  94. eps. Our implementation is optimized for memory usage.
  95. Notes
  96. -----
  97. For an example, see :ref:`examples/cluster/plot_dbscan.py
  98. <sphx_glr_auto_examples_cluster_plot_dbscan.py>`.
  99. This implementation bulk-computes all neighborhood queries, which increases
  100. the memory complexity to O(n.d) where d is the average number of neighbors,
  101. while original DBSCAN had memory complexity O(n). It may attract a higher
  102. memory complexity when querying these nearest neighborhoods, depending
  103. on the ``algorithm``.
  104. One way to avoid the query complexity is to pre-compute sparse
  105. neighborhoods in chunks using
  106. :func:`NearestNeighbors.radius_neighbors_graph
  107. <sklearn.neighbors.NearestNeighbors.radius_neighbors_graph>` with
  108. ``mode='distance'``, then using ``metric='precomputed'`` here.
  109. Another way to reduce memory and computation time is to remove
  110. (near-)duplicate points and use ``sample_weight`` instead.
  111. :class:`~sklearn.cluster.OPTICS` provides a similar clustering with lower
  112. memory usage.
  113. References
  114. ----------
  115. Ester, M., H. P. Kriegel, J. Sander, and X. Xu, `"A Density-Based
  116. Algorithm for Discovering Clusters in Large Spatial Databases with Noise"
  117. <https://www.dbs.ifi.lmu.de/Publikationen/Papers/KDD-96.final.frame.pdf>`_.
  118. In: Proceedings of the 2nd International Conference on Knowledge Discovery
  119. and Data Mining, Portland, OR, AAAI Press, pp. 226-231. 1996
  120. Schubert, E., Sander, J., Ester, M., Kriegel, H. P., & Xu, X. (2017).
  121. :doi:`"DBSCAN revisited, revisited: why and how you should (still) use DBSCAN."
  122. <10.1145/3068335>`
  123. ACM Transactions on Database Systems (TODS), 42(3), 19.
  124. """
  125. est = DBSCAN(
  126. eps=eps,
  127. min_samples=min_samples,
  128. metric=metric,
  129. metric_params=metric_params,
  130. algorithm=algorithm,
  131. leaf_size=leaf_size,
  132. p=p,
  133. n_jobs=n_jobs,
  134. )
  135. est.fit(X, sample_weight=sample_weight)
  136. return est.core_sample_indices_, est.labels_
  137. class DBSCAN(ClusterMixin, BaseEstimator):
  138. """Perform DBSCAN clustering from vector array or distance matrix.
  139. DBSCAN - Density-Based Spatial Clustering of Applications with Noise.
  140. Finds core samples of high density and expands clusters from them.
  141. Good for data which contains clusters of similar density.
  142. The worst case memory complexity of DBSCAN is :math:`O({n}^2)`, which can
  143. occur when the `eps` param is large and `min_samples` is low.
  144. Read more in the :ref:`User Guide <dbscan>`.
  145. Parameters
  146. ----------
  147. eps : float, default=0.5
  148. The maximum distance between two samples for one to be considered
  149. as in the neighborhood of the other. This is not a maximum bound
  150. on the distances of points within a cluster. This is the most
  151. important DBSCAN parameter to choose appropriately for your data set
  152. and distance function.
  153. min_samples : int, default=5
  154. The number of samples (or total weight) in a neighborhood for a point to
  155. be considered as a core point. This includes the point itself. If
  156. `min_samples` is set to a higher value, DBSCAN will find denser clusters,
  157. whereas if it is set to a lower value, the found clusters will be more
  158. sparse.
  159. metric : str, or callable, default='euclidean'
  160. The metric to use when calculating distance between instances in a
  161. feature array. If metric is a string or callable, it must be one of
  162. the options allowed by :func:`sklearn.metrics.pairwise_distances` for
  163. its metric parameter.
  164. If metric is "precomputed", X is assumed to be a distance matrix and
  165. must be square. X may be a :term:`sparse graph`, in which
  166. case only "nonzero" elements may be considered neighbors for DBSCAN.
  167. .. versionadded:: 0.17
  168. metric *precomputed* to accept precomputed sparse matrix.
  169. metric_params : dict, default=None
  170. Additional keyword arguments for the metric function.
  171. .. versionadded:: 0.19
  172. algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, default='auto'
  173. The algorithm to be used by the NearestNeighbors module
  174. to compute pointwise distances and find nearest neighbors.
  175. See NearestNeighbors module documentation for details.
  176. leaf_size : int, default=30
  177. Leaf size passed to BallTree or cKDTree. This can affect the speed
  178. of the construction and query, as well as the memory required
  179. to store the tree. The optimal value depends
  180. on the nature of the problem.
  181. p : float, default=None
  182. The power of the Minkowski metric to be used to calculate distance
  183. between points. If None, then ``p=2`` (equivalent to the Euclidean
  184. distance).
  185. n_jobs : int, default=None
  186. The number of parallel jobs to run.
  187. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
  188. ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
  189. for more details.
  190. Attributes
  191. ----------
  192. core_sample_indices_ : ndarray of shape (n_core_samples,)
  193. Indices of core samples.
  194. components_ : ndarray of shape (n_core_samples, n_features)
  195. Copy of each core sample found by training.
  196. labels_ : ndarray of shape (n_samples)
  197. Cluster labels for each point in the dataset given to fit().
  198. Noisy samples are given the label -1.
  199. n_features_in_ : int
  200. Number of features seen during :term:`fit`.
  201. .. versionadded:: 0.24
  202. feature_names_in_ : ndarray of shape (`n_features_in_`,)
  203. Names of features seen during :term:`fit`. Defined only when `X`
  204. has feature names that are all strings.
  205. .. versionadded:: 1.0
  206. See Also
  207. --------
  208. OPTICS : A similar clustering at multiple values of eps. Our implementation
  209. is optimized for memory usage.
  210. Notes
  211. -----
  212. For an example, see :ref:`examples/cluster/plot_dbscan.py
  213. <sphx_glr_auto_examples_cluster_plot_dbscan.py>`.
  214. This implementation bulk-computes all neighborhood queries, which increases
  215. the memory complexity to O(n.d) where d is the average number of neighbors,
  216. while original DBSCAN had memory complexity O(n). It may attract a higher
  217. memory complexity when querying these nearest neighborhoods, depending
  218. on the ``algorithm``.
  219. One way to avoid the query complexity is to pre-compute sparse
  220. neighborhoods in chunks using
  221. :func:`NearestNeighbors.radius_neighbors_graph
  222. <sklearn.neighbors.NearestNeighbors.radius_neighbors_graph>` with
  223. ``mode='distance'``, then using ``metric='precomputed'`` here.
  224. Another way to reduce memory and computation time is to remove
  225. (near-)duplicate points and use ``sample_weight`` instead.
  226. :class:`~sklearn.cluster.OPTICS` provides a similar clustering with lower memory
  227. usage.
  228. References
  229. ----------
  230. Ester, M., H. P. Kriegel, J. Sander, and X. Xu, `"A Density-Based
  231. Algorithm for Discovering Clusters in Large Spatial Databases with Noise"
  232. <https://www.dbs.ifi.lmu.de/Publikationen/Papers/KDD-96.final.frame.pdf>`_.
  233. In: Proceedings of the 2nd International Conference on Knowledge Discovery
  234. and Data Mining, Portland, OR, AAAI Press, pp. 226-231. 1996
  235. Schubert, E., Sander, J., Ester, M., Kriegel, H. P., & Xu, X. (2017).
  236. :doi:`"DBSCAN revisited, revisited: why and how you should (still) use DBSCAN."
  237. <10.1145/3068335>`
  238. ACM Transactions on Database Systems (TODS), 42(3), 19.
  239. Examples
  240. --------
  241. >>> from sklearn.cluster import DBSCAN
  242. >>> import numpy as np
  243. >>> X = np.array([[1, 2], [2, 2], [2, 3],
  244. ... [8, 7], [8, 8], [25, 80]])
  245. >>> clustering = DBSCAN(eps=3, min_samples=2).fit(X)
  246. >>> clustering.labels_
  247. array([ 0, 0, 0, 1, 1, -1])
  248. >>> clustering
  249. DBSCAN(eps=3, min_samples=2)
  250. """
  251. _parameter_constraints: dict = {
  252. "eps": [Interval(Real, 0.0, None, closed="neither")],
  253. "min_samples": [Interval(Integral, 1, None, closed="left")],
  254. "metric": [
  255. StrOptions(set(_VALID_METRICS) | {"precomputed"}),
  256. callable,
  257. ],
  258. "metric_params": [dict, None],
  259. "algorithm": [StrOptions({"auto", "ball_tree", "kd_tree", "brute"})],
  260. "leaf_size": [Interval(Integral, 1, None, closed="left")],
  261. "p": [Interval(Real, 0.0, None, closed="left"), None],
  262. "n_jobs": [Integral, None],
  263. }
  264. def __init__(
  265. self,
  266. eps=0.5,
  267. *,
  268. min_samples=5,
  269. metric="euclidean",
  270. metric_params=None,
  271. algorithm="auto",
  272. leaf_size=30,
  273. p=None,
  274. n_jobs=None,
  275. ):
  276. self.eps = eps
  277. self.min_samples = min_samples
  278. self.metric = metric
  279. self.metric_params = metric_params
  280. self.algorithm = algorithm
  281. self.leaf_size = leaf_size
  282. self.p = p
  283. self.n_jobs = n_jobs
  284. @_fit_context(
  285. # DBSCAN.metric is not validated yet
  286. prefer_skip_nested_validation=False
  287. )
  288. def fit(self, X, y=None, sample_weight=None):
  289. """Perform DBSCAN clustering from features, or distance matrix.
  290. Parameters
  291. ----------
  292. X : {array-like, sparse matrix} of shape (n_samples, n_features), or \
  293. (n_samples, n_samples)
  294. Training instances to cluster, or distances between instances if
  295. ``metric='precomputed'``. If a sparse matrix is provided, it will
  296. be converted into a sparse ``csr_matrix``.
  297. y : Ignored
  298. Not used, present here for API consistency by convention.
  299. sample_weight : array-like of shape (n_samples,), default=None
  300. Weight of each sample, such that a sample with a weight of at least
  301. ``min_samples`` is by itself a core sample; a sample with a
  302. negative weight may inhibit its eps-neighbor from being core.
  303. Note that weights are absolute, and default to 1.
  304. Returns
  305. -------
  306. self : object
  307. Returns a fitted instance of self.
  308. """
  309. X = self._validate_data(X, accept_sparse="csr")
  310. if sample_weight is not None:
  311. sample_weight = _check_sample_weight(sample_weight, X)
  312. # Calculate neighborhood for all samples. This leaves the original
  313. # point in, which needs to be considered later (i.e. point i is in the
  314. # neighborhood of point i. While True, its useless information)
  315. if self.metric == "precomputed" and sparse.issparse(X):
  316. # set the diagonal to explicit values, as a point is its own
  317. # neighbor
  318. with warnings.catch_warnings():
  319. warnings.simplefilter("ignore", sparse.SparseEfficiencyWarning)
  320. X.setdiag(X.diagonal()) # XXX: modifies X's internals in-place
  321. neighbors_model = NearestNeighbors(
  322. radius=self.eps,
  323. algorithm=self.algorithm,
  324. leaf_size=self.leaf_size,
  325. metric=self.metric,
  326. metric_params=self.metric_params,
  327. p=self.p,
  328. n_jobs=self.n_jobs,
  329. )
  330. neighbors_model.fit(X)
  331. # This has worst case O(n^2) memory complexity
  332. neighborhoods = neighbors_model.radius_neighbors(X, return_distance=False)
  333. if sample_weight is None:
  334. n_neighbors = np.array([len(neighbors) for neighbors in neighborhoods])
  335. else:
  336. n_neighbors = np.array(
  337. [np.sum(sample_weight[neighbors]) for neighbors in neighborhoods]
  338. )
  339. # Initially, all samples are noise.
  340. labels = np.full(X.shape[0], -1, dtype=np.intp)
  341. # A list of all core samples found.
  342. core_samples = np.asarray(n_neighbors >= self.min_samples, dtype=np.uint8)
  343. dbscan_inner(core_samples, neighborhoods, labels)
  344. self.core_sample_indices_ = np.where(core_samples)[0]
  345. self.labels_ = labels
  346. if len(self.core_sample_indices_):
  347. # fix for scipy sparse indexing issue
  348. self.components_ = X[self.core_sample_indices_].copy()
  349. else:
  350. # no core samples
  351. self.components_ = np.empty((0, X.shape[1]))
  352. return self
  353. def fit_predict(self, X, y=None, sample_weight=None):
  354. """Compute clusters from a data or distance matrix and predict labels.
  355. Parameters
  356. ----------
  357. X : {array-like, sparse matrix} of shape (n_samples, n_features), or \
  358. (n_samples, n_samples)
  359. Training instances to cluster, or distances between instances if
  360. ``metric='precomputed'``. If a sparse matrix is provided, it will
  361. be converted into a sparse ``csr_matrix``.
  362. y : Ignored
  363. Not used, present here for API consistency by convention.
  364. sample_weight : array-like of shape (n_samples,), default=None
  365. Weight of each sample, such that a sample with a weight of at least
  366. ``min_samples`` is by itself a core sample; a sample with a
  367. negative weight may inhibit its eps-neighbor from being core.
  368. Note that weights are absolute, and default to 1.
  369. Returns
  370. -------
  371. labels : ndarray of shape (n_samples,)
  372. Cluster labels. Noisy samples are given the label -1.
  373. """
  374. self.fit(X, sample_weight=sample_weight)
  375. return self.labels_
  376. def _more_tags(self):
  377. return {"pairwise": self.metric == "precomputed"}