import java.util.Random; import java.util.ArrayList; import java.util.StringTokenizer; import java.io.*; public class NNUtils { public static float[][] multiply(float[][] a,float[][] b){ // multiply two matrices and return the result // the order of the algorithm is n^3 if( a[0].length != b.length ){ System.err.println("error: inner matix dimentions must agree"); return null; } float[][] result = new float[a.length][b[0].length]; for(int i=0; i < a.length; i++) for(int j=0; j < b[0].length; j++){ float sum = 0.0f; for(int k=0; k < b.length; k++) sum += a[i][k]*b[k][j]; result[i][j] = sum; } return result; } public static float[][] random_matrix(int rows,int cols,float min,float max){ // create a rows by cols matrix of random values in range [min,max] Random rand = new Random(); float[][] result = new float[rows][cols]; for(int i=0; i < rows; i++) for(int j=0; j < cols; j++) result[i][j] = rand.nextFloat() * (max - min) + min; return result; } public static String array2string(float[] n){ String s = "["; for(int i=0; i < n.length - 1; i++) s += n[i]+", "; s += n[ n.length - 1 ]+"]"; return s; } public static float[][] read_training_set(String file_name){ // Read the training set from file_name, and return it in the // form of a matrix. // Each line of file_name is a comment (started with //) or // otherwise specify a training vector (we don't know how many // of elements of such a vector are inputs and outputs) float[][] matrix; // the training set matrix BufferedReader inp; try{ inp = new BufferedReader(new FileReader(file_name)); String s; ArrayList line = new ArrayList(); while( (s = inp.readLine()) != null ){ ArrayList fn = new ArrayList(); // to hold float numbers in a line StringTokenizer st = new StringTokenizer(s,", \t",false); if( ! st.hasMoreTokens() ) continue; String token = st.nextToken(); if( token.equals("//") ) continue; fn.add(new Float(Float.parseFloat(token))); while( st.hasMoreTokens() ){ token = st.nextToken(); fn.add(new Float(Float.parseFloat(token))); } line.add(fn); } int rows = line.size(); matrix = new float[rows][]; for(int i=0; i < rows; i++){ ArrayList fn = (ArrayList)line.get(i); matrix[i] = new float[fn.size()]; for(int j=0; j < fn.size(); j++) matrix[i][j] = ((Float)fn.get(j)).floatValue(); } }catch(Exception ex){ System.err.println("error in "+file_name); return null; } try{ inp.close(); }catch(Exception ex){ System.err.println(ex); } return matrix; } public static void main(String[] args) { System.out.println("START..."); float[][] a = NNUtils.random_matrix(100,100,-1,1); float[][] b = NNUtils.random_matrix(100,100,-1,1); long l1 = System.currentTimeMillis(); float[][] c = NNUtils.multiply(a,b); long l2 = System.currentTimeMillis(); System.out.println((l2-l1)/1000+" sec"); } }