You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@flink.apache.org by GitBox <gi...@apache.org> on 2022/05/09 01:23:36 UTC

[GitHub] [flink-ml] weibozhao commented on a diff in pull request #83: [FLINK-27170] Add Transformer and Estimator for OnlineLogisticRegression

weibozhao commented on code in PR #83:
URL: https://github.com/apache/flink-ml/pull/83#discussion_r867573941


##########
flink-ml-lib/src/test/java/org/apache/flink/ml/classification/OnlineLogisticRegressionTest.java:
##########
@@ -0,0 +1,444 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.ml.classification;
+
+import org.apache.flink.api.common.functions.MapFunction;
+import org.apache.flink.api.common.restartstrategy.RestartStrategies;
+import org.apache.flink.api.common.typeinfo.TypeInformation;
+import org.apache.flink.api.common.typeinfo.Types;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.api.java.typeutils.RowTypeInfo;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.ml.classification.logisticregression.LogisticRegression;
+import org.apache.flink.ml.classification.logisticregression.OnlineLogisticRegression;
+import org.apache.flink.ml.classification.logisticregression.OnlineLogisticRegressionModel;
+import org.apache.flink.ml.feature.MinMaxScalerTest;
+import org.apache.flink.ml.linalg.DenseVector;
+import org.apache.flink.ml.linalg.SparseVector;
+import org.apache.flink.ml.linalg.Vectors;
+import org.apache.flink.ml.util.StageTestUtils;
+import org.apache.flink.streaming.api.datastream.DataStream;
+import org.apache.flink.streaming.api.environment.ExecutionCheckpointingOptions;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.streaming.api.functions.source.SourceFunction;
+import org.apache.flink.table.api.Table;
+import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
+import org.apache.flink.table.api.internal.TableImpl;
+import org.apache.flink.test.util.AbstractTestBase;
+import org.apache.flink.types.Row;
+
+import org.apache.commons.collections.IteratorUtils;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static junit.framework.TestCase.assertEquals;
+
+/** Tests {@link OnlineLogisticRegression} and {@link OnlineLogisticRegressionModel}. */
+public class OnlineLogisticRegressionTest extends AbstractTestBase {
+    @Rule public final TemporaryFolder tempFolder = new TemporaryFolder();
+    private StreamExecutionEnvironment env;
+    private StreamTableEnvironment tEnv;
+    private Table trainDenseTable;
+    private static final String LABEL_COL = "label";
+    private static final String PREDICT_COL = "prediction";
+    private static final String FEATURE_COL = "features";
+    private static final String MODEL_VERSION_COL = "modelVersion";
+    private static final double[] ONE_ARRAY = new double[] {1.0, 1.0, 1.0};
+    private static final List<Row> TRAIN_DENSE_ROWS =
+            Arrays.asList(
+                    Row.of(Vectors.dense(0.1, 2.), 0.),
+                    Row.of(Vectors.dense(0.2, 2.), 0.),
+                    Row.of(Vectors.dense(0.3, 2.), 0.),
+                    Row.of(Vectors.dense(0.4, 2.), 0.),
+                    Row.of(Vectors.dense(0.5, 2.), 0.),
+                    Row.of(Vectors.dense(11., 12.), 1.),
+                    Row.of(Vectors.dense(12., 11.), 1.),
+                    Row.of(Vectors.dense(13., 12.), 1.),
+                    Row.of(Vectors.dense(14., 12.), 1.),
+                    Row.of(Vectors.dense(15., 12.), 1.));
+
+    private static final List<Row> PREDICT_DENSE_ROWS =
+            Arrays.asList(
+                    Row.of(Vectors.dense(0.8, 2.7), 0.),
+                    Row.of(Vectors.dense(0.8, 2.4), 0.),
+                    Row.of(Vectors.dense(0.7, 2.3), 0.),
+                    Row.of(Vectors.dense(0.4, 2.7), 0.),
+                    Row.of(Vectors.dense(0.5, 2.8), 0.),
+                    Row.of(Vectors.dense(10.2, 12.1), 1.),
+                    Row.of(Vectors.dense(13.3, 13.1), 1.),
+                    Row.of(Vectors.dense(13.5, 12.2), 1.),
+                    Row.of(Vectors.dense(14.9, 12.5), 1.),
+                    Row.of(Vectors.dense(15.5, 11.2), 1.));
+
+    private static final List<Row> TRAIN_SPARSE_ROWS =
+            Arrays.asList(
+                    Row.of(Vectors.sparse(10, new int[] {1, 3, 4}, ONE_ARRAY), 0.),
+                    Row.of(Vectors.sparse(10, new int[] {0, 2, 3}, ONE_ARRAY), 0.),
+                    Row.of(Vectors.sparse(10, new int[] {0, 3, 4}, ONE_ARRAY), 0.),
+                    Row.of(Vectors.sparse(10, new int[] {2, 3, 4}, ONE_ARRAY), 0.),
+                    Row.of(Vectors.sparse(10, new int[] {1, 3, 4}, ONE_ARRAY), 0.),
+                    Row.of(Vectors.sparse(10, new int[] {6, 7, 8}, ONE_ARRAY), 1.),
+                    Row.of(Vectors.sparse(10, new int[] {6, 8, 9}, ONE_ARRAY), 1.),
+                    Row.of(Vectors.sparse(10, new int[] {5, 8, 9}, ONE_ARRAY), 1.),
+                    Row.of(Vectors.sparse(10, new int[] {5, 6, 8}, ONE_ARRAY), 1.),
+                    Row.of(Vectors.sparse(10, new int[] {5, 6, 7}, ONE_ARRAY), 1.));
+
+    private static final List<Row> PREDICT_SPARSE_ROWS =
+            Arrays.asList(
+                    Row.of(Vectors.sparse(10, new int[] {1, 2, 4}, ONE_ARRAY), 0.),
+                    Row.of(Vectors.sparse(10, new int[] {2, 3, 4}, ONE_ARRAY), 0.),
+                    Row.of(Vectors.sparse(10, new int[] {0, 2, 4}, ONE_ARRAY), 0.),
+                    Row.of(Vectors.sparse(10, new int[] {1, 3, 4}, ONE_ARRAY), 0.),
+                    Row.of(Vectors.sparse(10, new int[] {6, 7, 9}, ONE_ARRAY), 1.),
+                    Row.of(Vectors.sparse(10, new int[] {7, 8, 9}, ONE_ARRAY), 1.),
+                    Row.of(Vectors.sparse(10, new int[] {5, 7, 9}, ONE_ARRAY), 1.),
+                    Row.of(Vectors.sparse(10, new int[] {5, 6, 7}, ONE_ARRAY), 1.),
+                    Row.of(Vectors.sparse(10, new int[] {5, 8, 9}, ONE_ARRAY), 1.));
+
+    private Table initDenseModel;
+
+    @Before
+    public void before() throws Exception {
+        Configuration config = new Configuration();
+        config.set(ExecutionCheckpointingOptions.ENABLE_CHECKPOINTS_AFTER_TASKS_FINISH, true);
+        env = StreamExecutionEnvironment.getExecutionEnvironment(config);
+        env.setParallelism(4);
+        env.enableCheckpointing(100);
+        env.setRestartStrategy(RestartStrategies.noRestart());
+        tEnv = StreamTableEnvironment.create(env);
+        DataStream<Row> dataStream = env.fromCollection(TRAIN_DENSE_ROWS);
+        trainDenseTable = tEnv.fromDataStream(dataStream).as(FEATURE_COL, LABEL_COL);
+        initDenseModel =
+                tEnv.fromDataStream(
+                        env.fromElements(Row.of(new DenseVector(new double[] {0.0, 0.0}), 0L)));
+    }
+
+    @Test
+    public void testFit() throws Exception {
+        Table onlinePredictTable = getTable(1, 1000, TRAIN_DENSE_ROWS, 4, false);
+        Table models =
+                new OnlineLogisticRegression()
+                        .setFeaturesCol(FEATURE_COL)
+                        .setInitialModelData(initDenseModel)
+                        .setGlobalBatchSize(100)
+                        .setLabelCol(LABEL_COL)
+                        .fit(onlinePredictTable)
+                        .getModelData()[0];
+        List<Row> modelList = IteratorUtils.toList(tEnv.toDataStream(models).executeAndCollect());
+        assertEquals(10, modelList.size());
+    }
+
+    @Test
+    public void testFitWithInitLrModel() throws Exception {
+        Table initLrModel =
+                new LogisticRegression()
+                        .setFeaturesCol(FEATURE_COL)
+                        .setLabelCol(LABEL_COL)
+                        .fit(trainDenseTable)
+                        .getModelData()[0];
+        Table onlineTrainTable = getTable(50, 1000, TRAIN_DENSE_ROWS, 4, false);
+        Table models =
+                new OnlineLogisticRegression()
+                        .setFeaturesCol(FEATURE_COL)
+                        .setInitialModelData(initLrModel)
+                        .setGlobalBatchSize(100)
+                        .setLabelCol(LABEL_COL)
+                        .fit(onlineTrainTable)
+                        .getModelData()[0];
+        List<Row> modelList = IteratorUtils.toList(tEnv.toDataStream(models).executeAndCollect());
+        assertEquals(10, modelList.size());
+    }
+
+    @Test
+    public void testDenseFitAndPredict() throws Exception {
+        Table onlineTrainTable = getTable(2, 2000, TRAIN_DENSE_ROWS, 2, false);
+        Table onlinePredictTable = getTable(2, 3000, PREDICT_DENSE_ROWS, 2, false);
+        OnlineLogisticRegressionModel model =
+                new OnlineLogisticRegression()
+                        .setFeaturesCol(FEATURE_COL)
+                        .setInitialModelData(initDenseModel)
+                        .setGlobalBatchSize(500)
+                        .setLabelCol(LABEL_COL)
+                        .fit(onlineTrainTable);
+        Table resultTable = model.setPredictionCol(PREDICT_COL).transform(onlinePredictTable)[0];
+        verifyPredictionResult(resultTable, 4);
+    }
+
+    @Test
+    public void testSparseFitAndPredict() throws Exception {
+        double[] doubleArray = new double[] {0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1};
+        Table initSparseModel =
+                tEnv.fromDataStream(env.fromElements(Row.of(new DenseVector(doubleArray), 0L)));
+        Table onlineTrainTable = getTable(5, 2000, TRAIN_SPARSE_ROWS, 4, true);
+        Table onlinePredictTable = getTable(5, 3000, PREDICT_SPARSE_ROWS, 4, true);
+        OnlineLogisticRegressionModel model =
+                new OnlineLogisticRegression()
+                        .setFeaturesCol(FEATURE_COL)
+                        .setInitialModelData(initSparseModel)
+                        .setGlobalBatchSize(500)
+                        .setLabelCol(LABEL_COL)
+                        .fit(onlineTrainTable);
+        Table resultTable = model.setPredictionCol(PREDICT_COL).transform(onlinePredictTable)[0];
+        verifyPredictionResult(resultTable, 4);
+    }
+
+    @Test
+    public void testParam() {
+        OnlineLogisticRegression onlineLogisticRegression = new OnlineLogisticRegression();
+        Assert.assertEquals("features", onlineLogisticRegression.getFeaturesCol());
+        Assert.assertEquals("count", onlineLogisticRegression.getBatchStrategy());
+        Assert.assertEquals("label", onlineLogisticRegression.getLabelCol());
+        Assert.assertEquals(0.1, onlineLogisticRegression.getL1(), 1.0e-5);
+        Assert.assertEquals(0.1, onlineLogisticRegression.getL2(), 1.0e-5);
+        Assert.assertEquals(0.1, onlineLogisticRegression.getAlpha(), 1.0e-5);
+        Assert.assertEquals(0.1, onlineLogisticRegression.getBeta(), 1.0e-5);
+        Assert.assertEquals(32, onlineLogisticRegression.getGlobalBatchSize());
+
+        onlineLogisticRegression
+                .setFeaturesCol("test_feature")
+                .setLabelCol("test_label")
+                .setGlobalBatchSize(5)
+                .setL1(0.25)
+                .setL2(0.25)
+                .setAlpha(0.25)
+                .setBeta(0.25);
+
+        Assert.assertEquals("test_feature", onlineLogisticRegression.getFeaturesCol());
+        Assert.assertEquals("test_label", onlineLogisticRegression.getLabelCol());
+        Assert.assertEquals(0.25, onlineLogisticRegression.getL1(), 1.0e-5);
+        Assert.assertEquals(0.25, onlineLogisticRegression.getL2(), 1.0e-5);
+        Assert.assertEquals(0.25, onlineLogisticRegression.getAlpha(), 1.0e-5);
+        Assert.assertEquals(0.25, onlineLogisticRegression.getBeta(), 1.0e-5);
+        Assert.assertEquals(5, onlineLogisticRegression.getGlobalBatchSize());
+
+        OnlineLogisticRegressionModel onlineLogisticRegressionModel =
+                new OnlineLogisticRegressionModel();
+        Assert.assertEquals("features", onlineLogisticRegressionModel.getFeaturesCol());
+        Assert.assertEquals("modelVersion", onlineLogisticRegressionModel.getModelVersionCol());
+        Assert.assertEquals("prediction", onlineLogisticRegressionModel.getPredictionCol());
+        Assert.assertEquals("rawPrediction", onlineLogisticRegressionModel.getRawPredictionCol());
+
+        onlineLogisticRegressionModel
+                .setFeaturesCol("test_feature")
+                .setPredictionCol("pred")
+                .setModelVersionCol("version")
+                .setRawPredictionCol("raw");
+
+        Assert.assertEquals("test_feature", onlineLogisticRegressionModel.getFeaturesCol());
+        Assert.assertEquals("version", onlineLogisticRegressionModel.getModelVersionCol());
+        Assert.assertEquals("pred", onlineLogisticRegressionModel.getPredictionCol());
+        Assert.assertEquals("raw", onlineLogisticRegressionModel.getRawPredictionCol());
+    }
+
+    @Test
+    public void testBatchSizeLessThanParallelism() throws Exception {
+        Table onlinePredictTable = getTable(1, 20, TRAIN_DENSE_ROWS, 4, true);
+        try {
+            new OnlineLogisticRegression()
+                    .setFeaturesCol(FEATURE_COL)
+                    .setInitialModelData(initDenseModel)
+                    .setGlobalBatchSize(2)
+                    .setLabelCol(LABEL_COL)
+                    .fit(onlinePredictTable);
+            Assert.fail("Expected IllegalStateException");
+        } catch (Exception e) {
+            Throwable exception = e;
+            while (exception.getCause() != null) {
+                exception = exception.getCause();
+            }
+            Assert.assertEquals(IllegalStateException.class, exception.getClass());
+            Assert.assertEquals(
+                    "There are more subtasks in the training process than the number "
+                            + "of elements in each batch. Some subtasks might be idling forever.",
+                    exception.getMessage());
+        }
+    }
+
+    @Test
+    public void testSaveAndReload() throws Exception {
+        Table onlineTrainTable = getTable(2, 2000, TRAIN_DENSE_ROWS, 2, false);
+        Table onlinePredictTable = getTable(2, 3000, PREDICT_DENSE_ROWS, 2, false);
+        OnlineLogisticRegression onlineLogisticRegression =
+                new OnlineLogisticRegression()
+                        .setFeaturesCol(FEATURE_COL)
+                        .setInitialModelData(initDenseModel)
+                        .setGlobalBatchSize(500)
+                        .setLabelCol(LABEL_COL);
+        OnlineLogisticRegression loadedOnlineLogisticRegression =
+                StageTestUtils.saveAndReload(
+                        tEnv, onlineLogisticRegression, tempFolder.newFolder().getAbsolutePath());
+        OnlineLogisticRegressionModel onlineLogisticRegressionModel =
+                loadedOnlineLogisticRegression.fit(onlineTrainTable);
+        Table resultTable =
+                onlineLogisticRegressionModel.setPredictionCol(PREDICT_COL)
+                        .transform(onlinePredictTable)[0];
+        verifyPredictionResult(resultTable, 4);
+        OnlineLogisticRegressionModel loadedOnlineLogisticRegressionModel =
+                StageTestUtils.saveAndReload(
+                        tEnv,
+                        onlineLogisticRegressionModel,
+                        tempFolder.newFolder().getAbsolutePath());
+        Table resultTableWithLoadedModel =
+                loadedOnlineLogisticRegressionModel.setPredictionCol(PREDICT_COL)
+                        .transform(onlinePredictTable)[0];
+        verifyPredictionResult(resultTableWithLoadedModel, -1);
+    }
+
+    @Test
+    public void testGetModelData() throws Exception {
+        Table onlineTrainTable = getTable(2, 2000, TRAIN_DENSE_ROWS, 1, false);
+        List<DenseVector> expected =
+                new ArrayList<>(
+                        Arrays.asList(
+                                Vectors.dense(0.6094293839451556, -0.3535110997464949),
+                                Vectors.dense(0.8817781161262602, -0.6045148530476719),
+                                Vectors.dense(1.0802504223028735, -0.7809336961447708),
+                                Vectors.dense(1.236292181150552, -0.9166121469926248)));
+        OnlineLogisticRegression onlineLogisticRegression =
+                new OnlineLogisticRegression()
+                        .setFeaturesCol(FEATURE_COL)
+                        .setInitialModelData(initDenseModel)
+                        .setGlobalBatchSize(500)
+                        .setLabelCol(LABEL_COL);
+        OnlineLogisticRegressionModel onlineLogisticRegressionModel =
+                onlineLogisticRegression.fit(onlineTrainTable);
+        Table modelData = onlineLogisticRegressionModel.getModelData()[0];
+        DataStream<DenseVector> dataStream =
+                tEnv.toDataStream(modelData)
+                        .map((MapFunction<Row, DenseVector>) value -> value.getFieldAs(0));
+        List<DenseVector> result = IteratorUtils.toList(dataStream.executeAndCollect());
+        result.sort((o1, o2) -> MinMaxScalerTest.compare(o1, o2));
+        Assert.assertEquals(expected, result);
+    }
+
+    @Test
+    public void testSetModelData() throws Exception {
+        Table onlinePredictTable = getTable(1, 1, TRAIN_DENSE_ROWS, 1, false);
+
+        OnlineLogisticRegressionModel onlineLogisticRegressionModel =
+                new OnlineLogisticRegressionModel().setFeaturesCol(FEATURE_COL);
+
+        Table modelData =
+                tEnv.fromDataStream(
+                        env.fromElements(Row.of(new DenseVector(new double[] {0.5, 0.1}), 0L)));
+        onlineLogisticRegressionModel.setModelData(modelData);
+
+        Row expected =
+                Row.of(
+                        Vectors.dense(0.1, 2.0),
+                        0.0,
+                        1.0,
+                        Vectors.dense(0.43782349911420193, 0.5621765008857981),
+                        0L);
+        DataStream<Row> results =
+                tEnv.toDataStream(onlineLogisticRegressionModel.transform(onlinePredictTable)[0]);
+        List<Row> resultList = IteratorUtils.toList(results.executeAndCollect());
+        Assert.assertEquals(expected, resultList.get(0));
+    }
+
+    private static void verifyPredictionResult(Table output, int expectedNum) throws Exception {
+        StreamTableEnvironment tEnv =
+                (StreamTableEnvironment) ((TableImpl) output).getTableEnvironment();
+        DataStream<Row> stream = tEnv.toDataStream(output);
+        List<Row> result = IteratorUtils.toList(stream.executeAndCollect());
+        Map<Long, Tuple2<Double, Double>> correctRatio = new HashMap<>();
+
+        for (Row row : result) {
+            long modelVersion = row.getFieldAs(MODEL_VERSION_COL);
+            Double pred = row.getFieldAs(PREDICT_COL);
+            Double label = row.getFieldAs(LABEL_COL);
+            if (correctRatio.containsKey(modelVersion)) {
+                Tuple2<Double, Double> t2 = correctRatio.get(modelVersion);
+                if (pred.equals(label)) {
+                    t2.f0 += 1.0;
+                }
+                t2.f1 += 1.0;
+            } else {
+                correctRatio.put(modelVersion, Tuple2.of(pred.equals(label) ? 1.0 : 0.0, 1.0));
+            }
+        }
+        int numModel = 0;
+        for (Long id : correctRatio.keySet()) {
+            assertEquals(1.0, correctRatio.get(id).f0 / correctRatio.get(id).f1, 1.0e-5);
+            numModel++;
+        }
+        if (expectedNum != -1) {
+            assertEquals(expectedNum, numModel);
+        }
+    }
+
+    /** Random selects samples with fixed size from a given sample list. */
+    private static class RandomSample implements SourceFunction<Row> {
+        private volatile boolean isRunning = true;
+        private final long timeInterval;
+        private final long numSample;
+        private final List<Row> data;
+
+        public RandomSample(long timeInterval, long numSample, List<Row> data) {
+            this.timeInterval = timeInterval;
+            this.numSample = numSample;
+            this.data = data;
+        }
+
+        @Override
+        public void run(SourceContext<Row> ctx) throws Exception {
+            int size = data.size();
+            for (int i = 0; i < numSample; ++i) {
+                int idx = i % size;
+                if (isRunning) {
+                    ctx.collect(data.get(idx));
+                    if (timeInterval > 0) {
+                        Thread.sleep(timeInterval);
+                    }
+                }
+            }
+        }
+
+        @Override
+        public void cancel() {
+            isRunning = false;
+        }
+    }
+
+    private Table getTable(
+            int timeInterval, int numSample, List<Row> data, int parallel, boolean isSparse) {

Review Comment:
   For the first question, I don't think so. The data is random sampling from a fixed dataset.
   
   
   The user set the total num samples, we need to calculate the num samples on every worker, then we need source parallel parameter.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@flink.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org