I have a piece of code which performs calculations on a matrix by iterating through its rows and columns. The piece of calculus performed is a cosine distance measure, with a code I found on Internet (could not retrieve the link right now).
There can be 10,000 rows and col. The matrix is symmetric so I just need to iterate half of it. Values are float.
The problem: it is very slow (will take 3 to 6 hours it seems). Can anyone point me to improvements? Thx!
Note on the code: it uses an abstract class for flexibility: this way, the cosine calculation defined in a separate class could be easily replaced by another one.
The code:
import Jama.Matrix;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.concurrent.ExecutionException;
public abstract class AbstractSimilarity {
HashSet<Triple<Double, Integer, Integer>> set = new HashSet();
public ArrayList<Thread> listThreads = new ArrayList();
public void transform(Matrix matrixToBeTransformed) throws InterruptedException,
ExecutionException {
int numDocs = termDocumentMatrix.getColumnDimension();
Main.similarityMatrix = new Matrix(numDocs, numDocs);
System.out.println("size of the matrix: " + numDocs + "x " + numDocs);
//1. iteration through all rows of the matrixToBeTransformed
for (int i = numDocs - 1; i >0 ; i--) {
System.out.println("matrix treatment... " + ((float) i / (float) numDocs * 100) + "%");
//2. isolates the row i of this matrixToBeTransformed
Matrix sourceDocMatrix = matrixToBeTransformed.getMatrix(
0, matrixToBeTransformed.getRowDimension() - 1, i, i);
// 3. Iterates through all columns of the matrixToBeTransformed
// for (int j = 0; j < numDocs; j++) {
// if (j < i) {
//
// //4. isolates the column j of this matrixToBeTransformed
// Matrix targetDocMatrix = matrixToBeTransformed.getMatrix(
// 0, matrixToBeTransformed.getRowDimension() - 1, j, j);
//5. computes the similarity between this given row and this given column and writes it in a resultMatrix
// Main.resultMatrix.set(i, j, computeSimilarity(sourceDocMatrix, targetDocMatrix));
// } else {
// Main.resultMatrix.set(i, j, 0);
// }
//
// }
}
The class which defines the computation to be done:
import Jama.Matrix;
public class CosineSimilarity extends AbstractSimilarity{
@Override
protected double computeSimilarity(Matrix sourceDoc, Matrix targetDoc) {
double dotProduct = sourceDoc.arrayTimes(targetDoc).norm1();
double eucledianDist = sourceDoc.normF() * targetDoc.normF();
return dotProduct / eucledianDist;
}
}