API Reference
Detailed documentation for the classes and functions in scikit-clarans.
CLARANS
The core class you will interact with.
- class clarans.CLARANS(n_clusters=8, numlocal=2, maxneighbor=None, max_iter=300, init='random', metric='euclidean', random_state=None)[source]
Bases:
ClusterMixin,TransformerMixin,BaseEstimator- Parameters:
n_clusters (int, default=8) – The number of clusters to form (also the number of medoids to generate).
numlocal (int, default=2) – The number of local searches to perform. CLARANS runs the search process
numlocaltimes starting from different random nodes to reduce the chance of getting stuck in poor local minima. Increasing this improves solution quality but increases runtime.maxneighbor (int, default=None) – The maximum number of neighbors (random swaps) to examine during each step. If
None, it defaults tomax(250, 1.25% of k*(n-k)). Higher values make the algorithm behave more like PAM (checking more neighbors); lower values make it faster but more random.max_iter (int, default=300) – The maximum number of successful swaps (improvements) allowed per local search. This acts as a safeguard against infinite loops.
init ({'random', 'heuristic', 'k-medoids++', 'build', array-like}, default='random') –
Strategy for selecting initial medoids:
'random': Selectsn_clustersrandom points. Fast but can result in poor starting points.'heuristic': Selects points that are “central” to the data (minimizing distance to all others).'k-medoids++': Optimized probabilistic initialization (similar to k-means++) for faster convergence.'build': The greedy initialization from the original PAM algorithm. High quality but slow (O(N^2)).
metric (str or callable, default='euclidean') – The distance metric to use. Supports all metrics from
sklearn.metrics.pairwise_distances(e.g., ‘euclidean’, ‘manhattan’, ‘cosine’).random_state (int, RandomState instance or None, default=None) – Determines random number generation for centroid initialization. Use an int to make the randomness deterministic.
- cluster_centers_
Coordinates of cluster centers (medoids).
- Type:
ndarray of shape (n_clusters, n_features)
- labels_
Labels of each point.
- Type:
ndarray of shape (n_samples,)
- medoid_indices_
Indices of the medoids in the training set X.
- Type:
ndarray of shape (n_clusters,)
Notes
Time complexity: each local search evaluates up to
maxneighborcandidate swaps, and each cost evaluation is O(n * k) (distance to medoids), so the worst-case runtime is roughly O(numlocal * maxneighbor * n * k).Initialization methods such as
'heuristic'and'build'may compute the full pairwise distance matrix and therefore have O(n^2) time and memory costs.Compared with
FastCLARANS, this implementation avoids caching the full distance matrix and is more memory-friendly for very large datasets at the cost of repeated distance computations.
References
Ng, R. T., & Han, J. (2002). CLARANS: A method for clustering objects for spatial data mining. IEEE transactions on knowledge and data engineering, 14(5), 1003-1016.
Examples
>>> from clarans import CLARANS >>> model = CLARANS(n_clusters=3, random_state=0) >>> model.fit(X)
- fit(X, y=None)[source]
Compute CLARANS clustering.
- Parameters:
X (array-like or sparse matrix of shape (n_samples, n_features)) – Training instances to cluster. Accepts CSR/CSC sparse matrices.
y (Ignored) – Not used, present here for API consistency.
- Returns:
self – Fitted estimator. Attributes set on the estimator include
medoid_indices_,cluster_centers_, andlabels_.- Return type:
- Raises:
ValueError – If
n_clusters >= n_samples, or if an explicitinitarray has an incompatible shape, or if not enough unique points exist to initialize the requested number of clusters.
Notes
Time complexity: each local search evaluates up to
maxneighborcandidate swaps, and each cost evaluation is O(n * k) (distance to medoids), so the worst-case runtime is roughly O(numlocal * maxneighbor * n * k).Initialization methods such as
'heuristic'and'build'may compute the full pairwise distance matrix and therefore have O(n^2) time and memory costs.Compared with
FastCLARANS, this implementation avoids caching the full distance matrix and is more memory-friendly for very large datasets at the cost of repeated distance computations.
Examples
>>> from clarans import CLARANS >>> model = CLARANS(n_clusters=3, random_state=0) >>> model.fit(X)
- predict(X)[source]
Predict the closest cluster each sample in X belongs to.
- Parameters:
X (array-like or sparse matrix of shape (n_samples, n_features)) – New data to predict. Accepts CSR/CSC sparse matrices.
- Returns:
labels – Index of the cluster each sample belongs to.
- Return type:
ndarray of shape (n_samples,)
- Raises:
ValueError – If the number of features in
Xdoes not match the number of features seen during fitting.
Notes
This method uses
pairwise_distances_argmin_minfrom scikit-learn to assign each sample to the nearest medoid.
- transform(X)[source]
Transform X to a cluster-distance space.
In the new space, each dimension is the distance to the cluster centers.
- Parameters:
X ({array-like, sparse matrix} of shape (n_samples, n_features)) – New data to transform.
- Returns:
X_new – X transformed in the new space.
- Return type:
ndarray of shape (n_samples, n_clusters)
- fit_predict(X, y=None, **kwargs)
Perform clustering on X and returns cluster labels.
- Parameters:
X (array-like of shape (n_samples, n_features)) – Input data.
y (Ignored) – Not used, present for API consistency by convention.
**kwargs (dict) –
Arguments to be passed to
fit.Added in version 1.4.
- Returns:
labels – Cluster labels.
- Return type:
ndarray of shape (n_samples,), dtype=np.int64
- fit_transform(X, y=None, **fit_params)
Fit to data, then transform it.
Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.
- Parameters:
X (array-like of shape (n_samples, n_features)) – Input samples.
y (array-like of shape (n_samples,) or (n_samples, n_outputs), default=None) – Target values (None for unsupervised transformations).
**fit_params (dict) – Additional fit parameters.
- Returns:
X_new – Transformed array.
- Return type:
ndarray array of shape (n_samples, n_features_new)
- get_metadata_routing()
Get metadata routing of this object.
Please check User Guide on how the routing mechanism works.
- Returns:
routing – A
MetadataRequestencapsulating routing information.- Return type:
MetadataRequest
- get_params(deep=True)
Get parameters for this estimator.
- set_output(*, transform=None)
Set output container.
See Introducing the set_output API for an example on how to use the API.
- Parameters:
transform ({"default", "pandas", "polars"}, default=None) –
Configure output of transform and fit_transform.
”default”: Default output format of a transformer
”pandas”: DataFrame output
”polars”: Polars output
None: Transform configuration is unchanged
Added in version 1.4: “polars” option was added.
- Returns:
self – Estimator instance.
- Return type:
estimator instance
- set_params(**params)
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as
Pipeline). The latter have parameters of the form<component>__<parameter>so that it’s possible to update each component of a nested object.- Parameters:
**params (dict) – Estimator parameters.
- Returns:
self – Estimator instance.
- Return type:
estimator instance
- class clarans.FastCLARANS(n_clusters=8, numlocal=2, maxneighbor=None, max_iter=300, init='random', metric='euclidean', random_state=None)[source]
Bases:
CLARANSFastCLARANS: Fast variant of the CLARANS clustering algorithm.
- Parameters:
n_clusters (int, default=8) – The number of clusters to form (also the number of medoids).
numlocal (int, default=2) – The number of local searches to perform. More local searches increase the chance of finding a better minimum at the cost of additional runtime.
maxneighbor (int or None, default=None) – The maximum number of non-medoid candidates to sample per local search. If
None, defaults to 2.5% of non-medoid points (i.e.,0.025 * (n - k)) as recommended in the paper.max_iter (int or None, default=300) – Maximum number of successful swaps (improvements) allowed per local search. Use
Noneto disable this safeguard.init ({'random', 'heuristic', 'k-medoids++', 'build', array-like}, default='random') – Method for initialization. If an array-like is provided it should be of shape (n_clusters, n_features) and will be snapped to the nearest points in X.
metric (str or callable, default='euclidean') – The distance metric passed to scikit-learn pairwise utilities.
random_state (int, RandomState instance or None, default=None) – Controls random number generation for reproducibility.
- medoid_indices_
Indices of the selected medoids in the training set.
- Type:
ndarray of shape (n_clusters,)
- cluster_centers_
Coordinates of the medoids (rows from the training data).
- Type:
ndarray of shape (n_clusters, n_features)
- labels_
Labels of each point indicating the nearest medoid.
- Type:
ndarray of shape (n_samples,)
Notes
This implementation follows the original FastCLARANS paper by computing distances on-the-fly rather than precomputing a full distance matrix. This keeps memory usage at O(n) instead of O(n^2), making it suitable for larger datasets.
The key improvement from FastCLARANS is the sampling strategy: instead of sampling random (medoid, non-medoid) pairs like CLARANS, it samples only non-medoid candidates and evaluates swaps with all k medoids at once using FastPAM1 delta formulas. This explores k edges of the search graph in the time CLARANS explores one.
References
Schubert, E., & Rousseeuw, P. J. (2021). Fast and eager k-medoids clustering: O(k) runtime improvement of the PAM, CLARA, and CLARANS algorithms. Information Systems, 101, 101804.
- fit(X, y=None)[source]
Fit the FastCLARANS model to X.
- Parameters:
X (array-like or sparse matrix of shape (n_samples, n_features)) – Training instances to cluster. Accepts CSR/CSC sparse matrices.
y (Ignored) – Not used, present for API consistency.
- Returns:
self – The fitted estimator. Attributes set on the estimator include
medoid_indices_,cluster_centers_andlabels_.- Return type:
- Raises:
ValueError – If
n_clusters >= n_samplesor if an explicitinitarray is provided with an incompatible shape or there are not enough unique points to form the requested number of medoids.
Notes
Unlike implementations that precompute the full distance matrix, this version computes distances on-the-fly to save memory. This is efficient for low-dimensional data with cheap distance metrics (e.g., Euclidean distance).
- fit_predict(X, y=None, **kwargs)
Perform clustering on X and returns cluster labels.
- Parameters:
X (array-like of shape (n_samples, n_features)) – Input data.
y (Ignored) – Not used, present for API consistency by convention.
**kwargs (dict) –
Arguments to be passed to
fit.Added in version 1.4.
- Returns:
labels – Cluster labels.
- Return type:
ndarray of shape (n_samples,), dtype=np.int64
- fit_transform(X, y=None, **fit_params)
Fit to data, then transform it.
Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.
- Parameters:
X (array-like of shape (n_samples, n_features)) – Input samples.
y (array-like of shape (n_samples,) or (n_samples, n_outputs), default=None) – Target values (None for unsupervised transformations).
**fit_params (dict) – Additional fit parameters.
- Returns:
X_new – Transformed array.
- Return type:
ndarray array of shape (n_samples, n_features_new)
- get_metadata_routing()
Get metadata routing of this object.
Please check User Guide on how the routing mechanism works.
- Returns:
routing – A
MetadataRequestencapsulating routing information.- Return type:
MetadataRequest
- get_params(deep=True)
Get parameters for this estimator.
- predict(X)
Predict the closest cluster each sample in X belongs to.
- Parameters:
X (array-like or sparse matrix of shape (n_samples, n_features)) – New data to predict. Accepts CSR/CSC sparse matrices.
- Returns:
labels – Index of the cluster each sample belongs to.
- Return type:
ndarray of shape (n_samples,)
- Raises:
ValueError – If the number of features in
Xdoes not match the number of features seen during fitting.
Notes
This method uses
pairwise_distances_argmin_minfrom scikit-learn to assign each sample to the nearest medoid.
- set_output(*, transform=None)
Set output container.
See Introducing the set_output API for an example on how to use the API.
- Parameters:
transform ({"default", "pandas", "polars"}, default=None) –
Configure output of transform and fit_transform.
”default”: Default output format of a transformer
”pandas”: DataFrame output
”polars”: Polars output
None: Transform configuration is unchanged
Added in version 1.4: “polars” option was added.
- Returns:
self – Estimator instance.
- Return type:
estimator instance
- set_params(**params)
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as
Pipeline). The latter have parameters of the form<component>__<parameter>so that it’s possible to update each component of a nested object.- Parameters:
**params (dict) – Estimator parameters.
- Returns:
self – Estimator instance.
- Return type:
estimator instance
- transform(X)
Transform X to a cluster-distance space.
In the new space, each dimension is the distance to the cluster centers.
- Parameters:
X ({array-like, sparse matrix} of shape (n_samples, n_features)) – New data to transform.
- Returns:
X_new – X transformed in the new space.
- Return type:
ndarray of shape (n_samples, n_clusters)
Helper Modules
Internal modules for initialization and utilities.
- clarans.initialization.initialize_heuristic(X, n_clusters, metric='euclidean')[source]
Initialize medoids using a heuristic approach.
Picks the n_clusters points with the smallest sum distance to every other point.
- Parameters:
- Returns:
current_medoids_indices – Indices of the selected medoids in the dataset.
- Return type:
ndarray of shape (n_clusters,), dtype int
Notes
This method computes the full pairwise distance matrix and therefore has O(n^2) time and memory complexity.
- clarans.initialization.initialize_build(X, n_clusters, metric='euclidean')[source]
Initialize medoids using the PAM BUILD step.
Greedily selects the first medoid that minimizes total distance, then subsequently adds medoids that maximally decrease the total cost.
- Parameters:
- Returns:
medoids – Indices of the selected medoids in the dataset.
- Return type:
ndarray of shape (n_clusters,), dtype int
- clarans.initialization.initialize_k_medoids_plus_plus(X, n_clusters, random_state=None, metric='euclidean', n_local_trials=None)[source]
Initialize medoids using k-medoids++ (similar to k-means++).
- Parameters:
X ({array-like, sparse matrix} of shape (n_samples, n_features)) – The input samples.
n_clusters (int) – The number of clusters to form.
random_state (int, RandomState instance or None, default=None) – Determines random number generation for centroid initialization.
metric (str or callable, default='euclidean') – The metric to use when calculating distance between instances in a feature array.
n_local_trials (int, default=None) – The number of seeding trials for each center (except the first), of which the one reducing inertia the most is greedily chosen. If None, the function uses a small logarithmic default.
- Returns:
medoids – Indices of the selected medoids in the dataset.
- Return type:
ndarray of shape (n_clusters,), dtype int
Notes
This implementation follows the k-means++ style seeding but uses distances squared and picks medoids (data indices) rather than centroids.
- clarans.utils.calculate_cost(X, medoid_indices, metric='euclidean')[source]
Calculate the total cost (sum of distances) for a given set of medoids.
- Parameters:
X ({array-like, sparse matrix} of shape (n_samples, n_features)) – The input samples.
medoid_indices (array-like of shape (n_clusters,)) – Indices of the medoids in the dataset X.
metric (str or callable, default='euclidean') – The metric to use when calculating distance between instances.
- Returns:
cost – The total sum of distances from each point to its nearest medoid.
- Return type: