Rename Collapser::entries() to get_entries()
[xapian.git] / xapian-letor / scorer / ndcg_score.cc
blobdb88bb3715c88fdf11c48913e05af2ce2eb3b9bc
1 /** @file ndcg_score.cc
2 * @brief Implementation of NDCGScore
3 */
4 /* Copyright (C) 2014 Hanxiao Sun
5 * Copyright (C) 2016 Ayush Tomar
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License as
9 * published by the Free Software Foundation; either version 2 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
20 * USA
23 #include <config.h>
25 #include "xapian-letor/scorer.h"
27 #include "debuglog.h"
28 #include "common/log2.h"
30 #include <algorithm>
31 #include <cmath>
33 using namespace std;
34 using namespace Xapian;
36 NDCGScore::NDCGScore()
38 LOGCALL_CTOR(API, "NDCGScore", NO_ARGS);
41 NDCGScore::~NDCGScore()
43 LOGCALL_DTOR(API, "NDCGScore");
46 static double
47 get_dcg(const std::vector<double> &labels)
49 LOGCALL_STATIC(API, double, "get_dcg", labels);
50 double dcg = 0;
51 for (int i = 0; i < int(labels.size()); ++i) {
52 dcg += (pow(2, labels[i]) - 1) / log2(i + 2);
54 return dcg;
57 double
58 NDCGScore::score(const std::vector<FeatureVector> & fvv) const {
59 LOGCALL(API, double, "NDCGScore::score", fvv);
60 std::vector<double> labels;
61 for (auto&& v : fvv) {
62 labels.push_back(v.get_label());
64 // DCG score of original ranking
65 double DCG = get_dcg(labels);
66 // DCG score of ideal ranking
67 sort(labels.begin(), labels.begin() + labels.size(), std::greater<double>());
68 double iDCG = get_dcg(labels);
70 if (iDCG == 0) // Don't divide by 0
71 return 0;
72 return DCG / iDCG;