API Reference

Estimators, initialization strategies, and utility functions.

Estimators

CLARANS

Randomized search k-medoids estimator (Ng & Han, 2002).

class clarans.CLARANS(*, n_clusters=8, num_local=2, max_neighbors='auto', init='k-medoids++', metric='euclidean', metric_params=None, random_state=None, cost_evaluation='delta', verbose=0)[source]

Bases: ClusterMixin, TransformerMixin, BaseEstimator

Clustering Large Applications based on RANdomized Search (CLARANS).

CLARANS is an efficient k-medoids clustering algorithm that searches for optimal medoids by examining a randomized subset of neighboring medoid configurations on the graph G_{n, k}.

Parameters:
  • n_clusters (int, default=8) – The number of clusters to form (also the number of medoids to generate).

  • num_local (int, default=2) – The number of local searches to perform. CLARANS runs the search process num_local times starting from different random nodes to reduce the chance of getting stuck in poor local minima. Increasing this improves solution quality but increases runtime.

  • max_neighbors (int or 'auto', default='auto') –

    The maximum number of neighbors (random swaps) to examine during each step. If 'auto', it defaults to max(250, 1.25% of k*(n-k)) as recommended in the original paper (Ng & Han, 2002). This adaptive default balances runtime and solution quality automatically without requiring manual tuning. Higher values make the algorithm behave more like PAM (checking more neighbors); lower values make it faster.

    Note

    In CLARANS, each neighbor evaluation tests a single randomly chosen pair (medoid, candidate). Setting a very small integer (e.g. max_neighbors=40) checks only a tiny fraction of the k * (n - k) search space, which often causes CLARANS to fail consecutive tests early and stop prematurely after only a few swaps. Contrast this with FastCLARANS, where each candidate step checks all k medoids simultaneously via FastPAM1 delta caching.

  • init (str | ArrayLike)

  • metric (str | Any)

  • metric_params (dict[str, Any] | None)

  • random_state (int | np.random.RandomState | None)

  • cost_evaluation (str)

  • verbose (int)

init{‘k-medoids++’, ‘random’, ‘heuristic’, ‘build’, array-like}, default=’k-medoids++’

Strategy for selecting initial medoids (adapted from scikit-learn-extra):

  • 'k-medoids++': Optimized probabilistic initialization (similar to k-means++) for faster convergence.

  • 'random': Selects n_clusters random points. Fast but can result in poor starting points.

  • 'heuristic': Selects points that are “central” to the data (minimizing distance to all others).

  • 'build': The greedy initialization from the original PAM algorithm. High quality but slow (O(N^2)).

  • array-like: If an array is passed, it should be of shape (n_clusters, n_features) giving the initial centers, or (n_clusters,) of integer indices if metric='precomputed'.

metricstr or callable, default=’euclidean’

The distance metric to use. Supports all metrics from sklearn.metrics.pairwise_distances, scipy.spatial.distance.cdist, and sklearn.metrics.DistanceMetric (e.g., ‘euclidean’, ‘manhattan’, ‘cosine’, ‘chebyshev’, ‘precomputed’) or a callable.

metric_paramsdict, default=None

Additional keyword arguments for the metric function.

random_stateint, RandomState instance or None, default=None

Determines random number generation for medoid swaps and random initialization. Pass an int for reproducible output across multiple function calls.

cost_evaluation{‘delta’, ‘brute_force’}, default=’delta’

Strategy for evaluating candidate neighbor medoid swaps:

  • 'delta': Uses FastPAM1-style nearest and second-nearest distance tracking (d1, d2) to evaluate swaps in O(n*d) without recalculating the full clustering cost. Recommended for optimal performance.

  • 'brute_force': Recalculates the total clustering cost from scratch in O(n*k*d) at each candidate swap, following the original classic CLARANS algorithm (Ng & Han, 2002).

verboseint, default=0

Verbosity mode. Controls the level of progress messages printed during fitting:

  • 0: Silent (default).

  • 1: Prints progress for each local search iteration (start, completion, cost, elapsed time, swaps performed, and candidates evaluated).

  • >=2: Additionally prints details on each successful medoid swap.

cluster_centers_

Coordinates of cluster centers (medoids). If metric='precomputed', this is None.

Type:

{ndarray, sparse matrix} of shape (n_clusters, n_features) or None

labels_

Labels of each point indicating the nearest medoid.

Type:

ndarray of shape (n_samples,)

