2.3. Clustering

Clustering ofunlabeled data can be performed with the module sklearn.cluster.

Each clustering algorithm comes in two variants: a class, that implementsthe fit method to learn the clusters on train data, and a function,that, given train data, returns an array of integer labels correspondingto the different clusters. For the class, the labels over the trainingdata can be found in the labels_ attribute.

Input data

One important thing to note is that the algorithms implemented inthis module can take different kinds of matrix as input. All themethods accept standard data matrices of shape [n_samples, n_features].These can be obtained from the classes in the sklearn.feature_extractionmodule. For AffinityPropagation, SpectralClusteringand DBSCAN one can also input similarity matrices of shape[n_samples, n_samples]. These can be obtained from the functionsin the sklearn.metrics.pairwise module.

2.3.1. Overview of clustering methods

../_images/sphx_glr_plot_cluster_comparison_0011.pngA comparison of the clustering algorithms in scikit-learn

Method nameParametersScalabilityUsecaseGeometry (metric used)
K-Meansnumber of clustersVery large n_samples, medium n_clusters withMiniBatch codeGeneral-purpose, even cluster size, flat geometry, not too many clustersDistances between points
Affinity propagationdamping, sample preferenceNot scalable with n_samplesMany clusters, uneven cluster size, non-flat geometryGraph distance (e.g. nearest-neighbor graph)
Mean-shiftbandwidthNot scalable with n_samplesMany clusters, uneven cluster size, non-flat geometryDistances between points
Spectral clusteringnumber of clustersMedium n_samples, small n_clustersFew clusters, even cluster size, non-flat geometryGraph distance (e.g. nearest-neighbor graph)
Ward hierarchical clusteringnumber of clusters or distance thresholdLarge n_samples and n_clustersMany clusters, possibly connectivity constraintsDistances between points
Agglomerative clusteringnumber of clusters or distance threshold, linkage type, distanceLarge n_samples and n_clustersMany clusters, possibly connectivity constraints, non EuclideandistancesAny pairwise distance
DBSCANneighborhood sizeVery large n_samples, medium n_clustersNon-flat geometry, uneven cluster sizesDistances between nearest points
OPTICSminimum cluster membershipVery large n_samples, large n_clustersNon-flat geometry, uneven cluster sizes, variable cluster densityDistances between points
Gaussian mixturesmanyNot scalableFlat geometry, good for density estimationMahalanobis distances to centers
Birchbranching factor, threshold, optional global clusterer.Large n_clusters and n_samplesLarge dataset, outlier removal, data reduction.Euclidean distance between points

Non-flat geometry clustering is useful when the clusters have a specificshape, i.e. a non-flat manifold, and the standard euclidean distance isnot the right metric. This case arises in the two top rows of the figureabove.

Gaussian mixture models, useful for clustering, are described inanother chapter of the documentation dedicated tomixture models. KMeans can be seen as a special case of Gaussian mixturemodel with equal covariance per component.

2.3.2. K-means

The KMeans algorithm clusters data by trying to separate samples in ngroups of equal variance, minimizing a criterion known as the inertia orwithin-cluster sum-of-squares (see below). This algorithm requires the numberof clusters to be specified. It scales well to large number of samples and hasbeen used across a large range of application areas in many different fields.

The k-means algorithm divides a set of

2.3. Clustering - 图2 samples2.3. Clustering - 图3 into2.3. Clustering - 图4 disjoint clusters2.3. Clustering - 图5, each described by the mean2.3. Clustering - 图6of the samples in the cluster. The means are commonly called the cluster“centroids”; note that they are not, in general, points from2.3. Clustering - 图7,although they live in the same space.

The K-means algorithm aims to choose centroids that minimise the inertia,or within-cluster sum-of-squares criterion:

2.3. Clustering - 图8

Inertia can be recognized as a measure of how internally coherent clusters are.It suffers from various drawbacks:

  • Inertia makes the assumption that clusters are convex and isotropic,which is not always the case. It responds poorly to elongated clusters,or manifolds with irregular shapes.

  • Inertia is not a normalized metric: we just know that lower values arebetter and zero is optimal. But in very high-dimensional spaces, Euclideandistances tend to become inflated(this is an instance of the so-called “curse of dimensionality”).Running a dimensionality reduction algorithm such as Principal component analysis (PCA) prior tok-means clustering can alleviate this problem and speed up thecomputations.

../_images/sphx_glr_plot_kmeans_assumptions_0011.pngK-means is often referred to as Lloyd’s algorithm. In basic terms, thealgorithm has three steps. The first step chooses the initial centroids, withthe most basic method being to choose

2.3. Clustering - 图10 samples from the dataset2.3. Clustering - 图11. After initialization, K-means consists of looping between thetwo other steps. The first step assigns each sample to its nearest centroid.The second step creates new centroids by taking the mean value of all of thesamples assigned to each previous centroid. The difference between the oldand the new centroids are computed and the algorithm repeats these last twosteps until this value is less than a threshold. In other words, it repeatsuntil the centroids do not move significantly.

../_images/sphx_glr_plot_kmeans_digits_0011.pngK-means is equivalent to the expectation-maximization algorithmwith a small, all-equal, diagonal covariance matrix.

The algorithm can also be understood through the concept of Voronoi diagrams. First the Voronoi diagram ofthe points is calculated using the current centroids. Each segment in theVoronoi diagram becomes a separate cluster. Secondly, the centroids are updatedto the mean of each segment. The algorithm then repeats this until a stoppingcriterion is fulfilled. Usually, the algorithm stops when the relative decreasein the objective function between iterations is less than the given tolerancevalue. This is not the case in this implementation: iteration stops whencentroids move less than the tolerance.

Given enough time, K-means will always converge, however this may be to a localminimum. This is highly dependent on the initialization of the centroids.As a result, the computation is often done several times, with differentinitializations of the centroids. One method to help address this issue is thek-means++ initialization scheme, which has been implemented in scikit-learn(use the init='k-means++' parameter). This initializes the centroids to be(generally) distant from each other, leading to provably better results thanrandom initialization, as shown in the reference.

The algorithm supports sample weights, which can be given by a parametersample_weight. This allows to assign more weight to some samples whencomputing cluster centers and values of inertia. For example, assigning aweight of 2 to a sample is equivalent to adding a duplicate of that sampleto the dataset

2.3. Clustering - 图13.

A parameter can be given to allow K-means to be run in parallel, calledn_jobs. Giving this parameter a positive value uses that many processors(default: 1). A value of -1 uses all available processors, with -2 using oneless, and so on. Parallelization generally speeds up computation at the cost ofmemory (in this case, multiple copies of centroids need to be stored, one foreach job).

Warning

The parallel version of K-Means is broken on OS X when numpy uses theAccelerate Framework. This is expected behavior: Accelerate can be calledafter a fork but you need to execv the subprocess with the Python binary(which multiprocessing does not do under posix).

K-means can be used for vector quantization. This is achieved using thetransform method of a trained model of KMeans.

Examples:

References:

2.3.2.1. Mini Batch K-Means

