Search in sources :

Example 1 with GDBBinaryClassifierOnTreesTrainer

use of org.apache.ignite.ml.tree.boosting.GDBBinaryClassifierOnTreesTrainer in project ignite by apache.

the class GDBOnTreesClassificationExportImportExample method main.

/**
 * Run example.
 *
 * @param args Command line arguments, none required.
 */
public static void main(String[] args) throws IOException {
    System.out.println();
    System.out.println(">>> GDB classification trainer example started.");
    // Start ignite grid.
    try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) {
        System.out.println("\n>>> Ignite grid started.");
        // Create cache with training data.
        CacheConfiguration<Integer, double[]> trainingSetCfg = createCacheConfiguration();
        IgniteCache<Integer, double[]> trainingSet = null;
        Path jsonMdlPath = null;
        try {
            trainingSet = fillTrainingData(ignite, trainingSetCfg);
            // Create classification trainer.
            GDBTrainer trainer = new GDBBinaryClassifierOnTreesTrainer(1.0, 300, 2, 0.).withCheckConvergenceStgyFactory(new MeanAbsValueConvergenceCheckerFactory(0.1));
            // Train decision tree model.
            GDBModel mdl = trainer.fit(ignite, trainingSet, new DoubleArrayVectorizer<Integer>().labeled(Vectorizer.LabelCoordinate.LAST));
            System.out.println("\n>>> Exported GDB classification model: " + mdl.toString(true));
            predictOnGeneratedData(mdl);
            jsonMdlPath = Files.createTempFile(null, null);
            mdl.toJSON(jsonMdlPath);
            IgniteFunction<Double, Double> lbMapper = lb -> lb > 0.5 ? 1.0 : 0.0;
            GDBModel modelImportedFromJSON = GDBModel.fromJSON(jsonMdlPath).withLblMapping(lbMapper);
            System.out.println("\n>>> Imported GDB classification model: " + modelImportedFromJSON.toString(true));
            predictOnGeneratedData(modelImportedFromJSON);
            System.out.println(">>> GDB classification trainer example completed.");
        } finally {
            if (trainingSet != null)
                trainingSet.destroy();
            if (jsonMdlPath != null)
                Files.deleteIfExists(jsonMdlPath);
        }
    } finally {
        System.out.flush();
    }
}
Also used : Path(java.nio.file.Path) Files(java.nio.file.Files) IgniteFunction(org.apache.ignite.ml.math.functions.IgniteFunction) IOException(java.io.IOException) Ignite(org.apache.ignite.Ignite) IgniteCache(org.apache.ignite.IgniteCache) RendezvousAffinityFunction(org.apache.ignite.cache.affinity.rendezvous.RendezvousAffinityFunction) MeanAbsValueConvergenceCheckerFactory(org.apache.ignite.ml.composition.boosting.convergence.mean.MeanAbsValueConvergenceCheckerFactory) GDBTrainer(org.apache.ignite.ml.composition.boosting.GDBTrainer) Ignition(org.apache.ignite.Ignition) CacheConfiguration(org.apache.ignite.configuration.CacheConfiguration) VectorUtils(org.apache.ignite.ml.math.primitives.vector.VectorUtils) GDBBinaryClassifierOnTreesTrainer(org.apache.ignite.ml.tree.boosting.GDBBinaryClassifierOnTreesTrainer) DoubleArrayVectorizer(org.apache.ignite.ml.dataset.feature.extractor.impl.DoubleArrayVectorizer) GDBModel(org.apache.ignite.ml.composition.boosting.GDBModel) NotNull(org.jetbrains.annotations.NotNull) Path(java.nio.file.Path) Vectorizer(org.apache.ignite.ml.dataset.feature.extractor.Vectorizer) DoubleArrayVectorizer(org.apache.ignite.ml.dataset.feature.extractor.impl.DoubleArrayVectorizer) GDBTrainer(org.apache.ignite.ml.composition.boosting.GDBTrainer) GDBModel(org.apache.ignite.ml.composition.boosting.GDBModel) GDBBinaryClassifierOnTreesTrainer(org.apache.ignite.ml.tree.boosting.GDBBinaryClassifierOnTreesTrainer) MeanAbsValueConvergenceCheckerFactory(org.apache.ignite.ml.composition.boosting.convergence.mean.MeanAbsValueConvergenceCheckerFactory) Ignite(org.apache.ignite.Ignite)