medoid_indices_

Indices of the medoids in the training set X.

Type:

ndarray of shape (n_clusters,)

inertia_

Sum of distances of samples to their closest cluster center.

Type:

float

max_neighbors_

Effective maximum number of non-improving neighbors examined per local search before concluding convergence.

Type:

int

n_neighbors_

Total number of neighbor transitions in the search graph G_{n, k}, equal to n_clusters * (n_samples - n_clusters).

Type:

int

n_iter_

Total number of candidate neighbors evaluated across all num_local searches.

Type:

int

n_swaps_

Total number of successful medoid swaps performed across all num_local searches.

Type:

int

n_features_in_

Number of features seen during fit. Defined only when metric != 'precomputed'.

Type:

int

Notes

  • Time complexity: In each local search, random candidate neighbor swaps are evaluated on the search graph G_{n,k}. The search terminates when max_neighbors consecutive non-improving swaps are tested. With S successful swaps and distance evaluation cost O(n * k * d), runtime per local search is bounded by O((S + max_neighbors) * n * k * d), repeated num_local times.

  • Memory complexity: Distances are computed on-the-fly, keeping memory usage at O(n) instead of O(n^2). Note that initialization methods such as 'build' and 'heuristic' compute full pairwise distance matrices and therefore have O(n^2) time and memory costs.

  • Compared with FastCLARANS: This class implements the classic randomized search from Ng & Han (2002). For faster execution on larger datasets, consider FastCLARANS, which tests swaps with all k medoids simultaneously using FastPAM1 delta calculations.

References

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, default=None) – Not used, present here for API consistency with scikit-learn pipelines and ClusterMixin.

Returns:

self – Fitted estimator. Attributes set on the estimator include medoid_indices_, cluster_centers_, and labels_.

Return type:

CLARANS

Raises:

ValueError – If n_clusters >= n_samples, or if an explicit init array 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 max_neighbors candidate swaps, and each cost evaluation is O(n * k) (distance to medoids), so the worst-case runtime is roughly O(num_local * max_neighbors * 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 X does not match the number of features seen during fitting.

Notes

This method uses pairwise_distances_argmin_min from 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)

score(X, y=None)[source]

Opposite of the total distance of samples to their closest cluster center.

Enables direct integration with GridSearchCV and cross_val_score. Uses transform(X) to evaluate distances to learned medoids on both train and unseen test data.

Parameters:
  • X ({array-like, sparse matrix} of shape (n_samples, n_features)) – or (n_samples, n_train_samples) if metric=’precomputed’. New data to score.

  • y (Ignored, default=None) – Not used, present here for API consistency with scikit-learn.

Returns:

score – Opposite of the total cost (sum of distances to the closest center).

Return type:

float

get_feature_names_out(input_features=None)[source]

Get output feature names for transformation.

The feature names out will be prefixed by the lowercased class name. For example, if the transformer outputs 3 features, then the feature names out are: [“clarans0”, “clarans1”, “clarans2”] (or fastclarans0, etc.).

Parameters:

input_features (array-like of str or None, default=None) – Only used to validate feature names with the names seen in fit.

Returns:

feature_names_out – Transformed feature names.

Return type:

ndarray of str objects

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. Pass only if the estimator accepts additional params in its fit method.

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 MetadataRequest encapsulating routing information.

Return type:

MetadataRequest

get_params(deep=True)

Get parameters for this estimator.

Parameters:

deep (bool, default=True) – If True, will return the parameters for this estimator and contained subobjects that are estimators.

Returns:

params – Parameter names mapped to their values.

Return type:

dict

set_output(*, transform=None)

Set output container.

Refer to the user guide for more details and 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

FastCLARANS

FastPAM1 k-medoids estimator (Schubert & Rousseeuw, 2021).

class clarans.FastCLARANS(*, n_clusters=8, num_local=2, max_neighbors='auto', init='k-medoids++', metric='euclidean', metric_params=None, random_state=None, verbose=0)[source]

Bases: CLARANS

FastCLARANS: Fast variant of the CLARANS clustering algorithm.

