Search in sources :

Example 1 with EvolutionOptimizationStrategy

use of org.apache.ignite.ml.selection.paramgrid.EvolutionOptimizationStrategy in project ignite by apache.

the class Step_16_Genetic_Programming_Search method main.

/**
 * Run example.
 */
public static void main(String[] args) {
    System.out.println();
    System.out.println(">>> Tutorial step 16 (Genetic Programming) 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(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);
            NormalizationTrainer<Integer, Vector> normalizationTrainer = new NormalizationTrainer<Integer, Vector>().withP(1);
            Preprocessor<Integer, Vector> normalizationPreprocessor = normalizationTrainer.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().withParameterSearchStrategy(new EvolutionOptimizationStrategy()).addHyperParam("p", normalizationTrainer::withP, new Double[] { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0 }).addHyperParam("maxDeep", trainerCV::withMaxDeep, new Double[] { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0 }).addHyperParam("minImpurityDecrease", trainerCV::withMinImpurityDecrease, new Double[] { 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0 });
            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 16 (Genetic Programming) example completed.");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    } finally {
        System.out.flush();
    }
}
Also used : DecisionTreeModel(org.apache.ignite.ml.tree.DecisionTreeModel) FileNotFoundException(java.io.FileNotFoundException) EvolutionOptimizationStrategy(org.apache.ignite.ml.selection.paramgrid.EvolutionOptimizationStrategy) Ignite(org.apache.ignite.Ignite) 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) ParamGrid(org.apache.ignite.ml.selection.paramgrid.ParamGrid) DecisionTreeClassificationTrainer(org.apache.ignite.ml.tree.DecisionTreeClassificationTrainer) CrossValidation(org.apache.ignite.ml.selection.cv.CrossValidation)

Example 2 with EvolutionOptimizationStrategy

use of org.apache.ignite.ml.selection.paramgrid.EvolutionOptimizationStrategy in project ignite by apache.

the class Step_17_Parallel_Genetic_Programming_Search method main.

/**
 * Run example.
 */
public static void main(String[] args) {
    System.out.println();
    System.out.println(">>> Tutorial step 17 (Parallel Genetic Programming) 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(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);
            NormalizationTrainer<Integer, Vector> normalizationTrainer = new NormalizationTrainer<Integer, Vector>().withP(1);
            Preprocessor<Integer, Vector> normalizationPreprocessor = normalizationTrainer.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().withParameterSearchStrategy(new EvolutionOptimizationStrategy()).addHyperParam("p", normalizationTrainer::withP, new Double[] { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0 }).addHyperParam("maxDeep", trainerCV::withMaxDeep, new Double[] { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0 }).addHyperParam("minImpurityDecrease", trainerCV::withMinImpurityDecrease, new Double[] { 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0 });
            scoreCalculator.withIgnite(ignite).withUpstreamCache(dataCache).withEnvironmentBuilder(LearningEnvironmentBuilder.defaultBuilder().withParallelismStrategyTypeDependency(ParallelismStrategy.ON_DEFAULT_POOL).withLoggingFactoryDependency(ConsoleLogger.Factory.LOW)).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 17 (Parallel Genetic Programming) example completed.");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    } finally {
        System.out.flush();
    }
}
Also used : DecisionTreeModel(org.apache.ignite.ml.tree.DecisionTreeModel) FileNotFoundException(java.io.FileNotFoundException) EvolutionOptimizationStrategy(org.apache.ignite.ml.selection.paramgrid.EvolutionOptimizationStrategy) Ignite(org.apache.ignite.Ignite) 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) ParamGrid(org.apache.ignite.ml.selection.paramgrid.ParamGrid) DecisionTreeClassificationTrainer(org.apache.ignite.ml.tree.DecisionTreeClassificationTrainer) CrossValidation(org.apache.ignite.ml.selection.cv.CrossValidation)

Example 3 with EvolutionOptimizationStrategy

use of org.apache.ignite.ml.selection.paramgrid.EvolutionOptimizationStrategy in project ignite by apache.

the class AbstractCrossValidation method scoreEvolutionAlgorithmSearchHyperparameterOptimization.

