文本搜索的运行时间非常慢[优化]

时间:2015-04-26 16:06:24

标签: java search optimization text

我想做什么

我有一个大小为8.5 GB的大文本文件,其中包含一个单词格式的300万行,后跟300个数字,如下所示:

字0.056646 -0.0256464 0.05246(依此类推)

单词后面的300个数字形成一个代表单词的向量。我有三个单词,我必须找到最接近第四个单词的向量,使用类比模型(我使用加法,乘法和方向)。

另外,它看起来像这样:

假设你有单词vector 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;
    }

2 个答案:

答案 0 :(得分:2)

有两个明显的问题:List<Double>Operator

第一个意味着代替使用double的8个字节(顺便提一句。float很可能会这样做),你需要两倍以上(包含值和引用的对象) 。更糟糕的是:你失去了空间位置,因为你的号码可能在记忆中的任何地方。

第二个意味着您为每个点产品执行N次虚拟呼叫。这可能不是当前的问题,但是当你在操作员之间切换时,它可能会减慢你的速度。

建议

我猜你的所有向量都相同,所以请使用double[]。你节省了大量内存并获得了很好的加速。

将您的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倍。

在内存紧张的情况下进行单词查找

你只有3M单词,很适合记忆。将它们放入ArrayList并对其进行排序。将向量写入二进制文件中的单词。现在,要找到一个向量,您需要做的就是

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

答案 1 :(得分:0)

所以你试图在一个300维空间的300万个坐标中回答20000 nearest neighbor searches

对每个查询迭代整个数据集必然会相当慢。通过将数据集插入可以有效回答最近邻居查询的数据结构(例如Ball Tree),您可能获得最大的加速。