Search in sources :

Example 6 with LogisticRegressionSGDTrainer

use of org.apache.ignite.ml.regressions.logistic.LogisticRegressionSGDTrainer in project ignite by apache.

the class Step_12_Model_Update method main.

/**
 * Run example.
 */
public static void main(String[] args) {
    System.out.println();
    System.out.println(">>> Tutorial step 12 (Model update) 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.5);
            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);
            LogisticRegressionSGDTrainer trainer = new LogisticRegressionSGDTrainer().withUpdatesStgy(new UpdatesStrategy<>(new SimpleGDUpdateCalculator(0.2), SimpleGDParameterUpdate.SUM_LOCAL, SimpleGDParameterUpdate.AVG)).withMaxIterations(100000).withLocIterations(100).withBatchSize(10).withSeed(123L);
            // Train LogReg model.
            LogisticRegressionModel mdl = trainer.fit(ignite, dataCache, split.getTrainFilter(), normalizationPreprocessor);
            // Update LogReg model with new portion of data.
            LogisticRegressionModel mdl2 = trainer.update(mdl, ignite, dataCache, split.getTestFilter(), normalizationPreprocessor);
            System.out.println("\n>>> Trained model: " + mdl);
            double accuracy = Evaluator.evaluate(dataCache, mdl2, normalizationPreprocessor, MetricName.ACCURACY);
            System.out.println("\n>>> Accuracy " + accuracy);
            System.out.println("\n>>> Test Error " + (1 - accuracy));
            System.out.println(">>> Tutorial step 12 (Model update) example completed.");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    } finally {
        System.out.flush();
    }
}
Also used : LogisticRegressionSGDTrainer(org.apache.ignite.ml.regressions.logistic.LogisticRegressionSGDTrainer) FileNotFoundException(java.io.FileNotFoundException) LogisticRegressionModel(org.apache.ignite.ml.regressions.logistic.LogisticRegressionModel) NormalizationTrainer(org.apache.ignite.ml.preprocessing.normalization.NormalizationTrainer) SimpleGDUpdateCalculator(org.apache.ignite.ml.optimization.updatecalculators.SimpleGDUpdateCalculator) Ignite(org.apache.ignite.Ignite) EncoderTrainer(org.apache.ignite.ml.preprocessing.encoding.EncoderTrainer) Vector(org.apache.ignite.ml.math.primitives.vector.Vector)

Example 7 with LogisticRegressionSGDTrainer

use of org.apache.ignite.ml.regressions.logistic.LogisticRegressionSGDTrainer in project ignite by apache.

the class LogisticRegressionExportImportExample method main.

/**
 * Run example.
 */
public static void main(String[] args) throws IOException {
    System.out.println();
    System.out.println(">>> Logistic regression model over partitioned dataset usage example started.");
    // Start ignite grid.
    try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) {
        System.out.println("\n>>> Ignite grid started.");
        IgniteCache<Integer, Vector> dataCache = null;
        Path jsonMdlPath = null;
        try {
            dataCache = new SandboxMLCache(ignite).fillCacheWith(MLSandboxDatasets.TWO_CLASSED_IRIS);
            System.out.println("\n>>> Create new logistic regression trainer object.");
            LogisticRegressionSGDTrainer trainer = new LogisticRegressionSGDTrainer().withUpdatesStgy(new UpdatesStrategy<>(new SimpleGDUpdateCalculator(0.2), SimpleGDParameterUpdate.SUM_LOCAL, SimpleGDParameterUpdate.AVG)).withMaxIterations(100000).withLocIterations(100).withBatchSize(10).withSeed(123L);
            System.out.println("\n>>> Perform the training to get the model.");
            Vectorizer<Integer, Vector, Integer, Double> vectorizer = new DummyVectorizer<Integer>().labeled(Vectorizer.LabelCoordinate.FIRST);
            LogisticRegressionModel mdl = trainer.fit(ignite, dataCache, vectorizer);
            System.out.println("\n>>> Exported logistic regression model: " + mdl);
            double accuracy = Evaluator.evaluate(dataCache, mdl, vectorizer, MetricName.ACCURACY);
            System.out.println("\n>>> Accuracy for exported logistic regression model " + accuracy);
            jsonMdlPath = Files.createTempFile(null, null);
            mdl.toJSON(jsonMdlPath);
            LogisticRegressionModel modelImportedFromJSON = LogisticRegressionModel.fromJSON(jsonMdlPath);
            System.out.println("\n>>> Imported logistic regression model: " + modelImportedFromJSON);
            accuracy = Evaluator.evaluate(dataCache, modelImportedFromJSON, vectorizer, MetricName.ACCURACY);
            System.out.println("\n>>> Accuracy for imported logistic regression model " + accuracy);
            System.out.println("\n>>> Logistic regression model over partitioned 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) LogisticRegressionSGDTrainer(org.apache.ignite.ml.regressions.logistic.LogisticRegressionSGDTrainer) SandboxMLCache(org.apache.ignite.examples.ml.util.SandboxMLCache) LogisticRegressionModel(org.apache.ignite.ml.regressions.logistic.LogisticRegressionModel) SimpleGDUpdateCalculator(org.apache.ignite.ml.optimization.updatecalculators.SimpleGDUpdateCalculator) Ignite(org.apache.ignite.Ignite) Vector(org.apache.ignite.ml.math.primitives.vector.Vector)

Example 8 with LogisticRegressionSGDTrainer

use of org.apache.ignite.ml.regressions.logistic.LogisticRegressionSGDTrainer in project ignite by apache.

the class BaggingTest method testNaiveBaggingLogRegression.

/**
 * Test that bagged log regression makes correct predictions.
 */
@Test
public void testNaiveBaggingLogRegression() {
    Map<Integer, double[]> cacheMock = getCacheMock(twoLinearlySeparableClasses);
    DatasetTrainer<LogisticRegressionModel, Double> trainer = new LogisticRegressionSGDTrainer().withUpdatesStgy(new UpdatesStrategy<>(new SimpleGDUpdateCalculator(0.2), SimpleGDParameterUpdate.SUM_LOCAL, SimpleGDParameterUpdate.AVG)).withMaxIterations(30000).withLocIterations(100).withBatchSize(10).withSeed(123L);
    BaggedTrainer<Double> baggedTrainer = TrainerTransformers.makeBagged(trainer, 7, 0.7, 2, 2, new OnMajorityPredictionsAggregator()).withEnvironmentBuilder(TestUtils.testEnvBuilder());
    BaggedModel mdl = baggedTrainer.fit(cacheMock, parts, new DoubleArrayVectorizer<Integer>().labeled(Vectorizer.LabelCoordinate.FIRST));
    Vector weights = ((LogisticRegressionModel) ((AdaptableDatasetModel) ((ModelsParallelComposition) ((AdaptableDatasetModel) mdl.model()).innerModel()).submodels().get(0)).innerModel()).weights();
    TestUtils.assertEquals(firstMdlWeights.get(parts), weights, 0.0);
    TestUtils.assertEquals(0, mdl.predict(VectorUtils.of(100, 10)), PRECISION);
    TestUtils.assertEquals(1, mdl.predict(VectorUtils.of(10, 100)), PRECISION);
}
Also used : LogisticRegressionSGDTrainer(org.apache.ignite.ml.regressions.logistic.LogisticRegressionSGDTrainer) DoubleArrayVectorizer(org.apache.ignite.ml.dataset.feature.extractor.impl.DoubleArrayVectorizer) OnMajorityPredictionsAggregator(org.apache.ignite.ml.composition.predictionsaggregator.OnMajorityPredictionsAggregator) LogisticRegressionModel(org.apache.ignite.ml.regressions.logistic.LogisticRegressionModel) SimpleGDUpdateCalculator(org.apache.ignite.ml.optimization.updatecalculators.SimpleGDUpdateCalculator) AdaptableDatasetModel(org.apache.ignite.ml.trainers.AdaptableDatasetModel) Vector(org.apache.ignite.ml.math.primitives.vector.Vector) TrainerTest(org.apache.ignite.ml.common.TrainerTest) Test(org.junit.Test)

Example 9 with LogisticRegressionSGDTrainer

use of org.apache.ignite.ml.regressions.logistic.LogisticRegressionSGDTrainer in project ignite by apache.

the class CrossValidationTest method testBasicFunctionality.

/**
 */
@Test
public void testBasicFunctionality() {
    Map<Integer, double[]> data = new HashMap<>();
    for (int i = 0; i < twoLinearlySeparableClasses.length; i++) data.put(i, twoLinearlySeparableClasses[i]);
    LogisticRegressionSGDTrainer trainer = new LogisticRegressionSGDTrainer().withUpdatesStgy(new UpdatesStrategy<>(new SimpleGDUpdateCalculator(0.2), SimpleGDParameterUpdate.SUM_LOCAL, SimpleGDParameterUpdate.AVG)).withMaxIterations(100000).withLocIterations(100).withBatchSize(14).withSeed(123L);
    Vectorizer<Integer, double[], Integer, Double> vectorizer = new DoubleArrayVectorizer<Integer>().labeled(Vectorizer.LabelCoordinate.FIRST);
    DebugCrossValidation<LogisticRegressionModel, Integer, double[]> scoreCalculator = new DebugCrossValidation<>();
    int folds = 4;
    scoreCalculator.withUpstreamMap(data).withAmountOfParts(1).withTrainer(trainer).withMetric(MetricName.ACCURACY).withPreprocessor(vectorizer).withAmountOfFolds(folds).isRunningOnPipeline(false);
    double[] scores = scoreCalculator.scoreByFolds();
    assertEquals(0.8389830508474576, scores[0], 1e-6);
    assertEquals(0.9402985074626866, scores[1], 1e-6);
    assertEquals(0.8809523809523809, scores[2], 1e-6);
    assertEquals(0.9921259842519685, scores[3], 1e-6);
}
Also used : LogisticRegressionSGDTrainer(org.apache.ignite.ml.regressions.logistic.LogisticRegressionSGDTrainer) HashMap(java.util.HashMap) LogisticRegressionModel(org.apache.ignite.ml.regressions.logistic.LogisticRegressionModel) SimpleGDUpdateCalculator(org.apache.ignite.ml.optimization.updatecalculators.SimpleGDUpdateCalculator) Test(org.junit.Test)

Example 10 with LogisticRegressionSGDTrainer

use of org.apache.ignite.ml.regressions.logistic.LogisticRegressionSGDTrainer in project ignite by apache.

the class CrossValidationTest method testRandomSearchWithPipeline.

/**
 */
@Test
public void testRandomSearchWithPipeline() {
    Map<Integer, double[]> data = new HashMap<>();
    for (int i = 0; i < twoLinearlySeparableClasses.length; i++) data.put(i, twoLinearlySeparableClasses[i]);
    LogisticRegressionSGDTrainer trainer = new LogisticRegressionSGDTrainer().withUpdatesStgy(new UpdatesStrategy<>(new SimpleGDUpdateCalculator(0.2), SimpleGDParameterUpdate.SUM_LOCAL, SimpleGDParameterUpdate.AVG)).withMaxIterations(100000).withLocIterations(100).withBatchSize(14).withSeed(123L);
    Vectorizer<Integer, double[], Integer, Double> vectorizer = new DoubleArrayVectorizer<Integer>().labeled(Vectorizer.LabelCoordinate.FIRST);
    ParamGrid paramGrid = new ParamGrid().withParameterSearchStrategy(new RandomStrategy().withMaxTries(10).withSeed(1234L).withSatisfactoryFitness(0.9)).addHyperParam("maxIterations", trainer::withMaxIterations, new Double[] { 10.0, 100.0, 1000.0, 10000.0 }).addHyperParam("locIterations", trainer::withLocIterations, new Double[] { 10.0, 100.0, 1000.0, 10000.0 }).addHyperParam("batchSize", trainer::withBatchSize, new Double[] { 1.0, 2.0, 4.0, 8.0, 16.0 });
    Pipeline<Integer, double[], Integer, Double> pipeline = new Pipeline<Integer, double[], Integer, Double>().addVectorizer(vectorizer).addTrainer(trainer);
    DebugCrossValidation<LogisticRegressionModel, Integer, double[]> scoreCalculator = (DebugCrossValidation<LogisticRegressionModel, Integer, double[]>) new DebugCrossValidation<LogisticRegressionModel, Integer, double[]>().withUpstreamMap(data).withAmountOfParts(1).withPipeline(pipeline).withMetric(MetricName.ACCURACY).withPreprocessor(vectorizer).withAmountOfFolds(4).isRunningOnPipeline(true).withParamGrid(paramGrid);
    CrossValidationResult crossValidationRes = scoreCalculator.tuneHyperParameters();
    assertEquals(crossValidationRes.getBestAvgScore(), 0.9343858500738256, 1e-6);
    assertEquals(crossValidationRes.getScoringBoard().size(), 10);
}
Also used : LogisticRegressionSGDTrainer(org.apache.ignite.ml.regressions.logistic.LogisticRegressionSGDTrainer) HashMap(java.util.HashMap) LogisticRegressionModel(org.apache.ignite.ml.regressions.logistic.LogisticRegressionModel) Pipeline(org.apache.ignite.ml.pipeline.Pipeline) ParamGrid(org.apache.ignite.ml.selection.paramgrid.ParamGrid) SimpleGDUpdateCalculator(org.apache.ignite.ml.optimization.updatecalculators.SimpleGDUpdateCalculator) RandomStrategy(org.apache.ignite.ml.selection.paramgrid.RandomStrategy) Test(org.junit.Test)

Aggregations

LogisticRegressionSGDTrainer (org.apache.ignite.ml.regressions.logistic.LogisticRegressionSGDTrainer)14 SimpleGDUpdateCalculator (org.apache.ignite.ml.optimization.updatecalculators.SimpleGDUpdateCalculator)12 LogisticRegressionModel (org.apache.ignite.ml.regressions.logistic.LogisticRegressionModel)12 Vector (org.apache.ignite.ml.math.primitives.vector.Vector)8 Test (org.junit.Test)7 HashMap (java.util.HashMap)6 Ignite (org.apache.ignite.Ignite)6 SandboxMLCache (org.apache.ignite.examples.ml.util.SandboxMLCache)4 TrainerTest (org.apache.ignite.ml.common.TrainerTest)3 ParamGrid (org.apache.ignite.ml.selection.paramgrid.ParamGrid)3 FileNotFoundException (java.io.FileNotFoundException)2 OnMajorityPredictionsAggregator (org.apache.ignite.ml.composition.predictionsaggregator.OnMajorityPredictionsAggregator)2 DoubleArrayVectorizer (org.apache.ignite.ml.dataset.feature.extractor.impl.DoubleArrayVectorizer)2 EncoderTrainer (org.apache.ignite.ml.preprocessing.encoding.EncoderTrainer)2 NormalizationTrainer (org.apache.ignite.ml.preprocessing.normalization.NormalizationTrainer)2 RandomStrategy (org.apache.ignite.ml.selection.paramgrid.RandomStrategy)2 DecisionTreeClassificationTrainer (org.apache.ignite.ml.tree.DecisionTreeClassificationTrainer)2 Path (java.nio.file.Path)1 StackedVectorDatasetTrainer (org.apache.ignite.ml.composition.stacking.StackedVectorDatasetTrainer)1 Pipeline (org.apache.ignite.ml.pipeline.Pipeline)1