-
Notifications
You must be signed in to change notification settings - Fork 3
/
baselearner_factory.cpp
1451 lines (1208 loc) · 46.9 KB
/
baselearner_factory.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
// ========================================================================== //
// ___. __ //
// ____ ____ _____ ______\_ |__ ____ ____ _______/ |_ //
// _/ ___\/ _ \ / \\____ \| __ \ / _ \ / _ \/ ___/\ __\ //
// \ \__( <_> ) Y Y \ |_> > \_\ ( <_> | <_> )___ \ | | //
// \___ >____/|__|_| / __/|___ /\____/ \____/____ > |__| //
// \/ \/|__| \/ \/ //
// //
// ========================================================================== //
//
// Compboost is free software: you can redistribute it and/or modify
// it under the terms of the LGPL-3 License.
// Compboost is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// LGPL-3 License for more details. You should have received a copy of
// the license along with compboost.
//
// =========================================================================== #
#include "baselearner_factory.h"
namespace blearnerfactory {
std::shared_ptr<BaselearnerFactory> jsonToBaselearnerFactory (const json& j, const mdata& mdsource, const mdata& mdinit)
{
std::shared_ptr<BaselearnerFactory> blf;
if (j["Class"] == "BaselearnerPolynomialFactory") {
blf = std::make_shared<BaselearnerPolynomialFactory>(j, mdsource, mdinit);
}
if (j["Class"] == "BaselearnerPSplineFactory") {
blf = std::make_shared<BaselearnerPSplineFactory>(j, mdsource, mdinit);
}
if (j["Class"] == "BaselearnerTensorFactory") {
blf = std::make_shared<BaselearnerTensorFactory>(j, mdsource, mdinit);
}
if (j["Class"] == "BaselearnerCenteredFactory") {
blf = std::make_shared<BaselearnerCenteredFactory>(j, mdsource, mdinit);
}
if (j["Class"] == "BaselearnerCategoricalRidgeFactory") {
blf = std::make_shared<BaselearnerCategoricalRidgeFactory>(j, mdsource, mdinit);
}
if (j["Class"] == "BaselearnerCategoricalBinaryFactory") {
blf = std::make_shared<BaselearnerCategoricalBinaryFactory>(j, mdsource, mdinit);
}
if (blf == nullptr) {
throw std::logic_error("No known class in JSON");
}
return blf;
}
// -------------------------------------------------------------------------- //
// Abstract 'BaselearnerFactory' class:
// -------------------------------------------------------------------------- //
BaselearnerFactory::BaselearnerFactory (const std::string blearner_type)
: _blearner_type ( blearner_type )
{ }
BaselearnerFactory::BaselearnerFactory (const std::string blearner_type, const std::shared_ptr<data::Data>& data_source)
: _blearner_type ( blearner_type ),
_sh_ptr_data_source ( data_source )
{ }
BaselearnerFactory::BaselearnerFactory (const json& j, const mdata& mdat)
: _blearner_type ( j["_blearner_type"].get<std::string>() ),
_sh_ptr_data_source ( data::extractDataFromMap(j["id_data_source"].get<std::string>(), mdat) )
{ }
std::vector<std::string> BaselearnerFactory::getDataIdentifier () const
{
if (_sh_ptr_data_source.use_count() == 0) {
throw std::logic_error("Data source is not initialized or 'getDataIdentifier()' is not implemented");
}
std::vector<std::string> out;
out.push_back(_sh_ptr_data_source->getDataIdentifier());
return out;
}
sdata BaselearnerFactory::getDataSource () const
{
return _sh_ptr_data_source;
}
std::string BaselearnerFactory::getBaselearnerType() const
{
return _blearner_type;
}
json BaselearnerFactory::baseToJson (const std::string cln) const
{
json j = {
{"Class", cln},
{"_blearner_type", _blearner_type},
{"id_data_source", _sh_ptr_data_source->getDataIdentifier()}
};
return j;
}
json BaselearnerFactory::dataSourceToJson (const bool rm_data) const
{
json j;
j[_sh_ptr_data_source->getDataIdentifier()] = _sh_ptr_data_source->toJson(rm_data);
return j;
}
std::vector<double> BaselearnerFactory::getMinMax () const
{
return _sh_ptr_data_source->getMinMax();
}
std::map<std::string, std::vector<std::string>> BaselearnerFactory::getValueNames () const
{
std::map<std::string, std::vector<std::string>> mout;
std::vector<std::string> out{ "x" };
mout[getDataIdentifier()[0]] = out;
return mout;
}
std::vector<sdata> BaselearnerFactory::getVecDataSource () const
{
std::vector<sdata> out;
out.push_back(_sh_ptr_data_source);
return out;
}
/// Destructor
BaselearnerFactory::~BaselearnerFactory () {}
// -------------------------------------------------------------------------- //
// BaselearnerFactory implementations:
// -------------------------------------------------------------------------- //
// BaselearnerPolynomial:
// -----------------------
BaselearnerPolynomialFactory::BaselearnerPolynomialFactory (const std::string blearner_type,
std::shared_ptr<data::Data> data_source, const unsigned int degree, const bool intercept,
const unsigned int bin_root, const double df, const double penalty)
: BaselearnerFactory::BaselearnerFactory ( blearner_type, data_source )
{
_attributes->df = df;
_attributes->penalty = penalty;
_attributes->degree = degree;
_attributes->use_intercept = intercept;
_attributes->bin_root = bin_root;
_sh_ptr_bindata = init::initPolynomialData(data_source, _attributes);
_attributes->penalty_mat = arma::diagmat( arma::vec(_sh_ptr_bindata->getNCols(), arma::fill::ones) );
arma::mat temp_xtx;
if (_attributes->degree == 1) {
arma::mat mraw = data_source->getDenseData();
arma::mat temp_mat(1, 2, arma::fill::zeros);
if (_attributes->use_intercept) {
temp_mat(0,0) = arma::as_scalar(arma::mean(mraw));
}
temp_mat(0,1) = arma::as_scalar(arma::sum(arma::pow(mraw - temp_mat(0,0), 2)));
temp_xtx = temp_mat;
_sh_ptr_bindata->setCache("identity", temp_xtx);
} else {
if (_sh_ptr_bindata->usesBinning()) {
arma::vec temp_weight(1, arma::fill::ones);
temp_xtx = binning::binnedMatMult(_sh_ptr_bindata->getDenseData(), _sh_ptr_bindata->getBinningIndex(), temp_weight);
} else {
temp_xtx = _sh_ptr_bindata->getDenseData().t() * _sh_ptr_bindata->getDenseData();
}
if (df > 0) {
try {
_attributes->penalty = dro::demmlerReinsch(temp_xtx, _attributes->penalty_mat, df);
} catch (const std::exception& e) {
std::string msg = "From constructor of BaselearnerPolynomialFactory with data '" + _sh_ptr_bindata->getDataIdentifier() +
"': Try to run demmlerDemmlerReinsch" + std::string(e.what());
throw msg;
}
}
_sh_ptr_bindata->setCache("cholesky", temp_xtx + _attributes->penalty * _attributes->penalty_mat);
}
_attributes->bin_root = 0;
}
BaselearnerPolynomialFactory::BaselearnerPolynomialFactory (const json& j, const mdata& mdsource, const mdata& mdinit)
: BaselearnerFactory::BaselearnerFactory ( j, mdsource ),
_sh_ptr_bindata ( std::static_pointer_cast<data::BinnedData>(data::extractDataFromMap(j["id_data_init"].get<std::string>(), mdinit)) ),
_attributes ( std::make_shared<init::PolynomialAttributes>(j["_attributes"]) )
{ }
sdata BaselearnerPolynomialFactory::instantiateData (const mdata& data_map) const
{
auto newdata = data::extractDataFromMap(this->_sh_ptr_data_source, data_map);
return init::initPolynomialData(newdata, _attributes);
}
bool BaselearnerPolynomialFactory::usesSparse () const
{
return false;
}
sdata BaselearnerPolynomialFactory::getInstantiatedData () const
{
return _sh_ptr_bindata;
}
arma::mat BaselearnerPolynomialFactory::getData () const
{
return _sh_ptr_bindata->getDenseData();
}
arma::vec BaselearnerPolynomialFactory::getDF () const
{
return arma::vec(1, arma::fill::value(_attributes->df));
}
arma::vec BaselearnerPolynomialFactory::getPenalty () const
{
return arma::vec(1, arma::fill::value(_attributes->penalty));
}
arma::mat BaselearnerPolynomialFactory::getPenaltyMat () const
{
return _attributes->penalty_mat;
}
std::string BaselearnerPolynomialFactory::getBaseModelName () const
{
return std::string("polynomial");
}
std::string BaselearnerPolynomialFactory::getFactoryId () const
{
return _sh_ptr_bindata->getDataIdentifier() + "_" + _blearner_type;
}
arma::mat BaselearnerPolynomialFactory::calculateLinearPredictor (const arma::mat& param) const
{
return _sh_ptr_bindata->getDenseData() * param;
}
arma::mat BaselearnerPolynomialFactory::calculateLinearPredictor (const arma::mat& param, const mdata& data_map) const
{
helper::debugPrint("From 'BaselearnerPolynomialFactory::calculateLinearPredictor' for feature " + this->_sh_ptr_data_source->getDataIdentifier());
// For newdata, we just extract the sparse data because no binning is used!
try {
auto newdata = data::extractDataFromMap(this->_sh_ptr_data_source, data_map);
return init::initPolynomialData(newdata, _attributes)->getDenseData() * param;
} catch (const char* msg) {
throw msg;
}
}
std::shared_ptr<blearner::Baselearner> BaselearnerPolynomialFactory::createBaselearner ()
{
return std::make_shared<blearner::BaselearnerPolynomial>(_blearner_type, _sh_ptr_bindata, _attributes);
}
json BaselearnerPolynomialFactory::toJson () const
{
json j = BaselearnerFactory::baseToJson("BaselearnerPolynomialFactory");
j["id_data_init"] = _sh_ptr_bindata->getDataIdentifier() + "." + _blearner_type;
j["_attributes"] = _attributes->toJson();
return j;
}
json BaselearnerPolynomialFactory::extractDataToJson (const bool save_source, const bool rm_data) const
{
json j;
std::string id_dat;
if (save_source) {
j = BaselearnerFactory::dataSourceToJson(rm_data);
} else {
id_dat = _sh_ptr_bindata->getDataIdentifier() + "." + _blearner_type;
j[id_dat] = _sh_ptr_bindata->toJson(rm_data);
}
return j;
}
// BaselearnerPSpline:
// -----------------------
/**
* \brief Default constructor of class `PSplineBleanrerFactory`
*
* The P-Spline constructor has some important tasks which are:
* - Set the knots
* - Initialize the spline base (knots must be setted prior)
* - Compute and store penalty matrix
*
* \param blearner_type `std::string` Name of the baselearner type (setted by
* the Rcpp Wrapper classes in `compboost_modules.cpp`)
* \param data_source `std::shared_ptr<data::Data>` Source of the data
* \param degree `unsigned int` Polynomial degree of the splines
* \param n_knots `unsigned int` Number of inner knots
* \param penalty `double` Regularization parameter `penalty = 0` gives
* b splines while a bigger penalty forces the splines into a global
* polynomial form
* \param differences `unsigned int` Number of differences used for the
* penalty matrix
* \param use_sparse_matrices `bool` Use sparse matrices for data storage
* \param use_binning `bool` Use binning to improve runtime performance and reduce memory load
*/
BaselearnerPSplineFactory::BaselearnerPSplineFactory (const std::string blearner_type,
const std::shared_ptr<data::Data>& data_source, const unsigned int degree, const unsigned int n_knots,
const double penalty, const double df, const unsigned int differences, const bool use_sparse_matrices,
const unsigned int bin_root, const std::string cache_type)
: BaselearnerFactory::BaselearnerFactory ( blearner_type, data_source )
{
_attributes->degree = degree;
_attributes->n_knots = n_knots;
_attributes->penalty = penalty;
_attributes->df = df;
_attributes->differences = differences;
_attributes->bin_root = bin_root;
_attributes->knots = splines::createKnots(data_source->getDenseData(), n_knots, degree);
_sh_ptr_bindata = init::initPSplineData(data_source, _attributes);
const arma::mat penalty_mat = splines::penaltyMat(_attributes->n_knots + (_attributes->degree + 1), _attributes->differences);
_attributes->penalty_mat = penalty_mat;;
arma::mat temp_xtx;
if (_sh_ptr_bindata->usesBinning()) {
arma::vec temp_weight(1, arma::fill::ones);
temp_xtx = binning::binnedSparseMatMult(_sh_ptr_bindata->getSparseData(), _sh_ptr_bindata->getBinningIndex(), temp_weight);
} else {
temp_xtx = _sh_ptr_bindata->getSparseData() * _sh_ptr_bindata->getSparseData().t();
}
if (df > 0) {
try {
_attributes->penalty = dro::demmlerReinsch(temp_xtx, penalty_mat, df);
} catch (const std::exception& e) {
std::string msg = "From constructor of BaselearnerPSplineFactory with data '" + _sh_ptr_bindata->getDataIdentifier() +
"': Try to run demmlerDemmlerReinsch" + std::string(e.what());
throw msg;
}
}
_sh_ptr_bindata->setCache(cache_type, temp_xtx + _attributes->penalty * _attributes->penalty_mat);
// Set bin_root to zero for later creation of data for predictions. We don't want to
// use binning there.
_attributes->bin_root = 0;
}
BaselearnerPSplineFactory::BaselearnerPSplineFactory (const json& j, const mdata& mdsource, const mdata& mdinit)
: BaselearnerFactory::BaselearnerFactory ( j, mdsource ),
_sh_ptr_bindata ( std::static_pointer_cast<data::BinnedData>(data::extractDataFromMap(j["id_data_init"].get<std::string>(), mdinit)) ),
_attributes ( std::make_shared<init::PSplineAttributes>(j["_attributes"]) )
{ }
bool BaselearnerPSplineFactory::usesSparse () const
{
return true;
}
sdata BaselearnerPSplineFactory::getInstantiatedData () const
{
return _sh_ptr_bindata;
}
sdata BaselearnerPSplineFactory::instantiateData (const mdata& data_map) const
{
auto newdata = data::extractDataFromMap(this->_sh_ptr_data_source, data_map);
auto attr_temp = _attributes;
attr_temp->bin_root = 0;
return init::initPSplineData(newdata, attr_temp);
}
arma::mat BaselearnerPSplineFactory::getData () const
{
return arma::mat(_sh_ptr_bindata->getSparseData());
}
arma::vec BaselearnerPSplineFactory::getDF () const
{
return arma::vec(1, arma::fill::value(_attributes->df));
}
arma::vec BaselearnerPSplineFactory::getPenalty () const
{
return arma::vec(1, arma::fill::value(_attributes->penalty));
}
arma::mat BaselearnerPSplineFactory::getPenaltyMat () const
{
return _attributes->penalty_mat;
}
std::string BaselearnerPSplineFactory::getBaseModelName () const
{
return std::string("pspline");
}
std::string BaselearnerPSplineFactory::getFactoryId () const
{
return _sh_ptr_bindata->getDataIdentifier() + "_" + _blearner_type;
}
arma::mat BaselearnerPSplineFactory::calculateLinearPredictor (const arma::mat& param) const
{
return (param.t() * _sh_ptr_bindata->getSparseData()).t();
}
arma::mat BaselearnerPSplineFactory::calculateLinearPredictor (const arma::mat& param, const mdata& data_map) const
{
helper::debugPrint("From 'BaselearnerPSplineFactory::calculateLinearPredictor' for feature " + this->_sh_ptr_data_source->getDataIdentifier());
try {
auto newdata = data::extractDataFromMap(this->_sh_ptr_data_source, data_map);
return (param.t() * init::initPSplineData(newdata, _attributes)->getSparseData()).t();
} catch (const char* msg) {
throw msg;
}
}
std::shared_ptr<blearner::Baselearner> BaselearnerPSplineFactory::createBaselearner ()
{
return std::make_shared<blearner::BaselearnerPSpline>(_blearner_type, std::static_pointer_cast<data::BinnedData>(_sh_ptr_bindata));
}
json BaselearnerPSplineFactory::toJson () const
{
json j = BaselearnerFactory::baseToJson("BaselearnerPSplineFactory");
j["id_data_init"] = _sh_ptr_bindata->getDataIdentifier() + "." + _blearner_type;
j["_attributes"] = _attributes->toJson();
return j;
}
json BaselearnerPSplineFactory::extractDataToJson (const bool save_source, const bool rm_data) const
{
json j;
std::string id_dat;
if (save_source) {
j = BaselearnerFactory::dataSourceToJson(rm_data);
} else {
id_dat = _sh_ptr_bindata->getDataIdentifier() + "." + _blearner_type;
j[id_dat] = _sh_ptr_bindata->toJson(rm_data);
}
return j;
}
// BaselearnerTensorFactory:
// ------------------------------------------------
BaselearnerTensorFactory::BaselearnerTensorFactory (const std::string& blearner_type,
std::shared_ptr<blearnerfactory::BaselearnerFactory> blearner1,
std::shared_ptr<blearnerfactory::BaselearnerFactory> blearner2, const bool isotrop)
: BaselearnerFactory::BaselearnerFactory (blearner_type, std::make_shared<data::InMemoryData>(
blearner1->getDataSource()->getDataIdentifier() + "_" +
blearner2->getDataSource()->getDataIdentifier())),
_blearner1 ( blearner1 ),
_blearner2 ( blearner2 ),
_isotrop ( isotrop )
{
// Get data from both learners
arma::mat bl1_penmat = _blearner1->getPenaltyMat();
arma::mat bl2_penmat = _blearner2->getPenaltyMat();
// PASS instantiated data of factories to initTensorData
_sh_ptr_data = init::initTensorData(_blearner1->getInstantiatedData(), _blearner2->getInstantiatedData());
arma::mat temp_xtx;
if (_sh_ptr_data->usesSparseMatrix()) {
temp_xtx = _sh_ptr_data->getSparseData() * _sh_ptr_data->getSparseData().t();
} else {
temp_xtx = _sh_ptr_data->getDenseData().t() * _sh_ptr_data->getDenseData();
}
// Calculate penalty matrix:
double df = arma::as_scalar(_blearner1->getDF() * _blearner2->getDF());
arma::mat penalty_mat;
if (_isotrop) {
penalty_mat = tensors::penaltySumKronecker(bl1_penmat, bl2_penmat);
try {
_attributes->penalty = dro::demmlerReinsch(temp_xtx, penalty_mat, df);
} catch (const std::exception& e) {
std::string msg = "From constructor of BaselearnerTensorFactory with data '" + _sh_ptr_data->getDataIdentifier() +
"': Try to run demmlerDemmlerReinsch" + std::string(e.what());
throw msg;
}
penalty_mat = penalty_mat * _attributes->penalty;
} else {
penalty_mat = tensors::penaltySumKronecker(bl1_penmat * arma::as_scalar(_blearner1->getPenalty()), bl2_penmat * arma::as_scalar(_blearner2->getPenalty()));
_attributes->penalty = arma::as_scalar(_blearner1->getPenalty() * _blearner2->getPenalty());
}
_sh_ptr_data->setCache("cholesky", temp_xtx + penalty_mat);
}
BaselearnerTensorFactory::BaselearnerTensorFactory (const json& j, const mdata& mdsource, const mdata& mdinit)
: BaselearnerFactory::BaselearnerFactory ( j, mdsource ),
_sh_ptr_data ( data::extractDataFromMap(j["id_data_init"].get<std::string>(), mdinit) ),
_attributes ( std::make_shared<init::TensorAttributes>(j["_attributes"])),
_blearner1 ( jsonToBaselearnerFactory(j["_blearner1"], mdsource, mdinit) ),
_blearner2 ( jsonToBaselearnerFactory(j["_blearner2"], mdsource, mdinit) ),
_isotrop ( j["_isotrop"].get<bool>() )
{ }
bool BaselearnerTensorFactory::usesSparse () const
{
return _blearner1->usesSparse() || _blearner2->usesSparse();
}
sdata BaselearnerTensorFactory::getInstantiatedData () const
{
return _sh_ptr_data;
}
sdata BaselearnerTensorFactory::instantiateData (const mdata& data_map) const
{
//auto data1 = data::extractDataFromMap(_blearner1->getInstantiatedData(), data_map);
//auto data2 = data::extractDataFromMap(_blearner2->getInstantiatedData(), data_map);
//
// Instantiate data ... again ... FIX
sdata newdata1 = _blearner1->instantiateData(data_map);
sdata newdata2 = _blearner2->instantiateData(data_map);
return init::initTensorData(newdata1, newdata2);
}
arma::mat BaselearnerTensorFactory::getData () const
{
arma::mat out;
if (_sh_ptr_data->usesSparseMatrix()) {
out = _sh_ptr_data->getSparseData();
} else {
out = _sh_ptr_data->getDenseData();
}
return out;
}
arma::vec BaselearnerTensorFactory::getDF () const
{
arma::vec df;
if (_isotrop) {
df = arma::vec(1, arma::fill::value(arma::as_scalar(_blearner1->getDF()) * arma::as_scalar(_blearner2->getDF())));
} else {
df = {
arma::as_scalar(_blearner1->getDF()),
arma::as_scalar(_blearner2->getDF()) };
}
return df;
}
arma::vec BaselearnerTensorFactory::getPenalty () const
{
arma::vec pen;
if (_isotrop) {
pen = arma::vec(1, arma::fill::value(_attributes->penalty));
} else {
pen = {
arma::as_scalar(_blearner1->getPenalty()),
arma::as_scalar(_blearner2->getPenalty()) };
}
return pen;
}
arma::mat BaselearnerTensorFactory::getPenaltyMat () const
{
arma::mat bl1_penmat = _blearner1->getPenaltyMat();
arma::mat bl2_penmat = _blearner2->getPenaltyMat();
double bl1_pen = arma::as_scalar(_blearner1->getPenalty());
double bl2_pen = arma::as_scalar(_blearner2->getPenalty());
arma::mat penalty_mat;
if (_isotrop) {
penalty_mat = tensors::penaltySumKronecker(bl1_penmat, bl2_penmat);
} else {
penalty_mat = tensors::penaltySumKronecker(bl1_pen * bl1_penmat, bl2_pen * bl2_penmat);
}
return penalty_mat;
}
std::string BaselearnerTensorFactory::getBaseModelName() const
{
return std::string("tensor");
}
std::string BaselearnerTensorFactory::getFactoryId () const
{
return _sh_ptr_data->getDataIdentifier() + "_" + _blearner_type;
}
std::shared_ptr<blearnerfactory::BaselearnerFactory> BaselearnerTensorFactory::getBl1 () const
{
return _blearner1;
}
std::shared_ptr<blearnerfactory::BaselearnerFactory> BaselearnerTensorFactory::getBl2 () const
{
return _blearner2;
}
arma::mat BaselearnerTensorFactory::calculateLinearPredictor (const arma::mat& param) const
{
if (_sh_ptr_data->usesSparseMatrix()) {
return (param.t() * _sh_ptr_data->getSparseData()).t();
} else {
return _sh_ptr_data->getDenseData() * param;
}
}
arma::mat BaselearnerTensorFactory::calculateLinearPredictor (const arma::mat& param, const mdata& data_map) const
{
try {
auto newdata = instantiateData(data_map);
if (newdata->usesSparseMatrix()) {
return (param.t() * newdata->getSparseData()).t();
} else {
return newdata->getDenseData() * param;
}
} catch (const char* msg) {
throw msg;
}
}
std::vector<std::string> BaselearnerTensorFactory::getDataIdentifier () const
{
std::vector<std::string> bld1 = _blearner1->getDataIdentifier();
std::vector<std::string> bld2 = _blearner2->getDataIdentifier();
for (unsigned int i = 0; i < bld2.size(); i++) {
bld1.push_back(bld2[i]);
}
return bld1;
}
std::vector<sdata> BaselearnerTensorFactory::getVecDataSource () const
{
auto dvec1 = _blearner1->getVecDataSource();
auto dvec2 = _blearner2->getVecDataSource();
for (auto& it : dvec2) {
dvec1.push_back(it);
}
return dvec1;
}
std::map<std::string, std::vector<std::string>> BaselearnerTensorFactory::getValueNames () const
{
std::map<std::string, std::vector<std::string>> mout, m1, m2;
m1 = _blearner1->getValueNames();
m2 = _blearner2->getValueNames();
for(auto const& ditem : m2)
m1[ditem.first] = ditem.second;
return m1;
}
std::shared_ptr<blearner::Baselearner> BaselearnerTensorFactory::createBaselearner ()
{
return std::make_shared<blearner::BaselearnerTensor>(_blearner_type, _sh_ptr_data);
}
std::vector<double> BaselearnerTensorFactory::getMinMax () const
{
return _sh_ptr_data->getMinMax();
}
json BaselearnerTensorFactory::toJson () const
{
json j = BaselearnerFactory::baseToJson("BaselearnerTensorFactory");
j["id_data_init"] = _sh_ptr_data->getDataIdentifier() + "." + _blearner_type;
j["_attributes"] = _attributes->toJson();
j["_blearner1"] = _blearner1->toJson();
j["_blearner2"] = _blearner2->toJson();
j["_isotrop"] = _isotrop;
return j;
}
json BaselearnerTensorFactory::extractDataToJson (const bool save_source, const bool rm_data) const
{
json j;
json jsub1;
json jsub2;
std::string id_dat;
if (save_source) {
// Save source data of all factories:
j = BaselearnerFactory::dataSourceToJson(); // X
jsub1 = _blearner1->extractDataToJson(true, rm_data); // Y
jsub2 = _blearner2->extractDataToJson(true, rm_data); // Z
} else {
// Save init data of the factories, e.g. the design matrix Z = X x Y.
id_dat = _sh_ptr_data->getDataIdentifier() + "." + _blearner_type;
j[id_dat] = _sh_ptr_data->toJson(rm_data); // X
// Also save the init data design matrices X and Z of the underlying factories:
jsub1 = _blearner1->extractDataToJson(false, rm_data); // X
jsub2 = _blearner2->extractDataToJson(false, rm_data); // Z
}
// Unroll to bring X, Y, and Z to the same level:
for (auto& it : jsub1.items()) {
j[it.key()] = it.value();
}
for (auto& it : jsub2.items()) {
j[it.key()] = it.value();
}
return j;
}
// BaselearnerCenterFactory:
// ------------------------------------------------
BaselearnerCenteredFactory::BaselearnerCenteredFactory (const std::string& blearner_type,
std::shared_ptr<blearnerfactory::BaselearnerFactory> blearner1,
std::shared_ptr<blearnerfactory::BaselearnerFactory> blearner2)
: BaselearnerFactory::BaselearnerFactory (blearner_type, std::make_shared<data::InMemoryData>(
blearner1->getDataSource()->getDataIdentifier() + "_" +
blearner2->getDataSource()->getDataIdentifier())),
_blearner1 ( blearner1 ),
_blearner2 ( blearner2 )
{
auto bldat1 = _blearner1->getInstantiatedData();
auto bldat2 = _blearner2->getInstantiatedData();
if (bldat1->usesBinning() != bldat2->usesBinning()) {
std::string msg = "Binning is just possible if applied to both base learners.";
throw msg;
}
arma::mat temp1;
if (bldat1->usesSparseMatrix()) {
temp1 = bldat1->getSparseData().t();
} else {
temp1 = bldat1->getDenseData();
}
arma::mat temp2;
if (bldat2->usesSparseMatrix()) {
temp2 = bldat2->getSparseData().t();
} else {
temp2 = bldat2->getDenseData();
}
// usesBinning has to be a function of the parent data class!
bool uses_binning = bldat1->usesBinning();
if (uses_binning) {
_attributes->rotation = tensors::centerDesignMatrix(temp1, temp2, bldat1->getBinningIndex());
} else {
_attributes->rotation = tensors::centerDesignMatrix(temp1, temp2);
}
_sh_ptr_bindata = init::initCenteredData(bldat1, _attributes);
if (uses_binning) {
_sh_ptr_bindata->setIndexVector(bldat1->getBinningIndex());
}
arma::mat pen = _attributes->rotation.t() * _blearner1->getPenaltyMat() * _attributes->rotation;
auto mcache = bldat1->getCache();
arma::mat temp_xtx;
if (mcache.first == "cholesky") {
temp_xtx = _attributes->rotation.t() * mcache.second;
temp_xtx = temp_xtx * temp_xtx.t();
}
if (mcache.first == "inverse") {
temp_xtx = _attributes->rotation.t() * arma::inv(mcache.second) * _attributes->rotation;
}
if ((mcache.first != "cholesky") && (mcache.first != "inverse")) {
throw "Can just handle cholesky or inverse cache types.";
}
_sh_ptr_bindata->setCache(mcache.first, temp_xtx);
}
BaselearnerCenteredFactory::BaselearnerCenteredFactory (const json& j, const mdata& mdsource, const mdata& mdinit)
: BaselearnerFactory::BaselearnerFactory ( j, mdsource ),
_sh_ptr_bindata ( std::static_pointer_cast<data::BinnedData>(data::extractDataFromMap(j["id_data_init"].get<std::string>(), mdinit)) ),
_blearner1 ( jsonToBaselearnerFactory(j["_blearner1"], mdsource, mdinit) ),
_blearner2 ( jsonToBaselearnerFactory(j["_blearner2"], mdsource, mdinit) ),
_attributes ( std::make_shared<init::CenteredAttributes>(j["_attributes"]) )
{ }
bool BaselearnerCenteredFactory::usesSparse () const
{
return false;
}
sdata BaselearnerCenteredFactory::getInstantiatedData () const
{
return _sh_ptr_bindata;
}
sdata BaselearnerCenteredFactory::instantiateData (const mdata& data_map) const
{
sdata newdata = _blearner1->instantiateData(data_map);
return init::initCenteredData(newdata, _attributes);
}
arma::mat BaselearnerCenteredFactory::getData () const
{
return _sh_ptr_bindata->getDenseData();
}
arma::vec BaselearnerCenteredFactory::getDF () const
{
double df1 = arma::as_scalar(_blearner1->getDF());
double df2 = arma::as_scalar(_blearner2->getDF());
return arma::vec(1, arma::fill::value(df1 - df2));
}
arma::vec BaselearnerCenteredFactory::getPenalty () const
{
return arma::vec(1, arma::fill::value(arma::as_scalar(_blearner1->getPenalty())));
}
arma::mat BaselearnerCenteredFactory::getPenaltyMat () const
{
return _attributes->rotation.t() * _blearner1->getPenaltyMat() * _attributes->rotation;
}
std::string BaselearnerCenteredFactory::getBaseModelName() const
{
return std::string("centered");
}
std::string BaselearnerCenteredFactory::getFactoryId () const
{
return _sh_ptr_bindata->getDataIdentifier() + "_" + _blearner_type;
}
arma::mat BaselearnerCenteredFactory::calculateLinearPredictor (const arma::mat& param) const
{
return _sh_ptr_bindata->getDenseData() * param;
}
arma::mat BaselearnerCenteredFactory::calculateLinearPredictor (const arma::mat& param, const mdata& data_map) const
{
try {
auto newdata = instantiateData(data_map);
return newdata->getDenseData() * param;
} catch (const char* msg) {
throw msg;
}
}
std::shared_ptr<blearner::Baselearner> BaselearnerCenteredFactory::createBaselearner ()
{
return std::make_shared<blearner::BaselearnerCentered>(_blearner_type, _sh_ptr_bindata);
}
arma::mat BaselearnerCenteredFactory::getRotation() const
{
return _attributes->rotation;
}
std::vector<std::string> BaselearnerCenteredFactory::getDataIdentifier () const
{
std::vector<std::string> bld1 = _blearner1->getDataIdentifier();
std::vector<std::string> bld2 = _blearner2->getDataIdentifier();
for (unsigned int i = 0; i < bld2.size(); i++) {
bld1.push_back(bld2[i]);
}
return bld1;
}
std::vector<sdata> BaselearnerCenteredFactory::getVecDataSource () const
{
auto dvec1 = _blearner1->getVecDataSource();
auto dvec2 = _blearner2->getVecDataSource();
for (auto& it : dvec2) {
dvec1.push_back(it);
}
return dvec1;
}
std::vector<double> BaselearnerCenteredFactory::getMinMax () const
{
return _sh_ptr_bindata->getMinMax();
}
json BaselearnerCenteredFactory::toJson () const
{
json j = BaselearnerFactory::baseToJson("BaselearnerCenteredFactory");
j["id_data_init"] = _sh_ptr_bindata->getDataIdentifier() + "." + _blearner_type;
j["_attributes"] = _attributes->toJson();
j["_blearner1"] = _blearner1->toJson();
j["_blearner2"] = _blearner2->toJson();
return j;
}
json BaselearnerCenteredFactory::extractDataToJson (const bool save_source, const bool rm_data) const
{
json j;
json jsub1;
json jsub2;
std::string id_dat;
if (save_source) {
// Save source data of all factories:
j = BaselearnerFactory::dataSourceToJson(); // X
jsub1 = _blearner1->extractDataToJson(true, rm_data); // Y
jsub2 = _blearner2->extractDataToJson(true, rm_data); // Z
} else {
// Save init data of the factories, e.g. the design matrix Z = X / Y.
id_dat = _sh_ptr_bindata->getDataIdentifier() + "." + _blearner_type;
j[id_dat] = _sh_ptr_bindata->toJson(rm_data); // X
// Also save the init data design matrices X and Z of the underlying factories:
jsub1 = _blearner1->extractDataToJson(false, rm_data); // X
jsub2 = _blearner2->extractDataToJson(false, rm_data); // Z
}
// Unroll to bring X, Y, and Z to the same level:
for (auto& it : jsub1.items()) {
j[it.key()] = it.value();
}
for (auto& it : jsub2.items()) {
j[it.key()] = it.value();
}
return j;
}
// BaselearnerCategoricalRidgeFactory:
// -------------------------------------------
BaselearnerCategoricalRidgeFactory::BaselearnerCategoricalRidgeFactory (const std::string blearner_type,
std::shared_ptr<data::CategoricalDataRaw>& cdata_source, const double df, const double penalty)
: BaselearnerFactory::BaselearnerFactory ( blearner_type, cdata_source )
{
_attributes->df = df;
_attributes->penalty = penalty;
auto chr_classes = cdata_source->getRawData();
std::string chr_class;
unsigned int int_class;
for (unsigned int i = 0; i < chr_classes.size(); i++) {
chr_class = chr_classes.at(i);
auto it = _attributes->dictionary.find(chr_class);
// Add class into dictionary if not already there:
if (it == _attributes->dictionary.end()) {
int_class = _attributes->dictionary.size();
_attributes->dictionary.insert(std::pair<std::string, unsigned int>(chr_class, int_class));
}
}
_sh_ptr_data = init::initRidgeData(cdata_source, _attributes);
_attributes->penalty_mat = arma::diagmat(arma::vec(_attributes->dictionary.size(), arma::fill::ones));
arma::vec xtx_diag(arma::diagvec((_sh_ptr_data->getSparseData() * _sh_ptr_data->getSparseData().t())));
if (df > 0) {
_attributes->penalty = dro::demmlerReinschRidge(xtx_diag, df);
}
arma::vec temp_XtX_inv = 1 / (xtx_diag + _attributes->penalty);
_sh_ptr_data->setCache("identity", temp_XtX_inv);
}
BaselearnerCategoricalRidgeFactory::BaselearnerCategoricalRidgeFactory (const json& j, const mdata& mdsource, const mdata& mdinit)
: BaselearnerFactory::BaselearnerFactory ( j, mdsource ),
_sh_ptr_data ( data::extractDataFromMap(j["id_data_init"].get<std::string>(), mdinit) ),
_attributes ( std::make_shared<init::RidgeAttributes>(j["_attributes"]) )
{ }
bool BaselearnerCategoricalRidgeFactory::usesSparse () const
{
return true;
}
sdata BaselearnerCategoricalRidgeFactory::getInstantiatedData () const
{
return _sh_ptr_data;
}
sdata BaselearnerCategoricalRidgeFactory::instantiateData (const mdata& data_map) const
{
auto newdata = data::extractDataFromMap(this->_sh_ptr_data, data_map);
auto cnewdata = std::static_pointer_cast<data::CategoricalDataRaw>(newdata);
return init::initRidgeData(cnewdata, _attributes);
}
arma::mat BaselearnerCategoricalRidgeFactory::getData () const
{
return arma::mat(_sh_ptr_data->getSparseData());
}
arma::vec BaselearnerCategoricalRidgeFactory::getDF () const