scoring.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. # Copyright 2008 Matt Chaput. All rights reserved.
  2. #
  3. # Redistribution and use in source and binary forms, with or without
  4. # modification, are permitted provided that the following conditions are met:
  5. #
  6. # 1. Redistributions of source code must retain the above copyright notice,
  7. # this list of conditions and the following disclaimer.
  8. #
  9. # 2. Redistributions in binary form must reproduce the above copyright
  10. # notice, this list of conditions and the following disclaimer in the
  11. # documentation and/or other materials provided with the distribution.
  12. #
  13. # THIS SOFTWARE IS PROVIDED BY MATT CHAPUT ``AS IS'' AND ANY EXPRESS OR
  14. # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  15. # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  16. # EVENT SHALL MATT CHAPUT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  17. # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  18. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  19. # OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  20. # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  21. # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  22. # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  23. #
  24. # The views and conclusions contained in the software and documentation are
  25. # those of the authors and should not be interpreted as representing official
  26. # policies, either expressed or implied, of Matt Chaput.
  27. """
  28. This module contains classes for scoring (and sorting) search results.
  29. """
  30. from __future__ import division
  31. from math import log, pi
  32. from whoosh.compat import iteritems
  33. # Base classes
  34. class WeightingModel(object):
  35. """Abstract base class for scoring models. A WeightingModel object provides
  36. a method, ``scorer``, which returns an instance of
  37. :class:`whoosh.scoring.Scorer`.
  38. Basically, WeightingModel objects store the configuration information for
  39. the model (for example, the values of B and K1 in the BM25F model), and
  40. then creates a scorer instance based on additional run-time information
  41. (the searcher, the fieldname, and term text) to do the actual scoring.
  42. """
  43. use_final = False
  44. def idf(self, searcher, fieldname, text):
  45. """Returns the inverse document frequency of the given term.
  46. """
  47. parent = searcher.get_parent()
  48. n = parent.doc_frequency(fieldname, text)
  49. dc = parent.doc_count_all()
  50. return log(dc / (n + 1)) + 1
  51. def scorer(self, searcher, fieldname, text, qf=1):
  52. """Returns an instance of :class:`whoosh.scoring.Scorer` configured
  53. for the given searcher, fieldname, and term text.
  54. """
  55. raise NotImplementedError(self.__class__.__name__)
  56. def final(self, searcher, docnum, score):
  57. """Returns a final score for each document. You can use this method
  58. in subclasses to apply document-level adjustments to the score, for
  59. example using the value of stored field to influence the score
  60. (although that would be slow).
  61. WeightingModel sub-classes that use ``final()`` should have the
  62. attribute ``use_final`` set to ``True``.
  63. :param searcher: :class:`whoosh.searching.Searcher` for the index.
  64. :param docnum: the doc number of the document being scored.
  65. :param score: the document's accumulated term score.
  66. :rtype: float
  67. """
  68. return score
  69. class BaseScorer(object):
  70. """Base class for "scorer" implementations. A scorer provides a method for
  71. scoring a document, and sometimes methods for rating the "quality" of a
  72. document and a matcher's current "block", to implement quality-based
  73. optimizations.
  74. Scorer objects are created by WeightingModel objects. Basically,
  75. WeightingModel objects store the configuration information for the model
  76. (for example, the values of B and K1 in the BM25F model), and then creates
  77. a scorer instance.
  78. """
  79. def supports_block_quality(self):
  80. """Returns True if this class supports quality optimizations.
  81. """
  82. return False
  83. def score(self, matcher):
  84. """Returns a score for the current document of the matcher.
  85. """
  86. raise NotImplementedError(self.__class__.__name__)
  87. def max_quality(self):
  88. """Returns the *maximum limit* on the possible score the matcher can
  89. give. This can be an estimate and not necessarily the actual maximum
  90. score possible, but it must never be less than the actual maximum
  91. score.
  92. """
  93. raise NotImplementedError(self.__class__.__name__)
  94. def block_quality(self, matcher):
  95. """Returns the *maximum limit* on the possible score the matcher can
  96. give **in its current "block"** (whatever concept of "block" the
  97. backend might use). This can be an estimate and not necessarily the
  98. actual maximum score possible, but it must never be less than the
  99. actual maximum score.
  100. If this score is less than the minimum score
  101. required to make the "top N" results, then we can tell the matcher to
  102. skip ahead to another block with better "quality".
  103. """
  104. raise NotImplementedError(self.__class__.__name__)
  105. # Scorer that just returns term weight
  106. class WeightScorer(BaseScorer):
  107. """A scorer that simply returns the weight as the score. This is useful
  108. for more complex weighting models to return when they are asked for a
  109. scorer for fields that aren't scorable (don't store field lengths).
  110. """
  111. def __init__(self, maxweight):
  112. self._maxweight = maxweight
  113. def supports_block_quality(self):
  114. return True
  115. def score(self, matcher):
  116. return matcher.weight()
  117. def max_quality(self):
  118. return self._maxweight
  119. def block_quality(self, matcher):
  120. return matcher.block_max_weight()
  121. @classmethod
  122. def for_(cls, searcher, fieldname, text):
  123. ti = searcher.term_info(fieldname, text)
  124. return cls(ti.max_weight())
  125. # Base scorer for models that only use weight and field length
  126. class WeightLengthScorer(BaseScorer):
  127. """Base class for scorers where the only per-document variables are term
  128. weight and field length.
  129. Subclasses should override the ``_score(weight, length)`` method to return
  130. the score for a document with the given weight and length, and call the
  131. ``setup()`` method at the end of the initializer to set up common
  132. attributes.
  133. """
  134. def setup(self, searcher, fieldname, text):
  135. """Initializes the scorer and then does the busy work of
  136. adding the ``dfl()`` function and maximum quality attribute.
  137. This method assumes the initializers of WeightLengthScorer subclasses
  138. always take ``searcher, offset, fieldname, text`` as the first three
  139. arguments. Any additional arguments given to this method are passed
  140. through to the initializer.
  141. Note: this method calls ``self._score()``, so you should only call it
  142. in the initializer after setting up whatever attributes ``_score()``
  143. depends on::
  144. class MyScorer(WeightLengthScorer):
  145. def __init__(self, searcher, fieldname, text, parm=1.0):
  146. self.parm = parm
  147. self.setup(searcher, fieldname, text)
  148. def _score(self, weight, length):
  149. return (weight / (length + 1)) * self.parm
  150. """
  151. ti = searcher.term_info(fieldname, text)
  152. if not searcher.schema[fieldname].scorable:
  153. return WeightScorer(ti.max_weight())
  154. self.dfl = lambda docid: searcher.doc_field_length(docid, fieldname, 1)
  155. self._maxquality = self._score(ti.max_weight(), ti.min_length())
  156. def supports_block_quality(self):
  157. return True
  158. def score(self, matcher):
  159. return self._score(matcher.weight(), self.dfl(matcher.id()))
  160. def max_quality(self):
  161. return self._maxquality
  162. def block_quality(self, matcher):
  163. return self._score(matcher.block_max_weight(),
  164. matcher.block_min_length())
  165. def _score(self, weight, length):
  166. # Override this method with the actual scoring function
  167. raise NotImplementedError(self.__class__.__name__)
  168. # WeightingModel implementations
  169. # Debugging model
  170. class DebugModel(WeightingModel):
  171. def __init__(self):
  172. self.log = []
  173. def scorer(self, searcher, fieldname, text, qf=1):
  174. return DebugScorer(searcher, fieldname, text, self.log)
  175. class DebugScorer(BaseScorer):
  176. def __init__(self, searcher, fieldname, text, log):
  177. ti = searcher.term_info(fieldname, text)
  178. self._maxweight = ti.max_weight()
  179. self.searcher = searcher
  180. self.fieldname = fieldname
  181. self.text = text
  182. self.log = log
  183. def supports_block_quality(self):
  184. return True
  185. def score(self, matcher):
  186. fieldname, text = self.fieldname, self.text
  187. docid = matcher.id()
  188. w = matcher.weight()
  189. length = self.searcher.doc_field_length(docid, fieldname)
  190. self.log.append((fieldname, text, docid, w, length))
  191. return w
  192. def max_quality(self):
  193. return self._maxweight
  194. def block_quality(self, matcher):
  195. return matcher.block_max_weight()
  196. # BM25F Model
  197. def bm25(idf, tf, fl, avgfl, B, K1):
  198. # idf - inverse document frequency
  199. # tf - term frequency in the current document
  200. # fl - field length in the current document
  201. # avgfl - average field length across documents in collection
  202. # B, K1 - free paramters
  203. return idf * ((tf * (K1 + 1)) / (tf + K1 * ((1 - B) + B * fl / avgfl)))
  204. class BM25F(WeightingModel):
  205. """Implements the BM25F scoring algorithm.
  206. """
  207. def __init__(self, B=0.75, K1=1.2, **kwargs):
  208. """
  209. >>> from whoosh import scoring
  210. >>> # Set a custom B value for the "content" field
  211. >>> w = scoring.BM25F(B=0.75, content_B=1.0, K1=1.5)
  212. :param B: free parameter, see the BM25 literature. Keyword arguments of
  213. the form ``fieldname_B`` (for example, ``body_B``) set field-
  214. specific values for B.
  215. :param K1: free parameter, see the BM25 literature.
  216. """
  217. self.B = B
  218. self.K1 = K1
  219. self._field_B = {}
  220. for k, v in iteritems(kwargs):
  221. if k.endswith("_B"):
  222. fieldname = k[:-2]
  223. self._field_B[fieldname] = v
  224. def supports_block_quality(self):
  225. return True
  226. def scorer(self, searcher, fieldname, text, qf=1):
  227. if not searcher.schema[fieldname].scorable:
  228. return WeightScorer.for_(searcher, fieldname, text)
  229. if fieldname in self._field_B:
  230. B = self._field_B[fieldname]
  231. else:
  232. B = self.B
  233. return BM25FScorer(searcher, fieldname, text, B, self.K1, qf=qf)
  234. class BM25FScorer(WeightLengthScorer):
  235. def __init__(self, searcher, fieldname, text, B, K1, qf=1):
  236. # IDF and average field length are global statistics, so get them from
  237. # the top-level searcher
  238. parent = searcher.get_parent() # Returns self if no parent
  239. self.idf = parent.idf(fieldname, text)
  240. self.avgfl = parent.avg_field_length(fieldname) or 1
  241. self.B = B
  242. self.K1 = K1
  243. self.qf = qf
  244. self.setup(searcher, fieldname, text)
  245. def _score(self, weight, length):
  246. s = bm25(self.idf, weight, length, self.avgfl, self.B, self.K1)
  247. return s
  248. # DFree model
  249. def dfree(tf, cf, qf, dl, fl):
  250. # tf - term frequency in current document
  251. # cf - term frequency in collection
  252. # qf - term frequency in query
  253. # dl - field length in current document
  254. # fl - total field length across all documents in collection
  255. prior = tf / dl
  256. post = (tf + 1.0) / (dl + 1.0)
  257. invpriorcol = fl / cf
  258. norm = tf * log(post / prior)
  259. return qf * norm * (tf * (log(prior * invpriorcol))
  260. + (tf + 1.0) * (log(post * invpriorcol))
  261. + 0.5 * log(post / prior))
  262. class DFree(WeightingModel):
  263. """Implements the DFree scoring model from Terrier.
  264. See http://terrier.org/
  265. """
  266. def supports_block_quality(self):
  267. return True
  268. def scorer(self, searcher, fieldname, text, qf=1):
  269. if not searcher.schema[fieldname].scorable:
  270. return WeightScorer.for_(searcher, fieldname, text)
  271. return DFreeScorer(searcher, fieldname, text, qf=qf)
  272. class DFreeScorer(WeightLengthScorer):
  273. def __init__(self, searcher, fieldname, text, qf=1):
  274. # Total term weight and total field length are global statistics, so
  275. # get them from the top-level searcher
  276. parent = searcher.get_parent() # Returns self if no parent
  277. self.cf = parent.weight(fieldname, text)
  278. self.fl = parent.field_length(fieldname)
  279. self.qf = qf
  280. self.setup(searcher, fieldname, text)
  281. def _score(self, weight, length):
  282. return dfree(weight, self.cf, self.qf, length, self.fl)
  283. # PL2 model
  284. rec_log2_of_e = 1.0 / log(2)
  285. def pl2(tf, cf, qf, dc, fl, avgfl, c):
  286. # tf - term frequency in the current document
  287. # cf - term frequency in the collection
  288. # qf - term frequency in the query
  289. # dc - doc count
  290. # fl - field length in the current document
  291. # avgfl - average field length across all documents
  292. # c -free parameter
  293. TF = tf * log(1.0 + (c * avgfl) / fl)
  294. norm = 1.0 / (TF + 1.0)
  295. f = cf / dc
  296. return norm * qf * (TF * log(1.0 / f)
  297. + f * rec_log2_of_e
  298. + 0.5 * log(2 * pi * TF)
  299. + TF * (log(TF) - rec_log2_of_e))
  300. class PL2(WeightingModel):
  301. """Implements the PL2 scoring model from Terrier.
  302. See http://terrier.org/
  303. """
  304. def __init__(self, c=1.0):
  305. self.c = c
  306. def scorer(self, searcher, fieldname, text, qf=1):
  307. if not searcher.schema[fieldname].scorable:
  308. return WeightScorer.for_(searcher, fieldname, text)
  309. return PL2Scorer(searcher, fieldname, text, self.c, qf=qf)
  310. class PL2Scorer(WeightLengthScorer):
  311. def __init__(self, searcher, fieldname, text, c, qf=1):
  312. # Total term weight, document count, and average field length are
  313. # global statistics, so get them from the top-level searcher
  314. parent = searcher.get_parent() # Returns self if no parent
  315. self.cf = parent.frequency(fieldname, text)
  316. self.dc = parent.doc_count_all()
  317. self.avgfl = parent.avg_field_length(fieldname) or 1
  318. self.c = c
  319. self.qf = qf
  320. self.setup(searcher, fieldname, text)
  321. def _score(self, weight, length):
  322. return pl2(weight, self.cf, self.qf, self.dc, length, self.avgfl,
  323. self.c)
  324. # Simple models
  325. class Frequency(WeightingModel):
  326. def scorer(self, searcher, fieldname, text, qf=1):
  327. maxweight = searcher.term_info(fieldname, text).max_weight()
  328. return WeightScorer(maxweight)
  329. class TF_IDF(WeightingModel):
  330. def scorer(self, searcher, fieldname, text, qf=1):
  331. # IDF is a global statistic, so get it from the top-level searcher
  332. parent = searcher.get_parent() # Returns self if no parent
  333. idf = parent.idf(fieldname, text)
  334. maxweight = searcher.term_info(fieldname, text).max_weight()
  335. return TF_IDFScorer(maxweight, idf)
  336. class TF_IDFScorer(BaseScorer):
  337. def __init__(self, maxweight, idf):
  338. self._maxquality = maxweight * idf
  339. self.idf = idf
  340. def supports_block_quality(self):
  341. return True
  342. def score(self, matcher):
  343. return matcher.weight() * self.idf
  344. def max_quality(self):
  345. return self._maxquality
  346. def block_quality(self, matcher):
  347. return matcher.block_max_weight() * self.idf
  348. # Utility models
  349. class Weighting(WeightingModel):
  350. """This class provides backwards-compatibility with the old weighting
  351. class architecture, so any existing custom scorers don't need to be
  352. rewritten.
  353. """
  354. def scorer(self, searcher, fieldname, text, qf=1):
  355. return self.CompatibilityScorer(searcher, fieldname, text, self.score)
  356. def score(self, searcher, fieldname, text, docnum, weight):
  357. raise NotImplementedError
  358. class CompatibilityScorer(BaseScorer):
  359. def __init__(self, searcher, fieldname, text, scoremethod):
  360. self.searcher = searcher
  361. self.fieldname = fieldname
  362. self.text = text
  363. self.scoremethod = scoremethod
  364. def score(self, matcher):
  365. return self.scoremethod(self.searcher, self.fieldname, self.text,
  366. matcher.id(), matcher.weight())
  367. class FunctionWeighting(WeightingModel):
  368. """Uses a supplied function to do the scoring. For simple scoring functions
  369. and experiments this may be simpler to use than writing a full weighting
  370. model class and scorer class.
  371. The function should accept the arguments
  372. ``searcher, fieldname, text, matcher``.
  373. For example, the following function will score documents based on the
  374. earliest position of the query term in the document::
  375. def pos_score_fn(searcher, fieldname, text, matcher):
  376. poses = matcher.value_as("positions")
  377. return 1.0 / (poses[0] + 1)
  378. pos_weighting = scoring.FunctionWeighting(pos_score_fn)
  379. with myindex.searcher(weighting=pos_weighting) as s:
  380. results = s.search(q)
  381. Note that the searcher passed to the function may be a per-segment searcher
  382. for performance reasons. If you want to get global statistics inside the
  383. function, you should use ``searcher.get_parent()`` to get the top-level
  384. searcher. (However, if you are using global statistics, you should probably
  385. write a real model/scorer combo so you can cache them on the object.)
  386. """
  387. def __init__(self, fn):
  388. self.fn = fn
  389. def scorer(self, searcher, fieldname, text, qf=1):
  390. return self.FunctionScorer(self.fn, searcher, fieldname, text, qf=qf)
  391. class FunctionScorer(BaseScorer):
  392. def __init__(self, fn, searcher, fieldname, text, qf=1):
  393. self.fn = fn
  394. self.searcher = searcher
  395. self.fieldname = fieldname
  396. self.text = text
  397. self.qf = qf
  398. def score(self, matcher):
  399. return self.fn(self.searcher, self.fieldname, self.text, matcher)
  400. class MultiWeighting(WeightingModel):
  401. """Chooses from multiple scoring algorithms based on the field.
  402. """
  403. def __init__(self, default, **weightings):
  404. """The only non-keyword argument specifies the default
  405. :class:`Weighting` instance to use. Keyword arguments specify
  406. Weighting instances for specific fields.
  407. For example, to use ``BM25`` for most fields, but ``Frequency`` for
  408. the ``id`` field and ``TF_IDF`` for the ``keys`` field::
  409. mw = MultiWeighting(BM25(), id=Frequency(), keys=TF_IDF())
  410. :param default: the Weighting instance to use for fields not
  411. specified in the keyword arguments.
  412. """
  413. self.default = default
  414. # Store weighting functions by field name
  415. self.weightings = weightings
  416. def scorer(self, searcher, fieldname, text, qf=1):
  417. w = self.weightings.get(fieldname, self.default)
  418. return w.scorer(searcher, fieldname, text, qf=qf)
  419. class ReverseWeighting(WeightingModel):
  420. """Wraps a weighting object and subtracts the wrapped model's scores from
  421. 0, essentially reversing the weighting model.
  422. """
  423. def __init__(self, weighting):
  424. self.weighting = weighting
  425. def scorer(self, searcher, fieldname, text, qf=1):
  426. subscorer = self.weighting.scorer(searcher, fieldname, text, qf=qf)
  427. return ReverseWeighting.ReverseScorer(subscorer)
  428. class ReverseScorer(BaseScorer):
  429. def __init__(self, subscorer):
  430. self.subscorer = subscorer
  431. def supports_block_quality(self):
  432. return self.subscorer.supports_block_quality()
  433. def score(self, matcher):
  434. return 0 - self.subscorer.score(matcher)
  435. def max_quality(self):
  436. return 0 - self.subscorer.max_quality()
  437. def block_quality(self, matcher):
  438. return 0 - self.subscorer.block_quality(matcher)
  439. #class PositionWeighting(WeightingModel):
  440. # def __init__(self, reversed=False):
  441. # self.reversed = reversed
  442. #
  443. # def scorer(self, searcher, fieldname, text, qf=1):
  444. # return PositionWeighting.PositionScorer()
  445. #
  446. # class PositionScorer(BaseScorer):
  447. # def score(self, matcher):
  448. # p = min(span.pos for span in matcher.spans())
  449. # if self.reversed:
  450. # return p
  451. # else:
  452. # return 0 - p