/
metric.cpp
6800 lines (6036 loc) · 248 KB
/
metric.cpp
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "metric.h"
#include "caching_metric.h"
#include "auc.h"
#include "auc_mu.h"
#include "balanced_accuracy.h"
#include "brier_score.h"
#include "classification_utils.h"
#include "dcg.h"
#include "doc_comparator.h"
#include "hinge_loss.h"
#include "kappa.h"
#include "llp.h"
#include "pfound.h"
#include "precision_recall_at_k.h"
#include "description_utils.h"
#include <catboost/libs/helpers/dispatch_generic_lambda.h>
#include <catboost/libs/helpers/exception.h>
#include <catboost/libs/helpers/short_vector_ops.h>
#include <catboost/libs/helpers/vector_helpers.h>
#include <catboost/libs/eval_result/eval_helpers.h>
#include <catboost/libs/logging/logging.h>
#include <catboost/private/libs/options/enum_helpers.h>
#include <catboost/private/libs/options/enums.h>
#include <catboost/private/libs/options/loss_description.h>
#include <library/cpp/fast_exp/fast_exp.h>
#include <library/cpp/fast_log/fast_log.h>
#include <util/generic/array_ref.h>
#include <util/generic/hash.h>
#include <util/generic/hash_set.h>
#include <util/generic/maybe.h>
#include <util/generic/string.h>
#include <util/generic/ymath.h>
#include <util/string/builder.h>
#include <util/string/cast.h>
#include <util/string/split.h>
#include <util/string/printf.h>
#include <util/system/yassert.h>
#include <limits>
#include <tuple>
using NCB::AppendTemporaryMetricsVector;
using NCB::AsVector;
/* TMetric */
static inline double OverflowSafeLogitProb(double approx) {
double expApprox = exp(approx);
return approx < 200 ? expApprox / (1.0 + expApprox) : 1.0;
}
TMetric::TMetric(ELossFunction lossFunction, TLossParams descriptionParams)
: LossFunction(lossFunction)
, DescriptionParams(std::move(descriptionParams)) {
}
EErrorType TMetric::GetErrorType() const {
return EErrorType::PerObjectError;
}
double TMetric::GetFinalError(const TMetricHolder& error) const {
Y_ASSERT(error.Stats.size() == 2);
return error.Stats[1] != 0 ? error.Stats[0] / error.Stats[1] : 0;
}
TVector<TString> TMetric::GetStatDescriptions() const {
return {"SumError", "SumWeight"};
}
const TMap<TString, TString>& TMetric::GetHints() const {
return Hints;
}
TString TMetric::GetDescription() const {
TLossParams descriptionParamsCopy = DescriptionParams;
descriptionParamsCopy.Erase("hints");
if (UseWeights.IsUserDefined()) {
descriptionParamsCopy.Put(UseWeights.GetName(), UseWeights.Get() ? "true" : "false");
}
return BuildDescriptionFromParams(LossFunction, descriptionParamsCopy);
}
void TMetric::AddHint(const TString& key, const TString& value) {
Hints[key] = value;
}
bool TMetric::NeedTarget() const {
return GetErrorType() != EErrorType::PairwiseError;
}
namespace {
struct TAdditiveMultiTargetMetric: public TMultiTargetMetric {
explicit TAdditiveMultiTargetMetric(ELossFunction lossFunction, const TLossParams& descriptionParams)
: TMultiTargetMetric(lossFunction, descriptionParams) {}
bool IsAdditiveMetric() const final {
return true;
}
virtual TMetricHolder Eval(
TConstArrayRef<TConstArrayRef<double>> approx,
TConstArrayRef<TConstArrayRef<double>> approxDelta,
TConstArrayRef<TConstArrayRef<float>> target,
TConstArrayRef<float> weight,
int begin,
int end,
NPar::ILocalExecutor& executor
) const override {
const auto evalMetric = [&](int from, int to) {
return EvalSingleThread(
approx, approxDelta, target, UseWeights.IsIgnored() || UseWeights ? weight : TVector<float>{}, from, to
);
};
return ParallelEvalMetric(evalMetric, GetMinBlockSize(end - begin), begin, end, executor);
}
virtual TMetricHolder EvalSingleThread(
TConstArrayRef<TConstArrayRef<double>> approx,
TConstArrayRef<TConstArrayRef<double>> approxDelta,
TConstArrayRef<TConstArrayRef<float>> target,
TConstArrayRef<float> weight,
int begin,
int end
) const = 0;
};
struct TAdditiveSingleTargetMetric: public TSingleTargetMetric {
explicit TAdditiveSingleTargetMetric(ELossFunction lossFunction, const TLossParams& descriptionParams)
: TSingleTargetMetric(lossFunction, descriptionParams) {}
bool IsAdditiveMetric() const final {
return true;
}
virtual TMetricHolder Eval(
TConstArrayRef<TConstArrayRef<double>> approx,
TConstArrayRef<TConstArrayRef<double>> approxDelta,
bool isExpApprox,
TConstArrayRef<float> target,
TConstArrayRef<float> weight,
TConstArrayRef<TQueryInfo> queriesInfo,
int begin,
int end,
NPar::ILocalExecutor& executor
) const override {
const auto evalMetric = [&](int from, int to) {
return EvalSingleThread(
approx, approxDelta, isExpApprox, target, UseWeights.IsIgnored() || UseWeights ? weight : TVector<float>{}, queriesInfo, from, to
);
};
return ParallelEvalMetric(evalMetric, GetMinBlockSize(end - begin), begin, end, executor);
}
virtual TMetricHolder EvalSingleThread(
TConstArrayRef<TConstArrayRef<double>> approx,
TConstArrayRef<TConstArrayRef<double>> approxDelta,
bool isExpApprox,
TConstArrayRef<float> target,
TConstArrayRef<float> weight,
TConstArrayRef<TQueryInfo> queriesInfo,
int begin,
int end
) const = 0;
};
struct TNonAdditiveSingleTargetMetric: public TSingleTargetMetric {
explicit TNonAdditiveSingleTargetMetric(ELossFunction lossFunction, const TLossParams& descriptionParams)
: TSingleTargetMetric(lossFunction, descriptionParams) {}
bool IsAdditiveMetric() const final {
return false;
}
};
}
static inline TConstArrayRef<double> GetRowRef(TConstArrayRef<TConstArrayRef<double>> matrix, size_t rowIdx) {
if (matrix.empty()) {
return TArrayRef<double>();
} else {
return matrix[rowIdx];
}
}
/* CrossEntropy */
namespace {
struct TCrossEntropyMetric final: public TAdditiveSingleTargetMetric {
explicit TCrossEntropyMetric(ELossFunction lossFunction, const TLossParams& params);
static TVector<THolder<IMetric>> Create(const TMetricConfig& config);
static TVector<TParamSet> ValidParamSets();
TMetricHolder EvalSingleThread(
TConstArrayRef<TConstArrayRef<double>> approx,
TConstArrayRef<TConstArrayRef<double>> approxDelta,
bool isExpApprox,
TConstArrayRef<float> target,
TConstArrayRef<float> weight,
TConstArrayRef<TQueryInfo> queriesInfo,
int begin,
int end
) const override;
void GetBestValue(EMetricBestValue* valueType, float* bestValue) const override;
private:
static constexpr double TargetBorder = GetDefaultTargetBorder();
ELossFunction LossFunction;
};
} // anonymous namespace
TVector<THolder<IMetric>> TCrossEntropyMetric::Create(const TMetricConfig& config) {
return AsVector(MakeHolder<TCrossEntropyMetric>(config.Metric, config.Params));
}
TCrossEntropyMetric::TCrossEntropyMetric(ELossFunction lossFunction, const TLossParams& params)
: TAdditiveSingleTargetMetric(lossFunction, params)
, LossFunction(lossFunction)
{
CB_ENSURE_INTERNAL(
lossFunction == ELossFunction::Logloss || lossFunction == ELossFunction::CrossEntropy,
"lossFunction " << lossFunction
);
if (lossFunction == ELossFunction::CrossEntropy) {
CB_ENSURE(TargetBorder == GetDefaultTargetBorder(), "TargetBorder is meaningless for crossEntropy metric");
}
}
TMetricHolder TCrossEntropyMetric::EvalSingleThread(
TConstArrayRef<TConstArrayRef<double>> approxRef,
TConstArrayRef<TConstArrayRef<double>> approxDeltaRef,
bool isExpApprox,
TConstArrayRef<float> target,
TConstArrayRef<float> weight,
TConstArrayRef<TQueryInfo> /*queriesInfo*/,
int begin,
int end
) const {
// p * log(1/(1+exp(-f))) + (1-p) * log(1 - 1/(1+exp(-f))) =
// p * log(exp(f) / (exp(f) + 1)) + (1-p) * log(exp(-f)/(1+exp(-f))) =
// p * log(exp(f) / (exp(f) + 1)) + (1-p) * log(1/(exp(f) + 1)) =
// p * (log(val) - log(val + 1)) + (1-p) * (-log(val + 1)) =
// p*log(val) - p*log(val+1) - log(val+1) + p*log(val+1) =
// p*log(val) - log(val+1)
CB_ENSURE(approxRef.size() == 1, "Metric logloss supports only single-dimensional data");
const auto impl = [=] (auto isExpApprox, auto hasDelta, auto hasWeight, auto isLogloss) {
float targetBorder = TargetBorder;
TConstArrayRef<double> approx = approxRef[0];
TConstArrayRef<double> approxDelta = GetRowRef(approxDeltaRef, /*rowIdx*/0);
int tailBegin;
auto holder = NMixedSimdOps::EvalCrossEntropyVectorized(
isExpApprox,
hasDelta,
hasWeight,
isLogloss,
approx,
approxDelta,
target,
weight,
targetBorder,
begin,
end,
&tailBegin);
for (int i = tailBegin; i < end; ++i) {
const float w = hasWeight ? weight[i] : 1;
const float prob = isLogloss ? target[i] > targetBorder : target[i];
if (isExpApprox) {
double expApprox = approx[i];
double nonExpApprox = FastLogf(expApprox);
if (hasDelta) {
expApprox *= approxDelta[i];
nonExpApprox += FastLogf(approxDelta[i]);
}
holder.Stats[0] += w * (IsFinite(expApprox) ? FastLogf(1 + expApprox) - prob * nonExpApprox : (1 - prob) * nonExpApprox);
} else {
double nonExpApprox = approx[i];
if (hasDelta) {
nonExpApprox += approxDelta[i];
}
const double expApprox = exp(nonExpApprox);
holder.Stats[0] += w * (IsFinite(expApprox) ? log(1 + expApprox) - prob * nonExpApprox : (1 - prob) * nonExpApprox);
}
holder.Stats[1] += w;
}
return holder;
};
return DispatchGenericLambda(impl, isExpApprox, !approxDeltaRef.empty(), !weight.empty(), LossFunction == ELossFunction::Logloss);
}
TVector<TParamSet> TCrossEntropyMetric::ValidParamSets() {
return {TParamSet{{TParamInfo{"use_weights", false, true}}, ""}};
};
void TCrossEntropyMetric::GetBestValue(EMetricBestValue* valueType, float* bestValue) const {
*valueType = EMetricBestValue::Min;
if (bestValue) {
*bestValue = 0;
}
}
/* CtrFactor */
namespace {
class TCtrFactorMetric final: public TAdditiveSingleTargetMetric {
public:
explicit TCtrFactorMetric(const TLossParams& params)
: TAdditiveSingleTargetMetric(ELossFunction::CtrFactor, params) {
}
static TVector<TParamSet> ValidParamSets();
TMetricHolder EvalSingleThread(
TConstArrayRef<TConstArrayRef<double>> approx,
TConstArrayRef<TConstArrayRef<double>> approxDelta,
bool isExpApprox,
TConstArrayRef<float> target,
TConstArrayRef<float> weight,
TConstArrayRef<TQueryInfo> queriesInfo,
int begin,
int end
) const override;
void GetBestValue(EMetricBestValue* valueType, float* bestValue) const override;
private:
static constexpr double TargetBorder = GetDefaultTargetBorder();
};
}
THolder<IMetric> MakeCtrFactorMetric(const TLossParams& params) {
return MakeHolder<TCtrFactorMetric>(params);
}
TMetricHolder TCtrFactorMetric::EvalSingleThread(
TConstArrayRef<TConstArrayRef<double>> approx,
TConstArrayRef<TConstArrayRef<double>> approxDelta,
bool isExpApprox,
TConstArrayRef<float> target,
TConstArrayRef<float> weight,
TConstArrayRef<TQueryInfo> /*queriesInfo*/,
int begin,
int end
) const {
Y_ASSERT(approxDelta.empty());
Y_ASSERT(!isExpApprox);
const auto& approxVec = approx.front();
Y_ASSERT(approxVec.size() == target.size());
TMetricHolder holder(2);
const double* approxPtr = approxVec.data();
const float* targetPtr = target.data();
for (int i = begin; i < end; ++i) {
float w = weight.empty() ? 1 : weight[i];
const float targetVal = targetPtr[i] > TargetBorder;
holder.Stats[0] += w * targetVal;
const double p = OverflowSafeLogitProb(approxPtr[i]);
holder.Stats[1] += w * p;
}
return holder;
}
void TCtrFactorMetric::GetBestValue(EMetricBestValue* valueType, float* bestValue) const {
*valueType = EMetricBestValue::FixedValue;
if (bestValue) {
*bestValue = 1;
}
}
TVector<TParamSet> TCtrFactorMetric::ValidParamSets() {
return {TParamSet{{TParamInfo{"use_weights", false, true}}, ""}};
};
/* SurvivalAFT */
namespace {
struct TSurvivalAftMetric final: public TAdditiveMultiTargetMetric {
explicit TSurvivalAftMetric(const TLossParams& params)
: TAdditiveMultiTargetMetric(ELossFunction::SurvivalAft, params) {
}
static TVector<THolder<IMetric>> Create(const TMetricConfig& config);
static TVector<TParamSet> ValidParamSets();
TMetricHolder EvalSingleThread(
TConstArrayRef<TConstArrayRef<double>> approx,
TConstArrayRef<TConstArrayRef<double>> approxDelta,
TConstArrayRef<TConstArrayRef<float>> target,
TConstArrayRef<float> weight,
int begin,
int end
) const override;
void GetBestValue(EMetricBestValue* valueType, float* bestValue) const override;
double GetFinalError(const TMetricHolder& error) const override;
};
}
TVector<THolder<IMetric>> TSurvivalAftMetric::Create(const TMetricConfig& config) {
config.ValidParams->insert("scale");
config.ValidParams->insert("dist");
return AsVector(MakeHolder<TSurvivalAftMetric>(config.Params));
}
TVector<TParamSet> TSurvivalAftMetric::ValidParamSets() {
// TODO(akhropov): SurvivalAft has 'scale' and 'dist' when it is used as an objective but no such params
// when used as a metric, it's better to have objectives as separate entities
return {TParamSet{{TParamInfo{"use_weights", false, true}}, ""}};
}
TMetricHolder TSurvivalAftMetric::EvalSingleThread(
TConstArrayRef<TConstArrayRef<double>> approx,
TConstArrayRef<TConstArrayRef<double>> approxDelta,
TConstArrayRef<TConstArrayRef<float>> target,
TConstArrayRef<float> weight,
int begin,
int end
) const {
const auto evalImpl = [=](auto useWeights, auto hasDelta) {
const auto realApprox = [=](int dim, int idx) { return fast_exp(approx[dim][idx] + (hasDelta ? approxDelta[dim][idx] : 0)); };
const auto realTarget = [=](int dim, int idx) { return target[dim][idx] == -1 ? std::numeric_limits<float>::infinity() : target[dim][idx]; };
const auto realWeight = [=](int idx) { return useWeights ? weight[idx] : 1; };
TMetricHolder error(2);
for (auto i : xrange(begin, end)) {
if ((realApprox(0, i) <= realTarget(0, i)) || (realApprox(0, i) >= realTarget(1, i))) {
double distanceFromInterval = Min(Abs(realApprox(0, i) - realTarget(0, i)), Abs(realApprox(0, i) - realTarget(1, i)));
error.Stats[0] += distanceFromInterval * realWeight(i);
}
error.Stats[1] += realWeight(i);
}
return error;
};
return DispatchGenericLambda(evalImpl, !weight.empty(), !approxDelta.empty());
}
double TSurvivalAftMetric::GetFinalError(const TMetricHolder& error) const {
return error.Stats[1] == 0 ? 0 : error.Stats[0] / error.Stats[1];
}
void TSurvivalAftMetric::GetBestValue(EMetricBestValue* valueType, float* bestValue) const {
*valueType = EMetricBestValue::Min;
if (bestValue) {
*bestValue = 0;
}
}
/* MultiRMSE */
namespace {
struct TMultiRMSEMetric final: public TAdditiveMultiTargetMetric {
explicit TMultiRMSEMetric(const TLossParams& params)
: TAdditiveMultiTargetMetric(ELossFunction::MultiRMSE, params)
{}
static TVector<THolder<IMetric>> Create(const TMetricConfig& config);
static TVector<TParamSet> ValidParamSets();
TMetricHolder EvalSingleThread(
TConstArrayRef<TConstArrayRef<double>> approx,
TConstArrayRef<TConstArrayRef<double>> approxDelta,
TConstArrayRef<TConstArrayRef<float>> target,
TConstArrayRef<float> weight,
int begin,
int end
) const override;
void GetBestValue(EMetricBestValue* valueType, float* bestValue) const override;
double GetFinalError(const TMetricHolder& error) const override;
};
}
// static
TVector<THolder<IMetric>> TMultiRMSEMetric::Create(const TMetricConfig& config) {
return AsVector(MakeHolder<TMultiRMSEMetric>(config.Params));
}
TMetricHolder TMultiRMSEMetric::EvalSingleThread(
TConstArrayRef<TConstArrayRef<double>> approx,
TConstArrayRef<TConstArrayRef<double>> approxDelta,
TConstArrayRef<TConstArrayRef<float>> target,
TConstArrayRef<float> weight,
int begin,
int end
) const {
const auto evalImpl = [=](auto useWeights, auto hasDelta) {
const auto realApprox = [=](int dim, int idx) { return approx[dim][idx] + (hasDelta ? approxDelta[dim][idx] : 0); };
const auto realWeight = [=](int idx) { return useWeights ? weight[idx] : 1; };
TMetricHolder error(2);
for (auto dim : xrange(target.size())) {
for (auto i : xrange(begin, end)) {
error.Stats[0] += realWeight(i) * Sqr(realApprox(dim, i) - target[dim][i]);
}
}
for (auto i : xrange(begin, end)) {
error.Stats[1] += realWeight(i);
}
return error;
};
return DispatchGenericLambda(evalImpl, !weight.empty(), !approxDelta.empty());
}
double TMultiRMSEMetric::GetFinalError(const TMetricHolder& error) const {
return error.Stats[1] == 0 ? 0 : sqrt(error.Stats[0] / error.Stats[1]);
}
void TMultiRMSEMetric::GetBestValue(EMetricBestValue* valueType, float* bestValue) const {
*valueType = EMetricBestValue::Min;
if (bestValue) {
*bestValue = 0;
}
}
TVector<TParamSet> TMultiRMSEMetric::ValidParamSets() {
return {TParamSet{{TParamInfo{"use_weights", false, true}}, ""}};
};
/* MultiRMSEWithMissingValues */
namespace {
struct TMultiRMSEWithMissingValues final: public TAdditiveMultiTargetMetric {
explicit TMultiRMSEWithMissingValues(const TLossParams& params)
: TAdditiveMultiTargetMetric(ELossFunction::MultiRMSEWithMissingValues, params)
{}
static TVector<THolder<IMetric>> Create(const TMetricConfig& config);
static TVector<TParamSet> ValidParamSets();
TMetricHolder EvalSingleThread(
TConstArrayRef<TConstArrayRef<double>> approx,
TConstArrayRef<TConstArrayRef<double>> approxDelta,
TConstArrayRef<TConstArrayRef<float>> target,
TConstArrayRef<float> weight,
int begin,
int end
) const override;
void GetBestValue(EMetricBestValue* valueType, float* bestValue) const override;
double GetFinalError(const TMetricHolder& error) const override;
};
}
// static
TVector<THolder<IMetric>> TMultiRMSEWithMissingValues::Create(const TMetricConfig& config) {
return AsVector(MakeHolder<TMultiRMSEWithMissingValues>(config.Params));
}
TMetricHolder TMultiRMSEWithMissingValues::EvalSingleThread(
TConstArrayRef<TConstArrayRef<double>> approx,
TConstArrayRef<TConstArrayRef<double>> approxDelta,
TConstArrayRef<TConstArrayRef<float>> target,
TConstArrayRef<float> weight,
int begin,
int end
) const {
const auto evalImpl = [=](auto useWeights, auto hasDelta) {
const auto realApprox = [=](int dim, int idx) { return approx[dim][idx] + (hasDelta ? approxDelta[dim][idx] : 0); };
const auto realWeight = [=](int idx) { return useWeights ? weight[idx] : 1; };
TMetricHolder error(target.size() * 2);
for (auto dim : xrange(target.size())) {
double sumWeights = 0.0;
double sumErrors = 0.0;
for (auto i : xrange(begin, end)) {
if (!IsNan(target[dim][i])) {
sumErrors += realWeight(i) * Sqr(realApprox(dim, i) - target[dim][i]);
sumWeights += realWeight(i);
}
}
error.Stats[dim * 2] += sumErrors;
error.Stats[dim * 2 + 1] += sumWeights;
}
return error;
};
return DispatchGenericLambda(evalImpl, !weight.empty(), !approxDelta.empty());
}
double TMultiRMSEWithMissingValues::GetFinalError(const TMetricHolder& error) const {
double finalError = 0.0;
for (size_t dim = 0; dim < error.Stats.size(); dim += 2) {
if (error.Stats[dim + 1] != 0) {
finalError += error.Stats[dim] / error.Stats[dim+1];
}
}
return sqrt(finalError);
}
void TMultiRMSEWithMissingValues::GetBestValue(EMetricBestValue* valueType, float* bestValue) const {
*valueType = EMetricBestValue::Min;
if (bestValue) {
*bestValue = 0;
}
}
TVector<TParamSet> TMultiRMSEWithMissingValues::ValidParamSets() {
return {TParamSet{{TParamInfo{"use_weights", false, true}}, ""}};
};
/* RMSEWithUncertainty */
namespace {
class TRMSEWithUncertaintyMetric final: public TAdditiveSingleTargetMetric {
public:
explicit TRMSEWithUncertaintyMetric(
ELossFunction lossFunction,
const TLossParams& descriptionParams);
static TVector<THolder<IMetric>> Create(const TMetricConfig& config);
static TVector<TParamSet> ValidParamSets();
TMetricHolder EvalSingleThread(
TConstArrayRef<TConstArrayRef<double>> approx,
TConstArrayRef<TConstArrayRef<double>> approxDelta,
bool isExpApprox,
TConstArrayRef<float> target,
TConstArrayRef<float> weight,
TConstArrayRef<TQueryInfo> queriesInfo,
int begin,
int end
) const override;
void GetBestValue(EMetricBestValue* valueType, float* bestValue) const override;
double GetFinalError(const TMetricHolder& error) const override;
};
}
TRMSEWithUncertaintyMetric::TRMSEWithUncertaintyMetric(
ELossFunction lossFunction,
const TLossParams& descriptionParams)
: TAdditiveSingleTargetMetric(lossFunction, descriptionParams)
{}
TVector<THolder<IMetric>> TRMSEWithUncertaintyMetric::Create(const TMetricConfig& config) {
return AsVector(MakeHolder<TRMSEWithUncertaintyMetric>(config.Metric, config.Params));
}
TMetricHolder TRMSEWithUncertaintyMetric::EvalSingleThread(
TConstArrayRef<TConstArrayRef<double>> approx,
TConstArrayRef<TConstArrayRef<double>> approxDelta,
bool isExpApprox,
TConstArrayRef<float> target,
TConstArrayRef<float> weights,
TConstArrayRef<TQueryInfo> /* queriesInfo */,
int begin,
int end
) const {
Y_ASSERT(!isExpApprox);
CB_ENSURE(approx.size() == 2,
"Approx dimension for RMSEWithUncertainty metric should be 2, found " << approx.size() <<
", probably your model was trained not with RMSEWithUncertainty loss function");
const auto evalImpl = [=](auto useWeights, auto hasDelta) {
const auto realApprox = [=](int dim, int idx) { return approx[dim][idx] + (hasDelta ? approxDelta[dim][idx] : 0); };
const auto realWeight = [=](int idx) { return useWeights ? weights[idx] : 1; };
TMetricHolder error(2);
double stats0 = 0;
double stats1 = 0;
for (auto i : xrange(begin, end)) {
double weight = realWeight(i);
double expSum = -2 * realApprox(1, i);
FastExpInplace(&expSum, /*count*/ 1);
// np.log(2 * np.pi) / 2.0
stats0 += weight * (0.9189385332046 + realApprox(1, i) + 0.5 * expSum * Sqr(realApprox(0, i) - target[i]));
stats1 += weight;
}
error.Stats[0] += stats0;
error.Stats[1] += stats1;
return error;
};
return DispatchGenericLambda(evalImpl, !weights.empty(), !approxDelta.empty());
}
double TRMSEWithUncertaintyMetric::GetFinalError(const TMetricHolder& error) const {
return error.Stats[1] == 0 ? 0 : error.Stats[0] / error.Stats[1];
}
void TRMSEWithUncertaintyMetric::GetBestValue(EMetricBestValue* valueType, float* bestValue) const {
*valueType = EMetricBestValue::Min;
if (bestValue) {
*bestValue = 0;
}
}
TVector<TParamSet> TRMSEWithUncertaintyMetric::ValidParamSets() {
return {TParamSet{{TParamInfo{"use_weights", false, true}}, ""}};
};
/* RMSE */
namespace {
struct TRMSEMetric final: public TAdditiveSingleTargetMetric {
explicit TRMSEMetric(const TLossParams& params)
: TAdditiveSingleTargetMetric(ELossFunction::RMSE, params)
{}
static TVector<THolder<IMetric>> Create(const TMetricConfig& config);
static TVector<TParamSet> ValidParamSets();
TMetricHolder EvalSingleThread(
TConstArrayRef<TConstArrayRef<double>> approx,
TConstArrayRef<TConstArrayRef<double>> approxDelta,
bool isExpApprox,
TConstArrayRef<float> target,
TConstArrayRef<float> weight,
TConstArrayRef<TQueryInfo> queriesInfo,
int begin,
int end
) const override;
double GetFinalError(const TMetricHolder& error) const override;
void GetBestValue(EMetricBestValue* valueType, float* bestValue) const override;
};
}
TVector<THolder<IMetric>> TRMSEMetric::Create(const TMetricConfig& config) {
return AsVector(MakeHolder<TRMSEMetric>(config.Params));
}
TMetricHolder TRMSEMetric::EvalSingleThread(
TConstArrayRef<TConstArrayRef<double>> approxRef,
TConstArrayRef<TConstArrayRef<double>> approxDeltaRef,
bool isExpApprox,
TConstArrayRef<float> target,
TConstArrayRef<float> weight,
TConstArrayRef<TQueryInfo> /*queriesInfo*/,
int begin,
int end
) const {
Y_ASSERT(!isExpApprox);
const auto impl = [=] (auto hasDelta, auto hasWeight) {
TConstArrayRef<double> approx = approxRef[0];
TConstArrayRef<double> approxDelta = GetRowRef(approxDeltaRef, /*rowIdx*/0);
TMetricHolder error(2);
for (int k : xrange(begin, end)) {
double targetMismatch = approx[k] - target[k];
if (hasDelta) {
targetMismatch += approxDelta[k];
}
const float w = hasWeight ? weight[k] : 1;
error.Stats[0] += Sqr(targetMismatch) * w;
error.Stats[1] += w;
}
return error;
};
return DispatchGenericLambda(impl, !approxDeltaRef.empty(), !weight.empty());
}
double TRMSEMetric::GetFinalError(const TMetricHolder& error) const {
return sqrt(error.Stats[0] / (error.Stats[1] + 1e-38));
}
void TRMSEMetric::GetBestValue(EMetricBestValue* valueType, float* bestValue) const {
*valueType = EMetricBestValue::Min;
if (bestValue) {
*bestValue = 0;
}
}
TVector<TParamSet> TRMSEMetric::ValidParamSets() {
return {TParamSet{{TParamInfo{"use_weights", false, true}}, ""}};
};
/* Log Cosh loss */
namespace {
struct TLogCoshMetric final: public TAdditiveSingleTargetMetric {
explicit TLogCoshMetric(const TLossParams& params)
: TAdditiveSingleTargetMetric(ELossFunction::LogCosh, params)
{}
static TVector<THolder<IMetric>> Create(const TMetricConfig& config);
static TVector<TParamSet> ValidParamSets();
TMetricHolder EvalSingleThread(
TConstArrayRef<TConstArrayRef<double>> approx,
TConstArrayRef<TConstArrayRef<double>> approxDelta,
bool isExpApprox,
TConstArrayRef<float> target,
TConstArrayRef<float> weight,
TConstArrayRef<TQueryInfo> queriesInfo,
int begin,
int end
) const override;
double GetFinalError(const TMetricHolder& error) const override;
void GetBestValue(EMetricBestValue* valueType, float* bestValue) const override;
};
}
TVector<THolder<IMetric>> TLogCoshMetric::Create(const TMetricConfig& config) {
return AsVector(MakeHolder<TLogCoshMetric>(config.Params));
}
TMetricHolder TLogCoshMetric::EvalSingleThread(
TConstArrayRef<TConstArrayRef<double>> approxRef,
TConstArrayRef<TConstArrayRef<double>> approxDeltaRef,
bool isExpApprox,
TConstArrayRef<float> target,
TConstArrayRef<float> weight,
TConstArrayRef<TQueryInfo> /*queriesInfo*/,
int begin,
int end
) const {
Y_ASSERT(!isExpApprox);
const double METRIC_APPROXIMATION_THRESHOLD = 12;
const auto impl = [=] (auto hasDelta, auto hasWeight) {
TConstArrayRef<double> approx = approxRef[0];
TConstArrayRef<double> approxDelta = GetRowRef(approxDeltaRef, /*rowIdx*/0);
TMetricHolder error(2);
for (int k : xrange(begin, end)) {
double targetMismatch = approx[k] - target[k];
if (hasDelta) {
targetMismatch += approxDelta[k];
}
const float w = hasWeight ? weight[k] : 1;
if (abs(targetMismatch) >= METRIC_APPROXIMATION_THRESHOLD)
error.Stats[0] += (abs(targetMismatch) - FastLogf(2)) * w;
else
error.Stats[0] += FastLogf(cosh(targetMismatch)) * w;
error.Stats[1] += w;
}
return error;
};
return DispatchGenericLambda(impl, !approxDeltaRef.empty(), !weight.empty());
}
double TLogCoshMetric::GetFinalError(const TMetricHolder& error) const {
return error.Stats[0] / (error.Stats[1] + 1e-38);
}
void TLogCoshMetric::GetBestValue(EMetricBestValue* valueType, float* bestValue) const {
*valueType = EMetricBestValue::Min;
if (bestValue) {
*bestValue = 0;
}
}
TVector<TParamSet> TLogCoshMetric::ValidParamSets() {
return {
TParamSet{
{TParamInfo{"use_weights", false, true}},
""
}
};
};
/* Cox partial loss */
namespace {
struct TCoxMetric final: public TNonAdditiveSingleTargetMetric {
explicit TCoxMetric(const TLossParams& params)
: TNonAdditiveSingleTargetMetric(ELossFunction::Cox, params)
{}
static TVector<THolder<IMetric>> Create(const TMetricConfig& config);
static TVector<TParamSet> ValidParamSets();
TMetricHolder Eval(
TConstArrayRef<TConstArrayRef<double>> approx,
TConstArrayRef<TConstArrayRef<double>> approxDelta,
bool isExpApprox,
TConstArrayRef<float> target,
TConstArrayRef<float> weight,
TConstArrayRef<TQueryInfo> queriesInfo,
int begin,
int end,
NPar::ILocalExecutor& executor
) const override;
double GetFinalError(const TMetricHolder& error) const override;
void GetBestValue(EMetricBestValue* valueType, float* bestValue) const override;
};
}
TVector<THolder<IMetric>> TCoxMetric::Create(const TMetricConfig& config) {
return AsVector(MakeHolder<TCoxMetric>(config.Params));
}
TVector<TParamSet> TCoxMetric::ValidParamSets() {
return {TParamSet{{}, ""}};
};
TMetricHolder TCoxMetric::Eval(
TConstArrayRef<TConstArrayRef<double>> approx,
TConstArrayRef<TConstArrayRef<double>> approxDelta,
bool isExpApprox,
TConstArrayRef<float> targets,
TConstArrayRef<float> /*weight*/,
TConstArrayRef<TQueryInfo> /*queriesInfo*/,
int /*begin*/,
int /*end*/,
NPar::ILocalExecutor& /* executor */
) const {
Y_ASSERT(!isExpApprox);
TMetricHolder error(2);
error.Stats[1] = 1;
const auto ndata = targets.ysize();
TVector<int> labelOrder(ndata);
std::iota(labelOrder.begin(), labelOrder.end(), 0);
std::sort(
labelOrder.begin(),
labelOrder.end(),
[=] (int lhs, int rhs) {
return std::abs(targets[lhs]) < std::abs(targets[rhs]);
}
);
const auto approxRef = approx[0];
const auto approxDeltaRef = GetRowRef(approxDelta, /*row idx*/ 0);
const auto getApprox = [=] (int i) {
return approxRef[i] + (approxDelta.empty() ? 0 : approxDeltaRef[i]);
};
double expPSum = 0;
for (auto i = 0; i < ndata; ++i) {
expPSum += std::exp(getApprox(i));
}
double lastExpP = 0.0;
double accumulatedSum = 0;
for (auto i : xrange(ndata)) {
const int ind = labelOrder[i];
const double y = targets[ind];
const double p = getApprox(ind);
const double expP = std::exp(p);
accumulatedSum += lastExpP;
if (y > 0) {
expPSum -= accumulatedSum;
accumulatedSum = 0;
error.Stats[0] += p - std::log(std::max(expPSum, 1e-20));
}
lastExpP = expP;
}
error.Stats[0] = error.Stats[0];
return error;
}
double TCoxMetric::GetFinalError(const TMetricHolder& error) const {
return error.Stats[0];
}
void TCoxMetric::GetBestValue(EMetricBestValue* valueType, float* bestValue) const {
*valueType = EMetricBestValue::Min;
if (bestValue) {
*bestValue = 0;
}
}
/* Lq */
namespace {
struct TLqMetric final: public TAdditiveSingleTargetMetric {
explicit TLqMetric(double q, const TLossParams& params)
: TAdditiveSingleTargetMetric(ELossFunction::Lq, params)
, Q(q) {
CB_ENSURE(Q >= 1, "Lq metric is defined for q >= 1, got " << q);
}
static TVector<THolder<IMetric>> Create(const TMetricConfig& config);
static TVector<TParamSet> ValidParamSets();
TMetricHolder EvalSingleThread(
TConstArrayRef<TConstArrayRef<double>> approx,
TConstArrayRef<TConstArrayRef<double>> approxDelta,
bool isExpApprox,
TConstArrayRef<float> target,
TConstArrayRef<float> weight,
TConstArrayRef<TQueryInfo> queriesInfo,
int begin,
int end
) const override;
void GetBestValue(EMetricBestValue* valueType, float* bestValue) const override;
private:
const double Q;
};
}
TVector<TParamSet> TLqMetric::ValidParamSets() {
return {
TParamSet{
{
TParamInfo{"use_weights", false, true},
TParamInfo{"q", true, {}}
},
""
}
};
}
// static
TVector<THolder<IMetric>> TLqMetric::Create(const TMetricConfig& config) {
CB_ENSURE(config.GetParamsMap().contains("q"), "Metric " << ELossFunction::Lq << " requires q as parameter");
config.ValidParams->insert("q");
return AsVector(MakeHolder<TLqMetric>(FromString<float>(config.GetParamsMap().at("q")),
config.Params));
}