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


##########
flink-ml-lib/src/test/java/org/apache/flink/ml/clustering/AgglomerativeClusteringTest.java:
##########
@@ -0,0 +1,312 @@
+/*
+ * 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.clustering;
+
+import org.apache.flink.api.common.restartstrategy.RestartStrategies;
+import org.apache.flink.configuration.Configuration;
+import 
org.apache.flink.ml.clustering.agglomerativeclustering.AgglomerativeClustering;
+import 
org.apache.flink.ml.clustering.agglomerativeclustering.AgglomerativeClusteringParams;
+import org.apache.flink.ml.common.distance.CosineDistanceMeasure;
+import org.apache.flink.ml.common.distance.EuclideanDistanceMeasure;
+import org.apache.flink.ml.common.distance.ManhattanDistanceMeasure;
+import org.apache.flink.ml.linalg.DenseVector;
+import org.apache.flink.ml.linalg.Vectors;
+import org.apache.flink.ml.util.TestUtils;
+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.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+/** Tests {@link AgglomerativeClustering}. */
+public class AgglomerativeClusteringTest extends AbstractTestBase {
+
+    @Rule public final TemporaryFolder tempFolder = new TemporaryFolder();
+    private StreamTableEnvironment tEnv;
+    private StreamExecutionEnvironment env;
+    private Table inputDataTable;
+
+    private static final List<DenseVector> INPUT_DATA =
+            Arrays.asList(
+                    Vectors.dense(1, 1),
+                    Vectors.dense(1, 4),
+                    Vectors.dense(1, 0),
+                    Vectors.dense(4, 1.5),
+                    Vectors.dense(4, 4),
+                    Vectors.dense(4, 0));
+
+    private static final List<Row> EUCLIDEAN_AVERAGE_MERGE_INFO =
+            Arrays.asList(
+                    Row.of(0, 2, 1, 2),
+                    Row.of(3, 5, 1.5, 2),
+                    Row.of(1, 4, 3, 2),
+                    Row.of(6, 7, 3.1394402, 4),
+                    Row.of(8, 9, 3.9559706, 6));
+
+    private static final List<Row> COSINE_AVERAGE_MERGE_INFO =
+            Arrays.asList(
+                    Row.of(2, 5, 0, 2),
+                    Row.of(0, 4, 1.1102230E-16, 2),
+                    Row.of(3, 6, 0.0636708, 3),
+                    Row.of(1, 7, 0.1425070, 3),
+                    Row.of(8, 9, 0.3664484, 6));
+
+    private static final List<Row> MANHATTAN_AVERAGE_MERGE_INFO =
+            Arrays.asList(
+                    Row.of(0, 2, 1, 2),
+                    Row.of(3, 5, 1.5, 2),
+                    Row.of(1, 4, 3, 2),
+                    Row.of(6, 7, 3.75, 4),
+                    Row.of(8, 9, 4.875, 6));
+
+    private static final List<Row> EUCLIDEAN_SINGLE_MERGE_INFO =
+            Arrays.asList(
+                    Row.of(0, 2, 1, 2),
+                    Row.of(3, 5, 1.5, 2),
+                    Row.of(4, 7, 2.5, 3),
+                    Row.of(8, 9, 3, 6),
+                    Row.of(1, 6, 3, 3));
+
+    private static final List<Row> EUCLIDEAN_WARD_MERGE_INFO =
+            Arrays.asList(
+                    Row.of(0, 2, 1, 2),
+                    Row.of(3, 5, 1.5, 2),
+                    Row.of(1, 4, 3, 2),
+                    Row.of(6, 7, 4.2573465, 4),
+                    Row.of(8, 9, 5.5113519, 6));
+
+    private static final List<Row> EUCLIDEAN_COMPLETE_MERGE_INFO =
+            Arrays.asList(
+                    Row.of(0, 2, 1, 2),
+                    Row.of(3, 5, 1.5, 2),
+                    Row.of(1, 4, 3, 2),
+                    Row.of(6, 7, 3.3541019, 4),
+                    Row.of(8, 9, 5, 6));
+
+    private static final List<Row> EUCLIDEAN_WARD_K_AS_TWO_RESULT =
+            Arrays.asList(
+                    Row.of(Vectors.dense(1, 1), 0),
+                    Row.of(Vectors.dense(1, 4), 1),
+                    Row.of(Vectors.dense(1, 0), 0),
+                    Row.of(Vectors.dense(4, 1.5), 0),
+                    Row.of(Vectors.dense(4, 4), 1),
+                    Row.of(Vectors.dense(4, 0), 0));
+
+    private static final List<Row> EUCLIDEAN_WARD_THRESHOLD_AS_TWO_RESULT =
+            Arrays.asList(
+                    Row.of(Vectors.dense(1, 1), 0),
+                    Row.of(Vectors.dense(1, 4), 1),
+                    Row.of(Vectors.dense(1, 0), 0),
+                    Row.of(Vectors.dense(4, 1.5), 2),
+                    Row.of(Vectors.dense(4, 4), 1),
+                    Row.of(Vectors.dense(4, 0), 2));
+
+    private static final double TOLERANCE = 1e-7;
+
+    @Before
+    public void before() {
+        Configuration config = new Configuration();
+        
config.set(ExecutionCheckpointingOptions.ENABLE_CHECKPOINTS_AFTER_TASKS_FINISH, 
true);
+        env = StreamExecutionEnvironment.getExecutionEnvironment(config);
+        env.setParallelism(3);
+        env.enableCheckpointing(100);
+        env.setRestartStrategy(RestartStrategies.noRestart());
+        tEnv = StreamTableEnvironment.create(env);
+        inputDataTable = 
tEnv.fromDataStream(env.fromCollection(INPUT_DATA)).as("features");
+    }
+
+    @Test
+    public void testParam() {
+        AgglomerativeClustering agglomerativeClustering = new 
AgglomerativeClustering();
+        assertEquals("features", agglomerativeClustering.getFeaturesCol());
+        assertEquals(2, agglomerativeClustering.getK().intValue());
+        assertNull(agglomerativeClustering.getDistanceThreshold());
+        assertEquals(AgglomerativeClustering.LINKAGE_WARD, 
agglomerativeClustering.getLinkage());
+        assertEquals(EuclideanDistanceMeasure.NAME, 
agglomerativeClustering.getDistanceMeasure());
+        assertFalse(agglomerativeClustering.getComputeFullTree());
+        assertEquals("prediction", agglomerativeClustering.getPredictionCol());
+
+        agglomerativeClustering
+                .setFeaturesCol("test_features")
+                .setK(null)
+                .setDistanceThreshold(0.01)
+                .setLinkage(AgglomerativeClusteringParams.LINKAGE_AVERAGE)
+                .setDistanceMeasure(CosineDistanceMeasure.NAME)
+                .setComputeFullTree(true)
+                .setPredictionCol("cluster_id");
+
+        assertEquals("test_features", 
agglomerativeClustering.getFeaturesCol());
+        assertNull(agglomerativeClustering.getK());
+        assertEquals(0.01, agglomerativeClustering.getDistanceThreshold(), 
TOLERANCE);
+        assertEquals(AgglomerativeClustering.LINKAGE_AVERAGE, 
agglomerativeClustering.getLinkage());
+        assertEquals(CosineDistanceMeasure.NAME, 
agglomerativeClustering.getDistanceMeasure());
+        assertTrue(agglomerativeClustering.getComputeFullTree());
+        assertEquals("cluster_id", agglomerativeClustering.getPredictionCol());
+    }
+
+    @Test
+    public void testOutputSchema() {
+        Table tempTable =
+                tEnv.fromDataStream(env.fromElements(Row.of("", "")))
+                        .as("test_features", "dummy_input");
+        AgglomerativeClustering agglomerativeClustering =
+                new AgglomerativeClustering()
+                        .setFeaturesCol("test_features")
+                        .setPredictionCol("test_prediction");
+        Table[] outputs = agglomerativeClustering.transform(tempTable);
+        assertEquals(2, outputs.length);
+        assertEquals(
+                Arrays.asList("test_features", "dummy_input", 
"test_prediction"),
+                outputs[0].getResolvedSchema().getColumnNames());
+        assertEquals(
+                Arrays.asList("clusterId1", "clusterId2", "distance", 
"sizeOfMergedCluster"),
+                outputs[1].getResolvedSchema().getColumnNames());
+    }
+
+    @Test
+    public void testTransform() throws Exception {
+        Table[] outputs;
+        AgglomerativeClustering agglomerativeClustering =
+                new AgglomerativeClustering()
+                        
.setLinkage(AgglomerativeClusteringParams.LINKAGE_AVERAGE)
+                        .setDistanceMeasure(EuclideanDistanceMeasure.NAME)
+                        .setPredictionCol("pred");
+
+        // Tests euclidean distance with linkage as average, k = 2.
+        outputs = agglomerativeClustering.transform(inputDataTable);
+        verifyClusteringResult(EUCLIDEAN_WARD_K_AS_TWO_RESULT, outputs[0]);
+
+        // Tests euclidean distance with linkage as average, k = 2, 
compute_full_tree = true.
+        outputs = 
agglomerativeClustering.setComputeFullTree(true).transform(inputDataTable);
+        verifyClusteringResult(EUCLIDEAN_WARD_K_AS_TWO_RESULT, outputs[0]);
+
+        // Tests euclidean distance with linkage as average, 
distance_threshold = 2.
+        outputs =
+                agglomerativeClustering
+                        .setK(null)
+                        .setDistanceThreshold(2.0)
+                        .transform(inputDataTable);
+        verifyClusteringResult(EUCLIDEAN_WARD_THRESHOLD_AS_TWO_RESULT, 
outputs[0]);
+    }
+
+    @Test
+    public void testMergeInfo() throws Exception {
+        Table[] outputs;
+        AgglomerativeClustering agglomerativeClustering =
+                new AgglomerativeClustering()
+                        
.setLinkage(AgglomerativeClusteringParams.LINKAGE_AVERAGE)
+                        .setDistanceMeasure(EuclideanDistanceMeasure.NAME)
+                        .setPredictionCol("pred")
+                        .setComputeFullTree(true);
+
+        // Tests euclidean distance with linkage as average.
+        outputs = agglomerativeClustering.transform(inputDataTable);
+        verifyMergeInfo(EUCLIDEAN_AVERAGE_MERGE_INFO, outputs[1]);
+
+        // Tests cosine distance with linkage as average.
+        agglomerativeClustering.setDistanceMeasure(CosineDistanceMeasure.NAME);
+        outputs = agglomerativeClustering.transform(inputDataTable);
+        verifyMergeInfo(COSINE_AVERAGE_MERGE_INFO, outputs[1]);
+
+        // Tests manhattan distance with linkage as average.
+        
agglomerativeClustering.setDistanceMeasure(ManhattanDistanceMeasure.NAME);
+        outputs = agglomerativeClustering.transform(inputDataTable);
+        verifyMergeInfo(MANHATTAN_AVERAGE_MERGE_INFO, outputs[1]);
+
+        // Tests euclidean distance with linkage as complete.
+        agglomerativeClustering
+                .setDistanceMeasure(EuclideanDistanceMeasure.NAME)
+                .setLinkage(AgglomerativeClusteringParams.LINKAGE_COMPLETE);
+        outputs = agglomerativeClustering.transform(inputDataTable);
+        verifyMergeInfo(EUCLIDEAN_COMPLETE_MERGE_INFO, outputs[1]);
+
+        // Tests euclidean distance with linkage as single.
+        
agglomerativeClustering.setLinkage(AgglomerativeClusteringParams.LINKAGE_SINGLE);
+        outputs = agglomerativeClustering.transform(inputDataTable);
+        verifyMergeInfo(EUCLIDEAN_SINGLE_MERGE_INFO, outputs[1]);
+
+        // Tests euclidean distance with linkage as ward.
+        
agglomerativeClustering.setLinkage(AgglomerativeClusteringParams.LINKAGE_WARD);
+        outputs = agglomerativeClustering.transform(inputDataTable);
+        verifyMergeInfo(EUCLIDEAN_WARD_MERGE_INFO, outputs[1]);
+
+        // Tests merge info not fully computed.
+        agglomerativeClustering.setComputeFullTree(false);
+        outputs = agglomerativeClustering.transform(inputDataTable);
+        verifyMergeInfo(EUCLIDEAN_WARD_MERGE_INFO.subList(0, 4), outputs[1]);
+    }
+
+    @Test
+    public void testSaveLoadTransform() throws Exception {
+        AgglomerativeClustering agglomerativeClustering =
+                new AgglomerativeClustering()
+                        
.setLinkage(AgglomerativeClusteringParams.LINKAGE_AVERAGE)
+                        .setDistanceMeasure(EuclideanDistanceMeasure.NAME)
+                        .setPredictionCol("pred");
+
+        agglomerativeClustering =
+                TestUtils.saveAndReload(
+                        tEnv, agglomerativeClustering, 
tempFolder.newFolder().getAbsolutePath());
+
+        Table[] outputs = agglomerativeClustering.transform(inputDataTable);
+        verifyClusteringResult(EUCLIDEAN_WARD_K_AS_TWO_RESULT, outputs[0]);
+    }
+
+    @SuppressWarnings("unchecked")
+    private void verifyMergeInfo(List<Row> expected, Table mergeInfoTable) 
throws Exception {
+        List<Row> mergeInfo =
+                
IteratorUtils.toList(tEnv.toDataStream(mergeInfoTable).executeAndCollect());
+        assertEquals(expected.size(), mergeInfo.size());
+        mergeInfo.sort(Comparator.comparingInt(o -> o.getFieldAs(0)));

Review Comment:
   Good catch. I have changed the unit test to verify the order of the merge 
information.



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