Robust clustering

Clustering by trimming, in robustmodels.cluster. A few outliers can pull a k-means center or a normal mixture component towards them, or take a cluster of their own. TClust discards the fraction alpha of observations that no cluster explains well, and fits normal clusters to the rest.

Use

>>> import numpy as np
>>> from robustmodels.cluster import TClust
>>> rng = np.random.default_rng(1)
>>> X = np.vstack(
...     [
...         rng.multivariate_normal([0, 0], np.eye(2), 100),
...         rng.multivariate_normal([5, 5], [[4, 0], [0, 0.3]], 80),
...         rng.multivariate_normal([-4, 6], [[1, 0.8], [0.8, 1]], 60),
...         rng.uniform(-10, 12, (12, 2)),  # scattered noise
...     ]
... )
>>> fit = TClust(n_clusters=3, alpha=0.05, random_state=0).fit(X)
>>> np.bincount(fit.labels_ + 1).tolist()  # trimmed, then each cluster
[13, 99, 79, 61]
>>> fit.means_.round(2).tolist()
[[-0.05, -0.05], [4.52, 4.95], [-4.16, 5.95]]

labels_ is -1 for trimmed observations, and the clusters are ordered by size. means_, covariances_ and weights_ describe the fitted normal clusters; predict(X) assigns new observations and trims those less plausible than every retained training observation.

import numpy as np
from robustmodels import plots
from robustmodels.cluster import TClust

rng = np.random.default_rng(1)
X = np.vstack([
    rng.multivariate_normal([0, 0], np.eye(2), 100),
    rng.multivariate_normal([5, 5], [[4, 0], [0, 0.3]], 80),
    rng.multivariate_normal([-4, 6], [[1, 0.8], [0.8, 1]], 60),
    rng.uniform(-10, 12, (12, 2)),
])
plots.cluster_plot(TClust(3, random_state=0).fit(X), X)

(png, svg)

Three clusters of different shapes with 97.5% ellipses and trimmed noise points.

Choosing the parameters

  • restr_factor bounds the ratio between the largest and the smallest eigenvalue of all the cluster covariances. Without a bound the likelihood is unbounded (a cluster can collapse on a few points). The default 12, as in R, allows elongated clusters of different sizes; 1 forces spherical clusters of equal spread.

  • equal_weights=True assumes clusters of similar size. With restr_factor=1 it gives trimmed k-means.

  • alpha should exceed the expected share of outliers; trimming a few regular observations costs little. Fit several values of alpha and n_clusters and compare the solutions and their plots; the trimmed likelihood (objective_) always grows with the number of clusters, so do not choose n_clusters by maximizing it.

  • n_init random starts (500 by default) are improved by concentration steps; the search returns a local maximum, so keep many starts.

The classification trimmed likelihood curves (García-Escudero et al. 2011), R’s ctlcurves, guide both choices: they draw objective_ against alpha for each number of clusters. Choose the smallest k whose curve is close to that of k + 1, and the smallest alpha from which they stay close. Here the curves for 3 and 4 clusters merge from alpha = 0.04: three clusters, with about 5% of noise.

import numpy as np
from robustmodels import plots

rng = np.random.default_rng(4)
X = np.vstack([
    rng.multivariate_normal([0, 0], np.eye(2), 100),
    rng.multivariate_normal([5, 5], [[4, 0], [0, 0.3]], 80),
    rng.multivariate_normal([-4, 6], [[1, 0.8], [0.8, 1]], 60),
    rng.uniform(-10, 12, (15, 2)),
])
plots.ctl_curves(X, n_init=100, random_state=0)

(png, svg)

Trimmed likelihood against the trimming level for one to four clusters.

Numerical checks and sources

The eigenvalue restriction is the optimal truncation of Fritz, García-Escudero and Mayo-Iscar (2013); the tests compare it with a brute-force minimization of its criterion over a fine grid. The fitted model reproduces its own assignment and trimming of the training data, and trimmed k-means assigns each retained observation to its nearest center and trims the farthest ones. On frozen data, R’s tclust 2.2 finds the same partition, means, weights and objective (to 1e-10), and tkmeans the same partition and centers. The starts and concentration steps follow tclust’s code. The fit works in centered, rescaled coordinates and returns estimates and likelihoods in the original units. converged_ indicates that consecutive assignments were identical. At the iteration limit the returned weights are the ones used to compute the final assignments and likelihood. If the updated covariances all collapse, the search keeps its last scored set of parameters.

