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/10/14 06:32:30 UTC

[GitHub] [flink-ml] yunfengzhou-hub opened a new pull request, #163: [FLINK-29591] Add built-in UDFs to convert between arrays and vectors

yunfengzhou-hub opened a new pull request, #163:
URL: https://github.com/apache/flink-ml/pull/163

   ## What is the purpose of the change
   
   This PR adds functions to convert between Vectors and numerical arrays
   
   ## Brief change log
   
   - Adds ScalarFunctions to convert Vectors to arrays and back.
   - Adds static utility functions to wrap the conversion logic.
   - Adds support for DenseVector DataType in python.
   - Adds examples and documentation of the utility functions above.
   
   ## Does this pull request potentially affect one of the following parts:
   
     - Dependencies (does it add or upgrade a dependency): (no)
     - The public API, i.e., is any changed class annotated with `@Public(Evolving)`: (yes)
   
   ## Documentation
   
     - Does this pull request introduce a new feature? (yes)
     - If yes, how is the feature documented? (JavaDocs)
   


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


[GitHub] [flink-ml] yunfengzhou-hub commented on a diff in pull request #163: [FLINK-29591] Add built-in UDFs to convert between arrays and vectors

Posted by GitBox <gi...@apache.org>.
yunfengzhou-hub commented on code in PR #163:
URL: https://github.com/apache/flink-ml/pull/163#discussion_r996813015


##########
flink-ml-python/pyflink/ml/core/linalg.py:
##########
@@ -776,3 +777,15 @@ def _double_to_long_bits(value: float) -> int:
         value = float("nan")
     # pack double into 64 bits, then unpack as long int
     return struct.unpack("Q", struct.pack("d", value))[0]
+
+
+parent_from_java_type = typeinfo._from_java_type
+
+
+def _from_java_type(j_type_info: JavaObject):
+    if "GenericType<org.apache.flink.ml.linalg.DenseVector>" == str(j_type_info):
+        return DenseVectorTypeInfo()
+    return parent_from_java_type(j_type_info)
+
+
+typeinfo._from_java_type = _from_java_type

Review Comment:
   According to offline discussion, I'll merge the logic related to java type here into that defined in `wrapper.py`, and extract the common logic of functions into wrapper.py. In this case, all usages of java vector type would go through wrapper.py and use the modified version of `_from_java_type()`.



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


[GitHub] [flink-ml] lindong28 commented on a diff in pull request #163: [FLINK-29591] Add built-in UDFs to convert between arrays and vectors

Posted by GitBox <gi...@apache.org>.
lindong28 commented on code in PR #163:
URL: https://github.com/apache/flink-ml/pull/163#discussion_r997598885


##########
flink-ml-python/pyflink/ml/core/wrapper.py:
##########
@@ -22,16 +22,15 @@
 from pyflink.common import typeinfo, Time
 from pyflink.common.typeinfo import _from_java_type, TypeInformation, _is_instance_of
 from pyflink.java_gateway import get_gateway
-from pyflink.table import Table, StreamTableEnvironment
-from pyflink.util.java_utils import to_jarray
-
 from pyflink.ml.core.api import Model, Transformer, AlgoOperator, Stage, Estimator
 from pyflink.ml.core.linalg import DenseVectorTypeInfo, SparseVectorTypeInfo, DenseMatrixTypeInfo, \
     VectorTypeInfo, DenseVector
 from pyflink.ml.core.param import Param, WithParams, StringArrayParam, IntArrayParam, VectorParam, \
     FloatArrayParam, FloatArrayArrayParam, WindowsParam
 from pyflink.ml.core.windows import GlobalWindows, CountTumblingWindows, EventTimeTumblingWindows, \
     ProcessingTimeTumblingWindows, EventTimeSessionWindows, ProcessingTimeSessionWindows
+from pyflink.table import Table, StreamTableEnvironment, Expression

Review Comment:
   Can we avoid unnecessary movement of import statements?



##########
flink-ml-python/pyflink/examples/ml/arraytovector_example.py:
##########
@@ -0,0 +1,60 @@
+################################################################################
+#  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.
+################################################################################
+
+# Simple program that converts double arrays to vectors.

Review Comment:
   nits: Would it be more informative and consistent with `double arrays` to specify the type of vectors like below:
   
   vectors -> dense vectors
   
   Same for other occurrences of this comment.



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


[GitHub] [flink-ml] yunfengzhou-hub commented on a diff in pull request #163: [FLINK-29591] Add built-in UDFs to convert between arrays and vectors

Posted by GitBox <gi...@apache.org>.
yunfengzhou-hub commented on code in PR #163:
URL: https://github.com/apache/flink-ml/pull/163#discussion_r996638399