The MiniBatchKMeans is a variant of the KMeans algorithmwhich uses mini-batches to reduce the computation time, while still attemptingto optimise the same objective function. Mini-batches are subsets of the inputdata, randomly sampled in each training iteration. These mini-batchesdrastically reduce the amount of computation required to converge to a localsolution. In contrast to other algorithms that reduce the convergence time ofk-means, mini-batch k-means produces results that are generally only slightlyworse than the standard algorithm.

The algorithm iterates between two major steps, similar to vanilla k-means.In the first step,

2.3. Clustering - 图14 samples are drawn randomly from the dataset, to forma mini-batch. These are then assigned to the nearest centroid. In the secondstep, the centroids are updated. In contrast to k-means, this is done on aper-sample basis. For each sample in the mini-batch, the assigned centroidis updated by taking the streaming average of the sample and all previoussamples assigned to that centroid. This has the effect of decreasing therate of change for a centroid over time. These steps are performed untilconvergence or a predetermined number of iterations is reached.

MiniBatchKMeans converges faster than KMeans, but the qualityof the results is reduced. In practice this difference in quality can be quitesmall, as shown in the example and cited reference.

../_images/sphx_glr_plot_mini_batch_kmeans_0011.png

Examples:

References:

2.3.3. Affinity Propagation

AffinityPropagation creates clusters by sending messages betweenpairs of samples until convergence. A dataset is then described using a smallnumber of exemplars, which are identified as those most representative of othersamples. The messages sent between pairs represent the suitability for onesample to be the exemplar of the other, which is updated in response to thevalues from other pairs. This updating happens iteratively until convergence,at which point the final exemplars are chosen, and hence the final clusteringis given.

../_images/sphx_glr_plot_affinity_propagation_0011.png

Affinity Propagation can be interesting as it chooses the number ofclusters based on the data provided. For this purpose, the two importantparameters are the preference, which controls how many exemplars areused, and the damping factor which damps the responsibility andavailability messages to avoid numerical oscillations when updating thesemessages.

The main drawback of Affinity Propagation is its complexity. Thealgorithm has a time complexity of the order

2.3. Clustering - 图17, where2.3. Clustering - 图18is the number of samples and2.3. Clustering - 图19 is the number of iterations untilconvergence. Further, the memory complexity is of the order2.3. Clustering - 图20 if a dense similarity matrix is used, but reducible if asparse similarity matrix is used. This makes Affinity Propagation mostappropriate for small to medium sized datasets.

Examples:

Algorithm description:The messages sent between points belong to one of two categories. The first isthe responsibility

2.3. Clustering - 图21,which is the accumulated evidence that sample2.3. Clustering - 图22should be the exemplar for sample2.3. Clustering - 图23.The second is the availability2.3. Clustering - 图24which is the accumulated evidence that sample2.3. Clustering - 图25should choose sample2.3. Clustering - 图26 to be its exemplar,and considers the values for all other samples that2.3. Clustering - 图27 shouldbe an exemplar. In this way, exemplars are chosen by samples if they are (1)similar enough to many samples and (2) chosen by many samples to berepresentative of themselves.

More formally, the responsibility of a sample

2.3. Clustering - 图28to be the exemplar of sample2.3. Clustering - 图29 is given by:

2.3. Clustering - 图30

Where

2.3. Clustering - 图31 is the similarity between samples2.3. Clustering - 图32 and2.3. Clustering - 图33.The availability of sample2.3. Clustering - 图34to be the exemplar of sample2.3. Clustering - 图35 is given by:

2.3. Clustering - 图36

To begin with, all values for

2.3. Clustering - 图37 and2.3. Clustering - 图38 are set to zero,and the calculation of each iterates until convergence.As discussed above, in order to avoid numerical oscillations when updating themessages, the damping factor2.3. Clustering - 图39 is introduced to iteration process:

2.3. Clustering - 图40

2.3. Clustering - 图41

where

2.3. Clustering - 图42 indicates the iteration times.

2.3.4. Mean Shift

MeanShift clustering aims to discover blobs in a smooth density ofsamples. It is a centroid based algorithm, which works by updating candidatesfor centroids to be the mean of the points within a given region. Thesecandidates are then filtered in a post-processing stage to eliminatenear-duplicates to form the final set of centroids.

Given a candidate centroid

2.3. Clustering - 图43 for iteration2.3. Clustering - 图44, the candidateis updated according to the following equation:

2.3. Clustering - 图45

Where

2.3. Clustering - 图46 is the neighborhood of samples within a given distancearound2.3. Clustering - 图47 and2.3. Clustering - 图48 is the mean shift vector that is computed for eachcentroid that points towards a region of the maximum increase in the density of points.This is computed using the following equation, effectively updating a centroidto be the mean of the samples within its neighborhood:

2.3. Clustering - 图49

The algorithm automatically sets the number of clusters, instead of relying on aparameter bandwidth, which dictates the size of the region to search through.This parameter can be set manually, but can be estimated using the providedestimate_bandwidth function, which is called if the bandwidth is not set.

The algorithm is not highly scalable, as it requires multiple nearest neighborsearches during the execution of the algorithm. The algorithm is guaranteed toconverge, however the algorithm will stop iterating when the change in centroidsis small.

Labelling a new sample is performed by finding the nearest centroid for agiven sample.

../_images/sphx_glr_plot_mean_shift_0011.png

Examples:

References:

2.3.5. Spectral clustering

SpectralClustering performs a low-dimension embedding of theaffinity matrix between samples, followed by clustering, e.g., by KMeans,of the components of the eigenvectors in the low dimensional space.It is especially computationally efficient if the affinity matrix is sparseand the amg solver is used for the eigenvalue problem (Note, the amg solverrequires that the pyamg module is installed.)

The present version of SpectralClustering requires the number of clustersto be specified in advance. It works well for a small number of clusters,but is not advised for many clusters.

For two clusters, SpectralClustering solves a convex relaxation of thenormalised cutsproblem on the similarity graph: cutting the graph in two so that the weight ofthe edges cut is small compared to the weights of the edges inside eachcluster. This criteria is especially interesting when working on images, wheregraph vertices are pixels, and weights of the edges of the similarity graph arecomputed using a function of a gradient of the image.

noisy_imgsegmented_img

Warning

Transforming distance to well-behaved similarities

Note that if the values of your similarity matrix are not welldistributed, e.g. with negative values or with a distance matrixrather than a similarity, the spectral problem will be singular andthe problem not solvable. In which case it is advised to apply atransformation to the entries of the matrix. For instance, in thecase of a signed distance matrix, is common to apply a heat kernel:

  1. similarity = np.exp(-beta * distance / distance.std())

See the examples for such an application.

Examples:

2.3.5.1. Different label assignment strategies

Different label assignment strategies can be used, corresponding to theassign_labels parameter of SpectralClustering."kmeans" strategy can match finer details, but can be unstable.In particular, unless you control the random_state, it may not bereproducible from run-to-run, as it depends on random initialization.The alternative "discretize" strategy is 100% reproducible, but tendsto create parcels of fairly even and geometrical shape.

