ConstrainedKMeans

class ccluster.size.ConstrainedKMeans(n_clusters, cluster_sizes, *, init='k-means++', n_init=10, max_iter=300, tol=0.0001, verbose=0, random_state=None, copy_x=True)

Perform K-means clustering algorithm with cluster size constraints.

Parameters:
n_clustersint, default=8

The number of clusters to form as well as the number of centroids to generate.

cluster_sizesarray-like of shape (n_constraints,), default=None

The constraints for the cluster sizes. If None, we retrieve the classical Lloyd algorithm. The constraints can either be exhaustive (n_constraints == n_clusters) or partial (n_constraints < n_clusters).

init{‘k-means++’, ‘random’}, callable or array-like of shape (n_clusters, n_features), default=’k-means++’

Method for initialization:

  • ‘k-means++’ : selects initial cluster centroids using sampling based on an empirical probability distribution of the points’ contribution to the overall inertia. This technique speeds up convergence. The algorithm implemented is “greedy k-means++”. It differs from the vanilla k-means++ by making several trials at each sampling step and choosing the best centroid among them.

  • ‘random’: choose n_clusters observations (rows) at random from data for the initial centroids.

  • If an array is passed, it should be of shape (n_clusters, n_features) and gives the initial centers.

  • If a callable is passed, it should take arguments X, n_clusters and a random state and return an initialization.

n_initint, default=10

Number of times the k-means algorithm is run with different centroid seeds. The final results will be the best output of n_init consecutive runs in terms of inertia.

max_iterint, default=300

Maximum number of iterations of the k-means algorithm for a single run.

tolfloat, default=1e-4

Relative tolerance with regards to Frobenius norm of the difference in the cluster centers of two consecutive iterations to declare convergence.

verboseint, default=0

Verbosity mode.

random_stateint, RandomState instance or None, default=None

Determines random number generation for centroid initialization. Use an int to make the randomness deterministic.

copy_xbool, default=True

When pre-computing distances it is more numerically accurate to center the data first. If copy_x is True (default), then the original data is not modified. If False, the original data is modified, and put back before the function returns, but small numerical differences may be introduced by subtracting and then adding the data mean. Note that if the original data is not C-contiguous, a copy will be made even if copy_x is False. If the original data is sparse, but not in CSR format, a copy will be made even if copy_x is False.

Attributes:
cluster_centers_ndarray of shape (n_clusters, n_features)

Coordinates of cluster centers. If the algorithm stops before fully converging (see tol and max_iter), these will not be consistent with labels_.

labels_ndarray of shape (n_samples,)

Labels of each point

inertia_float

Sum of squared distances of samples to their closest cluster center, weighted by the sample weights if provided.

n_iter_int

Number of iterations run.

Examples

>>> from ccluster.size import ConstrainedKMeans
>>> import numpy as np
>>> X = np.array([[1, 2], [1, 4], [1, 0],
>>>                [10, 2], [10, 4], [10, 0]])
>>> kmeans = ConstrainedKMeans(n_clusters=2, cluster_sizes=[2, 4], random_state=0, n_init=10).fit(X)
>>> kmeans.labels_
array([1, 1, 1, 0, 0, 1])
>>> kmeans.predict([[0, 0], [12, 3]], [1, 1])
array([1, 0], dtype=int32)
>>>  kmeans.cluster_centers_
array([[10.  ,  3.  ],
       [ 3.25,  1.5 ]])
fit(X, y=None)

Compute k-means clustering.

Parameters:
X{array-like, sparse matrix} of shape (n_samples, n_features)

Training instances to cluster. It must be noted that the data will be converted to C ordering, which will cause a memory copy if the given data is not C-contiguous. If a sparse matrix is passed, a copy will be made if it’s not in CSR format.

yIgnored

Not used, present here for API consistency by convention.

Returns:
selfobject

Fitted estimator.

fit_predict(X, y=None)

Compute cluster centers and predict cluster index for each sample.

Convenience method; equivalent to calling fit(X) followed by predict(X).

Parameters:
X{array-like, sparse matrix} of shape (n_samples, n_features)

New data to transform.

yIgnored

Not used, present here for API consistency by convention.

Returns:
labelsndarray of shape (n_samples,)

Index of the cluster each sample belongs to.

fit_transform(X, y=None)

Compute clustering and transform X to cluster-distance space.

Equivalent to fit(X).transform(X), but more efficiently implemented.

