Search in sources :

Example 31 with DecisionTreeModel

use of org.apache.ignite.ml.tree.DecisionTreeModel in project ignite by apache.

the class Step_8_CV_with_Param_Grid method main.

/**
 * Run example.
 */
public static void main(String[] args) {
    System.out.println();
    System.out.println(">>> Tutorial step 8 (cross-validation with param grid) 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);
            // Tune hyper-parameters with K-fold Cross-Validation on the split training set.
            DecisionTreeClassificationTrainer trainerCV = new DecisionTreeClassificationTrainer();
            CrossValidation<DecisionTreeModel, Integer, Vector> scoreCalculator = new CrossValidation<>();
            ParamGrid paramGrid = new ParamGrid().addHyperParam("maxDeep", trainerCV::withMaxDeep, new Double[] { 1.0, 2.0, 3.0, 4.0, 5.0, 10.0 }).addHyperParam("minImpurityDecrease", trainerCV::withMinImpurityDecrease, new Double[] { 0.0, 0.25, 0.5 });
            scoreCalculator.withIgnite(ignite).withUpstreamCache(dataCache).withTrainer(trainerCV).withMetric(MetricName.ACCURACY).withFilter(split.getTrainFilter()).isRunningOnPipeline(false).withPreprocessor(normalizationPreprocessor).withAmountOfFolds(3).withParamGrid(paramGrid);
            CrossValidationResult crossValidationRes = scoreCalculator.tuneHyperParameters();
            System.out.println("Train with maxDeep: " + crossValidationRes.getBest("maxDeep") + " and minImpurityDecrease: " + crossValidationRes.getBest("minImpurityDecrease"));
            DecisionTreeClassificationTrainer trainer = new DecisionTreeClassificationTrainer().withMaxDeep(crossValidationRes.getBest("maxDeep")).withMinImpurityDecrease(crossValidationRes.getBest("minImpurityDecrease"));
            System.out.println(crossValidationRes);
            System.out.println("Best score: " + Arrays.toString(crossValidationRes.getBestScore()));
            System.out.println("Best hyper params: " + crossValidationRes.getBestHyperParams());
            System.out.println("Best average score: " + crossValidationRes.getBestAvgScore());
            crossValidationRes.getScoringBoard().forEach((hyperParams, score) -> System.out.println("Score " + Arrays.toString(score) + " for hyper params " + hyperParams));
            // Train decision tree model.
            DecisionTreeModel bestMdl = trainer.fit(ignite, dataCache, split.getTrainFilter(), normalizationPreprocessor);
            System.out.println("\n>>> Trained model: " + bestMdl);
            double accuracy = Evaluator.evaluate(dataCache, split.getTestFilter(), bestMdl, normalizationPreprocessor, new Accuracy<>());
            System.out.println("\n>>> Accuracy " + accuracy);
            System.out.println("\n>>> Test Error " + (1 - accuracy));
            System.out.println(">>> Tutorial step 8 (cross-validation with param grid) example completed.");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    } finally {
        System.out.flush();
    }
}
Also used : DecisionTreeModel(org.apache.ignite.ml.tree.DecisionTreeModel) FileNotFoundException(java.io.FileNotFoundException) NormalizationTrainer(org.apache.ignite.ml.preprocessing.normalization.NormalizationTrainer) ParamGrid(org.apache.ignite.ml.selection.paramgrid.ParamGrid) DecisionTreeClassificationTrainer(org.apache.ignite.ml.tree.DecisionTreeClassificationTrainer) Ignite(org.apache.ignite.Ignite) CrossValidation(org.apache.ignite.ml.selection.cv.CrossValidation) EncoderTrainer(org.apache.ignite.ml.preprocessing.encoding.EncoderTrainer) Vector(org.apache.ignite.ml.math.primitives.vector.Vector) CrossValidationResult(org.apache.ignite.ml.selection.cv.CrossValidationResult)

Example 32 with DecisionTreeModel

use of org.apache.ignite.ml.tree.DecisionTreeModel in project ignite by apache.

the class GDBTrainerTest method testFitRegression.

/**
 */