Sources are García-Escudero, Gordaliza, Matrán and Mayo-Iscar (2008), Fritz, García-Escudero and Mayo-Iscar (2012, 2013) and Cuesta-Albertos, Gordaliza and Matrán (1997).

Reference

class TClust(n_clusters=2, *, alpha=0.05, restr_factor=12.0, equal_weights=False, n_init=500, max_iter=20, random_state=None)[source]

Robust clustering by trimming and eigenvalue restrictions (García-Escudero et al. 2008).

Finds n_clusters normal clusters that maximize the classification likelihood sum log(w_j phi(x_i; mu_j, Sigma_j)) of the observations they keep, after discarding a fraction alpha of the sample: the observations whose best cluster explains them worst. The ratio between the largest and smallest eigenvalue of all the covariance matrices is at most restr_factor, which keeps the problem well posed (otherwise a cluster could collapse on a few points) and controls how different the cluster shapes may be; restr_factor=1 with equal_weights=True gives trimmed k-means (Cuesta-Albertos, Gordaliza & Matrán 1997), with spherical clusters of equal size. The restriction is applied by the optimal truncation of Fritz, García-Escudero & Mayo-Iscar (2013).

The search follows R’s tclust: n_init random starts (each cluster from p + 1 random observations) improved by 3 concentration steps, then the best 5 by up to max_iter steps each; a step assigns and trims the observations and re-estimates the clusters. It finds a local maximum; more starts make the global one more likely.

Parameters:
  • n_clusters (int, default 2)

  • alpha (float in [0, 1), default 0.05) – Fraction of observations trimmed.

  • restr_factor (float >= 1, default 12.0) – Largest allowed ratio between eigenvalues of the covariance matrices.

  • equal_weights (bool, default False) – Clusters of equal size (weights 1 / n_clusters).

  • n_init (int, default 500) – Random starts.

  • max_iter (int, default 20) – Concentration steps for each of the best starts.

  • random_state (int, numpy.random.Generator, numpy.random.RandomState or None)

labels_

Cluster of each observation, -1 for trimmed ones.

Type:

ndarray of shape (n_samples,)

means_
Type:

ndarray of shape (n_clusters, n_features)

covariances_

Restricted covariance matrices.

Type:

ndarray of shape (n_clusters, n_features, n_features)

weights_

Fitted cluster proportions, or equal weights. At the iteration cap, these are the weights used for the last assignment.

Type:

ndarray of shape (n_clusters,)

objective_

Trimmed classification log-likelihood of the solution.

Type:

float

threshold_

Smallest log(w_j phi(x; mu_j, Sigma_j)) of a retained observation in its cluster; predict trims observations below it (up to rounding).

Type:

float

n_iter_

Concentration steps of the selected solution after its start.

Type:

int

converged_

Whether the selected solution reached a stable assignment.

Type:

bool

References

García-Escudero, L. A., Gordaliza, A., Matrán, C. and Mayo-Iscar, A. (2008). A general trimming approach to robust cluster analysis. The Annals of Statistics, 36(3), 1324-1345.

Fritz, H., García-Escudero, L. A. and Mayo-Iscar, A. (2012). tclust: An R package for a trimming approach to cluster analysis. Journal of Statistical Software, 47(12), 1-26.

Fritz, H., García-Escudero, L. A. and Mayo-Iscar, A. (2013). A fast algorithm for robust constrained clustering. Computational Statistics & Data Analysis, 61, 124-136.

Cuesta-Albertos, J. A., Gordaliza, A. and Matrán, C. (1997). Trimmed k-means: an attempt to robustify quantizers. The Annals of Statistics, 25(2), 553-576.

Examples

>>> import numpy as np
>>> from robustmodels.cluster import TClust
>>> rng = np.random.default_rng(0)
>>> X = np.vstack([rng.normal(0, 1, (60, 2)), rng.normal(6, 1, (60, 2))])
>>> X[:6] = rng.uniform(-20, 20, (6, 2))  # scattered noise
>>> fit = TClust(n_clusters=2, alpha=0.05, random_state=0).fit(X)
>>> np.flatnonzero(fit.labels_ == -1).tolist()  # point 0 fell near a cluster
[1, 2, 3, 4, 5, 109]
>>> (fit.means_.round(1) + 0.0).tolist()
[[5.7, 6.0], [0.0, 0.2]]
fit(X, y=None)[source]

Fit to X of shape (n_samples, n_features); y is ignored. Returns self.

predict(X)[source]

Cluster of each row of X; -1 below the training threshold_.