1 什么是BM25
摘录一段wiki
BM25 is a bag-of-words retrieval function that ranks a set of documents based on the query terms appearing in each document, regardless of the inter-relationship between the query terms within a document (e.g., their relative proximity). It is not a single function, but actually a whole family of scoring functions, with slightly different components and parameters. One of the most prominent instantiations of the function is as follows.
文档搜索中,并没有例如pr(google)这样的权威的评分作为排序的依据,所以有各种各样评分标准来评价我们搜索的相关度,而BM25就是其中比较著名的一种。
2 怎么用BM25
到底BM25评分还是个数学方法,我们先来看看它的数学表达式
大概解释一下公式的意思
对于公式1
score(D,Q):就是我们所要计算的评分,即为【给定搜索内容】Q在【给定文档】D中的相关程度,分数越高表示相关度越高。
q:【给定搜索内容】Q中的语素,英文的话就是单词,中文的话需要先进行简单的切词操作。
f(qi,D):在【给定文档】D中,某一个语素qi出现的频率。
|D|:【给定文档】D长度。
avgdl:索引中所有文档长度。
另外两个参数K1和b用来调整精准度,一般情况下我们取K1=2,b=0.75。
公式2是用来计算公式1中IDF(qi)的值
N:索引中文档的总数目。
n(qi):索引中包含语素qi的文档的总书目。
至此,公式所有变量、常量意义明确,我们就可以开始计算了。
--------------------------------------------------------------
由于公式并不难以理解,纯计算部分coder的事就没必要列出来了,这里我想说的是如何把这套评分体系和lucene结合起来。
众所皆知,lucene有score的功能,详见以下链接
http://lucene.apache.org/java/2_4_0/scoring.html
就不细说了。
现在我们做一个简单的demo,加入附件中的jar包
Java代码
public static void main(String[] args) throws ParseException, IOException {
//建立索引
IndexSearcher searcher = new IndexSearcher("/doc");
//计算平均长度avgdl
BM25Parameters.load("avgLengthPath");
BM25BooleanQuery query = new BM25BooleanQuery("This is my Query",
"Search-Field", new MMAnalyzer());
//开始进行检索
Hits hits = searcher.search(query);
//输出结果
for (int i = 0; i < 10; i++) {
System.out.println(hits.id(i) + ":" + hits.score(i));
}
}