-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathCNN.c
4136 lines (4005 loc) · 158 KB
/
CNN.c
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
/**********************************************************************************/
/* Copyright (c) 2018, Christopher Deotte */
/* */
/* 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. */
/**********************************************************************************/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/stat.h>
#include<unistd.h>
#include<dirent.h>
#include<math.h>
#include<time.h>
#include<pthread.h>
/* WEBGUI External Routines needed from webgui.c */
/* (These could be placed into a webgui.h) */
int webstart(int x);
void webreadline(char* str);
void webwriteline(char* str);
void webinit(char* str,int x);
void webupdate(int* ip, double* rp, char* sp);
void websettitle(char* str);
void websetmode(int x);
void webstop();
void websetcolors(int nc, double* r,double* g,double* b,int pane);
void webimagedisplay(int nx, int ny, int* image, int ipane);
void webframe(int frame);
void weblineflt(float* x, float* y, float* z, int n, int color);
void webfillflt(float* x, float* y, float* z, int n, int color);
void weblinedbl(double* x, double* y, double* z, int n, int color);
void webfilldbl(double* x, double* y, double* z, int n, int icolor);
void webgldisplay(int pane);
int webquery();
void webbutton(int highlight,char* cmd);
void webpause();
unsigned long fsize(char* file);
/* WEBGUI Internal Routines and Variables */
/* general routines for any program using webgui.c */
void initParameterMap(char* str, int n);
char* extractVal(char* str, char key);
char processCommand(char* str);
void updateParameter(char* str, int index1, int index2);
char arrayGet(char* key);
int ipGet(char* key);
void ipSet(char* key, int value);
double rpGet(char* key);
void rpSet(char* key, double value);
char* spGet(char* key);
void spSet(char* key, char* value);
/* general variables for any program using webgui.c */
int ct=0;
char** map_keys;
int* map_indices;
char* map_array;
double *rp_default, *rp;
int *ip_default, *ip;
char *sp_default, *sp;
char buffer[80];
/* Program Specific Routines */
/* Organized by category. (These functions */
/* could be placed in 10 different C files.) */
// LOAD DATA
int loadTrain(int ct, double testProp, int sh, float imgScale, float imgBias);
int loadTest(int ct, int sh, int rc, float imgScale, float imgBias);
// DISPLAY DATA
void displayDigit(int x, int ct, int p, int lay, int chan, int train, int cfy, int big);
void displayDigits(int *dgs, int ct, int pane, int train, int cfy, int wd, int big);
void doAugment(int img, int big, int t);
void viewAugment(int img, int ct, float rat, int r, float sc, int dx, int dy, int p, int big, int t, int cfy);
void printDigit(int a,int b,int *canvas,int m,int n,float *digit,int row,int col,int d3,int d1,int d2);
void printInt(int a,int b,int *canvas,int m,int n,int num,int col,int d1);
void printStr(int a,int b,int *canvas,int m,int n,char *str,int col,int d1);
// ADVANCED DISPLAY
void displayFilter(int ct, int p, int lay, int chan);
void displayFilter2(int ct, int p, int lay, int chan);
void maxActivations(int ct, int p, int lay, int chan, int t, int x);
void maxActivations2(int ct, int p, int lay, int chan, int t, int x);
void maxActivations3(int ct, int p, int lay, int chan, int train, int x);
void drawBorders(int lay, int chan, int *idxA, int *idxB, int ct);
void fakeHeap3(float *dist,int *idx, int *idxA, int *idxB, int k);
void sortHeap3(float *dist, int *idx, int *idxA, int *idxB, int k);
void setColors();
void setColors2();
void setColors3();
// DISPLAY PROGRESS
void displayConfusion(int (*confusion)[10]);
void displayCDigits(int x,int y);
void displayEntropy(float *ents, int entSize, float *ents2, int display);
void displayAccuracy(float *accs, int accSize,float *accs2, int display);
void line(int* img, int m, int n,float x1, float y1, float x2, float y2,int d,int c);
// DISPLAY DOTS
void clearImage(int p);
void updateImage();
void displayClassify(int dd);
void displayClassify3D();
void setColors4();
void placeDots();
void removeDot(float x, float y);
// INIT-NET
void initNet(int t);
void initArch(char *str, int x);
// NEURAL-NET
int isDigits(int init);
void randomizeTrainSet();
void dataAugment(int img, int r, float sc, float dx, float dy, int p, int hiRes, int loRes, int t);
void *runBackProp(void *arg);
int backProp(int x,float *ent, int ep);
int forwardProp(int x, int dp, int train, int lay);
float ReLU(float x);
float TanH(float x);
// KNN
void *runKNN(void *arg);
int singleKNN(int x, int k, int d, int p, int train, int big, int disp);
void fakeHeap(float *dist,int *idx,int k);
void sortHeap(float *dist,int *idx,int k);
float distance(float *digitA, float *digitB, int n, int x);
// PREDICT
void *predictKNN(void *arg);
void writePredictFile(int NN, int k, int d, int y, int big);
void writeFile();
// SPECIAL AND/OR DEBUG
void dreamProp(int y, int it, float bs, float ft, int ds, int lay, int chan, int p);
void dream(int x, int y, int it, float bs, float ft, int ds, int lay, int chan, int p);
int heatmap(int x, int t, int p, int wd);
void boundingBoxes();
void initData(int z);
void displayWeights();
void writeFile2();
float square(float x);
/* Program Specific Variables */
// MENU CREATION ARRAY
// (explained in webgui.c user manual)
//
const int lines = 218;
char init[218][80]={
"c c=Load, k=l",
"c c=Display, k=p",
"c c=Init-Net, k=i",
"c c=Activation, k=a",
"c c=DropOut, k=o",
"c c=DataAugment, k=d",
"c c=Train-Net, k=b",
"c c=Find-kNN, k=g",
"c c=Validate-kNN, k=k",
"c c=STOP, k=t",
"c c=Predict, k=w",
"c c=QUIT, k=q",
"c c=DotColor, k=s",
"c c=ClearPane3, k=c",
"c c=DotRemoveMode, k=r",
"c c=DotLowResMode, k=u",
"c c=Dot3dMode, k=h",
// Special features and/or debugging
// "c c=Dream, k=e",
// "c c=Heatmap, k=f",
// "c c=BoundingBoxes, k=j",
// "c c=InitImage, k=n",
// "c c=SaveImage, k=v",
// "c c=DisplayWeights, k=y",
// "c c=WriteWeights, k=z",
"n n=x, t=i, i=1, d=0",
"n n=epochs, t=i, i=2, d=100000",
"n n=learn, t=r, i=1, d=0.01",
"n n=color, t=i, i=3, d=0",
"n n=displayFreq, t=i, i=4, d=1",
"n n=net, t=i, i=5, d=3",
"n n=type, t=i, i=6, d=1",
"n n=rows, t=i, i=7, d=0",
"n n=k, t=i, i=8, d=5",
"n n=pane, t=i, i=9, d=3",
"n n=ratioD, t=r, i=2, d=0.0",
"n n=it, t=i, i=11, d=10",
"n n=blur, t=r, i=3, d=2.0",
"n n=y, t=i, i=12, d=0",
"n n=true, t=i, i=13, d=5",
"n n=predict, t=i, i=14, d=3",
"n n=norm, t=i, i=15, d=2",
"n n=count, t=i, i=16, d=54",
"n n=L0, t=s, i=1, d=0",
"n n=L1, t=s, i=2, d=0",
"n n=L2, t=s, i=3, d=0",
"n n=L3, t=s, i=4, d=0",
"n n=L4, t=s, i=5, d=0",
"n n=L5, t=s, i=6, d=0",
"n n=L6, t=s, i=7, d=2",
"n n=L7, t=s, i=8, d=20",
"n n=L8, t=s, i=9, d=20",
"n n=L9, t=s, i=10, d=6",
"n n=x2, t=i, i=17, d=43000",
"n n=mode, t=i, i=18, d=4",
"n n=validRatio, t=r, i=4, d=0.25",
"n n=trainSet, t=i, i=19, d=1",
"n n=NN, t=i, i=20, d=1",
"n n=big, t=i, i=21, d=1",
"n n=maxY, t=r, i=5, d=1.0",
"n n=minY, t=r, i=6, d=0.9",
"n n=displayFreq2, t=i, i=22, d=100",
"n n=angle, t=i, i=23, d=13",
"n n=layer, t=i, i=26, d=0",
"n n=channel, t=i, i=27, d=0",
"n n=z, t=i, i=28, d=1",
"n n=removeHeader, t=i, i=29, d=1",
"n n=dataFile, t=f, i=11, d=train.csv",
"n n=decay, t=r, i=7, d=0.95",
"n n=divideBy, t=r, i=8, d=255.0",
"n n=subtractBy, t=r, i=9, d=0.0",
"n n=classify, t=i, i=30, d=0",
"n n=scaleWeights, t=r, i=10, d=1.414",
"n n=scale, t=r, i=11, d=0.13",
"n n=conv, t=i, i=31, d=0",
"n n=pool, t=i, i=32, d=1",
"n n=dense, t=i, i=33, d=1",
"n n=ratioA, t=r, i=12, d=1.0",
"n n=col1Name, t=s, i=12, d=ImageId",
"n n=col2Name, t=s, i=13, d=Label",
"n n=row1Num, t=i, i=34, d=1",
"n n=fileName, t=s, i=14, d=submit.csv",
"n n=augment, t=i, i=35, d=0",
"n n=removeCol1, t=i, i=36, d=0",
"n n=xshift, t=r, i=13, d=2.8",
"n n=yshift, t=r, i=14, d=2.8",
"n n=flatten, t=r, i=15, d=1.0",
"n n=filterWidth, t=i, i=37, d=5",
"n n=colorize, t=i, i=38, d=0",
"n n=displayFreq3, t=i, i=39, d=2",
"r c=Heatmap, n=trainSet",
"r c=Heatmap, n=x",
"r c=Heatmap, n=filterWidth",
"r c=Heatmap, n=pane",
"r c=InitData, n=z",
"r c=NNpredict, n=trainSet",
"r c=NNpredict, n=x",
"r c=Dream, n=x",
"r c=Dream, n=y",
"r c=Dream, n=it",
"r c=Dream, n=learn",
"r c=Dream, n=blur",
"r c=Dream, n=flatten",
"r c=Dream, n=layer",
"r c=Dream, n=channel",
"r c=Dream, n=pane",
"r c=Dream, n=displayFreq3",
"r c=Train-Net, n=epochs",
"r c=Train-Net, n=learn",
"r c=Train-Net, n=decay",
"r c=Train-Net, n=displayFreq",
"r c=Train-Net, n=maxY",
"r c=Train-Net, n=minY",
"r c=Train-Net, n=mode",
"r c=DotColor, n=color",
"r c=Init-Net, n=net",
"r c=Init-Net, n=scaleWeights",
"r c=Activation, n=type",
"r c=Validate-kNN, n=big",
"r c=Validate-kNN, n=k",
"r c=Validate-kNN, n=norm",
"r c=Validate-kNN, n=displayFreq",
"r c=DropOut, n=ratioD",
"r c=DropOut, n=conv",
"r c=DropOut, n=pool",
"r c=DropOut, n=dense",
"r c=Display, n=trainSet",
"r c=Display, n=x",
"r c=Display, n=count",
"r c=Display, n=pane",
"r c=Display, n=big",
"r c=Display, n=layer",
"r c=Display, n=channel",
"r c=Display, n=classify",
"r c=Display, n=NN",
"r c=Display, n=augment",
"r c=Display, n=colorize",
"r c=Init-Net, n=L0",
"r c=Init-Net, n=L1",
"r c=Init-Net, n=L2",
"r c=Init-Net, n=L3",
"r c=Init-Net, n=L4",
"r c=Init-Net, n=L5",
"r c=Init-Net, n=L6",
"r c=Init-Net, n=L7",
"r c=Init-Net, n=L8",
"r c=Init-Net, n=L9",
"r c=SaveImage, n=x",
"r c=SaveImage, n=x2",
"r c=Find-kNN, n=trainSet",
"r c=Find-kNN, n=big",
"r c=Find-kNN, n=x",
"r c=Find-kNN, n=k",
"r c=Find-kNN, n=norm",
"r c=Find-kNN, n=pane",
"r c=Load, n=trainSet",
"r c=Load, n=rows",
"r c=Load, n=validRatio",
"r c=Load, n=removeHeader",
"r c=Load, n=removeCol1",
"r c=Load, n=dataFile",
"r c=Load, n=divideBy",
"r c=Load, n=subtractBy",
"r c=Predict, n=NN",
"r c=Predict, n=big",
"r c=Predict, n=k",
"r c=Predict, n=norm",
"r c=Predict, n=displayFreq2",
"r c=Predict, n=col1Name",
"r c=Predict, n=col2Name",
"r c=Predict, n=row1Num",
"r c=Predict, n=fileName",
"r c=DisplayAugment, n=x",
"r c=DisplayAugment, n=count",
"r c=DisplayAugment, n=ratioA",
"r c=DisplayAugment, n=angle",
"r c=DisplayAugment, n=scale",
"r c=DisplayAugment, n=xshift",
"r c=DisplayAugment, n=yshift",
"r c=DisplayAugment, n=pane",
"r c=DisplayAugment, n=big",
"r c=DataAugment, n=ratioA",
"r c=DataAugment, n=angle",
"r c=DataAugment, n=scale",
"r c=DataAugment, n=xshift",
"r c=DataAugment, n=yshift",
"s n=color, v=0, l=red",
"s n=color, v=1, l=orange",
"s n=color, v=2, l=yellow",
"s n=color, v=3, l=green",
"s n=color, v=4, l=blue",
"s n=color, v=5, l=purple",
"s n=net, v=0, l=custom",
// NAMES OF PRE-DEFINED NETS
"s n=net, v=1, l=2-20-20-6",
"s n=net, v=2, l=LeNet-5",
"s n=net, v=3, l=784-C3:10-C3:10-P2-C3:20-C3:20-P2-128-10",
"s n=net, v=4, l=784-1000-1000-10",
// debug nets
//"s n=net, v=5, l=784-C5:6-P2-50-10",
//"s n=net, v=6, l=196-100-10",
//"s n=net, v=7, l=16-C3:2-P2-2-2",
// NAMES ABOVE
"s n=type, v=0, l=Identity",
"s n=type, v=1, l=ReLU",
"s n=type, v=2, l=TanH",
"s n=mode, v=2, l=2fps",
"s n=mode, v=4, l=10fps",
"s n=mode, v=5, l=20fps",
"s n=mode, v=6, l=30fps",
"s n=trainSet, v=1, l=train_set",
"s n=trainSet, v=0, l=test_set",
"s n=NN, v=0, l=usekNN",
"s n=NN, v=1, l=useNN",
"s n=big, v=0, l=use196",
"s n=big, v=1, l=use784",
"s n=big, v=2, l=other",
"s n=removeHeader, v=0, l=no",
"s n=removeHeader, v=1, l=yes",
"s n=removeCol1, v=0, l=no",
"s n=removeCol1, v=1, l=yes",
"s n=classify, v=0, l=no",
"s n=classify, v=1, l=yes",
"s n=augment, v=0, l=no",
"s n=augment, v=1, l=yes",
"s n=colorize, v=0, l=no",
"s n=colorize, v=1, l=yes-1",
"s n=colorize, v=2, l=yes-2",
"s n=colorize, v=3, l=yes-3",
"s n=divideBy, v=255.0, l=pixel_data",
"s n=divideBy, v=1.0, l=no_scaling",
"s n=subtractBy, v=0.0, l=no_bias"
};
// NUMBER BITMAPS
const int digits[10][15] =
{{1,1,1, 1,0,1, 1,0,1, 1,0,1, 1,1,1}, //0
{0,1,0, 0,1,0, 0,1,0, 0,1,0, 0,1,0}, //1
{1,1,1, 0,0,1, 1,1,1, 1,0,0, 1,1,1}, //2
{1,1,1, 0,0,1, 1,1,1, 0,0,1, 1,1,1}, //3
{1,0,1, 1,0,1, 1,1,1, 0,0,1, 0,0,1}, //4
{1,1,1, 1,0,0, 1,1,1, 0,0,1, 1,1,1}, //5
{1,1,1, 1,0,0, 1,1,1, 1,0,1, 1,1,1}, //6
{1,1,1, 0,0,1, 0,0,1, 0,0,1, 0,0,1}, //7
{1,1,1, 1,0,1, 1,1,1, 1,0,1, 1,1,1}, //8
{1,1,1, 1,0,1, 1,1,1, 0,0,1, 0,0,1}}; //9
// LETTER BITMAPS
const int letters[26][15] =
{{0,1,0, 1,0,1, 1,1,1, 1,0,1, 1,0,1}, //A
{1,1,0, 1,0,1, 1,1,0, 1,0,1, 1,1,0}, //B
{1,1,1, 1,0,0, 1,0,0, 1,0,0, 1,1,1}, //C
{1,1,0, 1,0,1, 1,0,1, 1,0,1, 1,1,0}, //D
{1,1,1, 1,0,0, 1,1,1, 1,0,0, 1,1,1}, //E
{1,1,1, 1,0,0, 1,1,0, 1,0,0, 1,0,0}, //F
{1,1,1, 1,0,0, 1,0,1, 1,0,1, 1,1,1}, //G
{1,0,0, 1,0,1, 1,1,1, 1,0,1, 1,0,1}, //H
{1,1,1, 0,1,0, 0,1,0, 0,1,0, 1,1,1}, //I
{1,1,1, 0,1,0, 0,0,1, 1,0,1, 1,1,1}, //J
{1,0,1, 1,0,1, 1,1,0, 1,0,1, 1,0,1}, //K
{1,0,0, 1,0,0, 1,0,0, 1,0,0, 1,1,1}, //L
{1,0,1, 1,1,1, 1,0,1, 1,0,1, 1,0,1}, //M
{1,0,1, 1,1,1, 1,1,1, 1,1,1, 1,0,1}, //N
{0,1,0, 1,0,1, 1,0,1, 1,0,1, 0,1,0}, //O
{1,1,0, 1,0,1, 1,1,0, 1,0,0, 1,0,0}, //P
{1,1,1, 1,0,1, 1,0,1, 1,1,1, 0,0,1}, //Q
{1,1,1, 1,0,1, 1,1,1, 1,1,0, 1,0,1}, //R
{1,1,1, 1,0,0, 1,1,1, 0,0,1, 1,1,1}, //S
{1,1,1, 0,1,0, 0,1,0, 0,1,0, 0,1,0}, //T
{1,0,1, 1,0,1, 1,0,1, 1,0,1, 1,1,1}, //U
{1,0,1, 1,0,1, 1,0,1, 1,0,1, 0,1,0}, //V
{1,0,1, 1,0,1, 1,0,1, 1,1,1, 1,0,1}, //W
{1,0,1, 1,1,1, 1,1,1, 1,1,1, 1,0,1}, //X
{1,0,1, 1,0,1, 0,1,0, 0,1,0, 0,1,0}, //Y
{1,1,1, 0,0,1, 0,1,0, 1,0,0, 1,1,1}}; //Z
// TRAINING AND VALIDATION DATA
float (*trainImages)[784] = 0;
float (*trainImages2)[196] = 0;
int *trainDigits = 0;
int trainSizeI = 0, extraTrainSizeI = 1000;
int trainColumns = 0, trainSizeE = 0;
int *trainSet = 0; int trainSetSize = 0;
int *validSet = 0; int validSetSize = 0;
float *ents = 0, *ents2 = 0;
float *accs = 0, *accs2 = 0;
// TEST DATA
float (*testImages)[784] = 0;
float (*testImages2)[196] = 0;
int *testDigits;
int testSizeI = 0;
int testColumns = 0;
// NETWORK VARIABLES
int inited = -1;
int activation = 1; //0=Identity, 1=ReLU, 2=TanH
const int randomizeDescent = 1;
float an = 0.01;
int DOconv=1, DOdense=1, DOpool=1;
float dropOutRatio = 0.0, decay = 1.0;
float augmentRatio = 0.0, weightScale = 1.0;
float augmentScale = 0, imgBias=0.0;
int augmentAngle = 0;
float augmentDx = 0.0, augmentDy = 0.0;
// NETWORK ACTIVATIONS AND ERRORS
float prob = 0.0, prob0 = 0.0;
float prob1 = 0.0, prob2 = 0.0;
float* layers[10] = {0};
int* dropOut[10] = {0};
float* weights[10] = {0};
float* errors[10] = {0};
// NETWORK ARCHITECTURE
int numLayers = 0;
char layerNames[10][20] = {0};
int layerType[10] = {0}; //0FC, 1C, 2P
int layerSizes[10] = {0};
int layerConv[10] = {0};
int layerPad[10] = {0};
int layerWidth[10] = {0};
int layerChan[10] = {0};
int layerStride[10] = {0};
int layerConvStep[10] = {0};
int layerConvStep2[10] = {0};
// PREDEFINED NET ARCHITECTURES
char nets[8][10][20] =
{{"","","","","","","","","",""},
{"","","","","","","2","20","20","6"},
{"","","","784","C5:6","P2","C5:16","P2","128","10"},
{"","784","C3:10","C3:10","P2","C3:20","C3:20","P2","128","10"},
{"","","","","","","784","1000","1000","10"},
// debug nets below
{"","","","","","784","C5:6","P2","50","10"},
{"","","","","","","","196","100","10"},
{"","","","","","16","C3:2","P2","2","2"}};
// THREAD VARIABLES
pthread_t workerThread;
pthread_attr_t stackSizeAttribute;
int pass[5] = {0};
int working = 0;
int requiredStackSize = 8*1024*1024;
// IMAGE DISPLAY
int colorize = 1;
double red[8] = {1.0, 1.0, 1.0, 0.0, 0.0, 0.5, 1.0, 0.0};
double green[8] = {0.0, 0.5, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0};
double blue[8] = {0.0, 0.0, 0.0, 0.0, 1.0, 0.5, 1.0, 0.0};
double red2[256],green2[256],blue2[256];
double red3[256],green3[256],blue3[256];
int image[400][600] = {{0}};
int image2[80][120] = {{0}};
// CONFUSION MATRIX DATA
int maxCD = 54;
int cDigits[10][10][54];
int showAcc = 1;
int showEnt = 1;
int showCon = 0;
int showDig[3][55] = {{0}};
float scaleMin = 0.9, scaleMax = 1.0;
// DOT DATA
const int maxDots=250;
float trainDots[250][2];
int trainColors[250];
int trainSizeD = 0;
// DOT PARAMETERS
int useSmall = -1;
int removeMode = -1;
int dotsMode = 4; //6=fluid display 2=slower
// DOT 3D DISPLAY
int use3D = -1;
float heights3D[121][81] = {{0}};
float pa3D[121][81] = {{0}};
float pb3D[121][81] = {{0}};
float pc3D[121][81] = {{0}};
double *red4=0, *green4=0, *blue4=0;
int requestInit = 0;
// MISC
const char *weightsFile1 = "weights1.txt";
const char *weightsFile2 = "weights2.txt";
/**********************************************************************/
/* MAIN ROUTINE */
/**********************************************************************/
int main(int argc, char *argv[]){
if (argc>1) printf("Ignoring unknown argument(s)\n");
srand(time(0));
int i, offset=0;
char cmd, str[80], buffer[80];
// INITIALIZE WEBGUI
initParameterMap((char*)init,lines);
webinit((char*)init,lines);
websetmode(2);
websettitle("MNIST");
while (webstart(15000+offset)<0) offset++;
websetcolors(8,red,green,blue,3);
for (i=0;i<240000;i++) ((int*)image)[i]=6;
webimagedisplay(600,400,(int*)image,3);
for (i=0;i<256;i++){
red2[i] = (double)i/255.0;
green2[i] = (double)i/255.0;
blue2[i] = (double)i/255.0;
}
pthread_attr_init (&stackSizeAttribute);
pthread_attr_setstacksize (&stackSizeAttribute, requiredStackSize);
// MAIN LOOP TO PROCESS COMMANDS
while (1){
webreadline(str);
cmd = processCommand(str);
if (cmd=='l'){ // LOAD
int ct = ipGet("rows");
double v = rpGet("validRatio");
int t = ipGet("trainSet");
int sh = ipGet("removeHeader");
int rc = ipGet("removeCol1");
float imgScale = rpGet("divideBy");
imgBias = rpGet("subtractBy");
if (t==1){
webwriteline("Loading training images, please wait...");
int x = loadTrain(ct,v,sh,imgScale,imgBias);
sprintf(buffer,"Loaded %d rows training, %d features, vSetSize=%d",x,trainColumns,validSetSize);
webwriteline(buffer);
}
else{
webwriteline("Loading test images, please wait...");
int x = loadTest(ct,sh,rc,imgScale,imgBias);
sprintf(buffer,"Loaded %d rows test, %d features",x,testColumns);
webwriteline(buffer);
}
}
else if (cmd=='p'){ // DISPLAY
int x = ipGet("x");
int p = ipGet("pane");
int ct = ipGet("count");
int t = ipGet("trainSet");
int lay = ipGet("layer");
int chan = ipGet("channel");
int cfy = ipGet("classify");
int big = ipGet("big");
int aug = ipGet("augment");
colorize = ipGet("colorize");
//int nn = ipGet("NN");
char nm[10] = "training";
char ext[20] = " with label";
if (t==0) {
strcpy(nm,"test");
strcpy(ext,"");
}
if (cfy==1) strcpy(ext," with prediction");
// ADVANCED DISPLAY
if (lay!=0){
if ( (lay<0 || chan<0 || ct<0) && x>=0){
lay = abs(lay); chan = abs(chan); ct = abs(ct);
if (ct > layerChan[lay] - chan) ct = layerChan[lay] - chan;
sprintf(buffer,"Displaying layer %d max activation for x=%d",lay,x);
if (layerType[lay]!=0) maxActivations2(ct,p,lay,chan,t,x);
else sprintf(buffer,"Layer %d doesnt have filters",lay);
webwriteline(buffer);
}
else if (x<-1){
if (lay<0 || chan<0) ct = -abs(ct);
lay = abs(lay); chan = abs(chan);
if (ct < -layerChan[lay] + chan) ct = -layerChan[lay] + chan;
sprintf(buffer,"Displaying layer %d filter %d max activations",lay,chan);
if (layerType[lay]!=0) maxActivations(ct,p,lay,chan,t,x);
else sprintf(buffer,"Layer %d doesnt have filters",lay);
webwriteline(buffer);
}
else if (x==-1){
if (lay<0 || chan<0) ct = -abs(ct);
lay = abs(lay); chan = abs(chan);
if (ct > layerChan[lay] - chan) ct = layerChan[lay] - chan;
if (ct<=1) sprintf(buffer,"Displaying layer %d filter %d",lay,chan);
else sprintf(buffer,"Displaying layer %d filters %d thru %d",lay,chan,chan+ct-1);
if (lay==11-numLayers && layerType[lay]!=0) displayFilter(ct,p,lay,chan);
else if (lay>11-numLayers && layerType[lay]!=0) displayFilter2(ct,p,lay,chan);
else sprintf(buffer,"Layer %d doesnt have filters",lay);
webwriteline(buffer);
}
else{
if (aug==1) lay = -lay;
ct = abs(ct); if (ct==0) ct = 1;
if (ct > layerChan[lay] - chan) ct = layerChan[lay] - chan;
if (ct==1) sprintf(buffer,"Displaying layer %d filter %d activations for x=%d",abs(lay),chan,x);
else sprintf(buffer,"Displaying layer %d filter %d thru %d activations for x=%d",abs(lay),chan,chan+ct-1,x);
if (layerType[abs(lay)]!=0) displayDigit(x,ct,p,lay,chan,t,cfy,big);
else sprintf(buffer,"Layer %d doesnt have filters",abs(lay));
webwriteline(buffer);
}
}
// BASIC DISPLAY
else if (aug==1){
float rat = 1.0;
int p = ipGet("pane");
int r = ipGet("angle");
float sc = rpGet("scale");
float dx = rpGet("xshift");
float dy = rpGet("yshift");
viewAugment(x,ct,rat,r,sc,dx,dy,p,big,t,cfy);
}
else {
displayDigit(x,ct,p,0,0,t,cfy,big);
if (ct>1) sprintf(buffer,"Displaying %s images %d to %d%s",nm,x,x+ct-1,ext);
else sprintf(buffer,"Displaying %s image %d%s",nm,x,ext);
webwriteline(buffer);
}
}
else if (cmd=='i'){ // INIT-NET
int t = ipGet("net");
weightScale = rpGet("scaleWeights");
if (working==1) requestInit = 1;
else initNet(t);
sprintf(buffer,"Initialized NN=%d with Xavier init scaled=%.3f",t,weightScale);
webwriteline(buffer);
int len = sprintf(buffer,"Architecture (%s",layerNames[0]);
for (i=1;i<10;i++) len += sprintf(buffer+len,"-%s",layerNames[i]);
sprintf(buffer+len,")");
webwriteline(buffer);
}
else if (cmd=='a'){ // ACTIVATION
int a = ipGet("type");
if (a<0 || a>2) webwriteline("Invalid activation");
else {
activation = a;
sprintf(buffer,"Activation=%d where 0=Identity, 1=ReLU, 2=TanH",a);
webwriteline(buffer);
if (a==2 || a==0) webbutton(1,"Activation");
else webbutton(-1,"Activation");
}
}
else if (cmd=='o'){ // DROPOUT
dropOutRatio = rpGet("ratioD");
DOconv = ipGet("conv");
DOpool = ipGet("pool");
DOdense = ipGet("dense");
sprintf(buffer,"DropOutRatio = %f, conv=%d, pool=%d, dense=%d",dropOutRatio,DOconv,DOpool,DOdense);
webwriteline(buffer);
if (dropOutRatio>0.0) webbutton(1,"DropOut");
else webbutton(-1,"DropOut");
}
else if (cmd=='d'){ // DATA AUGMENTATION
augmentRatio = rpGet("ratioA");
augmentAngle = abs(ipGet("angle"));
augmentScale = fabs(rpGet("scale"));
augmentDx = rpGet("xshift");
augmentDy = rpGet("yshift");
sprintf(buffer,"AugmentRatio = %f, Angle = %d, Scale = %.2f, Dx = %.1f, Dy = %.1f",
augmentRatio,augmentAngle,augmentScale,augmentDx,augmentDy);
webwriteline(buffer);
if (augmentRatio>0.0) webbutton(1,"DataAugment");
else webbutton(-1,"DataAugment");
}
else if (cmd=='b'){ // TRAIN-NET
an = rpGet("learn");
scaleMin = rpGet("minY");
scaleMax = rpGet("maxY");
decay = rpGet("decay");
if (working==1){
sprintf(buffer,"wait until learning ends, learn=%f",an);
webwriteline(buffer);
}
else{
int x = ipGet("epochs");
int y = ipGet("displayFreq");
dotsMode = ipGet("mode");
sprintf(buffer,"Beginning %d epochs with lr=%f and decay=%f",x,an,decay);
webwriteline(buffer);
pass[0]=x; pass[1]=y; pass[2]=1; working=1;
pthread_create(&workerThread,&stackSizeAttribute,runBackProp,NULL);
}
}
else if (cmd=='g'){ // FIND-KNN
int t = ipGet("trainSet");
int big = ipGet("big");
int x = ipGet("x");
int k = ipGet("k");
int d = ipGet("norm");
int p = ipGet("pane");
int c = singleKNN(x,k,d,p,t,big,1);
sprintf(buffer,"kNN predicts %d for image %d with k=%d and L%d norm",c,x,k,d);
webwriteline(buffer);
}
else if (cmd=='k'){ // VALIDATE-KNN
if (working==1){
webwriteline("wait until learning ends");
}
else{
int x = ipGet("k");
int y = ipGet("displayFreq");
int big = ipGet("big");
int d = ipGet("norm");
pass[0]=big; pass[1]=y; pass[2]=x; pass[3]=d;
pass[4]=1; working=1;
pthread_create(&workerThread,&stackSizeAttribute,runKNN,NULL);
}
}
else if (cmd=='t'){ // STOP
working=0;
}
else if (cmd=='w'){ // PREDICT
int NN = ipGet("NN");
int k = ipGet("k");
int d = ipGet("norm");
int y = ipGet("displayFreq2");
int big = ipGet("big");
writePredictFile(NN,k,d,y,big);
}
else if (cmd=='q'){ // QUIT
if (working==1) pthread_cancel(workerThread);
webwriteline("QUITTING. Good-bye");
usleep(500000);
webstop();
return 0;
}
else if (cmd=='c'){ // CLEAR PANE 3
trainSizeD = 0;
updateImage();
webwriteline("Pane 3 cleared. Dots cleared");
if (red4 != NULL){
free(red4); free(green4); free(blue4);
red4 = NULL;
}
}
else if (cmd=='r'){ // DOT REMOVE MODE
if (removeMode==-1) removeMode = 1;
else removeMode = -1;
webbutton(removeMode,"DotRemoveMode");
sprintf(buffer,"Remove mode = %d",removeMode);
webwriteline(buffer);
}
else if (cmd=='u'){ // DOT LOW RES MODE
if (useSmall==-1) useSmall = 1;
else useSmall = -1;
webbutton(useSmall,"DotLowResMode");
sprintf(buffer,"UseSmall = %d",useSmall);
webwriteline(buffer);
if (isDigits(inited)!=1 && layerSizes[10-numLayers]==2 && working==0 && trainSizeD!=0){
if (use3D==1) displayClassify3D();
else displayClassify(0);
}
}
else if (cmd=='h'){ // DOT 3D MODE
if (use3D==-1) use3D = 1;
else use3D = -1;
webbutton(use3D,"Dot3dMode");
sprintf(buffer,"Use3D = %d",use3D);
webwriteline(buffer);
if (isDigits(inited)!=1 && layerSizes[10-numLayers]==2 && working==0 && trainSizeD!=0){
if (use3D==1) displayClassify3D();
else displayClassify(0);
}
}
// SPECIAL FEATURES, UNCOMMENT IN MENU TO TURN ON
else if (cmd=='e'){ // DREAM
int x = ipGet("x");
int y = ipGet("y");
int it = ipGet("it");
an = rpGet("learn");
int ds = ipGet("displayFreq3");
int lay = ipGet("layer");
int chan = ipGet("channel");
float bs = rpGet("blur");
float ft = rpGet("flatten");
int p = ipGet("pane");
sprintf(buffer,"Dreaming x=%d to y=%d, it=%d, an=%f",x,y,it,an);
webwriteline(buffer);
dream(x,y,it,bs,ft,ds,lay,chan,p);
}
else if (cmd=='f'){ // HEATMAP
int x = ipGet("x");
int p = ipGet("pane");
int t = ipGet("trainSet");
int wd = ipGet("filterWidth");
int y = heatmap(x,t,p,wd);
sprintf(buffer,"Displaying heatmap for x=%d, predict=%d, prob=%.3f",x,y,prob);
webwriteline(buffer);
}
else if (cmd=='j') // BOUNDING BOXES
boundingBoxes();
else if (cmd=='n'){ // INIT IMAGE
int z = ipGet("z");
sprintf(buffer,"Initing data with z=%d",z);
webwriteline(buffer);
initData(z);
}
else if (cmd=='v'){ // SAVE IMAGE
int x = ipGet("x");
int x2 = ipGet("x2");
for (i=0;i<196;i++) trainImages2[x2][i] = trainImages2[x][i];
for (i=0;i<784;i++) trainImages[x2][i] = trainImages[x][i];
trainDigits[x2] = trainDigits[x];
sprintf(buffer,"Saved image %d to %d",x,x2);
webwriteline(buffer);
}
else if (cmd=='y'){ // DISPLAY WEIGHTS
webwriteline("Weights displayed in shell");
displayWeights();
}
else if (cmd=='z'){ // WRITE WEIGHTS
writeFile2();
}
// PROCESS MOUSE CLICKS
else if (cmd=='m'){ // MOUSE CLICKS
float x = atof(extractVal(str,'x'));
float y = atof(extractVal(str,'y'));
int b = atoi(extractVal(str,'n'));
int p = atoi(extractVal(str,'e'));
int r, row, col, d, num, dd;
float c;
if (showDig[p-3][0]!=0){
d = showDig[p-3][0];
if (d<=6) {r=2; c=3;}
else if (d<=12) {r=3; c=4.5;}
else if (d<=24) {r=4; c=6;}
else if (d<=35) {r=5; c=7;}
else if (d<=54) {r=6; c=9;}
col = (int)(x*c/1.5);
row = (int)((1-y)*r);
if (col<0) col=0; if (col>=(int)c) col=c-1;
if (row<0) row=0; if (row>=r) row=r-1;
dd = 1+row*c+col;
num = showDig[p-3][dd];
if (x>1.48 && (1-y)<0.025){
if (p==3) showCon = 1;
else if (p==4) showEnt = 1;
else if (p==5) showAcc = 1;
clearImage(p);
}
else if (num!=-1 && dd<=showDig[p-3][0]){
sprintf(buffer,"Clicked image %d, digit %d",num,trainDigits[num]);
webwriteline(buffer);
ipSet("x",num);
webupdate(ip,rp,sp);
}
}
else if (showCon==0){
int c = ipGet("color");
if (p==3 && trainSizeD<100){
if (removeMode==1){
removeDot(x,y);
}
else{
trainDots[trainSizeD][0] = x;
trainDots[trainSizeD][1] = y;
trainColors[trainSizeD] = c + b;
trainSizeD++;
}
if (working==0) updateImage();
}
}
else if (p==3){
int col = (int)(x/0.1364)-1;
int row = (int)((1-y)/0.0909)-1;
if (col<0) col=0; if (col>9) col=9;
if (row<0) row=0; if (row>9) row=9;
displayCDigits(row,col);
}
}
}
return 0;
}
/**********************************************************************/
/* LOAD DATA */
/**********************************************************************/
int loadTrain(int ct, double testProp, int sh, float imgScale, float imgBias){
char *data;
// LOAD TRAINING DATA FROM FILE
if (ct<=0) ct=1e6;
int i, len = 0, lines=1, lines2=1;
float rnd;
// READ IN TRAIN.CSV
char buffer[1000000];
char name[80] = "train.csv";
strcpy(name,spGet("dataFile"));
if (access(name,F_OK)!=0) sprintf(name,"../%s",spGet("dataFile"));
if (access(name,F_OK)==0){
data = (char*)malloc((int)fsize(name)+1);
FILE *fp;
fp = fopen(name,"r");
while (fgets(buffer, 1000000, fp)) {
len += sprintf(data+len,"%s",buffer);
//lines++;
}
fclose(fp);
}
else {
sprintf(buffer,"ERROR: File %s not found.",name);
webwriteline(buffer);
return 0;
}
// COUNT LINES
for (i=0;i<len;i++){
if (data[i]=='\n') lines++;
if (data[i]=='\r') lines2++;
}
if (lines2>lines) lines=lines2;
// ALLOCATE MEMORY
if (trainImages!=NULL){
free(trainImages);
free(trainImages2);
free(trainDigits);
free(trainSet);
free(validSet);
trainImages = NULL;
}
trainImages = malloc(784 * (lines+extraTrainSizeI) * sizeof(float));
trainImages2 = malloc(196 * (lines+extraTrainSizeI) * sizeof(float));
trainDigits = malloc(lines * sizeof(int));
trainSet = malloc(lines * sizeof(int));
validSet = malloc(lines * sizeof(int));
// DECODE COMMA SEPARATED ROWS
int j = 0, k = 0, c = 0, mark = -1;
int d = 0, j1,j2;
while (data[j]!='\n' && data[j]!='\r'){
if (data[j]==',') c++;
j++;
}
if (data[j]!='\n' || data[j]!='\r') j++;
trainColumns = c;
c = 0; i = 0;
if (sh==1) i = j+1;
while(i<len && k<ct){
j = i; while (data[j]!=',' && data[j]!='\r' && data[j]!='\n') j++;
if (data[j]=='\n' || data[j]=='\r') mark = 1;
data[j] = 0;
d = atof(data+i);
if (mark == -1){
trainDigits[k] = (int)d;
mark = 0;
}
else if (mark==0) {
trainImages[k][c] = d/imgScale - imgBias;