Parameters:
  • n_clusters (int, default=8) – The number of clusters to form (also the number of medoids).

  • num_local (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.

  • max_neighbors (int | str) – The maximum number of non-medoid candidates to sample per local search. If 'auto', defaults to max(1, int(250 / k), int(0.025 * (n - k))) combining the 2.5% non-medoid sample recommended by Schubert & Rousseeuw (2021) with a proportional floor equivalent to 250 edge evaluations (Ng & Han, 2002). This adaptive default automatically scales with dataset size without requiring manual tuning.

  • init (str | ArrayLike)

  • metric (str | Any)

  • metric_params (dict[str, Any] | None)

  • random_state (int | np.random.RandomState | None)

  • verbose (int)

init{‘k-medoids++’, ‘random’, ‘heuristic’, ‘build’, array-like}, default=’k-medoids++’

Method for initialization (adapted from scikit-learn-extra). 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.

metricstr or callable, default=’euclidean’

The distance metric to use. Supports all metrics from sklearn.metrics.pairwise_distances, scipy.spatial.distance.cdist, and sklearn.metrics.DistanceMetric (e.g., ‘euclidean’, ‘manhattan’, ‘cosine’, ‘chebyshev’, ‘precomputed’) or a callable.

metric_paramsdict, default=None

Additional keyword arguments for the metric function.

random_stateint, RandomState instance or None, default=None

Controls random number generation for reproducibility.

verboseint, default=0

Verbosity mode. Controls the level of progress messages printed during fitting:

  • 0: Silent (default).

  • 1: Prints progress for each local search iteration (start, completion, cost, elapsed time, swaps performed, and candidates evaluated).

  • >=2: Additionally prints details on each successful medoid swap.

cluster_centers_

Coordinates of cluster centers (medoids). If metric='precomputed', this is None.

Type:

{ndarray, sparse matrix} of shape (n_clusters, n_features) or None

labels_

Labels of each point indicating the nearest medoid.

Type:

ndarray of shape (n_samples,)

medoid_indices_

Indices of the selected medoids in the training set.

Type:

ndarray of shape (n_clusters,)

inertia_

Sum of distances from each sample to its nearest medoid (total cost of the best solution found).

Type:

float

max_neighbors_

Effective maximum number of non-improving non-medoid candidates sampled per local search before concluding convergence.

Type:

int

n_neighbors_

Total number of non-medoid candidate points, equal to n_samples - n_clusters.

Type:

int

n_iter_

Total number of candidate neighbors evaluated across all num_local searches.

Type:

int

n_swaps_

Total number of successful medoid swaps performed across all num_local searches.

Type:

int

n_features_in_

Number of features seen during fit. Defined only when metric != 'precomputed'.

Type:

int

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

fit(X, y=None)

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, default=None) – Not used, present here for API consistency with scikit-learn pipelines and ClusterMixin.

Returns:

self – Fitted estimator. Attributes set on the estimator include medoid_indices_, cluster_centers_, and labels_.

Return type:

CLARANS

Raises:

ValueError – If n_clusters >= n_samples, or if an explicit init array 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 max_neighbors candidate swaps, and each cost evaluation is O(n * k) (distance to medoids), so the worst-case runtime is roughly O(num_local * max_neighbors * 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)
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. Pass only if the estimator accepts additional params in its fit method.

Returns:

X_new – Transformed array.

Return type:

ndarray array of shape (n_samples, n_features_new)

get_feature_names_out(input_features=None)

Get output feature names for transformation.

The feature names out will be prefixed by the lowercased class name. For example, if the transformer outputs 3 features, then the feature names out are: [“clarans0”, “clarans1”, “clarans2”] (or fastclarans0, etc.).

Parameters:

input_features (array-like of str or None, default=None) – Only used to validate feature names with the names seen in fit.

Returns:

feature_names_out – Transformed feature names.

Return type:

ndarray of str objects

get_metadata_routing()

Get metadata routing of this object.

Please check User Guide on how the routing mechanism works.

Returns:

routing – A MetadataRequest encapsulating routing information.

Return type:

MetadataRequest

get_params(deep=True)

Get parameters for this estimator.

Parameters:

deep (bool, default=True) – If True, will return the parameters for this estimator and contained subobjects that are estimators.

Returns:

params – Parameter names mapped to their values.

Return type:

dict

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 X does not match the number of features seen during fitting.

Notes

This method uses pairwise_distances_argmin_min from scikit-learn to assign each sample to the nearest medoid.

score(X, y=None)

Opposite of the total distance of samples to their closest cluster center.

Enables direct integration with GridSearchCV and cross_val_score. Uses transform(X) to evaluate distances to learned medoids on both train and unseen test data.