Example 2 with GDBBinaryClassifierOnTreesTrainer

use of org.apache.ignite.ml.tree.boosting.GDBBinaryClassifierOnTreesTrainer in project ignite by apache.

the class GDBOnTreesClassificationTrainerExample method main.

/**
 * Run example.
 *
 * @param args Command line arguments, none required.
 */
public static void main(String... args) {
    System.out.println();
    System.out.println(">>> GDB classification trainer example started.");
    // Start ignite grid.
    try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) {
        System.out.println(">>> Ignite grid started.");
        // Create cache with training data.
        CacheConfiguration<Integer, double[]> trainingSetCfg = createCacheConfiguration();
        IgniteCache<Integer, double[]> trainingSet = null;
        try {
            trainingSet = fillTrainingData(ignite, trainingSetCfg);
            // Create classification trainer.
            GDBTrainer trainer = new GDBBinaryClassifierOnTreesTrainer(1.0, 300, 2, 0.).withCheckConvergenceStgyFactory(new MeanAbsValueConvergenceCheckerFactory(0.1));
            // Train decision tree model.
            GDBModel mdl = trainer.fit(ignite, trainingSet, new DoubleArrayVectorizer<Integer>().labeled(Vectorizer.LabelCoordinate.LAST));
            System.out.println(">>> ---------------------------------");
            System.out.println(">>> | Prediction\t| Valid answer\t|");
            System.out.println(">>> ---------------------------------");
            // Calculate score.
            for (int x = -5; x < 5; x++) {
                double predicted = mdl.predict(VectorUtils.of(x));
                System.out.printf(">>> | %.4f\t\t| %.4f\t\t|\n", predicted, Math.sin(x) < 0 ? 0.0 : 1.0);
            }
            System.out.println(">>> ---------------------------------");
            System.out.println(">>> Count of trees = " + mdl.getModels().size());
            System.out.println(">>> ---------------------------------");
            System.out.println(">>> GDB classification trainer example completed.");
        } finally {
            trainingSet.destroy();
        }
    } finally {
        System.out.flush();
    }
}
Also used : MeanAbsValueConvergenceCheckerFactory(org.apache.ignite.ml.composition.boosting.convergence.mean.MeanAbsValueConvergenceCheckerFactory) DoubleArrayVectorizer(org.apache.ignite.ml.dataset.feature.extractor.impl.DoubleArrayVectorizer) GDBTrainer(org.apache.ignite.ml.composition.boosting.GDBTrainer) GDBModel(org.apache.ignite.ml.composition.boosting.GDBModel) Ignite(org.apache.ignite.Ignite) GDBBinaryClassifierOnTreesTrainer(org.apache.ignite.ml.tree.boosting.GDBBinaryClassifierOnTreesTrainer)

Example 3 with GDBBinaryClassifierOnTreesTrainer

use of org.apache.ignite.ml.tree.boosting.GDBBinaryClassifierOnTreesTrainer in project ignite by apache.

the class TargetEncoderExample method main.

/**
 * Run example.
 */
