File size: 2,006 Bytes
f9bfb80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include "bm25.h"
#include "tokenize.h"
#include <algorithm>
#include <cmath>

int32_t BM25::add(const std::string& text) {
    const int32_t id = n_docs_++;
    auto toks = tokenize(text);
    doc_len_.push_back(static_cast<int32_t>(toks.size()));
    total_len_ += toks.size();

    /* ๋ฌธ์„œ ๋‚ด ๋นˆ๋„๋ฅผ ๋จผ์ € ๋ชจ์•„์„œ ํฌ์ŠคํŒ…์— ํ•œ ๋ฒˆ๋งŒ ๋„ฃ๋Š”๋‹ค */
    std::unordered_map<std::string,int32_t> tf;
    tf.reserve(toks.size());
    for (auto& t : toks) tf[t]++;
    for (auto& [term, f] : tf) postings_[term].emplace_back(id, f);
    finalized_ = false;
    return id;
}

void BM25::finalize() {
    avgdl_ = n_docs_ ? static_cast<float>(total_len_ / n_docs_) : 0.0f;
    idf_.clear();
    idf_.reserve(postings_.size());
    for (auto& [term, plist] : postings_) {
        const double nq = static_cast<double>(plist.size());
        /* Robertson-Sparck Jones IDF, ์Œ์ˆ˜ ๋ฐฉ์ง€๋ฅผ ์œ„ํ•ด +1 */
        idf_[term] = static_cast<float>(
            std::log((n_docs_ - nq + 0.5) / (nq + 0.5) + 1.0));
    }
    finalized_ = true;
}

std::vector<ScoredDoc> BM25::search(const std::string& query, int k) const {
    std::vector<ScoredDoc> out;
    if (!finalized_ || n_docs_ == 0) return out;

    std::vector<float> acc(n_docs_, 0.0f);
    for (auto& term : tokenize(query)) {
        auto it = postings_.find(term);
        if (it == postings_.end()) continue;
        const float idf = idf_.at(term);
        for (auto& [doc, f] : it->second) {
            const float denom = f + k1_ * (1.0f - b_ + b_ * doc_len_[doc] / avgdl_);
            acc[doc] += idf * (f * (k1_ + 1.0f)) / denom;
        }
    }
    out.reserve(n_docs_);
    for (int32_t i = 0; i < n_docs_; i++)
        if (acc[i] > 0.0f) out.push_back({i, acc[i]});

    const int kk = std::min<int>(k, static_cast<int>(out.size()));
    std::partial_sort(out.begin(), out.begin() + kk, out.end(),
                      [](const ScoredDoc& a, const ScoredDoc& b){ return a.score > b.score; });
    out.resize(kk);
    return out;
}