assign_labels="kmeans"assign_labels="discretize"
coin_kmeanscoin_discretize

2.3.5.2. Spectral Clustering Graphs

Spectral Clustering can also be used to partition graphs via their spectralembeddings. In this case, the affinity matrix is the adjacency matrix of thegraph, and SpectralClustering is initialized with affinity='precomputed':

>>>

  1. >>> from sklearn.cluster import SpectralClustering
  2. >>> sc = SpectralClustering(3, affinity='precomputed', n_init=100,
  3. ... assign_labels='discretize')
  4. >>> sc.fit_predict(adjacency_matrix)

References:

2.3.6. Hierarchical clustering

Hierarchical clustering is a general family of clustering algorithms thatbuild nested clusters by merging or splitting them successively. Thishierarchy of clusters is represented as a tree (or dendrogram). The root of thetree is the unique cluster that gathers all the samples, the leaves being theclusters with only one sample. See the Wikipedia page for more details.

The AgglomerativeClustering object performs a hierarchical clusteringusing a bottom up approach: each observation starts in its own cluster, andclusters are successively merged together. The linkage criteria determines themetric used for the merge strategy:

  • Ward minimizes the sum of squared differences within all clusters. It is avariance-minimizing approach and in this sense is similar to the k-meansobjective function but tackled with an agglomerative hierarchicalapproach.

  • Maximum or complete linkage minimizes the maximum distance betweenobservations of pairs of clusters.

  • Average linkage minimizes the average of the distances between allobservations of pairs of clusters.

  • Single linkage minimizes the distance between the closestobservations of pairs of clusters.

AgglomerativeClustering can also scale to large number of sampleswhen it is used jointly with a connectivity matrix, but is computationallyexpensive when no connectivity constraints are added between samples: itconsiders at each step all the possible merges.

FeatureAgglomeration

The FeatureAgglomeration uses agglomerative clustering togroup together features that look very similar, thus decreasing thenumber of features. It is a dimensionality reduction tool, seeUnsupervised dimensionality reduction.

2.3.6.1. Different linkage type: Ward, complete, average, and single linkage

AgglomerativeClustering supports Ward, single, average, and completelinkage strategies.../_images/sphx_glr_plot_linkage_comparison_0011.pngAgglomerative cluster has a “rich get richer” behavior that leads touneven cluster sizes. In this regard, single linkage is the worststrategy, and Ward gives the most regular sizes. However, the affinity(or distance used in clustering) cannot be varied with Ward, thus for nonEuclidean metrics, average linkage is a good alternative. Single linkage,while not robust to noisy data, can be computed very efficiently and cantherefore be useful to provide hierarchical clustering of larger datasets.Single linkage can also perform well on non-globular data.

Examples:

2.3.6.2. Visualization of cluster hierarchy

It’s possible to visualize the tree representing the hierarchical merging of clustersas a dendrogram. Visual inspection can often be useful for understanding the structureof the data, though more so in the case of small sample sizes.../_images/sphx_glr_plot_agglomerative_dendrogram_0011.png

2.3.6.3. Adding connectivity constraints

An interesting aspect of AgglomerativeClustering is thatconnectivity constraints can be added to this algorithm (only adjacentclusters can be merged together), through a connectivity matrix that definesfor each sample the neighboring samples following a given structure of thedata. For instance, in the swiss-roll example below, the connectivityconstraints forbid the merging of points that are not adjacent on the swissroll, and thus avoid forming clusters that extend across overlapping folds ofthe roll.

unstructuredstructured

These constraint are useful to impose a certain local structure, but theyalso make the algorithm faster, especially when the number of the samplesis high.

The connectivity constraints are imposed via an connectivity matrix: ascipy sparse matrix that has elements only at the intersection of a rowand a column with indices of the dataset that should be connected. Thismatrix can be constructed from a-priori information: for instance, youmay wish to cluster web pages by only merging pages with a link pointingfrom one to another. It can also be learned from the data, for instanceusing sklearn.neighbors.kneighbors_graph to restrictmerging to nearest neighbors as in this example, orusing sklearn.feature_extraction.image.grid_to_graph toenable only merging of neighboring pixels on an image, as in thecoin example.

Examples:

Warning

Connectivity constraints with single, average and complete linkage

Connectivity constraints and single, complete or average linkage can enhancethe ‘rich getting richer’ aspect of agglomerative clustering,particularly so if they are built withsklearn.neighbors.kneighbors_graph. In the limit of a smallnumber of clusters, they tend to give a few macroscopically occupiedclusters and almost empty ones. (see the discussion inAgglomerative clustering with and without structure).Single linkage is the most brittle linkage option with regard to this issue.

../_images/sphx_glr_plot_agglomerative_clustering_0011.png../_images/sphx_glr_plot_agglomerative_clustering_0021.png../_images/sphx_glr_plot_agglomerative_clustering_0031.png../_images/sphx_glr_plot_agglomerative_clustering_0041.png

2.3.6.4. Varying the metric

Single, average and complete linkage can be used with a variety of distances (oraffinities), in particular Euclidean distance (l2), Manhattan distance(or Cityblock, or l1), cosine distance, or any precomputed affinitymatrix.

  • l1 distance is often good for sparse features, or sparse noise: i.e.many of the features are zero, as in text mining using occurrences ofrare words.

  • cosine distance is interesting because it is invariant to globalscalings of the signal.

The guidelines for choosing a metric is to use one that maximizes thedistance between samples in different classes, and minimizes that withineach class.../_images/sphx_glr_plot_agglomerative_clustering_metrics_0051.png../_images/sphx_glr_plot_agglomerative_clustering_metrics_0061.png../_images/sphx_glr_plot_agglomerative_clustering_metrics_0071.png

Examples:

2.3.7. DBSCAN

The DBSCAN algorithm views clusters as areas of high densityseparated by areas of low density. Due to this rather generic view, clustersfound by DBSCAN can be any shape, as opposed to k-means which assumes thatclusters are convex shaped. The central component to the DBSCAN is the conceptof core samples, which are samples that are in areas of high density. Acluster is therefore a set of core samples, each close to each other(measured by some distance measure)and a set of non-core samples that are close to a core sample (but are notthemselves core samples). There are two parameters to the algorithm,minsamples and eps,which define formally what we mean when we say _dense.Higher min_samples or lower epsindicate higher density necessary to form a cluster.

More formally, we define a core sample as being a sample in the dataset suchthat there exist minsamples other samples within a distance ofeps, which are defined as _neighbors of the core sample. This tellsus that the core sample is in a dense area of the vector space. A clusteris a set of core samples that can be built by recursively taking a coresample, finding all of its neighbors that are core samples, finding all oftheir neighbors that are core samples, and so on. A cluster also has aset of non-core samples, which are samples that are neighbors of a core samplein the cluster but are not themselves core samples. Intuitively, these samplesare on the fringes of a cluster.

Any core sample is part of a cluster, by definition. Any sample that is not acore sample, and is at least eps in distance from any core sample, isconsidered an outlier by the algorithm.

