private List < GraphResult > getPcaData ( double [ ] [ ] data , BiMap < Integer , String > dataNames ) { int rows = data . length ; int cols = data . length ; // Center the similarity matrix. double matrixSum = 0 ; double [ ] rowSums = new double [ rows ] ; for ( int i = 0 ; i < rows ; i ++ ) { for ( int j = 0 ; j < cols ; j ++ ) { matrixSum += data [ i ] [ j ] ; rowSums [ i ] += data [ i ] [ j ] ; } } double matrixMean = matrixSum / rows / cols ; for ( int i = 0 ; i < rows ; i ++ ) { for ( int j = 0 ; j < cols ; j ++ ) { double rowMean = rowSums [ i ] / rows ; double colMean = rowSums [ j ] / rows ; data [ i ] [ j ] = data [ i ] [ j ] - rowMean - colMean + matrixMean ; } } // Determine the eigenvectors, and scale them so that their // sum of squares equals their associated eigenvalue. Matrix matrix = new Matrix ( data ) ; EigenvalueDecomposition eig = matrix . eig ( ) ; Matrix eigenvectors = eig . getV ( ) ; double [ ] realEigenvalues = eig . getRealEigenvalues ( ) ; for ( int j = 0 ; j < eigenvectors . getColumnDimension ( ) ; j ++ ) { double sumSquares = 0 ; for ( int i = 0 ; i < eigenvectors . getRowDimension ( ) ; i ++ ) { sumSquares += eigenvectors . get ( i , j ) * eigenvectors . get ( i , j ) ; } for ( int i = 0 ; i < eigenvectors . getRowDimension ( ) ; i ++ ) { eigenvectors . set ( i , j , eigenvectors . get ( i , j ) * Math . sqrt ( realEigenvalues [ j ] / sumSquares ) ) ; } } // Find the indices of the top two eigenvalues. int maxIndex = - 1 ; int secondIndex = - 1 ; double maxEigenvalue = 0 ; double secondEigenvalue = 0 ; for ( int i = 0 ; i < realEigenvalues . length ; i ++ ) { double eigenvector = realEigenvalues [ i ] ; if ( eigenvector > maxEigenvalue ) { secondEigenvalue = maxEigenvalue ; secondIndex = maxIndex ; maxEigenvalue = eigenvector ; maxIndex = i ; } else if ( eigenvector > secondEigenvalue ) { secondEigenvalue = eigenvector ; secondIndex = i ; } } // Return projected data List < GraphResult > results = Lists . newArrayList ( ) ; for ( int i = 0 ; i < rows ; i ++ ) { results . add ( new GraphResult ( dataNames . get ( i ) , eigenvectors . get ( i , maxIndex ) , eigenvectors . get ( i , secondIndex ) ) ) ; } return results ; }
Convert the similarity matrix to an Eigen matrix .