use of org.apache.ignite.ml.math.Vector in project ignite by apache.
the class FuzzyCMeansLocalExample method main.
/**
* Executes example.
*
* @param args Command line arguments, none required.
*/
public static void main(String[] args) {
System.out.println(">>> Local Fuzzy C-Means usage example started.");
// Distance measure that computes distance between two points.
DistanceMeasure distanceMeasure = new EuclideanDistance();
// "Fuzziness" - specific constant that is used in membership calculation (1.0+-eps ~ K-Means).
double exponentialWeight = 2.0;
// Condition that indicated when algorithm must stop.
// In this example algorithm stops if memberships have changed insignificantly.
BaseFuzzyCMeansClusterer.StopCondition stopCond = BaseFuzzyCMeansClusterer.StopCondition.STABLE_MEMBERSHIPS;
// Maximum difference between new and old membership values with which algorithm will continue to work.
double maxDelta = 0.01;
// The maximum number of FCM iterations.
int maxIterations = 50;
// Value that is used to initialize random numbers generator. You can choose it randomly.
Long seed = null;
// Create new distributed clusterer with parameters described above.
System.out.println(">>> Create new Local Fuzzy C-Means clusterer.");
FuzzyCMeansLocalClusterer clusterer = new FuzzyCMeansLocalClusterer(distanceMeasure, exponentialWeight, stopCond, maxDelta, maxIterations, seed);
// Create sample data.
double[][] points = new double[][] { { -10, -10 }, { -9, -11 }, { -10, -9 }, { -11, -9 }, { 10, 10 }, { 9, 11 }, { 10, 9 }, { 11, 9 }, { -10, 10 }, { -9, 11 }, { -10, 9 }, { -11, 9 }, { 10, -10 }, { 9, -11 }, { 10, -9 }, { 11, -9 } };
// Initialize matrix of data points. Each row contains one point.
System.out.println(">>> Create the matrix that contains sample points.");
// Store points into matrix.
DenseLocalOnHeapMatrix pntMatrix = new DenseLocalOnHeapMatrix(points);
// Call clusterization method with some number of centers.
// It returns model that can predict results for new points.
System.out.println(">>> Perform clusterization.");
int numCenters = 4;
FuzzyCMeansModel mdl = clusterer.cluster(pntMatrix, numCenters);
// You can also get centers of clusters that is computed by Fuzzy C-Means algorithm.
Vector[] centers = mdl.centers();
String res = ">>> Results:\n" + ">>> 1st center: " + centers[0].get(0) + " " + centers[0].get(1) + "\n" + ">>> 2nd center: " + centers[1].get(0) + " " + centers[1].get(1) + "\n" + ">>> 3rd center: " + centers[2].get(0) + " " + centers[2].get(1) + "\n" + ">>> 4th center: " + centers[3].get(0) + " " + centers[3].get(1) + "\n";
System.out.println(res);
}
use of org.apache.ignite.ml.math.Vector in project ignite by apache.
the class DistributedLinearRegressionWithQRTrainerExample method main.
/**
* Run example.
*/
public static void main(String[] args) throws InterruptedException {
System.out.println();
System.out.println(">>> Linear regression model over sparse distributed matrix API usage example started.");
// Start ignite grid.
try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) {
System.out.println(">>> Ignite grid started.");
// Create IgniteThread, we must work with SparseDistributedMatrix inside IgniteThread
// because we create ignite cache internally.
IgniteThread igniteThread = new IgniteThread(ignite.configuration().getIgniteInstanceName(), SparseDistributedMatrixExample.class.getSimpleName(), () -> {
// Create SparseDistributedMatrix, new cache will be created automagically.
System.out.println(">>> Create new SparseDistributedMatrix inside IgniteThread.");
SparseDistributedMatrix distributedMatrix = new SparseDistributedMatrix(data);
System.out.println(">>> Create new linear regression trainer object.");
Trainer<LinearRegressionModel, Matrix> trainer = new LinearRegressionQRTrainer();
System.out.println(">>> Perform the training to get the model.");
LinearRegressionModel model = trainer.train(distributedMatrix);
System.out.println(">>> Linear regression model: " + model);
System.out.println(">>> ---------------------------------");
System.out.println(">>> | Prediction\t| Ground Truth\t|");
System.out.println(">>> ---------------------------------");
for (double[] observation : data) {
Vector inputs = new SparseDistributedVector(Arrays.copyOfRange(observation, 1, observation.length));
double prediction = model.apply(inputs);
double groundTruth = observation[0];
System.out.printf(">>> | %.4f\t\t| %.4f\t\t|\n", prediction, groundTruth);
}
System.out.println(">>> ---------------------------------");
});
igniteThread.start();
igniteThread.join();
}
}
use of org.apache.ignite.ml.math.Vector in project ignite by apache.
the class VectorExample method main.
/**
* Executes example.
*
* @param args Command line arguments, none required.
*/
public static void main(String[] args) {
System.out.println();
System.out.println(">>> Basic Vector API usage example started.");
System.out.println("\n>>> Creating perpendicular vectors.");
double[] data1 = new double[] { 1, 0, 3, 0, 5, 0 };
double[] data2 = new double[] { 0, 2, 0, 4, 0, 6 };
Vector v1 = new DenseLocalOnHeapVector(data1);
Vector v2 = new DenseLocalOnHeapVector(data2);
System.out.println(">>> First vector: " + Arrays.toString(data1));
System.out.println(">>> Second vector: " + Arrays.toString(data2));
double dotProduct = v1.dot(v2);
boolean dotProductIsAsExp = dotProduct == 0;
System.out.println("\n>>> Dot product of vectors: [" + dotProduct + "], it is 0 as expected: [" + dotProductIsAsExp + "].");
Vector hypotenuse = v1.plus(v2);
System.out.println("\n>>> Hypotenuse (sum of vectors): " + Arrays.toString(hypotenuse.getStorage().data()));
double lenSquared1 = v1.getLengthSquared();
double lenSquared2 = v2.getLengthSquared();
double lenSquaredHypotenuse = hypotenuse.getLengthSquared();
boolean lenSquaredHypotenuseIsAsExp = lenSquaredHypotenuse == lenSquared1 + lenSquared2;
System.out.println(">>> Squared length of first vector: [" + lenSquared1 + "].");
System.out.println(">>> Squared length of second vector: [" + lenSquared2 + "].");
System.out.println(">>> Squared length of hypotenuse: [" + lenSquaredHypotenuse + "], equals sum of squared lengths of two original vectors as expected: [" + lenSquaredHypotenuseIsAsExp + "].");
System.out.println("\n>>> Basic Vector API usage example completed.");
}
use of org.apache.ignite.ml.math.Vector in project ignite by apache.
the class FuzzyCMeansDistributedClusterer method calculateNewCenters.
/**
* Calculate new centers according to membership matrix.
*
* @param points Matrix with source points.
* @param membershipsAndSums Membership matrix and sums of membership coefficient for each center.
* @param k The number of centers.
* @return Array of new centers.
*/
private Vector[] calculateNewCenters(SparseDistributedMatrix points, MembershipsAndSums membershipsAndSums, int k) {
String cacheName = ((SparseDistributedMatrixStorage) points.getStorage()).cacheName();
UUID uuid = points.getUUID();
CentersArraySupplier supplier = new CentersArraySupplier(k, points.columnSize());
Vector[] centers = CacheUtils.distributedFold(cacheName, (IgniteBiFunction<Cache.Entry<SparseMatrixKey, ConcurrentHashMap<Integer, Double>>, Vector[], Vector[]>) (vectorWithIndex, centerSums) -> {
Integer idx = vectorWithIndex.getKey().index();
Vector pnt = MatrixUtil.localCopyOf(VectorUtils.fromMap(vectorWithIndex.getValue(), false));
Vector pntMemberships = membershipsAndSums.memberships.get(idx);
for (int i = 0; i < k; i++) {
Vector weightedPnt = pnt.times(pntMemberships.getX(i));
centerSums[i] = centerSums[i].plus(weightedPnt);
}
return centerSums;
}, key -> key.dataStructureId().equals(uuid), (sums1, sums2) -> {
for (int i = 0; i < k; i++) sums1[i] = sums1[i].plus(sums2[i]);
return sums1;
}, supplier);
for (int i = 0; i < k; i++) centers[i] = centers[i].divide(membershipsAndSums.membershipSums.getX(i));
return centers;
}
use of org.apache.ignite.ml.math.Vector in project ignite by apache.
the class FuzzyCMeansDistributedClusterer method calculateMembership.
/**
* Calculate matrix of membership coefficients for each point and each center.
*
* @param points Matrix with source points.
* @param centers Array of current centers.
* @return Membership matrix and sums of membership coefficients for each center.
*/
private MembershipsAndSums calculateMembership(SparseDistributedMatrix points, Vector[] centers) {
String cacheName = ((SparseDistributedMatrixStorage) points.getStorage()).cacheName();
UUID uuid = points.getUUID();
double fuzzyMembershipCoefficient = 2 / (exponentialWeight - 1);
MembershipsAndSumsSupplier supplier = new MembershipsAndSumsSupplier(centers.length);
return CacheUtils.distributedFold(cacheName, (IgniteBiFunction<Cache.Entry<SparseMatrixKey, ConcurrentHashMap<Integer, Double>>, MembershipsAndSums, MembershipsAndSums>) (vectorWithIndex, membershipsAndSums) -> {
Integer idx = vectorWithIndex.getKey().index();
Vector pnt = VectorUtils.fromMap(vectorWithIndex.getValue(), false);
Vector distances = new DenseLocalOnHeapVector(centers.length);
Vector pntMemberships = new DenseLocalOnHeapVector(centers.length);
for (int i = 0; i < centers.length; i++) distances.setX(i, distance(centers[i], pnt));
for (int i = 0; i < centers.length; i++) {
double invertedFuzzyWeight = 0.0;
for (int j = 0; j < centers.length; j++) {
double val = Math.pow(distances.getX(i) / distances.getX(j), fuzzyMembershipCoefficient);
if (Double.isNaN(val))
val = 1.0;
invertedFuzzyWeight += val;
}
double membership = Math.pow(1.0 / invertedFuzzyWeight, exponentialWeight);
pntMemberships.setX(i, membership);
}
membershipsAndSums.memberships.put(idx, pntMemberships);
membershipsAndSums.membershipSums = membershipsAndSums.membershipSums.plus(pntMemberships);
return membershipsAndSums;
}, key -> key.dataStructureId().equals(uuid), (mem1, mem2) -> {
mem1.merge(mem2);
return mem1;
}, supplier);
}
Aggregations