2 * @brief Implementation of NDCGScore
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
25 #include "xapian-letor/scorer.h"
34 using namespace Xapian
;
36 NDCGScore::NDCGScore()
38 LOGCALL_CTOR(API
, "NDCGScore", NO_ARGS
);
41 NDCGScore::~NDCGScore()
43 LOGCALL_DTOR(API
, "NDCGScore");
47 get_dcg(const std::vector
<double> &labels
)
49 LOGCALL_STATIC(API
, double, "get_dcg", labels
);
51 for (int i
= 0; i
< int(labels
.size()); ++i
) {
52 dcg
+= (exp2(labels
[i
]) - 1) / log2(i
+ 2);
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 if (rare(dcg
== 0.0)) {
67 // Avoid dividing by 0.
70 // DCG score of ideal ranking
71 sort(labels
.begin(), labels
.end(), std::greater
<double>());
72 double idcg
= get_dcg(labels
);
73 AssertRel(idcg
, >=, dcg
);