##########
flink-ml-python/pyflink/ml/core/linalg.py:
##########
@@ -776,3 +777,15 @@ def _double_to_long_bits(value: float) -> int:
         value = float("nan")
     # pack double into 64 bits, then unpack as long int
     return struct.unpack("Q", struct.pack("d", value))[0]
+
+
+parent_from_java_type = typeinfo._from_java_type
+
+
+def _from_java_type(j_type_info: JavaObject):
+    if "GenericType<org.apache.flink.ml.linalg.DenseVector>" == str(j_type_info):
+        return DenseVectorTypeInfo()
+    return parent_from_java_type(j_type_info)
+
+
+typeinfo._from_java_type = _from_java_type

Review Comment:
   It might be a little complicated to import a project's own class (DenseVectorTypeInfo) in the project's `__init__.py`. The current best practice is to define the module change in the most related non-init file, like the change of `_from_java_type_wrapper` in `pyflink/ml/core/wrapper.py`.



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


[GitHub] [flink-ml] lindong28 merged pull request #163: [FLINK-29591] Add built-in UDFs to convert between arrays and vectors

Posted by GitBox <gi...@apache.org>.
lindong28 merged PR #163:
URL: https://github.com/apache/flink-ml/pull/163


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


[GitHub] [flink-ml] lindong28 commented on a diff in pull request #163: [FLINK-29591] Add built-in UDFs to convert between arrays and vectors

Posted by GitBox <gi...@apache.org>.
lindong28 commented on code in PR #163:
URL: https://github.com/apache/flink-ml/pull/163#discussion_r996575556


##########
flink-ml-python/pyflink/ml/core/linalg.py:
##########
@@ -776,3 +777,15 @@ def _double_to_long_bits(value: float) -> int:
         value = float("nan")
     # pack double into 64 bits, then unpack as long int
     return struct.unpack("Q", struct.pack("d", value))[0]
+
+
+parent_from_java_type = typeinfo._from_java_type
+
+
+def _from_java_type(j_type_info: JavaObject):
+    if "GenericType<org.apache.flink.ml.linalg.DenseVector>" == str(j_type_info):
+        return DenseVectorTypeInfo()
+    return parent_from_java_type(j_type_info)
+
+
+typeinfo._from_java_type = _from_java_type

Review Comment:
   Would it be better to put the global module changes in `flink-ml-python/pyflink/ml/__init__.py`?



