zhipeng93 commented on code in PR #210:
URL: https://github.com/apache/flink-ml/pull/210#discussion_r1205036234


##########
flink-ml-lib/src/main/java/org/apache/flink/ml/common/gbt/GBTRunner.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.common.gbt;
+
+import org.apache.flink.api.common.functions.AggregateFunction;
+import org.apache.flink.api.common.functions.RichMapFunction;
+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.iteration.DataStreamList;
+import org.apache.flink.iteration.IterationConfig;
+import org.apache.flink.iteration.Iterations;
+import org.apache.flink.iteration.ReplayableDataStreamList;
+import org.apache.flink.ml.classification.gbtclassifier.GBTClassifier;
+import org.apache.flink.ml.common.broadcast.BroadcastUtils;
+import org.apache.flink.ml.common.datastream.DataStreamUtils;
+import org.apache.flink.ml.common.datastream.TableUtils;
+import org.apache.flink.ml.common.gbt.defs.BoostingStrategy;
+import org.apache.flink.ml.common.gbt.defs.FeatureMeta;
+import org.apache.flink.ml.common.gbt.defs.LossType;
+import org.apache.flink.ml.common.gbt.defs.Node;
+import org.apache.flink.ml.common.gbt.defs.TaskType;
+import org.apache.flink.ml.common.gbt.defs.TrainContext;
+import org.apache.flink.ml.linalg.typeinfo.DenseVectorTypeInfo;
+import org.apache.flink.ml.linalg.typeinfo.SparseVectorTypeInfo;
+import org.apache.flink.ml.linalg.typeinfo.VectorTypeInfo;
+import org.apache.flink.ml.param.Param;
+import org.apache.flink.ml.regression.gbtregressor.GBTRegressor;
+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.types.Row;
+import org.apache.flink.util.Preconditions;
+
+import org.apache.commons.lang3.ArrayUtils;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+/** Runs a gradient boosting trees implementation. */
+public class GBTRunner {
+
+    private static boolean isVectorType(TypeInformation<?> typeInfo) {
+        return typeInfo instanceof DenseVectorTypeInfo
+                || typeInfo instanceof SparseVectorTypeInfo
+                || typeInfo instanceof VectorTypeInfo;
+    }
+
+    public static DataStream<GBTModelData> train(Table data, BaseGBTParams<?> 
estimator) {
+        String[] featuresCols = estimator.getFeaturesCols();
+        TypeInformation<?>[] featuresTypes =
+                Arrays.stream(featuresCols)
+                        .map(d -> 
TableUtils.getTypeInfoByName(data.getResolvedSchema(), d))
+                        .toArray(TypeInformation[]::new);
+        for (int i = 0; i < featuresCols.length; i += 1) {
+            Preconditions.checkArgument(
+                    null != featuresTypes[i],
+                    String.format(
+                            "Column name %s not existed in the input data.", 
featuresCols[i]));
+        }
+
+        boolean isInputVector = featuresCols.length == 1 && 
isVectorType(featuresTypes[0]);
+        return train(data, getStrategy(estimator, isInputVector));
+    }
+
+    /** Trains a gradient boosting tree model with given data and parameters. 
*/
+    static DataStream<GBTModelData> train(Table dataTable, BoostingStrategy 
strategy) {
+        StreamTableEnvironment tEnv =
+                (StreamTableEnvironment) ((TableImpl) 
dataTable).getTableEnvironment();
+        Tuple2<Table, DataStream<FeatureMeta>> preprocessResult =
+                strategy.isInputVector
+                        ? Preprocess.preprocessVecCol(dataTable, strategy)
+                        : Preprocess.preprocessCols(dataTable, strategy);
+        dataTable = preprocessResult.f0;
+        DataStream<FeatureMeta> featureMeta = preprocessResult.f1;
+
+        DataStream<Row> data = tEnv.toDataStream(dataTable);
+        DataStream<Tuple2<Double, Long>> labelSumCount =
+                DataStreamUtils.aggregate(data, new 
LabelSumCountFunction(strategy.labelCol));
+        return boost(dataTable, strategy, featureMeta, labelSumCount);
+    }
+
+    public static DataStream<Map<String, Double>> getFeatureImportance(
+            DataStream<GBTModelData> modelData) {
+        return modelData
+                .map(
+                        value -> {
+                            Map<Integer, Double> featureImportanceMap = new 
HashMap<>();
+                            double sum = 0.;
+                            for (List<Node> tree : value.allTrees) {
+                                for (Node node : tree) {
+                                    if (node.isLeaf) {
+                                        continue;
+                                    }
+                                    featureImportanceMap.merge(
+                                            node.split.featureId, 
node.split.gain, Double::sum);
+                                    sum += node.split.gain;
+                                }
+                            }
+                            if (sum > 0.) {
+                                for (Map.Entry<Integer, Double> entry :
+                                        featureImportanceMap.entrySet()) {
+                                    entry.setValue(entry.getValue() / sum);
+                                }
+                            }
+
+                            List<String> featureNames = value.featureNames;
+                            return featureImportanceMap.entrySet().stream()
+                                    .collect(
+                                            Collectors.toMap(
+                                                    d -> 
featureNames.get(d.getKey()),
+                                                    Map.Entry::getValue));
+                        })
+                .returns(Types.MAP(Types.STRING, Types.DOUBLE));
+    }
+
+    private static DataStream<GBTModelData> boost(
+            Table dataTable,
+            BoostingStrategy strategy,
+            DataStream<FeatureMeta> featureMeta,
+            DataStream<Tuple2<Double, Long>> labelSumCount) {
+        StreamTableEnvironment tEnv =
+                (StreamTableEnvironment) ((TableImpl) 
dataTable).getTableEnvironment();
+
+        final String featureMetaBcName = "featureMeta";
+        final String labelSumCountBcName = "labelSumCount";
+        Map<String, DataStream<?>> bcMap = new HashMap<>();
+        bcMap.put(featureMetaBcName, featureMeta);
+        bcMap.put(labelSumCountBcName, labelSumCount);
+
+        DataStream<TrainContext> initTrainContext =
+                BroadcastUtils.withBroadcastStream(
+                        Collections.singletonList(
+                                tEnv.toDataStream(tEnv.fromValues(0), 
Integer.class)),
+                        bcMap,
+                        (inputs) -> {
+                            //noinspection unchecked
+                            DataStream<Integer> input = (DataStream<Integer>) 
(inputs.get(0));
+                            return input.map(
+                                    new InitTrainContextFunction(
+                                            featureMetaBcName, 
labelSumCountBcName, strategy));
+                        });
+
+        DataStream<Row> data = tEnv.toDataStream(dataTable);
+        DataStreamList dataStreamList =
+                Iterations.iterateBoundedStreamsUntilTermination(
+                        DataStreamList.of(initTrainContext.broadcast()),
+                        ReplayableDataStreamList.notReplay(data, featureMeta),

Review Comment:
   The `featureMeta` seems never used later. Can you remove it?



##########
flink-ml-core/src/main/java/org/apache/flink/ml/common/sharedobjects/SharedObjectsStreamOperator.java:
##########
@@ -0,0 +1,38 @@
+/*
+ * 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.common.sharedobjects;
+
+/** Interface for all operators that need to access the shared objects. */
+public interface SharedObjectsStreamOperator {

Review Comment:
   As I understand, this PR tries to provide an infrastructure for sharing 
objects among multiple Flink operators, through java static variables. 
   
   To achieve this, it empoys one specific Flink operator for each sharing 
object as the writer and others operators as the reader. Based on this, the 
GBDT implementation relies on the Flink events to guarantee the read/write 
order of each object. 
   
   However, can you explain some other machine learning algorithms that would 
use `SharedObjects` in the future? And is there a general way that developers 
can guarantee the order of read/writes is correct? If a reader of an object 
changes the value of that object, does it still follows the assumption of 
`SharedObjects`?
   
   There is another possible solution [1] that we put all the computation logic 
into one operator (i.e., WorkerOperator) and all the computation logic into 
another operator (i.e., ServerOperator). In this case, we would not need shared 
objects anymore. Let's have a thorough comparison between these two options.
   
   [1] https://github.com/apache/flink-ml/pull/237



##########
flink-ml-lib/src/main/java/org/apache/flink/ml/common/gbt/GBTRunner.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.common.gbt;
+
+import org.apache.flink.api.common.functions.AggregateFunction;
+import org.apache.flink.api.common.functions.RichMapFunction;
+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.iteration.DataStreamList;
+import org.apache.flink.iteration.IterationConfig;
+import org.apache.flink.iteration.Iterations;
+import org.apache.flink.iteration.ReplayableDataStreamList;
+import org.apache.flink.ml.classification.gbtclassifier.GBTClassifier;
+import org.apache.flink.ml.common.broadcast.BroadcastUtils;
+import org.apache.flink.ml.common.datastream.DataStreamUtils;
+import org.apache.flink.ml.common.datastream.TableUtils;
+import org.apache.flink.ml.common.gbt.defs.BoostingStrategy;
+import org.apache.flink.ml.common.gbt.defs.FeatureMeta;
+import org.apache.flink.ml.common.gbt.defs.LossType;
+import org.apache.flink.ml.common.gbt.defs.Node;
+import org.apache.flink.ml.common.gbt.defs.TaskType;
+import org.apache.flink.ml.common.gbt.defs.TrainContext;
+import org.apache.flink.ml.linalg.typeinfo.DenseVectorTypeInfo;
+import org.apache.flink.ml.linalg.typeinfo.SparseVectorTypeInfo;
+import org.apache.flink.ml.linalg.typeinfo.VectorTypeInfo;
+import org.apache.flink.ml.param.Param;
+import org.apache.flink.ml.regression.gbtregressor.GBTRegressor;
+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.types.Row;
+import org.apache.flink.util.Preconditions;
+
+import org.apache.commons.lang3.ArrayUtils;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+/** Runs a gradient boosting trees implementation. */
+public class GBTRunner {
+
+    private static boolean isVectorType(TypeInformation<?> typeInfo) {
+        return typeInfo instanceof DenseVectorTypeInfo
+                || typeInfo instanceof SparseVectorTypeInfo
+                || typeInfo instanceof VectorTypeInfo;
+    }
+
+    public static DataStream<GBTModelData> train(Table data, BaseGBTParams<?> 
estimator) {
+        String[] featuresCols = estimator.getFeaturesCols();
+        TypeInformation<?>[] featuresTypes =
+                Arrays.stream(featuresCols)
+                        .map(d -> 
TableUtils.getTypeInfoByName(data.getResolvedSchema(), d))
+                        .toArray(TypeInformation[]::new);
+        for (int i = 0; i < featuresCols.length; i += 1) {
+            Preconditions.checkArgument(
+                    null != featuresTypes[i],
+                    String.format(
+                            "Column name %s not existed in the input data.", 
featuresCols[i]));
+        }
+
+        boolean isInputVector = featuresCols.length == 1 && 
isVectorType(featuresTypes[0]);
+        return train(data, getStrategy(estimator, isInputVector));
+    }
+
+    /** Trains a gradient boosting tree model with given data and parameters. 
*/
+    static DataStream<GBTModelData> train(Table dataTable, BoostingStrategy 
strategy) {
+        StreamTableEnvironment tEnv =
+                (StreamTableEnvironment) ((TableImpl) 
dataTable).getTableEnvironment();
+        Tuple2<Table, DataStream<FeatureMeta>> preprocessResult =
+                strategy.isInputVector
+                        ? Preprocess.preprocessVecCol(dataTable, strategy)
+                        : Preprocess.preprocessCols(dataTable, strategy);
+        dataTable = preprocessResult.f0;
+        DataStream<FeatureMeta> featureMeta = preprocessResult.f1;
+
+        DataStream<Row> data = tEnv.toDataStream(dataTable);
+        DataStream<Tuple2<Double, Long>> labelSumCount =
+                DataStreamUtils.aggregate(data, new 
LabelSumCountFunction(strategy.labelCol));
+        return boost(dataTable, strategy, featureMeta, labelSumCount);
+    }
+
+    public static DataStream<Map<String, Double>> getFeatureImportance(
+            DataStream<GBTModelData> modelData) {
+        return modelData
+                .map(
+                        value -> {
+                            Map<Integer, Double> featureImportanceMap = new 
HashMap<>();
+                            double sum = 0.;
+                            for (List<Node> tree : value.allTrees) {
+                                for (Node node : tree) {
+                                    if (node.isLeaf) {
+                                        continue;
+                                    }
+                                    featureImportanceMap.merge(
+                                            node.split.featureId, 
node.split.gain, Double::sum);
+                                    sum += node.split.gain;
+                                }
+                            }
+                            if (sum > 0.) {
+                                for (Map.Entry<Integer, Double> entry :
+                                        featureImportanceMap.entrySet()) {
+                                    entry.setValue(entry.getValue() / sum);
+                                }
+                            }
+
+                            List<String> featureNames = value.featureNames;
+                            return featureImportanceMap.entrySet().stream()
+                                    .collect(
+                                            Collectors.toMap(
+                                                    d -> 
featureNames.get(d.getKey()),
+                                                    Map.Entry::getValue));
+                        })
+                .returns(Types.MAP(Types.STRING, Types.DOUBLE));
+    }
+
+    private static DataStream<GBTModelData> boost(
+            Table dataTable,
+            BoostingStrategy strategy,
+            DataStream<FeatureMeta> featureMeta,
+            DataStream<Tuple2<Double, Long>> labelSumCount) {
+        StreamTableEnvironment tEnv =
+                (StreamTableEnvironment) ((TableImpl) 
dataTable).getTableEnvironment();
+
+        final String featureMetaBcName = "featureMeta";
+        final String labelSumCountBcName = "labelSumCount";
+        Map<String, DataStream<?>> bcMap = new HashMap<>();
+        bcMap.put(featureMetaBcName, featureMeta);
+        bcMap.put(labelSumCountBcName, labelSumCount);
+
+        DataStream<TrainContext> initTrainContext =
+                BroadcastUtils.withBroadcastStream(
+                        Collections.singletonList(
+                                tEnv.toDataStream(tEnv.fromValues(0), 
Integer.class)),
+                        bcMap,
+                        (inputs) -> {
+                            //noinspection unchecked
+                            DataStream<Integer> input = (DataStream<Integer>) 
(inputs.get(0));
+                            return input.map(
+                                    new InitTrainContextFunction(
+                                            featureMetaBcName, 
labelSumCountBcName, strategy));
+                        });
+
+        DataStream<Row> data = tEnv.toDataStream(dataTable);
+        DataStreamList dataStreamList =
+                Iterations.iterateBoundedStreamsUntilTermination(
+                        DataStreamList.of(initTrainContext.broadcast()),

Review Comment:
   This `broadcast` in `initTrainContext#broadcast` is supposed to be removed 
during compilation. Is this expected?



-- 
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-unsubscr...@flink.apache.org

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

Reply via email to