-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMLP.cpp
1520 lines (1395 loc) · 46.7 KB
/
MLP.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 <Arduino.h>
#include "MLP.h"
#define MIN_float -HUGE_VAL
#define MAX_float +HUGE_VAL
#define SWAP(x, y) { typeof((x)) SWAPVal = (x); (x) = (y); (y) = SWAPVal; }
#define BIAS 1
template <typename T> int sgn(T val) {
return (T(0) < val) - (val < T(0));
}
//
/*
Constructor, arguments are:
number of layers
array of number of neurons
verbose level (0= silent, 1= intermediary, 2= very talkative, 3 = even more)
'skip' enables or disables to add to each layer inputs from layer l-2
*/
// MLP::MLP(int numLayers, int units[], int verbose, bool enableSkip)
MLP::MLP(int numLayers, int *units, int verbose, bool enableSkip)
{
_numLayers = numLayers;
_enableSkip = enableSkip; // For ResNet (https://en.wikipedia.org/wiki/Residual_neural_network)
for (int l = 0; l < _numLayers; l++) _units[l] = units[l];
_verbose = verbose;
generateNetwork();
for (int l = 0; l < _numLayers; l++) {
Layer[l]->Number = l;
Layer[l]->Units = _units[l];
Layer[l]->Output[0] = BIAS;
}
}
MLP::~MLP()
{
for (int l = 0; l < _numLayers; l++) {
if (l != 0) {
for (int i = 1; i <= _units[l]; i++) {
delete [] Layer[l]->Weight[i];
delete [] Layer[l]->WeightSave[i];
delete [] Layer[l]->dWeight[i];
delete [] Layer[l]->dWeightOld[i];
}
}
delete [] Layer[l]->Output;
delete [] Layer[l]->Error;
delete [] Layer[l]->Weight;
delete [] Layer[l]->WeightSave;
delete [] Layer[l]->dWeight;
delete [] Layer[l]->dWeightOld;
delete [] Layer[l];
}
delete [] Layer;
}
// EStimate the size of the network (number of bytes)
uint32_t MLP::estimateNetSize ()
{
uint32_t sum = 0;
for (uint8_t l = 1; l < _numLayers; l++) {
sum += Layer[l]->Units * (Layer[l - 1]->Units + 1) * 4;
sum += Layer[l]->Units * 2;
}
sum *= sizeof(float);
sum += 3 * sizeof(int);
return sum;
}
// Loads a network from SPIFFS file system
bool MLP::netLoad(const char* const path)
{
File file = SPIFFS.open(path);
if (!file || file.isDirectory()) {
Serial.printf("%s - failed to open file for reading\n", path);
return 0;
}
// Load header.
if (_verbose > 0) Serial.print("Loading network ");
_numLayers = readIntFile (file);
if (_verbose > 1) Serial.printf("-> %d layers \n", _numLayers);
for (int l = 0; l < _numLayers; l++) {
_units[l] = readIntFile (file);
_activations[l] = readIntFile (file);
if (_verbose > 1)
if (l != 0) Serial.printf("layer %d -> %d neurons, %s\n",
l, _units[l], ActivNames[_activations[l]]);
else Serial.printf("layer %d -> %d neurons\n", l, _units[l]);
}
// Read parameters
Alpha = readFloatFile (file);
AlphaSave = Alpha;
if (_verbose > 1) Serial.printf("Alpha = %f\n", Alpha, 6);
Eta = readFloatFile (file);
EtaSave = Eta;
if (_verbose > 1) Serial.printf("Eta = %f\n", Eta, 6);
Gain = readFloatFile (file);
GainSave = Gain;
if (_verbose > 1) Serial.printf("Gain = %f\n", Gain, 6);
// Load weights
if (_verbose > 1) Serial.print ("Reading weights : ");
int iW = 0;
for (int l = 1; l < _numLayers; l++) {
Layer[l]->Number = l;
for (int i = 1; i <= Layer[l]->Units; i++) {
for (int j = 0; j <= Layer[l - 1]->Units; j++) {
float x = readFloatFile (file);
Layer[l]->Weight[i][j] = x;
if (_verbose > 2) Serial.printf("\nLayer %d weigth %d, %d = %f",l,i,j, Layer[l]->Weight[i][j]);
++iW;
}
}
}
if (_verbose > 2) Serial.println();
if (_verbose > 1) Serial.printf("found %d weights\n", iW);
file.close();
Serial.println();
return 1;
}
// Saves a network to SPIFFS file system
void MLP::netSave(const char* const path)
{
File file = SPIFFS.open(path, FILE_WRITE);
if (!file) {
Serial.printf("%s - failed to open file for writing\n", path);
return;
}
// Save number of layers
if (_verbose > 0) Serial.printf("Saving network in file %s\n", path);
file.printf("%d\n", _numLayers);
if (_verbose > 1) Serial.printf ("%d layers\n", _numLayers);
for (int l = 0; l < _numLayers; l++) {
file.printf("%d\n", Layer[l]->Units);
file.printf("%d\n", Layer[l]->Activation);
if (_verbose > 1) {
if (l > 0) Serial.printf("Layer %d -> %d neurons, %s\n", l,
Layer[l]->Units, ActivNames[Layer[l]->Activation]);
else Serial.printf("Layer %d -> %d neurons\n", l, Layer[l]->Units);
}
}
// Save parameters
file.printf("%f\n%f\n%f\n", AlphaSave, EtaSave, GainSave);
if (_verbose > 1) Serial.printf("Alpha = %f\n", AlphaSave);
if (_verbose > 1) Serial.printf("Eta = %f\n" , EtaSave);
if (_verbose > 1) Serial.printf("Gain = %f\n" , GainSave);
// Save layers
int iW = 0;
for (int l = 1; l < _numLayers; l++) {
for (int i = 1; i <= Layer[l]->Units; i++) {
for (int j = 0; j <= Layer[l - 1]->Units; j++) {
file.printf("%.6f\n", Layer[l]->Weight[i][j]);
// Serial.printf("weight %d %d %d = %.6f\n", l,i,j,Layer[l]->Weight[i][j]);
++iW;
}
}
}
if (_verbose > 1) Serial.printf ("Saved %d weights\n", iW);
file.close();
}
// Read a dataset from a csv file on SPIFFS
int MLP::readCsvFromSpiffs (const char* const path, DATASET * dataset,
int nData, float coeff = 1.0f)
{
File file = SPIFFS.open(path);
if (!file || file.isDirectory()) {
Serial.printf("%s - failed to open file for reading\n", path);
return 0;
}
char buffer[500];
char * pch;
// If nData is provided
if (nData != 0) {
_nData = nData;
for (int i = 0; i < nData; i++) {
if (_verbose == 3) Serial.printf("line %d\n", i);
// Read a line of the csv file
int k = 0;
if (!file.available()) return -1; // Error: unexpected end of file
char c = file.read();
while (c != 10) { // CR
buffer[k++] = c;
c = file.read();
}
buffer[k] = NULL;
if (_verbose == 3) Serial.printf("%s\n", buffer);
pch = strtok (buffer, ",;");
for (int j = 0; j <= _units[0]; j++) { // Read each value in the line
float x = atof(pch);
if (_verbose == 3) Serial.printf("%f ", x);
if (j < _units[0]) dataset->data[i].In[j] = x / coeff;
else dataset->data[i].Out = x;
pch = strtok (NULL, ",;");
}
if (_verbose == 3) Serial.println();
}
} else { // Else scan the file
// First line : number of cols = 1 + number of input neurons
_nData = 1;
int i = 0;
while (file.available()) { // Read first line
char c = file.read();
buffer[i++] = c;
if (c == 10) break; // CR
}
buffer[i] = NULL;
if (_verbose == 3) Serial.println(buffer);
int nCols = 0;
pch = strtok (buffer, ",;");
while (pch != NULL) { // Count columns
float x = atof(pch);
if (i < _units[0]) dataset->data[0].In[nCols] = x / coeff;
else dataset->data[0].Out = x;
++nCols;
pch = strtok (NULL, ",;");
}
if (nCols != _units[0]+1) {
Serial.printf("Problem reading file line %d\n",nData);
Serial.printf("Read %d columns, and %d input neurons require %d columns\n",
nCols, _units[0], _units[0]+1 );
while(1);
}
_units[0] = nCols - 1;
// Next lines
while (file.available()) {
i = 0;
char c = file.read();
while (c != 10) { // CR
buffer[i++] = c;
c = file.read();
}
buffer[i] = NULL;
pch = strtok (buffer, ",;");
for (int i = 0; i < nCols; i++) {
float x = atof(pch);
if (i < nCols - 1) dataset->data[_nData].In[i] = x / coeff;
else dataset->data[_nData].Out = x;
pch = strtok (NULL, ",;");
}
++_nData;
}
}
// dataset->nData = _nData;
// dataset->nInput = _units[0];
processDataset (dataset);
if (_verbose > 0) Serial.printf("Read %d data of %d input\n", _nData, _units[0]);
return _nData;
}
// Allocate the memory for the user's dataset
int MLP::createDataset (DATASET* dataset, int nData)
{
float *pos = NULL; // position within a float array
_nData = nData;
// creating data vector
// dataset->data = (Data *)calloc(sizeof(Data), nData);
dataset->data = new Data [nData];
if (dataset->data == NULL) return -1;
dataset->nInput = _units[0];
dataset->nData = nData;
// creating input vector
// float *pData = (float *)calloc(sizeof(float), _units[0] * nData);
float *pData = new float [_units[0] * nData];
if (pData == NULL) return -2;
// Positioning each input on its sub-array
pos = pData;
for (int i = 0; i < nData; i++) {
dataset->data[i].In = pos;
pos += _units[0];
}
return 0;
}
void MLP::destroyDataset(DATASET* dataset)
{
// free(dataset->data[0].In);
// free(dataset->data);
delete [] dataset->data[0].In;
delete [] dataset->data;
}
// Display the parameters of the network
void MLP::displayNetwork()
{
Serial.println("---------------------------");
Serial.printf ("Network has %d layers:\n", _numLayers);
int numWeights = 0;
for (int l = 0; l < _numLayers; l++) {
Serial.printf("Layer number %d: %d neurons", l, Layer[l]->Units);
if (l == 0) Serial.println();
else {
Serial.printf(", activation %s, ", ActivNames[Layer[l]->Activation]);
int numW = Layer[l]->Units * (1 + Layer[l - 1]->Units);
numWeights += numW;
Serial.printf("%d weights\n", numW);
if (_verbose > 2 && l != 0) {
for (int i = 1; i <= Layer[l]->Units; i++)
for (int j = 0; j <= Layer[l - 1]->Units; j++)
Serial.printf("\t%d - %d: %f\n",i,j,Layer[l]->Weight[i][j]);
}
}
}
Serial.printf ("Total number of weights: %d\n", numWeights);
Serial.printf ("Average weight L1 norm: %.5f (lambda = %.3e)\n", regulL1Weights()/numWeights, _lambdaRegulL1);
Serial.printf ("Average weight L2 norm: %.5f (lambda = %.3e)\n", regulL2Weights()/numWeights, _lambdaRegulL2);
if (_enableSkip) Serial.println ("ResNet-like enabled");
Serial.printf ("Learning rate is: %.3f\n", Eta);
Serial.printf ("Gain is: %.3f\n", Gain);
Serial.printf ("Momentum is: %.3f\n", Alpha);
Serial.println("---------------------------");
}
// defines dataset parameters
void MLP::begin(float ratio)
{
_ratio = ratio; // ratio of training data vs. testing
_nTrain = _ratio * _nData; // size of training dataset
_nTest = _nData - _nTrain; // size of testing dataset
_batchSize = _nTrain / 20;
_outDelta = 0.0f;
_outMinVal = +HUGE_VAL;
_datasetProcessed = false;
_eval = false;
}
// initialize learning and optimizing parameters
void MLP::initLearn(float alpha, float eta, float gain, float anneal)
{
/*
alpha : momentum
eta : learning rate (LR)
gain : sigmoid gain
anneal : rate of variation of LR
*/
Alpha = alpha;
AlphaSave = alpha;
Eta = eta;
EtaSave = eta;
Gain = gain;
GainSave = gain;
_anneal = anneal;
}
// initialize test parameters
void MLP::setMaxError(float maxErr) {
_maxErr = maxErr;
}
void MLP::setVerbose (int verbose) {
/*
verbose levels:
0: silent
1: show progression
2: details of all training steps
3: 2 + content of dataset csv file
*/
_verbose = verbose;
}
void MLP::setParallel (bool parallel) {
_parallelRun = parallel;
}
void MLP::setIterations (int iters) {
_iters = iters;
}
void MLP::setEpochs (int epochs) {
_epochs = epochs;
}
void MLP::setBatchSize (int batchSize) {
_batchSize = batchSize;
}
void MLP::setAlpha (float alpha) {
Alpha = alpha;
AlphaSave = alpha;
}
void MLP::setEta (float eta) {
Eta = eta;
EtaSave = eta;
}
void MLP::setGain (float gain) {
Gain = gain;
GainSave = gain;
}
void MLP::setAnneal (float anneal) {
_anneal = anneal;
}
void MLP::setActivation (int* activations) {
_activations[0] = 99;
for (int l = 0; l < _numLayers - 1; l++) {
_activations[l + 1] = activations[l];
Layer[l + 1]->Activation = _activations[l + 1];
}
}
void MLP::setHeuristics (long heuristics) {
_heuristics = heuristics;
if (_heuristics != 0) {
_initialize = _heuristics & H_INIT_OPTIM; // 0x000001
_changeWeights = _heuristics & H_CHAN_WEIGH; // 0x000002
_mutateWeights = _heuristics & H_MUTA_WEIGH; // 0x000004
_changeBatch = _heuristics & H_CHAN_BATCH; // 0x000008
_changeEta = _heuristics & H_CHAN_LRATE; // 0x000010
_changeGain = _heuristics & H_CHAN_SGAIN; // 0x000020
_changeAlpha = _heuristics & H_CHAN_ALPHA; // 0x000040
_shuffleDataset = _heuristics & H_SHUF_DATAS; // 0x000080
_zeroWeights = _heuristics & H_ZERO_WEIGH; // 0x000100
_stopTotalError = _heuristics & H_STOP_TOTER; // 0x000200
_selectWeights = _heuristics & H_SELE_WEIGH; // 0x000400
_forceSGD = _heuristics & H_FORC_S_G_D; // 0x000800
_regulL1 = _heuristics & H_REG1_WEIGH; // 0x001000
_regulL2 = _heuristics & H_REG2_WEIGH; // 0x002000
}
}
void MLP::displayHeuristics () {
Serial.println("---------------------------");
Serial.println("Heuristics parameters:");
if(_initialize) Serial.println ("- Init with random weights");
if(_changeWeights) Serial.println ("- Random weights if needed");
if(_selectWeights) Serial.println ("- Select best weights at init");
if(_mutateWeights) Serial.println ("- Slighlty change weights if needed");
if(_changeBatch) Serial.println ("- Variable batch size");
if(_changeEta) Serial.println ("- Variable learning rate");
if(_changeGain) Serial.println ("- Variable Sigmoid gain");
if(_changeAlpha) Serial.println ("- Variable momentum");
if(_shuffleDataset) Serial.println ("- Shuffle dataset if needed");
if(_zeroWeights) Serial.printf ("- Force weights less than %f to zero\n", _zeroThreshold);
if(_stopTotalError) Serial.println ("- Stop optimization if train + test error under threshold");
if(_forceSGD) Serial.println ("- Force stochastic gradient descent");
if(_regulL1) Serial.println ("- Use L1 weight regularization");
if(_regulL2) Serial.println ("- Use L2 weight regularization");
if(_parallelRun) Serial.println ("- Compute using both processors");
Serial.println("---------------------------");
}
void MLP::setHeurInitialize (bool val) { _initialize = val; }
void MLP::setHeurChangeWeights (bool val, float range = 1.0f, float proba = 0.0f) {
_changeWeights = val;
_range = range;
_probaZeroWeight = proba;
}
void MLP::setHeurMutateWeights (bool val, float proba = 0.05f, float percent = 0.15f) {
_mutateWeights = val;
_proba = proba;
_percent = percent;
}
void MLP::setHeurChangeBatch (bool val) { _changeBatch = val; }
void MLP::setHeurChangeEta (bool val, float minEta = 0.35f, float maxEta = 1.1f) {
_changeEta = val;
_minEta = minEta;
_maxEta = maxEta;
}
void MLP::setHeurChangeAlpha (bool val, float minAlpha = 0.5f, float maxAlpha= 1.5f) {
_changeAlpha = val;
_minAlpha = minAlpha;
_maxAlpha = maxAlpha;
}
void MLP::setHeurChangeGain (bool val, float minGain = 0.5f, float maxGain = 2.0f) {
_changeGain = val;
_minGain = minGain;
_maxGain = maxGain;
}
void MLP::setHeurShuffleDataset (bool val) { _shuffleDataset = val; }
void MLP::setHeurZeroWeights (bool val, float zeroThreshold) {
_zeroWeights = val;
_zeroThreshold = zeroThreshold;
}
void MLP::setHeurRegulL1 (bool val, float lambda = 1.0f) {
_regulL1 = val;
_lambdaRegulL1 = lambda / 1000000.0f;
}
void MLP::setHeurRegulL2 (bool val, float lambda = 1.0f) {
_regulL2 = val;
_lambdaRegulL2 = lambda / 1000000.0f;
}
void MLP::setHeurTotalError (bool val) { _stopTotalError = val; }
void MLP::setHeurSelectWeights (bool val) { _selectWeights = val; }
int MLP::getIterations () {
return _iters;
}
int MLP::getEpochs () {
return _epochs;
}
int MLP::getBatchSize () {
return _batchSize;
}
float MLP::getAlpha () {
return Alpha;
}
float MLP::getEta () {
return Eta;
}
float MLP::getGain () {
return Gain;
}
float MLP::getAnneal () {
return _anneal;
}
int MLP::getNeuronNumbers (int layer) {
if (layer >= _numLayers) return 0;
return _units[layer];
}
float MLP::getWeight (int layer, int lower, int upper) {
if (layer >= _numLayers) return 0;
return Layer[layer]->Weight[upper][lower];
}
int MLP::setWeight (int layer, int upper, int lower, float val) {
if (layer >= _numLayers) return 0;
if (upper > Layer[layer]->Units) return 0;
if (lower > Layer[layer - 1]->Units) return 0;
Layer[layer]->Weight[upper][lower] = val;
return 1;
}
// Allocates the necessary memory for the network
void MLP::generateNetwork()
{
// Layer = (LAYER**) calloc(_numLayers, sizeof(LAYER*));
Layer = new LAYER*[_numLayers];
memset(Layer,0,_numLayers*sizeof(LAYER*));
for (int l = 0; l < _numLayers; l++) {
// Layer[l] = (LAYER*) malloc(sizeof(LAYER));
Layer[l] = new LAYER;
Layer[l]->Output = new float[_units[l] + 1];
Layer[l]->Error = new float[_units[l] + 1];
Layer[l]->Weight = new float*[_units[l] + 1];
Layer[l]->WeightSave = new float*[_units[l] + 1];
Layer[l]->dWeight = new float*[_units[l] + 1];
Layer[l]->dWeightOld = new float*[_units[l] + 1];
// Layer[l]->Output[0] = BIAS;
if (l != 0) {
if (!_enableSkip) { // No ResNet
int dim = _units[l - 1] + 1;
for (int i = 1; i <= _units[l]; i++) {
Layer[l]->Weight[i] = new float[dim];
Layer[l]->WeightSave[i] = new float[dim];
Layer[l]->dWeight[i] = new float[dim];
Layer[l]->dWeightOld[i] = new float[dim];
}
} else { // ResNet
int dim;
if (l == 1) dim = _units[l - 1] + 1;
else dim = _units[l - 2] + _units[l - 1] + 1;
for (int i = 1; i <= _units[l]; i++) {
Layer[l]->Weight[i] = new float[dim];
Layer[l]->WeightSave[i] = new float[dim];
Layer[l]->dWeight[i] = new float[dim];
Layer[l]->dWeightOld[i] = new float[dim];
}
}
}
}
InputLayer = Layer[0];
OutputLayer = Layer[_numLayers - 1];
}
void MLP::changeEta () {
static bool Eup = false;
float eta = Eta;
if (eta <= _minEta || eta >= _maxEta) Eup = !Eup;
if (Eup) Eta = eta / _anneal;
else Eta = eta * _anneal;
}
void MLP::changeGain () {
static bool Gup = true;
float gain = Gain;
if (gain <= _minGain || gain >= _maxGain) Gup = !Gup;
if (Gup) Gain = gain + 0.15;
else Gain = gain - 0.15;
}
void MLP::changeAlpha () {
static bool Aup = true;
float alpha = Alpha;
if (alpha <= _minAlpha || alpha >= _maxAlpha) Aup = !Aup;
if (Aup) Alpha = alpha + 0.15;
else Alpha = alpha - 0.15;
}
void MLP::changeBatchSize () {
_batchSize /= 1.5;
if (_batchSize > _nTrain / 4) _batchSize = _nTrain / 4;
if (_batchSize < 1) _batchSize = 1;
}
// select the best set of weights over 10 random ones
void MLP::selectWeights(DATASET* dataset) {
float minError = HUGE_VAL;
// if (_verbose > 1)
Serial.println(" - Selecting best weights");
for (uint8_t i = 0; i < 10; i++) {
randomWeights (1.0f);
float criterion = getTrainSetError (dataset);
if (_stopTotalError) criterion += getTestSetError (dataset);
if (criterion < minError) {
minError = criterion;
saveWeights();
}
}
restoreWeights();
}
// Simple function to optimize the training of the network
float MLP::optimize(DATASET* dataset, int iters, int epochs, int batchSize)
{
_iters = iters;
_epochs = epochs;
_batchSize = batchSize;
bool Stop = false;
uint16_t lastSave, lastIter = 0;
int iter, epoch;
_minError = MAX_float;
if (!_datasetProcessed) processDataset(dataset);
if (_initialize) {
if (_verbose > 0) Serial.println("Creating a new network");
(_selectWeights) ? selectWeights(dataset) : randomWeights(0.5f);
}
shuffleDataset (dataset, 0, _nData);
// Estimate maximum training duration
if (_verbose > 0) {
uint32_t dur = estimateDuration (dataset);
Serial.printf("Estimated duration for training and optimization: %u ms (%d min %d sec)\n", dur,
dur / 60000, (dur % 60000) / 1000);
}
// Print memory information
if (_verbose >1) {
Serial.printf("Free Heap: %d bytes\n",ESP.getFreeHeap());
Serial.printf("Estimated network size: %d bytes\n",estimateNetSize ());
uint16_t dataSize = _nData * (_units[0] + 1) * sizeof(float);
Serial.printf("Estimated dataset size: %d bytes\n", dataSize);
}
for (iter = 0; iter < _iters; iter++) {
/*
Each iteration :
- restore best weigths so far
- according to heuristics parameters:
- shuffle the complete dataset
- change batchsize
- mutate weights or create new random weights
- run epochs
- if too many epochs passed with no better solution:
change eta & gain, shuffle training set
- if a better solution is found: save the weights
- if the error is lower than the min: exit
Returns the final value of the error on the testing set
*/
if (_verbose > 0) Serial.printf("\nIteration number %d", iter + 1);
if (iter != 0) restoreWeights();
if (iter - lastIter > 1) {
lastIter = iter;
if (_mutateWeights) {
weightMutation (0.15f, 0.20f);
if (_verbose > 0) Serial.print(" -> Weight mutation");
}
if (_changeWeights) {
(_selectWeights) ? selectWeights(dataset) : randomWeights(1.0f);
if (_verbose > 0) Serial.print(" -> New random weights");
}
if (_changeBatch) {
changeBatchSize ();
if (_verbose > 0) Serial.printf(", changing batch size to %d", _batchSize);
}
}
if (_shuffleDataset) {
shuffleDataset (dataset, 0, _nData); // Shuffle complete dataset
if (_verbose > 1) Serial.print(", shuffling all dataset");
}
lastSave = 0;
for (epoch = 0; epoch < _epochs; epoch++) {
if (_verbose > 1) Serial.printf("\nEpoch %4d ", epoch);
// if (_forceSGD) {
trainNetSGD(dataset);
testNet(dataset, true);
// } else {
// trainAndTest (dataset);
// }
float epsilon = 0.003f;
// New best set of weights: save the weights
if (_criterion < _minError - epsilon) {
if (_verbose > 1) Serial.print(" - Saving network ...");
lastIter = iter;
_minError = _criterion;
saveWeights();
lastSave = epoch;
}
// Stop if the objective is reached
if (_criterion <= _maxErr) {
if (_verbose > 1) Serial.println(" - Stopping Training and restoring Weights ...");
Stop = true;
break;
}
// Heuristics: change the learning rate, the gain and shuffle training set
if (epoch - lastSave >= _epochs / 10) {
if (_changeEta) changeEta ();
if (_changeGain) changeGain ();
if (_changeAlpha) changeAlpha ();
if (_shuffleDataset) {
shuffleDataset (dataset, 0, _nTrain); // Shuffle training set
if (_verbose > 1) Serial.print(" - Shuffling training set ...");
}
if (_verbose > 1 && (_changeGain || _changeEta))
Serial.printf("\nChanging learning rate to %.3f, gain to %.2f, alpha to %.2f", Eta, Gain, Alpha);
lastSave = epoch;
}
}
if (Stop) {
++iter;
break;
}
}
restoreWeights();
int nepochs = (iter - 1) * _epochs;
if (nepochs < 0) nepochs = 0;
_totalEpochs = nepochs + epoch;
if (_verbose > 0) Serial.printf("\nFinished in %d iterations (%d epochs)\n",
iter, _totalEpochs);
return _testError;
}
// Train on a batch with no SGD
void MLP::trainAndTest (DATASET* dataset)
{
float *Output;
Output = new float [_units[_numLayers - 1]];
if (!_datasetProcessed) processDataset(dataset);
_eval = false;
_trainError = 0;
int sample;
for (int i = 0; i < _nTrain / _batchSize; i++) {
sample = i * _batchSize;
process(&dataset->data[sample].In[0], Output,
&dataset->data[sample].Out, _batchSize);
_trainError += Error;
}
sample += _batchSize;
if (_nTrain % _batchSize) {
process(&dataset->data[sample].In[0], Output,
&dataset->data[sample].Out, _nTrain % _batchSize);
_trainError += Error;
}
_testError = getTestSetError (dataset);
_criterion = _testError;
if (_stopTotalError) _criterion += _trainError;
if (_verbose > 0) {
if (_criterion < _minError && _verbose == 1) Serial.println();
if (_criterion < _minError || _verbose > 1) {
Serial.printf("NMSE is %6.3f on Training Set and %6.3f on Test Set",
_trainError * _batchSize, _testError);
}
}
// Prevent from going too far from the current best solution
if (_trainError * _batchSize + _testError >
4 * (TrainErrorSave * _batchSize + TestErrorSave)) restoreWeights();
delete [] Output;
}
// Train on a random batch of data
void MLP::trainNetSGD(DATASET* dataset)
{
// float *Output;
float *Output = new float [_units[_numLayers - 1]];
if (!_datasetProcessed) processDataset(dataset);
int sample = randomInt(0, _nTrain - _batchSize);
_eval = false;
process(&dataset->data[sample].In[0], Output,
&dataset->data[sample].Out, _batchSize);
delete [] Output;
}
float MLP::getTrainSetError (DATASET* dataset) {
float *Output;
Output = new float [_units[_numLayers - 1]];
float trainError = 0;
_eval = true;
for (int sample = 0; sample < _nTrain; sample++) {
process(&dataset->data[sample].In[0], Output,
&dataset->data[sample].Out, 1);
trainError += Error;
}
_eval = false;
delete [] Output;
return trainError;
}
float MLP::getTestSetError (DATASET* dataset) {
float *Output;
Output = new float [_units[_numLayers - 1]];
float testError = 0;
_eval = true;
for (int sample = _nTrain; sample < _nData; sample++) {
process(&dataset->data[sample].In[0], Output,
&dataset->data[sample].Out, 1);
testError += Error;
}
_eval = false;
delete [] Output;
return testError;
}
// Compute total error on training and testing sets
void MLP::testNet(DATASET* dataset, bool disp)
{
_testError = getTestSetError (dataset);
_criterion = _testError;
if (_stopTotalError) {
_trainError = getTrainSetError (dataset);
_criterion += _trainError;
}
if (disp && _verbose > 0) {
if (_criterion < _minError && _verbose == 1) Serial.println();
if (_criterion < _minError || _verbose > 1) {
if (!_stopTotalError) _trainError = getTrainSetError (dataset);
// NMSE : Normalized Mean Square Error (cost function)
Serial.printf("NMSE is %6.3f on Training Set and %6.3f on Test Set",
_trainError, _testError);
}
}
}
// Count the prediction errors on the training set and on the test set
void MLP::evaluateNet(DATASET* dataset, float threshold)
{
// _predict = true;
float *Out;
if (OutputLayer->Activation == SOFTMAX) Out = new float [OutputLayer->Units + 1];
else Out = new float [_units[_numLayers - 1]];
int nError = 0;
// _eval = true;
for (int sample = 0; sample < _nTrain; sample++) {
process(&dataset->data[sample].In[0], Out, &dataset->data[sample].Out, 1);
if (OutputLayer->Activation == SOFTMAX) {
// Softmax case : look for the highest value
int indexMax = 0;
float valMax = 0;
for (int j = 0; j < OutputLayer->Units; j++) {
if (Out[j] > valMax) {
valMax = Out[j];
indexMax = j;
}
}
if (abs(indexMax - dataset->data[sample].Out) > threshold) ++nError;
} else {
float x = Out[0] * _outDelta + _outMinVal;
if (abs(x - dataset->data[sample].Out) > threshold) ++nError;
}
}
if (_verbose > 0) Serial.printf("\nVerifying on %d train data : %2d errors (%.2f%%)\n", _nTrain, nError, 100.0 * nError / _nTrain);
_nTrainError = nError;
nError = 0;
for (int sample = _nTrain; sample < _nData; sample++) {
process(&dataset->data[sample].In[0], Out, &dataset->data[sample].Out, 1);
if (OutputLayer->Activation == SOFTMAX) {
// Softmax case : look for the highest value
int indexMax = 0;
float valMax = 0;
for (int j = 0; j < OutputLayer->Units; j++) {
if (Out[j] > valMax) {
valMax = Out[j];
indexMax = j;
}
}
if (abs(indexMax - dataset->data[sample].Out) > threshold) ++nError;
} else {
float x = Out[0] * _outDelta + _outMinVal;
if (abs(x - dataset->data[sample].Out) > threshold) ++nError;
}
}
if (_verbose > 0) Serial.printf("Verifying on %d test data : %2d errors (%.2f%%)\n", _nTest, nError, 100.0 * nError / _nTest);
_eval = false;
delete [] Out;
_nTestError = nError;
// _predict = false;
}
/* Provide the estimated time of the complete training in ms
The estimation is not very precise as the training time
may depend of other factors such as the verbose level
*/
uint32_t MLP::estimateDuration (DATASET* dataset)
{
saveWeights();
// randomWeights(0.5f);
unsigned long chrono = millis();
trainNetSGD(dataset);
testNet(dataset, false);
chrono = millis() - chrono;
restoreWeights();
return chrono * _iters * _epochs * 1.25f;
}
// Shuffle a portion of the dataset, in the provided range
void MLP::shuffleDataset (DATASET* dataset, int begin, int end)
{
for (int i = begin; i < end; i++) {
int ind = begin + random(end - begin);
for (int j = 0; j < _units[0]; j++)
SWAP(dataset->data[ind].In[j], dataset->data[i].In[j]);
SWAP(dataset->data[ind].Out, dataset->data[i].Out);
}
}
// Forward propagation : parallel task
void MLP::propagateNet()
{
if (_parallelRun) { // parallel
for (int l = 0; l < _numLayers - 1; l++) {
// Softmax case
if (l == _numLayers - 2 && OutputLayer->Activation == SOFTMAX) {
softmax();
} else {
// Create semaphore for tasks synchronization
byte numTasks = 2;
if (Layer[l + 1]->Units == 1) numTasks =1;
SemaphoreHandle_t barrierSemaphore = xSemaphoreCreateCounting( numTasks, 0 );
// Arguments for the tasks
argsStruct params[numTasks];
if (numTasks == 1) {
params[0] = {1, 1, l, this, &barrierSemaphore};
} else {
int med = (Layer[l + 1]->Units) / 2;
params[0] = {1, med, l, this, &barrierSemaphore};
params[1] = {med + 1, Layer[l + 1]->Units, l, this, &barrierSemaphore};
xTaskCreatePinnedToCore(
MLP::forwardTask, /* Function to implement the task */
"Forward1", /* Name of the task */
1000, /* Stack size in words */
(void*)¶ms[1], /* Task input parameter */
20, /* Priority of the task */
NULL, /* Task handle */
1); /* Core where the task runs */
}
xTaskCreatePinnedToCore(
MLP::forwardTask, /* Function to implement the task */
"Forward0", /* Name of the task */
1000, /* Stack size in words */
(void*)¶ms[0], /* Task input parameter */
20, /* Priority of the task */
NULL, /* Task handle */
0); /* Core where the task runs */
// Run tasks and wait until semaphore id released
for (int i = 0; i < numTasks; i++) {
xSemaphoreTake(barrierSemaphore, portMAX_DELAY);
}
vSemaphoreDelete(barrierSemaphore);
}
}
} else { // not parallel
for (int l = 0; l < _numLayers - 1; l++) {
// Softmax case
if (l == _numLayers - 2 && OutputLayer->Activation == SOFTMAX) {
softmax();
} else {
// Other activation
float Sum;