use of org.apache.ignite.ml.tree.DecisionTreeModel in project ignite by apache.
the class Step_2_Imputing method main.
/**
* Run example.
*/
public static void main(String[] args) {
System.out.println();
System.out.println(">>> Tutorial step 2 (imputing) example started.");
try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) {
try {
IgniteCache<Integer, Vector> dataCache = TitanicUtils.readPassengers(ignite);
final Vectorizer<Integer, Vector, Integer, Double> vectorizer = new DummyVectorizer<Integer>(0, 5, 6).labeled(1);
Preprocessor<Integer, Vector> imputingPreprocessor = new ImputerTrainer<Integer, Vector>().fit(ignite, dataCache, // "pclass", "sibsp", "parch"
vectorizer);
DecisionTreeClassificationTrainer trainer = new DecisionTreeClassificationTrainer(5, 0);
// Train decision tree model.
DecisionTreeModel mdl = trainer.fit(ignite, dataCache, vectorizer);
System.out.println("\n>>> Trained model: " + mdl);
double accuracy = Evaluator.evaluate(dataCache, mdl, imputingPreprocessor, new Accuracy<>());
System.out.println("\n>>> Accuracy " + accuracy);
System.out.println("\n>>> Test Error " + (1 - accuracy));
System.out.println(">>> Tutorial step 2 (imputing) example completed.");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} finally {
System.out.flush();
}
}
use of org.apache.ignite.ml.tree.DecisionTreeModel in project ignite by apache.
the class CrossValidationExample method main.
/**
* Executes example.
*
* @param args Command line arguments, none required.
*/
public static void main(String... args) {
System.out.println(">>> Cross validation score calculator 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, LabeledVector<Double>> trainingSetCfg = new CacheConfiguration<>();
trainingSetCfg.setName("TRAINING_SET");
trainingSetCfg.setAffinity(new RendezvousAffinityFunction(false, 10));
IgniteCache<Integer, LabeledVector<Double>> trainingSet = null;
try {
trainingSet = ignite.createCache(trainingSetCfg);
Random rnd = new Random(0);
// Fill training data.
for (int i = 0; i < 1000; i++) trainingSet.put(i, generatePoint(rnd));
// Create classification trainer.
DecisionTreeClassificationTrainer trainer = new DecisionTreeClassificationTrainer(4, 0);
LabeledDummyVectorizer<Integer, Double> vectorizer = new LabeledDummyVectorizer<>();
CrossValidation<DecisionTreeModel, Integer, LabeledVector<Double>> scoreCalculator = new CrossValidation<>();
double[] accuracyScores = scoreCalculator.withIgnite(ignite).withUpstreamCache(trainingSet).withTrainer(trainer).withMetric(MetricName.ACCURACY).withPreprocessor(vectorizer).withAmountOfFolds(4).isRunningOnPipeline(false).scoreByFolds();
System.out.println(">>> Accuracy: " + Arrays.toString(accuracyScores));
double[] balancedAccuracyScores = scoreCalculator.withMetric(MetricName.ACCURACY).scoreByFolds();
System.out.println(">>> Balanced Accuracy: " + Arrays.toString(balancedAccuracyScores));
System.out.println(">>> Cross validation score calculator example completed.");
} finally {
trainingSet.destroy();
}
} finally {
System.out.flush();
}
}
use of org.apache.ignite.ml.tree.DecisionTreeModel in project ignite by apache.
the class Step_14_Parallel_Brute_Force_Search method main.
/**
* Run example.
*/
public static void main(String[] args) {
System.out.println();
System.out.println(">>> Tutorial step 14 (Brute Force) 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 BruteForceStrategy()).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).isRunningOnPipeline(false).withMetric(MetricName.ACCURACY).withFilter(split.getTrainFilter()).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 14 (Brute Force) example completed.");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} finally {
System.out.flush();
}
}
use of org.apache.ignite.ml.tree.DecisionTreeModel 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();
}
}
use of org.apache.ignite.ml.tree.DecisionTreeModel 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());
}
Aggregations