##########
flink-ml-python/pyflink/ml/lib/tests/test_functions.py:
##########
@@ -0,0 +1,114 @@
+################################################################################
+#  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.
+################################################################################
+from pyflink.common import Types
+from pyflink.ml.core.linalg import Vectors, DenseVectorTypeInfo, SparseVectorTypeInfo, \
+    VectorTypeInfo
+from pyflink.ml.lib.functions import vector_to_array, array_to_vector
+from pyflink.ml.tests.test_utils import PyFlinkMLTestCase
+from pyflink.table.expressions import col
+
+
+class FunctionsTest(PyFlinkMLTestCase):
+    def setUp(self):
+        super(FunctionsTest, self).setUp()
+
+        self.double_arrays = [
+            ([0.0, 0.0],),
+            ([0.0, 1.0],),
+        ]
+
+        self.float_arrays = [
+            ([float(0.0), float(0.0)],),
+            ([float(0.0), float(1.0)],),
+        ]
+
+        self.int_arrays = [
+            ([0, 0],),
+            ([0, 1],),
+        ]
+
+        self.dense_vectors = [
+            (Vectors.dense(0.0, 0.0),),
+            (Vectors.dense(0.0, 1.0),),
+        ]
+
+        self.sparse_vectors = [
+            (Vectors.sparse(2, [], []),),
+            (Vectors.sparse(2, [1], [1.0]),),
+        ]
+
+        self.mixed_vectors = [
+            (Vectors.dense(0.0, 0.0),),
+            (Vectors.sparse(2, [1], [1.0]),),
+        ]
+
+    def test_vector_to_array(self):
+        self._test_vector_to_array(self.dense_vectors, DenseVectorTypeInfo())
+        self._test_vector_to_array(self.sparse_vectors, SparseVectorTypeInfo())
+        self._test_vector_to_array(self.mixed_vectors, VectorTypeInfo())
+
+    def _test_vector_to_array(self, vectors, vector_type_info):
+        input_table = self.t_env.from_data_stream(
+            self.env.from_collection(vectors,
+                                     type_info=Types.ROW_NAMED(
+                                         ['vector'],
+                                         [vector_type_info])
+                                     ))
+
+        output_table = input_table.select(vector_to_array(col('vector')).alias('array'))
+
+        output_value = [x['array'] for x in self.t_env.to_data_stream(output_table)
+                        .map(lambda r: r).execute_and_collect()]
+
+        self.assertEqual(len(output_value), len(self.double_arrays))
+
+        output_value.sort(key=lambda x: x[1])
+
+        for i in range(len(self.double_arrays)):
+            self.assertEqual(self.double_arrays[i][0], output_value[i])
+
+    def test_array_to_vector(self):
+        self._test_array_to_vector(self.double_arrays, Types.DOUBLE())
+        self._test_array_to_vector(self.float_arrays, Types.FLOAT())
+        self._test_array_to_vector(self.int_arrays, Types.INT())
+        self._test_array_to_vector(self.int_arrays, Types.LONG())
+
+    def _test_array_to_vector(self, arrays, array_element_type_info):
+        input_table = self.t_env.from_data_stream(
+            self.env.from_collection(
+                arrays,
+                type_info=Types.ROW_NAMED(
+                    ['array'],
+                    [Types.PRIMITIVE_ARRAY(array_element_type_info)]
+                )
+            )
+        )
+
+        output_table = input_table.select(array_to_vector(col('array')).alias('vector'))
+
+        field_names = output_table.get_schema().get_field_names()
+
+        output_value = [x[field_names.index('vector')] for x in

Review Comment:
   output_value -> output_values



##########
docs/content/docs/operators/functions.md:
##########
@@ -0,0 +1,236 @@
+---
+title: "Functions"
+type: docs
+weight: 2
+aliases:
+- /operators/functions.html
+---
+<!--
+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.
+-->
+
+## Functions
+
+Flink ML provides users with some built-in functions for data transformations.
+This page gives a brief overview of them. 
+
+### vectorToArray
+
+This function converts vectors into double arrays.

Review Comment:
   Would it be useful to mention sparse/dense like below? Same for similar comments in this PR.
   
   This function converts a column of Flink ML sparse/dense vectors into a column of dense arrays.



##########
docs/content/docs/operators/functions.md:
##########
@@ -0,0 +1,236 @@
+---
+title: "Functions"
+type: docs
+weight: 2
+aliases:
+- /operators/functions.html
+---
+<!--
+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.
+-->
+
+## Functions
+
+Flink ML provides users with some built-in functions for data transformations.
+This page gives a brief overview of them. 
+
+### vectorToArray
+
+This function converts vectors into double arrays.
+
+{{< tabs vectorToArray_examples >}}
+
+{{< tab "Java">}}
+```java
+import org.apache.flink.ml.linalg.Vector;
+import org.apache.flink.ml.linalg.Vectors;
+import org.apache.flink.ml.linalg.typeinfo.VectorTypeInfo;
+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.flink.util.CloseableIterator;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.apache.flink.ml.Functions.vectorToArray;
+import static org.apache.flink.table.api.Expressions.$;
+
+/** Simple program that converts vectors to double arrays. */
+public class VectorToArrayExample {
+    public static void main(String[] args) {
+        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
+        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
+
+        // Generates input vector data.
+        List<Vector> vectors =
+                Arrays.asList(
+                        Vectors.dense(0.0, 0.0),
+                        Vectors.sparse(2, new int[] {1}, new double[] {1.0}));
+        Table inputTable =
+                tEnv.fromDataStream(env.fromCollection(vectors, VectorTypeInfo.INSTANCE))
+                        .as("vector");
+
+        // Converts each vector to a double array.
+        Table outputTable = inputTable.select($("vector"), vectorToArray($("vector")).as("array"));
+
+        // Extracts and displays the results.
+        for (CloseableIterator<Row> it = outputTable.execute().collect(); it.hasNext(); ) {
+            Row row = it.next();
+            Vector vector = row.getFieldAs("vector");
+            Double[] doubleArray = row.getFieldAs("array");
+            System.out.printf(
+                    "Input vector: %s\tOutput double array: %s\n",
+                    vector, Arrays.toString(doubleArray));
+        }
+    }
+}
+```
+{{< /tab>}}
+
+{{< tab "Python">}}
+```python
+# Simple program that converts vectors to double arrays.
+
+from pyflink.common import Types
+from pyflink.datastream import StreamExecutionEnvironment
+from pyflink.table import StreamTableEnvironment
+
+from pyflink.ml.core.linalg import Vectors, VectorTypeInfo
+
+from pyflink.ml.lib.functions import vector_to_array
+from pyflink.table.expressions import col
+
+# create a new StreamExecutionEnvironment
+env = StreamExecutionEnvironment.get_execution_environment()
+
+# create a StreamTableEnvironment
+t_env = StreamTableEnvironment.create(env)
+
+# generate input vector data
+vectors = [
+    (Vectors.dense(0.0, 0.0),),
+    (Vectors.sparse(2, [1], [1.0]),),
+]
+input_table = t_env.from_data_stream(
+    env.from_collection(
+        vectors,
+        type_info=Types.ROW_NAMED(
+            ['vector'],
+            [VectorTypeInfo()])
+    ))
+
+# convert each vector to a double array
+output_table = input_table.select(vector_to_array(col('vector')).alias('array'))
+
+# extract and display the results
+output_value = [x for x in
+                t_env.to_data_stream(output_table).map(lambda r: r).execute_and_collect()]
+
+output_value.sort(key=lambda x: x[0])
+
+field_names = output_table.get_schema().get_field_names()
+for i in range(len(output_value)):
+    vector = vectors[i][0]
+    double_array = output_value[i][field_names.index("array")]
+    print("Input vector: %s \t output double array: %s" % (vector, double_array))
+
+```
+{{< /tab>}}
+
+{{< /tabs>}}
+
+### arrayToVector
+
+This function converts numerical arrays into vectors.

Review Comment:
   Would it be useful to mention the specific python class of the output value like below? Same for related comments in this PR.
   
   This function converts a column of arrays of numeric type into a column of pyflink.ml.core.linalg.DenseVector instances.



##########
flink-ml-python/pyflink/ml/lib/tests/test_functions.py:
##########
@@ -0,0 +1,114 @@
+################################################################################
+#  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.
+################################################################################
+from pyflink.common import Types
+from pyflink.ml.core.linalg import Vectors, DenseVectorTypeInfo, SparseVectorTypeInfo, \
+    VectorTypeInfo
+from pyflink.ml.lib.functions import vector_to_array, array_to_vector
+from pyflink.ml.tests.test_utils import PyFlinkMLTestCase
+from pyflink.table.expressions import col
+
+
+class FunctionsTest(PyFlinkMLTestCase):
+    def setUp(self):
+        super(FunctionsTest, self).setUp()
+
+        self.double_arrays = [
+            ([0.0, 0.0],),
+            ([0.0, 1.0],),
+        ]
+
+        self.float_arrays = [
+            ([float(0.0), float(0.0)],),
+            ([float(0.0), float(1.0)],),
+        ]
+
+        self.int_arrays = [
+            ([0, 0],),
+            ([0, 1],),
+        ]
+
+        self.dense_vectors = [
+            (Vectors.dense(0.0, 0.0),),
+            (Vectors.dense(0.0, 1.0),),
+        ]
+
+        self.sparse_vectors = [
+            (Vectors.sparse(2, [], []),),
+            (Vectors.sparse(2, [1], [1.0]),),
+        ]
+
+        self.mixed_vectors = [
+            (Vectors.dense(0.0, 0.0),),
+            (Vectors.sparse(2, [1], [1.0]),),
+        ]
+
+    def test_vector_to_array(self):
+        self._test_vector_to_array(self.dense_vectors, DenseVectorTypeInfo())
+        self._test_vector_to_array(self.sparse_vectors, SparseVectorTypeInfo())
+        self._test_vector_to_array(self.mixed_vectors, VectorTypeInfo())
+
+    def _test_vector_to_array(self, vectors, vector_type_info):
+        input_table = self.t_env.from_data_stream(
+            self.env.from_collection(vectors,
+                                     type_info=Types.ROW_NAMED(
+                                         ['vector'],
+                                         [vector_type_info])
+                                     ))
+
+        output_table = input_table.select(vector_to_array(col('vector')).alias('array'))
+
+        output_value = [x['array'] for x in self.t_env.to_data_stream(output_table)

Review Comment:
   output_value -> output_values



##########
docs/content/docs/operators/functions.md:
##########
@@ -0,0 +1,236 @@
+---
+title: "Functions"
+type: docs
+weight: 2
+aliases:
+- /operators/functions.html
+---
+<!--
+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.
+-->
+
+## Functions
+
+Flink ML provides users with some built-in functions for data transformations.

Review Comment:
   Would it be useful to specifically mention that these are table functions?
   
   Same for related comments in this PR.



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


[GitHub] [flink-ml] lindong28 commented on pull request #163: [FLINK-29591] Add built-in UDFs to convert between arrays and vectors

Posted by GitBox <gi...@apache.org>.
lindong28 commented on PR #163:
URL: https://github.com/apache/flink-ml/pull/163#issuecomment-1281747469

   Thanks for the PR. LGTM.


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