While the parameter minsamples primarily controls how tolerant thealgorithm is towards noise (on noisy and large data sets it may be desirableto increase this parameter), the parameter eps is _crucial to chooseappropriately for the data set and distance function and usually cannot beleft at the default value. It controls the local neighborhood of the points.When chosen too small, most data will not be clustered at all (and labeledas -1 for “noise”). When chosen too large, it causes close clusters tobe merged into one cluster, and eventually the entire data set to be returnedas a single cluster. Some heuristics for choosing this parameter have beendiscussed in the literature, for example based on a knee in the nearest neighbordistances plot (as discussed in the references below).

In the figure below, the color indicates cluster membership, with large circlesindicating core samples found by the algorithm. Smaller circles are non-coresamples that are still part of a cluster. Moreover, the outliers are indicatedby black points below.

dbscan_results

Examples:

Implementation

The DBSCAN algorithm is deterministic, always generating the same clusterswhen given the same data in the same order. However, the results can differ whendata is provided in a different order. First, even though the core sampleswill always be assigned to the same clusters, the labels of those clusterswill depend on the order in which those samples are encountered in the data.Second and more importantly, the clusters to which non-core samples are assignedcan differ depending on the data order. This would happen when a non-core samplehas a distance lower than eps to two core samples in different clusters. By thetriangular inequality, those two core samples must be more distant thaneps from each other, or they would be in the same cluster. The non-coresample is assigned to whichever cluster is generated first in a passthrough the data, and so the results will depend on the data ordering.

The current implementation uses ball trees and kd-treesto determine the neighborhood of points,which avoids calculating the full distance matrix(as was done in scikit-learn versions before 0.14).The possibility to use custom metrics is retained;for details, see NearestNeighbors.

Memory consumption for large sample sizes

This implementation is by default not memory efficient because it constructsa full pairwise similarity matrix in the case where kd-trees or ball-trees cannotbe used (e.g., with sparse matrices). This matrix will consume n^2 floats.A couple of mechanisms for getting around this are:

  • Use OPTICS clustering in conjunction with theextract_dbscan method. OPTICS clustering also calculates the fullpairwise matrix, but only keeps one row in memory at a time (memorycomplexity n).

  • A sparse radius neighborhood graph (where missing entries are presumed tobe out of eps) can be precomputed in a memory-efficient way and dbscancan be run over this with metric='precomputed'. Seesklearn.neighbors.NearestNeighbors.radius_neighbors_graph.

  • The dataset can be compressed, either by removing exact duplicates ifthese occur in your data, or by using BIRCH. Then you only have arelatively small number of representatives for a large number of points.You can then provide a sample_weight when fitting DBSCAN.

References:

  • “A Density-Based Algorithm for Discovering Clusters in Large Spatial Databaseswith Noise”Ester, M., H. P. Kriegel, J. Sander, and X. Xu,In Proceedings of the 2nd International Conference on Knowledge Discoveryand Data Mining, Portland, OR, AAAI Press, pp. 226–231. 1996

  • “DBSCAN revisited, revisited: why and how you should (still) use DBSCAN.Schubert, E., Sander, J., Ester, M., Kriegel, H. P., & Xu, X. (2017).In ACM Transactions on Database Systems (TODS), 42(3), 19.

2.3.8. OPTICS

The OPTICS algorithm shares many similarities with the DBSCANalgorithm, and can be considered a generalization of DBSCAN that relaxes theeps requirement from a single value to a value range. The key differencebetween DBSCAN and OPTICS is that the OPTICS algorithm builds a reachability_graph, which assigns each sample both a reachability distance, and a spotwithin the cluster ordering attribute; these two attributes are assignedwhen the model is fitted, and are used to determine cluster membership. IfOPTICS is run with the default value of _inf set for max_eps, then DBSCANstyle cluster extraction can be performed repeatedly in linear time for anygiven eps value using the cluster_optics_dbscan method. Settingmax_eps to a lower value will result in shorter run times, and can bethought of as the maximum neighborhood radius from each point to find otherpotential reachable points.

optics_results

The reachability distances generated by OPTICS allow for variable densityextraction of clusters within a single data set. As shown in the above plot,combining reachability distances and data set ordering produces a_reachability plot, where point density is represented on the Y-axis, andpoints are ordered such that nearby points are adjacent. ‘Cutting’ thereachability plot at a single value produces DBSCAN like results; all pointsabove the ‘cut’ are classified as noise, and each time that there is a breakwhen reading from left to right signifies a new cluster. The default clusterextraction with OPTICS looks at the steep slopes within the graph to findclusters, and the user can define what counts as a steep slope using theparameter xi. There are also other possibilities for analysis on the graphitself, such as generating hierarchical representations of the data throughreachability-plot dendrograms, and the hierarchy of clusters detected by thealgorithm can be accessed through the clusterhierarchy parameter. Theplot above has been color-coded so that cluster colors in planar space matchthe linear segment clusters of the reachability plot. Note that the blue andred clusters are adjacent in the reachability plot, and can be hierarchicallyrepresented as children of a larger parent cluster.

Examples:

Comparison with DBSCAN

The results from OPTICS cluster_optics_dbscan method and DBSCAN arevery similar, but not always identical; specifically, labeling of peripheryand noise points. This is in part because the first samples of each densearea processed by OPTICS have a large reachability value while being closeto other points in their area, and will thus sometimes be marked as noiserather than periphery. This affects adjacent points when they areconsidered as candidates for being marked as either periphery or noise.

Note that for any single value of eps, DBSCAN will tend to have ashorter run time than OPTICS; however, for repeated runs at varying epsvalues, a single run of OPTICS may require less cumulative runtime thanDBSCAN. It is also important to note that OPTICS’ output is close toDBSCAN’s only if eps and max_eps are close.

Computational Complexity

Spatial indexing trees are used to avoid calculating the full distancematrix, and allow for efficient memory usage on large sets of samples.Different distance metrics can be supplied via the metric keyword.

For large datasets, similar (but not identical) results can be obtained viaHDBSCAN. The HDBSCAN implementation ismultithreaded, and has better algorithmic runtime complexity than OPTICS,at the cost of worse memory scaling. For extremely large datasets thatexhaust system memory using HDBSCAN, OPTICS will maintain n (as opposedto n^2) memory scaling; however, tuning of the max_eps parameterwill likely need to be used to give a solution in a reasonable amount ofwall time.

References:

  • “OPTICS: ordering points to identify the clustering structure.”Ankerst, Mihael, Markus M. Breunig, Hans-Peter Kriegel, and Jörg Sander.In ACM Sigmod Record, vol. 28, no. 2, pp. 49-60. ACM, 1999.

2.3.9. Birch

The Birch builds a tree called the Clustering Feature Tree (CFT)for the given data. The data is essentially lossy compressed to a set ofClustering Feature nodes (CF Nodes). The CF Nodes have a number ofsubclusters called Clustering Feature subclusters (CF Subclusters)and these CF Subclusters located in the non-terminal CF Nodescan have CF Nodes as children.

