16VectorXf
log_loss(
const VectorXf& y,
const VectorXf& predict_proba,
17 const vector<float>& class_weights)
19 float eps = pow(10,-10);
23 float sum_weights = 0;
24 loss.resize(y.rows());
25 for (
unsigned i = 0; i < y.rows(); ++i)
27 if (predict_proba(i) < eps || 1 - predict_proba(i) < eps)
29 loss(i) = -(y(i)*log(eps) + (1-y(i))*log(1-eps));
31 loss(i) = -(y(i)*log(predict_proba(i)) + (1-y(i))*log(1-predict_proba(i)));
33 std::runtime_error(
"loss(i)= " + to_string(loss(i))
34 +
". y = " + to_string(y(i)) +
", predict_proba(i) = "
35 + to_string(predict_proba(i)));
37 if (!class_weights.empty())
39 loss(i) = loss(i) * class_weights.at(y(i));
40 sum_weights += class_weights.at(y(i));
45 loss = loss.array() / sum_weights * y.size();
61 const vector<float>& class_weights) {
64 vector<int> argsort(predict_proba.size());
65 iota(argsort.begin(), argsort.end(), 0);
66 sort(argsort.begin(), argsort.end(), [&](
int i,
int j) {
67 return predict_proba[i] > predict_proba[j];
71 if (!class_weights.empty())
72 for (
int i = 0; i < class_weights.size(); i++) {
73 ysum += y(i) * class_weights.at(y(i));
79 VectorXf precision(predict_proba.size());
80 VectorXf recall(predict_proba.size());
82 float true_positives = 0;
83 float false_positives = 0;
86 for (
int i = 0; i < predict_proba.size(); i++) {
87 if (predict_proba[argsort[i]] >= 0.5 && y[argsort[i]] == 1) {
91 if (!class_weights.empty())
92 false_positives = class_weights[y(argsort[i])];
96 positives = true_positives + false_positives;
98 precision[i] = true_positives / (positives + 1);
99 recall[i] = ysum==0.0 ? 1.0 : true_positives/ysum;
103 float average_precision = 0;
104 float last_recall = 0;
106 for (
int i = 0; i < predict_proba.size(); i++) {
107 if (recall[i] != last_recall) {
108 loss[i] = precision[i] * (recall[i] - last_recall);
109 average_precision += loss[i];
110 last_recall = recall[i];
114 return average_precision;
float mean_multi_log_loss(const VectorXf &y, const ArrayXXf &predict_proba, VectorXf &loss, const vector< float > &class_weights)
Calculates the mean multinomial log loss between the predicted probabilities and the true labels.
float average_precision_score(const VectorXf &y, const VectorXf &predict_proba, VectorXf &loss, const vector< float > &class_weights)
Calculates the average precision score between the predicted probabilities and the true labels.
VectorXf multi_log_loss(const VectorXf &y, const ArrayXXf &predict_proba, const vector< float > &class_weights)
Calculates the multinomial log loss between the predicted probabilities and the true labels.
VectorXf log_loss(const VectorXf &y, const VectorXf &predict_proba, const vector< float > &class_weights)
Calculates the log loss between the predicted probabilities and the true labels.