public static void main(String[] args) {
    System.out.println();
    System.out.println(">>> Train Gradient Boosing Decision Tree model on amazon-employee-access-challenge_train.csv dataset.");
    try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) {
        try {
            IgniteCache<Integer, Object[]> dataCache = new SandboxMLCache(ignite).fillObjectCacheWithCategoricalData(MLSandboxDatasets.AMAZON_EMPLOYEE_ACCESS);
            Set<Integer> featuresIndexies = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9));
            Set<Integer> targetEncodedfeaturesIndexies = new HashSet<>(Arrays.asList(1, 5, 6));
            Integer targetIndex = 0;
            final Vectorizer<Integer, Object[], Integer, Object> vectorizer = new ObjectArrayVectorizer<Integer>(featuresIndexies.toArray(new Integer[0])).labeled(targetIndex);
            Preprocessor<Integer, Object[]> strEncoderPreprocessor = new EncoderTrainer<Integer, Object[]>().withEncoderType(EncoderType.STRING_ENCODER).withEncodedFeature(0).withEncodedFeatures(featuresIndexies).fit(ignite, dataCache, vectorizer);
            Preprocessor<Integer, Object[]> targetEncoderProcessor = new EncoderTrainer<Integer, Object[]>().withEncoderType(EncoderType.TARGET_ENCODER).labeled(0).withEncodedFeatures(targetEncodedfeaturesIndexies).minSamplesLeaf(1).minCategorySize(1L).smoothing(1d).fit(ignite, dataCache, strEncoderPreprocessor);
            Preprocessor<Integer, Object[]> lbEncoderPreprocessor = new EncoderTrainer<Integer, Object[]>().withEncoderType(EncoderType.LABEL_ENCODER).fit(ignite, dataCache, targetEncoderProcessor);
            GDBTrainer trainer = new GDBBinaryClassifierOnTreesTrainer(0.5, 500, 4, 0.).withCheckConvergenceStgyFactory(new MedianOfMedianConvergenceCheckerFactory(0.1));
            // Train model.
            ModelsComposition mdl = trainer.fit(ignite, dataCache, lbEncoderPreprocessor);
            System.out.println("\n>>> Trained model: " + mdl);
            double accuracy = Evaluator.evaluate(dataCache, mdl, lbEncoderPreprocessor, new Accuracy());
            System.out.println("\n>>> Accuracy " + accuracy);
            System.out.println("\n>>> Test Error " + (1 - accuracy));
            System.out.println(">>> Train Gradient Boosing Decision Tree model on amazon-employee-access-challenge_train.csv dataset.");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    } finally {
        System.out.flush();
    }
}
Also used : SandboxMLCache(org.apache.ignite.examples.ml.util.SandboxMLCache) GDBTrainer(org.apache.ignite.ml.composition.boosting.GDBTrainer) FileNotFoundException(java.io.FileNotFoundException) ModelsComposition(org.apache.ignite.ml.composition.ModelsComposition) GDBBinaryClassifierOnTreesTrainer(org.apache.ignite.ml.tree.boosting.GDBBinaryClassifierOnTreesTrainer) Accuracy(org.apache.ignite.ml.selection.scoring.metric.classification.Accuracy) MedianOfMedianConvergenceCheckerFactory(org.apache.ignite.ml.composition.boosting.convergence.median.MedianOfMedianConvergenceCheckerFactory) Ignite(org.apache.ignite.Ignite) EncoderTrainer(org.apache.ignite.ml.preprocessing.encoding.EncoderTrainer) HashSet(java.util.HashSet)

Example 4 with GDBBinaryClassifierOnTreesTrainer

use of org.apache.ignite.ml.tree.boosting.GDBBinaryClassifierOnTreesTrainer in project ignite by apache.

the class Step_11_Boosting method main.

/**
 * Run example.
 */
