Clusters {@link matrix} using the {@link RandomSeed}
seeding algorithm and the specified {@link CriterionFunction}. The best
scoring solution out of {@code numRepetitions} will be returned.
175105
public static Assignments cluster(Matrix matrix,
                                      int numClusters,
                                      int numRepetitions,
                                      CriterionFunction criterion) {
        return cluster(matrix, numClusters, numRepetitions,
                       new RandomSeed(), criterion);
    }
1223736
def _score_clusters(self, X, y=None):
        
        stype = self.scoring.lower() # scoring method name

        if stype == "membership":
            return np.bincount(self.estimator.labels_)

        raise YellowbrickValueError("unknown scoring method '{}'".format(stype))
835829
public static Assignments cluster(Matrix matrix,
                                      int numClusters,
                                      int numRepetitions,
                                      KMeansSeed seedType,
                                      CriterionFunction criterion) {
        int[] bestAssignment = null;
        double bestScore = (criterion.isMaximize()) ? 0 : Double.MAX_VALUE;
        for (int i = 0; i < numRepetitions; ++i) {
            clusterIteration(matrix, numClusters, seedType, criterion);
            if (criterion.isMaximize()) {
                if (criterion.score() > bestScore) {
                    bestScore = criterion.score();
                    bestAssignment = criterion.assignments();
                }
            } else {
                if (criterion.score() < bestScore) {
                    bestScore = criterion.score();
                    bestAssignment = criterion.assignments();
                }
            }
        }

        // Convert the array of assignments to an Assignments object.
        Assignment[] assignments = new Assignment[matrix.rows()];
        for (int i = 0; i < bestAssignment.length; ++i)
            assignments[i] = new HardAssignment(bestAssignment[i]);

        return new Assignments(numClusters, assignments, matrix);
    }
634120
public static Assignments cluster(Matrix matrix,
                                      int numClusters,
                                      int numRepetitions) {
        return cluster(matrix, numClusters, numRepetitions,
                       new RandomSeed(), new I1Function());
    }
610739
def randmatrix(m, n, random_seed=None):
    """"""
    val = np.sqrt(6.0 / (m + n))
    np.random.seed(random_seed)
    return np.random.uniform(-val, val, size=(m, n))
5501
function getPointFromLargestVarianceCluster(clusters) {
    var maxVariance = -Number.MAX_VALUE;
    var selected = null;
    for (var clusterIndex = 0; clusterIndex < clusters.length; clusterIndex++) {
      var cluster = clusters[clusterIndex];

      if (cluster.getPoints().length > 0) {

        // compute the distance variance of the current cluster
        var center = cluster.getCenter();
        var points = cluster.getPoints();
        var distances = new Float32Array(points.length);
        for (var i = 0; i < points.length; i++) {
          distances[i] = distance(points[i], center);
        }
        var variance = morpheus.Variance(morpheus.VectorUtil.arrayAsVector(distances));

        // select the cluster with the largest variance
        if (variance > maxVariance) {
          maxVariance = variance;
          selected = cluster;
        }
      }
    }

    // did we find at least one non-empty cluster ?
    if (selected == null) {
      throw 'All clusters are empty';
    }

    // extract a random point from the cluster
    var selectedPoints = selected.getPoints();
    return selectedPoints.splice(nextInt(selectedPoints.length), 1);

  }
608900
@Override
  public void computeDensityEstimator(List<S> solutionList) {
    int size = solutionList.size();

    if (size == 0) {
      return;
    }

    if (size == 1) {
      solutionList.get(0).setAttribute(getAttributeIdentifier(), Double.POSITIVE_INFINITY);
      return;
    }

    if (size == 2) {
      solutionList.get(0).setAttribute(getAttributeIdentifier(), Double.POSITIVE_INFINITY);
      solutionList.get(1).setAttribute(getAttributeIdentifier(), Double.POSITIVE_INFINITY);

      return;
    }

    // Use a new SolutionSet to avoid altering the original solutionSet
    List<S> front = new ArrayList<>(size);
    for (S solution : solutionList) {
      front.add(solution);
    }

    for (int i = 0; i < size; i++) {
      front.get(i).setAttribute(getAttributeIdentifier(), 0.0);
    }

    double objetiveMaxn;
    double objetiveMinn;
    double distance;

    int numberOfObjectives = solutionList.get(0).getNumberOfObjectives() ;

    for (int i = 0; i < numberOfObjectives; i++) {
      // Sort the population by Obj n
      Collections.sort(front, new ObjectiveComparator<S>(i)) ;
      objetiveMinn = front.get(0).getObjective(i);
      objetiveMaxn = front.get(front.size() - 1).getObjective(i);

      // Set de crowding distance
      front.get(0).setAttribute(getAttributeIdentifier(), Double.POSITIVE_INFINITY);
      front.get(size - 1).setAttribute(getAttributeIdentifier(), Double.POSITIVE_INFINITY);

      for (int j = 1; j < size - 1; j++) {
        distance = front.get(j + 1).getObjective(i) - front.get(j - 1).getObjective(i);
        distance = distance / (objetiveMaxn - objetiveMinn);
        distance += (double)front.get(j).getAttribute(getAttributeIdentifier());
        front.get(j).setAttribute(getAttributeIdentifier(), distance);
      }
    }
  }
