mojolearn.DBSCAN#

class mojolearn.DBSCAN(eps=0.5, min_samples=5, *, metric='euclidean', algorithm='rbc', max_mbytes_per_batch=None, max_iterations=None, prediction_data=False)[source]#

Bases: NumericModeMixin

Density-based clustering (DBSCAN).

Groups points that lie in dense regions and marks isolated points as noise, following scikit-learn’s and cuML’s DBSCAN. A point is a core sample when at least min_samples points (itself included) lie within eps of it; clusters are the connected core samples plus their border points. Input is converted to float32; X must be finite.

Differences from scikit-learn and cuML:

  • algorithm defaults to 'rbc' (a random ball cover), not cuML’s 'brute'. Both give the same labels. scikit-learn’s 'kd_tree' and 'ball_tree' are not offered.

  • max_iterations=None runs label propagation to completion.

  • predict() labels new rows; neither library has it.

Parameters:
  • eps (float, default=0.5) – Neighborhood radius (a distance, not squared). Must be positive.

  • min_samples (int, default=5) – Minimum (weighted) number of points within eps, including the point itself, for a point to be a core sample. Must be at least 1.

  • metric (str, default=’euclidean’) – 'euclidean' / 'l2'; 'manhattan' / 'l1' / 'cityblock' and 'cosine' (algorithm='brute' only; 'cosine' raises ValueError for an all-zero row); or 'precomputed', where X is a square, non-negative distance matrix and a pair is a neighbor when its entry is <= eps (algorithm is then ignored, as in scikit-learn). Any other name raises ValueError.

  • algorithm ({‘rbc’, ‘brute’}, default=’rbc’) – Neighborhood search: 'rbc' is a random ball cover (Euclidean only), 'brute' an all-pairs scan (every metric).

  • max_mbytes_per_batch (int or None, default=None) – Device workspace budget in megabytes; None picks it automatically, as cuML does. It changes the number of batches, never the labels.

  • max_iterations (int or None, default=None) – Cap on label-propagation passes. None runs to completion. With an explicit cap that is reached, 'identical' mode raises an error and 'fast' mode returns the truncated labels.

  • prediction_data (bool, default=False) – Keep the core samples and their labels so predict() and save() can be used. Not allowed with metric='precomputed'.

  • numeric_mode ({‘identical’, ‘deterministic’, ‘fast’} or None, default=None) – Numeric mode ('fast' is Apple only); None uses the package default.

Variables:
  • labels_ (Array of int32, shape (n_samples,)) – Cluster label of each training row; -1 is noise and clusters are numbered from 0, so labels compare directly with scikit-learn’s.

  • core_sample_indices_ (Array of int32, shape (n_core,)) – Training indices of the core samples, ascending (scikit-learn uses intp).

  • components_ (Array of float32, shape (n_core, n_features)) – The core samples.

  • n_iter_ (int) – Total label-propagation passes, summed over batches.

  • n_features_in_ (int) – Number of features seen in fit().

  • n_samples_fit_ (int) – Number of training rows.

Examples

>>> import numpy as np, mojolearn
>>> X = np.random.default_rng(0).random((1000, 8), dtype=np.float32)
>>> model = mojolearn.DBSCAN(eps=0.5, min_samples=5).fit(X)
>>> labels = model.labels_
__init__(eps=0.5, min_samples=5, *, metric='euclidean', algorithm='rbc', max_mbytes_per_batch=None, max_iterations=None, prediction_data=False)[source]#

Methods

fit(X[, y, sample_weight])

Cluster X.

fit_predict(X[, y, sample_weight])

Fit and return labels_; see fit().

get_params([deep])

load(path)

Load a model written by save().

numeric_mode_used()

The numeric mode this estimator runs in.

predict(X)

Label new rows using the fitted clustering.

save(path)

Save a fitted model to path as an .npz file.

set_params(**params)

Set constructor parameters.

vendor_used()

The GPU backend this estimator runs on.

fit(X, y=None, sample_weight=None)[source]#

Cluster X.

Parameters:
  • X (array-like of shape (n_samples, n_features)) – Training rows, converted to float32; every value must be finite. With metric='precomputed', a square distance matrix of shape (n_samples, n_samples).

  • y (ignored)

  • sample_weight (array-like of shape (n_samples,), default=None) – Finite per-row weights. A point is a core sample when the sum of weights within eps reaches min_samples, as in scikit-learn and cuML.

Returns:

self

Raises:

ValueError – For a non-finite value, an unknown metric or algorithm, a metric the chosen algorithm does not serve, a non-positive eps, min_samples < 1 or a mismatched sample_weight.

fit_predict(X, y=None, sample_weight=None)[source]#

Fit and return labels_; see fit().

predict(X)[source]#

Label new rows using the fitted clustering.

A row gets the label of the nearest core sample within eps, and -1 (noise) when no core sample is within eps. Distance and “within eps” use the same test as fit(); a point exactly at eps is within it. Ties go to the lowest core sample index. Each row is labeled independently, so results do not depend on batching. Neither scikit-learn nor cuML has this method.

On the training rows, core samples get their fitted label. Noise rows get -1 with algorithm='brute'. Border rows may differ from labels_: the fit gives a border row the lowest-numbered nearby cluster, while predict gives the nearest core sample’s cluster.

Requires a fit with prediction_data=True; otherwise raises ValueError.

Parameters:

X (array-like of shape (n_queries, n_features)) – Rows to label, converted to float32; at least one row, the fitted feature count, and every value finite.

Returns:

labels (Array of int32, shape (n_queries,))

save(path)[source]#

Save a fitted model to path as an .npz file.

Stores the core samples, their indices and labels, labels_, eps, metric, algorithm and the fitted sizes. Requires a fit with prediction_data=True (ValueError otherwise); an unfitted model raises RuntimeError. A loaded model can predict(), including on a CPU-only install.

Parameters:

path (str or path-like)

classmethod load(path)[source]#

Load a model written by save().

The returned model can predict(). Arrays are read at their saved dtype and never cast; a file that does not match raises ValueError.

Parameters:

path (str or path-like)

Returns:

DBSCAN