yunfengzhou-hub commented on code in PR #135:
URL: https://github.com/apache/flink-ml/pull/135#discussion_r935210096


##########
flink-ml-lib/src/test/java/org/apache/flink/ml/feature/ElementwiseProductTest.java:
##########
@@ -0,0 +1,207 @@
+/*
+ * 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.feature;
+
+import org.apache.flink.api.common.restartstrategy.RestartStrategies;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.ml.feature.elementwiseproduct.ElementwiseProduct;
+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.TestUtils;
+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.table.api.Table;
+import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
+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.Test;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+
+/** Tests {@link ElementwiseProduct}. */
+public class ElementwiseProductTest extends AbstractTestBase {
+
+    private StreamTableEnvironment tEnv;
+    private Table inputDataTable;
+
+    private static final List<Row> INPUT_DATA =
+            Arrays.asList(
+                    Row.of(
+                            0,
+                            Vectors.dense(2.1, 3.1),
+                            Vectors.sparse(5, new int[] {3}, new double[] 
{1.0})),
+                    Row.of(
+                            1,
+                            Vectors.dense(1.1, 3.3),
+                            Vectors.sparse(
+                                    5, new int[] {4, 2, 3, 1}, new double[] 
{4.0, 2.0, 3.0, 1.0})),
+                    Row.of(2, null, null));
+
+    private static final double[] EXPECTED_OUTPUT_DENSE_VEC_ARRAY_1 = new 
double[] {2.31, 3.41};
+    private static final double[] EXPECTED_OUTPUT_DENSE_VEC_ARRAY_2 = new 
double[] {1.21, 3.63};
+
+    private static final int EXPECTED_OUTPUT_SPARSE_VEC_SIZE_1 = 5;
+    private static final int[] EXPECTED_OUTPUT_SPARSE_VEC_INDICES_1 = new 
int[] {3};
+    private static final double[] EXPECTED_OUTPUT_SPARSE_VEC_VALUES_1 = new 
double[] {0.0};
+
+    private static final int EXPECTED_OUTPUT_SPARSE_VEC_SIZE_2 = 5;
+    private static final int[] EXPECTED_OUTPUT_SPARSE_VEC_INDICES_2 = new 
int[] {1, 2, 3, 4};
+    private static final double[] EXPECTED_OUTPUT_SPARSE_VEC_VALUES_2 =
+            new double[] {1.1, 0.0, 0.0, 0.0};
+
+    @Before
+    public void before() {
+        Configuration config = new Configuration();
+        
config.set(ExecutionCheckpointingOptions.ENABLE_CHECKPOINTS_AFTER_TASKS_FINISH, 
true);
+        StreamExecutionEnvironment env = 
StreamExecutionEnvironment.getExecutionEnvironment(config);
+        env.setParallelism(4);
+        env.enableCheckpointing(100);
+        env.setRestartStrategy(RestartStrategies.noRestart());
+        tEnv = StreamTableEnvironment.create(env);
+        DataStream<Row> dataStream = env.fromCollection(INPUT_DATA);
+        inputDataTable = tEnv.fromDataStream(dataStream).as("id", "vec", 
"sparseVec");
+    }
+
+    private void verifyOutputResult(Table output, String outputCol, boolean 
isSparse)
+            throws Exception {
+        DataStream<Row> dataStream = tEnv.toDataStream(output);
+        List<Row> results = 
IteratorUtils.toList(dataStream.executeAndCollect());
+        assertEquals(3, results.size());
+        for (Row result : results) {
+            if (result.getField(0) == (Object) 0) {
+                if (isSparse) {
+                    SparseVector sparseVector = (SparseVector) 
result.getField(outputCol);
+                    assertEquals(EXPECTED_OUTPUT_SPARSE_VEC_SIZE_1, 
sparseVector.size());
+                    assertArrayEquals(EXPECTED_OUTPUT_SPARSE_VEC_INDICES_1, 
sparseVector.indices);
+                    assertArrayEquals(
+                            EXPECTED_OUTPUT_SPARSE_VEC_VALUES_1, 
sparseVector.values, 1.0e-5);
+                } else {
+                    assertArrayEquals(
+                            EXPECTED_OUTPUT_DENSE_VEC_ARRAY_1,
+                            ((DenseVector) result.getField(outputCol)).values,
+                            1.0e-5);
+                }
+            } else if (result.getField(0) == (Object) 1) {

Review Comment:
   Do you think the following code could be simpler? Take the sparse vector 
case as an example:
   ```java
       private static final List<Vector> EXPECTED_OUTPUT_SPARSE_VEC =
               Arrays.asList(
                       Vectors.sparse(5, new int[] {3}, new double[] {0.0}),
                       Vectors.sparse(5, new int[] {1, 2, 3, 4}, new double[] 
{1.1, 0.0, 0.0, 0.0}),
                       null
               );
   
   ...
   
       private void verifyOutputResult(Table output, String outputCol, boolean 
isSparse)
               throws Exception {
           List<Row> results = IteratorUtils.toList(output.execute().collect());
           results.sort(Comparator.comparingInt(x -> (Integer) x.getField(0)));
           List<Vector> vectors = results.stream().map(x -> (Vector) 
x.getField(outputCol)).collect(Collectors.toList());
           assertEquals(vectors, EXPECTED_OUTPUT_SPARSE_VEC);
       }
   ```



##########
flink-ml-lib/src/test/java/org/apache/flink/ml/feature/ElementwiseProductTest.java:
##########
@@ -0,0 +1,207 @@
+/*
+ * 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.feature;
+
+import org.apache.flink.api.common.restartstrategy.RestartStrategies;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.ml.feature.elementwiseproduct.ElementwiseProduct;
+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.TestUtils;
+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.table.api.Table;
+import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
+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.Test;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+
+/** Tests {@link ElementwiseProduct}. */
+public class ElementwiseProductTest extends AbstractTestBase {
+
+    private StreamTableEnvironment tEnv;
+    private Table inputDataTable;
+
+    private static final List<Row> INPUT_DATA =
+            Arrays.asList(
+                    Row.of(
+                            0,
+                            Vectors.dense(2.1, 3.1),
+                            Vectors.sparse(5, new int[] {3}, new double[] 
{1.0})),
+                    Row.of(
+                            1,
+                            Vectors.dense(1.1, 3.3),
+                            Vectors.sparse(
+                                    5, new int[] {4, 2, 3, 1}, new double[] 
{4.0, 2.0, 3.0, 1.0})),
+                    Row.of(2, null, null));
+
+    private static final double[] EXPECTED_OUTPUT_DENSE_VEC_ARRAY_1 = new 
double[] {2.31, 3.41};
+    private static final double[] EXPECTED_OUTPUT_DENSE_VEC_ARRAY_2 = new 
double[] {1.21, 3.63};
+
+    private static final int EXPECTED_OUTPUT_SPARSE_VEC_SIZE_1 = 5;
+    private static final int[] EXPECTED_OUTPUT_SPARSE_VEC_INDICES_1 = new 
int[] {3};
+    private static final double[] EXPECTED_OUTPUT_SPARSE_VEC_VALUES_1 = new 
double[] {0.0};
+
+    private static final int EXPECTED_OUTPUT_SPARSE_VEC_SIZE_2 = 5;
+    private static final int[] EXPECTED_OUTPUT_SPARSE_VEC_INDICES_2 = new 
int[] {1, 2, 3, 4};
+    private static final double[] EXPECTED_OUTPUT_SPARSE_VEC_VALUES_2 =
+            new double[] {1.1, 0.0, 0.0, 0.0};

Review Comment:
   It might be uncommon for sparse vectors to store zero values. Can we improve 
it to 
   ```java
       private static final int[] EXPECTED_OUTPUT_SPARSE_VEC_INDICES_2 = new 
int[] {1};
       private static final double[] EXPECTED_OUTPUT_SPARSE_VEC_VALUES_2 =
               new double[] {1.1};
   ```
   by modifying `ElementwiseProduct` or `BLAS.hDot`?



##########
flink-ml-lib/src/main/java/org/apache/flink/ml/feature/elementwiseproduct/ElementwiseProduct.java:
##########
@@ -0,0 +1,112 @@
+/*
+ * 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.feature.elementwiseproduct;
+
+import org.apache.flink.api.common.functions.MapFunction;
+import org.apache.flink.api.java.typeutils.RowTypeInfo;
+import org.apache.flink.ml.api.Transformer;
+import org.apache.flink.ml.common.datastream.TableUtils;
+import org.apache.flink.ml.linalg.BLAS;
+import org.apache.flink.ml.linalg.Vector;
+import org.apache.flink.ml.linalg.typeinfo.VectorTypeInfo;
+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.types.Row;
+import org.apache.flink.util.Preconditions;
+
+import org.apache.commons.lang3.ArrayUtils;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * An transformer that multiplies each input vector with a given scaling 
vector using Hadamard
+ * product.
+ *
+ * <p>If the input vector is null, then the transformer will return null. If 
the input vector size
+ * not equals scaling vector size then the transformer will throw 
IllegalArgumentException.

Review Comment:
   nit: "If the size of the input vector does not equal the size of the scaling 
vector, the transformer will throw {@link IllegalArgumentException}`."



##########
flink-ml-python/pyflink/ml/lib/feature/tests/test_elementwiseproduct.py:
##########
@@ -0,0 +1,83 @@
+################################################################################
+#  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.
+################################################################################
+import os
+
+from pyflink.common import Types
+
+from pyflink.ml.core.linalg import Vectors, DenseVectorTypeInfo
+from pyflink.ml.lib.feature.elementwiseproduct import ElementwiseProduct
+from pyflink.ml.tests.test_utils import PyFlinkMLTestCase
+
+
+class ElementwiseProductTest(PyFlinkMLTestCase):
+    def setUp(self):
+        super(ElementwiseProductTest, self).setUp()
+        self.input_data_table = self.t_env.from_data_stream(
+            self.env.from_collection([
+                (0,
+                 Vectors.dense(2.1, 3.1)),
+                (1,
+                 Vectors.dense(1.1, 3.3)),
+            ],
+                type_info=Types.ROW_NAMED(
+                    ['id', 'vec'],
+                    [Types.INT(), DenseVectorTypeInfo()])))
+
+        self.expected_output_data_1 = Vectors.dense(2.31, 3.41)
+        self.expected_output_data_2 = Vectors.dense(1.21, 3.63)
+
+    def test_param(self):
+        elementwise_product = ElementwiseProduct()
+
+        self.assertEqual('input', elementwise_product.get_input_col())
+        self.assertEqual('output', elementwise_product.get_output_col())
+
+        elementwise_product.set_input_col('vec') \
+            .set_output_col('output_vec') \
+            .set_scaling_vec(Vectors.dense(1.1, 1.1))
+
+        self.assertEqual('vec', elementwise_product.get_input_col())
+        self.assertEqual(Vectors.dense(1.1, 1.1), 
elementwise_product.get_scaling_vec())
+        self.assertEqual('output_vec', elementwise_product.get_output_col())
+
+    def test_save_load_transform(self):
+        elementwise_product = ElementwiseProduct() \
+            .set_input_col('vec') \
+            .set_output_col('output_vec') \
+            .set_scaling_vec(Vectors.dense(1.1, 1.1))
+
+        path = os.path.join(self.temp_dir, 
'test_save_load_transform_elementwise_product')
+        elementwise_product.save(path)
+        elementwise_product = ElementwiseProduct.load(self.t_env, path)
+
+        output_table = elementwise_product.transform(self.input_data_table)[0]
+        actual_outputs = [(result[0], result[2]) for result in
+                          
self.t_env.to_data_stream(output_table).execute_and_collect()]
+
+        self.assertEqual(2, len(actual_outputs))
+        for actual_output in actual_outputs:
+            if actual_output[0] == 0:
+                self.assertAlmostEqual(self.expected_output_data_1.get(0),
+                                       actual_output[1].get(0), delta=1e-7)
+                self.assertAlmostEqual(self.expected_output_data_1.get(1),

Review Comment:
   Can we compare the two vectors or two arrays here, instead of comparing 
values at each index? If it is difficult, let's at least use a for loop here, 
and also check for the size of the vectors.



##########
flink-ml-python/pyflink/ml/core/param.py:
##########
@@ -86,6 +87,8 @@ def get_param_map(self) -> Dict['Param[Any]', Any]:
     @staticmethod
     def _is_compatible_type(param: 'Param[V]', value: V) -> bool:
         if value is not None and param.type != type(value):
+            if type(value).__name__ == 'DenseVector' or type(value).__name__ 
== 'SparseVector':
+                return issubclass(type(value), param.type)

Review Comment:
   Could you please illustrate why we need to add this code here, and why we 
don't need to add corresponding codes in the Java implementation?



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to