Example usage for org.apache.mahout.math Centroid Centroid

List of usage examples for org.apache.mahout.math Centroid Centroid

Introduction

In this page you can find the example usage for org.apache.mahout.math Centroid Centroid.

Prototype

public Centroid(int key, Vector initialValue) 

Source Link

Usage

From source file:io.ssc.relationdiscovery.KMeans.java

License:Open Source License

public KMeans(Matrix A, int k, DistanceMeasure distanceMeasure) {
    this.A = A;//from  w  ww  . j a  v  a  2 s  .  c  om
    this.k = k;
    this.distanceMeasure = distanceMeasure;

    centroids = new Centroid[k];

    log.info("Picking {} initial centroids", k);
    Iterator<MatrixSlice> samples = new FixedSizeSamplingIterator<MatrixSlice>(k, A.iterator());
    int index = 0;
    while (samples.hasNext()) {
        centroids[index] = new Centroid(index, samples.next().vector());
        index++;
    }
}

From source file:io.ssc.relationdiscovery.KMeans.java

License:Open Source License

private double singleIteration() {

    Centroid[] nextCentroids = new Centroid[k];
    for (int n = 0; n < k; n++) {
        nextCentroids[n] = new Centroid(n, new DenseVector(A.numCols()));
    }//from www. j  a  v  a 2  s . c om

    double[] centroidLengthsSquared = new double[k];
    for (int n = 0; n < k; n++) {
        centroidLengthsSquared[n] = centroids[n].getLengthSquared();
    }

    for (MatrixSlice rowSlice : A) {

        Vector row = rowSlice.vector();

        int nearestCentroid = 0;
        double closestDistance = Double.MAX_VALUE;

        for (int n = 0; n < k; n++) {
            double distance = distanceMeasure.distance(centroidLengthsSquared[n], centroids[n], row);
            if (distance < closestDistance) {
                closestDistance = distance;
                nearestCentroid = n;
            }
        }

        nextCentroids[nearestCentroid].update(row);
    }

    double maxChange = 0;
    for (int n = 0; n < k; n++) {
        maxChange = Math.max(maxChange, centroids[n].minus(nextCentroids[n]).norm(2));
    }

    centroids = nextCentroids;

    return maxChange;
}