The CF Subclusters hold the necessary information for clustering which preventsthe need to hold the entire input data in memory. This information includes:

  • Number of samples in a subcluster.

  • Linear Sum - A n-dimensional vector holding the sum of all samples

  • Squared Sum - Sum of the squared L2 norm of all samples.

  • Centroids - To avoid recalculation linear sum / n_samples.

  • Squared norm of the centroids.

The Birch algorithm has two parameters, the threshold and the branching factor.The branching factor limits the number of subclusters in a node and thethreshold limits the distance between the entering sample and the existingsubclusters.

This algorithm can be viewed as an instance or data reduction method,since it reduces the input data to a set of subclusters which are obtained directlyfrom the leaves of the CFT. This reduced data can be further processed by feedingit into a global clusterer. This global clusterer can be set by n_clusters.If n_clusters is set to None, the subclusters from the leaves are directlyread off, otherwise a global clustering step labels these subclusters into globalclusters (labels) and the samples are mapped to the global label of the nearest subcluster.

Algorithm description:

  • A new sample is inserted into the root of the CF Tree which is a CF Node.It is then merged with the subcluster of the root, that has the smallestradius after merging, constrained by the threshold and branching factor conditions.If the subcluster has any child node, then this is done repeatedly till it reachesa leaf. After finding the nearest subcluster in the leaf, the properties of thissubcluster and the parent subclusters are recursively updated.

  • If the radius of the subcluster obtained by merging the new sample and thenearest subcluster is greater than the square of the threshold and if thenumber of subclusters is greater than the branching factor, then a space is temporarilyallocated to this new sample. The two farthest subclusters are taken andthe subclusters are divided into two groups on the basis of the distancebetween these subclusters.

  • If this split node has a parent subcluster and there is roomfor a new subcluster, then the parent is split into two. If there is no room,then this node is again split into two and the process is continuedrecursively, till it reaches the root.

Birch or MiniBatchKMeans?

  • Birch does not scale very well to high dimensional data. As a rule of thumb ifn_features is greater than twenty, it is generally better to use MiniBatchKMeans.

  • If the number of instances of data needs to be reduced, or if one wants alarge number of subclusters either as a preprocessing step or otherwise,Birch is more useful than MiniBatchKMeans.

How to use partial_fit?

To avoid the computation of global clustering, for every call of partial_fitthe user is advised

  1. To set n_clusters=None initially

  2. Train all data by multiple calls to partial_fit.

  3. Set n_clusters to a required value usingbrc.set_params(n_clusters=n_clusters).

  4. Call partial_fit finally with no arguments, i.e. brc.partial_fit()which performs the global clustering.

../_images/sphx_glr_plot_birch_vs_minibatchkmeans_0011.png

References:

2.3.10. Clustering performance evaluation

Evaluating the performance of a clustering algorithm is not as trivial ascounting the number of errors or the precision and recall of a supervisedclassification algorithm. In particular any evaluation metric should nottake the absolute values of the cluster labels into account but ratherif this clustering define separations of the data similar to some groundtruth set of classes or satisfying some assumption such that membersbelong to the same class are more similar than members of differentclasses according to some similarity metric.

2.3.10.1. Adjusted Rand index

Given the knowledge of the ground truth class assignments labels_trueand our clustering algorithm assignments of the same sampleslabels_pred, the adjusted Rand index is a function that measuresthe similarity of the two assignments, ignoring permutations and withchance normalization:

>>>

  1. >>> from sklearn import metrics
  2. >>> labels_true = [0, 0, 0, 1, 1, 1]
  3. >>> labels_pred = [0, 0, 1, 1, 2, 2]
  4.  
  5. >>> metrics.adjusted_rand_score(labels_true, labels_pred)
  6. 0.24...

One can permute 0 and 1 in the predicted labels, rename 2 to 3, and getthe same score:

>>>

  1. >>> labels_pred = [1, 1, 0, 0, 3, 3]
  2. >>> metrics.adjusted_rand_score(labels_true, labels_pred)
  3. 0.24...

Furthermore, adjusted_rand_score is symmetric: swapping the argumentdoes not change the score. It can thus be used as a consensusmeasure:

>>>

  1. >>> metrics.adjusted_rand_score(labels_pred, labels_true)
  2. 0.24...

Perfect labeling is scored 1.0:

>>>

  1. >>> labels_pred = labels_true[:]
  2. >>> metrics.adjusted_rand_score(labels_true, labels_pred)
  3. 1.0

Bad (e.g. independent labelings) have negative or close to 0.0 scores:

>>>

  1. >>> labels_true = [0, 1, 2, 0, 3, 4, 5, 1]
  2. >>> labels_pred = [1, 1, 0, 0, 2, 2, 2, 2]
  3. >>> metrics.adjusted_rand_score(labels_true, labels_pred)
  4. -0.12...

2.3.10.1.1. Advantages

  • Random (uniform) label assignments have a ARI score close to 0.0for any value of n_clusters and n_samples (which is not thecase for raw Rand index or the V-measure for instance).

  • Bounded range [-1, 1]: negative values are bad (independentlabelings), similar clusterings have a positive ARI, 1.0 is the perfectmatch score.

  • No assumption is made on the cluster structure: can be usedto compare clustering algorithms such as k-means which assumes isotropicblob shapes with results of spectral clustering algorithms which canfind cluster with “folded” shapes.

2.3.10.1.2. Drawbacks

  • Contrary to inertia, ARI requires knowledge of the ground truthclasses while is almost never available in practice or requires manualassignment by human annotators (as in the supervised learning setting).

However ARI can also be useful in a purely unsupervised setting as abuilding block for a Consensus Index that can be used for clusteringmodel selection (TODO).

Examples:

2.3.10.1.3. Mathematical formulation

If C is a ground truth class assignment and K the clustering, let usdefine

2.3. Clustering - 图69 and2.3. Clustering - 图70 as:

2.3. Clustering - 图71, the number of pairs of elements that are in the same setin C and in the same set in K

2.3. Clustering - 图72, the number of pairs of elements that are in different setsin C and in different sets in K

The raw (unadjusted) Rand index is then given by:

2.3. Clustering - 图73

Where

2.3. Clustering - 图74 is the total number of possible pairsin the dataset (without ordering).

However the RI score does not guarantee that random label assignmentswill get a value close to zero (esp. if the number of clusters is inthe same order of magnitude as the number of samples).

To counter this effect we can discount the expected RI

2.3. Clustering - 图75 ofrandom labelings by defining the adjusted Rand index as follows:

2.3. Clustering - 图76

References

2.3.10.2. Mutual Information based scores

Given the knowledge of the ground truth class assignments labels_true andour clustering algorithm assignments of the same samples labels_pred, theMutual Information is a function that measures the agreement of the twoassignments, ignoring permutations. Two different normalized versions of thismeasure are available, Normalized Mutual Information (NMI) and AdjustedMutual Information (AMI). NMI is often used in the literature, while AMI wasproposed more recently and is normalized against chance:

>>>

  1. >>> from sklearn import metrics
  2. >>> labels_true = [0, 0, 0, 1, 1, 1]
  3. >>> labels_pred = [0, 0, 1, 1, 2, 2]
  4.  
  5. >>> metrics.adjusted_mutual_info_score(labels_true, labels_pred)
  6. 0.22504...

