forked from opencv/opencv
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcnn.cpp
More file actions
1675 lines (1361 loc) · 61.5 KB
/
cnn.cpp
File metadata and controls
1675 lines (1361 loc) · 61.5 KB
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
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of Intel Corporation may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#include "precomp.hpp"
#if 0
/****************************************************************************************\
* Auxilary functions declarations *
\****************************************************************************************/
/*---------------------- functions for the CNN classifier ------------------------------*/
static float icvCNNModelPredict(
const CvStatModel* cnn_model,
const CvMat* image,
CvMat* probs CV_DEFAULT(0) );
static void icvCNNModelUpdate(
CvStatModel* cnn_model, const CvMat* images, int tflag,
const CvMat* responses, const CvStatModelParams* params,
const CvMat* CV_DEFAULT(0), const CvMat* sample_idx CV_DEFAULT(0),
const CvMat* CV_DEFAULT(0), const CvMat* CV_DEFAULT(0));
static void icvCNNModelRelease( CvStatModel** cnn_model );
static void icvTrainCNNetwork( CvCNNetwork* network,
const float** images,
const CvMat* responses,
const CvMat* etalons,
int grad_estim_type,
int max_iter,
int start_iter );
/*------------------------- functions for the CNN network ------------------------------*/
static void icvCNNetworkAddLayer( CvCNNetwork* network, CvCNNLayer* layer );
static void icvCNNetworkRelease( CvCNNetwork** network );
/* In all layer functions we denote input by X and output by Y, where
X and Y are column-vectors, so that
length(X)==<n_input_planes>*<input_height>*<input_width>,
length(Y)==<n_output_planes>*<output_height>*<output_width>.
*/
/*------------------------ functions for convolutional layer ---------------------------*/
static void icvCNNConvolutionRelease( CvCNNLayer** p_layer );
static void icvCNNConvolutionForward( CvCNNLayer* layer, const CvMat* X, CvMat* Y );
static void icvCNNConvolutionBackward( CvCNNLayer* layer, int t,
const CvMat* X, const CvMat* dE_dY, CvMat* dE_dX );
/*------------------------ functions for sub-sampling layer ----------------------------*/
static void icvCNNSubSamplingRelease( CvCNNLayer** p_layer );
static void icvCNNSubSamplingForward( CvCNNLayer* layer, const CvMat* X, CvMat* Y );
static void icvCNNSubSamplingBackward( CvCNNLayer* layer, int t,
const CvMat* X, const CvMat* dE_dY, CvMat* dE_dX );
/*------------------------ functions for full connected layer --------------------------*/
static void icvCNNFullConnectRelease( CvCNNLayer** p_layer );
static void icvCNNFullConnectForward( CvCNNLayer* layer, const CvMat* X, CvMat* Y );
static void icvCNNFullConnectBackward( CvCNNLayer* layer, int,
const CvMat*, const CvMat* dE_dY, CvMat* dE_dX );
/****************************************************************************************\
* Functions implementations *
\****************************************************************************************/
#define ICV_CHECK_CNN_NETWORK(network) \
{ \
CvCNNLayer* first_layer, *layer, *last_layer; \
int n_layers, i; \
if( !network ) \
CV_ERROR( CV_StsNullPtr, \
"Null <network> pointer. Network must be created by user." ); \
n_layers = network->n_layers; \
first_layer = last_layer = network->layers; \
for( i = 0, layer = first_layer; i < n_layers && layer; i++ ) \
{ \
if( !ICV_IS_CNN_LAYER(layer) ) \
CV_ERROR( CV_StsNullPtr, "Invalid network" ); \
last_layer = layer; \
layer = layer->next_layer; \
} \
\
if( i == 0 || i != n_layers || first_layer->prev_layer || layer ) \
CV_ERROR( CV_StsNullPtr, "Invalid network" ); \
\
if( first_layer->n_input_planes != 1 ) \
CV_ERROR( CV_StsBadArg, "First layer must contain only one input plane" ); \
\
if( img_size != first_layer->input_height*first_layer->input_width ) \
CV_ERROR( CV_StsBadArg, "Invalid input sizes of the first layer" ); \
\
if( params->etalons->cols != last_layer->n_output_planes* \
last_layer->output_height*last_layer->output_width ) \
CV_ERROR( CV_StsBadArg, "Invalid output sizes of the last layer" ); \
}
#define ICV_CHECK_CNN_MODEL_PARAMS(params) \
{ \
if( !params ) \
CV_ERROR( CV_StsNullPtr, "Null <params> pointer" ); \
\
if( !ICV_IS_MAT_OF_TYPE(params->etalons, CV_32FC1) ) \
CV_ERROR( CV_StsBadArg, "<etalons> must be CV_32FC1 type" ); \
if( params->etalons->rows != cnn_model->cls_labels->cols ) \
CV_ERROR( CV_StsBadArg, "Invalid <etalons> size" ); \
\
if( params->grad_estim_type != CV_CNN_GRAD_ESTIM_RANDOM && \
params->grad_estim_type != CV_CNN_GRAD_ESTIM_BY_WORST_IMG ) \
CV_ERROR( CV_StsBadArg, "Invalid <grad_estim_type>" ); \
\
if( params->start_iter < 0 ) \
CV_ERROR( CV_StsBadArg, "Parameter <start_iter> must be positive or zero" ); \
\
if( params->max_iter < 1 ) \
params->max_iter = 1; \
}
/****************************************************************************************\
* Classifier functions *
\****************************************************************************************/
ML_IMPL CvStatModel*
cvTrainCNNClassifier( const CvMat* _train_data, int tflag,
const CvMat* _responses,
const CvStatModelParams* _params,
const CvMat*, const CvMat* _sample_idx, const CvMat*, const CvMat* )
{
CvCNNStatModel* cnn_model = 0;
const float** out_train_data = 0;
CvMat* responses = 0;
CV_FUNCNAME("cvTrainCNNClassifier");
__BEGIN__;
int n_images;
int img_size;
CvCNNStatModelParams* params = (CvCNNStatModelParams*)_params;
CV_CALL(cnn_model = (CvCNNStatModel*)cvCreateStatModel(
CV_STAT_MODEL_MAGIC_VAL|CV_CNN_MAGIC_VAL, sizeof(CvCNNStatModel),
icvCNNModelRelease, icvCNNModelPredict, icvCNNModelUpdate ));
CV_CALL(cvPrepareTrainData( "cvTrainCNNClassifier",
_train_data, tflag, _responses, CV_VAR_CATEGORICAL,
0, _sample_idx, false, &out_train_data,
&n_images, &img_size, &img_size, &responses,
&cnn_model->cls_labels, 0 ));
ICV_CHECK_CNN_MODEL_PARAMS(params);
ICV_CHECK_CNN_NETWORK(params->network);
cnn_model->network = params->network;
CV_CALL(cnn_model->etalons = (CvMat*)cvClone( params->etalons ));
CV_CALL( icvTrainCNNetwork( cnn_model->network, out_train_data, responses,
cnn_model->etalons, params->grad_estim_type, params->max_iter,
params->start_iter ));
__END__;
if( cvGetErrStatus() < 0 && cnn_model )
{
cnn_model->release( (CvStatModel**)&cnn_model );
}
cvFree( &out_train_data );
cvReleaseMat( &responses );
return (CvStatModel*)cnn_model;
}
/****************************************************************************************/
static void icvTrainCNNetwork( CvCNNetwork* network,
const float** images,
const CvMat* responses,
const CvMat* etalons,
int grad_estim_type,
int max_iter,
int start_iter )
{
CvMat** X = 0;
CvMat** dE_dX = 0;
const int n_layers = network->n_layers;
int k;
CV_FUNCNAME("icvTrainCNNetwork");
__BEGIN__;
CvCNNLayer* first_layer = network->layers;
const int img_height = first_layer->input_height;
const int img_width = first_layer->input_width;
const int img_size = img_width*img_height;
const int n_images = responses->cols;
CvMat image = cvMat( 1, img_size, CV_32FC1 );
CvCNNLayer* layer;
int n;
CvRNG rng = cvRNG(-1);
CV_CALL(X = (CvMat**)cvAlloc( (n_layers+1)*sizeof(CvMat*) ));
CV_CALL(dE_dX = (CvMat**)cvAlloc( (n_layers+1)*sizeof(CvMat*) ));
memset( X, 0, (n_layers+1)*sizeof(CvMat*) );
memset( dE_dX, 0, (n_layers+1)*sizeof(CvMat*) );
CV_CALL(X[0] = cvCreateMat( img_height*img_width,1,CV_32FC1 ));
CV_CALL(dE_dX[0] = cvCreateMat( 1, X[0]->rows, CV_32FC1 ));
for( k = 0, layer = first_layer; k < n_layers; k++, layer = layer->next_layer )
{
CV_CALL(X[k+1] = cvCreateMat( layer->n_output_planes*layer->output_height*
layer->output_width, 1, CV_32FC1 ));
CV_CALL(dE_dX[k+1] = cvCreateMat( 1, X[k+1]->rows, CV_32FC1 ));
}
for( n = 1; n <= max_iter; n++ )
{
float loss, max_loss = 0;
int i;
int worst_img_idx = -1;
int* right_etal_idx = responses->data.i;
CvMat etalon;
// Find the worst image (which produces the greatest loss) or use the random image
if( grad_estim_type == CV_CNN_GRAD_ESTIM_BY_WORST_IMG )
{
for( i = 0; i < n_images; i++, right_etal_idx++ )
{
image.data.fl = (float*)images[i];
cvTranspose( &image, X[0] );
for( k = 0, layer = first_layer; k < n_layers; k++, layer = layer->next_layer )
CV_CALL(layer->forward( layer, X[k], X[k+1] ));
cvTranspose( X[n_layers], dE_dX[n_layers] );
cvGetRow( etalons, &etalon, *right_etal_idx );
loss = (float)cvNorm( dE_dX[n_layers], &etalon );
if( loss > max_loss )
{
max_loss = loss;
worst_img_idx = i;
}
}
}
else
worst_img_idx = cvRandInt(&rng) % n_images;
// Train network on the worst image
// 1) Compute the network output on the <image>
image.data.fl = (float*)images[worst_img_idx];
CV_CALL(cvTranspose( &image, X[0] ));
for( k = 0, layer = first_layer; k < n_layers - 1; k++, layer = layer->next_layer )
CV_CALL(layer->forward( layer, X[k], X[k+1] ));
CV_CALL(layer->forward( layer, X[k], X[k+1] ));
// 2) Compute the gradient
cvTranspose( X[n_layers], dE_dX[n_layers] );
cvGetRow( etalons, &etalon, responses->data.i[worst_img_idx] );
cvSub( dE_dX[n_layers], &etalon, dE_dX[n_layers] );
// 3) Update weights by the gradient descent
for( k = n_layers; k > 0; k--, layer = layer->prev_layer )
CV_CALL(layer->backward( layer, n + start_iter, X[k-1], dE_dX[k], dE_dX[k-1] ));
}
__END__;
for( k = 0; k <= n_layers; k++ )
{
cvReleaseMat( &X[k] );
cvReleaseMat( &dE_dX[k] );
}
cvFree( &X );
cvFree( &dE_dX );
}
/****************************************************************************************/
static float icvCNNModelPredict( const CvStatModel* model,
const CvMat* _image,
CvMat* probs )
{
CvMat** X = 0;
float* img_data = 0;
int n_layers = 0;
int best_etal_idx = -1;
int k;
CV_FUNCNAME("icvCNNModelPredict");
__BEGIN__;
CvCNNStatModel* cnn_model = (CvCNNStatModel*)model;
CvCNNLayer* first_layer, *layer = 0;
int img_height, img_width, img_size;
int nclasses, i;
float loss, min_loss = FLT_MAX;
float* probs_data;
CvMat etalon, image;
if( !CV_IS_CNN(model) )
CV_ERROR( CV_StsBadArg, "Invalid model" );
nclasses = cnn_model->cls_labels->cols;
n_layers = cnn_model->network->n_layers;
first_layer = cnn_model->network->layers;
img_height = first_layer->input_height;
img_width = first_layer->input_width;
img_size = img_height*img_width;
cvPreparePredictData( _image, img_size, 0, nclasses, probs, &img_data );
CV_CALL(X = (CvMat**)cvAlloc( (n_layers+1)*sizeof(CvMat*) ));
memset( X, 0, (n_layers+1)*sizeof(CvMat*) );
CV_CALL(X[0] = cvCreateMat( img_size,1,CV_32FC1 ));
for( k = 0, layer = first_layer; k < n_layers; k++, layer = layer->next_layer )
{
CV_CALL(X[k+1] = cvCreateMat( layer->n_output_planes*layer->output_height*
layer->output_width, 1, CV_32FC1 ));
}
image = cvMat( 1, img_size, CV_32FC1, img_data );
cvTranspose( &image, X[0] );
for( k = 0, layer = first_layer; k < n_layers; k++, layer = layer->next_layer )
CV_CALL(layer->forward( layer, X[k], X[k+1] ));
probs_data = probs ? probs->data.fl : 0;
etalon = cvMat( cnn_model->etalons->cols, 1, CV_32FC1, cnn_model->etalons->data.fl );
for( i = 0; i < nclasses; i++, etalon.data.fl += cnn_model->etalons->cols )
{
loss = (float)cvNorm( X[n_layers], &etalon );
if( loss < min_loss )
{
min_loss = loss;
best_etal_idx = i;
}
if( probs )
*probs_data++ = -loss;
}
if( probs )
{
cvExp( probs, probs );
CvScalar sum = cvSum( probs );
cvConvertScale( probs, probs, 1./sum.val[0] );
}
__END__;
for( k = 0; k <= n_layers; k++ )
cvReleaseMat( &X[k] );
cvFree( &X );
if( img_data != _image->data.fl )
cvFree( &img_data );
return ((float) ((CvCNNStatModel*)model)->cls_labels->data.i[best_etal_idx]);
}
/****************************************************************************************/
static void icvCNNModelUpdate(
CvStatModel* _cnn_model, const CvMat* _train_data, int tflag,
const CvMat* _responses, const CvStatModelParams* _params,
const CvMat*, const CvMat* _sample_idx,
const CvMat*, const CvMat* )
{
const float** out_train_data = 0;
CvMat* responses = 0;
CvMat* cls_labels = 0;
CV_FUNCNAME("icvCNNModelUpdate");
__BEGIN__;
int n_images, img_size, i;
CvCNNStatModelParams* params = (CvCNNStatModelParams*)_params;
CvCNNStatModel* cnn_model = (CvCNNStatModel*)_cnn_model;
if( !CV_IS_CNN(cnn_model) )
CV_ERROR( CV_StsBadArg, "Invalid model" );
CV_CALL(cvPrepareTrainData( "cvTrainCNNClassifier",
_train_data, tflag, _responses, CV_VAR_CATEGORICAL,
0, _sample_idx, false, &out_train_data,
&n_images, &img_size, &img_size, &responses,
&cls_labels, 0, 0 ));
ICV_CHECK_CNN_MODEL_PARAMS(params);
// Number of classes must be the same as when classifiers was created
if( !CV_ARE_SIZES_EQ(cls_labels, cnn_model->cls_labels) )
CV_ERROR( CV_StsBadArg, "Number of classes must be left unchanged" );
for( i = 0; i < cls_labels->cols; i++ )
{
if( cls_labels->data.i[i] != cnn_model->cls_labels->data.i[i] )
CV_ERROR( CV_StsBadArg, "Number of classes must be left unchanged" );
}
CV_CALL( icvTrainCNNetwork( cnn_model->network, out_train_data, responses,
cnn_model->etalons, params->grad_estim_type, params->max_iter,
params->start_iter ));
__END__;
cvFree( &out_train_data );
cvReleaseMat( &responses );
}
/****************************************************************************************/
static void icvCNNModelRelease( CvStatModel** cnn_model )
{
CV_FUNCNAME("icvCNNModelRelease");
__BEGIN__;
CvCNNStatModel* cnn;
if( !cnn_model )
CV_ERROR( CV_StsNullPtr, "Null double pointer" );
cnn = *(CvCNNStatModel**)cnn_model;
cvReleaseMat( &cnn->cls_labels );
cvReleaseMat( &cnn->etalons );
cnn->network->release( &cnn->network );
cvFree( &cnn );
__END__;
}
/****************************************************************************************\
* Network functions *
\****************************************************************************************/
ML_IMPL CvCNNetwork* cvCreateCNNetwork( CvCNNLayer* first_layer )
{
CvCNNetwork* network = 0;
CV_FUNCNAME( "cvCreateCNNetwork" );
__BEGIN__;
if( !ICV_IS_CNN_LAYER(first_layer) )
CV_ERROR( CV_StsBadArg, "Invalid layer" );
CV_CALL(network = (CvCNNetwork*)cvAlloc( sizeof(CvCNNetwork) ));
memset( network, 0, sizeof(CvCNNetwork) );
network->layers = first_layer;
network->n_layers = 1;
network->release = icvCNNetworkRelease;
network->add_layer = icvCNNetworkAddLayer;
__END__;
if( cvGetErrStatus() < 0 && network )
cvFree( &network );
return network;
}
/****************************************************************************************/
static void icvCNNetworkAddLayer( CvCNNetwork* network, CvCNNLayer* layer )
{
CV_FUNCNAME( "icvCNNetworkAddLayer" );
__BEGIN__;
CvCNNLayer* prev_layer;
if( network == NULL )
CV_ERROR( CV_StsNullPtr, "Null <network> pointer" );
prev_layer = network->layers;
while( prev_layer->next_layer )
prev_layer = prev_layer->next_layer;
if( ICV_IS_CNN_FULLCONNECT_LAYER(layer) )
{
if( layer->n_input_planes != prev_layer->output_width*prev_layer->output_height*
prev_layer->n_output_planes )
CV_ERROR( CV_StsBadArg, "Unmatched size of the new layer" );
if( layer->input_height != 1 || layer->output_height != 1 ||
layer->input_width != 1 || layer->output_width != 1 )
CV_ERROR( CV_StsBadArg, "Invalid size of the new layer" );
}
else if( ICV_IS_CNN_CONVOLUTION_LAYER(layer) || ICV_IS_CNN_SUBSAMPLING_LAYER(layer) )
{
if( prev_layer->n_output_planes != layer->n_input_planes ||
prev_layer->output_height != layer->input_height ||
prev_layer->output_width != layer->input_width )
CV_ERROR( CV_StsBadArg, "Unmatched size of the new layer" );
}
else
CV_ERROR( CV_StsBadArg, "Invalid layer" );
layer->prev_layer = prev_layer;
prev_layer->next_layer = layer;
network->n_layers++;
__END__;
}
/****************************************************************************************/
static void icvCNNetworkRelease( CvCNNetwork** network_pptr )
{
CV_FUNCNAME( "icvReleaseCNNetwork" );
__BEGIN__;
CvCNNetwork* network = 0;
CvCNNLayer* layer = 0, *next_layer = 0;
int k;
if( network_pptr == NULL )
CV_ERROR( CV_StsBadArg, "Null double pointer" );
if( *network_pptr == NULL )
return;
network = *network_pptr;
layer = network->layers;
if( layer == NULL )
CV_ERROR( CV_StsBadArg, "CNN is empty (does not contain any layer)" );
// k is the number of the layer to be deleted
for( k = 0; k < network->n_layers && layer; k++ )
{
next_layer = layer->next_layer;
layer->release( &layer );
layer = next_layer;
}
if( k != network->n_layers || layer)
CV_ERROR( CV_StsBadArg, "Invalid network" );
cvFree( &network );
__END__;
}
/****************************************************************************************\
* Layer functions *
\****************************************************************************************/
static CvCNNLayer* icvCreateCNNLayer( int layer_type, int header_size,
int n_input_planes, int input_height, int input_width,
int n_output_planes, int output_height, int output_width,
float init_learn_rate, int learn_rate_decrease_type,
CvCNNLayerRelease release, CvCNNLayerForward forward, CvCNNLayerBackward backward )
{
CvCNNLayer* layer = 0;
CV_FUNCNAME("icvCreateCNNLayer");
__BEGIN__;
CV_ASSERT( release && forward && backward )
CV_ASSERT( header_size >= sizeof(CvCNNLayer) )
if( n_input_planes < 1 || n_output_planes < 1 ||
input_height < 1 || input_width < 1 ||
output_height < 1 || output_width < 1 ||
input_height < output_height ||
input_width < output_width )
CV_ERROR( CV_StsBadArg, "Incorrect input or output parameters" );
if( init_learn_rate < FLT_EPSILON )
CV_ERROR( CV_StsBadArg, "Initial learning rate must be positive" );
if( learn_rate_decrease_type != CV_CNN_LEARN_RATE_DECREASE_HYPERBOLICALLY &&
learn_rate_decrease_type != CV_CNN_LEARN_RATE_DECREASE_SQRT_INV &&
learn_rate_decrease_type != CV_CNN_LEARN_RATE_DECREASE_LOG_INV )
CV_ERROR( CV_StsBadArg, "Invalid type of learning rate dynamics" );
CV_CALL(layer = (CvCNNLayer*)cvAlloc( header_size ));
memset( layer, 0, header_size );
layer->flags = ICV_CNN_LAYER|layer_type;
CV_ASSERT( ICV_IS_CNN_LAYER(layer) )
layer->n_input_planes = n_input_planes;
layer->input_height = input_height;
layer->input_width = input_width;
layer->n_output_planes = n_output_planes;
layer->output_height = output_height;
layer->output_width = output_width;
layer->init_learn_rate = init_learn_rate;
layer->learn_rate_decrease_type = learn_rate_decrease_type;
layer->release = release;
layer->forward = forward;
layer->backward = backward;
__END__;
if( cvGetErrStatus() < 0 && layer)
cvFree( &layer );
return layer;
}
/****************************************************************************************/
ML_IMPL CvCNNLayer* cvCreateCNNConvolutionLayer(
int n_input_planes, int input_height, int input_width,
int n_output_planes, int K,
float init_learn_rate, int learn_rate_decrease_type,
CvMat* connect_mask, CvMat* weights )
{
CvCNNConvolutionLayer* layer = 0;
CV_FUNCNAME("cvCreateCNNConvolutionLayer");
__BEGIN__;
const int output_height = input_height - K + 1;
const int output_width = input_width - K + 1;
if( K < 1 || init_learn_rate <= 0 )
CV_ERROR( CV_StsBadArg, "Incorrect parameters" );
CV_CALL(layer = (CvCNNConvolutionLayer*)icvCreateCNNLayer( ICV_CNN_CONVOLUTION_LAYER,
sizeof(CvCNNConvolutionLayer), n_input_planes, input_height, input_width,
n_output_planes, output_height, output_width,
init_learn_rate, learn_rate_decrease_type,
icvCNNConvolutionRelease, icvCNNConvolutionForward, icvCNNConvolutionBackward ));
layer->K = K;
CV_CALL(layer->weights = cvCreateMat( n_output_planes, K*K+1, CV_32FC1 ));
CV_CALL(layer->connect_mask = cvCreateMat( n_output_planes, n_input_planes, CV_8UC1));
if( weights )
{
if( !ICV_IS_MAT_OF_TYPE( weights, CV_32FC1 ) )
CV_ERROR( CV_StsBadSize, "Type of initial weights matrix must be CV_32FC1" );
if( !CV_ARE_SIZES_EQ( weights, layer->weights ) )
CV_ERROR( CV_StsBadSize, "Invalid size of initial weights matrix" );
CV_CALL(cvCopy( weights, layer->weights ));
}
else
{
CvRNG rng = cvRNG( 0xFFFFFFFF );
cvRandArr( &rng, layer->weights, CV_RAND_UNI, cvRealScalar(-1), cvRealScalar(1) );
}
if( connect_mask )
{
if( !ICV_IS_MAT_OF_TYPE( connect_mask, CV_8UC1 ) )
CV_ERROR( CV_StsBadSize, "Type of connection matrix must be CV_32FC1" );
if( !CV_ARE_SIZES_EQ( connect_mask, layer->connect_mask ) )
CV_ERROR( CV_StsBadSize, "Invalid size of connection matrix" );
CV_CALL(cvCopy( connect_mask, layer->connect_mask ));
}
else
CV_CALL(cvSet( layer->connect_mask, cvRealScalar(1) ));
__END__;
if( cvGetErrStatus() < 0 && layer )
{
cvReleaseMat( &layer->weights );
cvReleaseMat( &layer->connect_mask );
cvFree( &layer );
}
return (CvCNNLayer*)layer;
}
/****************************************************************************************/
ML_IMPL CvCNNLayer* cvCreateCNNSubSamplingLayer(
int n_input_planes, int input_height, int input_width,
int sub_samp_scale, float a, float s,
float init_learn_rate, int learn_rate_decrease_type, CvMat* weights )
{
CvCNNSubSamplingLayer* layer = 0;
CV_FUNCNAME("cvCreateCNNSubSamplingLayer");
__BEGIN__;
const int output_height = input_height/sub_samp_scale;
const int output_width = input_width/sub_samp_scale;
const int n_output_planes = n_input_planes;
if( sub_samp_scale < 1 || a <= 0 || s <= 0)
CV_ERROR( CV_StsBadArg, "Incorrect parameters" );
CV_CALL(layer = (CvCNNSubSamplingLayer*)icvCreateCNNLayer( ICV_CNN_SUBSAMPLING_LAYER,
sizeof(CvCNNSubSamplingLayer), n_input_planes, input_height, input_width,
n_output_planes, output_height, output_width,
init_learn_rate, learn_rate_decrease_type,
icvCNNSubSamplingRelease, icvCNNSubSamplingForward, icvCNNSubSamplingBackward ));
layer->sub_samp_scale = sub_samp_scale;
layer->a = a;
layer->s = s;
CV_CALL(layer->sumX =
cvCreateMat( n_output_planes*output_width*output_height, 1, CV_32FC1 ));
CV_CALL(layer->exp2ssumWX =
cvCreateMat( n_output_planes*output_width*output_height, 1, CV_32FC1 ));
cvZero( layer->sumX );
cvZero( layer->exp2ssumWX );
CV_CALL(layer->weights = cvCreateMat( n_output_planes, 2, CV_32FC1 ));
if( weights )
{
if( !ICV_IS_MAT_OF_TYPE( weights, CV_32FC1 ) )
CV_ERROR( CV_StsBadSize, "Type of initial weights matrix must be CV_32FC1" );
if( !CV_ARE_SIZES_EQ( weights, layer->weights ) )
CV_ERROR( CV_StsBadSize, "Invalid size of initial weights matrix" );
CV_CALL(cvCopy( weights, layer->weights ));
}
else
{
CvRNG rng = cvRNG( 0xFFFFFFFF );
cvRandArr( &rng, layer->weights, CV_RAND_UNI, cvRealScalar(-1), cvRealScalar(1) );
}
__END__;
if( cvGetErrStatus() < 0 && layer )
{
cvReleaseMat( &layer->exp2ssumWX );
cvFree( &layer );
}
return (CvCNNLayer*)layer;
}
/****************************************************************************************/
ML_IMPL CvCNNLayer* cvCreateCNNFullConnectLayer(
int n_inputs, int n_outputs, float a, float s,
float init_learn_rate, int learn_rate_decrease_type, CvMat* weights )
{
CvCNNFullConnectLayer* layer = 0;
CV_FUNCNAME("cvCreateCNNFullConnectLayer");
__BEGIN__;
if( a <= 0 || s <= 0 || init_learn_rate <= 0)
CV_ERROR( CV_StsBadArg, "Incorrect parameters" );
CV_CALL(layer = (CvCNNFullConnectLayer*)icvCreateCNNLayer( ICV_CNN_FULLCONNECT_LAYER,
sizeof(CvCNNFullConnectLayer), n_inputs, 1, 1, n_outputs, 1, 1,
init_learn_rate, learn_rate_decrease_type,
icvCNNFullConnectRelease, icvCNNFullConnectForward, icvCNNFullConnectBackward ));
layer->a = a;
layer->s = s;
CV_CALL(layer->exp2ssumWX = cvCreateMat( n_outputs, 1, CV_32FC1 ));
cvZero( layer->exp2ssumWX );
CV_CALL(layer->weights = cvCreateMat( n_outputs, n_inputs+1, CV_32FC1 ));
if( weights )
{
if( !ICV_IS_MAT_OF_TYPE( weights, CV_32FC1 ) )
CV_ERROR( CV_StsBadSize, "Type of initial weights matrix must be CV_32FC1" );
if( !CV_ARE_SIZES_EQ( weights, layer->weights ) )
CV_ERROR( CV_StsBadSize, "Invalid size of initial weights matrix" );
CV_CALL(cvCopy( weights, layer->weights ));
}
else
{
CvRNG rng = cvRNG( 0xFFFFFFFF );
cvRandArr( &rng, layer->weights, CV_RAND_UNI, cvRealScalar(-1), cvRealScalar(1) );
}
__END__;
if( cvGetErrStatus() < 0 && layer )
{
cvReleaseMat( &layer->exp2ssumWX );
cvReleaseMat( &layer->weights );
cvFree( &layer );
}
return (CvCNNLayer*)layer;
}
/****************************************************************************************\
* Layer FORWARD functions *
\****************************************************************************************/
static void icvCNNConvolutionForward( CvCNNLayer* _layer,
const CvMat* X,
CvMat* Y )
{
CV_FUNCNAME("icvCNNConvolutionForward");
if( !ICV_IS_CNN_CONVOLUTION_LAYER(_layer) )
CV_ERROR( CV_StsBadArg, "Invalid layer" );
{__BEGIN__;
const CvCNNConvolutionLayer* layer = (CvCNNConvolutionLayer*) _layer;
const int K = layer->K;
const int n_weights_for_Yplane = K*K + 1;
const int nXplanes = layer->n_input_planes;
const int Xheight = layer->input_height;
const int Xwidth = layer->input_width ;
const int Xsize = Xwidth*Xheight;
const int nYplanes = layer->n_output_planes;
const int Yheight = layer->output_height;
const int Ywidth = layer->output_width;
const int Ysize = Ywidth*Yheight;
int xx, yy, ni, no, kx, ky;
float *Yplane = 0, *Xplane = 0, *w = 0;
uchar* connect_mask_data = 0;
CV_ASSERT( X->rows == nXplanes*Xsize && X->cols == 1 );
CV_ASSERT( Y->rows == nYplanes*Ysize && Y->cols == 1 );
cvSetZero( Y );
Yplane = Y->data.fl;
connect_mask_data = layer->connect_mask->data.ptr;
w = layer->weights->data.fl;
for( no = 0; no < nYplanes; no++, Yplane += Ysize, w += n_weights_for_Yplane )
{
Xplane = X->data.fl;
for( ni = 0; ni < nXplanes; ni++, Xplane += Xsize, connect_mask_data++ )
{
if( *connect_mask_data )
{
float* Yelem = Yplane;
// Xheight-K+1 == Yheight && Xwidth-K+1 == Ywidth
for( yy = 0; yy < Xheight-K+1; yy++ )
{
for( xx = 0; xx < Xwidth-K+1; xx++, Yelem++ )
{
float* templ = Xplane+yy*Xwidth+xx;
float WX = 0;
for( ky = 0; ky < K; ky++, templ += Xwidth-K )
{
for( kx = 0; kx < K; kx++, templ++ )
{
WX += *templ*w[ky*K+kx];
}
}
*Yelem += WX + w[K*K];
}
}
}
}
}
}__END__;
}
/****************************************************************************************/
static void icvCNNSubSamplingForward( CvCNNLayer* _layer,
const CvMat* X,
CvMat* Y )
{
CV_FUNCNAME("icvCNNSubSamplingForward");
if( !ICV_IS_CNN_SUBSAMPLING_LAYER(_layer) )
CV_ERROR( CV_StsBadArg, "Invalid layer" );
{__BEGIN__;
const CvCNNSubSamplingLayer* layer = (CvCNNSubSamplingLayer*) _layer;
const int sub_sampl_scale = layer->sub_samp_scale;
const int nplanes = layer->n_input_planes;
const int Xheight = layer->input_height;
const int Xwidth = layer->input_width ;
const int Xsize = Xwidth*Xheight;
const int Yheight = layer->output_height;
const int Ywidth = layer->output_width;
const int Ysize = Ywidth*Yheight;
int xx, yy, ni, kx, ky;
float* sumX_data = 0, *w = 0;
CvMat sumX_sub_col, exp2ssumWX_sub_col;
CV_ASSERT(X->rows == nplanes*Xsize && X->cols == 1);
CV_ASSERT(layer->exp2ssumWX->cols == 1 && layer->exp2ssumWX->rows == nplanes*Ysize);
// update inner variable layer->exp2ssumWX, which will be used in back-progation
cvZero( layer->sumX );
cvZero( layer->exp2ssumWX );
for( ky = 0; ky < sub_sampl_scale; ky++ )
for( kx = 0; kx < sub_sampl_scale; kx++ )
{
float* Xplane = X->data.fl;
sumX_data = layer->sumX->data.fl;
for( ni = 0; ni < nplanes; ni++, Xplane += Xsize )
{
for( yy = 0; yy < Yheight; yy++ )
for( xx = 0; xx < Ywidth; xx++, sumX_data++ )
*sumX_data += Xplane[((yy+ky)*Xwidth+(xx+kx))];
}
}
w = layer->weights->data.fl;
cvGetRows( layer->sumX, &sumX_sub_col, 0, Ysize );
cvGetRows( layer->exp2ssumWX, &exp2ssumWX_sub_col, 0, Ysize );
for( ni = 0; ni < nplanes; ni++, w += 2 )
{
CV_CALL(cvConvertScale( &sumX_sub_col, &exp2ssumWX_sub_col, w[0], w[1] ));
sumX_sub_col.data.fl += Ysize;
exp2ssumWX_sub_col.data.fl += Ysize;
}
CV_CALL(cvScale( layer->exp2ssumWX, layer->exp2ssumWX, 2.0*layer->s ));
CV_CALL(cvExp( layer->exp2ssumWX, layer->exp2ssumWX ));
CV_CALL(cvMinS( layer->exp2ssumWX, FLT_MAX, layer->exp2ssumWX ));
//#ifdef _DEBUG
{
float* exp2ssumWX_data = layer->exp2ssumWX->data.fl;
for( ni = 0; ni < layer->exp2ssumWX->rows; ni++, exp2ssumWX_data++ )
{
if( *exp2ssumWX_data == FLT_MAX )
cvSetErrStatus( 1 );
}
}
//#endif
// compute the output variable Y == ( a - 2a/(layer->exp2ssumWX + 1))
CV_CALL(cvAddS( layer->exp2ssumWX, cvRealScalar(1), Y ));
CV_CALL(cvDiv( 0, Y, Y, -2.0*layer->a ));
CV_CALL(cvAddS( Y, cvRealScalar(layer->a), Y ));
}__END__;
}
/****************************************************************************************/
static void icvCNNFullConnectForward( CvCNNLayer* _layer, const CvMat* X, CvMat* Y )
{
CV_FUNCNAME("icvCNNFullConnectForward");
if( !ICV_IS_CNN_FULLCONNECT_LAYER(_layer) )
CV_ERROR( CV_StsBadArg, "Invalid layer" );
{__BEGIN__;
const CvCNNFullConnectLayer* layer = (CvCNNFullConnectLayer*)_layer;
CvMat* weights = layer->weights;
CvMat sub_weights, bias;
CV_ASSERT(X->cols == 1 && X->rows == layer->n_input_planes);
CV_ASSERT(Y->cols == 1 && Y->rows == layer->n_output_planes);
CV_CALL(cvGetSubRect( weights, &sub_weights,
cvRect(0, 0, weights->cols-1, weights->rows )));
CV_CALL(cvGetCol( weights, &bias, weights->cols-1));
// update inner variable layer->exp2ssumWX, which will be used in Back-Propagation
CV_CALL(cvGEMM( &sub_weights, X, 2*layer->s, &bias, 2*layer->s, layer->exp2ssumWX ));
CV_CALL(cvExp( layer->exp2ssumWX, layer->exp2ssumWX ));
CV_CALL(cvMinS( layer->exp2ssumWX, FLT_MAX, layer->exp2ssumWX ));
//#ifdef _DEBUG
{
float* exp2ssumWX_data = layer->exp2ssumWX->data.fl;
int i;
for( i = 0; i < layer->exp2ssumWX->rows; i++, exp2ssumWX_data++ )
{
if( *exp2ssumWX_data == FLT_MAX )
cvSetErrStatus( 1 );
}
}
//#endif
// compute the output variable Y == ( a - 2a/(layer->exp2ssumWX + 1))