用lucene提取tf-idf向量

时间:2012-02-08 07:14:56

标签: java lucene classification

我使用lucene索引了一组文档。我还为每个文档内容存储了DocumentTermVector。我写了一个程序并为每个文档得到了术语频率向量,但是如何获得每个文档的tf-idf向量?

以下是我在每个文档中输出术语频率的代码:

Directory dir = FSDirectory.open(new File(indexDir));
    IndexReader ir = IndexReader.open(dir);
    for (int docNum=0; docNum<ir.numDocs(); docNum++) {
        System.out.println(ir.document(docNum).getField("filename").stringValue());
        TermFreqVector tfv = ir.getTermFreqVector(docNum, "contents");
        if (tfv == null) {
        // ignore empty fields
        continue;
        }
        String terms[] = tfv.getTerms();
        int termCount = terms.length;
        int freqs[] = tfv.getTermFrequencies();

        for (int t=0; t < termCount; t++) {
        System.out.println(terms[t] + " " + freqs[t]);
        }
    }

lucene中是否有任何buit-in功能让我这样做?


没有人帮忙,我自己做了:

    Directory dir = FSDirectory.open(new File(indexDir));
    IndexReader ir = IndexReader.open(dir);

    int docNum;
    for (docNum = 0; docNum<ir.numDocs(); docNum++) {
        TermFreqVector tfv = ir.getTermFreqVector(docNum, "title");
        if (tfv == null) {
                // ignore empty fields
                continue;
        }
        String tterms[] = tfv.getTerms();
        int termCount = tterms.length;
        int freqs[] = tfv.getTermFrequencies();

        for (int t=0; t < termCount; t++) {
            double idf = ir.numDocs()/ir.docFreq(new Term("title", tterms[t]));
            System.out.println(tterms[t] + " " + freqs[t]*Math.log(idf));
        }
    }

有没有办法找到每个词的ID号?


没有人帮忙,我又一次自己做了:

    List list = new LinkedList();
    terms = null;
    try
    {
        terms = ir.terms(new Term("title", ""));
        while ("title".equals(terms.term().field()))
        {
        list.add(terms.term().text());
        if (!terms.next())
            break;
        }
    }
    finally
    {
        terms.close();
    }
    int docNum;
    for (docNum = 0; docNum<ir.numDocs(); docNum++) {
        TermFreqVector tfv = ir.getTermFreqVector(docNum, "title");
        if (tfv == null) {
                // ignore empty fields
                continue;
        }
        String tterms[] = tfv.getTerms();
        int termCount = tterms.length;
        int freqs[] = tfv.getTermFrequencies();

        for (int t=0; t < termCount; t++) {
            double idf = ir.numDocs()/ir.docFreq(new Term("title", tterms[t]));
            System.out.println(Collections.binarySearch(list, tterms[t]) + " " + tterms[t] + " " + freqs[t]*Math.log(idf));
        }
    }

1 个答案:

答案 0 :(得分:2)

你可能找不到tf-idf向量。但是,正如您已经完成的那样,您可以手动计算IDF。最好使用DefaultSimilarity(或您使用的任何相似性实现)为您计算它。

关于Term ID,我认为目前你不能。 At least not until Lucene 4.0,请参阅this