1241522
def init_random(X, n_clusters, random_state):
    """"""
    logger.info("Initializing randomly")
    idx = sorted(draw_seed(random_state, 0, len(X), size=n_clusters))
    centers = X[idx].compute()
    return centers
96025
@Override
	public void resetLearningImpl() {
		this.numClusters = this.numClustersOption.getValue();
		this.numDimensions = this.numDimensionsOption.getValue();
		this.maxNumClusterFeatures = this.maxNumClusterFeaturesOption.getValue();
		this.numProjections = this.numProjectionsOption.getValue();

		this.bufferPhase = true;
		this.buffer = new ArrayList<double[]>(
				this.maxNumClusterFeaturesOption.getValue() + 1);
		this.minDistance = Double.POSITIVE_INFINITY;
		this.pairwiseDifferent = 0;

		int hashSize = (int) Math.ceil(Math.log(
				5 * this.maxNumClusterFeaturesOption.getValue()) / Math.log(2));
		this.root = new ClusteringTreeHeadNode(null, new ClusteringFeature(
				new double[0], 1), this.numDimensionsOption.getValue(),
				this.numProjectionsOption.getValue(), Math.min(hashSize, 30),
				this.clustererRandom);
		this.rootCount = 0;
	}
448157
public static KMeansClustering setup(int clusterCount, int maxIterationCount, Distance distanceFunction,
                    boolean inverse) {
        ClusteringStrategy clusteringStrategy =
                        FixedClusterCountStrategy.setup(clusterCount, distanceFunction, inverse);
        clusteringStrategy.endWhenIterationCountEquals(maxIterationCount);
        return new KMeansClustering(clusteringStrategy);
    }
349401
public List<Set<Integer>> clusters() {
        List<Set<Integer>> clusters = new ArrayList<Set<Integer>>();
        for (int c = 0; c < numClusters; ++c)
            clusters.add(new HashSet<Integer>());
        for (int i = 0; i < assignments.length; ++i)
            for (int k : assignments[i].assignments()) {
                // Check that the item was place in a cluster
                if (k >= 0)
                    clusters.get(k).add(i);
            }
        return clusters;
    }
609005
private ClusterResult fullCluster(Matrix matrix,
                                      final int depth) {
        verbose("Clustering at depth " + depth);

        // If the matrix has only one element or the depth is equal to the
        // maximum number of desired clusters then all items are in a single
        // cluster.
        if (matrix.rows() <= 1) 
            return new ClusterResult(new int[matrix.rows()], 1);

        // Get a fresh new eigen cutter and compute the specral cut of the
        // matrix.
        EigenCut eigenCutter = cutterGenerator.generate();
        eigenCutter.computeCut(matrix);

        final Matrix leftMatrix = eigenCutter.getLeftCut();
        final Matrix rightMatrix = eigenCutter.getRightCut();

        verbose(String.format("Splitting into two matricies %d-%d",
                              leftMatrix.rows(), rightMatrix.rows()));

        // If the compute decided that the matrix should not be split, short
        // circuit any attempts to further cut the matrix.
        if (leftMatrix.rows() == matrix.rows() ||
            rightMatrix.rows() == matrix.rows())
            return new ClusterResult(new int[matrix.rows()], 1);


        // Do clustering on the left and right branches.  We can do this in
        // parallel because all of the data members in this class are thread
        // safe, since each call to fullCluster uses a new instance of a
        // EigenCutter which has all of the state for a particular partition.
        final ClusterResult[] results = new ClusterResult[2];
        results[0] = fullCluster(leftMatrix, depth+1);
        results[1] = fullCluster(rightMatrix, depth+1);

        ClusterResult leftResult = results[0];
        ClusterResult rightResult = results[1];

        verbose("Merging at depth " + depth);

        // Compute the relaxed correlation objective function over the split
        // partitions found so far.
        double splitObjective = eigenCutter.getSplitObjective(
                alpha, beta,
                leftResult.numClusters, leftResult.assignments,
                rightResult.numClusters, rightResult.assignments);

        // Compute the objective when we merge the two branches together.
        double mergedObjective = eigenCutter.getMergedObjective(alpha, beta);

        // If the merged objective value is less than the split version, combine
        // all clusters into one.
        int[] assignments = new int[matrix.rows()];
        int numClusters = 1;
        if (mergedObjective < splitObjective) {
            verbose("Selecting to combine sub trees at depth " + depth);
            Arrays.fill(assignments, 0);
        } else  {
            verbose("Selecting to maintain sub trees at depth " + depth);

            // Copy over the left assignments and the right assignments, where
            // the cluster id's of the right assignments are incremented to
            // avoid duplicate cluster ids.
            numClusters = leftResult.numClusters + rightResult.numClusters;

            int[] leftReordering = eigenCutter.getLeftReordering();
            int[] rightReordering = eigenCutter.getRightReordering();

            for (int index = 0; index < leftReordering.length; ++index)
                assignments[leftReordering[index]] = 
                    leftResult.assignments[index];
            for (int index = 0; index < rightReordering.length; ++index)
                assignments[rightReordering[index]] =
                    rightResult.assignments[index] + leftResult.numClusters;
        }
        return new ClusterResult(assignments, numClusters);
    }
1224654
def cluster_nodes(self, tol=0.2):
        
        lattice = self.structure.lattice

        vfcoords = [v.frac_coords for v in self.vnodes]

        # Manually generate the distance matrix (which needs to take into
        # account PBC.
        dist_matrix = np.array(lattice.get_all_distances(vfcoords, vfcoords))
        dist_matrix = (dist_matrix + dist_matrix.T) / 2
        for i in range(len(dist_matrix)):
            dist_matrix[i, i] = 0
        condensed_m = squareform(dist_matrix)
        z = linkage(condensed_m)
        cn = fcluster(z, tol, criterion="distance")
        merged_vnodes = []
        for n in set(cn):
            poly_indices = set()
            frac_coords = []
            for i, j in enumerate(np.where(cn == n)[0]):
                poly_indices.update(self.vnodes[j].polyhedron_indices)
                if i == 0:
                    frac_coords.append(self.vnodes[j].frac_coords)
                else:
                    fcoords = self.vnodes[j].frac_coords
                    # We need the image to combine the frac_coords properly.
                    d, image = lattice.get_distance_and_image(frac_coords[0],
                                                              fcoords)
                    frac_coords.append(fcoords + image)
            merged_vnodes.append(
                VoronoiPolyhedron(lattice, np.average(frac_coords, axis=0),
                                  poly_indices, self.coords))
        self.vnodes = merged_vnodes
        logger.debug("%d vertices after combination." % len(self.vnodes))
442880
public static HashFunction[] createHashFunctions(final int seed,
            final int num) {
        final HashFunction[] hashFunctions = new HashFunction[num];
        for (int i = 0; i < num; i++) {
            hashFunctions[i] = Hashing.murmur3_128(seed + i);
        }
        return hashFunctions;
    }
