-
Notifications
You must be signed in to change notification settings - Fork 0
/
RecursiveNN.h
2024 lines (1674 loc) · 65.5 KB
/
RecursiveNN.h
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
/*
* Recursive Neural Networks: neural networks for data structures
*
* Copyright (C) 2018 Alessandro Vullo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef RECURSIVE_NN_H
#define RECURSIVE_NN_H
#include "require.h"
#include "Options.h"
#include "ActivationFunctions.h"
#include "ErrorMinimizationProcedure.h"
#include "DataSet.h"
#include "Model.h"
#include <ctime>
#include <cfloat>
#include <vector>
#include <fstream>
#include <iostream>
using std::cout;
using std::endl;
// Generate a random number between 0.0 and 1.0
double rnd01() {
return ((double) rand() / (double) RAND_MAX);
}
// Generate a random number between -1.0 and +1.0
double nrnd01() {
return ((rnd01() * 2.0) - 1.0);
}
/*
Declaration and non-inline definition of the class
that represents a RecursiveNN model for structured inputs as DPAGs.
Future changes will include the implementation of the Bridge
Pattern to separate network abstraction from multiple
implementation with different space and time complexity
(e.g. the present and an implementation based on blitz::array class).
Another natural change would be to implement different
error minimization procedures (adding momentum to gradient descent,
conjugate gradient) via the Strategy Pattern.
*/
template<class HA_Function, class OA_Function, class EMP>
class RecursiveNN: public Model {
bool _ss_tr; // implement a super-source transduction
bool _ios_tr; // implement an io-isomorf structural trasduction
Problem _problem; // type of learning problem
// number of orientations (i.e. state transition functions)
// to consider for one particular domain
int _norient;
// Useful indices as reported in (Goller §3.2)
// _r: number of layers of the MLP state transition function(s)
// _s: number of layers of the MLP output function (super-source or io-isomorph)
int _n, _v, _m, _q, _r, _s;
/*
Number of units for each layer in an MLP:
- 0 .. _r-1: state transition function number of units per layer
- _r .. _s-1: output function (super-source | io-isomorph) number of units per layer
NOTE: thresholds not included, must be taken into account
*/
std::vector<int> _lnunits;
/*
Represent connection weights between successive layers
for each neural network (MLP) implementing a state transition
function along an orientation of the data structure
*/
double**** _layers_w;
double**** _prev_layers_w; // weight values in previous learning step
// error signals (delta) for each unit/layer/orientation
// (exclude representation layer, stored in node)
double*** _delta_layers;
// the contribution to the gradient of each connection weight
// between successive layers in each MLP
double**** _layers_gradient_w;
typedef double*** Node::*PTNLA;
typedef double** Node::*PTNDV;
PTNLA ptn_la;
PTNDV ptn_dv;
/*
Super-source transduction
A global output is associated to a given instance
The output function is again a MLP
*/
double*** _g_layers_w;
double*** _prev_g_layers_w;
double** _g_layers_activations;
double** _delta_g_layers;
double*** _g_layers_gradient_w;
/*
IO-Isomorph transduction: an output is associate to each node of a given instance
Represents connection weights in the network implementing the node output function
*/
double*** _h_layers_w;
double*** _prev_h_layers_w;
double** _delta_h_layers; // error signals in h output map layers
double*** _h_layers_gradient_w;
// Template parameters indicate the type of hidden and output units
// activation function.
HA_Function haf;
OA_Function oaf;
/*
Templatized Strategy Pattern.
The Net mantains an object that implements one
of the possibile error minimization procedures.
*/
friend EMP; // EMP object must be able to easily update net weights
EMP _wu_method;
/* Private functions */
// Specialized allocation&deallocation functions
void allocFoldingParts(double****, double****, double****, double***);
void allocSSPart();
void allocIOSPart();
void deallocFoldingParts(double****, double****, double****, double***);
void deallocSSPart();
void deallocIOSPart();
// Reset gradient components every time weights are updated.
void resetFoldingGradient(double****);
void resetSSGradient();
void resetIOSGradient();
// Reset output values in g MLP layers
void resetSSValues();
// Propagation routines for
// each specific part of the Net.
void propagateInputOnFoldingPart(Instance*, int);
void gPropagateInput(Instance*);
void hPropagateInput(Node*);
// Error Back-Propagation Through Structures
// routines for each specific part of the Net.
void backPropOnFoldingPart(Instance*, int);
void gBackPropagateError(Instance*);
void hBackPropagateError(Node*);
double computeSSError(Instance*);
double computeIOSError(Instance*);
public:
/*
Constructor used to train a RNN.
Network weights are initialized to random values.
*/
RecursiveNN();
/* Constructor: read network parameters from file */
RecursiveNN(const char*);
/* Destructor */
~RecursiveNN();
void propagateStructuredInput(Instance*);
void backPropagateError(Instance*);
// Implements weight update rule
void adjustWeights(float = 0.0, float = 0.0, float = 0.0);
// To restore previous parameters settings, so
// we can adjust learning rate, in case we make a bad move
void restorePrevWeights();
// To reset gradient components, made public so training procedure
// can use it to begin another training phase using the same network.
void resetGradientComponents();
/*
* this is better moved at the application level
*/
// Evaluate error and performance of the net over a data set
// float evaluatePerformanceOnDataSet(DataSet*, bool = false);
// Save learned Network parameters to file
void saveParameters(const char*);
// Predict output and compute error for a structure/dataset
void predict(Instance*);
void predict(DataSet*);
double computeError(Instance*);
double computeError(DataSet*);
// Compute the (squared norm) of the weights, necessary in order
// to compute the error when regularization is used (weight decay).
double computeWeightsNorm();
};
/*********************************************************
Non-inline template class member functions definitions
*********************************************************/
/* Private: F folding part allocation routine */
template<class HA_Function, class OA_Function, class EMP>
void RecursiveNN<HA_Function, OA_Function, EMP>::allocFoldingParts(double**** layers_w, double**** prev_layers_w, double**** layers_gradient_w, double*** delta_layers) {
// Assume constructor has initialized required dimension quantities
*layers_w = new double**[_r];
*prev_layers_w = new double**[_r];
*layers_gradient_w = new double**[_r];
if(_r > 1) {
*delta_layers = new double*[_r-1];
(*delta_layers)[0] = new double[_lnunits[0]];
memset((*delta_layers)[0], 0, (_lnunits[0]) * sizeof(double));
}
// Allocate weights and gradient components matrixes
// for f folding part. Connections from input layer
// have special dimensions.
(*layers_w)[0] = new double*[(_n+_v*_m) + 1];
(*prev_layers_w)[0] = new double*[(_n+_v*_m) + 1];
(*layers_gradient_w)[0] = new double*[(_n+_v*_m) + 1];
for(int i=0; i<(_n+_v*_m) + 1; i++) {
(*layers_w)[0][i] = new double[_lnunits[0]];
(*prev_layers_w)[0][i] = new double[_lnunits[0]];
(*layers_gradient_w)[0][i] = new double[_lnunits[0]];
// Reset gradient for corresponding weights
memset((*layers_gradient_w)[0][i], 0, _lnunits[0] * sizeof(double));
// Assign weights a random number between -1.0 and +1.0
for(int j=0; j<_lnunits[0]; j++) {
(*layers_w)[0][i][j] = nrnd01() / static_cast<double>(_lnunits[0]);
(*prev_layers_w)[0][i][j] = (*layers_w)[0][i][j];
}
}
// Allocate f weights&gradient matrixes for f folding part.
for(int k=1; k<_r; k++) {
// Allocate space for weight&delta matrix between layer i-1 and i.
// Automatically include space for threshold unit in layer i-1
(*layers_w)[k] = new double*[_lnunits[k-1] + 1];
(*prev_layers_w)[k] = new double*[_lnunits[k-1] + 1];
(*layers_gradient_w)[k] = new double*[_lnunits[k-1] + 1];
for(int i=0; i<_lnunits[k-1]+1; i++) {
(*layers_w)[k][i] = new double[_lnunits[k]];
(*prev_layers_w)[k][i] = new double[_lnunits[k]];
(*layers_gradient_w)[k][i] = new double[_lnunits[k]];
// Reset f gradient components for corresponding weights
memset((*layers_gradient_w)[k][i], 0, (_lnunits[k])*sizeof(double));
// Assign f weights a random number between -1.0 and +1.0
for(int j=0; j<_lnunits[k]; j++) {
(*layers_w)[k][i][j] = nrnd01() / static_cast<double>(_lnunits[k]);
(*prev_layers_w)[k][i][j] = (*layers_w)[k][i][j];
}
}
if(k < _r-1) {
(*delta_layers)[k] = new double[_lnunits[k]];
memset((*delta_layers)[k], 0, (_lnunits[k]) * sizeof(double));
}
}
}
/* Private: SS tranforming part allocation routine */
template<class HA_Function, class OA_Function, class EMP>
void RecursiveNN<HA_Function, OA_Function, EMP>::allocSSPart() {
// Assume constructor has initialized required dimension quantities
_g_layers_w = new double**[_s];
_prev_g_layers_w = new double**[_s];
_g_layers_gradient_w = new double**[_s];
_g_layers_activations = new double*[_s];
_delta_g_layers = new double*[_s];
// Allocate weights and gradient components matrixes
// for g transforming part. Connections from input layers
// have special dimensions.
_g_layers_w[0] = new double*[_norient*_m + 1];
_prev_g_layers_w[0] = new double*[_norient*_m + 1];
_g_layers_gradient_w[0] = new double*[_norient*_m + 1];
// Allocate and reset g layers output activation units and delta values.
_g_layers_activations[0] = new double[_lnunits[_r]];
memset(_g_layers_activations[0], 0, (_lnunits[_r])*sizeof(double));
_delta_g_layers[0] = new double[_lnunits[_r]];
memset(_delta_g_layers[0], 0, (_lnunits[_r])*sizeof(double));
for(int i=0; i<_norient*_m + 1; i++) {
_g_layers_w[0][i] = new double[_lnunits[_r]];
_prev_g_layers_w[0][i] = new double[_lnunits[_r]];
_g_layers_gradient_w[0][i] = new double[_lnunits[_r]];
// Reset gradient for corresponding weights
memset(_g_layers_gradient_w[0][i], 0, _lnunits[_r] * sizeof(double));
// Assign weights a random number between -1.0 and +1.0
for(int j=0; j<_lnunits[_r]; j++) {
_g_layers_w[0][i][j] = nrnd01() / static_cast<double>(_lnunits[_r]);
_prev_g_layers_w[0][i][j] = _g_layers_w[0][i][j];
}
}
// Allocate weights&gradient matrixes for g transforming part
for(int k=1; k<_s; k++) {
// Allocate space for weight&gradient matrixes between layer i-1 and i.
// Automatically include space for threshold unit in layer i-1
_g_layers_w[k] = new double*[_lnunits[_r+k-1] + 1];
_prev_g_layers_w[k] = new double*[_lnunits[_r+k-1] + 1];
_g_layers_gradient_w[k] = new double*[_lnunits[_r+k-1] + 1];
// Allocate and reset g layers output activation units and delta layers values.
_g_layers_activations[k] = new double[_lnunits[_r+k]];
memset(_g_layers_activations[k], 0, (_lnunits[_r+k])*sizeof(double));
_delta_g_layers[k] = new double[_lnunits[_r+k]];
memset(_delta_g_layers[k], 0, (_lnunits[_r+k])*sizeof(double));
for(int i=0; i<_lnunits[_r+k-1]+1; i++) {
_g_layers_w[k][i] = new double[_lnunits[_r+k]];
_prev_g_layers_w[k][i] = new double[_lnunits[_r+k]];
_g_layers_gradient_w[k][i] = new double[_lnunits[_r+k]];
// Reset g gradient components for corresponding weights
memset(_g_layers_gradient_w[k][i], 0, (_lnunits[_r+k])*sizeof(double));
// Assign g weights a random number between -1.0 and +1.0
for(int j=0; j<_lnunits[_r+k]; j++) {
_g_layers_w[k][i][j] = nrnd01() / static_cast<double>(_lnunits[_r+k]);
_prev_g_layers_w[k][i][j] = _g_layers_w[k][i][j];
}
}
}
}
/* Private: IOS tranforming part allocation routine */
template<class HA_Function, class OA_Function, class EMP>
void RecursiveNN<HA_Function, OA_Function, EMP>::allocIOSPart() {
// Assume constructor has initialized required dimension quantities
_h_layers_w = new double**[_s];
_prev_h_layers_w = new double**[_s];
_h_layers_gradient_w = new double**[_s];
_delta_h_layers = new double*[_s];
// Allocate weights and gradient components matrixes
// for h transforming part. Connections from input layers
// have special dimensions.
_h_layers_w[0] = new double*[_norient*_m + _n + 1];
_prev_h_layers_w[0] = new double*[_norient*_m + _n + 1];
_h_layers_gradient_w[0] = new double*[_norient*_m + _n + 1];
// Allocate and reset h first layer delta values.
_delta_h_layers[0] = new double[_lnunits[_r]];
memset(_delta_h_layers[0], 0, (_lnunits[_r])*sizeof(double));
for(int i=0; i<_norient*_m + _n + 1; i++) {
_h_layers_w[0][i] = new double[_lnunits[_r]];
_prev_h_layers_w[0][i] = new double[_lnunits[_r]];
_h_layers_gradient_w[0][i] = new double[_lnunits[_r]];
// Reset gradient for corresponding weights
memset(_h_layers_gradient_w[0][i], 0, _lnunits[_r] * sizeof(double));
// Assign weights a random number between -1.0 and +1.0
for(int j=0; j<_lnunits[_r]; j++) {
_h_layers_w[0][i][j] = nrnd01() / static_cast<double>(_lnunits[_r]);
_prev_h_layers_w[0][i][j] = _h_layers_w[0][i][j];
}
}
// Allocate weights&gradient matrixes for h map
for(int k=1; k<_s; k++) {
// Allocate space for weight&gradient matrixes between layer i-1 and i.
// Automatically include space for threshold unit in layer i-1
_h_layers_w[k] = new double*[_lnunits[_r+k-1] + 1];
_prev_h_layers_w[k] = new double*[_lnunits[_r+k-1] + 1];
_h_layers_gradient_w[k] = new double*[_lnunits[_r+k-1] + 1];
// Allocate and reset h layers delta layers values.
_delta_h_layers[k] = new double[_lnunits[_r+k]];
memset(_delta_h_layers[k], 0, (_lnunits[_r+k])*sizeof(double));
for(int i=0; i<_lnunits[_r+k-1]+1; i++) {
_h_layers_w[k][i] = new double[_lnunits[_r+k]];
_prev_h_layers_w[k][i] = new double[_lnunits[_r+k]];
_h_layers_gradient_w[k][i] = new double[_lnunits[_r+k]];
// Reset h gradient components for corresponding weights
memset(_h_layers_gradient_w[k][i], 0, (_lnunits[_r+k])*sizeof(double));
// Assign h weights a random number between -1.0 and +1.0
for(int j=0; j<_lnunits[_r+k]; j++) {
_h_layers_w[k][i][j] = nrnd01() / static_cast<double>(_lnunits[_r+k]);
_prev_h_layers_w[k][i][j] = _h_layers_w[k][i][j];
}
}
}
}
/* Private: Folding parts deallocation routine */
template<class HA_Function, class OA_Function, class EMP>
void RecursiveNN<HA_Function, OA_Function, EMP>::deallocFoldingParts(double**** layers_w, double**** prev_layers_w, double**** layers_gradient_w, double*** delta_layers) {
if((*layers_w)[0]) {
for(int i=0; i<(_n+_v*_m) + 1; i++) {
if((*layers_w)[0][i]) {
delete[] (*layers_w)[0][i];
delete[] (*prev_layers_w)[0][i];
}
(*layers_w)[0][i] = 0; (*prev_layers_w)[0][i] = 0;
}
delete[] (*layers_w)[0]; delete[] (*prev_layers_w)[0];
(*layers_w)[0] = 0; (*prev_layers_w)[0] = 0;
}
if((*layers_gradient_w)[0]) {
for(int i=0; i<(_n+_v*_m) + 1; i++) {
if((*layers_gradient_w)[0][i])
delete[] (*layers_gradient_w)[0][i];
(*layers_gradient_w)[0][i] = 0;
}
delete[] (*layers_gradient_w)[0];
(*layers_gradient_w)[0] = 0;
}
if(_r > 1 && (*delta_layers)[0]) {
delete[] (*delta_layers)[0];
(*delta_layers)[0] = 0;
}
for(int k=1; k<_r; k++) {
if((*layers_w)[k]) {
for(int i=0; i<_lnunits[k-1]+1; i++) {
if((*layers_w)[k][i]) {
delete[] (*layers_w)[k][i];
delete[] (*prev_layers_w)[k][i];
}
(*layers_w)[k][i] = 0; (*prev_layers_w)[k][i] = 0;
}
delete[] (*layers_w)[k]; delete[] (*prev_layers_w)[k];
(*layers_w)[k] = 0; (*prev_layers_w)[k] = 0;
}
if((*layers_gradient_w)[k]) {
for(int i=0; i<_lnunits[k-1]+1; i++) {
if((*layers_gradient_w)[k][i])
delete[] (*layers_gradient_w)[k][i];
(*layers_gradient_w)[k][i] = 0;
}
delete[] (*layers_gradient_w)[k];
(*layers_gradient_w)[k] = 0;
}
if(k < _r-1 && (*delta_layers)[k]) {
delete[] (*delta_layers)[k];
(*delta_layers)[k] = 0;
}
}
delete[] *layers_w; delete[] *prev_layers_w;
delete[] *layers_gradient_w;
if(_r > 1 && *delta_layers) {
delete[] *delta_layers;
*delta_layers = 0;
}
*layers_w = 0; *prev_layers_w = 0; *layers_gradient_w = 0;
}
/* Private: SS folding part deallocation routine */
template<class HA_Function, class OA_Function, class EMP>
void RecursiveNN<HA_Function, OA_Function, EMP>::deallocSSPart() {
if(_g_layers_w[0]) {
for(int i=0; i<_norient*_m + 1; i++) {
if(_g_layers_w[0][i]) {
delete[] _g_layers_w[0][i];
delete[] _prev_g_layers_w[0][i];
}
_g_layers_w[0][i] = 0; _prev_g_layers_w[0][i] = 0;
}
delete[] _g_layers_w[0]; delete[] _prev_g_layers_w[0];
_g_layers_w[0] = 0; _prev_g_layers_w[0] = 0;
}
if(_g_layers_gradient_w[0]) {
for(int i=0; i<_norient*_m + 1; i++) {
if(_g_layers_gradient_w[0][i])
delete[] _g_layers_gradient_w[0][i];
_g_layers_gradient_w[0][i] = 0;
}
delete[] _g_layers_gradient_w[0];
_g_layers_gradient_w[0] = 0;
}
if(_g_layers_activations[0]) {
delete[] _g_layers_activations[0];
_g_layers_activations[0] = 0;
}
if(_delta_g_layers[0]) {
delete[] _delta_g_layers[0];
_delta_g_layers[0] = 0;
}
for(int k=1; k<_s; k++) {
if(_g_layers_w[k]) {
for(int i=0; i<_lnunits[_r+k-1]+1; i++) {
if(_g_layers_w[k][i]) {
delete[] _g_layers_w[k][i];
delete[] _prev_g_layers_w[k][i];
}
_g_layers_w[k][i] = 0; _prev_g_layers_w[k][i] = 0;
}
delete[] _g_layers_w[k]; delete[] _prev_g_layers_w[k];
_g_layers_w[k] = 0; _prev_g_layers_w[k] = 0;
}
if(_g_layers_gradient_w[k]) {
for(int i=0; i<_lnunits[_r+k-1]+1; i++) {
if(_g_layers_gradient_w[k][i])
delete[] _g_layers_gradient_w[k][i];
_g_layers_gradient_w[k][i] = 0;
}
delete[] _g_layers_gradient_w[k];
_g_layers_gradient_w[k] = 0;
}
if(_g_layers_activations[k]) {
delete[] _g_layers_activations[k];
_g_layers_activations[k] = 0;
}
if(_delta_g_layers[k]) {
delete[] _delta_g_layers[k];
_delta_g_layers[k] = 0;
}
}
delete[] _g_layers_w; delete[] _prev_g_layers_w;
delete[] _g_layers_gradient_w;
delete[] _g_layers_activations;
delete[] _delta_g_layers;
_g_layers_w = 0; _prev_g_layers_w = 0; _g_layers_gradient_w = 0;
_g_layers_activations = 0; _delta_g_layers = 0;
}
/* Private: IOS output map deallocation routine */
template<class HA_Function, class OA_Function, class EMP>
void RecursiveNN<HA_Function, OA_Function, EMP>::deallocIOSPart() {
if(_h_layers_w[0]) {
for(int i=0; i<_norient*_m + _n + 1; i++) {
if(_h_layers_w[0][i]) {
delete[] _h_layers_w[0][i];
delete[] _prev_h_layers_w[0][i];
}
_h_layers_w[0][i] = 0; _prev_h_layers_w[0][i] = 0;
}
delete[] _h_layers_w[0]; delete[] _prev_h_layers_w[0];
_h_layers_w[0] = 0; _prev_h_layers_w[0] = 0;
}
if(_h_layers_gradient_w[0]) {
for(int i=0; i<_norient*_m + _n + 1; i++) {
if(_h_layers_gradient_w[0][i])
delete[] _h_layers_gradient_w[0][i];
_h_layers_gradient_w[0][i] = 0;
}
delete[] _h_layers_gradient_w[0];
_h_layers_gradient_w[0] = 0;
}
if(_delta_h_layers[0]) {
delete[] _delta_h_layers[0];
_delta_h_layers[0] = 0;
}
for(int k=1; k<_s; k++) {
if(_h_layers_w[k]) {
for(int i=0; i<_lnunits[_r+k-1]+1; i++) {
if(_h_layers_w[k][i]) {
delete[] _h_layers_w[k][i];
delete[] _prev_h_layers_w[k][i];
}
_h_layers_w[k][i] = 0; _prev_h_layers_w[k][i] = 0;
}
delete[] _h_layers_w[k]; delete[] _prev_h_layers_w[k];
_h_layers_w[k] = 0; _prev_h_layers_w[k] = 0;
}
if(_h_layers_gradient_w[k]) {
for(int i=0; i<_lnunits[_r+k-1]+1; i++) {
if(_h_layers_gradient_w[k][i])
delete[] _h_layers_gradient_w[k][i];
_h_layers_gradient_w[k][i] = 0;
}
delete[] _h_layers_gradient_w[k];
_h_layers_gradient_w[k] = 0;
}
if(_delta_h_layers[k]) {
delete[] _delta_h_layers[k];
_delta_h_layers[k] = 0;
}
}
delete[] _h_layers_w; delete[] _prev_h_layers_w;
delete[] _h_layers_gradient_w;
delete[] _delta_h_layers;
_h_layers_w = 0; _prev_h_layers_w = 0; _h_layers_gradient_w = 0;
_delta_h_layers = 0;
}
/*** Gradient components resetting methods ***/
template<class HA_Function, class OA_Function, class EMP>
void RecursiveNN<HA_Function, OA_Function, EMP>::resetGradientComponents() {
for(int i=0; i<_norient; ++i)
resetFoldingGradient(&(_layers_gradient_w[i]));
if(_ss_tr)
resetSSGradient();
if(_ios_tr)
resetIOSGradient();
}
template<class HA_Function, class OA_Function, class EMP>
void RecursiveNN<HA_Function, OA_Function, EMP>::resetFoldingGradient(double**** layers_gradient_w) {
for(int i=0; i<(_n+_v*_m) + 1; i++)
memset((*layers_gradient_w)[0][i], 0, _lnunits[0] * sizeof(double));
for(int k=1; k<_r; k++)
for(int i=0; i<_lnunits[k-1]+1; i++)
memset((*layers_gradient_w)[k][i], 0, (_lnunits[k])*sizeof(double));
}
template<class HA_Function, class OA_Function, class EMP>
void RecursiveNN<HA_Function, OA_Function, EMP>::resetSSGradient() {
for(int i=0; i<_norient*_m + 1; i++)
memset(_g_layers_gradient_w[0][i], 0, _lnunits[_r] * sizeof(double));
for(int k=1; k<_s; k++)
for(int i=0; i<_lnunits[_r+k-1]+1; i++)
memset(_g_layers_gradient_w[k][i], 0, (_lnunits[_r+k])*sizeof(double));
}
template<class HA_Function, class OA_Function, class EMP>
void RecursiveNN<HA_Function, OA_Function, EMP>::resetIOSGradient() {
for(int i=0; i<_norient*_m + _n + 1; i++)
memset(_h_layers_gradient_w[0][i], 0, _lnunits[_r] * sizeof(double));
for(int k=1; k<_s; k++)
for(int i=0; i<_lnunits[_r+k-1]+1; i++)
memset(_h_layers_gradient_w[k][i], 0, (_lnunits[_r+k])*sizeof(double));
}
// Reset output values in g MLP layers
template<class HA_Function, class OA_Function, class EMP>
void RecursiveNN<HA_Function, OA_Function, EMP>::resetSSValues() {
for(int k=0; k<_s; k++) {
memset(_g_layers_activations[k], 0, (_lnunits[_r+k])*sizeof(double));
}
}
/****** Public member functions ******/
/*
Constructor
- n: dimension for an input to a node
- v: valence of the domain (maximum outdegree)
- r: number of layers for the folding part
- s: number of layers for the tranforming part
- n_lunits: array where each slot indicates
number of units in each layer
lnunits[r-1] <=> m, number of units in representation layer
lnunits[r+s-1] <=> q, number of units in g&|h output layer
Obs: the input layer is constituted by n+v*m units grouped
into a label part and parts for substructures.
*/
template<class HA_Function, class OA_Function, class EMP> RecursiveNN<HA_Function, OA_Function, EMP>::RecursiveNN():
_norient(num_orientations(Options::instance()->domain())),
_n(Options::instance()->input_dim()),
_v(Options::instance()->domain_outdegree()),
_lnunits(Options::instance()->layers_number_units()) {
// Get other fundamental parameters from Options class
std::pair<int, int> indexes = Options::instance()->layers_indices();
_r = indexes.first; _s = indexes.second;
require(_lnunits.size() == (uint)(_r+_s), "Dim.Error");
// Number of output units of the
// transforming part (g MLP ouput function)
_q = _lnunits.back();
// _r is the number of layers for f and b folding parts,
// number of output units (_m) is the same for both.
_m = _lnunits[_r-1];
// get types of trasductions to implement
Transduction tr = Options::instance()->transduction();
switch(tr) {
case IO_ISOMORPH:
_ios_tr = true;
_ss_tr = false;
break;
case SUPER_SOURCE:
_ios_tr = false;
_ss_tr = true;
break;
default:
require(0, "Unknown transduction type");
}
_problem = Options::instance()->problem();
// Initialize random number generator
srand(time(0));
_layers_w = new double***[_norient];
_prev_layers_w = new double***[_norient];
_layers_gradient_w = new double***[_norient];
_delta_layers = new double**[_norient];
for(int i=0; i<_norient; ++i)
allocFoldingParts(&(_layers_w[i]), &(_prev_layers_w[i]), &(_layers_gradient_w[i]), &(_delta_layers[i]));
if(_ss_tr)
allocSSPart();
if(_ios_tr)
allocIOSPart();
// Allocate weight update method structures using _process_dr
// to decide whether or not to instantiate its b internal structures.
_wu_method.setInternals(this);
ptn_la = &Node::_layers_activations;
ptn_dv = &Node::_delta_lr;
}
/* Constructor */
template<class HA_Function, class OA_Function, class EMP>
RecursiveNN<HA_Function, OA_Function, EMP>::RecursiveNN(const char* network_filename) {
std::ifstream is(network_filename);
assure(is, network_filename);
// First the number of causal transductions and folding processing to implement
is >> _norient >> _ios_tr >> _ss_tr;
// Read node input dimension and max outdegree with
// the network was trained (or initialized)
is >> _n >> _v;
// Perfom necessary synchronization control with global parameters,
// to prevent using the net with values different from parameters
// of the other cooperating classes
Transduction tr = Options::instance()->transduction();
require(_ios_tr == (tr == IO_ISOMORPH)?true:false && _ss_tr == (tr == SUPER_SOURCE)?true:false,
"Synchronization Error between RecursiveNN and global parameters: check trasduction type");
require(_norient == num_orientations(Options::instance()->domain()), "Mismatch on number of orientations");
require(_n == Options::instance()->input_dim(), "Synchronization Error between RecursiveNN and global parameters: check nodes input dimension");
require(_v == Options::instance()->domain_outdegree(), "Synchronization Error between RecursiveNN and global parameters: check outdegree");
_problem = Options::instance()->problem();
// Then read values of r and s from file
is >> _r >> _s;
// Some other necessary controls
std::pair<int, int> indexes = Options::instance()->layers_indices();
require(_r == indexes.first && _s == indexes.second,
"Synchronization Error between RecursiveNN and global parameters: check layers indexes");
// Then the vector of number of units per layer
int i = 0, lnu;
while(i<_r+_s) {
is >> lnu;
_lnunits.push_back(lnu);
++i;
}
require(_lnunits == Options::instance()->layers_number_units(),
"Synchronization Error between RecursiveNN and global parameters: check layers number of units");
// Number of output units of the transforming part (g MLP ouput function)
_q = _lnunits.back();
// _r is the number of layers for the folding parts,
// number of output units (_m) is the same for all
_m = _lnunits[_r-1];
is.precision(Options::instance()->precision());
is.setf(std::ios::scientific);
_layers_w = new double***[_norient];
_prev_layers_w = new double***[_norient];
_layers_gradient_w = new double***[_norient];
_delta_layers = new double**[_norient];
// allocate space for each folding direction
for(int i=0; i<_norient; ++i)
allocFoldingParts(&(_layers_w[i]), &(_prev_layers_w[i]), &(_layers_gradient_w[i]), &(_delta_layers[i]));
// read weights for each folding direction
for(int o=0; o<_norient; ++o) {
for(int i=0; i<(_n+_v*_m) + 1; i++) {
for(int j=0; j<_lnunits[0]; j++) {
is >> _layers_w[o][0][i][j];
_prev_layers_w[o][0][i][j] = _layers_w[o][0][i][j];
}
}
for(int k=1; k<_r; k++) {
for(int i=0; i<_lnunits[k-1]+1; i++) {
for(int j=0; j<_lnunits[k]; j++) {
is >> _layers_w[o][k][i][j];
_prev_layers_w[o][k][i][j] = _layers_w[o][k][i][j];
}
}
}
}
// Eventually read weights for g output function layers
if(_ss_tr) {
allocSSPart();
for(int i=0; i<_norient*_m + 1; i++)
for(int j=0; j<_lnunits[_r]; j++) {
is >> _g_layers_w[0][i][j];
_prev_g_layers_w[0][i][j] = _g_layers_w[0][i][j];
}
for(int k=1; k<_s; k++) {
for(int i=0; i<_lnunits[_r+k-1]+1; i++) {
for(int j=0; j<_lnunits[_r+k]; j++) {
is >> _g_layers_w[k][i][j];
_prev_g_layers_w[k][i][j] = _g_layers_w[k][i][j];
}
}
}
}
// Eventually read weights for h map layers
if(_ios_tr) {
allocIOSPart();
for(int i=0; i<_norient*_m + _n + 1; i++)
for(int j=0; j<_lnunits[_r]; j++) {
is >> _h_layers_w[0][i][j];
_prev_h_layers_w[0][i][j] = _h_layers_w[0][i][j];
}
for(int k=1; k<_s; k++) {
for(int i=0; i<_lnunits[_r+k-1]+1; i++) {
for(int j=0; j<_lnunits[_r+k]; j++) {
is >> _h_layers_w[k][i][j];
_prev_h_layers_w[k][i][j] = _h_layers_w[k][i][j];
}
}
}
}
// Allocate weight update method structures
_wu_method.setInternals(this);
ptn_la = &Node::_layers_activations;
ptn_dv = &Node::_delta_lr;
}
/* Destructor */
template<class HA_Function, class OA_Function, class EMP>
RecursiveNN<HA_Function, OA_Function, EMP>::~RecursiveNN() {
for(int i=0; i<_norient; ++i)
deallocFoldingParts(&(_layers_w[i]), &(_prev_layers_w[i]), &(_layers_gradient_w[i]), &(_delta_layers[i]));
if(_ss_tr)
deallocSSPart();
if(_ios_tr)
deallocIOSPart();
}
/*
This function is to be used to evaluate a structure in
a casual or casual & non-casual fashion, compute its encoded
representation at root node ouput layers and evaluate it
with the ouptput (g) function.
*/
template<class HA_Function, class OA_Function, class EMP>
void RecursiveNN<HA_Function, OA_Function, EMP>::propagateStructuredInput(Instance* instance) {
// Reset output activations in nodes layers
// if _ios_tr is set h output activations are reset
instance->resetNodeOutputActivations();
// Reset output activations in output (g) function MLP layers
if(_ss_tr)
resetSSValues();
// Structure propagation by unfolding into casual parts
for(int i=0; i<_norient; ++i)
propagateInputOnFoldingPart(instance, i); //toNodes, sdags[0], sdags_top_ords[0], &_f_layers_w, ptn_fla);
// Evaluate current encoded structure (if supersource trasd.)
if(_ss_tr)
gPropagateInput(instance); // toNodes, sdags, sdags_top_ords);
// Compute output label for each node (if io-isomorf trasd.)
if(_ios_tr)
for(uint n=0; n<instance->num_nodes(); ++n)
hPropagateInput(instance->node(n));
}
/*******************
* Private methods *
*******************/
template<class HA_Function, class OA_Function, class EMP>
void RecursiveNN<HA_Function, OA_Function, EMP>::propagateInputOnFoldingPart(Instance* instance, int o) {
// A structured input is a sequence of nodes and a DAG with that vertices.
// Nodes are passed by (non-const) reference to allow the net
// storing output activations on each node for all of the folding layers.
DPAG* dpag = instance->orientation(o);
Vertex_d currentNode;
//VertexId vertex_id = boost::get(boost::vertex_index, *dpag);
EdgeId edge_id = boost::get(boost::edge_index, *dpag);
outIter out_i, out_end;
std::vector<int> top_ord = instance->topological_order(o);
for(std::vector<int>::const_reverse_iterator r_it=top_ord.rbegin(); r_it!=top_ord.rend(); ++r_it) {
int t = *r_it;
Node* node = instance->node(t);
currentNode = boost::vertex(t, *dpag);
require(_n == node->input_dim(), "Error in Node input dimension\n");
// Remember: if k==1 (0 according to the indexing scheme)
// net input for each unit comes both from current node
// immediate successors and from the node input label.
// We are in layer k == 1.
// for each unit in layer 1 (0)
for(int j=0; j<_lnunits[0]; j++) {
// calculate weighted sum of its inputs
double unit_input = 0.0;
// firstly take into account current node input label
for(int i=0; i<_n; i++) {
unit_input +=
_layers_w[o][0][i][j] * node->_encodedInput[i];
}
// add to weighted sum contribution of the previously
// computed representations of the immediate substructures.
// Eliminate control on max outdegree.
// Ignore edges whose id is greater than max outdegree.
for(boost::tie(out_i, out_end)=out_edges(currentNode, *dpag);
out_i!=out_end && edge_id[*out_i] < (uint)_v; ++out_i) {
//require(0<=edge_id[*out_i] && edge_id[*out_i] < _v, "Valence assertion failed!");