({{, (RefLink[ClusteringComponents, paclet:ref/ClusteringComponents])[array]
gives an array in which each element at the lowest level of array is replaced by an integer index representing the cluster in which the element lies.}, {, (RefLink[ClusteringComponents, paclet:ref/ClusteringComponents])[array,n]
finds at most n clusters.}, {, (RefLink[ClusteringComponents, paclet:ref/ClusteringComponents])[array,n,level]
finds clusters at the specified level in array.}, {, (RefLink[ClusteringComponents, paclet:ref/ClusteringComponents])[image]
finds clusters of pixels with similar values in image.}, {, (RefLink[ClusteringComponents, paclet:ref/ClusteringComponents])[image,n]
finds at most n clusters in image.}})

OpenersNotesSection(Spacer1)Details and Options

(RefLink[ClusteringComponents, paclet:ref/ClusteringComponents]) works for a variety of data types, including numerical, textual, and image, as well as dates and times.

The following options can be given:

By default, (RefLink[ClusteringComponents, paclet:ref/ClusteringComponents]) will preprocess the data automatically unless a (RefLink[DistanceFunction, paclet:ref/DistanceFunction]) is specified.

The setting for (RefLink[DistanceFunction, paclet:ref/DistanceFunction]) can be any distance or dissimilarity function, or a function f defining a distance between two values.

Possible settings for (RefLink[PerformanceGoal, paclet:ref/PerformanceGoal]) include:

Possible settings for (RefLink[Method, paclet:ref/Method]) include:

The methods "KMeans" and "KMedoids" can only be used when the number of clusters is specified.

Possible settings for (RefLink[CriterionFunction, paclet:ref/CriterionFunction]) include:

Possible settings for (RefLink[RandomSeeding, paclet:ref/RandomSeeding]) include:

OpenersPrimaryExamplesSection(Spacer1)Examples  (32)

OpenersExampleSection0(Spacer1)Basic Examples  (3)

Label two clusters of values in a list:

ClusteringComponents[{1,2,3,7,8}, 2]

Label a vector of strings:

ClusteringComponents[{"a", "aa", "aab", "aabb", "abbc", "abcc", "abccd"}]

Cluster analysis of an MR image:

ClusteringComponents[,7]//Colorize

OpenersExampleSection1(Spacer1)Scope  (10)

Clusters of values in a matrix:

ClusteringComponents[(({{1, 2, 2, 2, 1}, {1, 1, 1, 5, 5}, {1, 1, 5, 5, 5}, {1, 1, 5, 5, 6}, {1, 1, 4, 5, 6}}))] // MatrixForm

Find color clusters in an image:

ClusteringComponents[,5] // Colorize

Find clusters in a 3D image:

i=ExampleData[{"TestImage3D","MRknee"}]

seg=ClusteringComponents[i,3];
Image3D[Colorize[seg],ClipPlanes->{{-1,1,0,12}}]

Clustering transform of nested lists:

ClusteringComponents[{{1,2},3,{10,11},{12,{13}},14},2]

Find clusters at list level 2:

ClusteringComponents[{{1,2},{3,4},{10,11},{12,13}},2,2]

Find clusters at list level 1:

ClusteringComponents[{{1,2},{3,4},{10,11},{12,13}},2,1]

Find duplicates by specifying a large number of clusters:

ClusteringComponents[{1,2,2,7,7,8},100]

Labeling clusters in a matrix:

ClusteringComponents[(({{1, 1, 7, 7}, {1, 2, 6, 6}, {1, 6, 5, 5}, {0, 7, 5, 5}})),2]//Colorize

Clustering lists of Booleans:

ClusteringComponents[{{True,False,True},{False,False,True},{False,True,False}},2,1]

Clustering a list of Boolean vectors:

tfdata=RandomChoice[{True,False},{20,3}]

c = ClusteringComponents[tfdata, Automatic, 1]

OpenersExampleSection2(Spacer1)Options  (13)

OpenersExampleSubsection0(Spacer1)CriterionFunction  (1)

Generate some separated data and visualize it:

circle[r_, theta_] := {r Sin[theta], r Cos[theta]};
points =RandomVariate[MixtureDistribution[{1,1}, {UniformDistribution[{{3/2, 2}, {0,  2 Pi}}], UniformDistribution[{{0, 1/2}, {0,  2 Pi}}]}],  1000];
data = circle@@@points;
ListPlot[data, PlotRange->All]

Find a cluster assignment with exactly two clusters using different settings for (RefLink[CriterionFunction, paclet:ref/CriterionFunction]):

assignment1 = ClusteringComponents[data, 2, 1];

assignment2 = ClusteringComponents[data, 2, 1, CriterionFunction->"CalinskiHarabasz"];

Compare the two clusterings of the data:

cCluster1=Pick[data,assignment1,1];
cCluster2=Pick[data,assignment1,2];
ListPlot[{cCluster1,cCluster2}]