One can permute 0 and 1 in the predicted labels, rename 2 to 3 and getthe same score:

>>>

  1. >>> labels_pred = [1, 1, 0, 0, 3, 3]
  2. >>> metrics.adjusted_mutual_info_score(labels_true, labels_pred)
  3. 0.22504...

All, mutual_info_score, adjusted_mutual_info_score andnormalized_mutual_info_score are symmetric: swapping the argument doesnot change the score. Thus they can be used as a consensus measure:

>>>

  1. >>> metrics.adjusted_mutual_info_score(labels_pred, labels_true)
  2. 0.22504...

Perfect labeling is scored 1.0:

>>>

  1. >>> labels_pred = labels_true[:]
  2. >>> metrics.adjusted_mutual_info_score(labels_true, labels_pred)
  3. 1.0
  4.  
  5. >>> metrics.normalized_mutual_info_score(labels_true, labels_pred)
  6. 1.0

This is not true for mutual_info_score, which is therefore harder to judge:

>>>

  1. >>> metrics.mutual_info_score(labels_true, labels_pred)
  2. 0.69...

Bad (e.g. independent labelings) have non-positive scores:

>>>

  1. >>> labels_true = [0, 1, 2, 0, 3, 4, 5, 1]
  2. >>> labels_pred = [1, 1, 0, 0, 2, 2, 2, 2]
  3. >>> metrics.adjusted_mutual_info_score(labels_true, labels_pred)
  4. -0.10526...

2.3.10.2.1. Advantages

  • Random (uniform) label assignments have a AMI score close to 0.0for any value of n_clusters and n_samples (which is not thecase for raw Mutual Information or the V-measure for instance).

  • Upper bound of 1: Values close to zero indicate two labelassignments that are largely independent, while values close to oneindicate significant agreement. Further, an AMI of exactly 1 indicatesthat the two label assignments are equal (with or without permutation).

2.3.10.2.2. Drawbacks

  • Contrary to inertia, MI-based measures require the knowledgeof the ground truth classes while almost never available in practice orrequires manual assignment by human annotators (as in the supervised learningsetting).

However MI-based measures can also be useful in purely unsupervised setting as abuilding block for a Consensus Index that can be used for clusteringmodel selection.

  • NMI and MI are not adjusted against chance.

Examples:

2.3.10.2.3. Mathematical formulation

Assume two label assignments (of the same N objects),

2.3. Clustering - 图77 and2.3. Clustering - 图78.Their entropy is the amount of uncertainty for a partition set, defined by:

2.3. Clustering - 图79

where

2.3. Clustering - 图80 is the probability that an object picked atrandom from2.3. Clustering - 图81 falls into class2.3. Clustering - 图82. Likewise for2.3. Clustering - 图83:

2.3. Clustering - 图84

With

2.3. Clustering - 图85. The mutual information (MI) between2.3. Clustering - 图86and2.3. Clustering - 图87 is calculated by:

2.3. Clustering - 图88

where

2.3. Clustering - 图89 is the probability that an objectpicked at random falls into both classes2.3. Clustering - 图90 and2.3. Clustering - 图91.

It also can be expressed in set cardinality formulation:

2.3. Clustering - 图92

The normalized mutual information is defined as

2.3. Clustering - 图93

This value of the mutual information and also the normalized variant is notadjusted for chance and will tend to increase as the number of different labels(clusters) increases, regardless of the actual amount of “mutual information”between the label assignments.

The expected value for the mutual information can be calculated using thefollowing equation [VEB2009]. In this equation,

2.3. Clustering - 图94 (the number of elements in2.3. Clustering - 图95) and2.3. Clustering - 图96 (the number of elements in2.3. Clustering - 图97).

2.3. Clustering - 图98

Using the expected value, the adjusted mutual information can then becalculated using a similar form to that of the adjusted Rand index:

2.3. Clustering - 图99

For normalized mutual information and adjusted mutual information, the normalizingvalue is typically some generalized mean of the entropies of each clustering.Various generalized means exist, and no firm rules exist for preferring one over theothers. The decision is largely a field-by-field basis; for instance, in communitydetection, the arithmetic mean is most common. Eachnormalizing method provides “qualitatively similar behaviours” [YAT2016]. In ourimplementation, this is controlled by the average_method parameter.

Vinh et al. (2010) named variants of NMI and AMI by their averaging method [VEB2010]. Their‘sqrt’ and ‘sum’ averages are the geometric and arithmetic means; we use thesemore broadly common names.

References

  • VEB2009
  • Vinh, Epps, and Bailey, (2009). “Information theoretic measuresfor clusterings comparison”. Proceedings of the 26th Annual InternationalConference on Machine Learning - ICML ‘09.doi:10.1145/1553374.1553511.ISBN 9781605585161.

  • VEB2010

  • Vinh, Epps, and Bailey, (2010). “Information Theoretic Measures forClusterings Comparison: Variants, Properties, Normalization andCorrection for Chance”. JMLR<http://jmlr.csail.mit.edu/papers/volume11/vinh10a/vinh10a.pdf>

  • YAT2016

  • Yang, Algesheimer, and Tessone, (2016). “A comparative analysis ofcommunitydetection algorithms on artificial networks”. Scientific Reports 6: 30750.doi:10.1038/srep30750.

2.3.10.3. Homogeneity, completeness and V-measure

Given the knowledge of the ground truth class assignments of the samples,it is possible to define some intuitive metric using conditional entropyanalysis.

In particular Rosenberg and Hirschberg (2007) define the following twodesirable objectives for any cluster assignment:

  • homogeneity: each cluster contains only members of a single class.

  • completeness: all members of a given class are assigned to the samecluster.

We can turn those concept as scores homogeneity_score andcompleteness_score. Both are bounded below by 0.0 and above by1.0 (higher is better):

>>>

  1. >>> from sklearn import metrics
  2. >>> labels_true = [0, 0, 0, 1, 1, 1]
  3. >>> labels_pred = [0, 0, 1, 1, 2, 2]
  4.  
  5. >>> metrics.homogeneity_score(labels_true, labels_pred)
  6. 0.66...
  7.  
  8. >>> metrics.completeness_score(labels_true, labels_pred)
  9. 0.42...

Their harmonic mean called V-measure is computed byv_measure_score:

>>>

  1. >>> metrics.v_measure_score(labels_true, labels_pred)
  2. 0.51...

This function’s formula is as follows:

2.3. Clustering - 图100

beta defaults to a value of 1.0, but for using a value less than 1 for beta:

>>>

  1. >>> metrics.v_measure_score(labels_true, labels_pred, beta=0.6)
  2. 0.54...

more weight will be attributed to homogeneity, and using a value greater than 1:

>>>

  1. >>> metrics.v_measure_score(labels_true, labels_pred, beta=1.8)
  2. 0.48...

more weight will be attributed to completeness.

The V-measure is actually equivalent to the mutual information (NMI)discussed above, with the aggregation function being the arithmetic mean [B2011].

