-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathfeat.cc
executable file
·1625 lines (1354 loc) · 47.4 KB
/
feat.cc
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
/* FEAT
copyright 2017 William La Cava
license: GNU/GPL v3
*/
#include "feat.h"
//shogun initialization
void __attribute__ ((constructor)) ctor()
{
init_shogun_with_defaults();
}
void __attribute__ ((destructor)) dtor()
{
exit_shogun();
FT::Rnd::destroy();
FT::Logger::destroy();
}
using namespace FT;
/// @brief initialize Feat object for fitting.
void Feat::init()
{
if (params.n_jobs!=0)
omp_set_num_threads(params.n_jobs);
r.set_seed(params.random_state);
if (GPU)
initialize_cuda();
// set Feat's Normalizer to only normalize floats by default
this->N = Normalizer(false);
this->archive.set_objectives(params.objectives);
set_is_fitted(false);
// start the clock
timer.Reset();
// signal handler
signal(SIGINT, my_handler);
// reset statistics
this->stats = Log_Stats();
params.use_batch = params.bp.batch_size>0;
}
void Feat::fit(MatrixXf& X, VectorXf& y, LongData& Z)
{
/*!
* Input:
* X: n_features x n_samples MatrixXf of features
* y: VectorXf of labels
* Output:
* updates best_estimator, hof
* steps:
* 1. fit model yhat = f(X)
* 2. generate transformations Phi(X) for each individual
* 3. fit model yhat_new = f( Phi(X)) for each individual
* 4. evaluate features
* 5. selection parents
* 6. produce offspring from parents via variation
* 7. select surviving individuals from parents and offspring
*/
this->init();
std::ofstream log; ///< log file stream
if (!logfile.empty())
log.open(logfile, std::ofstream::app);
params.init(X, y);
string FEAT;
if (params.verbosity == 1)
{
FEAT = (
"/// Feature Engineering Automation Tool "
"* \xc2\xa9 La Cava et al 2017 "
"* GPL3 \\\\\\\n"
);
}
else if (params.verbosity == 2)
{
FEAT = (
"/////////////////////////////////////////////////////////////////////\n"
"// * Feature Engineering Automation Tool * //\n"
"// La Cava et al. 2017 //\n"
"// License: GPL v3 //\n"
"// https://cavalab.org/feat //\n"
"/////////////////////////////////////////////////////////////////////\n"
);
}
if (params.use_batch)
{
if (params.bp.batch_size >= X.cols())
{
logger.log("turning off batch because X has fewer than "
+ to_string(params.bp.batch_size) + " samples", 1);
params.use_batch = false;
}
else
{
logger.log("using batch with batch_size= "
+ to_string(params.bp.batch_size), 2);
}
}
// if(str_dim.compare("") != 0)
// {
// string dimension;
// dimension = str_dim.substr(0, str_dim.length() - 1);
// logger.log("STR DIM IS "+ dimension, 2);
// logger.log("Cols are " + std::to_string(X.rows()), 2);
// logger.log("Setting dimensionality as " +
// std::to_string((int)(ceil(stod(dimension)*X.rows()))), 2);
// set_max_dim(ceil(stod(dimension)*X.rows()));
// }
logger.log(FEAT,1);
this->archive.set_objectives(params.objectives);
// normalize data
if (params.normalize)
{
N.fit_normalize(X,params.dtypes);
}
this->pop = Population(params.pop_size);
this->evaluator = Evaluation(params.scorer_);
/* create an archive to save Pareto front,
* unless NSGA-2 is being used for survival
*/
/* if (!survival.compare("nsga2")) */
/* use_arch = false; */
/* else */
/* use_arch = true; */
use_arch = false;
logger.log("scorer: " + params.scorer_, 1);
// split data into training and test sets
//Data data(X, y, Z, params.classification);
DataRef d(X, y, Z, params.classification, params.protected_groups);
//DataRef d;
//d.setOriginalData(&data);
d.train_test_split(params.shuffle, params.split);
// define terminals based on size of X
params.set_terminals(d.o->X.rows(), d.o->Z);
// initial model on raw input
logger.log("Setting up data", 2);
float t0 = timer.Elapsed().count();
//data for batch training
MatrixXf Xb;
VectorXf yb;
LongData Zb;
Data db(Xb, yb, Zb, params.classification, params.protected_groups);
Data *tmp_train;
if(params.use_batch)
{
tmp_train = d.t;
d.t->get_batch(db, params.bp.batch_size);
d.setTrainingData(&db);
}
if (params.classification)
params.set_sample_weights(d.t->y);
// initialize population
////////////////////////
logger.log("Initializing population", 2);
bool random = selector.get_type() == "random";
// initial model
////////////////
logger.log("Fitting initial model", 2);
t0 = timer.Elapsed().count();
initial_model(d);
logger.log("Initial fitting took "
+ std::to_string(timer.Elapsed().count() - t0) + " seconds",2);
// initialize population with initial model and/or starting pop
pop.init(best_ind,params,random, this->starting_pop);
logger.log("Initial population:\n"+pop.print_eqns(),3);
// evaluate initial population
logger.log("Evaluating initial population",2);
evaluator.fitness(pop.individuals,*d.t,params);
evaluator.validation(pop.individuals,*d.v,params);
logger.log("Initial population done",2);
logger.log(std::to_string(timer.Elapsed().count()) + " seconds",2);
vector<size_t> survivors;
if(params.use_batch) // reset d to all training data
d.setTrainingData(tmp_train, true);
// =====================
// main generational loop
unsigned g = 0;
unsigned stall_count = 0;
float fraction = 0;
// continue until max gens is reached or max_time is up (if it is set)
while(
// time limit
(params.max_time == -1 || params.max_time > timer.Elapsed().count())
// generation limit
&& g<params.gens
// stall limit
&& (params.max_stall == 0 || stall_count < params.max_stall)
)
{
fraction = params.max_time == -1 ? ((g+1)*1.0)/params.gens :
timer.Elapsed().count()/params.max_time;
if(params.use_batch)
{
d.t->get_batch(db, params.bp.batch_size);
DataRef dbr; // reference to minibatch data
dbr.setTrainingData(&db);
dbr.setValidationData(d.v);
if (params.classification)
params.set_sample_weights(dbr.t->y);
run_generation(g, survivors, dbr, log, fraction, stall_count);
}
else
{
run_generation(g, survivors, d, log, fraction, stall_count);
}
g++;
}
// =====================
if ( params.max_stall != 0 && stall_count >= params.max_stall)
logger.log("learning stalled",2);
else if ( g >= params.gens)
logger.log("generation limit reached",2);
else
logger.log("max time reached",2);
logger.log("train score: " + std::to_string(this->min_loss), 2);
logger.log("validation score: " + std::to_string(min_loss_v), 2);
logger.log("fitting final model to all training data...",2);
// simplify the final model
if (simplify > 0.0)
{
this->best_ind.fit(*d.o, params);
simplify_model(d, this->best_ind);
}
// fit final model to best features
final_model(d);
// if we're not using an archive, let's store the final population in the
// archive
if (!use_arch)
{
archive.individuals = pop.individuals;
}
if (save_pop > 0)
{
pop.save(this->logfile+".pop.gen" + to_string(params.current_gen)
+ ".json");
this->best_ind.save(this->logfile+".best.json");
}
if (log.is_open())
log.close();
set_is_fitted(true);
logger.log("Run Completed. Total time taken is "
+ std::to_string(timer.Elapsed().count()) + " seconds", 1);
logger.log("best model: " + this->get_eqn(),1);
logger.log("tabular model:\n" + this->get_model(),2);
logger.log("/// ----------------------------------------------------------------- \\\\\\",
1);
}
/// set size of population
void Feat::set_pop_size(int pop_size){ params.pop_size = pop_size; }
/// set size of max generations
void Feat::set_gens(int gens){ params.gens = gens;}
/// set ML algorithm to use
void Feat::set_ml(string ml){ params.ml = ml; }
/// set EProblemType for shogun
void Feat::set_classification(bool classification)
{
params.classification = classification;
}
/// set level of debug info
void Feat::set_verbosity(int verbosity){ params.set_verbosity(verbosity); }
/// set maximum stall in learning, in generations
void Feat::set_max_stall(int max_stall){ params.max_stall = max_stall; }
/// set selection method
void Feat::set_selection(string sel){ this->selector = Selection(sel, false); }
/// set survivability
void Feat::set_survival(string surv)
{
survival=surv;
survivor = Selection(surv, true);
}
/// set cross rate in variation
void Feat::set_cross_rate(float cross_rate)
{
params.cross_rate = cross_rate;
variator.set_cross_rate(cross_rate);
}
/// set root cross rate in variation
void Feat::set_root_xo_rate(float cross_rate)
{
params.root_xo_rate = cross_rate;
}
/// set program output type ('f', 'b')
void Feat::set_otype(char ot){ params.set_otype(ot); }
/// set max depth of programs
void Feat::set_max_depth(unsigned int max_depth)
{
params.set_max_depth(max_depth);
}
/// set maximum dimensionality of programs
void Feat::set_max_dim(unsigned int max_dim){ params.set_max_dim(max_dim); }
///set dimensionality as multiple of the number of columns
// void Feat::set_max_dim(string str){ str_dim = str; }
/// set seeds for each core's random number generator
void Feat::set_random_state(int rs)
{
params.random_state=rs;
r.set_seed(rs);
}
/// flag to set whether to use variable or constants for terminals
void Feat::set_erc(bool erc){ params.erc = erc; }
/// flag to shuffle the input samples for train/test splits
void Feat::set_shuffle(bool sh){params.shuffle = sh;}
/// set train fraction of dataset
void Feat::set_split(float sp){params.split = sp;}
///set data types for input parameters
void Feat::set_dtypes(vector<char> dtypes){params.dtypes = dtypes;}
///set feedback
void Feat::set_fb(float fb){ params.feedback = fb;}
///set name for files
void Feat::set_logfile(string s){logfile = s;}
///set scoring function
void Feat::set_scorer(string s){params.set_scorer(s);}
string Feat::get_scorer_(){return params.scorer_;}
string Feat::get_scorer(){return params.scorer;}
/// set constant optimization options
void Feat::set_backprop(bool bp){params.backprop=bp;}
void Feat::set_simplify(float s){this->simplify=s;}
void Feat::set_corr_delete_mutate(bool s){this->params.corr_delete_mutate=s;}
void Feat::set_hillclimb(bool hc){params.hillclimb=hc;}
void Feat::set_iters(int iters){params.bp.iters = iters; params.hc.iters=iters;}
void Feat::set_lr(float lr){params.bp.learning_rate = lr;}
void Feat::set_batch_size(int bs)
{
params.bp.batch_size = bs;
params.use_batch = bs>0;
}
///set number of threads
void Feat::set_n_jobs(unsigned t){ omp_set_num_threads(t); }
void Feat::set_max_time(int time){ params.max_time = time; }
void Feat::set_use_batch(){ params.use_batch = true; }
void Feat::set_protected_groups(string pg)
{
params.set_protected_groups(pg);
}
/*
* getting functions
*/
///return population size
int Feat::get_pop_size(){ return params.pop_size; }
///return size of max generations
int Feat::get_gens(){ return params.gens; }
///return ML algorithm string
string Feat::get_ml(){ return params.ml; }
///return type of classification flag set
bool Feat::get_classification(){ return params.classification; }
///return maximum stall in learning, in generations
int Feat::get_max_stall() { return params.max_stall; }
///return program output type ('f', 'b')
vector<char> Feat::get_otypes(){ return params.otypes; }
///return current verbosity level set
int Feat::get_verbosity(){ return params.verbosity; }
///return max_depth of programs
int Feat::get_max_depth(){ return params.max_depth; }
///return cross rate for variation
float Feat::get_cross_rate(){ return params.cross_rate; }
///return max size of programs
int Feat::get_max_size(){ return params.max_size; }
///return max dimensionality of programs
int Feat::get_max_dim(){ return params.max_dim; }
///return boolean value of erc flag
bool Feat::get_erc(){ return params.erc; }
/// get name
string Feat::get_logfile(){ return logfile; }
///return number of features
int Feat::get_num_features(){ return params.num_features; }
///return whether option to shuffle the data is set or not
bool Feat::get_shuffle(){ return params.shuffle; }
///return fraction of data to use for training
float Feat::get_split(){ return params.split; }
///add custom node into feat
/* void add_function(unique_ptr<Node> N){ params.functions.push_back(N->clone()); } */
///return data types for input parameters
vector<char> Feat::get_dtypes(){ return params.dtypes; }
///return feedback setting
float Feat::get_fb(){ return params.feedback; }
///return best model
string Feat::get_representation(){ return best_ind.get_eqn();}
string Feat::get_eqn(bool sort){ return this->get_ind_eqn(sort, this->best_ind); };
string Feat::get_ind_eqn(bool sort, Individual& ind)
{
vector<string> features = ind.get_features();
vector<float> weights = ind.ml->get_weights();
float offset = ind.ml->get_bias();
/* if (params.normalize) */
/* { */
/* offset = this->N.adjust_offset(weights, offset); */
/* this->N.adjust_weights(weights); */
/* } */
vector<size_t> order(weights.size());
if (sort)
{
vector<float> aweights(weights.size());
for (int i =0; i<aweights.size(); ++i)
aweights[i] = fabs(weights[i]);
order = argsort(aweights, false);
}
else
iota(order.begin(), order.end(), 0);
string output;
output += to_string(offset);
if (weights.size() > 0)
{
if (weights.at(order.at(0)) > 0)
output += "+";
}
int i = 0;
for (const auto& o : order)
{
output += to_string(weights.at(o), 2);
output += "*";
output += features.at(o);
if (i < order.size()-1)
{
if (weights.at(order.at(i+1)) > 0)
output+= "+";
}
++i;
}
return output;
}
string Feat::get_model(bool sort)
{
vector<string> features = best_ind.get_features();
vector<float> weights = best_ind.ml->get_weights();
float offset = best_ind.ml->get_bias();
/* if (params.normalize) */
/* { */
/* offset = this->N.adjust_offset(weights, offset); */
/* this->N.adjust_weights(weights); */
/* } */
vector<size_t> order(weights.size());
if (sort)
{
vector<float> aweights(weights.size());
for (int i =0; i<aweights.size(); ++i)
aweights[i] = fabs(weights[i]);
order = argsort(aweights, false);
}
else
iota(order.begin(), order.end(), 0);
string output;
output += "Weight\tFeature\n";
output += to_string(offset) + "\toffset" + "\n";
for (const auto& o : order)
{
output += to_string(weights.at(o), 2);
output += "\t";
output += features.at(o);
output += "\n";
}
return output;
}
///get number of parameters in best
int Feat::get_n_params(){ return best_ind.get_n_params(); }
///get dimensionality of best
int Feat::get_dim(){ return best_ind.get_dim(); }
///get dimensionality of best
int Feat::get_complexity(){ return best_ind.get_complexity(); }
/// return the number of nodes in the best model
int Feat::get_n_nodes(){ return best_ind.program.size(); }
///return population as string
vector<json> Feat::get_archive(bool front)
{
/* TODO: maybe this should just return the to_json call of
* the underlying population / archive. I guess the problem
* is that we don't have to_json defined for vector<Individual>.
*/
vector<Individual>* printed_pop = NULL;
string r = "";
vector<size_t> idx;
bool subset = false;
if (front) // only return individuals on the Pareto front
{
if (use_arch)
{
printed_pop = &archive.individuals;
}
else
{
unsigned n = 1;
subset = true;
idx = this->pop.sorted_front(n);
printed_pop = &this->pop.individuals;
}
}
else
printed_pop = &this->pop.individuals;
if (!subset)
{
idx.resize(printed_pop->size());
std::iota(idx.begin(), idx.end(), 0);
}
bool includes_best_ind = false;
vector<json> json_archive;
for (int i = 0; i < idx.size(); ++i)
{
Individual& ind = printed_pop->at(idx[i]);
json j;
to_json(j, ind);
// r += j.dump();
json_archive.push_back(j);
if (i < idx.size() -1)
r += "\n";
// check if best_ind is in here
if (ind.id == best_ind.id)
includes_best_ind = true;
}
// add best_ind, if it is not included
if (!includes_best_ind)
{
json j;
to_json(j, best_ind);
json_archive.push_back(j);
}
// delete pop pointer
printed_pop = NULL;
delete printed_pop;
return json_archive;
}
/// return the coefficients or importance scores of the best model.
ArrayXf Feat::get_coefs()
{
auto tmpw = best_ind.ml->get_weights();
ArrayXf w = ArrayXf::Map(tmpw.data(), tmpw.size());
return w;
}
/// get longitudinal data from file s
std::map<string, std::pair<vector<ArrayXf>, vector<ArrayXf>>> Feat::get_Z(string s,
int * idx, int idx_size)
{
LongData Z;
vector<int> ids(idx,idx+idx_size);
load_partial_longitudinal(s,Z,',',ids);
return Z;
}
void Feat::fit(MatrixXf& X, VectorXf& y)
{
auto Z = LongData();
fit(X,y,Z);
}
void Feat::run_generation(unsigned int g,
vector<size_t> survivors,
DataRef &d,
std::ofstream &log,
float fraction,
unsigned& stall_count)
{
d.t->set_protected_groups();
params.set_current_gen(g);
// select parents
logger.log("selection..", 2);
vector<size_t> parents = selector.select(pop, params, *d.t);
logger.log("parents:\n"+pop.print_eqns(), 3);
// variation to produce offspring
logger.log("variation...", 2);
variator.vary(pop, parents, params,*d.t);
logger.log("offspring:\n" + pop.print_eqns(true), 3);
// evaluate offspring
logger.log("evaluating offspring...", 2);
evaluator.fitness(pop.individuals, *d.t, params, true);
evaluator.validation(pop.individuals, *d.v, params, true);
// select survivors from combined pool of parents and offspring
logger.log("survival...", 2);
survivors = survivor.survive(pop, params, *d.t);
// reduce population to survivors
logger.log("shrinking pop to survivors...",2);
pop.update(survivors);
logger.log("survivors:\n" + pop.print_eqns(), 3);
logger.log("update best...",2);
bool updated_best = update_best(d);
logger.log("calculate stats...",2);
calculate_stats(d);
if (params.max_stall > 0)
update_stall_count(stall_count, updated_best);
if ( (use_arch || params.verbosity>1) || !logfile.empty()) {
// set objectives to make sure they are reported in log/verbose/arch
#pragma omp parallel for
for (unsigned int i=0; i<pop.size(); ++i)
pop.individuals.at(i).set_obj(params.objectives);
}
logger.log("update archive...",2);
if (use_arch)
archive.update(pop,params);
if(params.verbosity>1)
print_stats(log, fraction);
else if(params.verbosity == 1)
printProgress(fraction);
if (!logfile.empty())
log_stats(log);
if (save_pop > 1)
pop.save(this->logfile+".pop.gen" +
to_string(params.current_gen) + ".json");
// tighten learning rate for grad descent as evolution progresses
if (params.backprop)
{
params.bp.learning_rate = \
(1-1/(1+float(params.gens)))*params.bp.learning_rate;
logger.log("learning rate: "
+ std::to_string(params.bp.learning_rate),3);
}
logger.log("finished with generation...",2);
}
void Feat::update_stall_count(unsigned& stall_count, bool best_updated)
{
if (params.current_gen == 0 || best_updated )
{
/* best_med_score = this->med_loss_v; */
stall_count = 0;
}
else
{
++stall_count;
}
logger.log("stall count: " + std::to_string(stall_count), 2);
}
void Feat::final_model(DataRef& d)
{
// fits final model to best tranformation found.
shared_ptr<CLabels> yhat;
if (params.tune_final)
yhat = best_ind.fit_tune(*d.o, params);
else
yhat = best_ind.fit(*d.o, params);
VectorXf tmp;
/* params.set_sample_weights(y); // need to set new sample weights for y, */
// which is probably from a validation set
float score = evaluator.S.score(d.o->y,yhat,tmp,params.class_weights);
logger.log("final_model score: " + std::to_string(score),2);
}
void Feat::simplify_model(DataRef& d, Individual& ind)
{
/* Simplifies the final model using some expert rules and stochastic hill
* climbing.
* Expert rules:
* - NOT(NOT(x)) simplifies to x
* Stochastic hill climbing:
* for some number iterations, apply delete mutation to the equation.
* if the output of the model doesn't change, keep the mutations.
*/
//////////////////////////////
// check for specific patterns
//////////////////////////////
//
Individual tmp_ind = ind;
int starting_size = ind.size();
vector<size_t> roots = tmp_ind.program.roots();
vector<size_t> idx_to_remove;
logger.log("\n=========\ndoing pattern pruning...",2);
logger.log("simplify: " + to_string(this->simplify), 2);
for (auto r : roots)
{
size_t start = tmp_ind.program.subtree(r);
int first_occurence = -2;
/* cout << "start: " << start << "\n"; */
for (int i = start ; i <= r; ++i)
{
/* cout << "i: " << i << ", first_occurence: " << first_occurence */
/* << "\n"; */
if (tmp_ind.program.at(i)->name.compare("not")==0)
{
if (first_occurence == i-1) // indicates two NOTs in a row
{
/* cout << "pushing back " << first_occurence */
/* << " and " << i << " to idx_to_remove\n"; */
idx_to_remove.push_back(first_occurence);
idx_to_remove.push_back(i);
// reset first_occurence so we don't pick up triple nots
first_occurence = -2;
}
else
{
first_occurence = i;
}
}
}
}
// remove indices in reverse order so they don't change
std::reverse(idx_to_remove.begin(), idx_to_remove.end());
for (auto idx: idx_to_remove)
{
/* cout << "removing " << tmp_ind.program.at(idx)->name */
/* << " at " << idx << "\n"; */
tmp_ind.program.erase(tmp_ind.program.begin()+idx);
}
int end_size = tmp_ind.size();
logger.log("pattern pruning reduced best model size by "
+ to_string(starting_size - end_size)
+ " nodes\n=========\n", 2);
if (tmp_ind.size() < ind.size())
{
ind = tmp_ind;
logger.log("new model:" + this->get_ind_eqn(false, ind),2);
}
///////////////////
// prune dimensions
///////////////////
/* set_verbosity(3); */
int iterations = ind.get_dim();
logger.log("\n=========\ndoing correlation deletion mutations...",2);
starting_size = ind.size();
VectorXf original_yhat;
if (params.classification && params.n_classes==2)
original_yhat = ind.predict_proba(*d.o).row(0);
else
original_yhat = ind.yhat;
for (int i = 0; i < iterations; ++i)
{
Individual tmp_ind = ind;
bool perfect_correlation = variator.correlation_delete_mutate(
tmp_ind, ind.Phi, params, *d.o);
if (ind.size() == tmp_ind.size())
{
continue;
}
tmp_ind.fit(*d.o, params);
VectorXf new_yhat;
if (params.classification && params.n_classes==2)
new_yhat = tmp_ind.predict_proba(*d.o).row(0);
else
new_yhat = tmp_ind.yhat;
if (((original_yhat - new_yhat).norm()/original_yhat.norm()
<= this->simplify )
or perfect_correlation)
{
logger.log("\ndelete dimension mutation success: went from "
+ to_string(ind.size()) + " to "
+ to_string(tmp_ind.size()) + " nodes. Output changed by "
+ to_string(100*(original_yhat
-new_yhat).norm()/(original_yhat.norm()))
+ " %", 2);
if (perfect_correlation)
logger.log("perfect correlation",2);
ind = tmp_ind;
}
else
{
logger.log("\ndelete dimension mutation failure. Output changed by "
+ to_string(100*(original_yhat
-new_yhat).norm()/(original_yhat.norm()))
+ " %", 2);
// if this mutation fails, it will continue to fail since it
// is deterministic. so, break in this case.
break;
}
}
end_size = ind.size();
logger.log("correlation pruning reduced best model size by "
+ to_string(starting_size - end_size)
+ " nodes\n=========\n", 2);
if (end_size < starting_size)
logger.log("new model:" + this->get_ind_eqn(false, ind),2);
/////////////////
// prune subtrees
/////////////////
iterations = 1000;
logger.log("\n=========\ndoing subtree deletion mutations...", 2);
starting_size = ind.size();
for (int i = 0; i < iterations; ++i)
{
Individual tmp_ind = ind;
this->variator.delete_mutate(tmp_ind, params);
if (ind.size() == tmp_ind.size())
continue;
tmp_ind.fit(*d.o, params);
VectorXf new_yhat;
if (params.classification && params.n_classes==2)
new_yhat = tmp_ind.predict_proba(*d.o).row(0);
else
new_yhat = tmp_ind.yhat;
if ((original_yhat - new_yhat).norm()/original_yhat.norm()
<= this->simplify )
{
logger.log("\ndelete mutation success: went from "
+ to_string(ind.size()) + " to "
+ to_string(tmp_ind.size()) + " nodes. Output changed by "
+ to_string(100*(original_yhat
-new_yhat).norm()/(original_yhat.norm()))
+ " %", 2);
ind = tmp_ind;
}
else
{
logger.log("\ndelete mutation failure. Output changed by "
+ to_string(100*(original_yhat
-new_yhat).norm()/(original_yhat.norm()))
+ " %", 2);
// if this mutation fails, it will continue to fail since it
// is deterministic. so, break in this case.
break;
}
}
end_size = ind.size();
logger.log("subtree deletion reduced best model size by "
+ to_string( starting_size - end_size )
+ " nodes", 2);
VectorXf new_yhat;
if (params.classification && params.n_classes==2)
new_yhat = ind.predict_proba(*d.o).row(0);
else
new_yhat = ind.yhat;
VectorXf difference = new_yhat - original_yhat;
/* cout << "final % difference: " << difference.norm()/original_yhat.norm() */
/* << endl; */
}
vector<float> Feat::univariate_initial_model(DataRef &d, int n_feats)
{
/*!
* If there are more data variables than the max feature size can allow, we
* can't initialize a model in the population without some sort of feature
* selection. To select features we do the following:
* 1) fit univariate models to all features in X and store the coefficients
* 2) fit univariate models to all features in median(Z) and store the
* coefficients
* 3) set terminal weights according to the univariate scores
* 4) construct a program of dimensionality n_feats using
* the largest magnitude coefficients
*/
vector<float> univariate_weights(d.t->X.rows() + d.t->Z.size(),0.0);
int N = d.t->X.cols();
MatrixXf predictor(1,N);
string ml_type = this->params.classification?
"LR" : "LinearRidgeRegression";
ML ml = ML(ml_type,params.normalize,params.classification,params.n_classes);