Просмотр исходного кода

Changed ClusteringPreprocessor to post process only indices

Simon Ding 4 лет назад
Родитель
Сommit
d7fe06864d

+ 4 - 6
jplag/src/main/java/de/jplag/clustering/ClusteringPreprocessor.java

@@ -1,7 +1,5 @@
 package de.jplag.clustering;
 
-import java.util.Collection;
-
 /**
  * Interface for classes that process similarity matrices before any clustering. Classes implementing this interface
  * must ensure that they do not produce zero rows/columns inside the similarity matrix. They must also be able to
@@ -17,9 +15,9 @@ public interface ClusteringPreprocessor {
     double[][] preprocessSimilarities(double[][] similarityMatrix);
 
     /**
-     * Change the indices contained in the clustering result to the indices used before preprocessing.
-     * @param result from clustering with preprocessed similarities
-     * @return the same result but with the indices from the original similarity matrix
+     * Maps the indices of the preprocessed similarity matrix back to indices in the original matrix.
+     * @param index after preprocessing
+     * @return corresponding index before preprocessing
      */
-    Collection<Collection<Integer>> postProcessResult(Collection<Collection<Integer>> result);
+    int originalIndexOf(int index);
 }

+ 3 - 1
jplag/src/main/java/de/jplag/clustering/PreprocessedClusteringAlgorithm.java

@@ -2,6 +2,7 @@ package de.jplag.clustering;
 
 import java.util.Collection;
 import java.util.Collections;
+import java.util.stream.Collectors;
 
 import org.apache.commons.math3.linear.Array2DRowRealMatrix;
 import org.apache.commons.math3.linear.RealMatrix;
@@ -26,7 +27,8 @@ public class PreprocessedClusteringAlgorithm implements GenericClusteringAlgorit
         double[][] data = preprocessor.preprocessSimilarities(similarityMatrix.getData());
         if (data.length > 2) {
             Collection<Collection<Integer>> preliminaryResult = base.cluster(new Array2DRowRealMatrix(data, false));
-            return preprocessor.postProcessResult(preliminaryResult);
+            return preliminaryResult.stream().map(cluster -> cluster.stream().map(preprocessor::originalIndexOf).collect(Collectors.toList()))
+                    .collect(Collectors.toList());
         }
         return Collections.emptyList();
     }

+ 5 - 6
jplag/src/main/java/de/jplag/clustering/PreprocessorHelper.java

@@ -3,7 +3,6 @@ package de.jplag.clustering;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.List;
-import java.util.stream.Collectors;
 import java.util.stream.DoubleStream;
 
 import org.apache.commons.math3.linear.Array2DRowRealMatrix;
@@ -40,11 +39,11 @@ public class PreprocessorHelper {
     }
 
     /**
-     * Implements the logic for {@link ClusteringPreprocessor#postProcessResult(Collection)}
-     * @param result clustering result gained from preprocessed similarities
-     * @return post processed clustering result
+     * Implements the logic for {@link ClusteringPreprocessor#originalIndexOf(Collection)}
+     * @param index after preprocessing
+     * @return corresponding index before preprocessing
      */
-    public Collection<Collection<Integer>> postProcessResult(Collection<Collection<Integer>> result) {
-        return result.stream().map(cluster -> cluster.stream().map(mapping::unmap).collect(Collectors.toList())).collect(Collectors.toList());
+    public int postProcessResult(int result) {
+        return mapping.unmap(result);
     }
 }

+ 6 - 5
jplag/src/main/java/de/jplag/clustering/algorithm/AgglomerativeClustering.java

@@ -5,6 +5,7 @@ import java.util.Collection;
 import java.util.HashSet;
 import java.util.List;
 import java.util.PriorityQueue;
+import java.util.Set;
 import java.util.stream.Collectors;
 
 import org.apache.commons.math3.linear.RealMatrix;
