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/07 07:05:52 UTC

[GitHub] [flink-ml] lindong28 commented on a diff in pull request #93: [FLINK-27091] Add Transformer and Estimator for LinearSVC

lindong28 commented on code in PR #93:
URL: https://github.com/apache/flink-ml/pull/93#discussion_r867315598


##########
flink-ml-lib/src/main/java/org/apache/flink/ml/classification/linearsvc/LinearSVC.java:
##########
@@ -0,0 +1,124 @@
+/*
+ * 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.linearsvc;
+
+import org.apache.flink.api.common.functions.ReduceFunction;
+import org.apache.flink.ml.api.Estimator;
+import org.apache.flink.ml.common.datastream.DataStreamUtils;
+import org.apache.flink.ml.common.feature.LabeledPointWithWeight;
+import org.apache.flink.ml.common.lossfunc.HingeLoss;
+import org.apache.flink.ml.common.optimizer.Optimizer;
+import org.apache.flink.ml.common.optimizer.SGD;
+import org.apache.flink.ml.linalg.DenseVector;
+import org.apache.flink.ml.param.Param;
+import org.apache.flink.ml.util.ParamUtils;
+import org.apache.flink.ml.util.ReadWriteUtils;
+import org.apache.flink.streaming.api.datastream.DataStream;
+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.util.Preconditions;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * An Estimator which implements the linear support vector classification.
+ *
+ * <p>See https://en.wikipedia.org/wiki/Support-vector_machine#Linear_SVM.
+ */
+public class LinearSVC implements Estimator<LinearSVC, LinearSVCModel>, LinearSVCParams<LinearSVC> {
+
+    private final Map<Param<?>, Object> paramMap = new HashMap<>();
+
+    public LinearSVC() {
+        ParamUtils.initializeMapWithDefaultValues(paramMap, this);
+    }
+
+    @Override
+    @SuppressWarnings({"rawTypes", "ConstantConditions"})
+    public LinearSVCModel fit(Table... inputs) {
+        Preconditions.checkArgument(inputs.length == 1);
+        StreamTableEnvironment tEnv =
+                (StreamTableEnvironment) ((TableImpl) inputs[0]).getTableEnvironment();
+
+        DataStream<LabeledPointWithWeight> trainData =
+                tEnv.toDataStream(inputs[0])
+                        .map(
+                                dataPoint -> {
+                                    double weight =
+                                            getWeightCol() == null
+                                                    ? 1.0
+                                                    : (Double) dataPoint.getField(getWeightCol());
+                                    double label = (Double) dataPoint.getField(getLabelCol());
+                                    Preconditions.checkState(

Review Comment:
   nits: it might be better to just string format instead of string concatenation:
   
   ```
   Preconditions.checkState(
           Double.compare(0.0, label) == 0
                   || Double.compare(1.0, label) == 0,
           "LinearSVC only supports binary classification. But detected label: %s.",
           label);
   ```



##########
flink-ml-lib/src/test/java/org/apache/flink/ml/classification/LinearSVCTest.java:
##########
@@ -0,0 +1,304 @@
+/*
+ * 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.restartstrategy.RestartStrategies;
+import org.apache.flink.api.common.typeinfo.TypeInformation;
+import org.apache.flink.api.common.typeinfo.Types;
+import org.apache.flink.api.java.typeutils.RowTypeInfo;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.ml.classification.linearsvc.LinearSVC;
+import org.apache.flink.ml.classification.linearsvc.LinearSVCModel;
+import org.apache.flink.ml.classification.linearsvc.LinearSVCModelData;
+import org.apache.flink.ml.linalg.DenseVector;
+import org.apache.flink.ml.linalg.Vectors;
+import org.apache.flink.ml.linalg.typeinfo.DenseVectorTypeInfo;
+import org.apache.flink.ml.util.ReadWriteUtils;
+import org.apache.flink.ml.util.StageTestUtils;
+import org.apache.flink.streaming.api.environment.ExecutionCheckpointingOptions;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.table.api.Table;
+import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
+import org.apache.flink.types.Row;
+
+import org.apache.commons.collections.IteratorUtils;
+import org.apache.commons.lang3.RandomUtils;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+/** Tests {@link LinearSVC} and {@link LinearSVCModel}. */
+public class LinearSVCTest {
+
+    @Rule public final TemporaryFolder tempFolder = new TemporaryFolder();
+
+    private StreamExecutionEnvironment env;
+
+    private StreamTableEnvironment tEnv;
+
+    private static final List<Row> trainData =
+            Arrays.asList(
+                    Row.of(Vectors.dense(1, 2, 3, 4), 0., 1.),
+                    Row.of(Vectors.dense(2, 2, 3, 4), 0., 2.),
+                    Row.of(Vectors.dense(3, 2, 3, 4), 0., 3.),
+                    Row.of(Vectors.dense(4, 2, 3, 4), 0., 4.),
+                    Row.of(Vectors.dense(5, 2, 3, 4), 0., 5.),
+                    Row.of(Vectors.dense(11, 2, 3, 4), 1., 1.),
+                    Row.of(Vectors.dense(12, 2, 3, 4), 1., 2.),
+                    Row.of(Vectors.dense(13, 2, 3, 4), 1., 3.),
+                    Row.of(Vectors.dense(14, 2, 3, 4), 1., 4.),
+                    Row.of(Vectors.dense(15, 2, 3, 4), 1., 5.));
+
+    private static final double[] expectedCoefficient =
+            new double[] {0.470, -0.273, -0.410, -0.546};
+
+    private static final double TOLERANCE = 1e-7;
+
+    private Table trainDataTable;
+
+    @Before
+    public void before() {
+        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);
+        Collections.shuffle(trainData);
+        trainDataTable =
+                tEnv.fromDataStream(
+                        env.fromCollection(
+                                trainData,
+                                new RowTypeInfo(
+                                        new TypeInformation[] {
+                                            DenseVectorTypeInfo.INSTANCE, Types.DOUBLE, Types.DOUBLE
+                                        },
+                                        new String[] {"features", "label", "weight"})));
+    }
+
+    @SuppressWarnings("ConstantConditions, unchecked")
+    private void verifyPredictionResult(
+            Table output, String featuresCol, String predictionCol, String rawPredictionCol)
+            throws Exception {
+        List<Row> predResult = IteratorUtils.toList(tEnv.toDataStream(output).executeAndCollect());
+        for (Row predictionRow : predResult) {
+            DenseVector feature = (DenseVector) predictionRow.getField(featuresCol);
+            double prediction = (double) predictionRow.getField(predictionCol);
+            DenseVector rawPrediction = (DenseVector) predictionRow.getField(rawPredictionCol);
+            if (feature.get(0) <= 5) {
+                assertEquals(0, prediction, TOLERANCE);
+                assertTrue(rawPrediction.get(0) < 0);
+            } else {
+                assertEquals(1, prediction, TOLERANCE);
+                assertTrue(rawPrediction.get(0) > 0);
+            }
+        }
+    }
+
+    @Test
+    public void testParam() {
+        LinearSVC linearSVC = new LinearSVC();
+        assertEquals("label", linearSVC.getLabelCol());

Review Comment:
   nits: could we make the order of these parameters consistent across the first group of assert calls, the setXXX calls, and the 2nd group of assert calls?



-- 
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