/**
 * Finds the best set of hyper-parameters based on Genetic Programming approach.
 */
private CrossValidationResult scoreEvolutionAlgorithmSearchHyperparameterOptimization() {
    EvolutionOptimizationStrategy stgy = (EvolutionOptimizationStrategy) paramGrid.getHyperParameterTuningStrategy();
    List<Double[]> paramSets = new ParameterSetGenerator(paramGrid.getParamValuesByParamIdx()).generate();
    // initialization
    List<Double[]> paramSetsCp = new ArrayList<>(paramSets);
    Collections.shuffle(paramSetsCp, new Random(stgy.getSeed()));
    int sizeOfPopulation = 20;
    List<Double[]> rndParamSets = paramSetsCp.subList(0, sizeOfPopulation);
    CrossValidationResult cvRes = new CrossValidationResult();
    Function<Chromosome, Double> fitnessFunction = (Chromosome chromosome) -> {
        TaskResult tr = calculateScoresForFixedParamSet(chromosome.toDoubleArray());
        cvRes.addScores(tr.locScores, tr.paramMap);
        return Arrays.stream(tr.locScores).average().orElse(Double.MIN_VALUE);
    };
    // TODO: common seed for shared lambdas can produce the same value on each function call? or sequent?
    Random rnd = new Random(stgy.getSeed());
    BiFunction<Integer, Double, Double> mutator = (Integer geneIdx, Double geneValue) -> {
        Double newGeneVal;
        Double[] possibleGeneValues = paramGrid.getParamRawData().get(geneIdx);
        newGeneVal = possibleGeneValues[rnd.nextInt(possibleGeneValues.length)];
        return newGeneVal;
    };
    GeneticAlgorithm ga = new GeneticAlgorithm(rndParamSets);
    ga.withFitnessFunction(fitnessFunction).withMutationOperator(mutator).withAmountOfEliteChromosomes(stgy.getNumberOfEliteChromosomes()).withCrossingoverProbability(stgy.getCrossingoverProbability()).withCrossoverStgy(stgy.getCrossoverStgy()).withAmountOfGenerations(stgy.getNumberOfGenerations()).withSelectionStgy(stgy.getSelectionStgy()).withMutationProbability(stgy.getMutationProbability());
    if (environment.parallelismStrategy().getParallelism() > 1)
        ga.runParallel(environment);
    else
        ga.run();
    return cvRes;
}
Also used : ArrayList(java.util.ArrayList) Chromosome(org.apache.ignite.ml.util.genetic.Chromosome) ParameterSetGenerator(org.apache.ignite.ml.selection.paramgrid.ParameterSetGenerator) EvolutionOptimizationStrategy(org.apache.ignite.ml.selection.paramgrid.EvolutionOptimizationStrategy) GeneticAlgorithm(org.apache.ignite.ml.util.genetic.GeneticAlgorithm) Random(java.util.Random)

Aggregations

EvolutionOptimizationStrategy (org.apache.ignite.ml.selection.paramgrid.EvolutionOptimizationStrategy)3 FileNotFoundException (java.io.FileNotFoundException)2 Ignite (org.apache.ignite.Ignite)2 Vector (org.apache.ignite.ml.math.primitives.vector.Vector)2 EncoderTrainer (org.apache.ignite.ml.preprocessing.encoding.EncoderTrainer)2 CrossValidation (org.apache.ignite.ml.selection.cv.CrossValidation)2 CrossValidationResult (org.apache.ignite.ml.selection.cv.CrossValidationResult)2 ParamGrid (org.apache.ignite.ml.selection.paramgrid.ParamGrid)2 DecisionTreeClassificationTrainer (org.apache.ignite.ml.tree.DecisionTreeClassificationTrainer)2 DecisionTreeModel (org.apache.ignite.ml.tree.DecisionTreeModel)2 ArrayList (java.util.ArrayList)1 Random (java.util.Random)1 ParameterSetGenerator (org.apache.ignite.ml.selection.paramgrid.ParameterSetGenerator)1 Chromosome (org.apache.ignite.ml.util.genetic.Chromosome)1 GeneticAlgorithm (org.apache.ignite.ml.util.genetic.GeneticAlgorithm)1