-
Notifications
You must be signed in to change notification settings - Fork 1
/
nnet_train_2.m
1473 lines (1087 loc) · 43.1 KB
/
nnet_train_2.m
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
function paramsp = nnet_train_2( runName, runDesc, paramsp, Win, bin, resumeFile, maxepoch, indata, outdata, numchunks, intest, outtest, numchunks_test, layersizes, layertypes, mattype, rms, errtype, hybridmode, weightcost, decay, jacket)
%
% Demo code for the paper "Deep Learning via Hessian-free Optimization" by James Martens.
%
% paramsp = nnet_train_2( runName, runDesc, paramsp, Win, bin, resumeFile, maxepoch, indata, outdata, numchunks, intest, outtest, numchunks_test, layersizes, layertypes, mattype, rms, errtype, hybridmode, weightcost, decay, jacket)
%
% IMPORTANT NOTES: The most important variables to tweak are `initlambda' (easy) and
% `maxiters' (harder). Also, if your particular application is still not working the next
% most likely way to fix it is tweaking the variable `initcoeff' which controls
% overall magnitude of the initial random weights. Please don't treat this code like a black-box,
% get a negative result, and then publish a paper about how the approach doesn't work :) And if
% you are running into difficulties feel free to e-mail me at [email protected]
%
% runName - name you give to the current run. This is used for the
% log-file and the files which contain the current parameters that get
% saved every 10 epochs
%
% runDesc - notes to yourself about the current run (can be the empty string)
%
% paramsp - initial parameters in the form of a vector (can be []). If
% this, or the arguments Win,bin are empty, the 'sparse initialization'
% technique is used
%
% Win, bin - initial parameters in their matrix forms (can be [])
%
% resumeFile - file used to resume a previous run from a file
%
% maxepoch - maximum number of 'epochs' (outer iteration of HF). There is no termination condition
% for the optimizer and usually I just stop it by issuing a break command
%
% indata/outdata - input/output training data for the net (each case is a
% column). Make sure that the training cases are randomly permuted when you invoke
% this function as it won't do it for you.
%
% numchunks - number of mini-batches used to partition the training set.
% During each epoch, a single mini-batch is used to compute the
% matrix-vector products, after which it gets cycled to the back of the
% last and is used again numchunk epochs later. Note that the gradient and
% line-search are still computed using the full training set. This of
% course is not practical for very large datasets, but in general you can
% afford to use a lot more data to compute the gradient than the
% matrix-vector products, since you only have to do the former once per iteration
% of the outer loop.
%
% intest/outtest - test data
%
% numchunks_test - while the test set isn't used for matrix-vector
% products, you still may want to partition it so that it can be processed
% in pieces on the GPU instead of all at once.
%
% layersizes - the size of each hidden layer (input and output sizes aren't
% specified in this vector since they are determined by the dimension of
% the data arguements)
%
% layertypes - a cell-array of strings that indicate the unit type in each
% layer. can be 'logistic', 'tanh', 'linear' or 'softmax'. I haven't
% thoroughly tested the softmax units. Also, the output units can't be
% tanh because I haven't implemented that (even though it's easy).
% Consider that an exercise :)
%
% mattype - the type of curvature matrix to use. can be 'gn' for
% Gauss-Newton, 'hess' for Hessian and 'empfish' for empirical Fisher. You
% should probably only ever use 'gn' if you actually want the training to
% go well
%
% rms - by default we use the canonical error function for
% each output unit type. e.g. square error for linear units and
% cross-entropy error for logistics. Setting this to 1 (instead of 0) overrides
% the default and forces it to use squared-error. Note that even if what you
% care about is minimizing squared error it's sometimes still better
% to run on the optimizer with the canonical error
%
% errtype - in addition to displaying the objective function (log-likelihood) you may also
% want to keep track of another metric like squared error when you train
% deep auto-encoders. This can be 'L2' for squared error, 'class' for
% classification error, or 'none' for nothing. It should be easy enough to
% add your own type of error should you need one
%
% hybridmode - set this 1 unless you want compute the matrix-vector
% products using the whole training dataset instead of the mini-batches.
% Note that in this case they still serve a purpose since the mini-batches
% are only loaded onto the gpu 1 at a time.
%
% weightcost - the strength of the l_2 prior on the weights
%
% decay - the amount to decay the previous search direction for the
% purposes of initializing the next run of CG. Should be 0.95
%
% jacket - set to 1 in order to use the Jacket computing library. Will run
% on the CPU otherwise and hence be really slow. You can easily port this code
% over to free and possibly slower GPU packages like GPUmat (in fact, I have some
% commented code which does just that (do a text search for "GPUmat version")
disp( ['Starting run named: ' runName ]);
rec_constants = {'layersizes', 'rms', 'weightcost', 'hybridmode', 'autodamp', 'initlambda', 'drop', 'boost', 'numchunks', 'mattype', 'errtype', 'decay'};
autodamp = 1;
drop = 2/3;
boost = 1/drop;
%In addition to maxiters the variable below is something you should manually
%adjust. It is quite problem specific. Fortunately after only 1 'epoch'
%you can often tell if you've made a bad choice. The value of rho should lie
%somewhere between 0.75 and 0.95. I could automate this part but I'm lazy
%and my code isn't designed to make such automation a natural thing to add. Also
%note that 'lambda' is being added to the normalized curvature matrix (i.e.
%divided by the number of cases) while in the ICML paper I was adding it to
%the unnormalized curvature matrix. This doesn't make any real
%difference to the optimization, but does make it somewhat easier to guage
%lambda and set its initial value since it will be 'independent' of the
%number of training cases in each mini-batch
initlambda = 1.0;
if strcmp(mattype, 'hess')
storeD = 1;
computeBV = @computeHV;
elseif strcmp(mattype, 'gn')
storeD = 0;
computeBV = @computeGV;
elseif strcmp(mattype, 'empfish')
storeD = 0;
computeBV = @computeFV;
end
if jacket
%mones = @gones;
%mzeros = @gzeros;
%conv = @gsingle;
% %GPUmat version:
% mones = @(varargin) ones(varargin{:}, GPUsingle);
% mzeros = @(varargin) zeros(varargin{:}, GPUsingle);
% conv = @GPUsingle;
%
% norm = @(x) sqrt(sum(x.*x));
%
% mrandn = @grandn;
%Parallel Computing Toolbox version
mones = @(varargin)gpuArray.ones(varargin{:}, 'single');
mzeros = @(varargin)gpuArray.zeros(varargin{:}, 'single');
conv = @(x)gpuArray(single(x));
norm = @(x) sqrt(sum(x.*x));
mrandn = @gpuArray.randn;
else
%use singles (this can make cpu code go faster):
mones = @(varargin)ones(varargin{:}, 'single');
mzeros = @(varargin)zeros(varargin{:}, 'single');
%conv = @(x)x;
conv = @single;
norm = @(x) sqrt(sum(x.*x)); %I added this to fix error
%use doubles:
%{
mones = @ones;
mzeros = @zeros;
%conv = @(x)x;
conv = @double;
%}
mrandn = @randn;
end
if hybridmode
store = conv; %cache activities on the gpu
%store = @single; %cache activities on the cpu
else
store = @single;
end
layersizes = [size(indata,1) layersizes size(outdata,1)];
numlayers = size(layersizes,2) - 1;
[indims numcases] = size(indata);
[tmp numtest] = size(intest);
if mod( numcases, numchunks ) ~= 0
error( 'Number of chunks doesn''t divide number of training cases!' );
end
sizechunk = numcases/numchunks;
sizechunk_test = numtest/numchunks_test;
if numcases >= 512*64
disp( 'jacket issues possible!' );
end
y = cell(numchunks, numlayers+1);
if storeD
dEdy = cell(numchunks, numlayers+1);
dEdx = cell(numchunks, numlayers);
end
function v = vec(A)
v = A(:);
end
psize = layersizes(1,2:(numlayers+1))*layersizes(1,1:numlayers)' + sum(layersizes(2:(numlayers+1)));
%pack all the parameters into a single vector for easy manipulation
function M = pack(W,b)
M = mzeros( psize, 1 );
cur = 0;
for i = 1:numlayers
M((cur+1):(cur + layersizes(i)*layersizes(i+1)), 1) = vec( W{i} );
cur = cur + layersizes(i)*layersizes(i+1);
M((cur+1):(cur + layersizes(i+1)), 1) = vec( b{i} );
cur = cur + layersizes(i+1);
end
end
%unpack parameters from a vector so they can be used in various neural-net
%computations
function [W,b] = unpack(M)
W = cell( numlayers, 1 );
b = cell( numlayers, 1 );
cur = 0;
for i = 1:numlayers
W{i} = reshape( M((cur+1):(cur + layersizes(i)*layersizes(i+1)), 1), [layersizes(i+1) layersizes(i)] );
cur = cur + layersizes(i)*layersizes(i+1);
b{i} = reshape( M((cur+1):(cur + layersizes(i+1)), 1), [layersizes(i+1) 1] );
cur = cur + layersizes(i+1);
end
end
%compute the vector-product with the Hessian matrix
function HV = computeHV(V)
if ~storeD
error('need to store D');
end
[VWu, Vbu] = unpack(V);
HV = mzeros(psize,1);
if hybridmode
chunkrange = targetchunk; %set outside
else
chunkrange = 1:numchunks;
end
for chunk = chunkrange
%application of R operator
Ry = cell(numlayers+1,1);
RdEdy = cell(numlayers+1,1);
RdEdx = cell(numlayers, 1);
HVW = cell(numlayers,1);
HVb = cell(numlayers,1);
%forward prop:
Ryip1 = mzeros(layersizes(1), sizechunk);
yip1 = conv(y{chunk, 1});
for i = 1:numlayers
Ryi = Ryip1;
Ryip1 = [];
yi = yip1;
yip1 = [];
Rxi = Wu{i}*Ryi + VWu{i}*yi + repmat(Vbu{i}, [1 sizechunk]);
Ry{i} = store(Ryi);
Ryi = [];
yip1 = conv(y{chunk, i+1});
if strcmp(layertypes{i}, 'logistic')
Ryip1 = Rxi.*yip1.*(1-yip1);
elseif strcmp(layertypes{i}, 'linear')
Ryip1 = Rxi;
elseif strcmp( layertypes{i}, 'softmax' )
Ryip1 = Rxi.*yip1 - yip1.* repmat( sum( Rxi.*yip1, 1 ), [layersizes(i+1) 1] );
else
error( 'Unknown/unsupported layer type' );
end
Rxi = [];
end
%backward prop:
%cross-entropy for logistics:
%RdEdy{numlayers+1} = (-(outdata./(y{numlayers+1}.^2) + (1-outdata)./(1-y{numlayers+1}).^2)).*Ry{numlayers+1};
%cross-entropy for softmax:
%RdEdy{numlayers+1} = -outdata./(y{numlayers+1}.^2).*Ry{numlayers+1};
for i = numlayers:-1:1
if i < numlayers
if strcmp(layertypes{i}, 'logistic')
%logistics:
dEdyip1 = conv( dEdy{chunk, i+1} );
RdEdx{i} = RdEdy{i+1}.*yip1.*(1-yip1) + dEdyip1.*Ryip1.*(1-2*yip1);
dEdyip1 = [];
elseif strcmp(layertypes{i}, 'linear')
RdEdx{i} = RdEdy{i+1};
else
error( 'Unknown/unsupported layer type' );
end
else
if ~rms
%assume canonical link functions:
RdEdx{i} = -Ryip1;
if strcmp(layertypes{i}, 'linear')
RdEdx{i} = 2*RdEdx{i};
end
else
dEdyip1 = 2*(conv(outdata(:, ((chunk-1)*sizechunk+1):(chunk*sizechunk) )) - yip1); %mult by 2 because we dont include the 1/2 before
RdEdyip1 = -2*Ryip1;
if strcmp( layertypes{i}, 'softmax' )
%softmax:
RdEdx{i} = RdEdyip1.*yip1 - yip1.*repmat( sum( RdEdyip1.*yip1, 1), [layersizes(i+1) 1] ) ...
+ dEdyip1.*Ryip1 - yip1.*repmat( sum( dEdyip1.*Ryip1, 1), [layersizes(i+1) 1] ) - Ryip1.*repmat( sum( dEdyip1.*yip1, 1), [layersizes(i+1) 1] );
%error( 'RMS error not supported with softmax output' );
elseif strcmp( layertypes{i}, 'logistic' )
RdEdx{i} = RdEdyip1.*yip1.*(1-yip1) + dEdyip1.*Ryip1.*(1-2*yip1);
elseif strcmp(layertypes{i}, 'linear')
RdEdx{i} = RdEdyip1;
else
error( 'Unknown/unsupported layer type' );
end
dEdyip1 = [];
RdEdyip1 = [];
end
end
RdEdy{i+1} = [];
yip1 = []; Ryip1 = [];
yi = conv( y{chunk, i} );
Ryi = conv( Ry{i} );
dEdxi = conv( dEdx{chunk, i} );
RdEdy{i} = VWu{i}'*dEdxi + Wu{i}'*RdEdx{i};
%(HV = RdEdW)
HVW{i} = RdEdx{i}*yi' + dEdxi*Ryi';
HVb{i} = sum(RdEdx{i},2);
RdEdx{i} = []; dEdxi = [];
yip1 = yi; yi = [];
Ryip1 = Ryi; Ryi = [];
end
yip1 = []; Ryip1 = []; RdEdy{1} = [];
HV = HV + pack(HVW, HVb);
end
HV = HV / conv(numcases);
if hybridmode
HV = HV * conv(numchunks);
end
HV = HV - conv(weightcost)*(maskp.*V);
if autodamp
HV = HV - conv(lambda)*V;
end
end
%compute the vector-product with the Gauss-Newton matrix
function GV = computeGV(V)
[VWu, Vbu] = unpack(V);
GV = mzeros(psize,1);
if hybridmode
chunkrange = targetchunk; %set outside
else
chunkrange = 1:numchunks;
end
for chunk = chunkrange
%application of R operator
rdEdy = cell(numlayers+1,1);
rdEdx = cell(numlayers, 1);
GVW = cell(numlayers,1);
GVb = cell(numlayers,1);
Rx = cell(numlayers,1);
Ry = cell(numlayers,1);
yip1 = conv(y{chunk, 1});
%forward prop:
Ryip1 = mzeros(layersizes(1), sizechunk);
for i = 1:numlayers
Ryi = Ryip1;
Ryip1 = [];
yi = yip1;
yip1 = [];
Rxi = Wu{i}*Ryi + VWu{i}*yi + repmat(Vbu{i}, [1 sizechunk]);
%Rx{i} = store(Rxi);
yip1 = conv(y{chunk, i+1});
if strcmp(layertypes{i}, 'logistic')
Ryip1 = Rxi.*yip1.*(1-yip1);
elseif strcmp(layertypes{i}, 'tanh')
Ryip1 = Rxi.*(1+yip1).*(1-yip1);
elseif strcmp(layertypes{i}, 'linear')
Ryip1 = Rxi;
elseif strcmp( layertypes{i}, 'softmax' )
Ryip1 = Rxi.*yip1 - yip1.* repmat( sum( Rxi.*yip1, 1 ), [layersizes(i+1) 1] );
else
error( 'Unknown/unsupported layer type' );
end
Rxi = [];
end
%Backwards pass. This is where things start to differ from computeHV Please note that the lower-case r
%notation doesn't really make sense so don't bother trying to decode it. Instead there is a much better
%way of thinkin about the GV computation, with its own notation, which I talk about in my more recent paper:
%"Learning Recurrent Neural Networks with Hessian-Free Optimization"
for i = numlayers:-1:1
if i < numlayers
%logistics:
if strcmp(layertypes{i}, 'logistic')
rdEdx{i} = rdEdy{i+1}.*yip1.*(1-yip1);
elseif strcmp(layertypes{i}, 'tanh')
rdEdx{i} = rdEdy{i+1}.*(1+yip1).*(1-yip1);
elseif strcmp(layertypes{i}, 'linear')
rdEdx{i} = rdEdy{i+1};
else
error( 'Unknown/unsupported layer type' );
end
else
if ~rms
%assume canonical link functions:
rdEdx{i} = -Ryip1;
if strcmp(layertypes{i}, 'linear')
rdEdx{i} = 2*rdEdx{i};
end
else
RdEdyip1 = -2*Ryip1;
if strcmp(layertypes{i}, 'softmax')
error( 'RMS error not supported with softmax output' );
elseif strcmp(layertypes{i}, 'logistic')
rdEdx{i} = RdEdyip1.*yip1.*(1-yip1);
elseif strcmp(layertypes{i}, 'tanh')
rdEdx{i} = RdEdyip1.*(1+yip1).*(1-yip1);
elseif strcmp(layertypes{i}, 'linear')
rdEdx{i} = RdEdyip1;
else
error( 'Unknown/unsupported layer type' );
end
RdEdyip1 = [];
end
Ryip1 = [];
end
rdEdy{i+1} = [];
rdEdy{i} = Wu{i}'*rdEdx{i};
yi = conv(y{chunk, i});
GVW{i} = rdEdx{i}*yi';
GVb{i} = sum(rdEdx{i},2);
rdEdx{i} = [];
yip1 = yi;
yi = [];
end
yip1 = [];
rdEdy{1} = [];
GV = GV + pack(GVW, GVb);
end
GV = GV / conv(numcases);
if hybridmode
GV = GV * conv(numchunks);
end
GV = GV - conv(weightcost)*(maskp.*V);
if autodamp
GV = GV - conv(lambda)*V;
end
end
%compute the vector-product with the emperical Fisher matrix
function FV = computeFV(V)
[VWu, Vbu] = unpack(V);
FV = mzeros(psize,1);
if hybridmode
chunkrange = targetchunk; %set outside
else
chunkrange = 1:numchunks;
end
for chunk = chunkrange
%application of R operator
rdEdy = cell(numlayers+1,1);
rdEdx = cell(numlayers, 1);
FVW = cell(numlayers,1);
FVb = cell(numlayers,1);
Rx = cell(numlayers,1);
%forward prop:
Ryip1 = mzeros(layersizes(1), sizechunk);
yip1 = conv(y{chunk, 1});
for i = 1:numlayers
Ryi = Ryip1;
Ryip1 = [];
yi = yip1;
yip1 = [];
Rxi = Wu{i}*Ryi + VWu{i}*yi + repmat(Vbu{i}, [1 sizechunk]);
%Rx{i} = store(Rxi);
yip1 = conv(y{chunk, i+1});
if i < numlayers
if strcmp(layertypes{i}, 'logistic')
Ryip1 = Rxi.*yip1.*(1-yip1);
elseif strcmp(layertypes{i}, 'tanh')
Ryip1 = Rxi.*(1+yip1).*(1-yip1);
elseif strcmp(layertypes{i}, 'linear')
Ryip1 = Rxi;
elseif strcmp( layertypes{i}, 'softmax' )
Ryip1 = Rxi.*yip1 - yip1.* repmat( sum( Rxi.*yip1, 1 ), [layersizes(i+1) 1] );
else
error( 'Unknown/unsupported layer type' );
end
else
dEdxi = conv(outdata(:, ((chunk-1)*sizechunk+1):(chunk*sizechunk) )) - yip1;
Ryip1 = repmat(sum(Rxi.*dEdxi, 1), [layersizes(i+1) 1]).*dEdxi;
%Ryip1 = Rxi.*(dEdxi.^2);
dEdxi = [];
if rms
error('not sure if this works');
end
end
Rxi = [];
end
%back prop:
%cross-entropy for logistics:
%dEdy{numlayers+1} = outdata./y{numlayers+1} - (1-outdata)./(1-y{numlayers+1});
%cross-entropy for softmax:
%dEdy{numlayers+1} = outdata./y{numlayers+1};
for i = numlayers:-1:1
if i < numlayers
%logistics:
if strcmp(layertypes{i}, 'logistic')
rdEdx{i} = rdEdy{i+1}.*yip1.*(1-yip1);
elseif strcmp(layertypes{i}, 'tanh')
rdEdx{i} = rdEdy{i+1}.*(1+yip1).*(1-yip1);
elseif strcmp(layertypes{i}, 'linear')
rdEdx{i} = rdEdy{i+1};
else
error( 'Unknown/unsupported layer type' );
end
else
if ~rms
%assume canonical link functions:
rdEdx{i} = -Ryip1;
if strcmp(layertypes{i}, 'linear')
rdEdx{i} = 2*rdEdx{i};
end
else
RdEdyip1 = -2*Ryip1;
if strcmp(layertypes{i}, 'softmax')
error( 'RMS error not supported with softmax output' );
elseif strcmp(layertypes{i}, 'logistic')
rdEdx{i} = RdEdyip1.*yip1.*(1-yip1);
elseif strcmp(layertypes{i}, 'tanh')
rdEdx{i} = RdEdyip1.*(1+yip1).*(1-yip1);
elseif strcmp(layertypes{i}, 'linear')
rdEdx{i} = RdEdyip1;
else
error( 'Unknown/unsupported layer type' );
end
RdEdyip1 = [];
end
Ryip1 = [];
end
rdEdy{i+1} = [];
rdEdy{i} = Wu{i}'*rdEdx{i};
yi = conv(y{chunk, i});
%standard gradient comp:
FVW{i} = rdEdx{i}*yi';
FVb{i} = sum(rdEdx{i},2);
%FVb{i} = rdEdx{i}*mones(sizechunk,1);
rdEdx{i} = [];
yip1 = yi;
yi = [];
end
yip1 = [];
rdEdy{1} = [];
FV = FV + pack(FVW, FVb);
end
FV = FV / conv(numcases);
if hybridmode
FV = FV * conv(numchunks);
end
FV = FV + gradchunk*(gradchunk'*V);
FV = FV - conv(weightcost)*(maskp.*V);
if autodamp
FV = FV - conv(lambda)*V;
end
end
function [ll, err] = computeLL(params, in, out, nchunks, tchunk)
ll = 0;
err = 0;
[W,b] = unpack(params);
if mod( size(in,2), nchunks ) ~= 0
error( 'Number of chunks doesn''t divide number of cases!' );
end
schunk = size(in,2)/nchunks;
if nargin > 4
chunkrange = tchunk;
else
chunkrange = 1:nchunks;
end
for chunk = chunkrange
yi = conv(in(:, ((chunk-1)*schunk+1):(chunk*schunk) ));
outc = conv(out(:, ((chunk-1)*schunk+1):(chunk*schunk) ));
for i = 1:numlayers
xi = W{i}*yi + repmat(b{i}, [1 schunk]);
if strcmp(layertypes{i}, 'logistic')
yi = 1./(1 + exp(-xi));
elseif strcmp(layertypes{i}, 'tanh')
yi = tanh(xi);
elseif strcmp(layertypes{i}, 'linear')
yi = xi;
elseif strcmp(layertypes{i}, 'softmax' )
tmp = exp(xi);
yi = tmp./repmat( sum(tmp), [layersizes(i+1) 1] );
tmp = [];
end
end
if rms || strcmp( layertypes{numlayers}, 'linear' )
ll = ll + double( -sum(sum((outc - yi).^2)) );
else
if strcmp( layertypes{numlayers}, 'logistic' )
%outc==0 and outc==1 are included in this formula to avoid
%the annoying case where you have 0*log(0) = 0*-Inf = NaN
%ll = ll + double( sum(sum(outc.*log(yi + (outc==0)) + (1-outc).*log(1-yi + (outc==1)))) );
%this version is more stable:
ll = ll + double(sum(sum(xi.*(outc - (xi >= 0)) - log(1+exp(xi - 2*xi.*(xi>=0))))));
elseif strcmp( layertypes{numlayers}, 'softmax' )
ll = ll + double(sum(sum(outc.*log(yi))));
end
end
xi = [];
if strcmp( errtype, 'class' )
%err = 1 - double(sum( sum(outc.*yi,1) == max(yi,[],1) ) )/size(in,2);
err = err + double(sum( sum(outc.*yi,1) ~= max(yi,[],1) ) ) / size(in,2);
elseif strcmp( errtype, 'L2' )
err = err + double(sum(sum((yi - outc).^2, 1))) / size(in,2);
elseif strcmp( errtype, 'none')
%do nothing
else
error( 'Unrecognized error type' );
end
%err = double( (mones(1,size(in,1))*((yi - out).^2))*mones(size(in,2),1)/conv(size(in,2)) );
outc = [];
yi = [];
end
ll = ll / size(in,2);
if nargin > 4
ll = ll*nchunks;
err = err*nchunks;
end
ll = ll - 0.5*weightcost*double(params'*(maskp.*params));
end
function yi = computePred(params, in) %for checking G computation using finite differences
[W, b] = unpack(params);
yi = in;
for i = 1:numlayers
xi = W{i}*yi + repmat(b{i}, [1 size(in,2)]);
if i < numlayers
if strcmp(layertypes{i}, 'logistic')
yi = 1./(1 + exp(-xi));
elseif strcmp(layertypes{i}, 'tanh')
yi = tanh(xi);
elseif strcmp(layertypes{i}, 'linear')
yi = xi;
elseif strcmp(layertypes{i}, 'softmax' )
tmp = exp(xi);
yi = tmp./repmat( sum(tmp), [layersizes(i+1) 1] );
tmp = [];
end
else
yi = xi;
end
end
end
maskp = mones(psize,1);
[maskW, maskb] = unpack(maskp);
disp('not masking out the weight-decay for biases');
for i = 1:length(maskb)
%maskb{i}(:) = 0; %uncomment this line apply the l_2 only to the connection weights and not the biases
end
maskp = pack(maskW,maskb);
indata = single(indata);
outdata = single(outdata);
intest = single(intest);
outtest = single(outtest);
function outputString( s )
fprintf( 1, '%s\n', s );
fprintf( fid, '%s\r\n', s );
end
fid = fopen( [runName '.txt'], 'a' );
outputString( '' );
outputString( '' );
outputString( '==================== New Run ====================' );
outputString( '' );
outputString( ['Start time: ' datestr(now)] );
outputString( '' );
outputString( ['Description: ' runDesc] );
outputString( '' );
ch = mzeros(psize, 1);
if ~isempty( resumeFile )
outputString( ['Resuming from file: ' resumeFile] );
outputString( '' );
load( resumeFile );
ch = conv(ch);
epoch = epoch + 1;
else
lambda = initlambda;
llrecord = zeros(maxepoch,2);
errrecord = zeros(maxepoch,2);
lambdarecord = zeros(maxepoch,1);
times = zeros(maxepoch,1);
totalpasses = 0;
epoch = 1;
end
if isempty(paramsp)
if ~isempty(Win)
paramsp = pack(Win,bin);
clear Win bin
else
%SPARSE INIT:
paramsp = zeros(psize,1); %not mzeros
[Wtmp,btmp] = unpack(paramsp);
numconn = 15;
for i = 1:numlayers
initcoeff = 1;
if i > 1 && strcmp( layertypes{i-1}, 'tanh' )
initcoeff = 0.5*initcoeff;
end
if strcmp( layertypes{i}, 'tanh' )
initcoeff = 0.5*initcoeff;
end
if strcmp( layertypes{i}, 'tanh' )
btmp{i}(:) = 0.5;
end
%outgoing
%{
for j = 1:layersizes(i)
idx = ceil(layersizes(i+1)*rand(1,numconn));
Wtmp{i}(idx,j) = randn(numconn,1)*coeff;
end
%}
%incoming
for j = 1:layersizes(i+1)
idx = ceil(layersizes(i)*rand(1,numconn));
Wtmp{i}(j,idx) = randn(numconn,1)*initcoeff;
end
end
paramsp = pack(Wtmp, btmp);
clear Wtmp btmp
end
elseif size(paramsp,1) ~= psize || size(paramsp,2) ~= 1
error( 'Badly sized initial parameter vector.' );
else
paramsp = conv(paramsp);
end
outputString( 'Initial constant values:' );
outputString( '------------------------' );
outputString( '' );
for i = 1:length(rec_constants)
outputString( [rec_constants{i} ': ' num2str(eval( rec_constants{i} )) ] );
end
outputString( '' );
outputString( '=================================================' );
outputString( '' );
for epoch = epoch:maxepoch
tic
targetchunk = mod(epoch-1, numchunks)+1;
[Wu, bu] = unpack(paramsp);
y = cell(numchunks, numlayers+1);
x = cell(numchunks, numlayers+1);
if storeD
dEdy = cell(numchunks, numlayers+1);
dEdx = cell(numchunks, numlayers);
end
grad = mzeros(psize,1);
grad2 = mzeros(psize,1);
ll = 0;
%forward prop:
%index transition takes place at nonlinearity
for chunk = 1:numchunks
y{chunk, 1} = store(indata(:, ((chunk-1)*sizechunk+1):(chunk*sizechunk) ));
yip1 = conv( y{chunk, 1} );
dEdW = cell(numlayers, 1);
dEdb = cell(numlayers, 1);
dEdW2 = cell(numlayers, 1);
dEdb2 = cell(numlayers, 1);
for i = 1:numlayers
yi = yip1;
yip1 = [];