use of org.apache.ignite.ml.math.impls.matrix.DenseLocalOnHeapMatrix in project ignite by apache.
the class FuzzyCMeansLocalClusterer method calculateMembership.
/**
* Calculate membership matrix.
*
* @param distances Matrix of distances.
* @param weights Vector of weights.
* @
*/
private Matrix calculateMembership(Matrix distances, Vector weights) {
Matrix newMembership = new DenseLocalOnHeapMatrix(distances.rowSize(), distances.columnSize());
int numPoints = distances.columnSize();
int numCenters = distances.rowSize();
double fuzzyMembershipCoefficient = 2 / (exponentialWeight - 1);
for (int i = 0; i < numCenters; i++) {
for (int j = 0; j < numPoints; j++) {
double invertedFuzzyWeight = 0.0;
for (int k = 0; k < numCenters; k++) {
double val = Math.pow(distances.get(i, j) / distances.get(k, j), fuzzyMembershipCoefficient);
if (Double.isNaN(val))
val = 1.0;
invertedFuzzyWeight += val;
}
double weight = 1.0 / invertedFuzzyWeight * weights.getX(j);
newMembership.setX(i, j, Math.pow(weight, exponentialWeight));
}
}
return newMembership;
}
use of org.apache.ignite.ml.math.impls.matrix.DenseLocalOnHeapMatrix in project ignite by apache.
the class FuzzyCMeansLocalClusterer method cluster.
/**
* {@inheritDoc}
*/
@Override
public FuzzyCMeansModel cluster(DenseLocalOnHeapMatrix points, int k, List<Double> weights) throws MathIllegalArgumentException, ConvergenceException {
GridArgumentCheck.notNull(points, "points");
GridArgumentCheck.notNull(weights, "weights");
if (points.rowSize() != weights.size())
throw new MathIllegalArgumentException("The number of points and the number of weights are not equal");
if (k < 2)
throw new MathIllegalArgumentException("The number of clusters is less than 2");
Matrix centers = new DenseLocalOnHeapMatrix(k, points.columnSize());
Matrix distances = new DenseLocalOnHeapMatrix(k, points.rowSize());
Matrix membership = new DenseLocalOnHeapMatrix(k, points.rowSize());
Vector weightsVector = new DenseLocalOnHeapVector(weights.size());
for (int i = 0; i < weights.size(); i++) weightsVector.setX(i, weights.get(i));
initializeCenters(centers, points, k, weightsVector);
int iteration = 0;
boolean finished = false;
while (iteration < maxIterations && !finished) {
calculateDistances(distances, points, centers);
Matrix newMembership = calculateMembership(distances, weightsVector);
Matrix newCenters = calculateNewCenters(points, newMembership);
if (this.stopCond == StopCondition.STABLE_CENTERS)
finished = areCentersStable(centers, newCenters);
else
finished = areMembershipStable(membership, newMembership);
centers = newCenters;
membership = newMembership;
iteration++;
}
if (iteration == maxIterations)
throw new ConvergenceException("Fuzzy C-Means algorithm has not converged after " + Integer.toString(iteration) + " iterations");
Vector[] centersArr = new Vector[k];
for (int i = 0; i < k; i++) centersArr[i] = centers.getRow(i);
return new FuzzyCMeansModel(centersArr, measure);
}
Aggregations