我有一段代碼,它通過迭代遍歷行和列來對矩陣執行計算。執行的微積分是一個餘弦距離度量,我在Internet上找到的代碼(現在無法檢索鏈接)。如何加快這段代碼?微積分迭代遍歷矩陣的行和列
可以有10,000行和列。矩陣是對稱的,所以我只需要迭代它的一半。值是浮動的。
問題:它很慢(看起來需要3到6個小時)。任何人都可以指出我的改進?謝謝!
關於代碼的注意事項:它使用抽象類來實現靈活性:這樣,在單獨的類中定義的餘弦計算可以很容易地被另一個類替換。
代碼:
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);
// }
//
// }
}
做定義的計算類:
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;
}
}
這是一個家庭作業項目嗎?你不能使用MatLab等數學軟件嗎? – 2012-03-02 15:20:59
這是一個在學術界的專業項目,我需要爲它使用Java - bc我自己的侷限性恐怕! – seinecle 2012-03-02 15:24:50
你有沒有分析過你的算法哪一部分需要最長的時間?只需在操作的開始/結束處添加新的Date().getTime();'並將它們相減,就可以給您一個很好的見解。 – Marcelo 2012-03-02 15:25:16