@@ -24,17 +25,17 @@ public class AgglomerativeClustering implements GenericClusteringAlgorithm {
 
     @Override
     public Collection<Collection<Integer>> cluster(RealMatrix similarityMatrix) {
-        int N = similarityMatrix.getRowDimension();
+        int size = similarityMatrix.getRowDimension();
         // all clusters that do not have a parent yet
-        HashSet<Cluster> clusters = new HashSet<>(N);
+        Set<Cluster> clusters = new HashSet<>(size);
         // calculated similarities. Might contain connections to already visited clusters, those need to be ignored.
         PriorityQueue<ClusterConnection> similarities;
 
         {
             // initialization
 
-            ArrayList<Cluster> initialClusters = new ArrayList<>(N);
-            for (int i = 0; i < N; i++) {
+            List<Cluster> initialClusters = new ArrayList<>(size);
+            for (int i = 0; i < size; i++) {
                 List<Integer> members = new ArrayList<>();
                 members.add(i);
                 Cluster cluster = new Cluster(members);
@@ -42,7 +43,7 @@ public class AgglomerativeClustering implements GenericClusteringAlgorithm {
                 clusters.add(cluster);
             }
 
-            ArrayList<ClusterConnection> initialSimilarities = new ArrayList<>(N * (N - 1) / 2);
+            List<ClusterConnection> initialSimilarities = new ArrayList<>(size * (size - 1) / 2);
 
             for (int leftIndex = 0; leftIndex < initialClusters.size(); leftIndex++) {
                 Cluster leftCluster = initialClusters.get(leftIndex);

+ 5 - 1
jplag/src/main/java/de/jplag/clustering/algorithm/BayesianOptimization.java

@@ -30,7 +30,7 @@ public class BayesianOptimization {
     private int initialPoints;
     private double noise;
     private RealVector lengthScale;
-    public boolean debug = false;
+    private boolean debug = false;
 
     /**
      * @param minima of the explored parameters
@@ -55,6 +55,10 @@ public class BayesianOptimization {
         this.lengthScale = lengthScale;
     }
 
+    public void setDebugLogging(boolean debug) {
+        this.debug = debug;
+    }
+
     private Stream<RealVector> sampleSolutionSpace() {
         RandomVectorGenerator generator = new HaltonSequenceGenerator(minima.getDimension());
         RealVector size = maxima.subtract(minima);

+ 2 - 0
jplag/src/main/java/de/jplag/clustering/algorithm/GaussianProcess.java

@@ -92,6 +92,8 @@ public class GaussianProcess {
      * are equal the kernel is isometric.
      */
     public static GaussianProcess fit(List<RealVector> X, double[] Y, double noise, boolean normalize, double[] lengthScale) {
+        if (X.size() < 1)
+            throw new IllegalArgumentException("X is empty");
         if (X.size() != Y.length) {
             throw new IllegalArgumentException(MessageFormat.format("X and Y are of different dimensions {0} and {1}", X.size(), Y.length));
         }

+ 1 - 3
jplag/src/main/java/de/jplag/clustering/preprocessors/CumulativeDistributionFunctionPreprocessor.java

@@ -1,7 +1,5 @@
 package de.jplag.clustering.preprocessors;
 
-import java.util.Collection;
-
 import org.apache.commons.math3.linear.Array2DRowRealMatrix;
 import org.apache.commons.math3.linear.DefaultRealMatrixChangingVisitor;
 import org.apache.commons.math3.linear.DefaultRealMatrixPreservingVisitor;
@@ -48,7 +46,7 @@ public class CumulativeDistributionFunctionPreprocessor implements ClusteringPre
     }
 
     @Override
-    public Collection<Collection<Integer>> postProcessResult(Collection<Collection<Integer>> result) {
+    public int originalIndexOf(int result) {
         return helper.postProcessResult(result);
     }
 

+ 2 - 4
jplag/src/main/java/de/jplag/clustering/preprocessors/PercentileThresholdProcessor.java

@@ -1,7 +1,5 @@
 package de.jplag.clustering.preprocessors;
 
-import java.util.Collection;
-
 import org.apache.commons.math3.linear.Array2DRowRealMatrix;
 import org.apache.commons.math3.linear.DefaultRealMatrixPreservingVisitor;
 import org.apache.commons.math3.stat.descriptive.rank.Percentile;
@@ -46,8 +44,8 @@ public class PercentileThresholdProcessor implements ClusteringPreprocessor {
     }
 
     @Override
-    public Collection<Collection<Integer>> postProcessResult(Collection<Collection<Integer>> result) {
-        return thresholdPreprocessor.postProcessResult(result);
+    public int originalIndexOf(int result) {
+        return thresholdPreprocessor.originalIndexOf(result);
     }
 
 }

+ 1 - 3
jplag/src/main/java/de/jplag/clustering/preprocessors/ThresholdPreprocessor.java

@@ -1,7 +1,5 @@
 package de.jplag.clustering.preprocessors;
 
-import java.util.Collection;
-
 import org.apache.commons.math3.linear.Array2DRowRealMatrix;
 import org.apache.commons.math3.linear.DefaultRealMatrixChangingVisitor;
 import org.apache.commons.math3.linear.RealMatrix;
@@ -34,7 +32,7 @@ public class ThresholdPreprocessor implements ClusteringPreprocessor {
     }
 
     @Override
-    public Collection<Collection<Integer>> postProcessResult(Collection<Collection<Integer>> result) {
+    public int originalIndexOf(int result) {
         return helper.postProcessResult(result);
     }
 

+ 3 - 1
jplag/src/test/java/de/jplag/cli/ClusteringTest.java

@@ -9,12 +9,14 @@ import de.jplag.clustering.Preprocessors;
 
 public class ClusteringTest extends CommandLineInterfaceTest {
 
+    private static final double EPSILON = 0.000001;
+
     @Test
     public void parsePercentilePreProcessor() {
         String argument = CommandLineArgument.CLUSTER_PREPROCESSING_PERCENTILE.flag() + "=" + Float.toString(0.5f);
         buildOptionsFromCLI(argument, CURRENT_DIRECTORY);
         assertEquals(Preprocessors.PERCENTILE, options.getClusteringOptions().getPreprocessor());
-        assertEquals(0.5, options.getClusteringOptions().getPreprocessorPercentile(), 0.000001);
+        assertEquals(0.5, options.getClusteringOptions().getPreprocessorPercentile(), EPSILON);
     }
 
     @Test

+ 4 - 4
jplag/src/test/java/de/jplag/clustering/ClusteringTest.java

@@ -85,8 +85,7 @@ public class ClusteringTest {
         URL url = loadFromClasspath("de/jplag/PseudonymizedReports/alt/C_1000_matches_max.csv");
         File file = new File(url.toURI());
         ReadResult r = readOldCsv(file);
-        ClusteringPreprocessor preprocessor = new CumulativeDistributionFunctionPreprocessor();
-        RealMatrix clusteringSimilarity = new Array2DRowRealMatrix(preprocessor.preprocessSimilarities(r.similarity.getData()));
+        RealMatrix clusteringSimilarity = new Array2DRowRealMatrix(r.similarity.getData());
 
         /*
          * AgglomerativeClustering.ClusteringOptions options = new AgglomerativeClustering.ClusteringOptions();
@@ -95,8 +94,9 @@ public class ClusteringTest {
          */
 
         SpectralClustering clusteringAlg = new SpectralClustering(ClusteringOptions.DEFAULTS);
-        Collection<Collection<Integer>> clustering = clusteringAlg.cluster(clusteringSimilarity);
-        clustering = preprocessor.postProcessResult(clustering);
+        ClusteringPreprocessor preprocessor = new CumulativeDistributionFunctionPreprocessor();
+        GenericClusteringAlgorithm preprocessedClusteringAlg = new PreprocessedClusteringAlgorithm(clusteringAlg, preprocessor);
+        Collection<Collection<Integer>> clustering = preprocessedClusteringAlg.cluster(clusteringSimilarity);
         ClusteringResult<Integer> mRes = ClusteringResult.fromIntegerCollections(new ArrayList<>(clustering), r.similarity);
         List<Cluster<Integer>> clusters = new ArrayList<>(mRes.getClusters());
         clusters.sort(Comparator.comparingDouble(