Welcome to k-means-constrained’s documentation!

The GitHub project can be found here.

To install k-means-constrained using pip:

pip install k-means-constrained

API documentation:

class k_means_constrained.KMeansConstrained(n_clusters=8, size_min=None, size_max=None, init='k-means++', n_init=10, max_iter=300, tol=0.0001, verbose=False, random_state=None, copy_x=True, n_jobs=1)[source]

K-Means clustering with minimum and maximum cluster size constraints

Parameters
n_clustersint, optional, default: 8

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

size_minint, optional, default: None

Constrain the label assignment so that each cluster has a minimum size of size_min. If None, no constrains will be applied

size_maxint, optional, default: None

Constrain the label assignment so that each cluster has a maximum size of size_max. If None, no constrains will be applied

init{‘k-means++’, ‘random’ or an ndarray}

Method for initialization, defaults to ‘k-means++’:

‘k-means++’ : selects initial cluster centers for k-mean clustering in a smart way to speed up convergence. See section Notes in k_init for more details.

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

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

n_initint, default: 10

Number of times 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.

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, optional, default: None

If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by np.random.

copy_xboolean, default True

When pre-computing distances it is more numerically accurate to center the data first. If copy_x is True, 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.

n_jobsint

The number of jobs to use for the computation. This works by computing each of the n_init runs in parallel.

If -1 all CPUs are used. If 1 is given, no parallel computing code is used at all, which is useful for debugging. For n_jobs below -1, (n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one are used.

Notes

K-means problem constrained with a minimum and/or maximum size for each cluster.

The constrained assignment is formulated as a Minimum Cost Flow (MCF) linear network optimisation problem. This is then solved using a cost-scaling push-relabel algorithm. The implementation used is

Google’s Operations Research tools’s SimpleMinCostFlow.

Ref: 1. Bradley, P. S., K. P. Bennett, and Ayhan Demiriz. “Constrained k-means clustering.”

Microsoft Research, Redmond (2000): 1-8.

  1. Google’s SimpleMinCostFlow implementation:

    https://github.com/google/or-tools/blob/master/ortools/graph/min_cost_flow.h

Examples

>>> from k_means_constrained import KMeansConstrained
>>> import numpy as np
>>> X = np.array([[1, 2], [1, 4], [1, 0],
...                [4, 2], [4, 4], [4, 0]])
>>> clf = KMeansConstrained(
...     n_clusters=2,
...     size_min=2,
...     size_max=5,
...     random_state=0
... )
>>> clf.fit_predict(X)
array([0, 0, 0, 1, 1, 1], dtype=int32)
>>> clf.cluster_centers_
array([[ 1.,  2.],
       [ 4.,  2.]])
>>> clf.labels_
array([0, 0, 0, 1, 1, 1], dtype=int32)
Attributes
cluster_centers_array, [n_clusters, n_features]

Coordinates of cluster centers

labels_ :

Labels of each point

inertia_float

Sum of squared distances of samples to their closest cluster center.

Methods

fit(X[, y])

Compute k-means clustering with given constants.

fit_predict(X[, y])

Compute cluster centers and predict cluster index for each sample.

fit_transform(X[, y])

Compute clustering and transform X to cluster-distance space.

get_params([deep])

Get parameters for this estimator.

predict(X[, size_min, size_max])

Predict the closest cluster each sample in X belongs to given the provided constraints.

score(X[, y])

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

set_params(**params)

Set the parameters of this estimator.

transform(X)

Transform X to a cluster-distance space.

fit(X, y=None)[source]

Compute k-means clustering with given constants.

Parameters
Xarray-like, shape=(n_samples, n_features)

Training instances to cluster.

yIgnored
predict(X, size_min='init', size_max='init')[source]

Predict the closest cluster each sample in X belongs to given the provided constraints. The constraints can be temporally overridden when determining which cluster each datapoint is assigned to.

Only computes the assignment step. It does not re-fit the cluster positions.

Parameters
Xarray-like, shape = [n_samples, n_features]

New data to predict.

size_minint, optional, default: size_min provided with initialisation

Constrain the label assignment so that each cluster has a minimum size of size_min. If None, no constrains will be applied. If ‘init’ the value provided during initialisation of the class will be used.

size_maxint, optional, default: size_max provided with initialisation

Constrain the label assignment so that each cluster has a maximum size of size_max. If None, no constrains will be applied. If ‘init’ the value provided during initialisation of the class will be used.

Returns
labelsarray, shape [n_samples,]

Index of the cluster each sample belongs to.

fit_predict(X, y=None)[source]

Compute cluster centers and predict cluster index for each sample.

Equivalent to calling fit(X) followed by predict(X) but also more efficient.

Parameters
X{array-like, sparse matrix}, shape = [n_samples, n_features]

New data to transform.

Returns
labelsarray, 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}, shape = [n_samples, n_features]

New data to transform.

Returns
X_newarray, shape [n_samples, k]

X transformed in the new space.

get_params(deep=True)

Get parameters for this estimator.

Parameters
deepboolean, optional

If True, will return the parameters for this estimator and contained subobjects that are estimators.

Returns
paramsmapping of string to any

Parameter names mapped to their values.

score(X, y=None)

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

Parameters
X{array-like, sparse matrix}, shape = [n_samples, n_features]

New data.

Returns
scorefloat

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

set_params(**params)

Set the parameters of this estimator.

The method works on simple estimators as well as on nested objects (such as pipelines). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.

Returns
self
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}, shape = [n_samples, n_features]

New data to transform.

Returns
X_newarray, shape [n_samples, k]

X transformed in the new space.