2016-12-05 3 views
6

Я нашел, что gensim имеет функцию ранжирования BM25. Однако я не могу найти учебник, как его использовать.Как использовать рейтинг gensim BM25 в python

В моем случае у меня был один запрос. несколько документов, которые были получены из поисковой системы. Как использовать рейтинг gensim BM 25 для сравнения запроса и документов, чтобы найти наиболее похожий?

Я новичок в gensim. Благодарю.

запроса:

"experimental studies of creep buckling ." 

документ 1:

" the 7 x 7 in . hypersonic wind tunnel at rae farnborough, part 1, design, instrumentation and flow visualization techniques . this is the first of three parts of the calibration report on the r.a.e. some details of the design and lay-out of the plant are given, together with the calculated performance figures, and the major components of the facility are briefly described . the instrumentation provided for the wind-tunnel is described in some detail, including the optical and other methods of flow visualization used in the tunnel . later parts will describe the calibration of the flow in the working-section, including temperature measurements . a discussion of the heater performance will also be included as well as the results of tests to determine starting and running pressure ratios, blockage effects, model starting loads, and humidity of the air flow ." 

документ 2:

" the 7 in. x 7 in. hypersonic wind tunnel at r.a.e. farnborough part ii. heater performance . tests on the storage heater, which is cylindrical in form and mounted horizontally, show that its performance is adequate for operation at m=6.8 and probably adequate for flows at m=8.2 with the existing nozzles . in its present state, the maximum design temperature of 680 degrees centigrade for operation at m=9 cannot be realised in the tunnel because of heat loss to the outlet attachments of the heater and quick-acting valve which form, in effect, a large heat sink . because of this heat loss there is rather poor response of stagnation temperature in the working section at the start of a run . it is hoped to cure this by preheating the heater outlet cone and the quick-acting valve . at pressures greater than about 100 p.s.i.g. free convection through the fibrous thermal insulation surrounding the heated core causes the top of the heater shell to become somewhat hotter than the bottom, which results in /hogging/ distortion of the shell . this free convection cools the heater core and a vertical temperature gradient is set up across it after only a few minutes at high pressure . modifications to be incorporated in the heater to improve its performance are described ." 

документ 3:

" supersonic flow at the surface of a circular cone at angle of attack . formulas for the inviscid flow properties on the surface of a cone at angle of attack are derived for use in conjunction with the m.i.t. cone tables . these formulas are based upon an entropy distribution on the cone surface which is uniform and equal to that of the shocked fluid in the windward meridian plane . they predict values for the flow variables which may differ significantly from the corresponding values obtained directly from the cone tables . the differences in the magnitudes of the flow variables computed by the two methods tend to increase with increasing free-stream mach number, cone angle and angle of attack ." 

документ 4:

" theory of aircraft structural models subjected to aerodynamic heating and external loads . the problem of investigating the simultaneous effects of transient aerodynamic heating and external loads on aircraft structures for the purpose of determining the ability of the structure to withstand flight to supersonic speeds is studied . by dimensional analyses it is shown that .. constructed of the same materials as the aircraft will be thermally similar to the aircraft with respect to the flow of heat through the structure will be similar to those of the aircraft when the structural model is constructed at the same temperature as the aircraft . external loads will be similar to those of the aircraft . subjected to heating and cooling that correctly simulate the aerodynamic heating of the aircraft, except with respect to angular velocities and angular accelerations, without requiring determination of the heat flux at each point on the surface and its variation with time . acting on the aerodynamically heated structural model to those acting on the aircraft is determined for the case of zero angular velocity and zero angular acceleration, so that the structural model may be subjected to the external loads required for simultaneous simulation of stresses and deformations due to external loads ." 

ответ

10

Полное раскрытие у меня нет никакого опыта с использованием ранжирования BM25, однако у меня совсем немного опыта с TF-IDF и LSI распределенных моделей gensim, наряду с индексом подобия gensim в.

У автора действительно хорошая работа по сохранению читаемой кодовой базы, поэтому, если у вас когда-либо возникнут проблемы с чем-либо подобным, я рекомендую просто прыгать в исходный код.

Глядя на исходном коде: https://github.com/RaRe-Technologies/gensim/blob/develop/gensim/summarization/bm25.py

Я инициировал BM25() объекта с документами, которые Вы вставили выше.

Похоже, наш старый добрый друг Радим не включает в себя функцию для вычисления average_idf для нас, что не Biggie, мы можем только plagarize линии 65 для нашего дела:

average_idf = sum(map(lambda k: float(bm25.idf[k]), bm25.idf.keys()))/len(bm25.idf.keys())

Тогда, хорошо, если я понимаю первоначальное намерение get_scores правильно, вы должны получить каждый балл BM25 по отношению к исходному запросу, просто делая

scores = bm_25_object.get_scores(query_doc, average_idf)

Который возвращает все баллы за каждый документ, а затем, если я понимаю рейтинг BM25, основываясь на том, что я читал на этой странице в Википедии: https://en.wikipedia.org/wiki/Okapi_BM25

Вы должны иметь возможность просто выбрать документ с наивысшим балл следующим образом:

best_result = docs[scores.index(max(scores))]

Таким образом, первый документ должен быть наиболее релевантной вашему запросу? Надеюсь, это то, чего вы ожидали в любом случае, и я надеюсь, что это помогло в определенной степени. Удачи!

+3

И вход для BM25() - это corpus = [dictionary.doc2bow (текст) для текста в текстах] ', вход' doc 'для' get_scores (doc, avg_idf) 'представляет собой массив словаря. Doc2bow (слово) – Lewen

Смежные вопросы