Search in sources :

Example 1 with KMeansTrainer

use of org.apache.ignite.ml.clustering.kmeans.KMeansTrainer in project ignite by apache.

the class KMeansClusterizationExportImportExample method main.

/**
 * Run example.
 */
public static void main(String[] args) throws IOException {
    System.out.println();
    System.out.println(">>> KMeans clustering algorithm over cached dataset usage example started.");
    // Start ignite grid.
    try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) {
        System.out.println(">>> Ignite grid started.");
        IgniteCache<Integer, Vector> dataCache = null;
        Path jsonMdlPath = null;
        try {
            dataCache = new SandboxMLCache(ignite).fillCacheWith(MLSandboxDatasets.TWO_CLASSED_IRIS);
            Vectorizer<Integer, Vector, Integer, Double> vectorizer = new DummyVectorizer<Integer>().labeled(Vectorizer.LabelCoordinate.FIRST);
            KMeansTrainer trainer = new KMeansTrainer().withDistance(new WeightedMinkowskiDistance(2, new double[] { 5.9360, 2.7700, 4.2600, 1.3260 }));
            // .withDistance(new MinkowskiDistance(2));
            KMeansModel mdl = trainer.fit(ignite, dataCache, vectorizer);
            System.out.println("\n>>> Exported KMeans model: " + mdl);
            jsonMdlPath = Files.createTempFile(null, null);
            mdl.toJSON(jsonMdlPath);
            KMeansModel modelImportedFromJSON = KMeansModel.fromJSON(jsonMdlPath);
            System.out.println("\n>>> Imported KMeans model: " + modelImportedFromJSON);
            System.out.println("\n>>> KMeans clustering algorithm over cached dataset usage example completed.");
        } finally {
            if (dataCache != null)
                dataCache.destroy();
            if (jsonMdlPath != null)
                Files.deleteIfExists(jsonMdlPath);
        }
    } finally {
        System.out.flush();
    }
}
Also used : Path(java.nio.file.Path) SandboxMLCache(org.apache.ignite.examples.ml.util.SandboxMLCache) KMeansModel(org.apache.ignite.ml.clustering.kmeans.KMeansModel) KMeansTrainer(org.apache.ignite.ml.clustering.kmeans.KMeansTrainer) Ignite(org.apache.ignite.Ignite) Vector(org.apache.ignite.ml.math.primitives.vector.Vector) WeightedMinkowskiDistance(org.apache.ignite.ml.math.distances.WeightedMinkowskiDistance)

Example 2 with KMeansTrainer

use of org.apache.ignite.ml.clustering.kmeans.KMeansTrainer in project ignite by apache.

the class LocalModelsTest method getClusterModel.

/**
 */
private KMeansModel getClusterModel() {
    Map<Integer, double[]> data = new HashMap<>();
    data.put(0, new double[] { 1.0, 1959, 325100 });
    data.put(1, new double[] { 1.0, 1960, 373200 });
    KMeansTrainer trainer = new KMeansTrainer().withAmountOfClusters(1);
    return trainer.fit(new LocalDatasetBuilder<>(data, 2), new DoubleArrayVectorizer<Integer>().labeled(Vectorizer.LabelCoordinate.LAST));
}
Also used : DoubleArrayVectorizer(org.apache.ignite.ml.dataset.feature.extractor.impl.DoubleArrayVectorizer) HashMap(java.util.HashMap) KMeansTrainer(org.apache.ignite.ml.clustering.kmeans.KMeansTrainer)

Example 3 with KMeansTrainer

use of org.apache.ignite.ml.clustering.kmeans.KMeansTrainer in project ignite by apache.

the class KeepBinaryTest method test.

/**
 * Startup Ignite, populate cache and train some model.
 */