Homogeneity, completeness and V-measure can be computed at once usinghomogeneity_completeness_v_measure as follows:

>>>

  1. >>> metrics.homogeneity_completeness_v_measure(labels_true, labels_pred)
  2. (0.66..., 0.42..., 0.51...)

The following clustering assignment is slightly better, since it ishomogeneous but not complete:

>>>

  1. >>> labels_pred = [0, 0, 0, 1, 2, 2]
  2. >>> metrics.homogeneity_completeness_v_measure(labels_true, labels_pred)
  3. (1.0, 0.68..., 0.81...)

Note

v_measure_score is symmetric: it can be used to evaluatethe agreement of two independent assignments on the same dataset.

This is not the case for completeness_score andhomogeneity_score: both are bound by the relationship:

  1. homogeneity_score(a, b) == completeness_score(b, a)

2.3.10.3.1. Advantages

  • Bounded scores: 0.0 is as bad as it can be, 1.0 is a perfect score.

  • Intuitive interpretation: clustering with bad V-measure can bequalitatively analyzed in terms of homogeneity and completenessto better feel what ‘kind’ of mistakes is done by the assignment.

  • No assumption is made on the cluster structure: can be usedto compare clustering algorithms such as k-means which assumes isotropicblob shapes with results of spectral clustering algorithms which canfind cluster with “folded” shapes.

2.3.10.3.2. Drawbacks

  • The previously introduced metrics are not normalized with regards torandom labeling: this means that depending on the number of samples,clusters and ground truth classes, a completely random labeling willnot always yield the same values for homogeneity, completeness andhence v-measure. In particular random labeling won’t yield zeroscores especially when the number of clusters is large.

This problem can safely be ignored when the number of samples is morethan a thousand and the number of clusters is less than 10. Forsmaller sample sizes or larger number of clusters it is safer to usean adjusted index such as the Adjusted Rand Index (ARI).

../_images/sphx_glr_plot_adjusted_for_chance_measures_0011.png

  • These metrics require the knowledge of the ground truth classes whilealmost never available in practice or requires manual assignment byhuman annotators (as in the supervised learning setting).

Examples:

2.3.10.3.3. Mathematical formulation

Homogeneity and completeness scores are formally given by:

2.3. Clustering - 图102

2.3. Clustering - 图103

where

2.3. Clustering - 图104 is the conditional entropy of the classes giventhe cluster assignments and is given by:

2.3. Clustering - 图105

and

2.3. Clustering - 图106 is the entropy of the classes and is given by:

2.3. Clustering - 图107

with

2.3. Clustering - 图108 the total number of samples,2.3. Clustering - 图109 and2.3. Clustering - 图110the number of samples respectively belonging to class2.3. Clustering - 图111 andcluster2.3. Clustering - 图112, and finally2.3. Clustering - 图113 the number of samplesfrom class2.3. Clustering - 图114 assigned to cluster2.3. Clustering - 图115.

The conditional entropy of clusters given class

2.3. Clustering - 图116 and theentropy of clusters2.3. Clustering - 图117 are defined in a symmetric manner.

Rosenberg and Hirschberg further define V-measure as the harmonicmean of homogeneity and completeness:

2.3. Clustering - 图118

References

2.3.10.4. Fowlkes-Mallows scores

The Fowlkes-Mallows index (sklearn.metrics.fowlkes_mallows_score) can beused when the ground truth class assignments of the samples is known. TheFowlkes-Mallows score FMI is defined as the geometric mean of thepairwise precision and recall:

2.3. Clustering - 图119

Where TP is the number of True Positive (i.e. the number of pairof points that belong to the same clusters in both the true labels and thepredicted labels), FP is the number of False Positive (i.e. the numberof pair of points that belong to the same clusters in the true labels and notin the predicted labels) and FN is the number of False Negative (i.e thenumber of pair of points that belongs in the same clusters in the predictedlabels and not in the true labels).

The score ranges from 0 to 1. A high value indicates a good similaritybetween two clusters.

>>>

  1. >>> from sklearn import metrics
  2. >>> labels_true = [0, 0, 0, 1, 1, 1]
  3. >>> labels_pred = [0, 0, 1, 1, 2, 2]

>>>

  1. >>> metrics.fowlkes_mallows_score(labels_true, labels_pred)
  2. 0.47140...

One can permute 0 and 1 in the predicted labels, rename 2 to 3 and getthe same score:

>>>

  1. >>> labels_pred = [1, 1, 0, 0, 3, 3]
  2.  
  3. >>> metrics.fowlkes_mallows_score(labels_true, labels_pred)
  4. 0.47140...

Perfect labeling is scored 1.0:

>>>

  1. >>> labels_pred = labels_true[:]
  2. >>> metrics.fowlkes_mallows_score(labels_true, labels_pred)
  3. 1.0

Bad (e.g. independent labelings) have zero scores:

>>>

  1. >>> labels_true = [0, 1, 2, 0, 3, 4, 5, 1]
  2. >>> labels_pred = [1, 1, 0, 0, 2, 2, 2, 2]
  3. >>> metrics.fowlkes_mallows_score(labels_true, labels_pred)
  4. 0.0

2.3.10.4.1. Advantages

  • Random (uniform) label assignments have a FMI score close to 0.0for any value of n_clusters and n_samples (which is not thecase for raw Mutual Information or the V-measure for instance).

  • Upper-bounded at 1: Values close to zero indicate two labelassignments that are largely independent, while values close to oneindicate significant agreement. Further, values of exactly 0 indicatepurely independent label assignments and a FMI of exactly 1 indicatesthat the two label assignments are equal (with or without permutation).

  • No assumption is made on the cluster structure: can be usedto compare clustering algorithms such as k-means which assumes isotropicblob shapes with results of spectral clustering algorithms which canfind cluster with “folded” shapes.

2.3.10.4.2. Drawbacks

  • Contrary to inertia, FMI-based measures require the knowledgeof the ground truth classes while almost never available in practice orrequires manual assignment by human annotators (as in the supervised learningsetting).

References

2.3.10.5. Silhouette Coefficient

If the ground truth labels are not known, evaluation must be performed usingthe model itself. The Silhouette Coefficient(sklearn.metrics.silhouette_score)is an example of such an evaluation, where ahigher Silhouette Coefficient score relates to a model with better definedclusters. The Silhouette Coefficient is defined for each sample and is composedof two scores:

  • a: The mean distance between a sample and all other points in the sameclass.

  • b: The mean distance between a sample and all other points in the nextnearest cluster.

The Silhouette Coefficient s for a single sample is then given as:

2.3. Clustering - 图120

The Silhouette Coefficient for a set of samples is given as the mean of theSilhouette Coefficient for each sample.

>>>

  1. >>> from sklearn import metrics
  2. >>> from sklearn.metrics import pairwise_distances
  3. >>> from sklearn import datasets
  4. >>> X, y = datasets.load_iris(return_X_y=True)

In normal usage, the Silhouette Coefficient is applied to the results of acluster analysis.

