Search in sources :

Example 61 with Vector

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);
}
Also used : DenseLocalOnHeapMatrix(org.apache.ignite.ml.math.impls.matrix.DenseLocalOnHeapMatrix) DistanceMeasure(org.apache.ignite.ml.math.distances.DistanceMeasure) EuclideanDistance(org.apache.ignite.ml.math.distances.EuclideanDistance) FuzzyCMeansModel(org.apache.ignite.ml.clustering.FuzzyCMeansModel) FuzzyCMeansLocalClusterer(org.apache.ignite.ml.clustering.FuzzyCMeansLocalClusterer) BaseFuzzyCMeansClusterer(org.apache.ignite.ml.clustering.BaseFuzzyCMeansClusterer) Vector(org.apache.ignite.ml.math.Vector)

Example 62 with Vector

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();
    }
}
Also used : SparseDistributedMatrix(org.apache.ignite.ml.math.impls.matrix.SparseDistributedMatrix) SparseDistributedMatrixExample(org.apache.ignite.examples.ml.math.matrix.SparseDistributedMatrixExample) Matrix(org.apache.ignite.ml.math.Matrix) SparseDistributedMatrix(org.apache.ignite.ml.math.impls.matrix.SparseDistributedMatrix) LinearRegressionModel(org.apache.ignite.ml.regressions.linear.LinearRegressionModel) LinearRegressionQRTrainer(org.apache.ignite.ml.regressions.linear.LinearRegressionQRTrainer) SparseDistributedVector(org.apache.ignite.ml.math.impls.vector.SparseDistributedVector) Ignite(org.apache.ignite.Ignite) IgniteThread(org.apache.ignite.thread.IgniteThread) Vector(org.apache.ignite.ml.math.Vector) SparseDistributedVector(org.apache.ignite.ml.math.impls.vector.SparseDistributedVector)

Example 63 with Vector

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.");
}
Also used : DenseLocalOnHeapVector(org.apache.ignite.ml.math.impls.vector.DenseLocalOnHeapVector) Vector(org.apache.ignite.ml.math.Vector) DenseLocalOnHeapVector(org.apache.ignite.ml.math.impls.vector.DenseLocalOnHeapVector)

Example 64 with Vector

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;
}
Also used : IgniteSupplier(org.apache.ignite.ml.math.functions.IgniteSupplier) GridArgumentCheck(org.apache.ignite.internal.util.GridArgumentCheck) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Functions(org.apache.ignite.ml.math.functions.Functions) Random(java.util.Random) DistanceMeasure(org.apache.ignite.ml.math.distances.DistanceMeasure) UUID(java.util.UUID) SparseDistributedMatrix(org.apache.ignite.ml.math.impls.matrix.SparseDistributedMatrix) Collectors(java.util.stream.Collectors) CacheUtils(org.apache.ignite.ml.math.distributed.CacheUtils) MatrixUtil(org.apache.ignite.ml.math.util.MatrixUtil) SparseDistributedMatrixStorage(org.apache.ignite.ml.math.impls.storage.matrix.SparseDistributedMatrixStorage) ArrayList(java.util.ArrayList) ConvergenceException(org.apache.ignite.ml.math.exceptions.ConvergenceException) List(java.util.List) SparseMatrixKey(org.apache.ignite.ml.math.distributed.keys.impl.SparseMatrixKey) Vector(org.apache.ignite.ml.math.Vector) MathIllegalArgumentException(org.apache.ignite.ml.math.exceptions.MathIllegalArgumentException) IgniteBiFunction(org.apache.ignite.ml.math.functions.IgniteBiFunction) DenseLocalOnHeapMatrix(org.apache.ignite.ml.math.impls.matrix.DenseLocalOnHeapMatrix) Map(java.util.Map) Cache(javax.cache.Cache) VectorUtils(org.apache.ignite.ml.math.VectorUtils) DenseLocalOnHeapVector(org.apache.ignite.ml.math.impls.vector.DenseLocalOnHeapVector) SparseDistributedMatrixStorage(org.apache.ignite.ml.math.impls.storage.matrix.SparseDistributedMatrixStorage) UUID(java.util.UUID) Vector(org.apache.ignite.ml.math.Vector) DenseLocalOnHeapVector(org.apache.ignite.ml.math.impls.vector.DenseLocalOnHeapVector)