public static void main(String[] args) {
    System.out.println();
    System.out.println(">>> Tutorial step 11 (Boosting) example started.");
    try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) {
        try {
            IgniteCache<Integer, Vector> dataCache = TitanicUtils.readPassengers(ignite);
            // Extracts "pclass", "sibsp", "parch", "sex", "embarked", "age", "fare".
            final Vectorizer<Integer, Vector, Integer, Double> vectorizer = new DummyVectorizer<Integer>(0, 3, 4, 5, 6, 8, 10).labeled(1);
            TrainTestSplit<Integer, Vector> split = new TrainTestDatasetSplitter<Integer, Vector>().split(0.75);
            Preprocessor<Integer, Vector> strEncoderPreprocessor = new EncoderTrainer<Integer, Vector>().withEncoderType(EncoderType.STRING_ENCODER).withEncodedFeature(1).withEncodedFeature(// <--- Changed index here.
            6).fit(ignite, dataCache, vectorizer);
            Preprocessor<Integer, Vector> imputingPreprocessor = new ImputerTrainer<Integer, Vector>().fit(ignite, dataCache, strEncoderPreprocessor);
            Preprocessor<Integer, Vector> minMaxScalerPreprocessor = new MinMaxScalerTrainer<Integer, Vector>().fit(ignite, dataCache, imputingPreprocessor);
            Preprocessor<Integer, Vector> normalizationPreprocessor = new NormalizationTrainer<Integer, Vector>().withP(1).fit(ignite, dataCache, minMaxScalerPreprocessor);
            // Create classification trainer.
            GDBTrainer trainer = new GDBBinaryClassifierOnTreesTrainer(0.5, 500, 4, 0.).withCheckConvergenceStgyFactory(new MedianOfMedianConvergenceCheckerFactory(0.1));
            // Train decision tree model.
            GDBModel mdl = trainer.fit(ignite, dataCache, split.getTrainFilter(), normalizationPreprocessor);
            System.out.println("\n>>> Trained model: " + mdl.toString(true));
            double accuracy = Evaluator.evaluate(dataCache, split.getTestFilter(), mdl, normalizationPreprocessor, MetricName.ACCURACY);
            System.out.println("\n>>> Accuracy " + accuracy);
            System.out.println("\n>>> Test Error " + (1 - accuracy));
            System.out.println(">>> Tutorial step 11 (Boosting) example completed.");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    } finally {
        System.out.flush();
    }
}
Also used : GDBTrainer(org.apache.ignite.ml.composition.boosting.GDBTrainer) GDBModel(org.apache.ignite.ml.composition.boosting.GDBModel) FileNotFoundException(java.io.FileNotFoundException) NormalizationTrainer(org.apache.ignite.ml.preprocessing.normalization.NormalizationTrainer) GDBBinaryClassifierOnTreesTrainer(org.apache.ignite.ml.tree.boosting.GDBBinaryClassifierOnTreesTrainer) MedianOfMedianConvergenceCheckerFactory(org.apache.ignite.ml.composition.boosting.convergence.median.MedianOfMedianConvergenceCheckerFactory) Ignite(org.apache.ignite.Ignite) EncoderTrainer(org.apache.ignite.ml.preprocessing.encoding.EncoderTrainer) Vector(org.apache.ignite.ml.math.primitives.vector.Vector)

Example 5 with GDBBinaryClassifierOnTreesTrainer

use of org.apache.ignite.ml.tree.boosting.GDBBinaryClassifierOnTreesTrainer in project ignite by apache.

the class GDBTrainerTest method testClassifier.

/**
 */