Parameters:
X{array-like, sparse matrix} of shape (n_samples, n_features)

New data to transform.

yIgnored

Not used, present here for API consistency by convention.

Returns:
X_newndarray of shape (n_samples, n_clusters)

X transformed in the new space.

predict(X, cluster_sizes=None)

Predict the closest cluster each sample in X belongs to.

In the vector quantization literature, cluster_centers_ is called the code book and each value returned by predict is the index of the closest code in the code book.

Parameters:
X{array-like, sparse matrix} of shape (n_samples, n_features)

New data to predict.

cluster_sizes: ndarray of shape (n_constraints,)

The number of points to assign to each constrained cluster.

Returns
——-
labelsndarray of shape (n_samples,)

Index of the cluster each sample belongs to.

score(X, y=None)

Opposite of the value of X on the K-means objective.

Parameters:
X{array-like, sparse matrix} of shape (n_samples, n_features)

New data.

yIgnored

Not used, present here for API consistency by convention.

Returns:
scorefloat

Opposite of the value of X on the K-means objective.

set_predict_request(*, cluster_sizes: bool | None | str = '$UNCHANGED$') ConstrainedKMeans

Request metadata passed to the predict method.

Note that this method is only relevant if enable_metadata_routing=True (see sklearn.set_config()). Please see User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to predict if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to predict.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Note

This method is only relevant if this estimator is used as a sub-estimator of a meta-estimator, e.g. used inside a Pipeline. Otherwise it has no effect.

Parameters:
cluster_sizesstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

Metadata routing for cluster_sizes parameter in predict.

Returns:
selfobject

The updated object.

transform(X)

Transform X to a cluster-distance space.

In the new space, each dimension is the distance to the cluster centers. Note that even if X is sparse, the array returned by transform will typically be dense.

Parameters:
X{array-like, sparse matrix} of shape (n_samples, n_features)

New data to transform.

Returns:
X_newndarray of shape (n_samples, n_clusters)

X transformed in the new space.

ConstrainedSpectralClustering

class ccluster.size.ConstrainedSpectralClustering(n_clusters=8, *, cluster_sizes=None, eigen_solver=None, n_components=None, random_state=None, n_init=10, gamma=1.0, affinity='rbf', n_neighbors=10, eigen_tol='auto', degree=3, coef0=1, kernel_params=None, n_jobs=None, verbose=False)

Apply clustering to a projection of the normalized Laplacian with cluster size constraints.

When calling fit, an affinity matrix is constructed using either a kernel function such the Gaussian (aka RBF) kernel with Euclidean distance d(X, X):

np.exp(-gamma * d(X,X) ** 2)

or a k-nearest neighbors connectivity matrix.

Alternatively, a user-provided affinity matrix can be specified by setting affinity='precomputed'.

Parameters:
n_clustersint, default=8

The dimension of the projection subspace.

cluster_sizesarray-like of shape (n_constraints,), default=None

The constraints for the cluster sizes. If None, we retrieve the classical spectral clustering algorithm. The constraints can either be exhaustive (n_constraints == n_clusters) or partial (n_constraints < n_clusters).

eigen_solver{‘arpack’, ‘lobpcg’, ‘amg’}, default=None

The eigenvalue decomposition strategy to use. AMG requires pyamg to be installed. It can be faster on very large, sparse problems, but may also lead to instabilities. If None, then 'arpack' is used.

n_componentsint, default=None

Number of eigenvectors to use for the spectral embedding. If None, defaults to n_clusters.

random_stateint, RandomState instance, default=None

A pseudo random number generator used for the initialization of the lobpcg eigenvectors decomposition when eigen_solver == ‘amg’, and for the K-Means initialization. Use an int to make the results deterministic across calls.

Note

When using eigen_solver == ‘amg’, it is necessary to also fix the global numpy seed with np.random.seed(int) to get deterministic results. See https://github.com/pyamg/pyamg/issues/139 for further information.

n_initint, default=10

Number of time the k-means algorithm will be run with different centroid seeds. The final results will be the best output of n_init consecutive runs in terms of inertia.

gammafloat, default=1.0

Kernel coefficient for rbf, poly, sigmoid, laplacian and chi2 kernels. Ignored for affinity='nearest_neighbors'.