dCluster1=Pick[data,assignment2,1];
dCluster2=Pick[data,assignment2,2];
ListPlot[{dCluster1,dCluster2}]

OpenersExampleSubsection1(Spacer1)DistanceFunction  (1)

By default, (RefLink[EditDistance, paclet:ref/EditDistance]) is used to cluster a list of strings:

sdata={"GCTAT","TAGGA","GAATT","CATCT","TCAGG","GGGGA","TTACG","GTCAG","TGGAG","GAAAA","ATAGG","TCCGA","TAACT","GTGAT","AAGAA","CCGTA","GCTAA","GCTGG","GAGGG","CTCAT"};

ClusteringComponents[sdata, 2]

Use (RefLink[HammingDistance, paclet:ref/HammingDistance]) to cluster based on the number of characters that disagree:

ClusteringComponents[sdata,2,DistanceFunction->HammingDistance]

OpenersExampleSubsection2(Spacer1)FeatureExtractor  (1)

Find clustering components for a list of images:

flowers={,,,,,,,,,,,,,,,,,,};

ClusteringComponents[flowers,3, 1]

Create a custom (RefLink[FeatureExtractor, paclet:ref/FeatureExtractor]) to extract features:

fe=FeatureExtraction[flowers,(DominantColors[#, 2]&)]

Look at the resulting features:

extractedfeatures = fe[flowers]

Use the (RefLink[FeatureExtractor, paclet:ref/FeatureExtractor]) to find new clustering components:

cnew = ClusteringComponents[flowers,3, 1,FeatureExtractor->fe]

Look at the new clustering:

GroupBy[Transpose[{extractedfeatures, flowers, cnew}], Last->Most]

OpenersExampleSubsection3(Spacer1)FeatureNames  (1)

Use (RefLink[FeatureNames, paclet:ref/FeatureNames]) to name features, and refer to their names in further specifications:

c = ClusteringComponents[{{2.3,"male"},{4.8,"male"},{9,"female"},{5.2,"female"}, {1,"male"}, {10,"male"}, {5,"female"}}, Automatic, 1,FeatureNames->{"age","gender"}, FeatureTypes-><|"age"->"Numerical", "gender"->"Nominal"|>]

OpenersExampleSubsection4(Spacer1)FeatureTypes  (1)

Use (RefLink[FeatureTypes, paclet:ref/FeatureTypes]) to enforce the interpretation of the features:

ClusteringComponents[{{2.3,"male"},{4.8,"male"},{9,"female"},{5.2,"female"}, {1,"male"}, {10,"male"}, {5,"female"}}, Automatic, 1,FeatureTypes->{"Numerical", "Nominal"}]

Compare it to the result obtained by assuming nominal features:

ClusteringComponents[{{2.3,"male"},{4.8,"male"},{9,"female"},{5.2,"female"}, {1,"male"}, {10,"male"}, {5,"female"}}, Automatic, 1,FeatureTypes->{"Nominal", "Nominal"}]

OpenersExampleSubsection5(Spacer1)Method  (5)

Generate normally distributed data and visualize its histogram:

Dis=MixtureDistribution[{1,1,1, 1},{
NormalDistribution[1,1],
NormalDistribution[-5,1],
NormalDistribution[10,1], NormalDistribution[20,1]}];
data=RandomVariate[Dis,500];
Histogram[data, {-7, 25, 0.3}]

Find cluster assignments for this data using the "GaussianMixture" method:

assignment = ClusteringComponents[data, Method->"GaussianMixture"];

Visualize the corresponding clustering:

clustering = Pick[data, assignment, #]&/@DeleteDuplicates[assignment];
Histogram[clustering,  {-7, 25, 0.3}]

Find cluster assignments for a list of string using the k-medoids method:

strings = DictionaryLookup["gi"~~__];

assignment = ClusteringComponents[strings, 4, Method->"KMedoids"];

Look at the resulting clustering:

GatherBy[Transpose[{strings, assignment}], Last][[All, All, 1]]

Find color clusters in an image using different methods:

animals = ;

Table[Colorize[ClusteringComponents[animals,  Method->method]], {method, {"GaussianMixture", "NeighborhoodContraction", "DBSCAN", "MeanShift", "Spectral", "JarvisPatrick"}}]

Find color clusters in an image using the "NeighborhoodContraction" method and its suboption:

house =;

Table[Colorize[ClusteringComponents[house,  Method->{"NeighborhoodContraction", "NeighborhoodRadius"->t}]], {t, {0.3, 0.1, 0.05}}]

Find color clusters in an image using the "Spectral" method and its suboption:

flower = ;

ClusteringComponents[flower,  Method->"Spectral"]//Colorize

Multicolumn[Table[Colorize[ClusteringComponents[flower,  Method->{"Spectral", "NeighborhoodRadius"->t}]], {t, {0.3, 0.2, 0.1, 0.08}}], 2,Frame->All]

OpenersExampleSubsection6(Spacer1)PerformanceGoal  (1)

Generate 500 random numerical vectors of length 1000:

vectors=RandomReal[{10,11},{5000,5}];

Compute their clustering and benchmark the operation:

AbsoluteTiming[ ClusteringComponents[vectors, Automatic, 1];]

Perform the same operation with (RefLink[PerformanceGoal, paclet:ref/PerformanceGoal]) set to "Speed":

AbsoluteTiming[ClusteringComponents[vectors, Automatic, 1, PerformanceGoal->"Speed"];]

OpenersExampleSubsection7(Spacer1)RandomSeeding  (1)

Generate 500 random numerical vectors in 2 dimensions:

vectors=RandomReal[{10,11},{500,2}];

Compute their clustering several times and compare the results:

clusterings = Table[ ClusteringComponents[vectors, Automatic, 1], 5];

SameQ@@clusterings

Compute their clustering several times by changing the (RefLink[RandomSeeding, paclet:ref/RandomSeeding]) option and compare the results:

randomclusterings = Table[ ClusteringComponents[vectors, Automatic, 1, RandomSeeding->RandomInteger[10]], 5];

SameQ@@randomclusterings

OpenersExampleSubsection8(Spacer1)Weights  (1)

Obtain cluster assignment for some numerical data:

data = {1, 1.1, 1.3, 5.6, 5.7, 5.65, 6.5};

ClusteringComponents[data]

Look at the cluster assignment when changing the weight given to each number:

ClusteringComponents[data, Weights->{1,1,1,1,1,1,0.2}]

OpenersExampleSection3(Spacer1)Applications  (2)

Color segmentation of a microscopic image, after smoothing with a Perona–Malik filter:

ClusteringComponents[PeronaMalikFilter[,5,0.05],6] // Colorize

Binary segmentation of an image:

(segs=ClusteringComponents[,2])//Colorize

Image[segs-1,"Bit"]

OpenersExampleSection4(Spacer1)Properties & Relations  (3)

(RefLink[ClusteringComponents, paclet:ref/ClusteringComponents]) gives an array of cluster indices while (RefLink[FindClusters, paclet:ref/FindClusters]) returns the list of clusters:

ClusteringComponents[{10,4,5,6,11}, 2]

FindClusters[{10,4,5,6,11}, 2]

Convert the result of (RefLink[ClusteringComponents, paclet:ref/ClusteringComponents]) to partitions of similar elements:

list={10,4,5,6,11};
components=ClusteringComponents[list]

Map[First,GatherBy[Transpose[{list,components}],Last],{2}]

(RefLink[FindClusters, paclet:ref/FindClusters]) yields the same result:

FindClusters[list]

Convert the result of (RefLink[FindClusters, paclet:ref/FindClusters]) to a list of cluster indices:

list={10,4,5,6,11};
f=FindClusters[list,2]

list/.Flatten[MapIndexed[(#1->#2[[1]])&,f,{2}]]

(RefLink[ClusteringComponents, paclet:ref/ClusteringComponents]) yields the same result:

ClusteringComponents[list]

OpenersExampleSection5(Spacer1)Possible Issues  (1)

The "KMeans" method cannot be used when the mean of a subset of the input does not belong to the input space:

ClusteringComponents[{{False,False,False},{True,True,False},{False,False,False},{True,True,False},{True,False,False},{True,False,False},{True,False,False}}, 2,1,DistanceFunction->(Abs[Length[#1]-Length[#2]]&),Method->"KMeans"]

({{DocumentationFooterIconsRelatedFunction.png, ({{See Also}, {(RefLink[ArrayComponents, paclet:ref/ArrayComponents])  ▪  (RefLink[FindClusters, paclet:ref/FindClusters])  ▪  (RefLink[MorphologicalComponents, paclet:ref/MorphologicalComponents])  ▪  (RefLink[WatershedComponents, paclet:ref/WatershedComponents])  ▪  (RefLink[ClusteringTree, paclet:ref/ClusteringTree])}})}})

({{DocumentationFooterIconsRelatedGuide.png, ({{Related Guides}, {▪(RefLinkPlain[Segmentation Analysis, paclet:guide/SegmentationAnalysis])}, {▪(RefLinkPlain[Cluster Analysis, paclet:guide/ClusterAnalysis])}, {▪(RefLinkPlain[Image Computation for Microscopy, paclet:guide/ImageComputationForMicroscopy])}, {▪(RefLinkPlain[Computer Vision, paclet:guide/ComputerVision])}, {▪(RefLinkPlain[3D Images, paclet:guide/3DImages])}, {▪(RefLinkPlain[Scientific Data Analysis, paclet:guide/ScientificDataAnalysis])}, {▪(RefLinkPlain[Machine Learning, paclet:guide/MachineLearning])}, {▪(RefLinkPlain[Computational Photography, paclet:guide/ComputationalPhotography])}, {▪(RefLinkPlain[Text Analysis, paclet:guide/TextAnalysis])}})}})