-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
e0fb205
commit e9c2988
Showing
2 changed files
with
51 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
43 changes: 43 additions & 0 deletions
43
src/test/java/org/mastodon/mamut/feature/dimensionalityreduction/pca/PCADemo.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
package org.mastodon.mamut.feature.dimensionalityreduction.pca; | ||
|
||
import java.util.ArrayList; | ||
import java.util.List; | ||
|
||
import org.apache.spark.api.java.JavaRDD; | ||
import org.apache.spark.api.java.JavaSparkContext; | ||
import org.apache.spark.mllib.linalg.Matrix; | ||
import org.apache.spark.mllib.linalg.Vector; | ||
import org.apache.spark.mllib.linalg.Vectors; | ||
import org.apache.spark.mllib.linalg.distributed.RowMatrix; | ||
import org.mastodon.mamut.feature.dimensionalityreduction.PlotPoints; | ||
import org.mastodon.mamut.feature.dimensionalityreduction.RandomDataTools; | ||
|
||
public class PCADemo | ||
{ | ||
// TODO: check https://stackoverflow.com/questions/10604507/pca-implementation-in-java | ||
public static void main( String[] args ) | ||
{ | ||
double[][] inputData = RandomDataTools.generateSampleData(); | ||
double[][] result = setUpPCA( inputData ); | ||
PlotPoints.plot( inputData, result, resultValues -> resultValues[ 0 ] > 10 ); | ||
} | ||
|
||
static double[][] setUpPCA( double[][] inputData ) | ||
{ | ||
try (JavaSparkContext jsc = new JavaSparkContext( "local", "PCA" )) | ||
{ | ||
List< Vector > data = new ArrayList<>(); | ||
for ( final double[] row : inputData ) | ||
data.add( Vectors.dense( row ) ); | ||
JavaRDD< Vector > rows = jsc.parallelize( data ); | ||
// Create a RowMatrix from JavaRDD<Vector>. | ||
RowMatrix rowMatrix = new RowMatrix( rows.rdd() ); | ||
// Compute the top 2 principal components. | ||
// Principal components are stored in a local dense matrix. | ||
Matrix pc = rowMatrix.computePrincipalComponents( 2 ); | ||
// Project the rows to the linear space spanned by the top 4 principal components. | ||
RowMatrix projected = rowMatrix.multiply( pc ); | ||
return projected.rows().toJavaRDD().collect().stream().map( Vector::toArray ).toArray( double[][]::new ); | ||
} | ||
} | ||
} |