Example 65 with Vector

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);
}
Also used : IgniteSupplier(org.apache.ignite.ml.math.functions.IgniteSupplier) GridArgumentCheck(org.apache.ignite.internal.util.GridArgumentCheck) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Functions(org.apache.ignite.ml.math.functions.Functions) Random(java.util.Random) DistanceMeasure(org.apache.ignite.ml.math.distances.DistanceMeasure) UUID(java.util.UUID) SparseDistributedMatrix(org.apache.ignite.ml.math.impls.matrix.SparseDistributedMatrix) Collectors(java.util.stream.Collectors) CacheUtils(org.apache.ignite.ml.math.distributed.CacheUtils) MatrixUtil(org.apache.ignite.ml.math.util.MatrixUtil) SparseDistributedMatrixStorage(org.apache.ignite.ml.math.impls.storage.matrix.SparseDistributedMatrixStorage) ArrayList(java.util.ArrayList) ConvergenceException(org.apache.ignite.ml.math.exceptions.ConvergenceException) List(java.util.List) SparseMatrixKey(org.apache.ignite.ml.math.distributed.keys.impl.SparseMatrixKey) Vector(org.apache.ignite.ml.math.Vector) MathIllegalArgumentException(org.apache.ignite.ml.math.exceptions.MathIllegalArgumentException) IgniteBiFunction(org.apache.ignite.ml.math.functions.IgniteBiFunction) DenseLocalOnHeapMatrix(org.apache.ignite.ml.math.impls.matrix.DenseLocalOnHeapMatrix) Map(java.util.Map) Cache(javax.cache.Cache) VectorUtils(org.apache.ignite.ml.math.VectorUtils) DenseLocalOnHeapVector(org.apache.ignite.ml.math.impls.vector.DenseLocalOnHeapVector) SparseDistributedMatrixStorage(org.apache.ignite.ml.math.impls.storage.matrix.SparseDistributedMatrixStorage) DenseLocalOnHeapVector(org.apache.ignite.ml.math.impls.vector.DenseLocalOnHeapVector) UUID(java.util.UUID) Vector(org.apache.ignite.ml.math.Vector) DenseLocalOnHeapVector(org.apache.ignite.ml.math.impls.vector.DenseLocalOnHeapVector)

Aggregations

Vector (org.apache.ignite.ml.math.Vector)116 DenseLocalOnHeapVector (org.apache.ignite.ml.math.impls.vector.DenseLocalOnHeapVector)62 Test (org.junit.Test)29 EuclideanDistance (org.apache.ignite.ml.math.distances.EuclideanDistance)20 DenseLocalOnHeapMatrix (org.apache.ignite.ml.math.impls.matrix.DenseLocalOnHeapMatrix)20 Matrix (org.apache.ignite.ml.math.Matrix)19 SparseDistributedMatrix (org.apache.ignite.ml.math.impls.matrix.SparseDistributedMatrix)17 Random (java.util.Random)12 ArrayList (java.util.ArrayList)11 DistanceMeasure (org.apache.ignite.ml.math.distances.DistanceMeasure)10 Arrays (java.util.Arrays)9 Ignite (org.apache.ignite.Ignite)9 SparseDistributedMatrixStorage (org.apache.ignite.ml.math.impls.storage.matrix.SparseDistributedMatrixStorage)9 LabeledDataset (org.apache.ignite.ml.structures.LabeledDataset)9 UUID (java.util.UUID)8 Collections (java.util.Collections)7 List (java.util.List)7 MathIllegalArgumentException (org.apache.ignite.ml.math.exceptions.MathIllegalArgumentException)7 DenseLocalOffHeapVector (org.apache.ignite.ml.math.impls.vector.DenseLocalOffHeapVector)7 HashMap (java.util.HashMap)6