private static void clusterIteration ( Matrix matrix , int numClusters , KMeansSeed seedType , CriterionFunction criterion ) { DoubleVector [ ] centers = seedType . chooseSeeds ( numClusters , matrix ) ; // Compute the initial set of assignments for each data point based on // the initial assignments. int [ ] initialAssignments = new int [ matrix . rows ( ) ] ; // If there is to be only one cluster, then everything will be auto // assigned to the first cluster. This is just a special case that only // comes up when comparing other solutions to the non-solution. if ( numClusters != 1 ) { int nc = 0 ; for ( int i = 0 ; i < matrix . rows ( ) ; ++ i ) { DoubleVector vector = matrix . getRowVector ( i ) ; double bestSimilarity = 0 ; for ( int c = 0 ; c < numClusters ; ++ c ) { double similarity = Similarity . cosineSimilarity ( centers [ c ] , vector ) ; nc ++ ; if ( similarity >= bestSimilarity ) { bestSimilarity = similarity ; initialAssignments [ i ] = c ; } } } } // Setup the criterion function with it's meta data. criterion . setup ( matrix , initialAssignments , numClusters ) ; // Iteratively swap each data point to a better cluster if such an // assignment exists. List < Integer > indices = new ArrayList < Integer > ( matrix . rows ( ) ) ; for ( int i = 0 ; i < matrix . rows ( ) ; ++ i ) indices . ( i ) ; // Iterate through each data point in random order. For each data // point, try to assign it to a new cluster. If no data point is moved // in an iteration, end the iterations. boolean changed = true ; while ( changed ) { changed = false ; Collections . shuffle ( indices ) ; for ( int index : indices ) changed |= criterion . update ( index ) ; } }
Performs one iteration of Direct Clustering over the data set .