yunfengzhou-hub commented on a change in pull request #32:
URL: https://github.com/apache/flink-ml/pull/32#discussion_r757181326



##########
File path: 
flink-ml-lib/src/main/java/org/apache/flink/ml/classification/naivebayes/NaiveBayes.java
##########
@@ -0,0 +1,377 @@
+/*
+ * 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.naivebayes;
+
+import org.apache.flink.api.common.functions.AggregateFunction;
+import org.apache.flink.api.common.functions.FlatMapFunction;
+import org.apache.flink.api.common.functions.MapFunction;
+import org.apache.flink.api.common.functions.ReduceFunction;
+import org.apache.flink.api.java.functions.KeySelector;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.api.java.tuple.Tuple3;
+import org.apache.flink.api.java.tuple.Tuple4;
+import org.apache.flink.ml.api.core.Estimator;
+import org.apache.flink.ml.common.datastream.EndOfStreamWindows;
+import org.apache.flink.ml.linalg.Vector;
+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.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
+import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
+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.Collector;
+import org.apache.flink.util.Preconditions;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+
+/**
+ * An Estimator which implements the naive bayes classification algorithm.
+ *
+ * <p>See https://en.wikipedia.org/wiki/Naive_Bayes_classifier.
+ */
+public class NaiveBayes
+        implements Estimator<NaiveBayes, NaiveBayesModel>, 
NaiveBayesParams<NaiveBayes> {
+    private final Map<Param<?>, Object> paramMap = new HashMap<>();
+
+    public NaiveBayes() {
+        ParamUtils.initializeMapWithDefaultValues(paramMap, this);
+    }
+
+    @Override
+    public NaiveBayesModel fit(Table... inputs) {
+        Preconditions.checkArgument(inputs.length == 1);
+
+        final String featuresCol = getFeaturesCol();
+        final String labelCol = getLabelCol();
+        final double smoothing = getSmoothing();
+
+        StreamTableEnvironment tEnv =
+                (StreamTableEnvironment) ((TableImpl) 
inputs[0]).getTableEnvironment();
+        DataStream<Tuple2<Vector, Integer>> input =
+                tEnv.toDataStream(inputs[0])
+                        .map(
+                                new MapFunction<Row, Tuple2<Vector, 
Integer>>() {
+                                    @Override
+                                    public Tuple2<Vector, Integer> map(Row 
row) throws Exception {
+                                        Number number = (Number) 
row.getField(labelCol);
+                                        Preconditions.checkArgument(
+                                                number.intValue() == 
number.doubleValue());
+                                        return new Tuple2<>(
+                                                (Vector) 
row.getField(featuresCol),
+                                                number.intValue());
+                                    }
+                                });
+
+        DataStream<NaiveBayesModelData> modelData =
+                input.flatMap(new ExtractFeatureFunction())
+                        .keyBy(
+                                (KeySelector<Tuple4<Integer, Integer, Double, 
Double>, Object>)
+                                        value -> new Tuple3<>(value.f0, 
value.f1, value.f2))
+                        .window(EndOfStreamWindows.get())
+                        .reduce(
+                                (ReduceFunction<Tuple4<Integer, Integer, 
Double, Double>>)
+                                        (t0, t1) ->
+                                                new Tuple4<>(t0.f0, t0.f1, 
t0.f2, t0.f3 + t1.f3))
+                        .keyBy(
+                                (KeySelector<Tuple4<Integer, Integer, Double, 
Double>, Object>)
+                                        value -> new Tuple2<>(value.f0, 
value.f1))
+                        .window(EndOfStreamWindows.get())
+                        .aggregate(new GenerateFeatureWeightMapFunction())
+                        .keyBy(
+                                (KeySelector<
+                                                Tuple4<
+                                                        Integer,
+                                                        Integer,
+                                                        Map<Double, Double>,
+                                                        Double>,
+                                                Object>)
+                                        value -> value.f0)
+                        .window(EndOfStreamWindows.get())
+                        .aggregate(new AggregateIntoArrayFunction())
+                        .windowAll(EndOfStreamWindows.get())
+                        .apply(new GenerateModelFunction(smoothing));
+
+        NaiveBayesModel model =
+                new NaiveBayesModel()
+                        
.setModelData(NaiveBayesModelData.getModelDataTable(tEnv, modelData));
+        ReadWriteUtils.updateExistingParams(model, paramMap);
+        return model;
+    }
+
+    @Override
+    public void save(String path) throws IOException {
+        ReadWriteUtils.saveMetadata(this, path);
+    }
+
+    public static NaiveBayes load(StreamExecutionEnvironment env, String path) 
throws IOException {
+        return ReadWriteUtils.loadStageParam(path);
+    }
+
+    @Override
+    public Map<Param<?>, Object> getParamMap() {
+        return paramMap;
+    }
+
+    /**
+     * Function to extract feature values from input rows.
+     *
+     * <p>Output records are tuples with the following fields in order:
+     *
+     * <ul>
+     *   <li>label value
+     *   <li>feature column index
+     *   <li>feature value
+     *   <li>weight
+     * </ul>
+     */
+    private static class ExtractFeatureFunction
+            implements FlatMapFunction<
+                    Tuple2<Vector, Integer>, Tuple4<Integer, Integer, Double, 
Double>> {
+        @Override
+        public void flatMap(
+                Tuple2<Vector, Integer> value,
+                Collector<Tuple4<Integer, Integer, Double, Double>> collector) 
{
+            Preconditions.checkNotNull(value.f1);
+            for (int i = 0; i < value.f0.size(); i++) {
+                collector.collect(new Tuple4<>(value.f1, i, value.f0.get(i), 
1.0));
+            }
+        }
+    }
+
+    /**
+     * Function that aggregates entries of feature value and weight into maps.
+     *
+     * <p>Input records should have the same label value and feature column 
index.
+     *
+     * <p>Input records are tuples with the following fields in order:
+     *
+     * <ul>
+     *   <li>label value
+     *   <li>feature column index
+     *   <li>feature value
+     *   <li>weight
+     * </ul>
+     *
+     * <p>Output records are tuples with the following fields in order:
+     *
+     * <ul>
+     *   <li>label value
+     *   <li>feature column index
+     *   <li>map of (feature value, weight)
+     * </ul>
+     */
+    private static class GenerateFeatureWeightMapFunction
+            implements AggregateFunction<
+                    Tuple4<Integer, Integer, Double, Double>,
+                    Tuple3<Integer, Integer, Map<Double, Double>>,
+                    Tuple4<Integer, Integer, Map<Double, Double>, Double>> {
+
+        @Override
+        public Tuple3<Integer, Integer, Map<Double, Double>> 
createAccumulator() {
+            return new Tuple3<>(0, -1, new HashMap<>());
+        }
+
+        @Override
+        public Tuple3<Integer, Integer, Map<Double, Double>> add(
+                Tuple4<Integer, Integer, Double, Double> value,
+                Tuple3<Integer, Integer, Map<Double, Double>> acc) {
+            acc.f0 = value.f0;
+            acc.f1 = value.f1;
+            acc.f2.put(value.f2, value.f3);
+            return acc;
+        }
+
+        @Override
+        public Tuple4<Integer, Integer, Map<Double, Double>, Double> getResult(
+                Tuple3<Integer, Integer, Map<Double, Double>> acc) {
+            double weightSum = 
acc.f2.values().stream().mapToDouble(Double::doubleValue).sum();
+            return new Tuple4<>(acc.f0, acc.f1, acc.f2, weightSum);
+        }
+
+        @Override
+        public Tuple3<Integer, Integer, Map<Double, Double>> merge(
+                Tuple3<Integer, Integer, Map<Double, Double>> acc0,
+                Tuple3<Integer, Integer, Map<Double, Double>> acc1) {
+            Preconditions.checkArgument(acc0.f1 != -1);
+            acc0.f2.putAll(acc1.f2);
+            return acc0;
+        }
+    }
+
+    /**
+     * Function that aggregates maps under the same label into arrays.
+     *
+     * <p>Length of the generated array equals to the number of feature 
columns.
+     *
+     * <p>Input records are tuples with the following fields in order:
+     *
+     * <ul>
+     *   <li>label value
+     *   <li>feature column index
+     *   <li>map of (feature value, weight)

Review comment:
       Yes. I'll fix it.




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