@Test
public void testFitRegression() {
    int size = 100;
    double[] xs = new double[size];
    double[] ys = new double[size];
    double from = -5.0;
    double to = 5.0;
    double step = Math.abs(from - to) / size;
    Map<Integer, double[]> learningSample = new HashMap<>();
    for (int i = 0; i < size; i++) {
        xs[i] = from + step * i;
        ys[i] = 2 * xs[i];
        learningSample.put(i, new double[] { xs[i], ys[i] });
    }
    GDBTrainer trainer = new GDBRegressionOnTreesTrainer(1.0, 2000, 3, 0.0).withUsingIdx(true);
    IgniteModel<Vector, Double> mdl = trainer.fit(learningSample, 1, new DoubleArrayVectorizer<Integer>().labeled(Vectorizer.LabelCoordinate.LAST));
    double mse = 0.0;
    for (int j = 0; j < size; j++) {
        double x = xs[j];
        double y = ys[j];
        double p = mdl.predict(VectorUtils.of(x));
        mse += Math.pow(y - p, 2);
    }
    mse /= size;
    assertEquals(0.0, mse, 0.0001);
    ModelsComposition composition = (ModelsComposition) mdl;
    assertTrue(!composition.toString().isEmpty());
    assertTrue(!composition.toString(true).isEmpty());
    assertTrue(!composition.toString(false).isEmpty());
    composition.getModels().forEach(m -> assertTrue(m instanceof DecisionTreeModel));
    assertEquals(2000, composition.getModels().size());
    assertTrue(composition.getPredictionsAggregator() instanceof WeightedPredictionsAggregator);
    trainer = trainer.withCheckConvergenceStgyFactory(new MeanAbsValueConvergenceCheckerFactory(0.1));
    assertTrue(trainer.fit(learningSample, 1, new DoubleArrayVectorizer<Integer>().labeled(1)).getModels().size() < 2000);
}
Also used : DoubleArrayVectorizer(org.apache.ignite.ml.dataset.feature.extractor.impl.DoubleArrayVectorizer) GDBRegressionOnTreesTrainer(org.apache.ignite.ml.tree.boosting.GDBRegressionOnTreesTrainer) 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) MeanAbsValueConvergenceCheckerFactory(org.apache.ignite.ml.composition.boosting.convergence.mean.MeanAbsValueConvergenceCheckerFactory) Vector(org.apache.ignite.ml.math.primitives.vector.Vector) TrainerTest(org.apache.ignite.ml.common.TrainerTest) Test(org.junit.Test)

Aggregations

DecisionTreeModel (org.apache.ignite.ml.tree.DecisionTreeModel)32 Ignite (org.apache.ignite.Ignite)27 DecisionTreeClassificationTrainer (org.apache.ignite.ml.tree.DecisionTreeClassificationTrainer)26 Vector (org.apache.ignite.ml.math.primitives.vector.Vector)20 FileNotFoundException (java.io.FileNotFoundException)18 EncoderTrainer (org.apache.ignite.ml.preprocessing.encoding.EncoderTrainer)12 CrossValidation (org.apache.ignite.ml.selection.cv.CrossValidation)9 CrossValidationResult (org.apache.ignite.ml.selection.cv.CrossValidationResult)7 ParamGrid (org.apache.ignite.ml.selection.paramgrid.ParamGrid)7 CacheConfiguration (org.apache.ignite.configuration.CacheConfiguration)6 LabeledVector (org.apache.ignite.ml.structures.LabeledVector)6 HashMap (java.util.HashMap)5 RendezvousAffinityFunction (org.apache.ignite.cache.affinity.rendezvous.RendezvousAffinityFunction)5 NormalizationTrainer (org.apache.ignite.ml.preprocessing.normalization.NormalizationTrainer)5 Test (org.junit.Test)4 Random (java.util.Random)3 SandboxMLCache (org.apache.ignite.examples.ml.util.SandboxMLCache)3 LabeledDummyVectorizer (org.apache.ignite.ml.dataset.feature.extractor.impl.LabeledDummyVectorizer)3 Path (java.nio.file.Path)2 List (java.util.List)2