簡體   English   中英

文本搜索的運行時間非常慢[優化]

[英]Incredibly slow runtime on text search [Optimization]

我想做什么

我有一個大小為8.5 GB的大文本文件,其中包含一個單詞格式的300萬行,后跟300個數字,如下所示:

字0.056646 -0.0256464 0.05246(依此類推)

單詞后面的300個數字形成一個代表單詞的向量。 我有三個單詞,我必須找到最接近第四個單詞的向量,使用類比模型(我使用加法,乘法和方向)。

另外,它看起來像這樣:

假設你有單詞vectors a,b和c,那么我會做c - a + b。 然后我將遍歷所有300萬行並使用余弦相似性通過尋找最大結果來找到第四個單詞d。 所以它看起來像這樣:d = max(cos(d',c-a + b))其中d'代表當前行的單詞。

問題是什么

上述示例代表一個查詢。 我必須執行總共20000個查詢。 而且我不只是為加法類比模型執行它,而是為了乘法和方向。 當我運行我的程序時,它仍在嘗試計算第一個查詢的第一個類比模型(添加)的第四個單詞,總共30秒后! 我在程序中急需優化。

首先,我正在對300萬行(3次)進行簡單的迭代,以找到單詞向量a,b和c所需的向量。 使用System.nanoTime()我了解到,對於這些向量中的每一個,查找向量大約需要1.5毫秒。 找到所有3個大約需要5毫秒。

接下來,我在矢量之間進行計算,使用我自己編寫的類(我似乎沒有找到任何處理矢量計算的標准API):

public class VectorCalculation {

    public static List<Double> plus(List<Double> v1, List<Double> v2){
        return operation(new Plus(), v1, v2);
    }

    public static List<Double> minus(List<Double> v1, List<Double> v2){
        return operation(new Minus(), v1, v2);
    }

    public static List<Double> operation(Operator op, List<Double> v1, List<Double> v2){
        if(v1.size() != v2.size())  throw new IllegalArgumentException("The dimension of the given lists are not the same.");
        List<Double> resultVector = new ArrayList<Double>();
        for(int i = 0; i < v1.size(); i++){
            resultVector.add(op.calculate(v1.get(i), v2.get(i)));
        }
        return resultVector;
    }
}

public interface Operator {
    public Double calculate(Double e1, Double e2);
}

public class Plus implements Operator {

    @Override
    public Double calculate(Double e1, Double e2) {
        return e1+e2;
    }
}

public class Minus implements Operator {

    @Override
    public Double calculate(Double e1, Double e2) {
        return e1-e2;
    }
}

矢量的計算在這里:

public class Addition extends AnalogyModel {

    @Override
    double calculateWordVector(List<Double> a, List<Double> b, List<Double> c, List<Double> d) {
        //long startTime1 = System.nanoTime();
        List<Double> result = VectorCalculation.plus(VectorCalculation.minus(c, a), b);
        //long endTime1 = System.nanoTime() - startTime1;
        double result2 = cosineSimilarity(d, result);
        //long endTime2 = System.nanoTime() - startTime1;
        //System.out.println(endTime1 + "       |       " + endTime2);
        return result2;
    }

    Double cosineSimilarity(List<Double> v1, List<Double> v2){
        if(v1.size() != v2.size())  throw new IllegalArgumentException("Vector dimensions are not the same.");

        // find the dividend
        Double dividend = dotProduct(v1, v2);

        // find the divisor
        Double divisor = dotProduct(v1, v1) * dotProduct(v2, v2);
        if(divisor == 0)    divisor = 0.0001;   // safety net against dividing by 0.

        return dividend/divisor;
    }

    /**
     * @return  Returns the dot product of two vectors.
     */
    Double dotProduct(List<Double> v1, List<Double> v2){
        System.out.println(v1);
        Double result = 0.0;
        for(int i = 0; i < v1.size(); i++){
            result += v1.get(i)*v2.get(i);
        }
        return result;
    }
}

計算結果所需的時間從粗略開始(大約0.1毫秒)但很快下降到大約0.025毫秒。 計算result2所需的時間通常非常適中,大約為0.005毫秒。 通過遍歷300萬行並保存向量列表找到d'。 此操作大約需要0.06毫秒。

總結一下:完成一個查詢所需的估計時間,對於一個類比模型,需要5 + 3000000 *(0.025 + 0.005 + 0.06)= 270005毫秒或270秒或4.5分鍾才能完成一個查詢...考慮到我需要為其他類比模型再做兩次這樣做,我需要總共做20000次,這顯然是不夠的。

文本文件中的單詞未排序。 看起來矢量計算太重了,但是必須縮短在文本文件中找到單詞矢量所需的時間。 如果文本文件被分成較小的文本文件會有幫助嗎?

更新 - 代碼讀取文件

    /**
     * @param vocabularyPath    The path of the vector text file.
     * @param word              The word to find the vector for.
     * @return  Returns the vector of the given word as an array list.
     */
    List<Double> getStringVector(String vocabularyPath, String word) throws IOException{
        BufferedReader br = new BufferedReader(new FileReader(vocabularyPath));

        String input = br.readLine();
        boolean found = false;
        while(!found && input != null){
            if(input.contains(word))    found = true;
            else input = br.readLine();
        }

        br.close();
        if(input == null)   return null;
        else return getVector(input);
    }

    /**
     * @param inputLine A line from the vector text file.
     * @return  Returns the vector of the given line as an array list.
     */
    List<Double> getVector(String inputLine){
        String[] splitString = inputLine.split("\\s+");
        List<String> stringList = new ArrayList<>(Arrays.asList(splitString));
        stringList.remove(0); // remove the word at the front
        stringList.remove(stringList.size()-1); // remove the empty string at the end
        List<Double> vectorList = new ArrayList<>();
        for(String s : stringList){
            vectorList.add(Double.parseDouble(s));
        }
        return vectorList;
    }

有兩個明顯的問題: List<Double>Operator

第一個意味着不是使用8個字節用於double float (btw。 float很可能會這樣做),而是需要兩倍以上(包含值和引用的對象)。 更糟糕的是:你失去了空間位置,因為你的號碼可能在記憶中的任何地方。

第二個意味着您為每個點產品執行N個虛擬調用。 這可能不是當前的問題,但是當你在操作員之間切換時,它可能會減慢你的速度。

建議

我猜你的所有矢量都長,所以使用double[] 你節省了大量的內存並獲得了很好的加速。

將您的operation重寫為類似的operation

public static void operationTo(double[] result, Operator op, double[] v1, double[] v2){
    int length = result.length;
    if(v1.length != length || v2.length != length) {
        throw new IllegalArgumentException("The dimension of the given lists are not the same.");
    }
    switch (op) { // use an enum
        case PLUS:
            for(int i = 0; i < length; i++) {
                result[i] = v1[i] + v2[i];
            }
        break;
        ...
    }
}

單詞查找

最快的方法是HashMap<String, double[]> ,假設它全部適合內存。 否則,數據庫(如已建議的那樣)可能是最佳選擇。 帶二分搜索的排序文件也可以。 但請注意,除Map之外的任何其他解決方案都要慢10倍。

單詞查找,以防內存緊張

你只有3個單詞,很適合記憶。 將它們放入ArrayList並對其進行排序。 將向量寫入二進制文件中的單詞。 現在,要找到一個向量,您需要做的就是

long index = Arrays.binarySeach(wordList, word);
randomAccessFile.seek(index * vectorLength * Double.SIZE / Byte.SIZE)

那么你試圖在一個300維空間的300萬個坐標中回答20000個最近鄰搜索

迭代每個查詢的整個數據集必然會相當慢。 通過將數據集插入可以有效回答最近鄰查詢的數據結構(例如Ball Tree) ,您可能獲得最大的加速。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM