Skip to content

Commit 3a44bc1

Browse files
author
Takanori MAEHARA
authored
Create roc-auc.cc
1 parent 9cca6b8 commit 3a44bc1

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

machine_learning/roc-auc.cc

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
#include <bits/stdc++.h>
2+
3+
using namespace std;
4+
5+
double trapezoid(double x1, double x2, double y1, double y2) {
6+
return (y2+y1)/2 * abs(x2-x1);
7+
}
8+
9+
double auc(vector<int> test, vector<double> pred) {
10+
int n = test.size();
11+
assert(n == pred.size());
12+
13+
vector<int> idx(n);
14+
for (int i = 0; i < n; ++i) idx[i] = i;
15+
sort(idx.begin(), idx.end(), [&](int i, int j) { return pred[i] > pred[j]; });
16+
17+
double a = 0.0;
18+
double fp = 0, tp = 0, fp_prev = 0, tp_prev = 0;
19+
double prev_score = -1.0/0.0;
20+
for (int i: idx) {
21+
if (pred[i] != prev_score) {
22+
a += trapezoid(fp, fp_prev, tp, tp_prev);
23+
prev_score = pred[i];
24+
fp_prev = fp;
25+
tp_prev = tp;
26+
}
27+
if (test[i] == 1) {
28+
tp += 1;
29+
} else {
30+
fp += 1;
31+
}
32+
}
33+
a += trapezoid(fp, fp_prev, tp, tp_prev);
34+
return a / (tp * fp);
35+
}
36+
int main() {
37+
vector<int> test = {0, 1, 0, 1, 1};
38+
vector<double> pred = {0.2, 0.3, 0.4, 0.5, 0.6};
39+
cout << auc(test, pred) << endl;
40+
}

0 commit comments

Comments
 (0)