becketqin commented on a change in pull request #11344: 
[FLINK-16250][python][ml] Add interfaces for PipelineStage and Pipeline
URL: https://github.com/apache/flink/pull/11344#discussion_r390733535
 
 

 ##########
 File path: flink-python/pyflink/ml/tests/test_pipeline_it_case.py
 ##########
 @@ -0,0 +1,171 @@
+################################################################################
+#  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.table.types import DataTypes
+from pyflink.testing.test_case_utils import MLTestCase
+
+from pyflink.ml.api import JavaTransformer, Transformer, Estimator, Model, \
+    MLEnvironmentFactory, Pipeline
+from pyflink.ml.api.param import WithParams, ParamInfo, TypeConverters
+from pyflink.ml.lib.param.colname import HasSelectedCols,\
+    HasPredictionCol, HasOutputCol
+from pyflink import keyword
+from pyflink.testing import source_sink_utils
+from pyflink.java_gateway import get_gateway
+
+
+class HasVectorCol(WithParams):
+    """
+    Trait for parameter vectorColName.
+    """
+    vector_col = ParamInfo(
+        "vectorCol",
+        "Name of a vector column",
+        is_optional=False,
+        type_converter=TypeConverters.to_string)
+
+    def set_vector_col(self, v: str) -> 'HasVectorCol':
+        return super().set(self.vector_col, v)
+
+    def get_vector_col(self) -> str:
+        return super().get(self.vector_col)
+
+
+class WrapperTransformer(JavaTransformer, HasSelectedCols):
+    """
+    A Transformer wrappers Java Transformer.
+    """
+    @keyword
+    def __init__(self, *, selected_cols=None):
+        _j_obj = get_gateway().jvm.org.apache.flink.ml.pipeline.\
+            UserDefinedPipelineStages.SelectColumnTransformer()
+        super().__init__(_j_obj)
+        kwargs = self._input_kwargs
+        self._set(**kwargs)
+
+
+class PythonAddTransformer(Transformer, HasSelectedCols, HasOutputCol):
+    """
+    A Transformer which is implemented with Python. Output a column
+    contains the sum of all columns.
+    """
+    @keyword
+    def __init__(self, *, selected_cols=None, output_col=None):
+        super().__init__()
+        kwargs = self._input_kwargs
+        self._set(**kwargs)
+
+    def transform(self, table_env, table):
+        input_columns = self.get_selected_cols()
+        expr = "+".join(input_columns)
+        expr = expr + " as " + self.get_output_col()
+        return table.add_columns(expr)
+
+
+class PythonEstimator(Estimator, HasVectorCol, HasPredictionCol):
+
+    def __init__(self):
+        super().__init__()
+
+    def fit(self, table_env, table):
+        return PythonModel(
+            table_env,
+            table.select("max(features) as max_sum"),
+            self.get_prediction_col())
+
+
+class PythonModel(Model):
+
+    def __init__(self, table_env, model_data_table, output_col_name):
+        self._model_data_table = model_data_table
+        self._output_col_name = output_col_name
+        self.max_sum = 0
+        self.load_model(table_env)
+
+    def load_model(self, table_env):
+        """
+        Train the model to get the max_sum value which is used to predicate 
data.
+        """
+        table_sink = source_sink_utils.TestRetractSink(["max_sum"], 
[DataTypes.BIGINT()])
+        table_env.register_table_sink("Model_Results", table_sink)
+        self._model_data_table.insert_into("Model_Results")
+        table_env.execute("load model")
+        actual = source_sink_utils.results()
+        self.max_sum = actual.apply(0)
+
+    def transform(self, table_env, table):
+        """
+        Use max_sum to predicate input. Return turn if input value is bigger 
than max_sum
+        """
+        return table\
+            .add_columns("features > {} as {}".format(self.max_sum, 
self._output_col_name))\
+            .select("{}".format(self._output_col_name))
+
+
+class PythonPipelineTest(MLTestCase):
+
+    def test_java_transformer(self):
+        t_env = 
MLEnvironmentFactory().get_default().get_stream_table_environment()
+
+        table_sink = source_sink_utils.TestAppendSink(
+            ['a', 'b'], [DataTypes.BIGINT(), DataTypes.BIGINT()])
+        t_env.register_table_sink("TransformerResults", table_sink)
+
+        source_table = t_env.from_elements([(1, 2, 3, 4), (4, 3, 2, 1)], ['a', 
'b', 'c', 'd'])
+        transformer = WrapperTransformer(selected_cols=["a", "b"])
+        transformer\
+            .transform(t_env, source_table)\
+            .insert_into("TransformerResults")
+
+        # execute
+        t_env.execute('JavaPipelineITCase')
+        actual = source_sink_utils.results()
+        self.assert_equals(actual, ["1,2", "4,3"])
+
+    def test_pipeline(self):
+        t_env = 
MLEnvironmentFactory().get_default().get_stream_table_environment()
+        train_table = t_env.from_elements(
+            [(1, 2), (1, 4), (1, 0), (10, 2), (10, 4), (10, 0)], ['a', 'b'])
+        serving_table = t_env.from_elements([(0, 0), (12, 3)], ['a', 'b'])
+
+        table_sink = source_sink_utils.TestAppendSink(
+            ['predicate_result'],
 
 Review comment:
   typo -> predictResult

----------------------------------------------------------------
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.
 
For queries about this service, please contact Infrastructure at:
[email protected]


With regards,
Apache Git Services

Reply via email to