affinitystr or callable, default=’rbf’
How to construct the affinity matrix.
  • ‘nearest_neighbors’: construct the affinity matrix by computing a graph of nearest neighbors.

  • ‘rbf’: construct the affinity matrix using a radial basis function (RBF) kernel.

  • ‘precomputed’: interpret X as a precomputed affinity matrix, where larger values indicate greater similarity between instances.

  • ‘precomputed_nearest_neighbors’: interpret X as a sparse graph of precomputed distances, and construct a binary affinity matrix from the n_neighbors nearest neighbors of each instance.

  • one of the kernels supported by pairwise_kernels().

Only kernels that produce similarity scores (non-negative values that increase with similarity) should be used. This property is not checked by the clustering algorithm.

n_neighborsint, default=10

Number of neighbors to use when constructing the affinity matrix using the nearest neighbors method. Ignored for affinity='rbf'.

eigen_tolfloat, default=”auto”

Stopping criterion for eigen decomposition of the Laplacian matrix. If eigen_tol=”auto” then the passed tolerance will depend on the eigen_solver:

  • If eigen_solver=”arpack”, then eigen_tol=0.0;

  • If eigen_solver=”lobpcg” or eigen_solver=”amg”, then eigen_tol=None which configures the underlying lobpcg solver to automatically resolve the value according to their heuristics. See, scipy.sparse.linalg.lobpcg() for details.

Note that when using eigen_solver=”lobpcg” or eigen_solver=”amg” values of tol<1e-5 may lead to convergence issues and should be avoided.

degreefloat, default=3

Degree of the polynomial kernel. Ignored by other kernels.

coef0float, default=1

Zero coefficient for polynomial and sigmoid kernels. Ignored by other kernels.

kernel_paramsdict of str to any, default=None

Parameters (keyword arguments) and values for kernel passed as callable object. Ignored by other kernels.

n_jobsint, default=None

The number of parallel jobs to run when affinity=’nearest_neighbors’ or affinity=’precomputed_nearest_neighbors’. The neighbors search will be done in parallel. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors.

verbosebool, default=False

Verbosity mode.

Attributes:
affinity_matrix_array-like of shape (n_samples, n_samples)

Affinity matrix used for clustering. Available only after calling fit.

labels_ndarray of shape (n_samples,)

Labels of each point

n_features_in_int

Number of features seen during fit.

feature_names_in_ndarray of shape (n_features_in_,)

Names of features seen during fit. Defined only when X has feature names that are all strings.

Notes

A distance matrix for which 0 indicates identical elements and high values indicate very dissimilar elements can be transformed into an affinity / similarity matrix that is well-suited for the algorithm by applying the Gaussian (aka RBF, heat) kernel:

np.exp(- dist_matrix ** 2 / (2. * delta ** 2))

where delta is a free parameter representing the width of the Gaussian kernel.

An alternative is to take a symmetric version of the k-nearest neighbors connectivity matrix of the points.

If the pyamg package is installed, it is used: this greatly speeds up computation.

Examples

>>> from ccluster.size import ConstrainedSpectralClustering
>>> import numpy as np
>>> X = np.array([[1, 1], [2, 1], [1, 0],
...               [4, 7], [3, 5], [3, 6]])
>>> clustering = ConstrainedSpectralClustering(n_clusters=2, cluster_sizes=[4, 2],
...         random_state=0).fit(X)
>>> clustering.labels_
array([0, 0, 0, 1, 0, 1])
>>> clustering
ConstrainedSpectralClustering(cluster_sizes=array([4, 2]), n_clusters=2,
    random_state=0)
fit(X, y=None)

Perform spectral clustering from features, or affinity matrix.

Parameters:
X{array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples, n_samples)

Training instances to cluster, similarities / affinities between instances if affinity='precomputed', or distances between instances if affinity='precomputed_nearest_neighbors. If a sparse matrix is provided in a format other than csr_matrix, csc_matrix, or coo_matrix, it will be converted into a sparse csr_matrix.

yIgnored

Not used, present here for API consistency by convention.

Returns:
selfobject

A fitted instance of the estimator.

fit_predict(X, y=None)

Perform constrained spectral clustering on X and return cluster labels.

Parameters:
X{array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples, n_samples)

Training instances to cluster, similarities / affinities between instances if affinity='precomputed', or distances between instances if affinity='precomputed_nearest_neighbors. If a sparse matrix is provided in a format other than csr_matrix, csc_matrix, or coo_matrix, it will be converted into a sparse csr_matrix.

yIgnored

Not used, present here for API consistency by convention.

Returns:
labelsndarray of shape (n_samples,)

Cluster labels.