833120
def movMF(
    X,
    n_clusters,
    posterior_type="soft",
    force_weights=None,
    n_init=10,
    n_jobs=1,
    max_iter=300,
    verbose=False,
    init="random-class",
    random_state=None,
    tol=1e-6,
    copy_x=True,
):
    
    if n_init <= 0:
        raise ValueError(
            "Invalid number of initializations."
            " n_init=%d must be bigger than zero." % n_init
        )
    random_state = check_random_state(random_state)

    if max_iter <= 0:
        raise ValueError(
            "Number of iterations should be a positive number,"
            " got %d instead" % max_iter
        )

    best_inertia = np.infty
    X = as_float_array(X, copy=copy_x)
    tol = _tolerance(X, tol)

    if hasattr(init, "__array__"):
        init = check_array(init, dtype=X.dtype.type, copy=True)
        _validate_center_shape(X, n_clusters, init)

        if n_init != 1:
            warnings.warn(
                "Explicit initial center position passed: "
                "performing only one init in k-means instead of n_init=%d" % n_init,
                RuntimeWarning,
                stacklevel=2,
            )
            n_init = 1

    # defaults
    best_centers = None
    best_labels = None
    best_weights = None
    best_concentrations = None
    best_posterior = None
    best_inertia = None

    if n_jobs == 1:
        # For a single thread, less memory is needed if we just store one set
        # of the best results (as opposed to one set per run per thread).
        for it in range(n_init):
            # cluster on the sphere
            (centers, weights, concentrations, posterior, labels, inertia) = _movMF(
                X,
                n_clusters,
                posterior_type=posterior_type,
                force_weights=force_weights,
                max_iter=max_iter,
                verbose=verbose,
                init=init,
                random_state=random_state,
                tol=tol,
            )

            # determine if these results are the best so far
            if best_inertia is None or inertia < best_inertia:
                best_centers = centers.copy()
                best_labels = labels.copy()
                best_weights = weights.copy()
                best_concentrations = concentrations.copy()
                best_posterior = posterior.copy()
                best_inertia = inertia
    else:
        # parallelisation of movMF runs
        seeds = random_state.randint(np.iinfo(np.int32).max, size=n_init)
        results = Parallel(n_jobs=n_jobs, verbose=0)(
            delayed(_movMF)(
                X,
                n_clusters,
                posterior_type=posterior_type,
                force_weights=force_weights,
                max_iter=max_iter,
                verbose=verbose,
                init=init,
                random_state=random_state,
                tol=tol,
            )
            for seed in seeds
        )

        # Get results with the lowest inertia
        centers, weights, concentrations, posteriors, labels, inertia = zip(*results)
        best = np.argmin(inertia)
        best_labels = labels[best]
        best_inertia = inertia[best]
        best_centers = centers[best]
        best_concentrations = concentrations[best]
        best_posterior = posteriors[best]
        best_weights = weights[best]

    return (
        best_centers,
        best_labels,
        best_inertia,
        best_weights,
        best_concentrations,
        best_posterior,
    )
184453
private void clusterIt() {

		dendrogram = new LinkedPair[numItems-1];


		logger.debug("Initial matrix: \n"+matrixToString());


		for (int m=0;m<numItems-1;m++) {

			updateIndicesToCheck(m);
			LinkedPair pair = getClosestPair();
			merge(pair);
			dendrogram[m] = pair;

			//if (debug) {
			//	System.out.println("Matrix after iteration "+m+" (merged "+pair.getFirst()+","+pair.getSecond()+")");
			//	printMatrix();
			//}
		}

	}
554718
@Override
	public Clustering getClusteringResult() {
		List<double[]> microClustering;
		// If the buffer phase is active then the buffer (without duplicates) is
		// equal to the micro clustering
		if (this.bufferPhase) {
			microClustering = new ArrayList<double[]>(this.buffer.size());
			for (double[] pointA : this.buffer) {
				// Searches for a duplicate of the current point
				boolean duplicate = false;
				for (double[] pointB : microClustering) {
					int i;
					for (i = 0; i < pointA.length; i++) {
						if (pointA[i] != pointB[i + 1]) {
							break;
						}
					}
					if (i == pointA.length) {
						duplicate = true;
						pointB[0] += 1;
						break;
					}
				}

				if (!duplicate) {
					// Copies the point to an array with the weight in the first
					// element
					double[] pointWeighted = new double[pointA.length + 1];
					pointWeighted[0] = 1;
					System.arraycopy(pointA, 0, pointWeighted, 1, pointA.length);
					microClustering.add(pointWeighted);
				}
			}
		} else {
			// Collects all nodes as arrays with the weight in the first element
			microClustering = this.root
					.addToClusteringCenters(new ArrayList<double[]>(this.rootCount));
		}
		// Runs the k-means algorithm five times on the micro clustering
		List<double[]> result = null;
		double minValue = Double.POSITIVE_INFINITY;
		for (int i = 0; i < 5; i++) {
			// Creates the starting centroids
			List<double[]> newResult = CoresetKMeans
					.generatekMeansPlusPlusCentroids(this.numClusters,
							microClustering, this.clustererRandom);
			// Runs the k-means algorithm with changing the starting centroids
			double newValue = CoresetKMeans.kMeans(newResult, microClustering);
			// Selects the result with minimum costs
			if (newValue < minValue) {
				result = newResult;
				minValue = newValue;
			}
		}

		// Prepares the points for the clustering result
		AutoExpandVector<Cluster> resultClustering = new AutoExpandVector<Cluster>(
				result.size());
		for (double[] point : result) {
			resultClustering.add(new SphereCluster(point, 0.0));
		}
		return new Clustering(resultClustering);
	}