>>>

  1. >>> import numpy as np
  2. >>> from sklearn.cluster import KMeans
  3. >>> kmeans_model = KMeans(n_clusters=3, random_state=1).fit(X)
  4. >>> labels = kmeans_model.labels_
  5. >>> metrics.silhouette_score(X, labels, metric='euclidean')
  6. 0.55...

References

  • Peter J. Rousseeuw (1987). “Silhouettes: a Graphical Aid to theInterpretation and Validation of Cluster Analysis”. Computationaland Applied Mathematics 20: 53–65.doi:10.1016/0377-0427(87)90125-790125-7).

2.3.10.5.1. Advantages

  • The score is bounded between -1 for incorrect clustering and +1 for highlydense clustering. Scores around zero indicate overlapping clusters.

  • The score is higher when clusters are dense and well separated, which relatesto a standard concept of a cluster.

2.3.10.5.2. Drawbacks

  • The Silhouette Coefficient is generally higher for convex clusters than otherconcepts of clusters, such as density based clusters like those obtainedthrough DBSCAN.

Examples:

2.3.10.6. Calinski-Harabasz Index

If the ground truth labels are not known, the Calinski-Harabasz index(sklearn.metrics.calinski_harabasz_score) - also known as the VarianceRatio Criterion - can be used to evaluate the model, where a higherCalinski-Harabasz score relates to a model with better defined clusters.

The index is the ratio of the sum of between-clusters dispersion and ofinter-cluster dispersion for all clusters (where dispersion is defined as thesum of distances squared):

>>>

  1. >>> from sklearn import metrics
  2. >>> from sklearn.metrics import pairwise_distances
  3. >>> from sklearn import datasets
  4. >>> X, y = datasets.load_iris(return_X_y=True)

In normal usage, the Calinski-Harabasz index is applied to the results of acluster analysis:

>>>

  1. >>> import numpy as np
  2. >>> from sklearn.cluster import KMeans
  3. >>> kmeans_model = KMeans(n_clusters=3, random_state=1).fit(X)
  4. >>> labels = kmeans_model.labels_
  5. >>> metrics.calinski_harabasz_score(X, labels)
  6. 561.62...

2.3.10.6.1. Advantages

  • The score is higher when clusters are dense and well separated, which relatesto a standard concept of a cluster.

  • The score is fast to compute.

2.3.10.6.2. Drawbacks

  • The Calinski-Harabasz index is generally higher for convex clusters than otherconcepts of clusters, such as density based clusters like those obtainedthrough DBSCAN.

2.3.10.6.3. Mathematical formulation

For a set of data

2.3. Clustering - 图121 of size2.3. Clustering - 图122 which has been clustered into2.3. Clustering - 图123 clusters, the Calinski-Harabasz score2.3. Clustering - 图124 is defined as theratio of the between-clusters dispersion mean and the within-cluster dispersion:

2.3. Clustering - 图125

where

2.3. Clustering - 图126 is trace of the between group dispersion matrixand2.3. Clustering - 图127 is the trace of the within-cluster dispersionmatrix defined by:

2.3. Clustering - 图128

2.3. Clustering - 图129

with

2.3. Clustering - 图130 the set of points in cluster2.3. Clustering - 图131,2.3. Clustering - 图132 the centerof cluster2.3. Clustering - 图133,2.3. Clustering - 图134 the center of2.3. Clustering - 图135, and2.3. Clustering - 图136 thenumber of points in cluster2.3. Clustering - 图137.

References

2.3.10.7. Davies-Bouldin Index

If the ground truth labels are not known, the Davies-Bouldin index(sklearn.metrics.davies_bouldin_score) can be used to evaluate themodel, where a lower Davies-Bouldin index relates to a model with betterseparation between the clusters.

This index signifies the average ‘similarity’ between clusters, where thesimilarity is a measure that compares the distance between clusters with thesize of the clusters themselves.

Zero is the lowest possible score. Values closer to zero indicate a betterpartition.

In normal usage, the Davies-Bouldin index is applied to the results of acluster analysis as follows:

>>>

  1. >>> from sklearn import datasets
  2. >>> iris = datasets.load_iris()
  3. >>> X = iris.data
  4. >>> from sklearn.cluster import KMeans
  5. >>> from sklearn.metrics import davies_bouldin_score
  6. >>> kmeans = KMeans(n_clusters=3, random_state=1).fit(X)
  7. >>> labels = kmeans.labels_
  8. >>> davies_bouldin_score(X, labels)
  9. 0.6619...

2.3.10.7.1. Advantages

  • The computation of Davies-Bouldin is simpler than that of Silhouette scores.

  • The index is computed only quantities and features inherent to the dataset.

2.3.10.7.2. Drawbacks

  • The Davies-Boulding index is generally higher for convex clusters than otherconcepts of clusters, such as density based clusters like those obtained fromDBSCAN.

  • The usage of centroid distance limits the distance metric to Euclidean space.

2.3.10.7.3. Mathematical formulation

The index is defined as the average similarity between each cluster

2.3. Clustering - 图138for2.3. Clustering - 图139 and its most similar one2.3. Clustering - 图140. In the context ofthis index, similarity is defined as a measure2.3. Clustering - 图141 that trades off:

2.3. Clustering - 图142, the average distance between each point of cluster2.3. Clustering - 图143 andthe centroid of that cluster – also know as cluster diameter.

2.3. Clustering - 图144, the distance between cluster centroids2.3. Clustering - 图145 and2.3. Clustering - 图146.

A simple choice to construct

2.3. Clustering - 图147 so that it is nonnegative andsymmetric is:

2.3. Clustering - 图148

Then the Davies-Bouldin index is defined as:

2.3. Clustering - 图149

References

2.3.10.8. Contingency Matrix

Contingency matrix (sklearn.metrics.cluster.contingency_matrix)reports the intersection cardinality for every true/predicted cluster pair.The contingency matrix provides sufficient statistics for all clusteringmetrics where the samples are independent and identically distributed andone doesn’t need to account for some instances not being clustered.

Here is an example:

>>>

  1. >>> from sklearn.metrics.cluster import contingency_matrix
  2. >>> x = ["a", "a", "a", "b", "b", "b"]
  3. >>> y = [0, 0, 1, 1, 2, 2]
  4. >>> contingency_matrix(x, y)
  5. array([[2, 1, 0],
  6. [0, 1, 2]])

The first row of output array indicates that there are three samples whosetrue cluster is “a”. Of them, two are in predicted cluster 0, one is in 1,and none is in 2. And the second row indicates that there are three sampleswhose true cluster is “b”. Of them, none is in predicted cluster 0, one is in1 and two are in 2.

A confusion matrix for classification is a squarecontingency matrix where the order of rows and columns correspond to a listof classes.

2.3.10.8.1. Advantages

  • Allows to examine the spread of each true cluster across predictedclusters and vice versa.

  • The contingency table calculated is typically utilized in the calculationof a similarity statistic (like the others listed in this document) betweenthe two clusterings.

2.3.10.8.2. Drawbacks

  • Contingency matrix is easy to interpret for a small number of clusters, butbecomes very hard to interpret for a large number of clusters.

  • It doesn’t give a single metric to use as an objective for clusteringoptimisation.

References