Parameters:
  • X ({array-like, sparse matrix} of shape (n_samples, n_features)) – or (n_samples, n_train_samples) if metric=’precomputed’. New data to score.

  • y (Ignored, default=None) – Not used, present here for API consistency with scikit-learn.

Returns:

score – Opposite of the total cost (sum of distances to the closest center).

Return type:

float

set_output(*, transform=None)

Set output container.

Refer to the user guide for more details and 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

Initialization

Medoid initialization strategies: k-medoids++, build, heuristic, and random sampling.

Initialization strategies for k-medoids clustering.

The initialization methods (‘k-medoids++’, ‘heuristic’, ‘build’) are adapted from the scikit-learn-extra KMedoids implementation: https://scikit-learn-extra.readthedocs.io/en/stable/generated/sklearn_extra.cluster.KMedoids.html

clarans._initialization.initialize_heuristic(X, n_clusters, metric='euclidean', metric_params=None)[source]

Initialize medoids using a heuristic approach.

Picks the n_clusters points with the smallest sum distance to every other point.

Parameters:
  • X ({array-like, sparse matrix} of shape (n_samples, n_features)) – The input samples.

  • n_clusters (int) – The number of clusters to form.

  • metric (str or callable, default='euclidean') – The metric to use when calculating distance between instances in a feature array.

  • metric_params (dict, default=None) – Additional keyword arguments for the metric function.

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.

References

Adapted from the scikit-learn-extra KMedoids implementation: https://scikit-learn-extra.readthedocs.io/en/stable/generated/sklearn_extra.cluster.KMedoids.html

clarans._initialization.initialize_build(X, n_clusters, metric='euclidean', metric_params=None)[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:
  • X ({array-like, sparse matrix} of shape (n_samples, n_features)) – The input samples.

  • n_clusters (int) – The number of clusters to form.

  • metric (str or callable, default='euclidean') – The metric to use when calculating distance between instances in a feature array.

  • metric_params (dict, default=None) – Additional keyword arguments for the metric function.

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. This method implements the greedy BUILD phase from PAM (Kaufman & Rousseeuw, 1990).

References

Adapted from the scikit-learn-extra KMedoids implementation: https://scikit-learn-extra.readthedocs.io/en/stable/generated/sklearn_extra.cluster.KMedoids.html

clarans._initialization.initialize_k_medoids_plus_plus(X, n_clusters, random_state=None, metric='euclidean', n_local_trials=None, metric_params=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 initial medoid selection.

  • 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 local seeding trials for each center. If None, defaults to 2 + int(np.log(n_clusters)) as recommended by Arthur & Vassilvitskii.

  • metric_params (dict, default=None) – Additional keyword arguments for the metric function.

Returns:

medoid_indices – 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 (Arthur & Vassilvitskii, 2007) but uses distances squared and picks medoids (data indices) rather than centroids.

References

Adapted from the scikit-learn-extra KMedoids implementation: https://scikit-learn-extra.readthedocs.io/en/stable/generated/sklearn_extra.cluster.KMedoids.html

Utilities

Distance metrics, objective evaluations, and validation helpers.

clarans.utils.calculate_cost(X, medoid_indices, metric='euclidean', metric_params=None)[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)) – or shape (n_samples, n_samples) if metric=’precomputed’. 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.

  • metric_params (dict, default=None) – Additional keyword arguments for the metric function.

Returns:

cost – The total sum of distances from each point to its nearest medoid.

Return type:

float

clarans.utils.check_medoids(medoid_indices=None, n_samples=None, *, medoids=None)[source]

Validate and convert medoid indices to a 1D NumPy array of integers.

Parameters:
  • medoid_indices (array-like of shape (n_clusters,)) – Indices representing medoid observations.

  • n_samples (int, optional) – Total number of samples in the dataset. If provided, ensures that all medoid indices satisfy 0 <= idx < n_samples.

  • medoids (array-like of shape (n_clusters,), optional) – Alias for medoid_indices for backwards compatibility.

Returns:

medoids_arr – Validated 1D array of unique medoid indices.

Return type:

np.ndarray of shape (n_clusters,) and dtype np.intp

Raises:
  • ValueError – If medoid_indices is empty, contains duplicate indices, has invalid dimensions, contains negative indices, or has indices outside the valid range [0, n_samples - 1].

  • TypeError – If medoid_indices contains non-integer elements.

exception clarans.utils.EfficiencyWarning[source]

Bases: UserWarning

Warning issued when falling back to pure Python/NumPy implementation.