Lucene:每个令牌的TF-IDF

bwitn5fc  于 2022-11-07  发布在  Lucene
关注(0)|答案(1)|浏览(174)

我正在学习Lucene 8,这是我第一次使用Lucene。
我想有每个术语的TF-IDF,以获得前10.000令牌在我的Lucene目录.我已经尝试了很多方法,但我卡住了,我不知道如何进行.这是一个例子,我做了什么:

private static void getTokensForField(IndexReader reader, String fieldName) throws IOException {

        List<LeafReaderContext> list = reader.leaves();
        Similarity similarity = new ClassicSimilarity();

        int docnum = reader.numDocs();

        for (LeafReaderContext lrc : list) {
            Terms terms = lrc.reader().terms(fieldName);
            if (terms != null) {
                TermsEnum termsEnum = terms.iterator();

                BytesRef term;
                while ((term = termsEnum.next()) != null) {
                    double tf = termsEnum.totalTermFreq() / terms.size();
                    double idf =Math.log(docnum  / termsEnum.docFreq());
                   // System.out.println(term.utf8ToString() + "\tTF: " + tf + "\tIDF: " + idf);
                }
            }
        }
    }

其实我也在研究这个课题,但是我找到的资源并不是很有用。
我也在网上搜索过,但所有的东西都被否决了。
你有什么建议吗?

kgsdhlau

kgsdhlau1#

据我所知,访问TF和IDF等统计信息的最简单方法是使用Explanation类。
不过,我想澄清一下(如果我告诉你的是你已经知道的事情,请道歉):“术语频率”值用于文档 * 中的术语 * -因此,相同的术语在不同的文档中可能会产生不同的值。
我不太清楚这对于您的“* 获得Lucene目录中的前10.000个令牌 *"的愿望意味着什么。也许这意味着您需要计算每个文档中每个术语的TF,然后为该术语选择“最佳”值,以满足您的需要?
下面是一个构建Explanation的简单示例:

private static void getExplanation(IndexSearcher searcher, Query query, int docID) throws IOException {
    Explanation explanation = searcher.explain(query, docID);
    //explanation.getDescription(); // do what you need with this data
    //explanation.getDetails();     // do what you need with this data
    }

因此,您可以在循环访问查询的命中数时调用此方法:

private static void printHits(Query query) throws IOException {
    IndexReader reader = DirectoryReader.open(FSDirectory.open(Paths.get(INDEX_PATH)));

    IndexSearcher searcher = new IndexSearcher(reader);
    TopDocs results = searcher.search(query, 100); // or whatever you need instead of 100
    ScoreDoc[] hits = results.scoreDocs;
    for (ScoreDoc hit : hits) {
        getExplanation(searcher, query, hit.doc);
    }
}

explanation.getDetails()提供的信息基本上与使用Luke分析查询时看到的信息相同:

作为文本:

0.14566182 weight(body:war in 3) [BM25Similarity], result of:
  0.14566182 score(freq=1.0), computed as boost * idf * tf from:
    0.2876821 idf, computed as log(1 + (N - n + 0.5) / (n + 0.5)) from:
      4 n, number of documents containing term
      5 N, total number of documents with field
    0.50632906 tf, computed as freq / (freq + k1 * (1 - b + b * dl / avgdl)) from:
      1.0 freq, occurrences of term within document
      1.2 k1, term saturation parameter
      0.75 b, length normalization parameter
      3.0 dl, length of field
      4.0 avgdl, average length of field

相关问题