private void testClassifier(BiFunction<GDBTrainer, Map<Integer, double[]>, IgniteModel<Vector, Double>> fitter) {
    int sampleSize = 100;
    double[] xs = new double[sampleSize];
    double[] ys = new double[sampleSize];
    for (int i = 0; i < sampleSize; i++) {
        xs[i] = i;
        ys[i] = ((int) (xs[i] / 10.0) % 2) == 0 ? -1.0 : 1.0;
    }
    Map<Integer, double[]> learningSample = new HashMap<>();
    for (int i = 0; i < sampleSize; i++) learningSample.put(i, new double[] { xs[i], ys[i] });
    GDBTrainer trainer = new GDBBinaryClassifierOnTreesTrainer(0.3, 500, 3, 0.0).withUsingIdx(true).withCheckConvergenceStgyFactory(new MeanAbsValueConvergenceCheckerFactory(0.3));
    IgniteModel<Vector, Double> mdl = fitter.apply(trainer, learningSample);
    int errorsCnt = 0;
    for (int j = 0; j < sampleSize; j++) {
        double x = xs[j];
        double y = ys[j];
        double p = mdl.predict(VectorUtils.of(x));
        if (p != y)
            errorsCnt++;
    }
    assertEquals(0, errorsCnt);
    assertTrue(mdl instanceof ModelsComposition);
    ModelsComposition composition = (ModelsComposition) mdl;
    composition.getModels().forEach(m -> assertTrue(m instanceof DecisionTreeModel));
    assertTrue(composition.getModels().size() < 500);
    assertTrue(composition.getPredictionsAggregator() instanceof WeightedPredictionsAggregator);
    trainer = trainer.withCheckConvergenceStgyFactory(new ConvergenceCheckerStubFactory());
    assertEquals(500, ((ModelsComposition) fitter.apply(trainer, learningSample)).getModels().size());
}
Also used : HashMap(java.util.HashMap) DecisionTreeModel(org.apache.ignite.ml.tree.DecisionTreeModel) WeightedPredictionsAggregator(org.apache.ignite.ml.composition.predictionsaggregator.WeightedPredictionsAggregator) ModelsComposition(org.apache.ignite.ml.composition.ModelsComposition) GDBBinaryClassifierOnTreesTrainer(org.apache.ignite.ml.tree.boosting.GDBBinaryClassifierOnTreesTrainer) MeanAbsValueConvergenceCheckerFactory(org.apache.ignite.ml.composition.boosting.convergence.mean.MeanAbsValueConvergenceCheckerFactory) ConvergenceCheckerStubFactory(org.apache.ignite.ml.composition.boosting.convergence.simple.ConvergenceCheckerStubFactory) Vector(org.apache.ignite.ml.math.primitives.vector.Vector)

Aggregations

GDBBinaryClassifierOnTreesTrainer (org.apache.ignite.ml.tree.boosting.GDBBinaryClassifierOnTreesTrainer)6 Ignite (org.apache.ignite.Ignite)4 GDBTrainer (org.apache.ignite.ml.composition.boosting.GDBTrainer)4 MeanAbsValueConvergenceCheckerFactory (org.apache.ignite.ml.composition.boosting.convergence.mean.MeanAbsValueConvergenceCheckerFactory)4 ModelsComposition (org.apache.ignite.ml.composition.ModelsComposition)3 GDBModel (org.apache.ignite.ml.composition.boosting.GDBModel)3 DoubleArrayVectorizer (org.apache.ignite.ml.dataset.feature.extractor.impl.DoubleArrayVectorizer)3 Vector (org.apache.ignite.ml.math.primitives.vector.Vector)3 FileNotFoundException (java.io.FileNotFoundException)2 HashMap (java.util.HashMap)2 MedianOfMedianConvergenceCheckerFactory (org.apache.ignite.ml.composition.boosting.convergence.median.MedianOfMedianConvergenceCheckerFactory)2 ConvergenceCheckerStubFactory (org.apache.ignite.ml.composition.boosting.convergence.simple.ConvergenceCheckerStubFactory)2 WeightedPredictionsAggregator (org.apache.ignite.ml.composition.predictionsaggregator.WeightedPredictionsAggregator)2 Vectorizer (org.apache.ignite.ml.dataset.feature.extractor.Vectorizer)2 VectorUtils (org.apache.ignite.ml.math.primitives.vector.VectorUtils)2 EncoderTrainer (org.apache.ignite.ml.preprocessing.encoding.EncoderTrainer)2 DecisionTreeModel (org.apache.ignite.ml.tree.DecisionTreeModel)2 IOException (java.io.IOException)1 Files (java.nio.file.Files)1 Path (java.nio.file.Path)1