1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | import weka.core.matrix.Matrix; public class EntropyCalculator { public static double getEntropy(Matrix matrix) { double entropy = 0 ; double [] sumOfRows = getSumOfRows(matrix); double sumOfMatrix = 0 ; for ( int i = 0 ; i < sumOfRows.length; i++) { sumOfMatrix += sumOfRows[i]; } for ( int i = 0 ; i < matrix.getRowDimension(); i++) { double r = sumOfRows[i] / sumOfMatrix; double sum = 0 ; for ( int j = 0 ; j < matrix.getColumnDimension(); j++) { double x = matrix.get(i, j) / sumOfRows[i]; if (x == 0 ) { sum += 0 ; } else { sum += x * (Math.log10(x) / Math.log10( 2 )); } } entropy += (r * sum) * (- 1 ); } return entropy; } private static double [] getSumOfRows(Matrix matrix) { double [] result = new double [matrix.getRowDimension()]; for ( int i = 0 ; i < matrix.getRowDimension(); i++) { for ( int j = 0 ; j < matrix.getColumnDimension(); j++) { result[i] += matrix.get(i, j); } } return result; } private static double [] getSumOfColumns(Matrix matrix) { double [] result = new double [matrix.getColumnDimension()]; for ( int i = 0 ; i < matrix.getRowDimension(); i++) { for ( int j = 0 ; j < matrix.getColumnDimension(); j++) { result[j] += matrix.get(i, j); } } return result; } public static void main(String[] args) { double [][] array = new double [ 3 ][ 3 ]; array[ 0 ][ 0 ] = 3 ; array[ 0 ][ 1 ] = 4 ; array[ 0 ][ 2 ] = 12 ; array[ 1 ][ 0 ] = 8 ; array[ 1 ][ 1 ] = 3 ; array[ 1 ][ 2 ] = 12 ; array[ 2 ][ 0 ] = 12 ; array[ 2 ][ 1 ] = 12 ; array[ 2 ][ 2 ] = 0 ; System.out.println(getEntropy( new Matrix(array))); } |
Entropy In Java
Subscribe to:
Posts
(
Atom
)
No comments :
Post a Comment