@Test
public void test() {
    IgniteCache<Integer, BinaryObject> dataCache = populateCache(ignite);
    KMeansTrainer trainer = new KMeansTrainer();
    CacheBasedDatasetBuilder<Integer, BinaryObject> datasetBuilder = new CacheBasedDatasetBuilder<>(ignite, dataCache).withKeepBinary(true);
    KMeansModel mdl = trainer.fit(datasetBuilder, new BinaryObjectVectorizer<Integer>("feature1").labeled("label"));
    Integer zeroCentre = mdl.predict(VectorUtils.num2Vec(0.0));
    assertTrue(mdl.centers()[zeroCentre].get(0) == 0);
}
Also used : KMeansModel(org.apache.ignite.ml.clustering.kmeans.KMeansModel) BinaryObjectVectorizer(org.apache.ignite.ml.dataset.feature.extractor.impl.BinaryObjectVectorizer) BinaryObject(org.apache.ignite.binary.BinaryObject) KMeansTrainer(org.apache.ignite.ml.clustering.kmeans.KMeansTrainer) GridCommonAbstractTest(org.apache.ignite.testframework.junits.common.GridCommonAbstractTest) Test(org.junit.Test)

Example 4 with KMeansTrainer

use of org.apache.ignite.ml.clustering.kmeans.KMeansTrainer in project ignite by apache.

the class CustomersClusterizationExample method main.

/**
 * Runs example.
 */
public static void main(String[] args) throws IOException {
    try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) {
        System.out.println(">>> Ignite grid started.");
        IgniteCache<Integer, Vector> dataCache = null;
        try {
            System.out.println(">>> Fill dataset cache.");
            dataCache = new SandboxMLCache(ignite).fillCacheWith(MLSandboxDatasets.WHOLESALE_CUSTOMERS);
            System.out.println(">>> Start training and scoring.");
            for (int amountOfClusters = 1; amountOfClusters < 10; amountOfClusters++) {
                KMeansTrainer trainer = new KMeansTrainer().withAmountOfClusters(amountOfClusters).withDistance(new EuclideanDistance()).withEnvironmentBuilder(LearningEnvironmentBuilder.defaultBuilder().withRNGSeed(0)).withMaxIterations(50);
                // This vectorizer works with values in cache of Vector class.
                Vectorizer<Integer, Vector, Integer, Double> vectorizer = new DummyVectorizer<Integer>().labeled(// FIRST means "label are stored at first coordinate of vector"
                Vectorizer.LabelCoordinate.FIRST);
                // Splits dataset to train and test samples with 80/20 proportion.
                TrainTestSplit<Integer, Vector> split = new TrainTestDatasetSplitter<Integer, Vector>().split(0.8);
                KMeansModel mdl = trainer.fit(ignite, dataCache, split.getTrainFilter(), vectorizer);
                double entropy = computeMeanEntropy(dataCache, split.getTestFilter(), vectorizer, mdl);
                System.out.println(String.format(">> Clusters mean entropy [%d clusters]: %.2f", amountOfClusters, entropy));
            }
        } finally {
            if (dataCache != null)
                dataCache.destroy();
        }
    } finally {
        System.out.flush();
    }
}
Also used : SandboxMLCache(org.apache.ignite.examples.ml.util.SandboxMLCache) KMeansModel(org.apache.ignite.ml.clustering.kmeans.KMeansModel) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) EuclideanDistance(org.apache.ignite.ml.math.distances.EuclideanDistance) KMeansTrainer(org.apache.ignite.ml.clustering.kmeans.KMeansTrainer) Ignite(org.apache.ignite.Ignite) Vector(org.apache.ignite.ml.math.primitives.vector.Vector) LabeledVector(org.apache.ignite.ml.structures.LabeledVector)

Example 5 with KMeansTrainer

use of org.apache.ignite.ml.clustering.kmeans.KMeansTrainer in project ignite by apache.

the class KMeansClusterizationExample method main.

/**
 * Run example.
 */
public static void main(String[] args) throws IOException {
    System.out.println();
    System.out.println(">>> KMeans clustering algorithm over cached dataset usage example started.");
    // Start ignite grid.
    try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) {
        System.out.println(">>> Ignite grid started.");
        IgniteCache<Integer, Vector> dataCache = null;
        try {
            dataCache = new SandboxMLCache(ignite).fillCacheWith(MLSandboxDatasets.TWO_CLASSED_IRIS);
            Vectorizer<Integer, Vector, Integer, Double> vectorizer = new DummyVectorizer<Integer>().labeled(Vectorizer.LabelCoordinate.FIRST);
            KMeansTrainer trainer = new KMeansTrainer();
            KMeansModel mdl = trainer.fit(ignite, dataCache, vectorizer);
            System.out.println(">>> KMeans centroids");
            Tracer.showAscii(mdl.centers()[0]);
            Tracer.showAscii(mdl.centers()[1]);
            System.out.println(">>>");
            System.out.println(">>> --------------------------------------------");
            System.out.println(">>> | Predicted cluster\t| Erased class label\t|");
            System.out.println(">>> --------------------------------------------");
            try (QueryCursor<Cache.Entry<Integer, Vector>> observations = dataCache.query(new ScanQuery<>())) {
                for (Cache.Entry<Integer, Vector> observation : observations) {
                    Vector val = observation.getValue();
                    Vector inputs = val.copyOfRange(1, val.size());
                    double groundTruth = val.get(0);
                    double prediction = mdl.predict(inputs);
                    System.out.printf(">>> | %.4f\t\t\t| %.4f\t\t|\n", prediction, groundTruth);
                }
                System.out.println(">>> ---------------------------------");
                System.out.println(">>> KMeans clustering algorithm over cached dataset usage example completed.");
            }
        } finally {
            if (dataCache != null)
                dataCache.destroy();
        }
    } finally {
        System.out.flush();
    }
}
Also used : SandboxMLCache(org.apache.ignite.examples.ml.util.SandboxMLCache) KMeansModel(org.apache.ignite.ml.clustering.kmeans.KMeansModel) KMeansTrainer(org.apache.ignite.ml.clustering.kmeans.KMeansTrainer) Ignite(org.apache.ignite.Ignite) Vector(org.apache.ignite.ml.math.primitives.vector.Vector) IgniteCache(org.apache.ignite.IgniteCache) SandboxMLCache(org.apache.ignite.examples.ml.util.SandboxMLCache) Cache(javax.cache.Cache)

Aggregations

KMeansTrainer (org.apache.ignite.ml.clustering.kmeans.KMeansTrainer)10 KMeansModel (org.apache.ignite.ml.clustering.kmeans.KMeansModel)8 Vector (org.apache.ignite.ml.math.primitives.vector.Vector)5 Ignite (org.apache.ignite.Ignite)4 SandboxMLCache (org.apache.ignite.examples.ml.util.SandboxMLCache)3 Test (org.junit.Test)3 HashMap (java.util.HashMap)2 BinaryObject (org.apache.ignite.binary.BinaryObject)2 TrainerTest (org.apache.ignite.ml.common.TrainerTest)2 DoubleArrayVectorizer (org.apache.ignite.ml.dataset.feature.extractor.impl.DoubleArrayVectorizer)2 EuclideanDistance (org.apache.ignite.ml.math.distances.EuclideanDistance)2 DenseVector (org.apache.ignite.ml.math.primitives.vector.impl.DenseVector)2 Path (java.nio.file.Path)1 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1 Cache (javax.cache.Cache)1 IgniteCache (org.apache.ignite.IgniteCache)1 BinaryObjectVectorizer (org.apache.ignite.ml.dataset.feature.extractor.impl.BinaryObjectVectorizer)1 WeightedMinkowskiDistance (org.apache.ignite.ml.math.distances.WeightedMinkowskiDistance)1 LabeledVector (org.apache.ignite.ml.structures.LabeledVector)1 GridCommonAbstractTest (org.apache.ignite.testframework.junits.common.GridCommonAbstractTest)1